e364fe527dca75b9032af083c37f27709d7decc7
[freeradius.git] / src / modules / rlm_sql / sql.c
1 /*
2  *  sql.c               rlm_sql - FreeRADIUS SQL Module
3  *              Main code directly taken from ICRADIUS
4  *
5  * Version:     $Id$
6  *
7  *   This program is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU General Public License as published by
9  *   the Free Software Foundation; either version 2 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This program is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with this program; if not, write to the Free Software
19  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  * Copyright 2001,2006  The FreeRADIUS server project
22  * Copyright 2000  Mike Machado <mike@innercite.com>
23  * Copyright 2000  Alan DeKok <aland@ox.org>
24  * Copyright 2001  Chad Miller <cmiller@surfsouth.com>
25  */
26
27 RCSID("$Id$")
28
29 #include        <freeradius-devel/radiusd.h>
30 #include        <freeradius-devel/rad_assert.h>
31
32 #include        <sys/file.h>
33 #include        <sys/stat.h>
34
35 #include        <ctype.h>
36
37 #include        "rlm_sql.h"
38
39 #ifdef HAVE_PTHREAD_H
40 #endif
41
42 /*
43  *      Translate rlm_sql rcodes to humanly
44  *      readable reason strings.
45  */
46 const FR_NAME_NUMBER sql_rcode_table[] = {
47         { "success",            RLM_SQL_OK              },
48         { "need alt query",     RLM_SQL_ALT_QUERY       },
49         { "server error",       RLM_SQL_ERROR           },
50         { "query invalid",      RLM_SQL_QUERY_INVALID   },
51         { "no connection",      RLM_SQL_RECONNECT       },
52         { NULL, 0 }
53 };
54
55
56 void *mod_conn_create(TALLOC_CTX *ctx, void *instance)
57 {
58         int rcode;
59         rlm_sql_t *inst = instance;
60         rlm_sql_handle_t *handle;
61
62         /*
63          *      Connections cannot be alloced from the inst or
64          *      pool contexts due to threading issues.
65          */
66         handle = talloc_zero(ctx, rlm_sql_handle_t);
67         if (!handle) return NULL;
68
69         handle->log_ctx = talloc_pool(handle, 2048);
70         if (!handle->log_ctx) {
71                 talloc_free(handle);
72                 return NULL;
73         }
74
75         /*
76          *      Handle requires a pointer to the SQL inst so the
77          *      destructor has access to the module configuration.
78          */
79         handle->inst = inst;
80
81         rcode = (inst->module->sql_socket_init)(handle, inst->config);
82         if (rcode != 0) {
83         fail:
84                 /*
85                  *      Destroy any half opened connections.
86                  */
87                 talloc_free(handle);
88                 return NULL;
89         }
90
91         if (inst->config->connect_query) {
92                 if (rlm_sql_select_query(inst, NULL, &handle, inst->config->connect_query) != RLM_SQL_OK) goto fail;
93                 (inst->module->sql_finish_select_query)(handle, inst->config);
94         }
95
96         return handle;
97 }
98
99 /*************************************************************************
100  *
101  *      Function: sql_fr_pair_list_afrom_str
102  *
103  *      Purpose: Read entries from the database and fill VALUE_PAIR structures
104  *
105  *************************************************************************/
106 int sql_fr_pair_list_afrom_str(TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **head, rlm_sql_row_t row)
107 {
108         VALUE_PAIR *vp;
109         char const *ptr, *value;
110         char buf[MAX_STRING_LEN];
111         char do_xlat = 0;
112         FR_TOKEN token, op = T_EOL;
113
114         /*
115          *      Verify the 'Attribute' field
116          */
117         if (!row[2] || row[2][0] == '\0') {
118                 REDEBUG("Attribute field is empty or NULL, skipping the entire row");
119                 return -1;
120         }
121
122         /*
123          *      Verify the 'op' field
124          */
125         if (row[4] != NULL && row[4][0] != '\0') {
126                 ptr = row[4];
127                 op = gettoken(&ptr, buf, sizeof(buf), false);
128                 if (!fr_assignment_op[op] && !fr_equality_op[op]) {
129                         REDEBUG("Invalid op \"%s\" for attribute %s", row[4], row[2]);
130                         return -1;
131                 }
132
133         } else {
134                 /*
135                  *  Complain about empty or invalid 'op' field
136                  */
137                 op = T_OP_CMP_EQ;
138                 REDEBUG("The op field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
139                 REDEBUG("You MUST FIX THIS if you want the configuration to behave as you expect");
140         }
141
142         /*
143          *      The 'Value' field may be empty or NULL
144          */
145         if (!row[3]) {
146                 REDEBUG("Value field is empty or NULL, skipping the entire row");
147                 return -1;
148         }
149
150         /*
151          *      If we have a new-style quoted string, where the
152          *      *entire* string is quoted, do xlat's.
153          */
154         if (row[3] != NULL &&
155            ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
156            (row[3][0] == row[3][strlen(row[3])-1])) {
157
158                 token = gettoken(&value, buf, sizeof(buf), false);
159                 switch (token) {
160                 /*
161                  *      Take the unquoted string.
162                  */
163                 case T_SINGLE_QUOTED_STRING:
164                 case T_DOUBLE_QUOTED_STRING:
165                         value = buf;
166                         break;
167
168                 /*
169                  *      Mark the pair to be allocated later.
170                  */
171                 case T_BACK_QUOTED_STRING:
172                         do_xlat = 1;
173
174                         /* FALL-THROUGH */
175
176                 /*
177                  *      Keep the original string.
178                  */
179                 default:
180                         value = row[3];
181                         break;
182                 }
183         }
184
185         /*
186          *      Create the pair
187          */
188         vp = fr_pair_make(ctx, NULL, row[2], NULL, op);
189         if (!vp) {
190                 REDEBUG("Failed to create the pair: %s", fr_strerror());
191                 return -1;
192         }
193
194         if (do_xlat) {
195                 if (fr_pair_mark_xlat(vp, value) < 0) {
196                         REDEBUG("Error marking pair for xlat: %s", fr_strerror());
197
198                         talloc_free(vp);
199                         return -1;
200                 }
201         } else {
202                 if (fr_pair_value_from_str(vp, value, -1) < 0) {
203                         REDEBUG("Error parsing value: %s", fr_strerror());
204
205                         talloc_free(vp);
206                         return -1;
207                 }
208         }
209
210         /*
211          *      Add the pair into the packet
212          */
213         fr_pair_add(head, vp);
214         return 0;
215 }
216
217 /** Call the driver's sql_fetch_row function
218  *
219  * Calls the driver's sql_fetch_row logging any errors. On success, will
220  * write row data to (*handle)->row.
221  *
222  * @param inst Instance of rlm_sql.
223  * @param request The Current request, may be NULL.
224  * @param handle Handle to retrieve errors for.
225  * @return on success RLM_SQL_OK, other sql_rcode_t constants on error.
226  */
227 sql_rcode_t rlm_sql_fetch_row(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle)
228 {
229         int ret;
230
231         if (!*handle || !(*handle)->conn) return RLM_SQL_ERROR;
232
233         /*
234          *      We can't implement reconnect logic here, because the caller
235          *      may require the original connection to free up queries or
236          *      result sets associated with that connection.
237          */
238         ret = (inst->module->sql_fetch_row)(*handle, inst->config);
239         if (ret < 0) {
240                 MOD_ROPTIONAL(RERROR, ERROR, "Error fetching row");
241
242                 rlm_sql_print_error(inst, request, *handle, false);
243         }
244
245         return ret;
246 }
247
248 /** Retrieve any errors from the SQL driver
249  *
250  * Retrieves errors from the driver from the last operation and writes them to
251  * to request/global log, in the ERROR, WARN, INFO and DEBUG categories.
252  *
253  * @param inst Instance of rlm_sql.
254  * @param request Current request, may be NULL.
255  * @param handle Handle to retrieve errors for.
256  * @param force_debug Force all errors to be logged as debug messages.
257  */
258 void rlm_sql_print_error(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t *handle, bool force_debug)
259 {
260         char const      *driver;
261         sql_log_entry_t log[20];
262         size_t          num, i;
263
264         num = (inst->module->sql_error)(handle->log_ctx, log, (sizeof(log) / sizeof(*log)), handle, inst->config);
265         if (num == 0) {
266                 MOD_ROPTIONAL(RERROR, ERROR, "Unknown error");
267                 return;
268         }
269
270         driver = inst->config->sql_driver_name;
271
272         for (i = 0; i < num; i++) {
273                 if (force_debug) goto debug;
274
275                 switch (log[i].type) {
276                 case L_ERR:
277                         MOD_ROPTIONAL(RERROR, ERROR, "%s: %s", driver, log[i].msg);
278                         break;
279
280                 case L_WARN:
281                         MOD_ROPTIONAL(RWARN, WARN, "%s: %s", driver, log[i].msg);
282                         break;
283
284                 case L_INFO:
285                         MOD_ROPTIONAL(RINFO, INFO, "%s: %s", driver, log[i].msg);
286                         break;
287
288                 case L_DBG:
289                 default:
290                 debug:
291                         MOD_ROPTIONAL(RDEBUG, DEBUG, "%s: %s", driver, log[i].msg);
292                         break;
293                 }
294         }
295
296         talloc_free_children(handle->log_ctx);
297 }
298
299 /** Call the driver's sql_query method, reconnecting if necessary.
300  *
301  * @note Caller must call (inst->module->sql_finish_query)(handle, inst->config);
302  *      after they're done with the result.
303  *
304  * @param handle to query the database with. *handle should not be NULL, as this indicates
305  *      previous reconnection attempt has failed.
306  * @param request Current request.
307  * @param inst rlm_sql instance data.
308  * @param query to execute. Should not be zero length.
309  * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required
310  *      (also sets *handle = NULL), RLM_SQL_QUERY_INVALID/RLM_SQL_ERROR on invalid query or
311  *      connection error, RLM_SQL_ALT_QUERY on constraints violation.
312  */
313 sql_rcode_t rlm_sql_query(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle, char const *query)
314 {
315         int ret = RLM_SQL_ERROR;
316         int i, count;
317
318         /* Caller should check they have a valid handle */
319         rad_assert(*handle);
320
321         /* There's no query to run, return an error */
322         if (query[0] == '\0') {
323                 if (request) REDEBUG("Zero length query");
324                 return RLM_SQL_QUERY_INVALID;
325         }
326
327         /*
328          *  inst->pool may be NULL is this function is called by mod_conn_create.
329          */
330         count = inst->pool ? fr_connection_pool_get_num(inst->pool) : 0;
331
332         /*
333          *  Here we try with each of the existing connections, then try to create
334          *  a new connection, then give up.
335          */
336         for (i = 0; i < (count + 1); i++) {
337                 MOD_ROPTIONAL(RDEBUG2, DEBUG2, "Executing query: %s", query);
338
339                 ret = (inst->module->sql_query)(*handle, inst->config, query);
340                 switch (ret) {
341                 case RLM_SQL_OK:
342                         break;
343
344                 /*
345                  *      Run through all available sockets until we exhaust all existing
346                  *      sockets in the pool and fail to establish a *new* connection.
347                  */
348                 case RLM_SQL_RECONNECT:
349                         *handle = fr_connection_reconnect(inst->pool, *handle);
350                         /* Reconnection failed */
351                         if (!*handle) return RLM_SQL_RECONNECT;
352                         /* Reconnection succeeded, try again with the new handle */
353                         continue;
354
355                 /*
356                  *      These are bad and should make rlm_sql return invalid
357                  */
358                 case RLM_SQL_QUERY_INVALID:
359                         rlm_sql_print_error(inst, request, *handle, false);
360                         (inst->module->sql_finish_query)(*handle, inst->config);
361                         break;
362
363                 /*
364                  *      Server or client errors.
365                  *
366                  *      If the driver claims to be able to distinguish between
367                  *      duplicate row errors and other errors, and we hit a
368                  *      general error treat it as a failure.
369                  *
370                  *      Otherwise rewrite it to RLM_SQL_ALT_QUERY.
371                  */
372                 case RLM_SQL_ERROR:
373                         if (inst->module->flags & RLM_SQL_RCODE_FLAGS_ALT_QUERY) {
374                                 rlm_sql_print_error(inst, request, *handle, false);
375                                 (inst->module->sql_finish_query)(*handle, inst->config);
376                                 break;
377                         }
378                         ret = RLM_SQL_ALT_QUERY;
379                         /* FALL-THROUGH */
380
381                 /*
382                  *      Driver suggested using an alternative query
383                  */
384                 case RLM_SQL_ALT_QUERY:
385                         rlm_sql_print_error(inst, request, *handle, true);
386                         (inst->module->sql_finish_query)(*handle, inst->config);
387                         break;
388
389                 }
390
391                 return ret;
392         }
393
394         MOD_ROPTIONAL(RERROR, ERROR, "Hit reconnection limit");
395
396         return RLM_SQL_ERROR;
397 }
398
399 /** Call the driver's sql_select_query method, reconnecting if necessary.
400  *
401  * @note Caller must call (inst->module->sql_finish_select_query)(handle, inst->config);
402  *      after they're done with the result.
403  *
404  * @param inst rlm_sql instance data.
405  * @param request Current request.
406  * @param handle to query the database with. *handle should not be NULL, as this indicates
407  *        previous reconnection attempt has failed.
408  * @param query to execute. Should not be zero length.
409  * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required (also sets *handle = NULL),
410  *         RLM_SQL_QUERY_INVALID/RLM_SQL_ERROR on invalid query or connection error.
411  */
412 sql_rcode_t rlm_sql_select_query(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,  char const *query)
413 {
414         int ret = RLM_SQL_ERROR;
415         int i, count;
416
417         /* Caller should check they have a valid handle */
418         rad_assert(*handle);
419
420         /* There's no query to run, return an error */
421         if (query[0] == '\0') {
422                 if (request) REDEBUG("Zero length query");
423
424                 return RLM_SQL_QUERY_INVALID;
425         }
426
427         /*
428          *  inst->pool may be NULL is this function is called by mod_conn_create.
429          */
430         count = inst->pool ? fr_connection_pool_get_num(inst->pool) : 0;
431
432         /*
433          *  For sanity, for when no connections are viable, and we can't make a new one
434          */
435         for (i = 0; i < (count + 1); i++) {
436                 MOD_ROPTIONAL(RDEBUG2, DEBUG2, "Executing select query: %s", query);
437
438                 ret = (inst->module->sql_select_query)(*handle, inst->config, query);
439                 switch (ret) {
440                 case RLM_SQL_OK:
441                         break;
442
443                 /*
444                  *      Run through all available sockets until we exhaust all existing
445                  *      sockets in the pool and fail to establish a *new* connection.
446                  */
447                 case RLM_SQL_RECONNECT:
448                         *handle = fr_connection_reconnect(inst->pool, *handle);
449                         /* Reconnection failed */
450                         if (!*handle) return RLM_SQL_RECONNECT;
451                         /* Reconnection succeeded, try again with the new handle */
452                         continue;
453
454                 case RLM_SQL_QUERY_INVALID:
455                 case RLM_SQL_ERROR:
456                 default:
457                         rlm_sql_print_error(inst, request, *handle, false);
458                         (inst->module->sql_finish_select_query)(*handle, inst->config);
459                         break;
460                 }
461
462                 return ret;
463         }
464
465         MOD_ROPTIONAL(RERROR, ERROR, "Hit reconnection limit");
466
467         return RLM_SQL_ERROR;
468 }
469
470
471 /*************************************************************************
472  *
473  *      Function: sql_getvpdata
474  *
475  *      Purpose: Get any group check or reply pairs
476  *
477  *************************************************************************/
478 int sql_getvpdata(TALLOC_CTX *ctx, rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
479                   VALUE_PAIR **pair, char const *query)
480 {
481         rlm_sql_row_t   row;
482         int             rows = 0;
483         sql_rcode_t     rcode;
484
485         rad_assert(request);
486
487         rcode = rlm_sql_select_query(inst, request, handle, query);
488         if (rcode != RLM_SQL_OK) return -1; /* error handled by rlm_sql_select_query */
489
490         while (rlm_sql_fetch_row(inst, request, handle) == 0) {
491                 row = (*handle)->row;
492                 if (!row) break;
493                 if (sql_fr_pair_list_afrom_str(ctx, request, pair, row) != 0) {
494                         REDEBUG("Error parsing user data from database result");
495
496                         (inst->module->sql_finish_select_query)(*handle, inst->config);
497
498                         return -1;
499                 }
500                 rows++;
501         }
502         (inst->module->sql_finish_select_query)(*handle, inst->config);
503
504         return rows;
505 }
506
507 /*
508  *      Log the query to a file.
509  */
510 void rlm_sql_query_log(rlm_sql_t *inst, REQUEST *request,
511                        sql_acct_section_t *section, char const *query)
512 {
513         int fd;
514         char const *filename = NULL;
515         char *expanded = NULL;
516         size_t len;
517         bool failed = false;    /* Write the log message outside of the critical region */
518
519         filename = inst->config->logfile;
520         if (section && section->logfile) filename = section->logfile;
521
522         if (!filename || !*filename) {
523                 return;
524         }
525
526         if (radius_axlat(&expanded, request, filename, NULL, NULL) < 0) {
527                 return;
528         }
529
530         fd = exfile_open(inst->ef, filename, 0640, true);
531         if (fd < 0) {
532                 ERROR("rlm_sql (%s): Couldn't open logfile '%s': %s", inst->name,
533                       expanded, fr_syserror(errno));
534
535                 talloc_free(expanded);
536                 return;
537         }
538
539         len = strlen(query);
540         if ((write(fd, query, len) < 0) || (write(fd, ";\n", 2) < 0)) {
541                 failed = true;
542         }
543
544         if (failed) {
545                 ERROR("rlm_sql (%s): Failed writing to logfile '%s': %s", inst->name, expanded,
546                       fr_syserror(errno));
547         }
548
549         talloc_free(expanded);
550         exfile_close(inst->ef, fd);
551 }