Added query_timeout parameter. For now, it does nothing.
[freeradius.git] / src / modules / rlm_sql / rlm_sql.c
1 /*
2  * rlm_sql.c            SQL Module
3  *              Main SQL module file. Most ICRADIUS code is located in sql.c
4  *
5  * Version:     $Id$
6  *
7  *   This program is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU General Public License as published by
9  *   the Free Software Foundation; either version 2 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This program is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with this program; if not, write to the Free Software
19  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  * Copyright 2000,2006  The FreeRADIUS server project
22  * Copyright 2000  Mike Machado <mike@innercite.com>
23  * Copyright 2000  Alan DeKok <aland@ox.org>
24  */
25
26 #include <freeradius-devel/ident.h>
27 RCSID("$Id$")
28
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/modules.h>
31 #include <freeradius-devel/rad_assert.h>
32 #include <ltdl.h>
33
34 #include <sys/stat.h>
35
36 #include "rlm_sql.h"
37
38 static char *allowed_chars = NULL;
39
40 static const CONF_PARSER module_config[] = {
41         {"driver",PW_TYPE_STRING_PTR,
42          offsetof(SQL_CONFIG,sql_driver), NULL, "mysql"},
43         {"server",PW_TYPE_STRING_PTR,
44          offsetof(SQL_CONFIG,sql_server), NULL, "localhost"},
45         {"port",PW_TYPE_STRING_PTR,
46          offsetof(SQL_CONFIG,sql_port), NULL, ""},
47         {"login", PW_TYPE_STRING_PTR,
48          offsetof(SQL_CONFIG,sql_login), NULL, ""},
49         {"password", PW_TYPE_STRING_PTR,
50          offsetof(SQL_CONFIG,sql_password), NULL, ""},
51         {"radius_db", PW_TYPE_STRING_PTR,
52          offsetof(SQL_CONFIG,sql_db), NULL, "radius"},
53         {"read_groups", PW_TYPE_BOOLEAN,
54          offsetof(SQL_CONFIG,read_groups), NULL, "yes"},
55         {"sqltrace", PW_TYPE_BOOLEAN,
56          offsetof(SQL_CONFIG,sqltrace), NULL, "no"},
57         {"sqltracefile", PW_TYPE_STRING_PTR,
58          offsetof(SQL_CONFIG,tracefile), NULL, SQLTRACEFILE},
59         {"readclients", PW_TYPE_BOOLEAN,
60          offsetof(SQL_CONFIG,do_clients), NULL, "no"},
61         {"deletestalesessions", PW_TYPE_BOOLEAN,
62          offsetof(SQL_CONFIG,deletestalesessions), NULL, "yes"},
63         {"num_sql_socks", PW_TYPE_INTEGER,
64          offsetof(SQL_CONFIG,num_sql_socks), NULL, "5"},
65         {"lifetime", PW_TYPE_INTEGER,
66          offsetof(SQL_CONFIG,lifetime), NULL, "0"},
67         {"max_queries", PW_TYPE_INTEGER,
68          offsetof(SQL_CONFIG,max_queries), NULL, "0"},
69         {"sql_user_name", PW_TYPE_STRING_PTR,
70          offsetof(SQL_CONFIG,query_user), NULL, ""},
71         {"default_user_profile", PW_TYPE_STRING_PTR,
72          offsetof(SQL_CONFIG,default_profile), NULL, ""},
73         {"nas_query", PW_TYPE_STRING_PTR,
74          offsetof(SQL_CONFIG,nas_query), NULL, "SELECT id,nasname,shortname,type,secret FROM nas"},
75         {"authorize_check_query", PW_TYPE_STRING_PTR,
76          offsetof(SQL_CONFIG,authorize_check_query), NULL, ""},
77         {"authorize_reply_query", PW_TYPE_STRING_PTR,
78          offsetof(SQL_CONFIG,authorize_reply_query), NULL, NULL},
79         {"authorize_group_check_query", PW_TYPE_STRING_PTR,
80          offsetof(SQL_CONFIG,authorize_group_check_query), NULL, ""},
81         {"authorize_group_reply_query", PW_TYPE_STRING_PTR,
82          offsetof(SQL_CONFIG,authorize_group_reply_query), NULL, ""},
83         {"accounting_onoff_query", PW_TYPE_STRING_PTR,
84          offsetof(SQL_CONFIG,accounting_onoff_query), NULL, ""},
85         {"accounting_update_query", PW_TYPE_STRING_PTR,
86          offsetof(SQL_CONFIG,accounting_update_query), NULL, ""},
87         {"accounting_update_query_alt", PW_TYPE_STRING_PTR,
88          offsetof(SQL_CONFIG,accounting_update_query_alt), NULL, ""},
89         {"accounting_start_query", PW_TYPE_STRING_PTR,
90          offsetof(SQL_CONFIG,accounting_start_query), NULL, ""},
91         {"accounting_start_query_alt", PW_TYPE_STRING_PTR,
92          offsetof(SQL_CONFIG,accounting_start_query_alt), NULL, ""},
93         {"accounting_stop_query", PW_TYPE_STRING_PTR,
94          offsetof(SQL_CONFIG,accounting_stop_query), NULL, ""},
95         {"accounting_stop_query_alt", PW_TYPE_STRING_PTR,
96          offsetof(SQL_CONFIG,accounting_stop_query_alt), NULL, ""},
97         {"group_membership_query", PW_TYPE_STRING_PTR,
98          offsetof(SQL_CONFIG,groupmemb_query), NULL, NULL},
99         {"connect_failure_retry_delay", PW_TYPE_INTEGER,
100          offsetof(SQL_CONFIG,connect_failure_retry_delay), NULL, "60"},
101         {"simul_count_query", PW_TYPE_STRING_PTR,
102          offsetof(SQL_CONFIG,simul_count_query), NULL, ""},
103         {"simul_verify_query", PW_TYPE_STRING_PTR,
104          offsetof(SQL_CONFIG,simul_verify_query), NULL, ""},
105         {"postauth_query", PW_TYPE_STRING_PTR,
106          offsetof(SQL_CONFIG,postauth_query), NULL, ""},
107         {"safe-characters", PW_TYPE_STRING_PTR,
108          offsetof(SQL_CONFIG,allowed_chars), NULL,
109         "@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_: /"},
110
111         /*
112          *      This only works for a few drivers.
113          */
114         {"query_timeout", PW_TYPE_INTEGER,
115          offsetof(SQL_CONFIG,query_timeout), NULL, NULL},
116          
117         {NULL, -1, 0, NULL, NULL}
118 };
119
120 /*
121  *      Fall-Through checking function from rlm_files.c
122  */
123 static int fallthrough(VALUE_PAIR *vp)
124 {
125         VALUE_PAIR *tmp;
126         tmp = pairfind(vp, PW_FALL_THROUGH);
127
128         return tmp ? tmp->vp_integer : 0;
129 }
130
131
132
133 /*
134  *      Yucky prototype.
135  */
136 static int generate_sql_clients(SQL_INST *inst);
137 static size_t sql_escape_func(char *out, size_t outlen, const char *in);
138
139 /*
140  *      sql xlat function. Right now only SELECTs are supported. Only
141  *      the first element of the SELECT result will be used.
142  *
143  *      For other statements (insert, update, delete, etc.), the
144  *      number of affected rows will be returned.
145  */
146 static int sql_xlat(void *instance, REQUEST *request,
147                     char *fmt, char *out, size_t freespace,
148                     UNUSED RADIUS_ESCAPE_STRING func)
149 {
150         SQLSOCK *sqlsocket;
151         SQL_ROW row;
152         SQL_INST *inst = instance;
153         char querystr[MAX_QUERY_LEN];
154         char sqlusername[MAX_STRING_LEN];
155         size_t ret = 0;
156
157         RDEBUG("sql_xlat");
158
159         /*
160          * Add SQL-User-Name attribute just in case it is needed
161          *  We could search the string fmt for SQL-User-Name to see if this is
162          *  needed or not
163          */
164         sql_set_user(inst, request, sqlusername, NULL);
165         /*
166          * Do an xlat on the provided string (nice recursive operation).
167          */
168         if (!radius_xlat(querystr, sizeof(querystr), fmt, request, sql_escape_func)) {
169                 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
170                        inst->config->xlat_name);
171                 return 0;
172         }
173
174         query_log(request, inst,querystr);
175         sqlsocket = sql_get_socket(inst);
176         if (sqlsocket == NULL)
177                 return 0;
178
179         /*
180          *      If the query starts with any of the following prefixes,
181          *      then return the number of rows affected
182          */
183         if ((strncasecmp(querystr, "insert", 6) == 0) ||
184             (strncasecmp(querystr, "update", 6) == 0) ||
185             (strncasecmp(querystr, "delete", 6) == 0)) {
186                 int numaffected;
187                 char buffer[21]; /* 64bit max is 20 decimal chars + null byte */
188
189                 if (rlm_sql_query(sqlsocket,inst,querystr)) {
190                         radlog(L_ERR, "rlm_sql (%s): database query error, %s: %s",
191                                 inst->config->xlat_name, querystr,
192                                 (inst->module->sql_error)(sqlsocket,
193                                                           inst->config));
194                         sql_release_socket(inst,sqlsocket);
195                         return 0;
196                 }
197                
198                 numaffected = (inst->module->sql_affected_rows)(sqlsocket,
199                                                                 inst->config);
200                 if (numaffected < 1) {
201                         RDEBUG("rlm_sql (%s): SQL query affected no rows",
202                                 inst->config->xlat_name);
203                 }
204
205                 /*
206                  *      Don't chop the returned number if freespace is
207                  *      too small.  This hack is necessary because
208                  *      some implementations of snprintf return the
209                  *      size of the written data, and others return
210                  *      the size of the data they *would* have written
211                  *      if the output buffer was large enough.
212                  */
213                 snprintf(buffer, sizeof(buffer), "%d", numaffected);
214                 ret = strlen(buffer);
215                 if (ret >= freespace){
216                         RDEBUG("rlm_sql (%s): Can't write result, insufficient string space",
217                                inst->config->xlat_name);
218                         (inst->module->sql_finish_query)(sqlsocket,
219                                                          inst->config);
220                         sql_release_socket(inst,sqlsocket);
221                         return 0;
222                 }
223                 
224                 memcpy(out, buffer, ret + 1); /* we did bounds checking above */
225
226                 (inst->module->sql_finish_query)(sqlsocket, inst->config);
227                 sql_release_socket(inst,sqlsocket);
228                 return ret;
229         } /* else it's a SELECT statement */
230
231         if (rlm_sql_select_query(sqlsocket,inst,querystr)){
232                 radlog(L_ERR, "rlm_sql (%s): database query error, %s: %s",
233                        inst->config->xlat_name,querystr,
234                        (inst->module->sql_error)(sqlsocket, inst->config));
235                 sql_release_socket(inst,sqlsocket);
236                 return 0;
237         }
238
239         ret = rlm_sql_fetch_row(sqlsocket, inst);
240
241         if (ret) {
242                 RDEBUG("SQL query did not succeed");
243                 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
244                 sql_release_socket(inst,sqlsocket);
245                 return 0;
246         }
247
248         row = sqlsocket->row;
249         if (row == NULL) {
250                 RDEBUG("SQL query did not return any results");
251                 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
252                 sql_release_socket(inst,sqlsocket);
253                 return 0;
254         }
255
256         if (row[0] == NULL){
257                 RDEBUG("row[0] returned NULL");
258                 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
259                 sql_release_socket(inst,sqlsocket);
260                 return 0;
261         }
262         ret = strlen(row[0]);
263         if (ret >= freespace){
264                 RDEBUG("Insufficient string space");
265                 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
266                 sql_release_socket(inst,sqlsocket);
267                 return 0;
268         }
269
270         strlcpy(out,row[0],freespace);
271
272         RDEBUG("sql_xlat finished");
273
274         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
275         sql_release_socket(inst,sqlsocket);
276         return ret;
277 }
278
279 static int generate_sql_clients(SQL_INST *inst)
280 {
281         SQLSOCK *sqlsocket;
282         SQL_ROW row;
283         char querystr[MAX_QUERY_LEN];
284         RADCLIENT *c;
285         char *prefix_ptr = NULL;
286         unsigned int i = 0;
287         int numf = 0;
288
289         DEBUG("rlm_sql (%s): Processing generate_sql_clients",
290               inst->config->xlat_name);
291
292         /* NAS query isn't xlat'ed */
293         strlcpy(querystr, inst->config->nas_query, sizeof(querystr));
294         DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
295               inst->config->xlat_name, querystr);
296
297         sqlsocket = sql_get_socket(inst);
298         if (sqlsocket == NULL)
299                 return -1;
300         if (rlm_sql_select_query(sqlsocket,inst,querystr)){
301                 radlog(L_ERR, "rlm_sql (%s): database query error, %s: %s",
302                        inst->config->xlat_name,querystr,
303                        (inst->module->sql_error)(sqlsocket, inst->config));
304                 sql_release_socket(inst,sqlsocket);
305                 return -1;
306         }
307
308         while(rlm_sql_fetch_row(sqlsocket, inst) == 0) {
309                 i++;
310                 row = sqlsocket->row;
311                 if (row == NULL)
312                         break;
313         /*
314          *  The return data for each row MUST be in the following order:
315          *
316          *  0. Row ID (currently unused)
317          *  1. Name (or IP address)
318          *  2. Shortname
319          *  3. Type
320          *  4. Secret
321          *  5. Virtual Server (optional)
322          */
323                 if (!row[0]){
324                         radlog(L_ERR, "rlm_sql (%s): No row id found on pass %d",inst->config->xlat_name,i);
325                         continue;
326                 }
327                 if (!row[1]){
328                         radlog(L_ERR, "rlm_sql (%s): No nasname found for row %s",inst->config->xlat_name,row[0]);
329                         continue;
330                 }
331                 if (!row[2]){
332                         radlog(L_ERR, "rlm_sql (%s): No short name found for row %s",inst->config->xlat_name,row[0]);
333                         continue;
334                 }
335                 if (!row[4]){
336                         radlog(L_ERR, "rlm_sql (%s): No secret found for row %s",inst->config->xlat_name,row[0]);
337                         continue;
338                 }
339
340                 DEBUG("rlm_sql (%s): Read entry nasname=%s,shortname=%s,secret=%s",inst->config->xlat_name,
341                         row[1],row[2],row[4]);
342
343                 c = rad_malloc(sizeof(*c));
344                 memset(c, 0, sizeof(*c));
345
346 #ifdef WITH_DYNAMIC_CLIENTS
347                 c->dynamic = 1;
348 #endif
349
350                 /*
351                  *      Look for prefixes
352                  */
353                 c->prefix = -1;
354                 prefix_ptr = strchr(row[1], '/');
355                 if (prefix_ptr) {
356                         c->prefix = atoi(prefix_ptr + 1);
357                         if ((c->prefix < 0) || (c->prefix > 128)) {
358                                 radlog(L_ERR, "rlm_sql (%s): Invalid Prefix value '%s' for IP.",
359                                        inst->config->xlat_name, prefix_ptr + 1);
360                                 free(c);
361                                 continue;
362                         }
363                         /* Replace '/' with '\0' */
364                         *prefix_ptr = '\0';
365                 }
366
367                 /*
368                  *      Always get the numeric representation of IP
369                  */
370                 if (ip_hton(row[1], AF_UNSPEC, &c->ipaddr) < 0) {
371                         radlog(L_CONS|L_ERR, "rlm_sql (%s): Failed to look up hostname %s: %s",
372                                inst->config->xlat_name,
373                                row[1], fr_strerror());
374                         free(c);
375                         continue;
376                 } else {
377                         char buffer[256];
378                         ip_ntoh(&c->ipaddr, buffer, sizeof(buffer));
379                         c->longname = strdup(buffer);
380                 }
381
382                 if (c->prefix < 0) switch (c->ipaddr.af) {
383                 case AF_INET:
384                         c->prefix = 32;
385                         break;
386                 case AF_INET6:
387                         c->prefix = 128;
388                         break;
389                 default:
390                         break;
391                 }
392
393                 /*
394                  *      Other values (secret, shortname, nastype, virtual_server)
395                  */
396                 c->secret = strdup(row[4]);
397                 c->shortname = strdup(row[2]);
398                 if(row[3] != NULL)
399                         c->nastype = strdup(row[3]);
400
401                 numf = (inst->module->sql_num_fields)(sqlsocket, inst->config);
402                 if ((numf > 5) && (row[5] != NULL)) c->server = strdup(row[5]);
403
404                 DEBUG("rlm_sql (%s): Adding client %s (%s, server=%s) to clients list",
405                       inst->config->xlat_name,
406                       c->longname,c->shortname, c->server ? c->server : "<none>");
407                 if (!client_add(NULL, c)) {
408                         DEBUG("rlm_sql (%s): Failed to add client %s (%s) to clients list.  Maybe there's a duplicate?",
409                               inst->config->xlat_name,
410                               c->longname,c->shortname);
411                         client_free(c);
412                         return -1;
413                 }
414         }
415         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
416         sql_release_socket(inst, sqlsocket);
417
418         return 0;
419 }
420
421
422 /*
423  *      Translate the SQL queries.
424  */
425 static size_t sql_escape_func(char *out, size_t outlen, const char *in)
426 {
427         size_t len = 0;
428
429         while (in[0]) {
430                 /*
431                  *      Non-printable characters get replaced with their
432                  *      mime-encoded equivalents.
433                  */
434                 if ((in[0] < 32) ||
435                     strchr(allowed_chars, *in) == NULL) {
436                         /*
437                          *      Only 3 or less bytes available.
438                          */
439                         if (outlen <= 3) {
440                                 break;
441                         }
442
443                         snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
444                         in++;
445                         out += 3;
446                         outlen -= 3;
447                         len += 3;
448                         continue;
449                 }
450
451                 /*
452                  *      Only one byte left.
453                  */
454                 if (outlen <= 1) {
455                         break;
456                 }
457
458                 /*
459                  *      Allowed character.
460                  */
461                 *out = *in;
462                 out++;
463                 in++;
464                 outlen--;
465                 len++;
466         }
467         *out = '\0';
468         return len;
469 }
470
471 /*
472  *      Set the SQL user name.
473  *
474  *      We don't call the escape function here. The resulting string
475  *      will be escaped later in the queries xlat so we don't need to
476  *      escape it twice. (it will make things wrong if we have an
477  *      escape candidate character in the username)
478  */
479 int sql_set_user(SQL_INST *inst, REQUEST *request, char *sqlusername, const char *username)
480 {
481         VALUE_PAIR *vp=NULL;
482         char tmpuser[MAX_STRING_LEN];
483
484         tmpuser[0] = '\0';
485         sqlusername[0]= '\0';
486
487         /* Remove any user attr we added previously */
488         pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
489
490         if (username != NULL) {
491                 strlcpy(tmpuser, username, sizeof(tmpuser));
492         } else if (strlen(inst->config->query_user)) {
493                 radius_xlat(tmpuser, sizeof(tmpuser), inst->config->query_user, request, NULL);
494         } else {
495                 return 0;
496         }
497
498         strlcpy(sqlusername, tmpuser, MAX_STRING_LEN);
499         RDEBUG2("sql_set_user escaped user --> '%s'", sqlusername);
500         vp = radius_pairmake(request, &request->packet->vps,
501                              "SQL-User-Name", NULL, 0);
502         if (!vp) {
503                 radlog(L_ERR, "%s", fr_strerror());
504                 return -1;
505         }
506
507         strlcpy(vp->vp_strvalue, tmpuser, sizeof(vp->vp_strvalue));
508         vp->length = strlen(vp->vp_strvalue);
509
510         return 0;
511
512 }
513
514
515 static void sql_grouplist_free (SQL_GROUPLIST **group_list)
516 {
517         SQL_GROUPLIST *last;
518
519         while(*group_list) {
520                 last = *group_list;
521                 *group_list = (*group_list)->next;
522                 free(last);
523         }
524 }
525
526
527 static int sql_get_grouplist (SQL_INST *inst, SQLSOCK *sqlsocket, REQUEST *request, SQL_GROUPLIST **group_list)
528 {
529         char    querystr[MAX_QUERY_LEN];
530         int     num_groups = 0;
531         SQL_ROW row;
532         SQL_GROUPLIST   *group_list_tmp;
533
534         /* NOTE: sql_set_user should have been run before calling this function */
535
536         group_list_tmp = *group_list = NULL;
537
538         if (!inst->config->groupmemb_query ||
539             (inst->config->groupmemb_query[0] == 0))
540                 return 0;
541
542         if (!radius_xlat(querystr, sizeof(querystr), inst->config->groupmemb_query, request, sql_escape_func)) {
543                 radlog_request(L_ERR, 0, request, "xlat \"%s\" failed.",
544                                inst->config->groupmemb_query);
545                 return -1;
546         }
547
548         if (rlm_sql_select_query(sqlsocket, inst, querystr) < 0) {
549                 radlog_request(L_ERR, 0, request,
550                                "database query error, %s: %s",
551                                querystr,
552                        (inst->module->sql_error)(sqlsocket,inst->config));
553                 return -1;
554         }
555         while (rlm_sql_fetch_row(sqlsocket, inst) == 0) {
556                 row = sqlsocket->row;
557                 if (row == NULL)
558                         break;
559                 if (row[0] == NULL){
560                         RDEBUG("row[0] returned NULL");
561                         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
562                         sql_grouplist_free(group_list);
563                         return -1;
564                 }
565                 if (*group_list == NULL) {
566                         *group_list = rad_malloc(sizeof(SQL_GROUPLIST));
567                         group_list_tmp = *group_list;
568                 } else {
569                         rad_assert(group_list_tmp != NULL);
570                         group_list_tmp->next = rad_malloc(sizeof(SQL_GROUPLIST));
571                         group_list_tmp = group_list_tmp->next;
572                 }
573                 group_list_tmp->next = NULL;
574                 strlcpy(group_list_tmp->groupname, row[0], MAX_STRING_LEN);
575         }
576
577         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
578
579         return num_groups;
580 }
581
582
583 /*
584  * sql groupcmp function. That way we can do group comparisons (in the users file for example)
585  * with the group memberships reciding in sql
586  * The group membership query should only return one element which is the username. The returned
587  * username will then be checked with the passed check string.
588  */
589
590 static int sql_groupcmp(void *instance, REQUEST *request, VALUE_PAIR *request_vp, VALUE_PAIR *check,
591                         VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
592 {
593         SQLSOCK *sqlsocket;
594         SQL_INST *inst = instance;
595         char sqlusername[MAX_STRING_LEN];
596         SQL_GROUPLIST *group_list, *group_list_tmp;
597
598         check_pairs = check_pairs;
599         reply_pairs = reply_pairs;
600         request_vp = request_vp;
601
602         RDEBUG("sql_groupcmp");
603         if (!check || !check->vp_strvalue || !check->length){
604                 RDEBUG("sql_groupcmp: Illegal group name");
605                 return 1;
606         }
607         if (!request){
608                 RDEBUG("sql_groupcmp: NULL request");
609                 return 1;
610         }
611         /*
612          * Set, escape, and check the user attr here
613          */
614         if (sql_set_user(inst, request, sqlusername, NULL) < 0)
615                 return 1;
616
617         /*
618          *      Get a socket for this lookup
619          */
620         sqlsocket = sql_get_socket(inst);
621         if (sqlsocket == NULL) {
622                 /* Remove the username we (maybe) added above */
623                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
624                 return 1;
625         }
626
627         /*
628          *      Get the list of groups this user is a member of
629          */
630         if (sql_get_grouplist(inst, sqlsocket, request, &group_list) < 0) {
631                 radlog_request(L_ERR, 0, request,
632                                "Error getting group membership");
633                 /* Remove the username we (maybe) added above */
634                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
635                 sql_release_socket(inst, sqlsocket);
636                 return 1;
637         }
638
639         for (group_list_tmp = group_list; group_list_tmp != NULL; group_list_tmp = group_list_tmp->next) {
640                 if (strcmp(group_list_tmp->groupname, check->vp_strvalue) == 0){
641                         RDEBUG("sql_groupcmp finished: User is a member of group %s",
642                                check->vp_strvalue);
643                         /* Free the grouplist */
644                         sql_grouplist_free(&group_list);
645                         /* Remove the username we (maybe) added above */
646                         pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
647                         sql_release_socket(inst, sqlsocket);
648                         return 0;
649                 }
650         }
651
652         /* Free the grouplist */
653         sql_grouplist_free(&group_list);
654         /* Remove the username we (maybe) added above */
655         pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
656         sql_release_socket(inst,sqlsocket);
657
658         RDEBUG("sql_groupcmp finished: User is NOT a member of group %s",
659                check->vp_strvalue);
660
661         return 1;
662 }
663
664
665
666 static int rlm_sql_process_groups(SQL_INST *inst, REQUEST *request, SQLSOCK *sqlsocket, int *dofallthrough)
667 {
668         VALUE_PAIR *check_tmp = NULL;
669         VALUE_PAIR *reply_tmp = NULL;
670         SQL_GROUPLIST *group_list, *group_list_tmp;
671         VALUE_PAIR *sql_group = NULL;
672         char    querystr[MAX_QUERY_LEN];
673         int found = 0;
674         int rows;
675
676         /*
677          *      Get the list of groups this user is a member of
678          */
679         if (sql_get_grouplist(inst, sqlsocket, request, &group_list) < 0) {
680                 radlog_request(L_ERR, 0, request, "Error retrieving group list");
681                 return -1;
682         }
683
684         for (group_list_tmp = group_list; group_list_tmp != NULL && *dofallthrough != 0; group_list_tmp = group_list_tmp->next) {
685                 /*
686                  *      Add the Sql-Group attribute to the request list so we know
687                  *      which group we're retrieving attributes for
688                  */
689                 sql_group = pairmake("Sql-Group", group_list_tmp->groupname, T_OP_EQ);
690                 if (!sql_group) {
691                         radlog_request(L_ERR, 0, request,
692                                        "Error creating Sql-Group attribute");
693                         return -1;
694                 }
695                 pairadd(&request->packet->vps, sql_group);
696                 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_group_check_query, request, sql_escape_func)) {
697                         radlog_request(L_ERR, 0, request,
698                                        "Error generating query; rejecting user");
699                         /* Remove the grouup we added above */
700                         pairdelete(&request->packet->vps, PW_SQL_GROUP);
701                         return -1;
702                 }
703                 rows = sql_getvpdata(inst, sqlsocket, &check_tmp, querystr);
704                 if (rows < 0) {
705                         radlog_request(L_ERR, 0, request, "Error retrieving check pairs for group %s",
706                                group_list_tmp->groupname);
707                         /* Remove the grouup we added above */
708                         pairdelete(&request->packet->vps, PW_SQL_GROUP);
709                         pairfree(&check_tmp);
710                         return -1;
711                 } else if (rows > 0) {
712                         /*
713                          *      Only do this if *some* check pairs were returned
714                          */
715                         if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) == 0) {
716                                 found = 1;
717                                 RDEBUG2("User found in group %s",
718                                         group_list_tmp->groupname);
719                                 /*
720                                  *      Now get the reply pairs since the paircompare matched
721                                  */
722                                 if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_group_reply_query, request, sql_escape_func)) {
723                                         radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
724                                         /* Remove the grouup we added above */
725                                         pairdelete(&request->packet->vps, PW_SQL_GROUP);
726                                         pairfree(&check_tmp);
727                                         return -1;
728                                 }
729                                 if (sql_getvpdata(inst, sqlsocket, &reply_tmp, querystr) < 0) {
730                                         radlog_request(L_ERR, 0, request, "Error retrieving reply pairs for group %s",
731                                                group_list_tmp->groupname);
732                                         /* Remove the grouup we added above */
733                                         pairdelete(&request->packet->vps, PW_SQL_GROUP);
734                                         pairfree(&check_tmp);
735                                         pairfree(&reply_tmp);
736                                         return -1;
737                                 }
738                                 *dofallthrough = fallthrough(reply_tmp);
739                                 pairxlatmove(request, &request->reply->vps, &reply_tmp);
740                                 pairxlatmove(request, &request->config_items, &check_tmp);
741                         }
742                 } else {
743                         /*
744                          *      rows == 0.  This is like having the username on a line
745                          *      in the user's file with no check vp's.  As such, we treat
746                          *      it as found and add the reply attributes, so that we
747                          *      match expected behavior
748                          */
749                         found = 1;
750                         RDEBUG2("User found in group %s",
751                                 group_list_tmp->groupname);
752                         /*
753                          *      Now get the reply pairs since the paircompare matched
754                          */
755                         if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_group_reply_query, request, sql_escape_func)) {
756                                 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
757                                 /* Remove the grouup we added above */
758                                 pairdelete(&request->packet->vps, PW_SQL_GROUP);
759                                 pairfree(&check_tmp);
760                                 return -1;
761                         }
762                         if (sql_getvpdata(inst, sqlsocket, &reply_tmp, querystr) < 0) {
763                                 radlog_request(L_ERR, 0, request, "Error retrieving reply pairs for group %s",
764                                        group_list_tmp->groupname);
765                                 /* Remove the grouup we added above */
766                                 pairdelete(&request->packet->vps, PW_SQL_GROUP);
767                                 pairfree(&check_tmp);
768                                 pairfree(&reply_tmp);
769                                 return -1;
770                         }
771                         *dofallthrough = fallthrough(reply_tmp);
772                         pairxlatmove(request, &request->reply->vps, &reply_tmp);
773                         pairxlatmove(request, &request->config_items, &check_tmp);
774                 }
775
776                 /*
777                  * Delete the Sql-Group we added above
778                  * And clear out the pairlists
779                  */
780                 pairdelete(&request->packet->vps, PW_SQL_GROUP);
781                 pairfree(&check_tmp);
782                 pairfree(&reply_tmp);
783         }
784
785         sql_grouplist_free(&group_list);
786         return found;
787 }
788
789
790 static int rlm_sql_detach(void *instance)
791 {
792         SQL_INST *inst = instance;
793
794         paircompare_unregister(PW_SQL_GROUP, sql_groupcmp);
795
796         if (inst->config) {
797                 int i;
798
799                 if (inst->sqlpool) {
800                         sql_poolfree(inst);
801                 }
802
803                 if (inst->config->xlat_name) {
804                         xlat_unregister(inst->config->xlat_name,(RAD_XLAT_FUNC)sql_xlat);
805                         free(inst->config->xlat_name);
806                 }
807
808                 /*
809                  *      Free up dynamically allocated string pointers.
810                  */
811                 for (i = 0; module_config[i].name != NULL; i++) {
812                         char **p;
813                         if (module_config[i].type != PW_TYPE_STRING_PTR) {
814                                 continue;
815                         }
816
817                         /*
818                          *      Treat 'config' as an opaque array of bytes,
819                          *      and take the offset into it.  There's a
820                          *      (char*) pointer at that offset, and we want
821                          *      to point to it.
822                          */
823                         p = (char **) (((char *)inst->config) + module_config[i].offset);
824                         if (!*p) { /* nothing allocated */
825                                 continue;
826                         }
827                         free(*p);
828                         *p = NULL;
829                 }
830                 /*
831                  *      Catch multiple instances of the module.
832                  */
833                 if (allowed_chars == inst->config->allowed_chars) {
834                         allowed_chars = NULL;
835                 }
836                 free(inst->config);
837                 inst->config = NULL;
838         }
839
840         if (inst->handle) {
841 #if 0
842                 /*
843                  *      FIXME: Call the modules 'destroy' function?
844                  */
845                 lt_dlclose(inst->handle);       /* ignore any errors */
846 #endif
847         }
848         free(inst);
849
850         return 0;
851 }
852 static int rlm_sql_instantiate(CONF_SECTION * conf, void **instance)
853 {
854         SQL_INST *inst;
855         const char *xlat_name;
856
857         inst = rad_malloc(sizeof(SQL_INST));
858         memset(inst, 0, sizeof(SQL_INST));
859
860         inst->config = rad_malloc(sizeof(SQL_CONFIG));
861         memset(inst->config, 0, sizeof(SQL_CONFIG));
862
863         /*
864          *      Export these methods, too.  This avoids RTDL_GLOBAL.
865          */
866         inst->sql_set_user = sql_set_user;
867         inst->sql_get_socket = sql_get_socket;
868         inst->sql_release_socket = sql_release_socket;
869         inst->sql_escape_func = sql_escape_func;
870         inst->sql_query = rlm_sql_query;
871         inst->sql_select_query = rlm_sql_select_query;
872         inst->sql_fetch_row = rlm_sql_fetch_row;
873
874         /*
875          * If the configuration parameters can't be parsed, then
876          * fail.
877          */
878         if (cf_section_parse(conf, inst->config, module_config) < 0) {
879                 rlm_sql_detach(inst);
880                 return -1;
881         }
882
883         xlat_name = cf_section_name2(conf);
884         if (xlat_name == NULL)
885                 xlat_name = cf_section_name1(conf);
886         if (xlat_name){
887                 inst->config->xlat_name = strdup(xlat_name);
888                 xlat_register(xlat_name, (RAD_XLAT_FUNC)sql_xlat, inst);
889         }
890
891         if (inst->config->num_sql_socks > MAX_SQL_SOCKS) {
892                 radlog(L_ERR, "rlm_sql (%s): sql_instantiate: number of sqlsockets cannot exceed MAX_SQL_SOCKS, %d",
893                        inst->config->xlat_name, MAX_SQL_SOCKS);
894                 rlm_sql_detach(inst);
895                 return -1;
896         }
897
898         /*
899          *      Sanity check for crazy people.
900          */
901         if (strncmp(inst->config->sql_driver, "rlm_sql_", 8) != 0) {
902                 radlog(L_ERR, "\"%s\" is NOT an SQL driver!",
903                        inst->config->sql_driver);
904                 rlm_sql_detach(inst);
905                 return -1;
906         }
907
908         inst->handle = lt_dlopenext(inst->config->sql_driver);
909         if (inst->handle == NULL) {
910                 radlog(L_ERR, "Could not link driver %s: %s",
911                        inst->config->sql_driver,
912                        lt_dlerror());
913                 radlog(L_ERR, "Make sure it (and all its dependent libraries!) are in the search path of your system's ld.");
914                 rlm_sql_detach(inst);
915                 return -1;
916         }
917
918         inst->module = (rlm_sql_module_t *) lt_dlsym(inst->handle, inst->config->sql_driver);
919         if (!inst->module) {
920                 radlog(L_ERR, "Could not link symbol %s: %s",
921                        inst->config->sql_driver,
922                        lt_dlerror());
923                 rlm_sql_detach(inst);
924                 return -1;
925         }
926
927         radlog(L_INFO, "rlm_sql (%s): Driver %s (module %s) loaded and linked",
928                inst->config->xlat_name, inst->config->sql_driver,
929                inst->module->name);
930         radlog(L_INFO, "rlm_sql (%s): Attempting to connect to %s@%s:%s/%s",
931                inst->config->xlat_name, inst->config->sql_login,
932                inst->config->sql_server, inst->config->sql_port,
933                inst->config->sql_db);
934
935         if (sql_init_socketpool(inst) < 0) {
936                 rlm_sql_detach(inst);
937                 return -1;
938         }
939
940         paircompare_register(PW_SQL_GROUP, PW_USER_NAME, sql_groupcmp, inst);
941
942         if (inst->config->do_clients){
943                 if (generate_sql_clients(inst) == -1){
944                         radlog(L_ERR, "Failed to load clients from SQL.");
945                         rlm_sql_detach(inst);
946                         return -1;
947                 }
948         }
949         allowed_chars = inst->config->allowed_chars;
950
951         *instance = inst;
952
953         return RLM_MODULE_OK;
954 }
955
956
957 static int rlm_sql_authorize(void *instance, REQUEST * request)
958 {
959         VALUE_PAIR *check_tmp = NULL;
960         VALUE_PAIR *reply_tmp = NULL;
961         VALUE_PAIR *user_profile = NULL;
962         int     found = 0;
963         int     dofallthrough = 1;
964         int     rows;
965         SQLSOCK *sqlsocket;
966         SQL_INST *inst = instance;
967         char    querystr[MAX_QUERY_LEN];
968         char    sqlusername[MAX_STRING_LEN];
969         /*
970          * the profile username is used as the sqlusername during
971          * profile checking so that we don't overwrite the orignal
972          * sqlusername string
973          */
974         char   profileusername[MAX_STRING_LEN];
975
976         /*
977          * Set, escape, and check the user attr here
978          */
979         if (sql_set_user(inst, request, sqlusername, NULL) < 0)
980                 return RLM_MODULE_FAIL;
981
982
983         /*
984          * reserve a socket
985          */
986         sqlsocket = sql_get_socket(inst);
987         if (sqlsocket == NULL) {
988                 /* Remove the username we (maybe) added above */
989                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
990                 return RLM_MODULE_FAIL;
991         }
992
993
994         /*
995          *  After this point, ALL 'return's MUST release the SQL socket!
996          */
997
998         /*
999          * Alright, start by getting the specific entry for the user
1000          */
1001         if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_check_query, request, sql_escape_func)) {
1002                 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
1003                 sql_release_socket(inst, sqlsocket);
1004                 /* Remove the username we (maybe) added above */
1005                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1006                 return RLM_MODULE_FAIL;
1007         }
1008         rows = sql_getvpdata(inst, sqlsocket, &check_tmp, querystr);
1009         if (rows < 0) {
1010                 radlog_request(L_ERR, 0, request, "SQL query error; rejecting user");
1011                 sql_release_socket(inst, sqlsocket);
1012                 /* Remove the username we (maybe) added above */
1013                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1014                 pairfree(&check_tmp);
1015                 return RLM_MODULE_FAIL;
1016         } else if (rows > 0) {
1017                 /*
1018                  *      Only do this if *some* check pairs were returned
1019                  */
1020                 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) == 0) {
1021                         found = 1;
1022                         RDEBUG2("User found in radcheck table");
1023
1024                         if (inst->config->authorize_reply_query &&
1025                             *inst->config->authorize_reply_query) {
1026
1027                         /*
1028                          *      Now get the reply pairs since the paircompare matched
1029                          */
1030                         if (!radius_xlat(querystr, sizeof(querystr), inst->config->authorize_reply_query, request, sql_escape_func)) {
1031                                 radlog_request(L_ERR, 0, request, "Error generating query; rejecting user");
1032                                 sql_release_socket(inst, sqlsocket);
1033                                 /* Remove the username we (maybe) added above */
1034                                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1035                                 pairfree(&check_tmp);
1036                                 return RLM_MODULE_FAIL;
1037                         }
1038                         if (sql_getvpdata(inst, sqlsocket, &reply_tmp, querystr) < 0) {
1039                                 radlog_request(L_ERR, 0, request, "SQL query error; rejecting user");
1040                                 sql_release_socket(inst, sqlsocket);
1041                                 /* Remove the username we (maybe) added above */
1042                                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1043                                 pairfree(&check_tmp);
1044                                 pairfree(&reply_tmp);
1045                                 return RLM_MODULE_FAIL;
1046                         }
1047
1048                         if (!inst->config->read_groups)
1049                                 dofallthrough = fallthrough(reply_tmp);
1050                         pairxlatmove(request, &request->reply->vps, &reply_tmp);
1051                         }
1052                         pairxlatmove(request, &request->config_items, &check_tmp);
1053                 }
1054         }
1055
1056         /*
1057          *      Clear out the pairlists
1058          */
1059         pairfree(&check_tmp);
1060         pairfree(&reply_tmp);
1061
1062         /*
1063          *      dofallthrough is set to 1 by default so that if the user information
1064          *      is not found, we will still process groups.  If the user information,
1065          *      however, *is* found, Fall-Through must be set in order to process
1066          *      the groups as well
1067          */
1068         if (dofallthrough) {
1069                 rows = rlm_sql_process_groups(inst, request, sqlsocket, &dofallthrough);
1070                 if (rows < 0) {
1071                         radlog_request(L_ERR, 0, request, "Error processing groups; rejecting user");
1072                         sql_release_socket(inst, sqlsocket);
1073                         /* Remove the username we (maybe) added above */
1074                         pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1075                         return RLM_MODULE_FAIL;
1076                 } else if (rows > 0) {
1077                         found = 1;
1078                 }
1079         }
1080
1081         /*
1082          *      repeat the above process with the default profile or User-Profile
1083          */
1084         if (dofallthrough) {
1085                 int profile_found = 0;
1086                 /*
1087                 * Check for a default_profile or for a User-Profile.
1088                 */
1089                 user_profile = pairfind(request->config_items, PW_USER_PROFILE);
1090                 if (inst->config->default_profile[0] != 0 || user_profile != NULL){
1091                         char *profile = inst->config->default_profile;
1092
1093                         if (user_profile != NULL)
1094                                 profile = user_profile->vp_strvalue;
1095                         if (profile && strlen(profile)){
1096                                 RDEBUG("Checking profile %s", profile);
1097                                 if (sql_set_user(inst, request, profileusername, profile) < 0) {
1098                                         radlog_request(L_ERR, 0, request, "Error setting profile; rejecting user");
1099                                         sql_release_socket(inst, sqlsocket);
1100                                         /* Remove the username we (maybe) added above */
1101                                         pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1102                                         return RLM_MODULE_FAIL;
1103                                 } else {
1104                                         profile_found = 1;
1105                                 }
1106                         }
1107                 }
1108
1109                 if (profile_found) {
1110                         rows = rlm_sql_process_groups(inst, request, sqlsocket, &dofallthrough);
1111                         if (rows < 0) {
1112                                 radlog_request(L_ERR, 0, request, "Error processing profile groups; rejecting user");
1113                                 sql_release_socket(inst, sqlsocket);
1114                                 /* Remove the username we (maybe) added above */
1115                                 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1116                                 return RLM_MODULE_FAIL;
1117                         } else if (rows > 0) {
1118                                 found = 1;
1119                         }
1120                 }
1121         }
1122
1123         /* Remove the username we (maybe) added above */
1124         pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
1125         sql_release_socket(inst, sqlsocket);
1126
1127         if (!found) {
1128                 RDEBUG("User %s not found", sqlusername);
1129                 return RLM_MODULE_NOTFOUND;
1130         } else {
1131                 return RLM_MODULE_OK;
1132         }
1133 }
1134
1135 /*
1136  *      Accounting: save the account data to our sql table
1137  */
1138 static int rlm_sql_accounting(void *instance, REQUEST * request) {
1139
1140         SQLSOCK *sqlsocket = NULL;
1141         VALUE_PAIR *pair;
1142         SQL_INST *inst = instance;
1143         int     ret = RLM_MODULE_OK;
1144         int     numaffected = 0;
1145         int     acctstatustype = 0;
1146         char    querystr[MAX_QUERY_LEN];
1147         char    logstr[MAX_QUERY_LEN];
1148         char    sqlusername[MAX_STRING_LEN];
1149
1150 #ifdef CISCO_ACCOUNTING_HACK
1151         int     acctsessiontime = 0;
1152 #endif
1153
1154         memset(querystr, 0, MAX_QUERY_LEN);
1155
1156         /*
1157          * Find the Acct Status Type
1158          */
1159         if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE)) != NULL) {
1160                 acctstatustype = pair->vp_integer;
1161         } else {
1162                 radius_xlat(logstr, sizeof(logstr), "packet has no accounting status type. [user '%{User-Name}', nas '%{NAS-IP-Address}']", request, NULL);
1163                 radlog_request(L_ERR, 0, request, "%s", logstr);
1164                 return RLM_MODULE_INVALID;
1165         }
1166
1167         switch (acctstatustype) {
1168                         /*
1169                          * The Terminal server informed us that it was rebooted
1170                          * STOP all records from this NAS
1171                          */
1172                 case PW_STATUS_ACCOUNTING_ON:
1173                 case PW_STATUS_ACCOUNTING_OFF:
1174                         RDEBUG("Received Acct On/Off packet");
1175                         radius_xlat(querystr, sizeof(querystr), inst->config->accounting_onoff_query, request, sql_escape_func);
1176                         query_log(request, inst, querystr);
1177
1178                         sqlsocket = sql_get_socket(inst);
1179                         if (sqlsocket == NULL)
1180                                 return(RLM_MODULE_FAIL);
1181                         if (*querystr) { /* non-empty query */
1182                                 if (rlm_sql_query(sqlsocket, inst, querystr)) {
1183                                         radlog_request(L_ERR, 0, request, "Couldn't update SQL accounting for Acct On/Off packet - %s",
1184                                                (inst->module->sql_error)(sqlsocket, inst->config));
1185                                         ret = RLM_MODULE_FAIL;
1186                                 }
1187                                 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1188                         }
1189
1190                         break;
1191
1192                         /*
1193                          * Got an update accounting packet
1194                          */
1195                 case PW_STATUS_ALIVE:
1196
1197                         /*
1198                          * Set, escape, and check the user attr here
1199                          */
1200                         sql_set_user(inst, request, sqlusername, NULL);
1201
1202                         radius_xlat(querystr, sizeof(querystr), inst->config->accounting_update_query, request, sql_escape_func);
1203                         query_log(request, inst, querystr);
1204
1205                         sqlsocket = sql_get_socket(inst);
1206                         if (sqlsocket == NULL)
1207                                 return(RLM_MODULE_FAIL);
1208                         if (*querystr) { /* non-empty query */
1209                                 if (rlm_sql_query(sqlsocket, inst, querystr)) {
1210                                         radlog_request(L_ERR, 0, request, "Couldn't update SQL accounting ALIVE record - %s",
1211                                                (inst->module->sql_error)(sqlsocket, inst->config));
1212                                         ret = RLM_MODULE_FAIL;
1213                                 }
1214                                 else {
1215                                         numaffected = (inst->module->sql_affected_rows)(sqlsocket, inst->config);
1216                                         if (numaffected < 1) {
1217
1218                                                 /*
1219                                                  * If our update above didn't match anything
1220                                                  * we assume it's because we haven't seen a
1221                                                  * matching Start record.  So we have to
1222                                                  * insert this update rather than do an update
1223                                                  */
1224                                                 radius_xlat(querystr, sizeof(querystr), inst->config->accounting_update_query_alt, request, sql_escape_func);
1225                                                 query_log(request, inst, querystr);
1226                                                 if (*querystr) { /* non-empty query */
1227                                                         if (rlm_sql_query(sqlsocket, inst, querystr)) {
1228                                                                 radlog_request(L_ERR, 0, request, "Couldn't insert SQL accounting ALIVE record - %s",
1229                                                                        (inst->module->sql_error)(sqlsocket, inst->config));
1230                                                                 ret = RLM_MODULE_FAIL;
1231                                                         }
1232                                                         (inst->module->sql_finish_query)(sqlsocket, inst->config);
1233                                                 }
1234                                         }
1235                                 }
1236                                 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1237                         }
1238                         break;
1239
1240                         /*
1241                          * Got accounting start packet
1242                          */
1243                 case PW_STATUS_START:
1244
1245                         /*
1246                          * Set, escape, and check the user attr here
1247                          */
1248                         sql_set_user(inst, request, sqlusername, NULL);
1249
1250                         radius_xlat(querystr, sizeof(querystr), inst->config->accounting_start_query, request, sql_escape_func);
1251                         query_log(request, inst, querystr);
1252
1253                         sqlsocket = sql_get_socket(inst);
1254                         if (sqlsocket == NULL)
1255                                 return(RLM_MODULE_FAIL);
1256                         if (*querystr) { /* non-empty query */
1257                                 if (rlm_sql_query(sqlsocket, inst, querystr)) {
1258                                         radlog_request(L_ERR, 0, request, "Couldn't insert SQL accounting START record - %s",
1259                                                (inst->module->sql_error)(sqlsocket, inst->config));
1260
1261                                         /*
1262                                          * We failed the insert above.  It's probably because
1263                                          * the stop record came before the start.  We try
1264                                          * our alternate query now (typically an UPDATE)
1265                                          */
1266                                         radius_xlat(querystr, sizeof(querystr), inst->config->accounting_start_query_alt, request, sql_escape_func);
1267                                         query_log(request, inst, querystr);
1268
1269                                         if (*querystr) { /* non-empty query */
1270                                                 if (rlm_sql_query(sqlsocket, inst, querystr)) {
1271                                                         radlog_request(L_ERR, 0, request, "Couldn't update SQL accounting START record - %s",
1272                                                                (inst->module->sql_error)(sqlsocket, inst->config));
1273                                                         ret = RLM_MODULE_FAIL;
1274                                                 }
1275                                                 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1276                                         }
1277                                 }
1278                                 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1279                         }
1280                         break;
1281
1282                         /*
1283                          * Got accounting stop packet
1284                          */
1285                 case PW_STATUS_STOP:
1286
1287                         /*
1288                          * Set, escape, and check the user attr here
1289                          */
1290                         sql_set_user(inst, request, sqlusername, NULL);
1291
1292                         radius_xlat(querystr, sizeof(querystr), inst->config->accounting_stop_query, request, sql_escape_func);
1293                         query_log(request, inst, querystr);
1294
1295                         sqlsocket = sql_get_socket(inst);
1296                         if (sqlsocket == NULL)
1297                                 return(RLM_MODULE_FAIL);
1298                         if (*querystr) { /* non-empty query */
1299                                 if (rlm_sql_query(sqlsocket, inst, querystr)) {
1300                                         radlog_request(L_ERR, 0, request, "Couldn't update SQL accounting STOP record - %s",
1301                                                (inst->module->sql_error)(sqlsocket, inst->config));
1302                                         ret = RLM_MODULE_FAIL;
1303                                 }
1304                                 else {
1305                                         numaffected = (inst->module->sql_affected_rows)(sqlsocket, inst->config);
1306                                         if (numaffected < 1) {
1307                                                 /*
1308                                                  * If our update above didn't match anything
1309                                                  * we assume it's because we haven't seen a
1310                                                  * matching Start record.  So we have to
1311                                                  * insert this stop rather than do an update
1312                                                  */
1313 #ifdef CISCO_ACCOUNTING_HACK
1314                                                 /*
1315                                                  * If stop but zero session length AND no previous
1316                                                  * session found, drop it as in invalid packet
1317                                                  * This is to fix CISCO's aaa from filling our
1318                                                  * table with bogus crap
1319                                                  */
1320                                                 if ((pair = pairfind(request->packet->vps, PW_ACCT_SESSION_TIME)) != NULL)
1321                                                         acctsessiontime = pair->vp_integer;
1322
1323                                                 if (acctsessiontime <= 0) {
1324                                                         radius_xlat(logstr, sizeof(logstr), "stop packet with zero session length. [user '%{User-Name}', nas '%{NAS-IP-Address}']", request, NULL);
1325                                                         radlog_request(L_ERR, 0, request, "%s", logstr);
1326                                                         sql_release_socket(inst, sqlsocket);
1327                                                         ret = RLM_MODULE_NOOP;
1328                                                 }
1329 #endif
1330
1331                                                 radius_xlat(querystr, sizeof(querystr), inst->config->accounting_stop_query_alt, request, sql_escape_func);
1332                                                 query_log(request, inst, querystr);
1333
1334                                                 if (*querystr) { /* non-empty query */
1335                                                         if (rlm_sql_query(sqlsocket, inst, querystr)) {
1336                                                                 radlog_request(L_ERR, 0, request, "Couldn't insert SQL accounting STOP record - %s",
1337
1338                                                                        (inst->module->sql_error)(sqlsocket, inst->config));
1339                                                                 ret = RLM_MODULE_FAIL;
1340                                                         }
1341                                                         (inst->module->sql_finish_query)(sqlsocket, inst->config);
1342                                                 }
1343                                         }
1344                                 }
1345                                 (inst->module->sql_finish_query)(sqlsocket, inst->config);
1346                         }
1347                         break;
1348
1349                         /*
1350                          *      Anything else is ignored.
1351                          */
1352                 default:
1353                         RDEBUG("Unsupported Acct-Status-Type = %d",
1354                        acctstatustype);
1355                         return RLM_MODULE_NOOP;
1356                         break;
1357
1358         }
1359
1360         sql_release_socket(inst, sqlsocket);
1361
1362         return ret;
1363 }
1364
1365
1366 /*
1367  *        See if a user is already logged in. Sets request->simul_count to the
1368  *        current session count for this user.
1369  *
1370  *        Check twice. If on the first pass the user exceeds his
1371  *        max. number of logins, do a second pass and validate all
1372  *        logins by querying the terminal server (using eg. SNMP).
1373  */
1374
1375 static int rlm_sql_checksimul(void *instance, REQUEST * request) {
1376         SQLSOCK         *sqlsocket;
1377         SQL_INST        *inst = instance;
1378         SQL_ROW         row;
1379         char            querystr[MAX_QUERY_LEN];
1380         char            sqlusername[MAX_STRING_LEN];
1381         int             check = 0;
1382         uint32_t        ipno = 0;
1383         char            *call_num = NULL;
1384         VALUE_PAIR      *vp;
1385         int             ret;
1386         uint32_t        nas_addr = 0;
1387         int             nas_port = 0;
1388
1389         /* If simul_count_query is not defined, we don't do any checking */
1390         if (!inst->config->simul_count_query ||
1391             (inst->config->simul_count_query[0] == 0)) {
1392                 return RLM_MODULE_NOOP;
1393         }
1394
1395         if((request->username == NULL) || (request->username->length == 0)) {
1396                 radlog_request(L_ERR, 0, request, "Zero Length username not permitted\n");
1397                 return RLM_MODULE_INVALID;
1398         }
1399
1400
1401         if(sql_set_user(inst, request, sqlusername, NULL) < 0)
1402                 return RLM_MODULE_FAIL;
1403
1404         radius_xlat(querystr, sizeof(querystr), inst->config->simul_count_query, request, sql_escape_func);
1405
1406         /* initialize the sql socket */
1407         sqlsocket = sql_get_socket(inst);
1408         if(sqlsocket == NULL)
1409                 return RLM_MODULE_FAIL;
1410
1411         if(rlm_sql_select_query(sqlsocket, inst, querystr)) {
1412                 radlog(L_ERR, "rlm_sql (%s) sql_checksimul: Database query failed", inst->config->xlat_name);
1413                 sql_release_socket(inst, sqlsocket);
1414                 return RLM_MODULE_FAIL;
1415         }
1416
1417         ret = rlm_sql_fetch_row(sqlsocket, inst);
1418
1419         if (ret != 0) {
1420                 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1421                 sql_release_socket(inst, sqlsocket);
1422                 return RLM_MODULE_FAIL;
1423         }
1424
1425         row = sqlsocket->row;
1426         if (row == NULL) {
1427                 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1428                 sql_release_socket(inst, sqlsocket);
1429                 return RLM_MODULE_FAIL;
1430         }
1431
1432         request->simul_count = atoi(row[0]);
1433         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1434
1435         if(request->simul_count < request->simul_max) {
1436                 sql_release_socket(inst, sqlsocket);
1437                 return RLM_MODULE_OK;
1438         }
1439
1440         /*
1441          *      Looks like too many sessions, so let's start verifying
1442          *      them, unless told to rely on count query only.
1443          */
1444         if (!inst->config->simul_verify_query ||
1445             (inst->config->simul_verify_query[0] == '\0')) {
1446                 sql_release_socket(inst, sqlsocket);
1447                 return RLM_MODULE_OK;
1448         }
1449
1450         radius_xlat(querystr, sizeof(querystr), inst->config->simul_verify_query, request, sql_escape_func);
1451         if(rlm_sql_select_query(sqlsocket, inst, querystr)) {
1452                 radlog_request(L_ERR, 0, request, "Database query error");
1453                 sql_release_socket(inst, sqlsocket);
1454                 return RLM_MODULE_FAIL;
1455         }
1456
1457         /*
1458          *      Setup some stuff, like for MPP detection.
1459          */
1460         request->simul_count = 0;
1461
1462         if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS)) != NULL)
1463                 ipno = vp->vp_ipaddr;
1464         if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID)) != NULL)
1465                 call_num = vp->vp_strvalue;
1466
1467
1468         while (rlm_sql_fetch_row(sqlsocket, inst) == 0) {
1469                 row = sqlsocket->row;
1470                 if (row == NULL)
1471                         break;
1472                 if (!row[2]){
1473                         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1474                         sql_release_socket(inst, sqlsocket);
1475                         RDEBUG("Cannot zap stale entry. No username present in entry.", inst->config->xlat_name);
1476                         return RLM_MODULE_FAIL;
1477                 }
1478                 if (!row[1]){
1479                         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1480                         sql_release_socket(inst, sqlsocket);
1481                         RDEBUG("Cannot zap stale entry. No session id in entry.", inst->config->xlat_name);
1482                         return RLM_MODULE_FAIL;
1483                 }
1484                 if (row[3])
1485                         nas_addr = inet_addr(row[3]);
1486                 if (row[4])
1487                         nas_port = atoi(row[4]);
1488
1489                 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1490
1491                 if (check == 0) {
1492                         /*
1493                          *      Stale record - zap it.
1494                          */
1495                         if (inst->config->deletestalesessions == TRUE) {
1496                                 uint32_t framed_addr = 0;
1497                                 char proto = 0;
1498                                 int sess_time = 0;
1499
1500                                 if (row[5])
1501                                         framed_addr = inet_addr(row[5]);
1502                                 if (row[7]){
1503                                         if (strcmp(row[7], "PPP") == 0)
1504                                                 proto = 'P';
1505                                         else if (strcmp(row[7], "SLIP") == 0)
1506                                                 proto = 'S';
1507                                 }
1508                                 if (row[8])
1509                                         sess_time = atoi(row[8]);
1510                                 session_zap(request, nas_addr, nas_port,
1511                                             row[2], row[1], framed_addr,
1512                                             proto, sess_time);
1513                         }
1514                 }
1515                 else if (check == 1) {
1516                         /*
1517                          *      User is still logged in.
1518                          */
1519                         ++request->simul_count;
1520
1521                         /*
1522                          *      Does it look like a MPP attempt?
1523                          */
1524                         if (row[5] && ipno && inet_addr(row[5]) == ipno)
1525                                 request->simul_mpp = 2;
1526                         else if (row[6] && call_num &&
1527                                 !strncmp(row[6],call_num,16))
1528                                 request->simul_mpp = 2;
1529                 }
1530                 else {
1531                         /*
1532                          *      Failed to check the terminal server for
1533                          *      duplicate logins: return an error.
1534                          */
1535                         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1536                         sql_release_socket(inst, sqlsocket);
1537                         radlog_request(L_ERR, 0, request, "Failed to check the terminal server for user '%s'.", row[2]);
1538                         return RLM_MODULE_FAIL;
1539                 }
1540         }
1541
1542         (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
1543         sql_release_socket(inst, sqlsocket);
1544
1545         /*
1546          *      The Auth module apparently looks at request->simul_count,
1547          *      not the return value of this module when deciding to deny
1548          *      a call for too many sessions.
1549          */
1550         return RLM_MODULE_OK;
1551 }
1552
1553 /*
1554  *      Execute postauth_query after authentication
1555  */
1556 static int rlm_sql_postauth(void *instance, REQUEST *request) {
1557         SQLSOCK         *sqlsocket = NULL;
1558         SQL_INST        *inst = instance;
1559         char            querystr[MAX_QUERY_LEN];
1560         char            sqlusername[MAX_STRING_LEN];
1561
1562         if(sql_set_user(inst, request, sqlusername, NULL) < 0)
1563                 return RLM_MODULE_FAIL;
1564
1565         /* If postauth_query is not defined, we stop here */
1566         if (!inst->config->postauth_query ||
1567             (inst->config->postauth_query[0] == '\0'))
1568                 return RLM_MODULE_NOOP;
1569
1570         /* Expand variables in the query */
1571         memset(querystr, 0, MAX_QUERY_LEN);
1572         radius_xlat(querystr, sizeof(querystr), inst->config->postauth_query,
1573                     request, sql_escape_func);
1574         query_log(request, inst, querystr);
1575         DEBUG2("rlm_sql (%s) in sql_postauth: query is %s",
1576                inst->config->xlat_name, querystr);
1577
1578         /* Initialize the sql socket */
1579         sqlsocket = sql_get_socket(inst);
1580         if (sqlsocket == NULL)
1581                 return RLM_MODULE_FAIL;
1582
1583         /* Process the query */
1584         if (rlm_sql_query(sqlsocket, inst, querystr)) {
1585                 radlog(L_ERR, "rlm_sql (%s) in sql_postauth: Database query error - %s",
1586                        inst->config->xlat_name,
1587                        (inst->module->sql_error)(sqlsocket, inst->config));
1588                 sql_release_socket(inst, sqlsocket);
1589                 return RLM_MODULE_FAIL;
1590         }
1591         (inst->module->sql_finish_query)(sqlsocket, inst->config);
1592
1593         sql_release_socket(inst, sqlsocket);
1594         return RLM_MODULE_OK;
1595 }
1596
1597 /* globally exported name */
1598 module_t rlm_sql = {
1599         RLM_MODULE_INIT,
1600         "SQL",
1601         RLM_TYPE_THREAD_SAFE,   /* type: reserved */
1602         rlm_sql_instantiate,    /* instantiation */
1603         rlm_sql_detach,         /* detach */
1604         {
1605                 NULL,                   /* authentication */
1606                 rlm_sql_authorize,      /* authorization */
1607                 NULL,                   /* preaccounting */
1608                 rlm_sql_accounting,     /* accounting */
1609                 rlm_sql_checksimul,     /* checksimul */
1610                 NULL,                   /* pre-proxy */
1611                 NULL,                   /* post-proxy */
1612                 rlm_sql_postauth        /* post-auth */
1613         },
1614 };