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