Massive change to the server core to remove horrid code in
[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         VALUE_PAIR      *pair;
209
210         struct detail_instance *inst = instance;
211
212         /*
213          *      Nothing to log: don't do anything.
214          */
215         if (!packet) {
216                 return RLM_MODULE_NOOP;
217         }
218
219         /*
220          *      Create a directory for this nas.
221          *
222          *      Generate the path for the detail file.  Use the
223          *      same format, but truncate at the last /.  Then
224          *      feed it through radius_xlat() to expand the
225          *      variables.
226          */
227         radius_xlat(buffer, sizeof(buffer), inst->detailfile, request, NULL);
228         DEBUG2("rlm_detail: %s expands to %s", inst->detailfile, buffer);
229
230         /*
231          *      Grab the last directory delimiter.
232          */
233         p = strrchr(buffer,'/');
234
235         /*
236          *      There WAS a directory delimiter there, and
237          *      the file doesn't exist, so
238          *      we prolly must create it the dir(s)
239          */
240         if ((p) && (stat(buffer, &st) < 0)) {
241                 *p = '\0';
242                 /*
243                  *      NO previously cached directory name, so we've
244                  *      got to create a new one.
245                  *
246                  *      OR the new directory name is different than the old,
247                  *      so we've got to create a new one.
248                  *
249                  *      OR the cached directory has somehow gotten removed,
250                  *      so we've got to create a new one.
251                  */
252                 if ((inst->last_made_directory == NULL) ||
253                     (strcmp(inst->last_made_directory, buffer) != 0)) {
254                         free((char *) inst->last_made_directory);
255                         inst->last_made_directory = strdup(buffer);
256                 }
257
258                 /*
259                  *      stat the directory, and don't do anything if
260                  *      it exists.  If it doesn't exist, create it.
261                  *
262                  *      This also catches the case where some idiot
263                  *      deleted a directory that the server was using.
264                  */
265                 if (rad_mkdir(inst->last_made_directory, inst->dirperm) < 0) {
266                         radlog(L_ERR, "rlm_detail: Failed to create directory %s: %s", inst->last_made_directory, strerror(errno));
267                         return RLM_MODULE_FAIL;
268                 }
269
270                 *p = '/';
271         } /* else there was no directory delimiter. */
272
273         locked = 0;
274         lock_count = 0;
275         do {
276                 /*
277                  *      Open & create the file, with the given
278                  *      permissions.
279                  */
280                 if ((outfd = open(buffer, O_WRONLY | O_APPEND | O_CREAT,
281                                   inst->detailperm)) < 0) {
282                         radlog(L_ERR, "rlm_detail: Couldn't open file %s: %s",
283                                buffer, strerror(errno));
284                         return RLM_MODULE_FAIL;
285                 }
286
287                 /*
288                  *      If we fail to aquire the filelock in 80 tries
289                  *      (approximately two seconds) we bail out.
290                  */
291                 if (inst->locking) {
292                         lseek(outfd, 0L, SEEK_SET);
293                         if (rad_lockfd_nonblock(outfd, 0) < 0) {
294                                 close(outfd);
295                                 tv.tv_sec = 0;
296                                 tv.tv_usec = 25000;
297                                 select(0, NULL, NULL, NULL, &tv);
298                                 lock_count++;
299                                 continue;
300                         }
301
302                         /*
303                          *      The file might have been deleted by
304                          *      radrelay while we tried to acquire
305                          *      the lock (race condition)
306                          */
307                         if (fstat(outfd, &st) != 0) {
308                                 radlog(L_ERR, "rlm_detail: Couldn't stat file %s: %s",
309                                        buffer, strerror(errno));
310                                 close(outfd);
311                                 return RLM_MODULE_FAIL;
312                         }
313                         if (st.st_nlink == 0) {
314                                 DEBUG("rlm_detail: File %s removed by another program, retrying",
315                                       buffer);
316                                 close(outfd);
317                                 lock_count = 0;
318                                 continue;
319                         }
320
321                         DEBUG("rlm_detail: Acquired filelock, tried %d time(s)",
322                               lock_count + 1);
323                         locked = 1;
324                 }
325         } while (inst->locking && !locked && lock_count < 80);
326
327         if (inst->locking && !locked) {
328                 close(outfd);
329                 radlog(L_ERR, "rlm_detail: Failed to aquire filelock for %s, giving up",
330                        buffer);
331                 return RLM_MODULE_FAIL;
332         }
333
334         /*
335          *      Convert the FD to FP.  The FD is no longer valid
336          *      after this operation.
337          */
338         if ((outfp = fdopen(outfd, "a")) == NULL) {
339                 radlog(L_ERR, "rlm_detail: Couldn't open file %s: %s",
340                        buffer, strerror(errno));
341                 if (inst->locking) {
342                         lseek(outfd, 0L, SEEK_SET);
343                         rad_unlockfd(outfd, 0);
344                         DEBUG("rlm_detail: Released filelock");
345                 }
346                 close(outfd);   /* automatically releases the lock */
347
348                 return RLM_MODULE_FAIL;
349         }
350
351         /*
352          *      Post a timestamp
353          */
354         fseek(outfp, 0L, SEEK_END);
355         radius_xlat(timestamp, sizeof(timestamp), inst->header, request, NULL);
356         fprintf(outfp, "%s\n", timestamp);
357
358         /*
359          *      Write the information to the file.
360          */
361         if (!compat) {
362                 /*
363                  *      Print out names, if they're OK.
364                  *      Numbers, if not.
365                  */
366                 if ((packet->code > 0) &&
367                     (packet->code <= PW_ACCESS_CHALLENGE)) {
368                         fprintf(outfp, "\tPacket-Type = %s\n",
369                                 packet_codes[packet->code]);
370                 } else {
371                         fprintf(outfp, "\tPacket-Type = %d\n", packet->code);
372                 }
373         }
374
375         if (inst->log_srcdst) {
376                 VALUE_PAIR src_vp, dst_vp;
377
378                 src_vp.name[0] = dst_vp.name[0] = '\0'; /* for vp_prints() */
379                 src_vp.operator = dst_vp.operator = T_OP_EQ;
380
381                 switch (packet->src_ipaddr.af) {
382                 case AF_INET:
383                         src_vp.type = PW_TYPE_IPADDR;
384                         src_vp.attribute = PW_PACKET_SRC_IP_ADDRESS;
385                         src_vp.lvalue = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
386                         dst_vp.type = PW_TYPE_IPADDR;
387                         dst_vp.attribute = PW_PACKET_DST_IP_ADDRESS;
388                         dst_vp.lvalue = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
389                         break;
390                 case AF_INET6:
391                         src_vp.type = PW_TYPE_IPV6ADDR; 
392                         src_vp.attribute = PW_PACKET_SRC_IPV6_ADDRESS;
393                         memcpy(src_vp.vp_strvalue,
394                                &packet->src_ipaddr.ipaddr.ip6addr,
395                                sizeof(packet->src_ipaddr.ipaddr.ip6addr));
396                         dst_vp.type = PW_TYPE_IPV6ADDR; 
397                         dst_vp.attribute = PW_PACKET_DST_IPV6_ADDRESS;
398                         memcpy(dst_vp.vp_strvalue,
399                                &packet->dst_ipaddr.ipaddr.ip6addr,
400                                sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
401                         break;
402                 default:
403                         break;
404                 }
405
406                 fputs("\t", outfp);
407                 vp_print(outfp, &src_vp);
408                 fputs("\n", outfp);
409                 fputs("\t", outfp);
410                 vp_print(outfp, &dst_vp);
411                 fputs("\n", outfp);
412
413                 src_vp.attribute = PW_PACKET_SRC_PORT;
414                 src_vp.type = PW_TYPE_INTEGER;
415                 src_vp.lvalue = packet->src_port;
416                 dst_vp.attribute = PW_PACKET_DST_PORT;
417                 dst_vp.type = PW_TYPE_INTEGER;
418                 dst_vp.lvalue = packet->dst_port;
419
420                 fputs("\t", outfp);
421                 vp_print(outfp, &src_vp);
422                 fputs("\n", outfp);
423                 fputs("\t", outfp);
424                 vp_print(outfp, &dst_vp);
425                 fputs("\n", outfp);
426         }
427
428         /* Write each attribute/value to the log file */
429         for (pair = packet->vps; pair != NULL; pair = pair->next) {
430                 DICT_ATTR da;
431                 da.attr = pair->attribute;
432
433                 if (inst->ht &&
434                     lrad_hash_table_finddata(inst->ht, &da)) continue;
435
436                 /*
437                  *      Don't print passwords in old format...
438                  */
439                 if (compat && (pair->attribute == PW_USER_PASSWORD)) continue;
440
441                 /*
442                  *      Print all of the attributes.
443                  */
444                 fputs("\t", outfp);
445                 vp_print(outfp, pair);
446                 fputs("\n", outfp);
447         }
448
449         /*
450          *      Add non-protocol attibutes.
451          */
452         if (compat) {
453                 if (request->proxy) {
454                         char proxy_buffer[128];
455
456                         inet_ntop(request->proxy->dst_ipaddr.af,
457                                   &request->proxy->dst_ipaddr.ipaddr,
458                                   proxy_buffer, sizeof(proxy_buffer));
459                         fprintf(outfp, "\tFreeradius-Proxied-To = %s\n",
460                                         proxy_buffer);
461                                 DEBUG("rlm_detail: Freeradius-Proxied-To = %s",
462                                       proxy_buffer);
463                 }
464
465                 fprintf(outfp, "\tTimestamp = %ld\n",
466                         (unsigned long) request->timestamp);
467
468                 if (request->packet->verified == 2)
469                         fputs("\tRequest-Authenticator = Verified\n", outfp);
470                 else if (request->packet->verified == 1)
471                         fputs("\tRequest-Authenticator = None\n", outfp);
472         }
473
474         fputs("\n", outfp);
475
476         if (inst->locking) {
477                 fflush(outfp);
478                 lseek(outfd, 0L, SEEK_SET);
479                 rad_unlockfd(outfd, 0);
480                 DEBUG("rlm_detail: Released filelock");
481         }
482
483         fclose(outfp);
484
485         /*
486          *      And everything is fine.
487          */
488         return RLM_MODULE_OK;
489 }
490
491 /*
492  *      Accounting - write the detail files.
493  */
494 static int detail_accounting(void *instance, REQUEST *request)
495 {
496
497         return do_detail(instance,request,request->packet, TRUE);
498 }
499
500 /*
501  *      Incoming Access Request - write the detail files.
502  */
503 static int detail_authorize(void *instance, REQUEST *request)
504 {
505         return do_detail(instance,request,request->packet, FALSE);
506 }
507
508 /*
509  *      Outgoing Access-Request Reply - write the detail files.
510  */
511 static int detail_postauth(void *instance, REQUEST *request)
512 {
513         return do_detail(instance,request,request->reply, FALSE);
514 }
515
516
517 /*
518  *      Outgoing Access-Request to home server - write the detail files.
519  */
520 static int detail_pre_proxy(void *instance, REQUEST *request)
521 {
522         if (request->proxy &&
523             request->proxy->vps) {
524                 return do_detail(instance,request,request->proxy, FALSE);
525         }
526
527         return RLM_MODULE_NOOP;
528 }
529
530
531 /*
532  *      Outgoing Access-Request Reply - write the detail files.
533  */
534 static int detail_post_proxy(void *instance, REQUEST *request)
535 {
536         if (request->proxy_reply &&
537             request->proxy_reply->vps) {
538                 return do_detail(instance,request,request->proxy_reply, FALSE);
539         }
540
541         return RLM_MODULE_NOOP;
542 }
543
544
545 /* globally exported name */
546 module_t rlm_detail = {
547         RLM_MODULE_INIT,
548         "detail",
549         RLM_TYPE_THREAD_UNSAFE,        /* type: reserved */
550         detail_instantiate,             /* instantiation */
551         detail_detach,                  /* detach */
552         {
553                 NULL,                   /* authentication */
554                 detail_authorize,       /* authorization */
555                 NULL,                   /* preaccounting */
556                 detail_accounting,      /* accounting */
557                 NULL,                   /* checksimul */
558                 detail_pre_proxy,       /* pre-proxy */
559                 detail_post_proxy,      /* post-proxy */
560                 detail_postauth         /* post-auth */
561         },
562 };
563