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