import from HEAD
[freeradius.git] / src / modules / rlm_sqlcounter / rlm_sqlcounter.c
1 /*
2  * rlm_sqlcounter.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  */
23
24 /* This module is based directly on the rlm_counter module */
25
26
27 #include "autoconf.h"
28 #include "libradius.h"
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34
35 #include "radiusd.h"
36 #include "modules.h"
37 #include "conffile.h"
38
39 #define MAX_QUERY_LEN 1024
40
41 #include <time.h>
42
43
44 /*      Note: When your counter spans more than 1 period (ie 3 months or 2 weeks), this module
45  *      probably does NOT do what you want!  It calculates the range of dates to count across
46  *      by first calculating the End of the Current period and then subtracting the number of
47  *      periods you specify from that to determine the beginning of the range.
48  *
49  *      For example, if you specify a 3 month counter and today is June 15th, the end of the current
50  *      period is June 30. Subtracting 3 months from that gives April 1st.  So, the counter will
51  *      sum radacct entries from April 1st to June 30. Then, next month, it will sum entries
52  *      from May 1st to July 31st.
53  *
54  *      To fix this behavior, we need to add some way of storing the Next Reset Time
55  */
56
57
58 static const char rcsid[] = "$Id$";
59
60 /*
61  *      Define a structure for our module configuration.
62  *
63  *      These variables do not need to be in a structure, but it's
64  *      a lot cleaner to do so, and a pointer to the structure can
65  *      be used as the instance handle.
66  */
67 typedef struct rlm_sqlcounter_t {
68         char *counter_name;     /* Daily-Session-Time */
69         char *check_name;       /* Max-Daily-Session */
70         char *key_name;         /* User-Name */
71         char *sqlmod_inst;      /* instance of SQL module to use, usually just 'sql' */
72         char *query;            /* SQL query to retrieve current session time */
73         char *reset;            /* daily, weekly, monthly, never or user defined */
74         char *allowed_chars;    /* safe characters list for SQL queries */
75         time_t reset_time;
76         time_t last_reset;
77         int  key_attr;          /* attribute number for key field */
78         int  dict_attr;         /* attribute number for the counter. */
79 } rlm_sqlcounter_t;
80
81 /*
82  *      A mapping of configuration file names to internal variables.
83  *
84  *      Note that the string is dynamically allocated, so it MUST
85  *      be freed.  When the configuration file parse re-reads the string,
86  *      it free's the old one, and strdup's the new one, placing the pointer
87  *      to the strdup'd string into 'config.string'.  This gets around
88  *      buffer over-flows.
89  */
90 static CONF_PARSER module_config[] = {
91   { "counter-name", PW_TYPE_STRING_PTR, offsetof(rlm_sqlcounter_t,counter_name), NULL,  NULL },
92   { "check-name", PW_TYPE_STRING_PTR, offsetof(rlm_sqlcounter_t,check_name), NULL, NULL },
93   { "key", PW_TYPE_STRING_PTR, offsetof(rlm_sqlcounter_t,key_name), NULL, NULL },
94   { "sqlmod-inst", PW_TYPE_STRING_PTR, offsetof(rlm_sqlcounter_t,sqlmod_inst), NULL, NULL },
95   { "query", PW_TYPE_STRING_PTR, offsetof(rlm_sqlcounter_t,query), NULL, NULL },
96   { "reset", PW_TYPE_STRING_PTR, offsetof(rlm_sqlcounter_t,reset), NULL,  NULL },
97   { "safe-characters", PW_TYPE_STRING_PTR, offsetof(rlm_sqlcounter_t,allowed_chars), NULL, "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /"},
98   { NULL, -1, 0, NULL, NULL }
99 };
100
101 static char *allowed_chars = NULL;
102
103 /*
104  *      Translate the SQL queries.
105  */
106 static int sql_escape_func(char *out, int outlen, const char *in)
107 {
108         int len = 0;
109
110         while (in[0]) {
111                 /*
112                  *      Non-printable characters get replaced with their
113                  *      mime-encoded equivalents.
114                  */
115                 if ((in[0] < 32) ||
116                     strchr(allowed_chars, *in) == NULL) {
117                         /*
118                          *      Only 3 or less bytes available.
119                          */
120                         if (outlen <= 3) {
121                                 break;
122                         }
123
124                         snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
125                         in++;
126                         out += 3;
127                         outlen -= 3;
128                         len += 3;
129                         continue;
130                 }
131
132                 /*
133                  *      Only one byte left.
134                  */
135                 if (outlen <= 1) {
136                         break;
137                 }
138
139                 /*
140                  *      Allowed character.
141                  */
142                 *out = *in;
143                 out++;
144                 in++;
145                 outlen--;
146                 len++;
147         }
148         *out = '\0';
149         return len;
150 }
151
152 static int find_next_reset(rlm_sqlcounter_t *data, time_t timeval)
153 {
154         int ret=0;
155         unsigned int num=1;
156         char last = 0;
157         struct tm *tm, s_tm;
158         char sCurrentTime[40], sNextTime[40];
159
160         tm = localtime_r(&timeval, &s_tm);
161         strftime(sCurrentTime, sizeof(sCurrentTime),"%Y-%m-%d %H:%M:%S",tm);
162         tm->tm_sec = tm->tm_min = 0;
163
164         if (data->reset == NULL)
165                 return -1;
166         if (isdigit((int) data->reset[0])){
167                 unsigned int len=0;
168
169                 len = strlen(data->reset);
170                 if (len == 0)
171                         return -1;
172                 last = data->reset[len - 1];
173                 if (!isalpha((int) last))
174                         last = 'd';
175 /*              num = atoi(data->reset); */
176                 DEBUG("rlm_sqlcounter: num=%d, last=%c",num,last);
177         }
178         if (strcmp(data->reset, "hourly") == 0 || last == 'h') {
179                 /*
180                  *  Round up to the next nearest hour.
181                  */
182                 tm->tm_hour += num;
183                 data->reset_time = mktime(tm);
184         } else if (strcmp(data->reset, "daily") == 0 || last == 'd') {
185                 /*
186                  *  Round up to the next nearest day.
187                  */
188                 tm->tm_hour = 0;
189                 tm->tm_mday += num;
190                 data->reset_time = mktime(tm);
191         } else if (strcmp(data->reset, "weekly") == 0 || last == 'w') {
192                 /*
193                  *  Round up to the next nearest week.
194                  */
195                 tm->tm_hour = 0;
196                 tm->tm_mday += (7 - tm->tm_wday) +(7*(num-1));
197                 data->reset_time = mktime(tm);
198         } else if (strcmp(data->reset, "monthly") == 0 || last == 'm') {
199                 tm->tm_hour = 0;
200                 tm->tm_mday = 1;
201                 tm->tm_mon += num;
202                 data->reset_time = mktime(tm);
203         } else if (strcmp(data->reset, "never") == 0) {
204                 data->reset_time = 0;
205         } else {
206                 radlog(L_ERR, "rlm_sqlcounter: Unknown reset timer \"%s\"",
207                         data->reset);
208                 return -1;
209         }
210         strftime(sNextTime, sizeof(sNextTime),"%Y-%m-%d %H:%M:%S",tm);
211         DEBUG2("rlm_sqlcounter: Current Time: %d [%s], Next reset %d [%s]",
212                 (int)timeval,sCurrentTime,(int)data->reset_time, sNextTime);
213
214         return ret;
215 }
216
217
218 /*  I don't believe that this routine handles Daylight Saving Time adjustments
219     properly.  Any suggestions?
220 */
221
222 static int find_prev_reset(rlm_sqlcounter_t *data, time_t timeval)
223 {
224         int ret=0;
225         unsigned int num=1;
226         char last = 0;
227         struct tm *tm, s_tm;
228         char sCurrentTime[40], sPrevTime[40];
229
230         tm = localtime_r(&timeval, &s_tm);
231         strftime(sCurrentTime, sizeof(sCurrentTime),"%Y-%m-%d %H:%M:%S",tm);
232         tm->tm_sec = tm->tm_min = 0;
233
234         if (data->reset == NULL)
235                 return -1;
236         if (isdigit((int) data->reset[0])){
237                 unsigned int len=0;
238
239                 len = strlen(data->reset);
240                 if (len == 0)
241                         return -1;
242                 last = data->reset[len - 1];
243                 if (!isalpha((int) last))
244                         last = 'd';
245                 num = atoi(data->reset);
246                 DEBUG("rlm_sqlcounter: num=%d, last=%c",num,last);
247         }
248         if (strcmp(data->reset, "hourly") == 0 || last == 'h') {
249                 /*
250                  *  Round down to the prev nearest hour.
251                  */
252                 tm->tm_hour -= num - 1;
253                 data->last_reset = mktime(tm);
254         } else if (strcmp(data->reset, "daily") == 0 || last == 'd') {
255                 /*
256                  *  Round down to the prev nearest day.
257                  */
258                 tm->tm_hour = 0;
259                 tm->tm_mday -= num - 1;
260                 data->last_reset = mktime(tm);
261         } else if (strcmp(data->reset, "weekly") == 0 || last == 'w') {
262                 /*
263                  *  Round down to the prev nearest week.
264                  */
265                 tm->tm_hour = 0;
266                 tm->tm_mday -= (7 - tm->tm_wday) +(7*(num-1));
267                 data->last_reset = mktime(tm);
268         } else if (strcmp(data->reset, "monthly") == 0 || last == 'm') {
269                 tm->tm_hour = 0;
270                 tm->tm_mday = 1;
271                 tm->tm_mon -= num - 1;
272                 data->last_reset = mktime(tm);
273         } else if (strcmp(data->reset, "never") == 0) {
274                 data->reset_time = 0;
275         } else {
276                 radlog(L_ERR, "rlm_sqlcounter: Unknown reset timer \"%s\"",
277                         data->reset);
278                 return -1;
279         }
280         strftime(sPrevTime, sizeof(sPrevTime),"%Y-%m-%d %H:%M:%S",tm);
281         DEBUG2("rlm_sqlcounter: Current Time: %d [%s], Prev reset %d [%s]",
282                 (int)timeval,sCurrentTime,(int)data->last_reset, sPrevTime);
283
284         return ret;
285 }
286
287
288 /*
289  *      Replace %<whatever> in a string.
290  *
291  *      %b      last_reset
292  *      %e      reset_time
293  *      %k      key_name
294  *      %S      sqlmod_inst
295  *
296  */
297
298 static int sqlcounter_expand(char *out, int outlen, const char *fmt, void *instance)
299 {
300         rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
301         int c,freespace;
302         const char *p;
303         char *q;
304         char tmpdt[40]; /* For temporary storing of dates */
305         int openbraces=0;
306
307         q = out;
308         for (p = fmt; *p ; p++) {
309         /* Calculate freespace in output */
310         freespace = outlen - (q - out);
311                 if (freespace <= 1)
312                         break;
313                 c = *p;
314                 if ((c != '%') && (c != '$') && (c != '\\')) {
315                         /*
316                          * We check if we're inside an open brace.  If we are
317                          * then we assume this brace is NOT literal, but is
318                          * a closing brace and apply it
319                          */
320                         if((c == '}') && openbraces) {
321                                 openbraces--;
322                                 continue;
323                         }
324                         *q++ = *p;
325                         continue;
326                 }
327                 if (*++p == '\0') break;
328                 if (c == '\\') switch(*p) {
329                         case '\\':
330                                 *q++ = *p;
331                                 break;
332                         case 't':
333                                 *q++ = '\t';
334                                 break;
335                         case 'n':
336                                 *q++ = '\n';
337                                 break;
338                         default:
339                                 *q++ = c;
340                                 *q++ = *p;
341                                 break;
342
343                 } else if (c == '%') switch(*p) {
344
345                         case '%':
346                                 *q++ = *p;
347                         case 'b': /* last_reset */
348                                 snprintf(tmpdt, sizeof(tmpdt), "%lu", data->last_reset);
349                                 strNcpy(q, tmpdt, freespace);
350                                 q += strlen(q);
351                                 break;
352                         case 'e': /* reset_time */
353                                 snprintf(tmpdt, sizeof(tmpdt), "%lu", data->reset_time);
354                                 strNcpy(q, tmpdt, freespace);
355                                 q += strlen(q);
356                                 break;
357                         case 'k': /* Key Name */
358                                 strNcpy(q, data->key_name, freespace);
359                                 q += strlen(q);
360                                 break;
361                         case 'S': /* SQL module instance */
362                                 strNcpy(q, data->sqlmod_inst, freespace);
363                                 q += strlen(q);
364                                 break;
365                         default:
366                                 *q++ = '%';
367                                 *q++ = *p;
368                                 break;
369                 }
370         }
371         *q = '\0';
372
373         DEBUG2("sqlcounter_expand:  '%s'", out);
374
375         return strlen(out);
376 }
377
378
379 /*
380  *      See if the counter matches.
381  */
382 static int sqlcounter_cmp(void *instance, REQUEST *req, VALUE_PAIR *request, VALUE_PAIR *check,
383                 VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
384 {
385         rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
386         int counter;
387         char querystr[MAX_QUERY_LEN];
388         char responsestr[MAX_QUERY_LEN];
389
390         check_pairs = check_pairs; /* shut the compiler up */
391         reply_pairs = reply_pairs;
392
393         /* first, expand %k, %b and %e in query */
394         sqlcounter_expand(querystr, MAX_QUERY_LEN, data->query, instance);
395
396         /* second, xlat any request attribs in query */
397         radius_xlat(responsestr, MAX_QUERY_LEN, querystr, req, sql_escape_func);
398
399         /* third, wrap query with sql module call & expand */
400         snprintf(querystr, sizeof(querystr), "%%{%%S:%s}", responsestr);
401         sqlcounter_expand(responsestr, MAX_QUERY_LEN, querystr, instance);
402
403         /* Finally, xlat resulting SQL query */
404         radius_xlat(querystr, MAX_QUERY_LEN, responsestr, req, sql_escape_func);
405
406         counter = atoi(querystr);
407
408         return counter - check->lvalue;
409 }
410
411
412 /*
413  *      Do any per-module initialization that is separate to each
414  *      configured instance of the module.  e.g. set up connections
415  *      to external databases, read configuration files, set up
416  *      dictionary entries, etc.
417  *
418  *      If configuration information is given in the config section
419  *      that must be referenced in later calls, store a handle to it
420  *      in *instance otherwise put a null pointer there.
421  */
422 static int sqlcounter_instantiate(CONF_SECTION *conf, void **instance)
423 {
424         rlm_sqlcounter_t *data;
425         DICT_ATTR *dattr;
426         ATTR_FLAGS flags;
427         time_t now;
428         char buffer[MAX_STRING_LEN];
429
430         /*
431          *      Set up a storage area for instance data
432          */
433         data = rad_malloc(sizeof(*data));
434         if (!data) {
435                 return -1;
436         }
437         memset(data, 0, sizeof(*data));
438
439         /*
440          *      If the configuration parameters can't be parsed, then
441          *      fail.
442          */
443         if (cf_section_parse(conf, data, module_config) < 0) {
444                 free(data);
445                 return -1;
446         }
447
448         /*
449          *      No query, die.
450          */
451         if (data->query == NULL) {
452                 radlog(L_ERR, "rlm_sqlcounter: 'query' must be set.");
453                 return -1;
454         }
455
456         /*
457          *      Safe characters list for sql queries. Everything else is
458          *      replaced rwith their mime-encoded equivalents.
459          */
460         allowed_chars = data->allowed_chars;
461
462         /*
463          *      Discover the attribute number of the key.
464          */
465         if (data->key_name == NULL) {
466                 radlog(L_ERR, "rlm_sqlcounter: 'key' must be set.");
467                 return -1;
468         }
469         sql_escape_func(buffer, sizeof(buffer), data->key_name);
470         if (strcmp(buffer, data->key_name) != 0) {
471                 radlog(L_ERR, "rlm_sqlcounter: The value for option 'key' is too long or contains unsafe characters.");
472                 return -1;
473         }
474         dattr = dict_attrbyname(data->key_name);
475         if (dattr == NULL) {
476                 radlog(L_ERR, "rlm_sqlcounter: No such attribute %s",
477                                 data->key_name);
478                 return -1;
479         }
480         data->key_attr = dattr->attr;
481
482         /*
483          *      Check the "sqlmod-inst" option.
484          */
485         if (data->sqlmod_inst == NULL) {
486                 radlog(L_ERR, "rlm_sqlcounter: 'sqlmod-inst' must be set.");
487                 return -1;
488         }
489         sql_escape_func(buffer, sizeof(buffer), data->sqlmod_inst);
490         if (strcmp(buffer, data->sqlmod_inst) != 0) {
491                 radlog(L_ERR, "rlm_sqlcounter: The value for option 'sqlmod-inst' is too long or contains unsafe characters.");
492                 return -1;
493         }
494
495         /*
496          *  Create a new attribute for the counter.
497          */
498         if (data->counter_name == NULL) {
499                 radlog(L_ERR, "rlm_sqlcounter: 'counter-name' must be set.");
500                 return -1;
501         }
502
503         memset(&flags, 0, sizeof(flags));
504         dict_addattr(data->counter_name, 0, PW_TYPE_INTEGER, -1, flags);
505         dattr = dict_attrbyname(data->counter_name);
506         if (dattr == NULL) {
507                 radlog(L_ERR, "rlm_sqlcounter: Failed to create counter attribute %s",
508                                 data->counter_name);
509                 return -1;
510         }
511         data->dict_attr = dattr->attr;
512         DEBUG2("rlm_sqlcounter: Counter attribute %s is number %d",
513                         data->counter_name, data->dict_attr);
514
515         /*
516          * Create a new attribute for the check item.
517          */
518         if (data->check_name == NULL) {
519                 radlog(L_ERR, "rlm_sqlcounter: 'check-name' must be set.");
520                 return -1;
521         }
522         dict_addattr(data->check_name, 0, PW_TYPE_INTEGER, -1, flags);
523         dattr = dict_attrbyname(data->check_name);
524         if (dattr == NULL) {
525                 radlog(L_ERR, "rlm_sqlcounter: Failed to create check attribute %s",
526                                 data->counter_name);
527                 return -1;
528         }
529         DEBUG2("rlm_sqlcounter: Check attribute %s is number %d",
530                         data->check_name, dattr->attr);
531
532         /*
533          *  Discover the end of the current time period.
534          */
535         if (data->reset == NULL) {
536                 radlog(L_ERR, "rlm_sqlcounter: 'reset' must be set.");
537                 return -1;
538         }
539         now = time(NULL);
540         data->reset_time = 0;
541
542         if (find_next_reset(data,now) == -1)
543                 return -1;
544
545         /*
546          *  Discover the beginning of the current time period.
547          */
548         data->last_reset = 0;
549
550         if (find_prev_reset(data,now) == -1)
551                 return -1;
552
553
554         /*
555          *      Register the counter comparison operation.
556          */
557         paircompare_register(data->dict_attr, 0, sqlcounter_cmp, data);
558
559         *instance = data;
560
561         return 0;
562 }
563
564 /*
565  *      Find the named user in this modules database.  Create the set
566  *      of attribute-value pairs to check and reply with for this user
567  *      from the database. The authentication code only needs to check
568  *      the password, the rest is done here.
569  */
570 static int sqlcounter_authorize(void *instance, REQUEST *request)
571 {
572         rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
573         int ret=RLM_MODULE_NOOP;
574         int counter=0;
575         int res=0;
576         DICT_ATTR *dattr;
577         VALUE_PAIR *key_vp, *check_vp;
578         VALUE_PAIR *reply_item;
579         char msg[128];
580         char querystr[MAX_QUERY_LEN];
581         char responsestr[MAX_QUERY_LEN];
582
583         /* quiet the compiler */
584         instance = instance;
585         request = request;
586
587         /*
588          *      Before doing anything else, see if we have to reset
589          *      the counters.
590          */
591         if (data->reset_time && (data->reset_time <= request->timestamp)) {
592
593                 /*
594                  *      Re-set the next time and prev_time for this counters range
595                  */
596                 data->last_reset = data->reset_time;
597                 find_next_reset(data,request->timestamp);
598         }
599
600
601         /*
602          *      Look for the key.  User-Name is special.  It means
603          *      The REAL username, after stripping.
604          */
605         DEBUG2("rlm_sqlcounter: Entering module authorize code");
606         key_vp = (data->key_attr == PW_USER_NAME) ? request->username : pairfind(request->packet->vps, data->key_attr);
607         if (key_vp == NULL) {
608                 DEBUG2("rlm_sqlcounter: Could not find Key value pair");
609                 return ret;
610         }
611
612         /*
613          *      Look for the check item
614          */
615         if ((dattr = dict_attrbyname(data->check_name)) == NULL) {
616                 return ret;
617         }
618         /* DEBUG2("rlm_sqlcounter: Found Check item attribute %d", dattr->attr); */
619         if ((check_vp= pairfind(request->config_items, dattr->attr)) == NULL) {
620                 DEBUG2("rlm_sqlcounter: Could not find Check item value pair");
621                 return ret;
622         }
623
624         /* first, expand %k, %b and %e in query */
625         sqlcounter_expand(querystr, MAX_QUERY_LEN, data->query, instance);
626
627         /* second, xlat any request attribs in query */
628         radius_xlat(responsestr, MAX_QUERY_LEN, querystr, request, sql_escape_func);
629
630         /* third, wrap query with sql module & expand */
631         snprintf(querystr, sizeof(querystr), "%%{%%S:%s}", responsestr);
632         sqlcounter_expand(responsestr, MAX_QUERY_LEN, querystr, instance);
633
634         /* Finally, xlat resulting SQL query */
635         radius_xlat(querystr, MAX_QUERY_LEN, responsestr, request, sql_escape_func);
636
637         counter = atoi(querystr);
638
639
640         /*
641          * Check if check item > counter
642          */
643         res=check_vp->lvalue - counter;
644         if (res > 0) {
645                 DEBUG2("rlm_sqlcounter: (Check item - counter) is greater than zero");
646                 /*
647                  *      We are assuming that simultaneous-use=1. But
648                  *      even if that does not happen then our user
649                  *      could login at max for 2*max-usage-time Is
650                  *      that acceptable?
651                  */
652
653                 /*
654                  *      User is allowed, but set Session-Timeout.
655                  *      Stolen from main/auth.c
656                  */
657
658                 /*
659                  *      If we are near a reset then add the next
660                  *      limit, so that the user will not need to
661                  *      login again
662                  */
663                 if (data->reset_time && (
664                         res >= (data->reset_time - request->timestamp))) {
665                         res = data->reset_time - request->timestamp;
666                         res += check_vp->lvalue;
667                 }
668
669                 if ((reply_item = pairfind(request->reply->vps, PW_SESSION_TIMEOUT)) != NULL) {
670                         if (reply_item->lvalue > res)
671                                 reply_item->lvalue = res;
672                 } else {
673                         if ((reply_item = paircreate(PW_SESSION_TIMEOUT, PW_TYPE_INTEGER)) == NULL) {
674                                 radlog(L_ERR|L_CONS, "no memory");
675                                 return RLM_MODULE_NOOP;
676                         }
677                         reply_item->lvalue = res;
678                         pairadd(&request->reply->vps, reply_item);
679                 }
680
681                 ret=RLM_MODULE_OK;
682
683                 DEBUG2("rlm_sqlcounter: Authorized user %s, check_item=%d, counter=%d",
684                                 key_vp->strvalue,check_vp->lvalue,counter);
685                 DEBUG2("rlm_sqlcounter: Sent Reply-Item for user %s, Type=Session-Timeout, value=%d",
686                                 key_vp->strvalue,reply_item->lvalue);
687         }
688         else{
689                 char module_fmsg[MAX_STRING_LEN];
690                 VALUE_PAIR *module_fmsg_vp;
691
692                 DEBUG2("rlm_sqlcounter: (Check item - counter) is less than zero");
693
694                 /*
695                  * User is denied access, send back a reply message
696                  */
697                 snprintf(msg, sizeof(msg), "Your maximum %s usage time has been reached", data->reset);
698                 reply_item=pairmake("Reply-Message", msg, T_OP_EQ);
699                 pairadd(&request->reply->vps, reply_item);
700
701                 snprintf(module_fmsg, sizeof(module_fmsg), "rlm_sqlcounter: Maximum %s usage time reached", data->reset);
702                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
703                 pairadd(&request->packet->vps, module_fmsg_vp);
704
705                 ret=RLM_MODULE_REJECT;
706
707                 DEBUG2("rlm_sqlcounter: Rejected user %s, check_item=%d, counter=%d",
708                                 key_vp->strvalue,check_vp->lvalue,counter);
709         }
710
711         return ret;
712 }
713
714 static int sqlcounter_detach(void *instance)
715 {
716         rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
717
718         paircompare_unregister(data->dict_attr, sqlcounter_cmp);
719         free(data->reset);
720         free(data->query);
721         free(data->check_name);
722         free(data->sqlmod_inst);
723         free(data->counter_name);
724         free(data->allowed_chars);
725         allowed_chars = NULL;
726
727         free(instance);
728         return 0;
729 }
730
731 /*
732  *      The module name should be the only globally exported symbol.
733  *      That is, everything else should be 'static'.
734  *
735  *      If the module needs to temporarily modify it's instantiation
736  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
737  *      The server will then take care of ensuring that the module
738  *      is single-threaded.
739  */
740 module_t rlm_sqlcounter = {
741         "SQL Counter",
742         RLM_TYPE_THREAD_SAFE,           /* type */
743         NULL,                           /* initialization */
744         sqlcounter_instantiate,         /* instantiation */
745         {
746                 NULL,                   /* authentication */
747                 sqlcounter_authorize,   /* authorization */
748                 NULL,                   /* preaccounting */
749                 NULL,                   /* accounting */
750                 NULL,                   /* checksimul */
751                 NULL,                   /* pre-proxy */
752                 NULL,                   /* post-proxy */
753                 NULL                    /* post-auth */
754         },
755         sqlcounter_detach,              /* detach */
756         NULL,                           /* destroy */
757 };
758