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