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