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