use new RCSID macro to prevent Id keyword from being optimized out
[freeradius.git] / src / modules / rlm_detail / rlm_detail.c
1 /*
2  * rlm_detail.c accounting:    Write the "detail" files.
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000,2006  The FreeRADIUS server project
21  */
22
23 #include        <freeradius-devel/ident.h>
24 RCSID("$Id$")
25
26 #include        <freeradius-devel/autoconf.h>
27
28 #include        <sys/stat.h>
29 #include        <sys/select.h>
30
31 #include        <stdlib.h>
32 #include        <string.h>
33 #include        <ctype.h>
34 #include        <fcntl.h>
35
36 #include        <freeradius-devel/radiusd.h>
37 #include        <freeradius-devel/modules.h>
38 #include        <freeradius-devel/rad_assert.h>
39
40 #define         DIRLEN  8192
41
42 static const char *packet_codes[] = {
43   "",
44   "Access-Request",
45   "Access-Accept",
46   "Access-Reject",
47   "Accounting-Request",
48   "Accounting-Response",
49   "Accounting-Status",
50   "Password-Request",
51   "Password-Accept",
52   "Password-Reject",
53   "Accounting-Message",
54   "Access-Challenge"
55 };
56
57
58 struct detail_instance {
59         /* detail file */
60         char *detailfile;
61
62         /* detail file permissions */
63         int detailperm;
64
65         /* directory permissions */
66         int dirperm;
67
68         /* last made directory */
69         char *last_made_directory;
70
71         /* timestamp & stuff */
72         char *header;
73
74         /* if we want file locking */
75         int locking;
76
77         /* log src/dst information */
78         int log_srcdst;
79
80         lrad_hash_table_t *ht;
81 };
82
83 static const CONF_PARSER module_config[] = {
84         { "detailfile",    PW_TYPE_STRING_PTR,
85           offsetof(struct detail_instance,detailfile), NULL, "%A/%{Client-IP-Address}/detail" },
86         { "header",    PW_TYPE_STRING_PTR,
87           offsetof(struct detail_instance,header), NULL, "%t" },
88         { "detailperm",    PW_TYPE_INTEGER,
89           offsetof(struct detail_instance,detailperm), NULL, "0600" },
90         { "dirperm",       PW_TYPE_INTEGER,
91           offsetof(struct detail_instance,dirperm),    NULL, "0755" },
92         { "locking",       PW_TYPE_BOOLEAN,
93           offsetof(struct detail_instance,locking),    NULL, "no" },
94         { "log_packet_header",       PW_TYPE_BOOLEAN,
95           offsetof(struct detail_instance,log_srcdst),    NULL, "no" },
96         { NULL, -1, 0, NULL, NULL }
97 };
98
99
100 /*
101  *      Clean up.
102  */
103 static int detail_detach(void *instance)
104 {
105         struct detail_instance *inst = instance;
106         free((char *) inst->detailfile);
107
108         free((char*) inst->last_made_directory);
109
110         if (inst->ht) lrad_hash_table_free(inst->ht);
111
112         free(inst);
113         return 0;
114 }
115
116
117 static uint32_t detail_hash(const void *data)
118 {
119         const DICT_ATTR *da = data;
120         return lrad_hash(&(da->attr), sizeof(da->attr));
121 }
122
123 static int detail_cmp(const void *a, const void *b)
124 {
125         return ((const DICT_ATTR *)a)->attr - ((const DICT_ATTR *)b)->attr;
126 }
127
128
129 /*
130  *      (Re-)read radiusd.conf into memory.
131  */
132 static int detail_instantiate(CONF_SECTION *conf, void **instance)
133 {
134         struct detail_instance *inst;
135         CONF_SECTION    *cs;
136
137         inst = rad_malloc(sizeof(*inst));
138         if (!inst) {
139                 return -1;
140         }
141         memset(inst, 0, sizeof(*inst));
142
143         if (cf_section_parse(conf, inst, module_config) < 0) {
144                 detail_detach(inst);
145                 return -1;
146         }
147
148         inst->last_made_directory = NULL;
149
150         /*
151          *      Suppress certain attributes.
152          */
153         cs = cf_section_sub_find(conf, "suppress");
154         if (cs) {
155                 CONF_ITEM       *ci;
156
157                 inst->ht = lrad_hash_table_create(detail_hash, detail_cmp,
158                                                   NULL);
159
160                 for (ci = cf_item_find_next(cs, NULL);
161                      ci != NULL;
162                      ci = cf_item_find_next(cs, ci)) {
163                         const char      *attr;
164                         DICT_ATTR       *da;
165
166                         if (!cf_item_is_pair(ci)) continue;
167                                                 
168                         attr = cf_pair_attr(cf_itemtopair(ci));
169                         if (!attr) continue; /* pair-anoia */
170
171                         da = dict_attrbyname(attr);
172                         if (!da) {
173                                 radlog(L_INFO, "rlm_detail: WARNING: No such attribute %s: Cannot suppress printing it.", attr);
174                                 continue;
175                         }
176
177                         /*
178                          *      For better distribution we should really
179                          *      hash the attribute number or name.  But
180                          *      since the suppression list will usually
181                          *      be small, it doesn't matter.
182                          */
183                         if (!lrad_hash_table_insert(inst->ht, da)) {
184                                 radlog(L_ERR, "rlm_detail: Failed trying to remember %s", attr);
185                                 detail_detach(inst);
186                                 return -1;
187                         }
188                 }
189         }
190
191
192         *instance = inst;
193         return 0;
194 }
195
196 /*
197  *      Do detail, compatible with old accounting
198  */
199 static int do_detail(void *instance, REQUEST *request, RADIUS_PACKET *packet,
200                      int compat)
201 {
202         int             outfd;
203         FILE            *outfp;
204         char            timestamp[256];
205         char            buffer[DIRLEN];
206         char            *p;
207         struct stat     st;
208         int             locked;
209         int             lock_count;
210         struct timeval  tv;
211         REALM           *proxy_realm;
212         char            proxy_buffer[16];
213         VALUE_PAIR      *pair = packet->vps;
214
215         struct detail_instance *inst = instance;
216
217         /*
218          *      Nothing to log: don't do anything.
219          */
220         if (!packet) {
221                 return RLM_MODULE_NOOP;
222         }
223
224         /*
225          *      Create a directory for this nas.
226          *
227          *      Generate the path for the detail file.  Use the
228          *      same format, but truncate at the last /.  Then
229          *      feed it through radius_xlat() to expand the
230          *      variables.
231          */
232         radius_xlat(buffer, sizeof(buffer), inst->detailfile, request, NULL);
233         DEBUG2("rlm_detail: %s expands to %s", inst->detailfile, buffer);
234
235         /*
236          *      Grab the last directory delimiter.
237          */
238         p = strrchr(buffer,'/');
239
240         /*
241          *      There WAS a directory delimiter there, and
242          *      the file doesn't exist, so
243          *      we prolly must create it the dir(s)
244          */
245         if ((p) && (stat(buffer, &st) < 0)) {
246                 *p = '\0';
247                 /*
248                  *      NO previously cached directory name, so we've
249                  *      got to create a new one.
250                  *
251                  *      OR the new directory name is different than the old,
252                  *      so we've got to create a new one.
253                  *
254                  *      OR the cached directory has somehow gotten removed,
255                  *      so we've got to create a new one.
256                  */
257                 if ((inst->last_made_directory == NULL) ||
258                     (strcmp(inst->last_made_directory, buffer) != 0)) {
259                         free((char *) inst->last_made_directory);
260                         inst->last_made_directory = strdup(buffer);
261                 }
262
263                 /*
264                  *      stat the directory, and don't do anything if
265                  *      it exists.  If it doesn't exist, create it.
266                  *
267                  *      This also catches the case where some idiot
268                  *      deleted a directory that the server was using.
269                  */
270                 if (rad_mkdir(inst->last_made_directory, inst->dirperm) < 0) {
271                         radlog(L_ERR, "rlm_detail: Failed to create directory %s: %s", inst->last_made_directory, strerror(errno));
272                         return RLM_MODULE_FAIL;
273                 }
274
275                 *p = '/';
276         } /* else there was no directory delimiter. */
277
278         locked = 0;
279         lock_count = 0;
280         do {
281                 /*
282                  *      Open & create the file, with the given
283                  *      permissions.
284                  */
285                 if ((outfd = open(buffer, O_WRONLY | O_APPEND | O_CREAT,
286                                   inst->detailperm)) < 0) {
287                         radlog(L_ERR, "rlm_detail: Couldn't open file %s: %s",
288                                buffer, strerror(errno));
289                         return RLM_MODULE_FAIL;
290                 }
291
292                 /*
293                  *      If we fail to aquire the filelock in 80 tries
294                  *      (approximately two seconds) we bail out.
295                  */
296                 if (inst->locking) {
297                         lseek(outfd, 0L, SEEK_SET);
298                         if (rad_lockfd_nonblock(outfd, 0) < 0) {
299                                 close(outfd);
300                                 tv.tv_sec = 0;
301                                 tv.tv_usec = 25000;
302                                 select(0, NULL, NULL, NULL, &tv);
303                                 lock_count++;
304                                 continue;
305                         }
306
307                         /*
308                          *      The file might have been deleted by
309                          *      radrelay while we tried to acquire
310                          *      the lock (race condition)
311                          */
312                         if (fstat(outfd, &st) != 0) {
313                                 radlog(L_ERR, "rlm_detail: Couldn't stat file %s: %s",
314                                        buffer, strerror(errno));
315                                 close(outfd);
316                                 return RLM_MODULE_FAIL;
317                         }
318                         if (st.st_nlink == 0) {
319                                 DEBUG("rlm_detail: File %s removed by another program, retrying",
320                                       buffer);
321                                 close(outfd);
322                                 lock_count = 0;
323                                 continue;
324                         }
325
326                         DEBUG("rlm_detail: Acquired filelock, tried %d time(s)",
327                               lock_count + 1);
328                         locked = 1;
329                 }
330         } while (inst->locking && !locked && lock_count < 80);
331
332         if (inst->locking && !locked) {
333                 close(outfd);
334                 radlog(L_ERR, "rlm_detail: Failed to aquire filelock for %s, giving up",
335                        buffer);
336                 return RLM_MODULE_FAIL;
337         }
338
339         /*
340          *      Convert the FD to FP.  The FD is no longer valid
341          *      after this operation.
342          */
343         if ((outfp = fdopen(outfd, "a")) == NULL) {
344                 radlog(L_ERR, "rlm_detail: Couldn't open file %s: %s",
345                        buffer, strerror(errno));
346                 if (inst->locking) {
347                         lseek(outfd, 0L, SEEK_SET);
348                         rad_unlockfd(outfd, 0);
349                         DEBUG("rlm_detail: Released filelock");
350                 }
351                 close(outfd);   /* automatically releases the lock */
352
353                 return RLM_MODULE_FAIL;
354         }
355
356         /*
357          *      Post a timestamp
358          */
359         fseek(outfp, 0L, SEEK_END);
360         radius_xlat(timestamp, sizeof(timestamp), inst->header, request, NULL);
361         fprintf(outfp, "%s\n", timestamp);
362
363         /*
364          *      Write the information to the file.
365          */
366         if (!compat) {
367                 /*
368                  *      Print out names, if they're OK.
369                  *      Numbers, if not.
370                  */
371                 if ((packet->code > 0) &&
372                     (packet->code <= PW_ACCESS_CHALLENGE)) {
373                         fprintf(outfp, "\tPacket-Type = %s\n",
374                                 packet_codes[packet->code]);
375                 } else {
376                         fprintf(outfp, "\tPacket-Type = %d\n", packet->code);
377                 }
378         }
379
380         if (inst->log_srcdst) {
381                 VALUE_PAIR src_vp, dst_vp;
382
383                 src_vp.name[0] = dst_vp.name[0] = '\0'; /* for vp_prints() */
384                 src_vp.operator = dst_vp.operator = T_OP_EQ;
385
386                 switch (packet->src_ipaddr.af) {
387                 case AF_INET:
388                         src_vp.type = PW_TYPE_IPADDR;
389                         src_vp.attribute = PW_PACKET_SRC_IP_ADDRESS;
390                         src_vp.lvalue = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
391                         dst_vp.type = PW_TYPE_IPADDR;
392                         dst_vp.attribute = PW_PACKET_DST_IP_ADDRESS;
393                         dst_vp.lvalue = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
394                         break;
395                 case AF_INET6:
396                         src_vp.type = PW_TYPE_IPV6ADDR; 
397                         src_vp.attribute = PW_PACKET_SRC_IPV6_ADDRESS;
398                         memcpy(src_vp.vp_strvalue,
399                                &packet->src_ipaddr.ipaddr.ip6addr,
400                                sizeof(packet->src_ipaddr.ipaddr.ip6addr));
401                         dst_vp.type = PW_TYPE_IPV6ADDR; 
402                         dst_vp.attribute = PW_PACKET_DST_IPV6_ADDRESS;
403                         memcpy(dst_vp.vp_strvalue,
404                                &packet->dst_ipaddr.ipaddr.ip6addr,
405                                sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
406                         break;
407                 default:
408                         break;
409                 }
410
411                 fputs("\t", outfp);
412                 vp_print(outfp, &src_vp);
413                 fputs("\n", outfp);
414                 fputs("\t", outfp);
415                 vp_print(outfp, &dst_vp);
416                 fputs("\n", outfp);
417
418                 src_vp.attribute = PW_PACKET_SRC_PORT;
419                 src_vp.type = PW_TYPE_INTEGER;
420                 src_vp.lvalue = packet->src_port;
421                 dst_vp.attribute = PW_PACKET_DST_PORT;
422                 dst_vp.type = PW_TYPE_INTEGER;
423                 dst_vp.lvalue = packet->dst_port;
424
425                 fputs("\t", outfp);
426                 vp_print(outfp, &src_vp);
427                 fputs("\n", outfp);
428                 fputs("\t", outfp);
429                 vp_print(outfp, &dst_vp);
430                 fputs("\n", outfp);
431         }
432
433         /* Write each attribute/value to the log file */
434         for (; pair != NULL; pair = pair->next) {
435                 DICT_ATTR da;
436                 da.attr = pair->attribute;
437
438                 if (inst->ht &&
439                     lrad_hash_table_finddata(inst->ht, &da)) continue;
440
441                 /*
442                  *      Don't print passwords in old format...
443                  */
444                 if (compat && (pair->attribute == PW_USER_PASSWORD)) continue;
445
446                 /*
447                  *      Print all of the attributes.
448                  */
449                 fputs("\t", outfp);
450                 vp_print(outfp, pair);
451                 fputs("\n", outfp);
452         }
453
454         /*
455          *      Add non-protocol attibutes.
456          */
457         if (compat) {
458                 if ((pair = pairfind(request->config_items,
459                                      PW_PROXY_TO_REALM)) != NULL) {
460                         proxy_realm = realm_find(pair->vp_strvalue, TRUE);
461                         if (proxy_realm) {
462                                 memset((char *) proxy_buffer, 0, 16);
463
464                                 rad_assert(proxy_realm->acct_ipaddr.af == AF_INET);
465
466                                 inet_ntop(proxy_realm->acct_ipaddr.af,
467                                           &proxy_realm->acct_ipaddr.ipaddr,
468                                           proxy_buffer, sizeof(proxy_buffer));
469                                 fprintf(outfp, "\tFreeradius-Proxied-To = %s\n",
470                                         proxy_buffer);
471                                 DEBUG("rlm_detail: Freeradius-Proxied-To set to %s",
472                                       proxy_buffer);
473                         }
474                 }
475                 fprintf(outfp, "\tTimestamp = %ld\n",
476                         (unsigned long) request->timestamp);
477
478                 if (request->packet->verified == 2)
479                         fputs("\tRequest-Authenticator = Verified\n", outfp);
480                 else if (request->packet->verified == 1)
481                         fputs("\tRequest-Authenticator = None\n", outfp);
482         }
483
484         fputs("\n", outfp);
485
486         if (inst->locking) {
487                 fflush(outfp);
488                 lseek(outfd, 0L, SEEK_SET);
489                 rad_unlockfd(outfd, 0);
490                 DEBUG("rlm_detail: Released filelock");
491         }
492
493         fclose(outfp);
494
495         /*
496          *      And everything is fine.
497          */
498         return RLM_MODULE_OK;
499 }
500
501 /*
502  *      Accounting - write the detail files.
503  */
504 static int detail_accounting(void *instance, REQUEST *request)
505 {
506
507         return do_detail(instance,request,request->packet, TRUE);
508 }
509
510 /*
511  *      Incoming Access Request - write the detail files.
512  */
513 static int detail_authorize(void *instance, REQUEST *request)
514 {
515         return do_detail(instance,request,request->packet, FALSE);
516 }
517
518 /*
519  *      Outgoing Access-Request Reply - write the detail files.
520  */
521 static int detail_postauth(void *instance, REQUEST *request)
522 {
523         return do_detail(instance,request,request->reply, FALSE);
524 }
525
526
527 /*
528  *      Outgoing Access-Request to home server - write the detail files.
529  */
530 static int detail_pre_proxy(void *instance, REQUEST *request)
531 {
532         if (request->proxy &&
533             request->proxy->vps) {
534                 return do_detail(instance,request,request->proxy, FALSE);
535         }
536
537         return RLM_MODULE_NOOP;
538 }
539
540
541 /*
542  *      Outgoing Access-Request Reply - write the detail files.
543  */
544 static int detail_post_proxy(void *instance, REQUEST *request)
545 {
546         if (request->proxy_reply &&
547             request->proxy_reply->vps) {
548                 return do_detail(instance,request,request->proxy_reply, FALSE);
549         }
550
551         return RLM_MODULE_NOOP;
552 }
553
554
555 /* globally exported name */
556 module_t rlm_detail = {
557         RLM_MODULE_INIT,
558         "detail",
559         RLM_TYPE_THREAD_UNSAFE,        /* type: reserved */
560         detail_instantiate,             /* instantiation */
561         detail_detach,                  /* detach */
562         {
563                 NULL,                   /* authentication */
564                 detail_authorize,       /* authorization */
565                 NULL,                   /* preaccounting */
566                 detail_accounting,      /* accounting */
567                 NULL,                   /* checksimul */
568                 detail_pre_proxy,       /* pre-proxy */
569                 detail_post_proxy,      /* post-proxy */
570                 detail_postauth         /* post-auth */
571         },
572 };
573