2 * This program is is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or (at
5 * your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 * @file rlm_sqlcounter.c
20 * @brief Tracks data usage and other counters using SQL.
22 * @copyright 2001,2006 The FreeRADIUS server project
23 * @copyright 2001 Alan DeKok <aland@ox.org>
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
33 #define MAX_QUERY_LEN 1024
36 * Note: When your counter spans more than 1 period (ie 3 months
37 * or 2 weeks), this module probably does NOT do what you want! It
38 * calculates the range of dates to count across by first calculating
39 * the End of the Current period and then subtracting the number of
40 * periods you specify from that to determine the beginning of the
43 * For example, if you specify a 3 month counter and today is June 15th,
44 * the end of the current period is June 30. Subtracting 3 months from
45 * that gives April 1st. So, the counter will sum radacct entries from
46 * April 1st to June 30. Then, next month, it will sum entries from
47 * May 1st to July 31st.
49 * To fix this behavior, we need to add some way of storing the Next
54 * Define a structure for our module configuration.
56 * These variables do not need to be in a structure, but it's
57 * a lot cleaner to do so, and a pointer to the structure can
58 * be used as the instance handle.
60 typedef struct rlm_sqlcounter_t {
61 char const *counter_name; //!< Daily-Session-Time.
62 char const *limit_name; //!< Max-Daily-Session.
63 char const *reply_name; //!< Session-Timeout.
64 char const *key_name; //!< User-Name.
65 char const *sqlmod_inst; //!< Instance of SQL module to use,
66 //!< usually just 'sql'.
67 char const *query; //!< SQL query to retrieve current
69 char const *reset; //!< Daily, weekly, monthly,
70 //!< never or user defined.
73 DICT_ATTR const *key_attr; //!< Attribute number for key field.
74 DICT_ATTR const *dict_attr; //!< Attribute number for the counter.
75 DICT_ATTR const *reply_attr; //!< Attribute number for the reply.
79 * A mapping of configuration file names to internal variables.
81 * Note that the string is dynamically allocated, so it MUST
82 * be freed. When the configuration file parse re-reads the string,
83 * it free's the old one, and strdup's the new one, placing the pointer
84 * to the strdup'd string into 'config.string'. This gets around
87 static const CONF_PARSER module_config[] = {
88 { "sql-module-instance", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sqlcounter_t, sqlmod_inst), NULL },
89 { "sql_module_instance", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_REQUIRED, rlm_sqlcounter_t, sqlmod_inst), NULL },
91 { "key", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_ATTRIBUTE, rlm_sqlcounter_t, key_name), NULL },
92 { "query", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_XLAT | PW_TYPE_REQUIRED, rlm_sqlcounter_t, query), NULL },
93 { "reset", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_REQUIRED, rlm_sqlcounter_t, reset), NULL },
95 { "counter-name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sqlcounter_t, counter_name), NULL },
96 { "counter_name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_REQUIRED, rlm_sqlcounter_t, counter_name), NULL },
98 { "check-name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sqlcounter_t, limit_name), NULL },
99 { "check_name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_REQUIRED, rlm_sqlcounter_t, limit_name), NULL },
101 { "reply-name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_DEPRECATED, rlm_sqlcounter_t, reply_name), NULL },
102 { "reply_name", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_ATTRIBUTE, rlm_sqlcounter_t, reply_name), "Session-Timeout" },
104 { NULL, -1, 0, NULL, NULL }
107 static int find_next_reset(rlm_sqlcounter_t *inst, time_t timeval)
111 unsigned int num = 1;
114 char sCurrentTime[40], sNextTime[40];
116 tm = localtime_r(&timeval, &s_tm);
117 len = strftime(sCurrentTime, sizeof(sCurrentTime), "%Y-%m-%d %H:%M:%S", tm);
118 if (len == 0) *sCurrentTime = '\0';
119 tm->tm_sec = tm->tm_min = 0;
121 rad_assert(inst->reset != NULL);
123 if (isdigit((int) inst->reset[0])){
124 len = strlen(inst->reset);
127 last = inst->reset[len - 1];
128 if (!isalpha((int) last))
130 num = atoi(inst->reset);
131 DEBUG("rlm_sqlcounter: num=%d, last=%c",num,last);
133 if (strcmp(inst->reset, "hourly") == 0 || last == 'h') {
135 * Round up to the next nearest hour.
138 inst->reset_time = mktime(tm);
139 } else if (strcmp(inst->reset, "daily") == 0 || last == 'd') {
141 * Round up to the next nearest day.
145 inst->reset_time = mktime(tm);
146 } else if (strcmp(inst->reset, "weekly") == 0 || last == 'w') {
148 * Round up to the next nearest week.
151 tm->tm_mday += (7 - tm->tm_wday) +(7*(num-1));
152 inst->reset_time = mktime(tm);
153 } else if (strcmp(inst->reset, "monthly") == 0 || last == 'm') {
157 inst->reset_time = mktime(tm);
158 } else if (strcmp(inst->reset, "never") == 0) {
159 inst->reset_time = 0;
164 len = strftime(sNextTime, sizeof(sNextTime),"%Y-%m-%d %H:%M:%S",tm);
165 if (len == 0) *sNextTime = '\0';
166 DEBUG2("rlm_sqlcounter: Current Time: %" PRId64 " [%s], Next reset %" PRId64 " [%s]",
167 (int64_t) timeval, sCurrentTime, (int64_t) inst->reset_time, sNextTime);
173 /* I don't believe that this routine handles Daylight Saving Time adjustments
174 properly. Any suggestions?
177 static int find_prev_reset(rlm_sqlcounter_t *inst, time_t timeval)
181 unsigned int num = 1;
184 char sCurrentTime[40], sPrevTime[40];
186 tm = localtime_r(&timeval, &s_tm);
187 len = strftime(sCurrentTime, sizeof(sCurrentTime), "%Y-%m-%d %H:%M:%S", tm);
188 if (len == 0) *sCurrentTime = '\0';
189 tm->tm_sec = tm->tm_min = 0;
191 rad_assert(inst->reset != NULL);
193 if (isdigit((int) inst->reset[0])){
194 len = strlen(inst->reset);
197 last = inst->reset[len - 1];
198 if (!isalpha((int) last))
200 num = atoi(inst->reset);
201 DEBUG("rlm_sqlcounter: num=%d, last=%c",num,last);
203 if (strcmp(inst->reset, "hourly") == 0 || last == 'h') {
205 * Round down to the prev nearest hour.
207 tm->tm_hour -= num - 1;
208 inst->last_reset = mktime(tm);
209 } else if (strcmp(inst->reset, "daily") == 0 || last == 'd') {
211 * Round down to the prev nearest day.
214 tm->tm_mday -= num - 1;
215 inst->last_reset = mktime(tm);
216 } else if (strcmp(inst->reset, "weekly") == 0 || last == 'w') {
218 * Round down to the prev nearest week.
221 tm->tm_mday -= (7 - tm->tm_wday) +(7*(num-1));
222 inst->last_reset = mktime(tm);
223 } else if (strcmp(inst->reset, "monthly") == 0 || last == 'm') {
226 tm->tm_mon -= num - 1;
227 inst->last_reset = mktime(tm);
228 } else if (strcmp(inst->reset, "never") == 0) {
229 inst->reset_time = 0;
233 len = strftime(sPrevTime, sizeof(sPrevTime), "%Y-%m-%d %H:%M:%S", tm);
234 if (len == 0) *sPrevTime = '\0';
235 DEBUG2("rlm_sqlcounter: Current Time: %" PRId64 " [%s], Prev reset %" PRId64 " [%s]",
236 (int64_t) timeval, sCurrentTime, (int64_t) inst->last_reset, sPrevTime);
243 * Replace %<whatever> in a string.
252 static size_t sqlcounter_expand(char *out, int outlen, char const *fmt, rlm_sqlcounter_t *inst)
257 char tmpdt[40]; /* For temporary storing of dates */
262 /* Calculate freespace in output */
263 freespace = outlen - (q - out);
264 if (freespace <= 1) {
269 * Non-% get copied as-is.
276 if (!*p) { /* % and then EOS --> % */
281 if (freespace <= 2) return -1;
284 * We need TWO %% in a row before we do our expansions.
285 * If we only get one, just copy the %s as-is.
299 if (freespace <= 3) return -1;
302 case 'b': /* last_reset */
303 snprintf(tmpdt, sizeof(tmpdt), "%" PRId64, (int64_t) inst->last_reset);
304 strlcpy(q, tmpdt, freespace);
308 case 'e': /* reset_time */
309 snprintf(tmpdt, sizeof(tmpdt), "%" PRId64, (int64_t) inst->reset_time);
310 strlcpy(q, tmpdt, freespace);
314 case 'k': /* Key Name */
315 WARN("Please replace '%%k' with '${key}'");
316 strlcpy(q, inst->key_name, freespace);
322 * %%s gets copied over as-is.
333 DEBUG2("sqlcounter_expand: '%s'", out);
340 * See if the counter matches.
342 static int sqlcounter_cmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *req , VALUE_PAIR *check,
343 UNUSED VALUE_PAIR *check_pairs, UNUSED VALUE_PAIR **reply_pairs)
345 rlm_sqlcounter_t *inst = instance;
348 char query[MAX_QUERY_LEN], subst[MAX_QUERY_LEN];
349 char *expanded = NULL;
352 /* First, expand %k, %b and %e in query */
353 if (sqlcounter_expand(subst, sizeof(subst), inst->query, inst) <= 0) {
354 REDEBUG("Insufficient query buffer space");
356 return RLM_MODULE_FAIL;
359 /* Then combine that with the name of the module were using to do the query */
360 len = snprintf(query, sizeof(query), "%%{%s:%s}", inst->sqlmod_inst, subst);
361 if (len >= sizeof(query) - 1) {
362 REDEBUG("Insufficient query buffer space");
364 return RLM_MODULE_FAIL;
367 /* Finally, xlat resulting SQL query */
368 if (radius_axlat(&expanded, request, query, NULL, NULL) < 0) {
369 return RLM_MODULE_FAIL;
372 if (sscanf(expanded, "%" PRIu64, &counter) != 1) {
373 RDEBUG2("No integer found in string \"%s\"", expanded);
375 talloc_free(expanded);
377 if (counter < check->vp_integer64) {
380 if (counter > check->vp_integer64) {
386 static int mod_bootstrap(CONF_SECTION *conf, void *instance)
388 rlm_sqlcounter_t *inst = instance;
393 * Register the counter comparison operation.
395 if (paircompare_register_byname(inst->counter_name, NULL, true, sqlcounter_cmp, inst) < 0) {
396 cf_log_err_cs(conf, "Failed to create counter attribute %s: %s", inst->counter_name, fr_strerror());
401 inst->dict_attr = dict_attrbyname(inst->counter_name);
402 da = dict_attrbyname(inst->counter_name);
404 cf_log_err_cs(conf, "Failed to find counter attribute %s", inst->counter_name);
407 inst->dict_attr = da;
410 * Create a new attribute for the check item.
412 memset(&flags, 0, sizeof(flags));
413 if ((dict_addattr(inst->limit_name, -1, 0, PW_TYPE_INTEGER64, flags) < 0) ||
414 !(da = dict_attrbyname(inst->limit_name))) {
415 cf_log_err_cs(conf, "Failed to create check attribute %s: %s", inst->limit_name, fr_strerror());
423 * Do any per-module initialization that is separate to each
424 * configured instance of the module. e.g. set up connections
425 * to external databases, read configuration files, set up
426 * dictionary entries, etc.
428 * If configuration information is given in the config section
429 * that must be referenced in later calls, store a handle to it
430 * in *instance otherwise put a null pointer there.
432 static int mod_instantiate(CONF_SECTION *conf, void *instance)
434 rlm_sqlcounter_t *inst = instance;
438 rad_assert(inst->query && *inst->query);
440 da = dict_attrbyname(inst->key_name);
442 cf_log_err_cs(conf, "Invalid attribute '%s'", inst->key_name);
447 da = dict_attrbyname(inst->reply_name);
449 cf_log_err_cs(conf, "Invalid attribute '%s'", inst->reply_name);
452 inst->reply_attr = da;
455 inst->reset_time = 0;
457 if (find_next_reset(inst, now) == -1) {
458 cf_log_err_cs(conf, "Invalid reset '%s'", inst->reset);
463 * Discover the beginning of the current time period.
465 inst->last_reset = 0;
467 if (find_prev_reset(inst, now) < 0) {
468 cf_log_err_cs(conf, "Invalid reset '%s'", inst->reset);
476 * Find the named user in this modules database. Create the set
477 * of attribute-value pairs to check and reply with for this user
478 * from the database. The authentication code only needs to check
479 * the password, the rest is done here.
481 static rlm_rcode_t CC_HINT(nonnull) mod_authorize(void *instance, REQUEST *request)
483 rlm_sqlcounter_t *inst = instance;
484 int rcode = RLM_MODULE_NOOP;
485 uint64_t counter, res;
487 VALUE_PAIR *key_vp, *limit;
488 VALUE_PAIR *reply_item;
491 char query[MAX_QUERY_LEN], subst[MAX_QUERY_LEN];
492 char *expanded = NULL;
497 * Before doing anything else, see if we have to reset
500 if (inst->reset_time && (inst->reset_time <= request->timestamp)) {
502 * Re-set the next time and prev_time for this counters range
504 inst->last_reset = inst->reset_time;
505 find_next_reset(inst,request->timestamp);
509 * Look for the key. User-Name is special. It means
510 * The REAL username, after stripping.
512 if ((inst->key_attr->vendor == 0) && (inst->key_attr->attr == PW_USER_NAME)) {
513 key_vp = request->username;
515 key_vp = pair_find_by_da(request->packet->vps, inst->key_attr, TAG_ANY);
518 RWDEBUG2("Couldn't find key attribute, request:%s, doing nothing...", inst->key_attr->name);
523 * Look for the check item
525 if ((da = dict_attrbyname(inst->limit_name)) == NULL) {
529 limit = pair_find_by_da(request->config, da, TAG_ANY);
531 /* Yes this really is 'check' as distinct from control */
532 RWDEBUG2("Couldn't find check attribute, control:%s, doing nothing...", inst->limit_name);
536 /* First, expand %k, %b and %e in query */
537 if (sqlcounter_expand(subst, sizeof(subst), inst->query, inst) <= 0) {
538 REDEBUG("Insufficient query buffer space");
540 return RLM_MODULE_FAIL;
543 /* Then combine that with the name of the module were using to do the query */
544 len = snprintf(query, sizeof(query), "%%{%s:%s}", inst->sqlmod_inst, subst);
545 if (len >= (sizeof(query) - 1)) {
546 REDEBUG("Insufficient query buffer space");
548 return RLM_MODULE_FAIL;
551 /* Finally, xlat resulting SQL query */
552 if (radius_axlat(&expanded, request, query, NULL, NULL) < 0) {
553 return RLM_MODULE_FAIL;
555 talloc_free(expanded);
557 if (sscanf(expanded, "%" PRIu64, &counter) != 1) {
558 RDEBUG2("No integer found in result string \"%s\". May be first session, setting counter to 0",
564 * Check if check item > counter
566 if (limit->vp_integer64 <= counter) {
567 /* User is denied access, send back a reply message */
568 snprintf(msg, sizeof(msg), "Your maximum %s usage time has been reached", inst->reset);
569 pairmake_reply("Reply-Message", msg, T_OP_EQ);
571 REDEBUG2("Maximum %s usage time reached", inst->reset);
572 REDEBUG2("Rejecting user, &control:%s value (%" PRIu64 ") is less than counter value (%" PRIu64 ")",
573 inst->limit_name, limit->vp_integer64, counter);
575 return RLM_MODULE_REJECT;
578 res = limit->vp_integer64 - counter;
579 RDEBUG2("Allowing user, &control:%s value (%" PRIu64 ") is greater than counter value (%" PRIu64 ")",
580 inst->limit_name, limit->vp_integer64, counter);
582 * We are assuming that simultaneous-use=1. But
583 * even if that does not happen then our user
584 * could login at max for 2*max-usage-time Is
589 * If we are near a reset then add the next
590 * limit, so that the user will not need to login
591 * again. Do this only for Session-Timeout.
593 if (((inst->reply_attr->vendor == 0) && (inst->reply_attr->attr == PW_SESSION_TIMEOUT)) &&
594 inst->reset_time && (res >= (uint64_t)(inst->reset_time - request->timestamp))) {
595 uint64_t to_reset = inst->reset_time - request->timestamp;
597 RDEBUG2("Time remaining (%" PRIu64 "s) is greater than time to reset (%" PRIu64 "s). "
598 "Adding %" PRIu64 "s to reply value", to_reset, res, to_reset);
599 res = to_reset + limit->vp_integer;
603 * Limit the reply attribute to the minimum of the existing value, or this new one.
605 reply_item = pair_find_by_da(request->reply->vps, inst->reply_attr, TAG_ANY);
607 if (reply_item->vp_integer64 <= res) {
608 RDEBUG2("Leaving existing &reply:%s value of %" PRIu64, inst->reply_attr->name,
609 reply_item->vp_integer64);
611 return RLM_MODULE_OK;
614 reply_item = radius_paircreate(request->reply, &request->reply->vps, inst->reply_attr->attr,
615 inst->reply_attr->vendor);
617 reply_item->vp_integer64 = res;
619 RDEBUG2("Setting &reply:%s value to %" PRIu64, inst->reply_name, reply_item->vp_integer64);
621 return RLM_MODULE_OK;
625 * The module name should be the only globally exported symbol.
626 * That is, everything else should be 'static'.
628 * If the module needs to temporarily modify it's instantiation
629 * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
630 * The server will then take care of ensuring that the module
631 * is single-threaded.
633 extern module_t rlm_sqlcounter;
634 module_t rlm_sqlcounter = {
635 .magic = RLM_MODULE_INIT,
636 .name = "sqlcounter",
637 .type = RLM_TYPE_THREAD_SAFE,
638 .inst_size = sizeof(rlm_sqlcounter_t),
639 .config = module_config,
640 .bootstrap = mod_bootstrap,
641 .instantiate = mod_instantiate,
643 [MOD_AUTHORIZE] = mod_authorize