'static' to 'static const'
[freeradius.git] / src / modules / rlm_counter / rlm_counter.c
1 /*
2  * rlm_counter.c
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Copyright 2001  The FreeRADIUS server project
21  * Copyright 2001  Alan DeKok <aland@ox.org>
22  * Copyright 2001-3  Kostas Kalevras <kkalev@noc.ntua.gr>
23  */
24
25 #include "config.h"
26 #include "autoconf.h"
27 #include "libradius.h"
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <ctype.h>
33
34 #include "radiusd.h"
35 #include "modules.h"
36 #include "conffile.h"
37
38 #include <gdbm.h>
39 #include <time.h>
40
41 #ifdef NEEDS_GDBM_SYNC
42 #       define GDBM_SYNCOPT GDBM_SYNC
43 #else
44 #       define GDBM_SYNCOPT 0
45 #endif
46
47 #ifdef GDBM_NOLOCK
48 #define GDBM_COUNTER_OPTS (GDBM_SYNCOPT | GDBM_NOLOCK)
49 #else
50 #define GDBM_COUNTER_OPTS (GDBM_SYNCOPT)
51 #endif
52
53 #ifndef HAVE_GDBM_FDESC
54 #define gdbm_fdesc(foo) (-1)
55 #endif
56
57 #define UNIQUEID_MAX_LEN 32
58
59 static const char rcsid[] = "$Id$";
60
61 /*
62  *      Define a structure for our module configuration.
63  *
64  *      These variables do not need to be in a structure, but it's
65  *      a lot cleaner to do so, and a pointer to the structure can
66  *      be used as the instance handle.
67  */
68 typedef struct rlm_counter_t {
69         char *filename;         /* name of the database file */
70         char *reset;            /* daily, weekly, monthly, never or user defined */
71         char *key_name;         /* User-Name */
72         char *count_attribute;  /* Acct-Session-Time */
73         char *return_attribute; /* Session-Timeout */
74         char *counter_name;     /* Daily-Session-Time */
75         char *check_name;       /* Daily-Max-Session */
76         char *service_type;     /* Service-Type to search for */
77         int cache_size;
78         int service_val;
79         int key_attr;
80         int count_attr;
81         int return_attr;
82         int check_attr;
83         time_t reset_time;      /* The time of the next reset. */
84         time_t last_reset;      /* The time of the last reset. */
85         int dict_attr;          /* attribute number for the counter. */
86         GDBM_FILE gdbm;         /* The gdbm file handle */
87 #ifdef HAVE_PTHREAD_H
88         pthread_mutex_t mutex;  /* A mutex to lock the gdbm file for only one reader/writer */
89 #endif
90 } rlm_counter_t;
91
92 #ifndef HAVE_PTHREAD_H
93 /*
94  *      This is a lot simpler than putting ifdef's around
95  *      every use of the pthread functions.
96  */
97 #define pthread_mutex_lock(a)
98 #define pthread_mutex_unlock(a)
99 #define pthread_mutex_init(a,b)
100 #define pthread_mutex_destroy(a)
101 #endif
102
103 typedef struct rad_counter {
104         unsigned int user_counter;
105         char uniqueid[UNIQUEID_MAX_LEN];
106 } rad_counter;
107
108 /*
109  *      A mapping of configuration file names to internal variables.
110  *
111  *      Note that the string is dynamically allocated, so it MUST
112  *      be freed.  When the configuration file parse re-reads the string,
113  *      it free's the old one, and strdup's the new one, placing the pointer
114  *      to the strdup'd string into 'config.string'.  This gets around
115  *      buffer over-flows.
116  */
117 static const CONF_PARSER module_config[] = {
118   { "filename", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,filename), NULL, NULL },
119   { "key", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,key_name), NULL, NULL },
120   { "reset", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,reset), NULL,  NULL },
121   { "count-attribute", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,count_attribute), NULL, NULL },
122   { "return-attribute", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,return_attribute), NULL, NULL },
123   { "counter-name", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,counter_name), NULL,  NULL },
124   { "check-name", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,check_name), NULL, NULL },
125   { "allowed-servicetype", PW_TYPE_STRING_PTR, offsetof(rlm_counter_t,service_type),NULL, NULL },
126   { "cache-size", PW_TYPE_INTEGER, offsetof(rlm_counter_t,cache_size), NULL, "1000" },
127   { NULL, -1, 0, NULL, NULL }
128 };
129
130 static int counter_detach(void *instance);
131
132
133 /*
134  *      See if the counter matches.
135  */
136 static int counter_cmp(void *instance,
137                        REQUEST *req UNUSED,
138                        VALUE_PAIR *request, VALUE_PAIR *check,
139                        VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
140 {
141         rlm_counter_t *data = (rlm_counter_t *) instance;
142         datum key_datum;
143         datum count_datum;
144         VALUE_PAIR *key_vp;
145         rad_counter counter;
146
147         check_pairs = check_pairs; /* shut the compiler up */
148         reply_pairs = reply_pairs;
149         req = req;
150
151         /*
152          *      Find the key attribute.
153          */
154         key_vp = pairfind(request, data->key_attr);
155         if (key_vp == NULL) {
156                 return RLM_MODULE_NOOP;
157         }
158
159         key_datum.dptr = key_vp->strvalue;
160         key_datum.dsize = key_vp->length;
161
162         count_datum = gdbm_fetch(data->gdbm, key_datum);
163
164         if (count_datum.dptr == NULL) {
165                 return -1;
166         }
167         memcpy(&counter, count_datum.dptr, sizeof(rad_counter));
168         free(count_datum.dptr);
169
170         return counter.user_counter - check->lvalue;
171 }
172
173
174 static int add_defaults(rlm_counter_t *data)
175 {
176         datum key_datum;
177         datum time_datum;
178         const char *default1 = "DEFAULT1";
179         const char *default2 = "DEFAULT2";
180
181         DEBUG2("rlm_counter: add_defaults: Start");
182
183         key_datum.dptr = (char *) default1;
184         key_datum.dsize = strlen(default1);
185         time_datum.dptr = (char *) &data->reset_time;
186         time_datum.dsize = sizeof(time_t);
187
188         if (gdbm_store(data->gdbm, key_datum, time_datum, GDBM_REPLACE) < 0){
189                 radlog(L_ERR, "rlm_counter: Failed storing data to %s: %s",
190                                 data->filename, gdbm_strerror(gdbm_errno));
191                 return RLM_MODULE_FAIL;
192         }
193         DEBUG2("rlm_counter: DEFAULT1 set to %d",(int)data->reset_time);
194
195         key_datum.dptr = (char *) default2;
196         key_datum.dsize = strlen(default2);
197         time_datum.dptr = (char *) &data->last_reset;
198         time_datum.dsize = sizeof(time_t);
199
200         if (gdbm_store(data->gdbm, key_datum, time_datum, GDBM_REPLACE) < 0){
201                 radlog(L_ERR, "rlm_counter: Failed storing data to %s: %s",
202                                 data->filename, gdbm_strerror(gdbm_errno));
203                 return RLM_MODULE_FAIL;
204         }
205         DEBUG2("rlm_counter: DEFAULT2 set to %d",(int)data->last_reset);
206         DEBUG2("rlm_counter: add_defaults: End");
207
208         return RLM_MODULE_OK;
209 }
210
211 static int reset_db(rlm_counter_t *data)
212 {
213         int cache_size = data->cache_size;
214         int ret;
215
216         DEBUG2("rlm_counter: reset_db: Closing database");
217         gdbm_close(data->gdbm);
218
219         /*
220          *      Open a completely new database.
221          */
222         data->gdbm = gdbm_open(data->filename, sizeof(int),
223                         GDBM_NEWDB | GDBM_COUNTER_OPTS, 0600, NULL);
224         if (data->gdbm == NULL) {
225                 radlog(L_ERR, "rlm_counter: Failed to open file %s: %s",
226                                 data->filename, strerror(errno));
227                 return RLM_MODULE_FAIL;
228         }
229         if (gdbm_setopt(data->gdbm, GDBM_CACHESIZE, &cache_size, sizeof(int)) == -1)
230                 radlog(L_ERR, "rlm_counter: Failed to set cache size");
231         DEBUG2("rlm_counter: reset_db: Opened new database");
232
233         /*
234          * Add defaults
235          */
236         ret = add_defaults(data);
237         if (ret != RLM_MODULE_OK)
238                 return ret;
239
240         DEBUG2("rlm_counter: reset_db ended");
241
242         return RLM_MODULE_OK;
243 }
244
245 static int find_next_reset(rlm_counter_t *data, time_t timeval)
246 {
247         int ret=0;
248         unsigned int num=1;
249         char last = 0;
250         struct tm *tm, s_tm;
251         char sCurrentTime[40], sNextTime[40];
252
253         tm = localtime_r(&timeval, &s_tm);
254         strftime(sCurrentTime, sizeof(sCurrentTime),"%Y-%m-%d %H:%M:%S",tm);
255         tm->tm_sec = tm->tm_min = 0;
256
257         if (data->reset == NULL)
258                 return -1;
259         if (isdigit((int) data->reset[0])){
260                 unsigned int len=0;
261
262                 len = strlen(data->reset);
263                 if (len == 0)
264                         return -1;
265                 last = data->reset[len - 1];
266                 if (!isalpha((int) last))
267                         last = 'd';
268                 num = atoi(data->reset);
269                 DEBUG("rlm_counter: num=%d, last=%c",num,last);
270         }
271         if (strcmp(data->reset, "hourly") == 0 || last == 'h') {
272                 /*
273                  *  Round up to the next nearest hour.
274                  */
275                 tm->tm_hour += num;
276                 data->reset_time = mktime(tm);
277         } else if (strcmp(data->reset, "daily") == 0 || last == 'd') {
278                 /*
279                  *  Round up to the next nearest day.
280                  */
281                 tm->tm_hour = 0;
282                 tm->tm_mday += num;
283                 data->reset_time = mktime(tm);
284         } else if (strcmp(data->reset, "weekly") == 0 || last == 'w') {
285                 /*
286                  *  Round up to the next nearest week.
287                  */
288                 tm->tm_hour = 0;
289                 tm->tm_mday += (7 - tm->tm_wday) +(7*(num-1));
290                 data->reset_time = mktime(tm);
291         } else if (strcmp(data->reset, "monthly") == 0 || last == 'm') {
292                 tm->tm_hour = 0;
293                 tm->tm_mday = 1;
294                 tm->tm_mon += num;
295                 data->reset_time = mktime(tm);
296         } else if (strcmp(data->reset, "never") == 0) {
297                 data->reset_time = 0;
298         } else {
299                 radlog(L_ERR, "rlm_counter: Unknown reset timer \"%s\"",
300                         data->reset);
301                 return -1;
302         }
303         strftime(sNextTime, sizeof(sNextTime),"%Y-%m-%d %H:%M:%S",tm);
304         DEBUG2("rlm_counter: Current Time: %d [%s], Next reset %d [%s]",
305                 (int)timeval,sCurrentTime,(int)data->reset_time,sNextTime);
306
307         return ret;
308 }
309
310
311 /*
312  *      Do any per-module initialization that is separate to each
313  *      configured instance of the module.  e.g. set up connections
314  *      to external databases, read configuration files, set up
315  *      dictionary entries, etc.
316  *
317  *      If configuration information is given in the config section
318  *      that must be referenced in later calls, store a handle to it
319  *      in *instance otherwise put a null pointer there.
320  */
321 static int counter_instantiate(CONF_SECTION *conf, void **instance)
322 {
323         rlm_counter_t *data;
324         DICT_ATTR *dattr;
325         DICT_VALUE *dval;
326         ATTR_FLAGS flags;
327         time_t now;
328         int cache_size;
329         int ret;
330         datum key_datum;
331         datum time_datum;
332         const char *default1 = "DEFAULT1";
333         const char *default2 = "DEFAULT2";
334
335         /*
336          *      Set up a storage area for instance data
337          */
338         data = rad_malloc(sizeof(*data));
339         if (!data) {
340                 radlog(L_ERR, "rlm_counter: rad_malloc() failed.");
341                 return -1;
342         }
343         memset(data, 0, sizeof(*data));
344
345         /*
346          *      If the configuration parameters can't be parsed, then
347          *      fail.
348          */
349         if (cf_section_parse(conf, data, module_config) < 0) {
350                 free(data);
351                 return -1;
352         }
353         cache_size = data->cache_size;
354
355         /*
356          *      Discover the attribute number of the key.
357          */
358         if (data->key_name == NULL) {
359                 radlog(L_ERR, "rlm_counter: 'key' must be set.");
360                 counter_detach(data);
361                 return -1;
362         }
363         dattr = dict_attrbyname(data->key_name);
364         if (dattr == NULL) {
365                 radlog(L_ERR, "rlm_counter: No such attribute %s",
366                                 data->key_name);
367                 counter_detach(data);
368                 return -1;
369         }
370         data->key_attr = dattr->attr;
371
372         /*
373          *      Discover the attribute number of the counter.
374          */
375         if (data->count_attribute == NULL) {
376                 radlog(L_ERR, "rlm_counter: 'count-attribute' must be set.");
377                 counter_detach(data);
378                 return -1;
379         }
380         dattr = dict_attrbyname(data->count_attribute);
381         if (dattr == NULL) {
382                 radlog(L_ERR, "rlm_counter: No such attribute %s",
383                                 data->count_attribute);
384                 counter_detach(data);
385                 return -1;
386         }
387         data->count_attr = dattr->attr;
388
389         /*
390          * Discover the attribute number of the return attribute.
391          */
392         if (data->return_attribute != NULL) {
393                 dattr = dict_attrbyname(data->return_attribute);
394                 if (dattr == NULL) {
395                         radlog(L_ERR, "rlm_counter: No such attribute %s",
396                                         data->return_attribute);
397                         counter_detach(data);
398                         return -1;
399                 }
400                 if (dattr->type != PW_TYPE_INTEGER) {
401                         radlog(L_ERR, "rlm_counter: Return attribute %s is not of type integer",
402                                 data->return_attribute);
403                         counter_detach(data);
404                         return -1;
405                 }
406                 data->return_attr = dattr->attr;
407         }
408         
409
410         /*
411          *  Create a new attribute for the counter.
412          */
413         if (data->counter_name == NULL) {
414                 radlog(L_ERR, "rlm_counter: 'counter-name' must be set.");
415                 counter_detach(data);
416                 return -1;
417         }
418
419         memset(&flags, 0, sizeof(flags));
420         dict_addattr(data->counter_name, 0, PW_TYPE_INTEGER, -1, flags);
421         dattr = dict_attrbyname(data->counter_name);
422         if (dattr == NULL) {
423                 radlog(L_ERR, "rlm_counter: Failed to create counter attribute %s",
424                                 data->counter_name);
425                 counter_detach(data);
426                 return -1;
427         }
428         data->dict_attr = dattr->attr;
429         DEBUG2("rlm_counter: Counter attribute %s is number %d",
430                         data->counter_name, data->dict_attr);
431
432         /*
433          * Create a new attribute for the check item.
434          */
435         if (data->check_name == NULL) {
436                 radlog(L_ERR, "rlm_counter: 'check-name' must be set.");
437                 counter_detach(data);
438                 return -1;
439         }
440         dict_addattr(data->check_name, 0, PW_TYPE_INTEGER, -1, flags);
441         dattr = dict_attrbyname(data->check_name);
442         if (dattr == NULL) {
443                 radlog(L_ERR, "rlm_counter: Failed to create check attribute %s",
444                                 data->counter_name);
445                 counter_detach(data);
446                 return -1;
447         }
448         data->check_attr = dattr->attr;
449
450         /*
451          * Find the attribute for the allowed protocol
452          */
453         if (data->service_type != NULL) {
454                 if ((dval = dict_valbyname(PW_SERVICE_TYPE, data->service_type)) == NULL) {
455                         radlog(L_ERR, "rlm_counter: Failed to find attribute number for %s",
456                                         data->service_type);
457                         counter_detach(data);
458                         return -1;
459                 }
460                 data->service_val = dval->value;
461         }
462
463         /*
464          * Find when to reset the database.
465          */
466         if (data->reset == NULL) {
467                 radlog(L_ERR, "rlm_counter: 'reset' must be set.");
468                 counter_detach(data);
469                 return -1;
470         }
471         now = time(NULL);
472         data->reset_time = 0;
473         data->last_reset = now;
474
475         if (find_next_reset(data,now) == -1){
476                 radlog(L_ERR, "rlm_counter: find_next_reset() returned -1. Exiting.");
477                 counter_detach(data);
478                 return -1;
479         }
480
481         if (data->filename == NULL) {
482                 radlog(L_ERR, "rlm_counter: 'filename' must be set.");
483                 counter_detach(data);
484                 return -1;
485         }
486         data->gdbm = gdbm_open(data->filename, sizeof(int),
487                         GDBM_WRCREAT | GDBM_COUNTER_OPTS, 0600, NULL);
488         if (data->gdbm == NULL) {
489                 radlog(L_ERR, "rlm_counter: Failed to open file %s: %s",
490                                 data->filename, strerror(errno));
491                 counter_detach(data);
492                 return -1;
493         }
494         if (gdbm_setopt(data->gdbm, GDBM_CACHESIZE, &cache_size, sizeof(int)) == -1)
495                 radlog(L_ERR, "rlm_counter: Failed to set cache size");
496
497         /*
498          * Look for the DEFAULT1 entry. This entry if it exists contains the
499          * time of the next database reset. This time is set each time we reset
500          * the database. If next_reset < now then we reset the database.
501          * That way we can overcome the problem where radiusd is down during a database
502          * reset time. If we did not keep state information in the database then the reset
503          * would be extended and that would create problems.
504          *
505          * We also store the time of the last reset in the DEFAULT2 entry.
506          *
507          * If DEFAULT1 and DEFAULT2 do not exist (new database) we add them to the database
508          */
509
510         key_datum.dptr = (char *)default1;
511         key_datum.dsize = strlen(default1);
512
513         time_datum = gdbm_fetch(data->gdbm, key_datum);
514         if (time_datum.dptr != NULL){
515                 time_t next_reset = 0;
516
517                 memcpy(&next_reset, time_datum.dptr, sizeof(time_t));
518                 free(time_datum.dptr);
519                 if (next_reset && next_reset <= now){
520
521                         data->last_reset = now;
522                         ret = reset_db(data);
523                         if (ret != RLM_MODULE_OK){
524                                 radlog(L_ERR, "rlm_counter: reset_db() failed");
525                                 counter_detach(data);
526                                 return -1;
527                         }
528                 }
529                 else
530                         data->reset_time = next_reset;
531                 key_datum.dptr = (char *)default2;
532                 key_datum.dsize = strlen(default2);
533
534                 time_datum = gdbm_fetch(data->gdbm, key_datum);
535                 if (time_datum.dptr != NULL){
536                         memcpy(&data->last_reset, time_datum.dptr, sizeof(time_t));
537                         free(time_datum.dptr);
538                 }
539         }
540         else{
541                 ret = add_defaults(data);
542                 if (ret != RLM_MODULE_OK){
543                         radlog(L_ERR, "rlm_counter: add_defaults() failed");
544                         counter_detach(data);
545                         return -1;
546                 }
547         }
548
549
550         /*
551          *      Register the counter comparison operation.
552          */
553         paircompare_register(data->dict_attr, 0, counter_cmp, data);
554
555         /*
556          * Init the mutex
557          */
558         pthread_mutex_init(&data->mutex, NULL);
559
560         *instance = data;
561
562         return 0;
563 }
564
565 /*
566  *      Write accounting information to this modules database.
567  */
568 static int counter_accounting(void *instance, REQUEST *request)
569 {
570         rlm_counter_t *data = (rlm_counter_t *)instance;
571         datum key_datum;
572         datum count_datum;
573         VALUE_PAIR *key_vp, *count_vp, *proto_vp, *uniqueid_vp;
574         rad_counter counter;
575         int rcode;
576         int acctstatustype = 0;
577         time_t diff;
578
579         if ((key_vp = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE)) != NULL)
580                 acctstatustype = key_vp->lvalue;
581         else {
582                 DEBUG("rlm_counter: Could not find account status type in packet.");
583                 return RLM_MODULE_NOOP;
584         }
585         if (acctstatustype != PW_STATUS_STOP){
586                 DEBUG("rlm_counter: We only run on Accounting-Stop packets.");
587                 return RLM_MODULE_NOOP;
588         }
589         uniqueid_vp = pairfind(request->packet->vps, PW_ACCT_UNIQUE_SESSION_ID);
590         if (uniqueid_vp != NULL)
591                 DEBUG("rlm_counter: Packet Unique ID = '%s'",uniqueid_vp->strvalue);
592
593         /*
594          *      Before doing anything else, see if we have to reset
595          *      the counters.
596          */
597         if (data->reset_time && (data->reset_time <= request->timestamp)) {
598                 int ret;
599
600                 DEBUG("rlm_counter: Time to reset the database.");
601                 data->last_reset = data->reset_time;
602                 find_next_reset(data,request->timestamp);
603                 pthread_mutex_lock(&data->mutex);
604                 ret = reset_db(data);
605                 pthread_mutex_unlock(&data->mutex);
606                 if (ret != RLM_MODULE_OK)
607                         return ret;
608         }
609         /*
610          * Check if we need to watch out for a specific service-type. If yes then check it
611          */
612         if (data->service_type != NULL) {
613                 if ((proto_vp = pairfind(request->packet->vps, PW_SERVICE_TYPE)) == NULL){
614                         DEBUG("rlm_counter: Could not find Service-Type attribute in the request. Returning NOOP.");
615                         return RLM_MODULE_NOOP;
616                 }
617                 if ((unsigned)proto_vp->lvalue != data->service_val){
618                         DEBUG("rlm_counter: This Service-Type is not allowed. Returning NOOP.");
619                         return RLM_MODULE_NOOP;
620                 }
621         }
622         /*
623          * Check if request->timestamp - {Acct-Delay-Time} < last_reset
624          * If yes reject the packet since it is very old
625          */
626         key_vp = pairfind(request->packet->vps, PW_ACCT_DELAY_TIME);
627         if (key_vp != NULL){
628                 if (key_vp->lvalue != 0 &&
629                     (request->timestamp - key_vp->lvalue) < data->last_reset){
630                         DEBUG("rlm_counter: This packet is too old. Returning NOOP.");
631                         return RLM_MODULE_NOOP;
632                 }
633         }
634
635
636
637         /*
638          *      Look for the key.  User-Name is special.  It means
639          *      The REAL username, after stripping.
640          */
641         key_vp = (data->key_attr == PW_USER_NAME) ? request->username : pairfind(request->packet->vps, data->key_attr);
642         if (key_vp == NULL){
643                 DEBUG("rlm_counter: Could not find the key-attribute in the request. Returning NOOP.");
644                 return RLM_MODULE_NOOP;
645         }
646
647         /*
648          *      Look for the attribute to use as a counter.
649          */
650         count_vp = pairfind(request->packet->vps, data->count_attr);
651         if (count_vp == NULL){
652                 DEBUG("rlm_counter: Could not find the count-attribute in the request.");
653                 return RLM_MODULE_NOOP;
654         }
655
656         key_datum.dptr = key_vp->strvalue;
657         key_datum.dsize = key_vp->length;
658
659         DEBUG("rlm_counter: Searching the database for key '%s'",key_vp->strvalue);
660         pthread_mutex_lock(&data->mutex);
661         count_datum = gdbm_fetch(data->gdbm, key_datum);
662         pthread_mutex_unlock(&data->mutex);
663         if (count_datum.dptr == NULL){
664                 DEBUG("rlm_counter: Could not find the requested key in the database.");
665                 counter.user_counter = 0;
666                 if (uniqueid_vp != NULL)
667                         strncpy(counter.uniqueid,uniqueid_vp->strvalue,UNIQUEID_MAX_LEN - 1);
668                 else
669                         memset((char *)counter.uniqueid,0,UNIQUEID_MAX_LEN);
670         }
671         else{
672                 DEBUG("rlm_counter: Key found.");
673                 memcpy(&counter, count_datum.dptr, sizeof(rad_counter));
674                 free(count_datum.dptr);
675                 if (counter.uniqueid)
676                         DEBUG("rlm_counter: Counter Unique ID = '%s'",counter.uniqueid);
677                 if (uniqueid_vp != NULL){
678                         if (counter.uniqueid != NULL &&
679                                 strncmp(uniqueid_vp->strvalue,counter.uniqueid, UNIQUEID_MAX_LEN - 1) == 0){
680                                 DEBUG("rlm_counter: Unique IDs for user match. Droping the request.");
681                                 return RLM_MODULE_NOOP;
682                         }
683                         strncpy(counter.uniqueid,uniqueid_vp->strvalue,UNIQUEID_MAX_LEN - 1);
684                 }
685                 DEBUG("rlm_counter: User=%s, Counter=%d.",request->username->strvalue,counter.user_counter);
686         }
687
688         if (data->count_attr == PW_ACCT_SESSION_TIME) {
689                 /*
690                  *      If session time < diff then the user got in after the
691                  *      last reset. So add his session time, otherwise add the
692                  *      diff.
693                  *
694                  *      That way if he logged in at 23:00 and we reset the
695                  *      daily counter at 24:00 and he logged out at 01:00
696                  *      then we will only count one hour (the one in the new
697                  *      day). That is the right thing
698                  */
699                 diff = request->timestamp - data->last_reset;
700                 counter.user_counter += (count_vp->lvalue < diff) ? count_vp->lvalue : diff;
701
702         } else if (count_vp->type == PW_TYPE_INTEGER) {
703                 /*
704                  *      Integers get counted, without worrying about
705                  *      reset dates.
706                  */
707                 counter.user_counter += count_vp->lvalue;
708
709         } else {
710                 /*
711                  *      The attribute is NOT an integer, just count once
712                  *      more that we've seen it.
713                  */
714                 counter.user_counter++;
715         }
716
717         DEBUG("rlm_counter: User=%s, New Counter=%d.",request->username->strvalue,counter.user_counter);
718         count_datum.dptr = (char *) &counter;
719         count_datum.dsize = sizeof(rad_counter);
720
721         DEBUG("rlm_counter: Storing new value in database.");
722         pthread_mutex_lock(&data->mutex);
723         rcode = gdbm_store(data->gdbm, key_datum, count_datum, GDBM_REPLACE);
724         pthread_mutex_unlock(&data->mutex);
725         if (rcode < 0) {
726                 radlog(L_ERR, "rlm_counter: Failed storing data to %s: %s",
727                                 data->filename, gdbm_strerror(gdbm_errno));
728                 return RLM_MODULE_FAIL;
729         }
730         DEBUG("rlm_counter: New value stored successfully.");
731
732         return RLM_MODULE_OK;
733 }
734
735 /*
736  *      Find the named user in this modules database.  Create the set
737  *      of attribute-value pairs to check and reply with for this user
738  *      from the database. The authentication code only needs to check
739  *      the password, the rest is done here.
740  */
741 static int counter_authorize(void *instance, REQUEST *request)
742 {
743         rlm_counter_t *data = (rlm_counter_t *) instance;
744         int ret=RLM_MODULE_NOOP;
745         datum key_datum;
746         datum count_datum;
747         rad_counter counter;
748         int res=0;
749         VALUE_PAIR *key_vp, *check_vp;
750         VALUE_PAIR *reply_item;
751         char msg[128];
752
753         /* quiet the compiler */
754         instance = instance;
755         request = request;
756
757         /*
758          *      Before doing anything else, see if we have to reset
759          *      the counters.
760          */
761         if (data->reset_time && (data->reset_time <= request->timestamp)) {
762                 int ret2;
763
764                 data->last_reset = data->reset_time;
765                 find_next_reset(data,request->timestamp);
766                 pthread_mutex_lock(&data->mutex);
767                 ret2 = reset_db(data);
768                 pthread_mutex_unlock(&data->mutex);
769                 if (ret2 != RLM_MODULE_OK)
770                         return ret2;
771         }
772
773
774         /*
775          *      Look for the key.  User-Name is special.  It means
776          *      The REAL username, after stripping.
777          */
778         DEBUG2("rlm_counter: Entering module authorize code");
779         key_vp = (data->key_attr == PW_USER_NAME) ? request->username : pairfind(request->packet->vps, data->key_attr);
780         if (key_vp == NULL) {
781                 DEBUG2("rlm_counter: Could not find Key value pair");
782                 return ret;
783         }
784
785         /*
786          *      Look for the check item
787          */
788         if ((check_vp= pairfind(request->config_items, data->check_attr)) == NULL) {
789                 DEBUG2("rlm_counter: Could not find Check item value pair");
790                 return ret;
791         }
792
793         key_datum.dptr = key_vp->strvalue;
794         key_datum.dsize = key_vp->length;
795
796
797         /*
798          * Init to be sure
799          */
800
801         counter.user_counter = 0;
802
803         DEBUG("rlm_counter: Searching the database for key '%s'",key_vp->strvalue);
804         pthread_mutex_lock(&data->mutex);
805         count_datum = gdbm_fetch(data->gdbm, key_datum);
806         pthread_mutex_unlock(&data->mutex);
807         if (count_datum.dptr != NULL){
808                 DEBUG("rlm_counter: Key Found.");
809                 memcpy(&counter, count_datum.dptr, sizeof(rad_counter));
810                 free(count_datum.dptr);
811         }
812         else
813                 DEBUG("rlm_counter: Could not find the requested key in the database.");
814
815         /*
816          * Check if check item > counter
817          */
818         DEBUG("rlm_counter: Check item = %d, Count = %d",check_vp->lvalue,counter.user_counter);
819         res=check_vp->lvalue - counter.user_counter;
820         if (res > 0) {
821                 DEBUG("rlm_counter: res is greater than zero");
822                 if (data->count_attr == PW_ACCT_SESSION_TIME) {
823                         /*
824                          * Do the following only if the count attribute is
825                          * AcctSessionTime
826                          */
827
828                         /*
829                         *       We are assuming that simultaneous-use=1. But
830                         *       even if that does not happen then our user
831                         *       could login at max for 2*max-usage-time Is
832                         *       that acceptable?
833                         */
834
835                         /*
836                         *       User is allowed, but set Session-Timeout.
837                         *       Stolen from main/auth.c
838                         */
839
840                         /*
841                         *       If we are near a reset then add the next
842                         *       limit, so that the user will not need to
843                         *       login again
844                         *       Before that set the return value to the time
845                         *       remaining to next reset
846                         */
847                         if (data->reset_time && (
848                                 res >= (data->reset_time - request->timestamp))) {
849                                 res = data->reset_time - request->timestamp;
850                                 res += check_vp->lvalue;
851                         }
852
853                         if ((reply_item = pairfind(request->reply->vps, PW_SESSION_TIMEOUT)) != NULL) {
854                                 if (reply_item->lvalue > res)
855                                         reply_item->lvalue = res;
856                         } else {
857                                 if ((reply_item = paircreate(PW_SESSION_TIMEOUT, PW_TYPE_INTEGER)) == NULL) {
858                                         radlog(L_ERR|L_CONS, "no memory");
859                                         return RLM_MODULE_NOOP;
860                                 }
861                                 reply_item->lvalue = res;
862                                 pairadd(&request->reply->vps, reply_item);
863                         }
864                 }
865                 else if (data->return_attr) {
866                         if ((reply_item = pairfind(request->reply->vps, data->return_attr)) != NULL) {
867                                 if (reply_item->lvalue > res)
868                                         reply_item->lvalue = res;
869                         }
870                         else {
871                                 if ((reply_item = paircreate(data->return_attr, PW_TYPE_INTEGER)) == NULL) {
872                                         radlog(L_ERR|L_CONS, "no memory");
873                                         return RLM_MODULE_NOOP;
874                                 }
875                                 reply_item->lvalue = res;
876                                 pairadd(&request->reply->vps, reply_item);
877                         }
878                 }
879
880                 ret=RLM_MODULE_OK;
881
882                 DEBUG2("rlm_counter: (Check item - counter) is greater than zero");
883                 DEBUG2("rlm_counter: Authorized user %s, check_item=%d, counter=%d",
884                                 key_vp->strvalue,check_vp->lvalue,counter.user_counter);
885                 DEBUG2("rlm_counter: Sent Reply-Item for user %s, Type=Session-Timeout, value=%d",
886                                 key_vp->strvalue,res);
887         }
888         else{
889                 char module_fmsg[MAX_STRING_LEN];
890                 VALUE_PAIR *module_fmsg_vp;
891
892                 /*
893                  * User is denied access, send back a reply message
894                 */
895                 sprintf(msg, "Your maximum %s usage time has been reached", data->reset);
896                 reply_item=pairmake("Reply-Message", msg, T_OP_EQ);
897                 pairadd(&request->reply->vps, reply_item);
898
899                 snprintf(module_fmsg,sizeof(module_fmsg), "rlm_counter: Maximum %s usage time reached", data->reset);
900                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
901                 pairadd(&request->packet->vps, module_fmsg_vp);
902
903                 ret=RLM_MODULE_REJECT;
904
905                 DEBUG2("rlm_counter: Rejected user %s, check_item=%d, counter=%d",
906                                 key_vp->strvalue,check_vp->lvalue,counter.user_counter);
907         }
908
909         return ret;
910 }
911
912 static int counter_detach(void *instance)
913 {
914         rlm_counter_t *data = (rlm_counter_t *) instance;
915
916         paircompare_unregister(data->dict_attr, counter_cmp);
917         if (data->gdbm)
918                 gdbm_close(data->gdbm);
919         free(data->filename);
920         free(data->reset);
921         free(data->key_name);
922         free(data->count_attribute);
923         free(data->counter_name);
924         free(data->check_name);
925         free(data->service_type);
926         pthread_mutex_destroy(&data->mutex);
927
928         free(instance);
929         return 0;
930 }
931
932 /*
933  *      The module name should be the only globally exported symbol.
934  *      That is, everything else should be 'static'.
935  *
936  *      If the module needs to temporarily modify it's instantiation
937  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
938  *      The server will then take care of ensuring that the module
939  *      is single-threaded.
940  */
941 module_t rlm_counter = {
942         "Counter",
943         RLM_TYPE_THREAD_SAFE,           /* type */
944         NULL,                           /* initialization */
945         counter_instantiate,            /* instantiation */
946         {
947                 NULL,                   /* authentication */
948                 counter_authorize,      /* authorization */
949                 NULL,                   /* preaccounting */
950                 counter_accounting,     /* accounting */
951                 NULL,                   /* checksimul */
952                 NULL,                   /* pre-proxy */
953                 NULL,                   /* post-proxy */
954                 NULL                    /* post-auth */
955         },
956         counter_detach,                 /* detach */
957         NULL,                           /* destroy */
958 };