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