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