mod_conn_create should not be global
[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         { "no more rows",       RLM_SQL_NO_MORE_ROWS    },
53         { NULL, 0 }
54 };
55
56
57 /*************************************************************************
58  *
59  *      Function: sql_fr_pair_list_afrom_str
60  *
61  *      Purpose: Read entries from the database and fill VALUE_PAIR structures
62  *
63  *************************************************************************/
64 int sql_fr_pair_list_afrom_str(TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **head, rlm_sql_row_t row)
65 {
66         VALUE_PAIR *vp;
67         char const *ptr, *value;
68         char buf[MAX_STRING_LEN];
69         char do_xlat = 0;
70         FR_TOKEN token, op = T_EOL;
71
72         /*
73          *      Verify the 'Attribute' field
74          */
75         if (!row[2] || row[2][0] == '\0') {
76                 REDEBUG("Attribute field is empty or NULL, skipping the entire row");
77                 return -1;
78         }
79
80         /*
81          *      Verify the 'op' field
82          */
83         if (row[4] != NULL && row[4][0] != '\0') {
84                 ptr = row[4];
85                 op = gettoken(&ptr, buf, sizeof(buf), false);
86                 if (!fr_assignment_op[op] && !fr_equality_op[op]) {
87                         REDEBUG("Invalid op \"%s\" for attribute %s", row[4], row[2]);
88                         return -1;
89                 }
90
91         } else {
92                 /*
93                  *  Complain about empty or invalid 'op' field
94                  */
95                 op = T_OP_CMP_EQ;
96                 REDEBUG("The op field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
97                 REDEBUG("You MUST FIX THIS if you want the configuration to behave as you expect");
98         }
99
100         /*
101          *      The 'Value' field may be empty or NULL
102          */
103         if (!row[3]) {
104                 REDEBUG("Value field is empty or NULL, skipping the entire row");
105                 return -1;
106         }
107
108         value = row[3];
109
110         /*
111          *      If we have a new-style quoted string, where the
112          *      *entire* string is quoted, do xlat's.
113          */
114         if (row[3] != NULL &&
115            ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
116            (row[3][0] == row[3][strlen(row[3])-1])) {
117
118                 token = gettoken(&value, buf, sizeof(buf), false);
119                 switch (token) {
120                 /*
121                  *      Take the unquoted string.
122                  */
123                 case T_SINGLE_QUOTED_STRING:
124                 case T_DOUBLE_QUOTED_STRING:
125                         value = buf;
126                         break;
127
128                 /*
129                  *      Mark the pair to be allocated later.
130                  */
131                 case T_BACK_QUOTED_STRING:
132                         do_xlat = 1;
133
134                         /* FALL-THROUGH */
135
136                 /*
137                  *      Keep the original string.
138                  */
139                 default:
140                         value = row[3];
141                         break;
142                 }
143         }
144
145         /*
146          *      Create the pair
147          */
148         vp = fr_pair_make(ctx, NULL, row[2], NULL, op);
149         if (!vp) {
150                 REDEBUG("Failed to create the pair: %s", fr_strerror());
151                 return -1;
152         }
153
154         if (do_xlat) {
155                 if (fr_pair_mark_xlat(vp, value) < 0) {
156                         REDEBUG("Error marking pair for xlat: %s", fr_strerror());
157
158                         talloc_free(vp);
159                         return -1;
160                 }
161         } else {
162                 if (fr_pair_value_from_str(vp, value, -1) < 0) {
163                         REDEBUG("Error parsing value: %s", fr_strerror());
164
165                         talloc_free(vp);
166                         return -1;
167                 }
168         }
169
170         /*
171          *      Add the pair into the packet
172          */
173         fr_pair_add(head, vp);
174         return 0;
175 }
176
177 /** Call the driver's sql_fetch_row function
178  *
179  * Calls the driver's sql_fetch_row logging any errors. On success, will
180  * write row data to (*handle)->row.
181  *
182  * @param inst Instance of rlm_sql.
183  * @param request The Current request, may be NULL.
184  * @param handle Handle to retrieve errors for.
185  * @return on success RLM_SQL_OK, other sql_rcode_t constants on error.
186  */
187 sql_rcode_t rlm_sql_fetch_row(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle)
188 {
189         int ret;
190
191         if (!*handle || !(*handle)->conn) return RLM_SQL_ERROR;
192
193         /*
194          *      We can't implement reconnect logic here, because the caller
195          *      may require the original connection to free up queries or
196          *      result sets associated with that connection.
197          */
198         ret = (inst->module->sql_fetch_row)(*handle, inst->config);
199         if (ret < 0) {
200                 MOD_ROPTIONAL(RERROR, ERROR, "Error fetching row");
201
202                 rlm_sql_print_error(inst, request, *handle, false);
203         }
204
205         return ret;
206 }
207
208 /** Retrieve any errors from the SQL driver
209  *
210  * Retrieves errors from the driver from the last operation and writes them to
211  * to request/global log, in the ERROR, WARN, INFO and DEBUG categories.
212  *
213  * @param inst Instance of rlm_sql.
214  * @param request Current request, may be NULL.
215  * @param handle Handle to retrieve errors for.
216  * @param force_debug Force all errors to be logged as debug messages.
217  */
218 void rlm_sql_print_error(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t *handle, bool force_debug)
219 {
220         char const      *driver;
221         sql_log_entry_t log[20];
222         size_t          num, i;
223
224         num = (inst->module->sql_error)(handle->log_ctx, log, (sizeof(log) / sizeof(*log)), handle, inst->config);
225         if (num == 0) {
226                 MOD_ROPTIONAL(RERROR, ERROR, "Unknown error");
227                 return;
228         }
229
230         driver = inst->config->sql_driver_name;
231
232         for (i = 0; i < num; i++) {
233                 if (force_debug) goto debug;
234
235                 switch (log[i].type) {
236                 case L_ERR:
237                         MOD_ROPTIONAL(RERROR, ERROR, "%s: %s", driver, log[i].msg);
238                         break;
239
240                 case L_WARN:
241                         MOD_ROPTIONAL(RWARN, WARN, "%s: %s", driver, log[i].msg);
242                         break;
243
244                 case L_INFO:
245                         MOD_ROPTIONAL(RINFO, INFO, "%s: %s", driver, log[i].msg);
246                         break;
247
248                 case L_DBG:
249                 default:
250                 debug:
251                         MOD_ROPTIONAL(RDEBUG, DEBUG, "%s: %s", driver, log[i].msg);
252                         break;
253                 }
254         }
255
256         talloc_free_children(handle->log_ctx);
257 }
258
259 /** Call the driver's sql_query method, reconnecting if necessary.
260  *
261  * @note Caller must call (inst->module->sql_finish_query)(handle, inst->config);
262  *      after they're done with the result.
263  *
264  * @param handle to query the database with. *handle should not be NULL, as this indicates
265  *      previous reconnection attempt has failed.
266  * @param request Current request.
267  * @param inst rlm_sql instance data.
268  * @param query to execute. Should not be zero length.
269  * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required
270  *      (also sets *handle = NULL), RLM_SQL_QUERY_INVALID/RLM_SQL_ERROR on invalid query or
271  *      connection error, RLM_SQL_ALT_QUERY on constraints violation.
272  */
273 sql_rcode_t rlm_sql_query(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle, char const *query)
274 {
275         int ret = RLM_SQL_ERROR;
276         int i, count;
277
278         /* Caller should check they have a valid handle */
279         rad_assert(*handle);
280
281         /* There's no query to run, return an error */
282         if (query[0] == '\0') {
283                 if (request) REDEBUG("Zero length query");
284                 return RLM_SQL_QUERY_INVALID;
285         }
286
287         /*
288          *  inst->pool may be NULL is this function is called by mod_conn_create.
289          */
290         count = inst->pool ? fr_connection_pool_get_num(inst->pool) : 0;
291
292         /*
293          *  Here we try with each of the existing connections, then try to create
294          *  a new connection, then give up.
295          */
296         for (i = 0; i < (count + 1); i++) {
297                 MOD_ROPTIONAL(RDEBUG2, DEBUG2, "Executing query: %s", query);
298
299                 ret = (inst->module->sql_query)(*handle, inst->config, query);
300                 switch (ret) {
301                 case RLM_SQL_OK:
302                         break;
303
304                 /*
305                  *      Run through all available sockets until we exhaust all existing
306                  *      sockets in the pool and fail to establish a *new* connection.
307                  */
308                 case RLM_SQL_RECONNECT:
309                         *handle = fr_connection_reconnect(inst->pool, *handle);
310                         /* Reconnection failed */
311                         if (!*handle) return RLM_SQL_RECONNECT;
312                         /* Reconnection succeeded, try again with the new handle */
313                         continue;
314
315                 /*
316                  *      These are bad and should make rlm_sql return invalid
317                  */
318                 case RLM_SQL_QUERY_INVALID:
319                         rlm_sql_print_error(inst, request, *handle, false);
320                         (inst->module->sql_finish_query)(*handle, inst->config);
321                         break;
322
323                 /*
324                  *      Server or client errors.
325                  *
326                  *      If the driver claims to be able to distinguish between
327                  *      duplicate row errors and other errors, and we hit a
328                  *      general error treat it as a failure.
329                  *
330                  *      Otherwise rewrite it to RLM_SQL_ALT_QUERY.
331                  */
332                 case RLM_SQL_ERROR:
333                         if (inst->module->flags & RLM_SQL_RCODE_FLAGS_ALT_QUERY) {
334                                 rlm_sql_print_error(inst, request, *handle, false);
335                                 (inst->module->sql_finish_query)(*handle, inst->config);
336                                 break;
337                         }
338                         ret = RLM_SQL_ALT_QUERY;
339                         /* FALL-THROUGH */
340
341                 /*
342                  *      Driver suggested using an alternative query
343                  */
344                 case RLM_SQL_ALT_QUERY:
345                         rlm_sql_print_error(inst, request, *handle, true);
346                         (inst->module->sql_finish_query)(*handle, inst->config);
347                         break;
348
349                 }
350
351                 return ret;
352         }
353
354         MOD_ROPTIONAL(RERROR, ERROR, "Hit reconnection limit");
355
356         return RLM_SQL_ERROR;
357 }
358
359 /** Call the driver's sql_select_query method, reconnecting if necessary.
360  *
361  * @note Caller must call (inst->module->sql_finish_select_query)(handle, inst->config);
362  *      after they're done with the result.
363  *
364  * @param inst rlm_sql instance data.
365  * @param request Current request.
366  * @param handle to query the database with. *handle should not be NULL, as this indicates
367  *        previous reconnection attempt has failed.
368  * @param query to execute. Should not be zero length.
369  * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required (also sets *handle = NULL),
370  *         RLM_SQL_QUERY_INVALID/RLM_SQL_ERROR on invalid query or connection error.
371  */
372 sql_rcode_t rlm_sql_select_query(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,  char const *query)
373 {
374         int ret = RLM_SQL_ERROR;
375         int i, count;
376
377         /* Caller should check they have a valid handle */
378         rad_assert(*handle);
379
380         /* There's no query to run, return an error */
381         if (query[0] == '\0') {
382                 if (request) REDEBUG("Zero length query");
383
384                 return RLM_SQL_QUERY_INVALID;
385         }
386
387         /*
388          *  inst->pool may be NULL is this function is called by mod_conn_create.
389          */
390         count = inst->pool ? fr_connection_pool_get_num(inst->pool) : 0;
391
392         /*
393          *  For sanity, for when no connections are viable, and we can't make a new one
394          */
395         for (i = 0; i < (count + 1); i++) {
396                 MOD_ROPTIONAL(RDEBUG2, DEBUG2, "Executing select query: %s", query);
397
398                 ret = (inst->module->sql_select_query)(*handle, inst->config, query);
399                 switch (ret) {
400                 case RLM_SQL_OK:
401                         break;
402
403                 /*
404                  *      Run through all available sockets until we exhaust all existing
405                  *      sockets in the pool and fail to establish a *new* connection.
406                  */
407                 case RLM_SQL_RECONNECT:
408                         *handle = fr_connection_reconnect(inst->pool, *handle);
409                         /* Reconnection failed */
410                         if (!*handle) return RLM_SQL_RECONNECT;
411                         /* Reconnection succeeded, try again with the new handle */
412                         continue;
413
414                 case RLM_SQL_QUERY_INVALID:
415                 case RLM_SQL_ERROR:
416                 default:
417                         rlm_sql_print_error(inst, request, *handle, false);
418                         (inst->module->sql_finish_select_query)(*handle, inst->config);
419                         break;
420                 }
421
422                 return ret;
423         }
424
425         MOD_ROPTIONAL(RERROR, ERROR, "Hit reconnection limit");
426
427         return RLM_SQL_ERROR;
428 }
429
430
431 /*************************************************************************
432  *
433  *      Function: sql_getvpdata
434  *
435  *      Purpose: Get any group check or reply pairs
436  *
437  *************************************************************************/
438 int sql_getvpdata(TALLOC_CTX *ctx, rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
439                   VALUE_PAIR **pair, char const *query)
440 {
441         rlm_sql_row_t   row;
442         int             rows = 0;
443         sql_rcode_t     rcode;
444
445         rad_assert(request);
446
447         rcode = rlm_sql_select_query(inst, request, handle, query);
448         if (rcode != RLM_SQL_OK) return -1; /* error handled by rlm_sql_select_query */
449
450         while (rlm_sql_fetch_row(inst, request, handle) == RLM_SQL_OK) {
451                 row = (*handle)->row;
452                 if (!row) break;
453                 if (sql_fr_pair_list_afrom_str(ctx, request, pair, row) != 0) {
454                         REDEBUG("Error parsing user data from database result");
455
456                         (inst->module->sql_finish_select_query)(*handle, inst->config);
457
458                         return -1;
459                 }
460                 rows++;
461         }
462         (inst->module->sql_finish_select_query)(*handle, inst->config);
463
464         return rows;
465 }
466
467 /*
468  *      Log the query to a file.
469  */
470 void rlm_sql_query_log(rlm_sql_t *inst, REQUEST *request,
471                        sql_acct_section_t *section, char const *query)
472 {
473         int fd;
474         char const *filename = NULL;
475         char *expanded = NULL;
476         size_t len;
477         bool failed = false;    /* Write the log message outside of the critical region */
478
479         filename = inst->config->logfile;
480         if (section && section->logfile) filename = section->logfile;
481
482         if (!filename || !*filename) {
483                 return;
484         }
485
486         if (radius_axlat(&expanded, request, filename, NULL, NULL) < 0) {
487                 return;
488         }
489
490         fd = exfile_open(inst->ef, filename, 0640, true);
491         if (fd < 0) {
492                 ERROR("rlm_sql (%s): Couldn't open logfile '%s': %s", inst->name,
493                       expanded, fr_syserror(errno));
494
495                 talloc_free(expanded);
496                 return;
497         }
498
499         len = strlen(query);
500         if ((write(fd, query, len) < 0) || (write(fd, ";\n", 2) < 0)) {
501                 failed = true;
502         }
503
504         if (failed) {
505                 ERROR("rlm_sql (%s): Failed writing to logfile '%s': %s", inst->name, expanded,
506                       fr_syserror(errno));
507         }
508
509         talloc_free(expanded);
510         exfile_close(inst->ef, fd);
511 }