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.
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.
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
20 * Copyright 2001 The FreeRADIUS server project
21 * Copyright 2001 Alan DeKok <aland@ox.org>
24 /* This module is based directly on the rlm_counter module */
28 #include "libradius.h"
39 #define MAX_QUERY_LEN 1024
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.
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.
54 * To fix this behavior, we need to add some way of storing the Next Reset Time
58 static const char rcsid[] = "$Id$";
61 * Define a structure for our module configuration.
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.
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 */
77 int key_attr; /* attribute number for key field */
78 int dict_attr; /* attribute number for the counter. */
82 * A mapping of configuration file names to internal variables.
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
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 }
101 static char *allowed_chars = NULL;
104 * Translate the SQL queries.
106 static int sql_escape_func(char *out, int outlen, const char *in)
112 * Non-printable characters get replaced with their
113 * mime-encoded equivalents.
116 strchr(allowed_chars, *in) == NULL) {
118 * Only 3 or less bytes available.
124 snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
133 * Only one byte left.
152 static int find_next_reset(rlm_sqlcounter_t *data, time_t timeval)
158 char sCurrentTime[40], sNextTime[40];
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;
164 if (data->reset == NULL)
166 if (isdigit((int) data->reset[0])){
169 len = strlen(data->reset);
172 last = data->reset[len - 1];
173 if (!isalpha((int) last))
175 /* num = atoi(data->reset); */
176 DEBUG("rlm_sqlcounter: num=%d, last=%c",num,last);
178 if (strcmp(data->reset, "hourly") == 0 || last == 'h') {
180 * Round up to the next nearest hour.
183 data->reset_time = mktime(tm);
184 } else if (strcmp(data->reset, "daily") == 0 || last == 'd') {
186 * Round up to the next nearest day.
190 data->reset_time = mktime(tm);
191 } else if (strcmp(data->reset, "weekly") == 0 || last == 'w') {
193 * Round up to the next nearest week.
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') {
202 data->reset_time = mktime(tm);
203 } else if (strcmp(data->reset, "never") == 0) {
204 data->reset_time = 0;
206 radlog(L_ERR, "rlm_sqlcounter: Unknown reset timer \"%s\"",
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);
218 /* I don't believe that this routine handles Daylight Saving Time adjustments
219 properly. Any suggestions?
222 static int find_prev_reset(rlm_sqlcounter_t *data, time_t timeval)
228 char sCurrentTime[40], sPrevTime[40];
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;
234 if (data->reset == NULL)
236 if (isdigit((int) data->reset[0])){
239 len = strlen(data->reset);
242 last = data->reset[len - 1];
243 if (!isalpha((int) last))
245 num = atoi(data->reset);
246 DEBUG("rlm_sqlcounter: num=%d, last=%c",num,last);
248 if (strcmp(data->reset, "hourly") == 0 || last == 'h') {
250 * Round down to the prev nearest hour.
252 tm->tm_hour -= num - 1;
253 data->last_reset = mktime(tm);
254 } else if (strcmp(data->reset, "daily") == 0 || last == 'd') {
256 * Round down to the prev nearest day.
259 tm->tm_mday -= num - 1;
260 data->last_reset = mktime(tm);
261 } else if (strcmp(data->reset, "weekly") == 0 || last == 'w') {
263 * Round down to the prev nearest week.
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') {
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;
276 radlog(L_ERR, "rlm_sqlcounter: Unknown reset timer \"%s\"",
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);
289 * Replace %<whatever> in a string.
298 static int sqlcounter_expand(char *out, int outlen, const char *fmt, void *instance)
300 rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
304 char tmpdt[40]; /* For temporary storing of dates */
308 for (p = fmt; *p ; p++) {
309 /* Calculate freespace in output */
310 freespace = outlen - (q - out);
314 if ((c != '%') && (c != '$') && (c != '\\')) {
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
320 if((c == '}') && openbraces) {
327 if (*++p == '\0') break;
328 if (c == '\\') switch(*p) {
343 } else if (c == '%') switch(*p) {
347 case 'b': /* last_reset */
348 snprintf(tmpdt, sizeof(tmpdt), "%lu", data->last_reset);
349 strNcpy(q, tmpdt, freespace);
352 case 'e': /* reset_time */
353 snprintf(tmpdt, sizeof(tmpdt), "%lu", data->reset_time);
354 strNcpy(q, tmpdt, freespace);
357 case 'k': /* Key Name */
358 strNcpy(q, data->key_name, freespace);
361 case 'S': /* SQL module instance */
362 strNcpy(q, data->sqlmod_inst, freespace);
373 DEBUG2("sqlcounter_expand: '%s'", out);
380 * See if the counter matches.
382 static int sqlcounter_cmp(void *instance, REQUEST *req, VALUE_PAIR *request, VALUE_PAIR *check,
383 VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
385 rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
387 char querystr[MAX_QUERY_LEN];
388 char responsestr[MAX_QUERY_LEN];
390 check_pairs = check_pairs; /* shut the compiler up */
391 reply_pairs = reply_pairs;
393 /* first, expand %k, %b and %e in query */
394 sqlcounter_expand(querystr, MAX_QUERY_LEN, data->query, instance);
396 /* second, xlat any request attribs in query */
397 radius_xlat(responsestr, MAX_QUERY_LEN, querystr, req, sql_escape_func);
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);
403 /* Finally, xlat resulting SQL query */
404 radius_xlat(querystr, MAX_QUERY_LEN, responsestr, req, sql_escape_func);
406 counter = atoi(querystr);
408 return counter - check->lvalue;
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.
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.
422 static int sqlcounter_instantiate(CONF_SECTION *conf, void **instance)
424 rlm_sqlcounter_t *data;
428 char buffer[MAX_STRING_LEN];
431 * Set up a storage area for instance data
433 data = rad_malloc(sizeof(*data));
437 memset(data, 0, sizeof(*data));
440 * If the configuration parameters can't be parsed, then
443 if (cf_section_parse(conf, data, module_config) < 0) {
451 if (data->query == NULL) {
452 radlog(L_ERR, "rlm_sqlcounter: 'query' must be set.");
457 * Safe characters list for sql queries. Everything else is
458 * replaced rwith their mime-encoded equivalents.
460 allowed_chars = data->allowed_chars;
463 * Discover the attribute number of the key.
465 if (data->key_name == NULL) {
466 radlog(L_ERR, "rlm_sqlcounter: 'key' must be set.");
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.");
474 dattr = dict_attrbyname(data->key_name);
476 radlog(L_ERR, "rlm_sqlcounter: No such attribute %s",
480 data->key_attr = dattr->attr;
483 * Check the "sqlmod-inst" option.
485 if (data->sqlmod_inst == NULL) {
486 radlog(L_ERR, "rlm_sqlcounter: 'sqlmod-inst' must be set.");
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.");
496 * Create a new attribute for the counter.
498 if (data->counter_name == NULL) {
499 radlog(L_ERR, "rlm_sqlcounter: 'counter-name' must be set.");
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);
507 radlog(L_ERR, "rlm_sqlcounter: Failed to create counter attribute %s",
511 data->dict_attr = dattr->attr;
512 DEBUG2("rlm_sqlcounter: Counter attribute %s is number %d",
513 data->counter_name, data->dict_attr);
516 * Create a new attribute for the check item.
518 if (data->check_name == NULL) {
519 radlog(L_ERR, "rlm_sqlcounter: 'check-name' must be set.");
522 dict_addattr(data->check_name, 0, PW_TYPE_INTEGER, -1, flags);
523 dattr = dict_attrbyname(data->check_name);
525 radlog(L_ERR, "rlm_sqlcounter: Failed to create check attribute %s",
529 DEBUG2("rlm_sqlcounter: Check attribute %s is number %d",
530 data->check_name, dattr->attr);
533 * Discover the end of the current time period.
535 if (data->reset == NULL) {
536 radlog(L_ERR, "rlm_sqlcounter: 'reset' must be set.");
540 data->reset_time = 0;
542 if (find_next_reset(data,now) == -1)
546 * Discover the beginning of the current time period.
548 data->last_reset = 0;
550 if (find_prev_reset(data,now) == -1)
555 * Register the counter comparison operation.
557 paircompare_register(data->dict_attr, 0, sqlcounter_cmp, data);
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.
570 static int sqlcounter_authorize(void *instance, REQUEST *request)
572 rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
573 int ret=RLM_MODULE_NOOP;
577 VALUE_PAIR *key_vp, *check_vp;
578 VALUE_PAIR *reply_item;
580 char querystr[MAX_QUERY_LEN];
581 char responsestr[MAX_QUERY_LEN];
583 /* quiet the compiler */
588 * Before doing anything else, see if we have to reset
591 if (data->reset_time && (data->reset_time <= request->timestamp)) {
594 * Re-set the next time and prev_time for this counters range
596 data->last_reset = data->reset_time;
597 find_next_reset(data,request->timestamp);
602 * Look for the key. User-Name is special. It means
603 * The REAL username, after stripping.
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");
613 * Look for the check item
615 if ((dattr = dict_attrbyname(data->check_name)) == NULL) {
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");
624 /* first, expand %k, %b and %e in query */
625 sqlcounter_expand(querystr, MAX_QUERY_LEN, data->query, instance);
627 /* second, xlat any request attribs in query */
628 radius_xlat(responsestr, MAX_QUERY_LEN, querystr, request, sql_escape_func);
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);
634 /* Finally, xlat resulting SQL query */
635 radius_xlat(querystr, MAX_QUERY_LEN, responsestr, request, sql_escape_func);
637 counter = atoi(querystr);
641 * Check if check item > counter
643 res=check_vp->lvalue - counter;
645 DEBUG2("rlm_sqlcounter: (Check item - counter) is greater than zero");
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
654 * User is allowed, but set Session-Timeout.
655 * Stolen from main/auth.c
659 * If we are near a reset then add the next
660 * limit, so that the user will not need to
663 if (data->reset_time && (
664 res >= (data->reset_time - request->timestamp))) {
665 res = data->reset_time - request->timestamp;
666 res += check_vp->lvalue;
669 if ((reply_item = pairfind(request->reply->vps, PW_SESSION_TIMEOUT)) != NULL) {
670 if (reply_item->lvalue > res)
671 reply_item->lvalue = res;
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;
677 reply_item->lvalue = res;
678 pairadd(&request->reply->vps, reply_item);
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);
689 char module_fmsg[MAX_STRING_LEN];
690 VALUE_PAIR *module_fmsg_vp;
692 DEBUG2("rlm_sqlcounter: (Check item - counter) is less than zero");
695 * User is denied access, send back a reply message
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);
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);
705 ret=RLM_MODULE_REJECT;
707 DEBUG2("rlm_sqlcounter: Rejected user %s, check_item=%d, counter=%d",
708 key_vp->strvalue,check_vp->lvalue,counter);
714 static int sqlcounter_detach(void *instance)
716 rlm_sqlcounter_t *data = (rlm_sqlcounter_t *) instance;
718 paircompare_unregister(data->dict_attr, sqlcounter_cmp);
721 free(data->check_name);
722 free(data->sqlmod_inst);
723 free(data->counter_name);
724 free(data->allowed_chars);
725 allowed_chars = NULL;
732 * The module name should be the only globally exported symbol.
733 * That is, everything else should be 'static'.
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.
740 module_t rlm_sqlcounter = {
742 RLM_TYPE_THREAD_SAFE, /* type */
743 NULL, /* initialization */
744 sqlcounter_instantiate, /* instantiation */
746 NULL, /* authentication */
747 sqlcounter_authorize, /* authorization */
748 NULL, /* preaccounting */
749 NULL, /* accounting */
750 NULL, /* checksimul */
751 NULL, /* pre-proxy */
752 NULL, /* post-proxy */
755 sqlcounter_detach, /* detach */