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