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