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