Escape \n \r \t in the sql module escape function (now the xlat won't do it for us)
[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 || (inst->config->groupmemb_query[0] == 0)) {
541                 return 0;
542         }
543
544         if (radius_axlat(&expanded, request, inst->config->groupmemb_query, sql_escape_func, inst) < 0) {
545                 return -1;
546         }
547
548         ret = rlm_sql_select_query(handle, inst, expanded);
549         talloc_free(expanded);
550         if (ret != RLM_SQL_OK) return -1;
551
552         while (rlm_sql_fetch_row(handle, inst) == 0) {
553                 row = (*handle)->row;
554                 if (!row)
555                         break;
556
557                 if (!row[0]){
558                         RDEBUG("row[0] returned NULL");
559                         (inst->module->sql_finish_select_query)(*handle, inst->config);
560                         talloc_free(entry);
561                         return -1;
562                 }
563
564                 if (!*phead) {
565                         *phead = talloc_zero(*handle, rlm_sql_grouplist_t);
566                         entry = *phead;
567                 } else {
568                         entry->next = talloc_zero(*phead, rlm_sql_grouplist_t);
569                         entry = entry->next;
570                 }
571                 entry->next = NULL;
572                 entry->name = talloc_typed_strdup(entry, row[0]);
573
574                 num_groups++;
575         }
576
577         (inst->module->sql_finish_select_query)(*handle, inst->config);
578
579         return num_groups;
580 }
581
582
583 /*
584  * sql groupcmp function. That way we can do group comparisons (in the users file for example)
585  * with the group memberships reciding in sql
586  * The group membership query should only return one element which is the username. The returned
587  * username will then be checked with the passed check string.
588  */
589
590 static int CC_HINT(nonnull (1, 2, 4)) sql_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *request_vp,
591                                                    VALUE_PAIR *check, UNUSED VALUE_PAIR *check_pairs,
592                                                    UNUSED VALUE_PAIR **reply_pairs)
593 {
594         rlm_sql_handle_t *handle;
595         rlm_sql_t *inst = instance;
596         rlm_sql_grouplist_t *head, *entry;
597
598         RDEBUG("sql_groupcmp");
599
600         if (check->length == 0){
601                 RDEBUG("sql_groupcmp: Illegal group name");
602                 return 1;
603         }
604
605         /*
606          *      Set, escape, and check the user attr here
607          */
608         if (sql_set_user(inst, request, NULL) < 0)
609                 return 1;
610
611         /*
612          *      Get a socket for this lookup
613          */
614         handle = fr_connection_get(inst->pool);
615         if (!handle) {
616                 return 1;
617         }
618
619         /*
620          *      Get the list of groups this user is a member of
621          */
622         if (sql_get_grouplist(inst, &handle, request, &head) < 0) {
623                 REDEBUG("Error getting group membership");
624                 fr_connection_release(inst->pool, handle);
625                 return 1;
626         }
627
628         for (entry = head; entry != NULL; entry = entry->next) {
629                 if (strcmp(entry->name, check->vp_strvalue) == 0){
630                         RDEBUG("sql_groupcmp finished: User is a member of group %s",
631                                check->vp_strvalue);
632                         talloc_free(head);
633                         fr_connection_release(inst->pool, handle);
634                         return 0;
635                 }
636         }
637
638         /* Free the grouplist */
639         talloc_free(head);
640         fr_connection_release(inst->pool, handle);
641
642         RDEBUG("sql_groupcmp finished: User is NOT a member of group %s", check->vp_strvalue);
643
644         return 1;
645 }
646
647 static rlm_rcode_t rlm_sql_process_groups(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
648                                           sql_fall_through_t *do_fall_through)
649 {
650         rlm_rcode_t             rcode = RLM_MODULE_NOOP;
651         VALUE_PAIR              *check_tmp = NULL, *reply_tmp = NULL, *sql_group = NULL;
652         rlm_sql_grouplist_t     *head = NULL, *entry = NULL;
653
654         char                    *expanded = NULL;
655         int                     rows;
656
657         rad_assert(request->packet != NULL);
658
659         /*
660          *      Get the list of groups this user is a member of
661          */
662         rows = sql_get_grouplist(inst, handle, request, &head);
663         if (rows < 0) {
664                 REDEBUG("Error retrieving group list");
665
666                 return RLM_MODULE_FAIL;
667         }
668         if (rows == 0) {
669                 RDEBUG2("User not found in any groups");
670                 rcode = RLM_MODULE_NOTFOUND;
671                 goto finish;
672         }
673         rad_assert(head);
674
675         RDEBUG2("User found in the group table");
676
677         entry = head;
678         do {
679                 /*
680                  *      Add the Sql-Group attribute to the request list so we know
681                  *      which group we're retrieving attributes for
682                  */
683                 sql_group = pairmake_packet("Sql-Group", entry->name, T_OP_EQ);
684                 if (!sql_group) {
685                         REDEBUG("Error creating Sql-Group attribute");
686                         rcode = RLM_MODULE_FAIL;
687                         goto finish;
688                 }
689
690                 if (inst->config->authorize_group_check_query && *inst->config->authorize_group_check_query) {
691                         vp_cursor_t cursor;
692                         VALUE_PAIR *vp;
693
694                         /*
695                          *      Expand the group query
696                          */
697                         if (radius_axlat(&expanded, request, inst->config->authorize_group_check_query,
698                                          sql_escape_func, inst) < 0) {
699                                 REDEBUG("Error generating query");
700                                 rcode = RLM_MODULE_FAIL;
701                                 goto finish;
702                         }
703
704                         rows = sql_getvpdata(request, inst, request, handle, &check_tmp, expanded);
705                         TALLOC_FREE(expanded);
706                         if (rows < 0) {
707                                 REDEBUG("Error retrieving check pairs for group %s", entry->name);
708                                 rcode = RLM_MODULE_FAIL;
709                                 goto finish;
710                         }
711
712                         /*
713                          *      If we got check rows we need to process them before we decide to process the reply rows
714                          */
715                         if ((rows > 0) &&
716                             (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0)) {
717                                 pairfree(&check_tmp);
718                                 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
719
720                                 continue;
721                         }
722
723                         RDEBUG2("Group \"%s\": Conditional check items matched", entry->name);
724                         rcode = RLM_MODULE_OK;
725
726                         RDEBUG2("Group \"%s\": Merging assignment check items", entry->name);
727                         RINDENT();
728                         for (vp = fr_cursor_init(&cursor, &check_tmp);
729                              vp;
730                              vp = fr_cursor_next(&cursor)) {
731                                 if (!fr_assignment_op[vp->op]) continue;
732
733                                 rdebug_pair(2, request, vp);
734                         }
735                         REXDENT();
736                         radius_pairmove(request, &request->config_items, check_tmp, true);
737                         check_tmp = NULL;
738                 }
739
740                 if (inst->config->authorize_group_reply_query && *inst->config->authorize_group_reply_query) {
741                         /*
742                          *      Now get the reply pairs since the paircompare matched
743                          */
744                         if (radius_axlat(&expanded, request, inst->config->authorize_group_reply_query,
745                                          sql_escape_func, inst) < 0) {
746                                 REDEBUG("Error generating query");
747                                 rcode = RLM_MODULE_FAIL;
748                                 goto finish;
749                         }
750
751                         rows = sql_getvpdata(request->reply, inst, request, handle, &reply_tmp, expanded);
752                         TALLOC_FREE(expanded);
753                         if (rows < 0) {
754                                 REDEBUG("Error retrieving reply pairs for group %s", entry->name);
755                                 rcode = RLM_MODULE_FAIL;
756                                 goto finish;
757                         }
758                         *do_fall_through = fall_through(reply_tmp);
759
760                         RDEBUG2("Group \"%s\": Merging reply items", entry->name);
761                         rcode = RLM_MODULE_OK;
762
763                         rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp);
764
765                         radius_pairmove(request, &request->reply->vps, reply_tmp, true);
766                         reply_tmp = NULL;
767                 }
768
769                 pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
770                 entry = entry->next;
771         } while (entry != NULL && (*do_fall_through == FALL_THROUGH_YES));
772
773 finish:
774         talloc_free(head);
775         pairdelete(&request->packet->vps, PW_SQL_GROUP, 0, TAG_ANY);
776
777         return rcode;
778 }
779
780
781 static int mod_detach(void *instance)
782 {
783         rlm_sql_t *inst = instance;
784
785         if (inst->pool) fr_connection_pool_delete(inst->pool);
786
787         /*
788          *  We need to explicitly free all children, so if the driver
789          *  parented any memory off the instance, their destructors
790          *  run before we unload the bytecode for them.
791          *
792          *  If we don't do this, we get a SEGV deep inside the talloc code
793          *  when it tries to call a destructor that no longer exists.
794          */
795         talloc_free_children(inst);
796
797         /*
798          *  Decrements the reference count. The driver object won't be unloaded
799          *  until all instances of rlm_sql that use it have been destroyed.
800          */
801         if (inst->handle) dlclose(inst->handle);
802
803         return 0;
804 }
805
806 static int mod_instantiate(CONF_SECTION *conf, void *instance)
807 {
808         rlm_sql_t *inst = instance;
809
810         /*
811          *      Hack...
812          */
813         inst->config = &inst->myconfig;
814         inst->cs = conf;
815
816         inst->config->xlat_name = cf_section_name2(conf);
817         if (!inst->config->xlat_name) {
818                 inst->config->xlat_name = cf_section_name1(conf);
819         } else {
820                 char *group_name;
821                 DICT_ATTR const *da;
822                 ATTR_FLAGS flags;
823
824                 /*
825                  *      Allocate room for <instance>-SQL-Group
826                  */
827                 group_name = talloc_typed_asprintf(inst, "%s-SQL-Group", inst->config->xlat_name);
828                 DEBUG("rlm_sql (%s): Creating new attribute %s",
829                       inst->config->xlat_name, group_name);
830
831                 memset(&flags, 0, sizeof(flags));
832                 if (dict_addattr(group_name, -1, 0, PW_TYPE_STRING, flags) < 0) {
833                         ERROR("rlm_sql (%s): Failed to create "
834                                "attribute %s: %s", inst->config->xlat_name, group_name,
835                                fr_strerror());
836                         return -1;
837                 }
838
839                 da = dict_attrbyname(group_name);
840                 if (!da) {
841                         ERROR("rlm_sql (%s): Failed to create "
842                                "attribute %s", inst->config->xlat_name, group_name);
843                         return -1;
844                 }
845
846                 if (inst->config->groupmemb_query &&
847                     inst->config->groupmemb_query[0]) {
848                         DEBUG("rlm_sql (%s): Registering sql_groupcmp for %s",
849                               inst->config->xlat_name, group_name);
850                         paircompare_register(da, dict_attrbyvalue(PW_USER_NAME, 0),
851                                              false, sql_groupcmp, inst);
852                 }
853         }
854
855         rad_assert(inst->config->xlat_name);
856
857         /*
858          *      Complain if the strings exist, but are empty.
859          */
860 #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)
861
862         CHECK_STRING(authorize_check_query);
863         CHECK_STRING(authorize_reply_query);
864         CHECK_STRING(authorize_group_check_query);
865         CHECK_STRING(authorize_group_reply_query);
866
867         /*
868          *      This will always exist, as cf_section_parse_init()
869          *      will create it if it doesn't exist.  However, the
870          *      "reference" config item won't exist in an auto-created
871          *      configuration.  So if that doesn't exist, we ignore
872          *      the whole subsection.
873          */
874         inst->config->accounting.cs = cf_section_sub_find(conf, "accounting");
875         inst->config->accounting.reference_cp = (cf_pair_find(inst->config->accounting.cs, "reference") != NULL);
876
877         inst->config->postauth.cs = cf_section_sub_find(conf, "post-auth");
878         inst->config->postauth.reference_cp = (cf_pair_find(inst->config->postauth.cs, "reference") != NULL);
879
880         /*
881          *      Cache the SQL-User-Name DICT_ATTR, so we can be slightly
882          *      more efficient about creating SQL-User-Name attributes.
883          */
884         inst->sql_user = dict_attrbyname("SQL-User-Name");
885         if (!inst->sql_user) {
886                 return -1;
887         }
888
889         /*
890          *      Export these methods, too.  This avoids RTDL_GLOBAL.
891          */
892         inst->sql_set_user              = sql_set_user;
893         inst->sql_escape_func           = sql_escape_func;
894         inst->sql_query                 = rlm_sql_query;
895         inst->sql_select_query          = rlm_sql_select_query;
896         inst->sql_fetch_row             = rlm_sql_fetch_row;
897
898         /*
899          *      Register the SQL xlat function
900          */
901         xlat_register(inst->config->xlat_name, sql_xlat, sql_escape_func, inst);
902
903         /*
904          *      Sanity check for crazy people.
905          */
906         if (strncmp(inst->config->sql_driver_name, "rlm_sql_", 8) != 0) {
907                 ERROR("rlm_sql (%s): \"%s\" is NOT an SQL driver!", inst->config->xlat_name, inst->config->sql_driver_name);
908                 return -1;
909         }
910
911         /*
912          *      Load the appropriate driver for our database
913          */
914         inst->handle = lt_dlopenext(inst->config->sql_driver_name);
915         if (!inst->handle) {
916                 ERROR("Could not link driver %s: %s", inst->config->sql_driver_name, dlerror());
917                 ERROR("Make sure it (and all its dependent libraries!) are in the search path of your system's ld");
918                 return -1;
919         }
920
921         inst->module = (rlm_sql_module_t *) dlsym(inst->handle,
922                                                   inst->config->sql_driver_name);
923         if (!inst->module) {
924                 ERROR("Could not link symbol %s: %s", inst->config->sql_driver_name, dlerror());
925                 return -1;
926         }
927
928         if (inst->module->mod_instantiate) {
929                 CONF_SECTION *cs;
930                 char const *name;
931
932                 name = strrchr(inst->config->sql_driver_name, '_');
933                 if (!name) {
934                         name = inst->config->sql_driver_name;
935                 } else {
936                         name++;
937                 }
938
939                 cs = cf_section_sub_find(conf, name);
940                 if (!cs) {
941                         cs = cf_section_alloc(conf, name, NULL);
942                         if (!cs) {
943                                 return -1;
944                         }
945                 }
946
947                 /*
948                  *      It's up to the driver to register a destructor
949                  */
950                 if (inst->module->mod_instantiate(cs, inst->config) < 0) {
951                         return -1;
952                 }
953         }
954
955         inst->lf = fr_logfile_init(inst);
956         if (!inst->lf) {
957                 cf_log_err_cs(conf, "Failed creating log file context");
958                 return -1;
959         }
960
961         INFO("rlm_sql (%s): Driver %s (module %s) loaded and linked", inst->config->xlat_name,
962              inst->config->sql_driver_name, inst->module->name);
963
964         /*
965          *      Initialise the connection pool for this instance
966          */
967         INFO("rlm_sql (%s): Attempting to connect to database \"%s\"", inst->config->xlat_name, inst->config->sql_db);
968
969         inst->pool = fr_connection_pool_module_init(inst->cs, inst, mod_conn_create, NULL, NULL);
970         if (!inst->pool) return -1;
971
972         if (inst->config->groupmemb_query &&
973             inst->config->groupmemb_query[0]) {
974                 paircompare_register(dict_attrbyvalue(PW_SQL_GROUP, 0),
975                                 dict_attrbyvalue(PW_USER_NAME, 0), false, sql_groupcmp, inst);
976         }
977
978         if (inst->config->do_clients) {
979                 if (generate_sql_clients(inst) == -1){
980                         ERROR("Failed to load clients from SQL");
981                         return -1;
982                 }
983         }
984
985         return RLM_MODULE_OK;
986 }
987
988
989 static rlm_rcode_t CC_HINT(nonnull) mod_authorize(void *instance, REQUEST *request)
990 {
991         rlm_rcode_t rcode = RLM_MODULE_NOOP;
992
993         rlm_sql_t *inst = instance;
994         rlm_sql_handle_t  *handle;
995
996         VALUE_PAIR *check_tmp = NULL;
997         VALUE_PAIR *reply_tmp = NULL;
998         VALUE_PAIR *user_profile = NULL;
999
1000         bool    user_found = false;
1001
1002         sql_fall_through_t do_fall_through = FALL_THROUGH_DEFAULT;
1003
1004         int     rows;
1005
1006         char    *expanded = NULL;
1007
1008         rad_assert(request->packet != NULL);
1009         rad_assert(request->reply != NULL);
1010
1011         if (!inst->config->authorize_check_query && !inst->config->authorize_reply_query &&
1012             !inst->config->read_groups && !inst->config->read_profiles) {
1013                 RWDEBUG("No authorization checks configured, returning noop");
1014
1015                 return RLM_MODULE_NOOP;
1016         }
1017
1018         /*
1019          *      Set, escape, and check the user attr here
1020          */
1021         if (sql_set_user(inst, request, NULL) < 0) {
1022                 return RLM_MODULE_FAIL;
1023         }
1024
1025         /*
1026          *      Reserve a socket
1027          *
1028          *      After this point use goto error or goto release to cleanup socket temporary pairlists and
1029          *      temporary attributes.
1030          */
1031         handle = fr_connection_get(inst->pool);
1032         if (!handle) {
1033                 rcode = RLM_MODULE_FAIL;
1034                 goto error;
1035         }
1036
1037         /*
1038          *      Query the check table to find any conditions associated with this user/realm/whatever...
1039          */
1040         if (inst->config->authorize_check_query && *inst->config->authorize_check_query) {
1041                 vp_cursor_t cursor;
1042                 VALUE_PAIR *vp;
1043
1044                 if (radius_axlat(&expanded, request, inst->config->authorize_check_query,
1045                                  sql_escape_func, inst) < 0) {
1046                         REDEBUG("Error generating query");
1047                         rcode = RLM_MODULE_FAIL;
1048                         goto error;
1049                 }
1050
1051                 rows = sql_getvpdata(request, inst, request, &handle, &check_tmp, expanded);
1052                 TALLOC_FREE(expanded);
1053                 if (rows < 0) {
1054                         REDEBUG("SQL query error getting check attributes");
1055                         rcode = RLM_MODULE_FAIL;
1056                         goto error;
1057                 }
1058
1059                 if (rows == 0) goto skipreply;  /* Don't need to free VPs we don't have */
1060
1061                 /*
1062                  *      Only do this if *some* check pairs were returned
1063                  */
1064                 RDEBUG2("User found in radcheck table");
1065                 user_found = true;
1066                 if (paircompare(request, request->packet->vps, check_tmp, &request->reply->vps) != 0) {
1067                         pairfree(&check_tmp);
1068                         check_tmp = NULL;
1069                         goto skipreply;
1070                 }
1071
1072                 RDEBUG2("Conditional check items matched, merging assignment check items");
1073                 RINDENT();
1074                 for (vp = fr_cursor_init(&cursor, &check_tmp);
1075                      vp;
1076                      vp = fr_cursor_next(&cursor)) {
1077                         if (!fr_assignment_op[vp->op]) continue;
1078
1079                         rdebug_pair(2, request, vp);
1080                 }
1081                 REXDENT();
1082                 radius_pairmove(request, &request->config_items, check_tmp, true);
1083
1084                 rcode = RLM_MODULE_OK;
1085                 check_tmp = NULL;
1086         }
1087
1088         if (inst->config->authorize_reply_query && *inst->config->authorize_reply_query) {
1089                 /*
1090                  *      Now get the reply pairs since the paircompare matched
1091                  */
1092                 if (radius_axlat(&expanded, request, inst->config->authorize_reply_query,
1093                                  sql_escape_func, inst) < 0) {
1094                         REDEBUG("Error generating query");
1095                         rcode = RLM_MODULE_FAIL;
1096                         goto error;
1097                 }
1098
1099                 rows = sql_getvpdata(request->reply, inst, request, &handle, &reply_tmp, expanded);
1100                 TALLOC_FREE(expanded);
1101                 if (rows < 0) {
1102                         REDEBUG("SQL query error getting reply attributes");
1103                         rcode = RLM_MODULE_FAIL;
1104                         goto error;
1105                 }
1106
1107                 if (rows == 0) goto skipreply;
1108
1109                 do_fall_through = fall_through(reply_tmp);
1110
1111                 RDEBUG2("User found in radreply table, merging reply items");
1112                 user_found = true;
1113
1114                 rdebug_pair_list(L_DBG_LVL_2, request, reply_tmp);
1115
1116                 radius_pairmove(request, &request->reply->vps, reply_tmp, true);
1117
1118                 rcode = RLM_MODULE_OK;
1119                 reply_tmp = NULL;
1120         }
1121
1122 skipreply:
1123         if ((do_fall_through == FALL_THROUGH_YES) ||
1124             (inst->config->read_groups && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1125                 rlm_rcode_t ret;
1126
1127                 RDEBUG3("... falling-through to group processing");
1128                 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1129                 switch (ret) {
1130                 /*
1131                  *      Nothing bad happened, continue...
1132                  */
1133                 case RLM_MODULE_UPDATED:
1134                         rcode = RLM_MODULE_UPDATED;
1135                         /* FALL-THROUGH */
1136                 case RLM_MODULE_OK:
1137                         if (rcode != RLM_MODULE_UPDATED) {
1138                                 rcode = RLM_MODULE_OK;
1139                         }
1140                         /* FALL-THROUGH */
1141                 case RLM_MODULE_NOOP:
1142                         user_found = true;
1143                         break;
1144
1145                 case RLM_MODULE_NOTFOUND:
1146                         break;
1147
1148                 default:
1149                         rcode = ret;
1150                         goto release;
1151                 }
1152         }
1153
1154         /*
1155          *      Repeat the above process with the default profile or User-Profile
1156          */
1157         if ((do_fall_through == FALL_THROUGH_YES) ||
1158             (inst->config->read_profiles && (do_fall_through == FALL_THROUGH_DEFAULT))) {
1159                 rlm_rcode_t ret;
1160
1161                 /*
1162                  *  Check for a default_profile or for a User-Profile.
1163                  */
1164                 RDEBUG3("... falling-through to profile processing");
1165                 user_profile = pairfind(request->config_items, PW_USER_PROFILE, 0, TAG_ANY);
1166
1167                 char const *profile = user_profile ?
1168                                       user_profile->vp_strvalue :
1169                                       inst->config->default_profile;
1170
1171                 if (!profile || !*profile) {
1172                         goto release;
1173                 }
1174
1175                 RDEBUG2("Checking profile %s", profile);
1176
1177                 if (sql_set_user(inst, request, profile) < 0) {
1178                         REDEBUG("Error setting profile");
1179                         rcode = RLM_MODULE_FAIL;
1180                         goto error;
1181                 }
1182
1183                 ret = rlm_sql_process_groups(inst, request, &handle, &do_fall_through);
1184                 switch (ret) {
1185                 /*
1186                  *      Nothing bad happened, continue...
1187                  */
1188                 case RLM_MODULE_UPDATED:
1189                         rcode = RLM_MODULE_UPDATED;
1190                         /* FALL-THROUGH */
1191                 case RLM_MODULE_OK:
1192                         if (rcode != RLM_MODULE_UPDATED) {
1193                                 rcode = RLM_MODULE_OK;
1194                         }
1195                         /* FALL-THROUGH */
1196                 case RLM_MODULE_NOOP:
1197                         user_found = true;
1198                         break;
1199
1200                 case RLM_MODULE_NOTFOUND:
1201                         break;
1202
1203                 default:
1204                         rcode = ret;
1205                         goto release;
1206                 }
1207         }
1208
1209         /*
1210          *      At this point the key (user) hasn't be found in the check table, the reply table
1211          *      or the group mapping table, and there was no matching profile.
1212          */
1213 release:
1214         if (!user_found) {
1215                 rcode = RLM_MODULE_NOTFOUND;
1216         }
1217
1218         fr_connection_release(inst->pool, handle);
1219         sql_unset_user(inst, request);
1220
1221         return rcode;
1222
1223 error:
1224         pairfree(&check_tmp);
1225         pairfree(&reply_tmp);
1226         sql_unset_user(inst, request);
1227
1228         fr_connection_release(inst->pool, handle);
1229
1230         return rcode;
1231 }
1232
1233 /*
1234  *      Generic function for failing between a bunch of queries.
1235  *
1236  *      Uses the same principle as rlm_linelog, expanding the 'reference' config
1237  *      item using xlat to figure out what query it should execute.
1238  *
1239  *      If the reference matches multiple config items, and a query fails or
1240  *      doesn't update any rows, the next matching config item is used.
1241  *
1242  */
1243 static int acct_redundant(rlm_sql_t *inst, REQUEST *request, sql_acct_section_t *section)
1244 {
1245         rlm_rcode_t             rcode = RLM_MODULE_OK;
1246
1247         rlm_sql_handle_t        *handle = NULL;
1248         int                     sql_ret;
1249         int                     numaffected = 0;
1250
1251         CONF_ITEM               *item;
1252         CONF_PAIR               *pair;
1253         char const              *attr = NULL;
1254         char const              *value;
1255
1256         char                    path[MAX_STRING_LEN];
1257         char                    *p = path;
1258         char                    *expanded = NULL;
1259
1260         rad_assert(section);
1261
1262         if (section->reference[0] != '.') {
1263                 *p++ = '.';
1264         }
1265
1266         if (radius_xlat(p, sizeof(path) - (p - path), request, section->reference, NULL, NULL) < 0) {
1267                 rcode = RLM_MODULE_FAIL;
1268
1269                 goto finish;
1270         }
1271
1272         item = cf_reference_item(NULL, section->cs, path);
1273         if (!item) {
1274                 rcode = RLM_MODULE_FAIL;
1275
1276                 goto finish;
1277         }
1278
1279         if (cf_item_is_section(item)){
1280                 REDEBUG("Sections are not supported as references");
1281                 rcode = RLM_MODULE_FAIL;
1282
1283                 goto finish;
1284         }
1285
1286         pair = cf_itemtopair(item);
1287         attr = cf_pair_attr(pair);
1288
1289         RDEBUG2("Using query template '%s'", attr);
1290
1291         handle = fr_connection_get(inst->pool);
1292         if (!handle) {
1293                 rcode = RLM_MODULE_FAIL;
1294
1295                 goto finish;
1296         }
1297
1298         sql_set_user(inst, request, NULL);
1299
1300         while (true) {
1301                 value = cf_pair_value(pair);
1302                 if (!value) {
1303                         RDEBUG("Ignoring null query");
1304                         rcode = RLM_MODULE_NOOP;
1305
1306                         goto finish;
1307                 }
1308
1309                 if (radius_axlat(&expanded, request, value, sql_escape_func, inst) < 0) {
1310                         rcode = RLM_MODULE_FAIL;
1311
1312                         goto finish;
1313                 }
1314
1315                 if (!*expanded) {
1316                         RDEBUG("Ignoring null query");
1317                         rcode = RLM_MODULE_NOOP;
1318                         talloc_free(expanded);
1319
1320                         goto finish;
1321                 }
1322
1323                 rlm_sql_query_log(inst, request, section, expanded);
1324
1325                 /*
1326                  *  If rlm_sql_query cannot use the socket it'll try and
1327                  *  reconnect. Reconnecting will automatically release
1328                  *  the current socket, and try to select a new one.
1329                  *
1330                  *  If we get RLM_SQL_RECONNECT it means all connections in the pool
1331                  *  were exhausted, and we couldn't create a new connection,
1332                  *  so we do not need to call fr_connection_release.
1333                  */
1334                 sql_ret = rlm_sql_query(&handle, inst, expanded);
1335                 TALLOC_FREE(expanded);
1336                 if (sql_ret == RLM_SQL_RECONNECT) {
1337                         rcode = RLM_MODULE_FAIL;
1338                         goto finish;
1339                 }
1340                 rad_assert(handle);
1341
1342                 /*
1343                  *  Assume all other errors are incidental, and just meant our
1344                  *  operation failed and its not a client or SQL syntax error.
1345                  *
1346                  *  @fixme We should actually be able to distinguish between key
1347                  *  constraint violations (which we expect) and other errors.
1348                  */
1349                 if (sql_ret == RLM_SQL_OK) {
1350                         numaffected = (inst->module->sql_affected_rows)(handle, inst->config);
1351                         if (numaffected > 0) {
1352                                 break;  /* A query succeeded, were done! */
1353                         }
1354
1355                         RDEBUG("No records updated");
1356                 }
1357
1358                 (inst->module->sql_finish_query)(handle, inst->config);
1359
1360                 /*
1361                  *  We assume all entries with the same name form a redundant
1362                  *  set of queries.
1363                  */
1364                 pair = cf_pair_find_next(section->cs, pair, attr);
1365
1366                 if (!pair) {
1367                         RDEBUG("No additional queries configured");
1368                         rcode = RLM_MODULE_NOOP;
1369
1370                         goto finish;
1371                 }
1372
1373                 RDEBUG("Trying next query...");
1374         }
1375
1376         (inst->module->sql_finish_query)(handle, inst->config);
1377
1378 finish:
1379         talloc_free(expanded);
1380         fr_connection_release(inst->pool, handle);
1381         sql_unset_user(inst, request);
1382
1383         return rcode;
1384 }
1385
1386 #ifdef WITH_ACCOUNTING
1387
1388 /*
1389  *      Accounting: Insert or update session data in our sql table
1390  */
1391 static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST * request) {
1392         rlm_sql_t *inst = instance;
1393
1394         if (inst->config->accounting.reference_cp) {
1395                 return acct_redundant(inst, request, &inst->config->accounting);
1396         }
1397
1398         return RLM_MODULE_NOOP;
1399 }
1400
1401 #endif
1402
1403 #ifdef WITH_SESSION_MGMT
1404 /*
1405  *      See if a user is already logged in. Sets request->simul_count to the
1406  *      current session count for this user.
1407  *
1408  *      Check twice. If on the first pass the user exceeds his
1409  *      max. number of logins, do a second pass and validate all
1410  *      logins by querying the terminal server (using eg. SNMP).
1411  */
1412
1413 static rlm_rcode_t CC_HINT(nonnull) mod_checksimul(void *instance, REQUEST * request) {
1414         rlm_rcode_t             rcode = RLM_MODULE_OK;
1415         rlm_sql_handle_t        *handle = NULL;
1416         rlm_sql_t               *inst = instance;
1417         rlm_sql_row_t           row;
1418         int                     check = 0;
1419         uint32_t                ipno = 0;
1420         char const              *call_num = NULL;
1421         VALUE_PAIR              *vp;
1422         int                     ret;
1423         uint32_t                nas_addr = 0;
1424         uint32_t                nas_port = 0;
1425
1426         char                    *expanded = NULL;
1427
1428         /* If simul_count_query is not defined, we don't do any checking */
1429         if (!inst->config->simul_count_query || (inst->config->simul_count_query[0] == '\0')) {
1430                 return RLM_MODULE_NOOP;
1431         }
1432
1433         if((!request->username) || (request->username->length == '\0')) {
1434                 REDEBUG("Zero Length username not permitted");
1435
1436                 return RLM_MODULE_INVALID;
1437         }
1438
1439
1440         if(sql_set_user(inst, request, NULL) < 0) {
1441                 return RLM_MODULE_FAIL;
1442         }
1443
1444         if (radius_axlat(&expanded, request, inst->config->simul_count_query, sql_escape_func, inst) < 0) {
1445                 sql_unset_user(inst, request);
1446                 return RLM_MODULE_FAIL;
1447         }
1448
1449         /* initialize the sql socket */
1450         handle = fr_connection_get(inst->pool);
1451         if (!handle) {
1452                 talloc_free(expanded);
1453                 sql_unset_user(inst, request);
1454                 return RLM_MODULE_FAIL;
1455         }
1456
1457         if (rlm_sql_select_query(&handle, inst, expanded) != RLM_SQL_OK) {
1458                 rcode = RLM_MODULE_FAIL;
1459                 goto finish;
1460         }
1461
1462         ret = rlm_sql_fetch_row(&handle, inst);
1463         if (ret != 0) {
1464                 rcode = RLM_MODULE_FAIL;
1465                 goto finish;
1466         }
1467
1468         row = handle->row;
1469         if (!row) {
1470                 rcode = RLM_MODULE_FAIL;
1471                 goto finish;
1472         }
1473
1474         request->simul_count = atoi(row[0]);
1475
1476         (inst->module->sql_finish_select_query)(handle, inst->config);
1477         TALLOC_FREE(expanded);
1478
1479         if (request->simul_count < request->simul_max) {
1480                 rcode = RLM_MODULE_OK;
1481                 goto finish;
1482         }
1483
1484         /*
1485          *      Looks like too many sessions, so let's start verifying
1486          *      them, unless told to rely on count query only.
1487          */
1488         if (!inst->config->simul_verify_query || (inst->config->simul_verify_query[0] == '\0')) {
1489                 rcode = RLM_MODULE_OK;
1490
1491                 goto finish;
1492         }
1493
1494         if (radius_axlat(&expanded, request, inst->config->simul_verify_query, sql_escape_func, inst) < 0) {
1495                 rcode = RLM_MODULE_FAIL;
1496
1497                 goto finish;
1498         }
1499
1500         if (rlm_sql_select_query(&handle, inst, expanded) != RLM_SQL_OK) goto finish;
1501
1502         /*
1503          *      Setup some stuff, like for MPP detection.
1504          */
1505         request->simul_count = 0;
1506
1507         if ((vp = pairfind(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
1508                 ipno = vp->vp_ipaddr;
1509         }
1510
1511         if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
1512                 call_num = vp->vp_strvalue;
1513         }
1514
1515         while (rlm_sql_fetch_row(&handle, inst) == 0) {
1516                 row = handle->row;
1517                 if (!row) {
1518                         break;
1519                 }
1520
1521                 if (!row[2]){
1522                         RDEBUG("Cannot zap stale entry. No username present in entry");
1523                         rcode = RLM_MODULE_FAIL;
1524
1525                         goto finish;
1526                 }
1527
1528                 if (!row[1]){
1529                         RDEBUG("Cannot zap stale entry. No session id in entry");
1530                         rcode = RLM_MODULE_FAIL;
1531
1532                         goto finish;
1533                 }
1534
1535                 if (row[3]) {
1536                         nas_addr = inet_addr(row[3]);
1537                 }
1538
1539                 if (row[4]) {
1540                         nas_port = atoi(row[4]);
1541                 }
1542
1543                 check = rad_check_ts(nas_addr, nas_port, row[2], row[1]);
1544                 if (check == 0) {
1545                         /*
1546                          *      Stale record - zap it.
1547                          */
1548                         if (inst->config->deletestalesessions == true) {
1549                                 uint32_t framed_addr = 0;
1550                                 char proto = 0;
1551                                 int sess_time = 0;
1552
1553                                 if (row[5])
1554                                         framed_addr = inet_addr(row[5]);
1555                                 if (row[7]){
1556                                         if (strcmp(row[7], "PPP") == 0)
1557                                                 proto = 'P';
1558                                         else if (strcmp(row[7], "SLIP") == 0)
1559                                                 proto = 'S';
1560                                 }
1561                                 if (row[8])
1562                                         sess_time = atoi(row[8]);
1563                                 session_zap(request, nas_addr, nas_port,
1564                                             row[2], row[1], framed_addr,
1565                                             proto, sess_time);
1566                         }
1567                 }
1568                 else if (check == 1) {
1569                         /*
1570                          *      User is still logged in.
1571                          */
1572                         ++request->simul_count;
1573
1574                         /*
1575                          *      Does it look like a MPP attempt?
1576                          */
1577                         if (row[5] && ipno && inet_addr(row[5]) == ipno) {
1578                                 request->simul_mpp = 2;
1579                         } else if (row[6] && call_num && !strncmp(row[6],call_num,16)) {
1580                                 request->simul_mpp = 2;
1581                         }
1582                 } else {
1583                         /*
1584                          *      Failed to check the terminal server for
1585                          *      duplicate logins: return an error.
1586                          */
1587                         REDEBUG("Failed to check the terminal server for user '%s'.", row[2]);
1588
1589                         rcode = RLM_MODULE_FAIL;
1590                         goto finish;
1591                 }
1592         }
1593
1594         finish:
1595
1596         (inst->module->sql_finish_select_query)(handle, inst->config);
1597         fr_connection_release(inst->pool, handle);
1598         talloc_free(expanded);
1599         sql_unset_user(inst, request);
1600
1601         /*
1602          *      The Auth module apparently looks at request->simul_count,
1603          *      not the return value of this module when deciding to deny
1604          *      a call for too many sessions.
1605          */
1606         return rcode;
1607 }
1608 #endif
1609
1610 /*
1611  *      Postauth: Write a record of the authentication attempt
1612  */
1613 static rlm_rcode_t CC_HINT(nonnull) mod_post_auth(void *instance, REQUEST * request) {
1614         rlm_sql_t *inst = instance;
1615
1616         if (inst->config->postauth.reference_cp) {
1617                 return acct_redundant(inst, request, &inst->config->postauth);
1618         }
1619
1620         return RLM_MODULE_NOOP;
1621 }
1622
1623 /*
1624  *      Execute postauth_query after authentication
1625  */
1626
1627
1628 /* globally exported name */
1629 module_t rlm_sql = {
1630         RLM_MODULE_INIT,
1631         "SQL",
1632         RLM_TYPE_THREAD_SAFE,   /* type: reserved */
1633         sizeof(rlm_sql_t),
1634         module_config,
1635         mod_instantiate,        /* instantiation */
1636         mod_detach,             /* detach */
1637         {
1638                 NULL,                   /* authentication */
1639                 mod_authorize,  /* authorization */
1640                 NULL,                   /* preaccounting */
1641 #ifdef WITH_ACCOUNTING
1642                 mod_accounting, /* accounting */
1643 #else
1644                 NULL,
1645 #endif
1646 #ifdef WITH_SESSION_MGMT
1647                 mod_checksimul, /* checksimul */
1648 #else
1649                 NULL,
1650 #endif
1651                 NULL,                   /* pre-proxy */
1652                 NULL,                   /* post-proxy */
1653                 mod_post_auth   /* post-auth */
1654         },
1655 };