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