Create non xlated values too!
[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 #include <freeradius-devel/ident.h>
28 RCSID("$Id$")
29
30 #include        <freeradius-devel/radiusd.h>
31 #include        <freeradius-devel/rad_assert.h>
32
33 #include        <sys/file.h>
34 #include        <sys/stat.h>
35
36 #include        <ctype.h>
37
38 #include        "rlm_sql.h"
39
40 #ifdef HAVE_PTHREAD_H
41 #endif
42
43 static int sql_conn_destructor(void *conn)
44 {
45         rlm_sql_handle_t *handle = conn;
46         rlm_sql_t *inst = handle->inst;
47         
48         rad_assert(inst);
49         
50         exec_trigger(NULL, inst->cs, "modules.sql.close", FALSE);
51
52         if (handle->conn) {
53                 (inst->module->sql_close)(handle, inst->config);
54         }
55         
56         if (inst->module->sql_destroy_socket) {
57                 (inst->module->sql_destroy_socket)(handle, inst->config);
58         }
59         
60         return 0;
61 }
62
63 static void *sql_conn_create(void *ctx)
64 {
65         int rcode;
66         rlm_sql_t *inst = ctx;
67         rlm_sql_handle_t *handle;
68
69         handle = talloc_zero(ctx, rlm_sql_handle_t);
70         
71         /*
72          *      Handle requires a pointer to the SQL inst so the
73          *      destructor has access to the module configuration.
74          */
75         handle->inst = inst;
76         talloc_set_destructor((void *) handle, sql_conn_destructor);
77
78         rcode = (inst->module->sql_init_socket)(handle, inst->config);
79         if (rcode == 0) {
80                 exec_trigger(NULL, inst->cs, "modules.sql.open", FALSE);
81                 
82                 return handle;
83         }
84
85         radlog(L_ERR, "rlm_sql (%s): Error opening connection: %s",
86                inst->config->xlat_name,
87                (inst->module->sql_error)(handle, inst->config));
88
89         exec_trigger(NULL, inst->cs, "modules.sql.fail", TRUE);
90
91         talloc_free(handle);
92         return NULL;
93 }
94
95 /*
96  *      @todo Calls to this should eventually go away.
97  */
98 static int sql_conn_delete(UNUSED void *ctx, void *conn)
99 {       
100         return talloc_free(conn);
101 }
102
103 /*************************************************************************
104  *
105  *      Function: sql_init_socketpool
106  *
107  *      Purpose: Connect to the sql server, if possible
108  *
109  *************************************************************************/
110 int sql_init_socketpool(rlm_sql_t * inst)
111 {
112         inst->pool = fr_connection_pool_init(inst->cs, inst,
113                                              sql_conn_create,
114                                              NULL,
115                                              sql_conn_delete);
116         if (!inst->pool) return -1;
117
118         return 1;
119 }
120
121 /*************************************************************************
122  *
123  *     Function: sql_poolfree
124  *
125  *     Purpose: Clean up and free sql pool
126  *
127  *************************************************************************/
128 void sql_poolfree(rlm_sql_t * inst)
129 {
130         fr_connection_pool_delete(inst->pool);
131 }
132
133
134 /*************************************************************************
135  *
136  *      Function: sql_get_socket
137  *
138  *      Purpose: Return a SQL handle from the connection pool
139  *
140  *************************************************************************/
141 rlm_sql_handle_t * sql_get_socket(rlm_sql_t * inst)
142 {
143         return fr_connection_get(inst->pool);
144 }
145
146 /*************************************************************************
147  *
148  *      Function: sql_release_socket
149  *
150  *      Purpose: Frees a SQL handle back to the connection pool
151  *
152  *************************************************************************/
153 int sql_release_socket(rlm_sql_t * inst, rlm_sql_handle_t * handle)
154 {
155         fr_connection_release(inst->pool, handle);
156         return 0;
157 }
158
159
160 /*************************************************************************
161  *
162  *      Function: sql_userparse
163  *
164  *      Purpose: Read entries from the database and fill VALUE_PAIR structures
165  *
166  *************************************************************************/
167 int sql_userparse(VALUE_PAIR **head, rlm_sql_row_t row)
168 {
169         VALUE_PAIR *vp;
170         const char *ptr, *value;
171         char buf[MAX_STRING_LEN];
172         char do_xlat = 0;
173         FR_TOKEN token, operator = T_EOL;
174
175         /*
176          *      Verify the 'Attribute' field
177          */
178         if (row[2] == NULL || row[2][0] == '\0') {
179                 radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
180                 return -1;
181         }
182
183         /*
184          *      Verify the 'op' field
185          */
186         if (row[4] != NULL && row[4][0] != '\0') {
187                 ptr = row[4];
188                 operator = gettoken(&ptr, buf, sizeof(buf));
189                 if ((operator < T_OP_ADD) ||
190                     (operator > T_OP_CMP_EQ)) {
191                         radlog(L_ERR, "rlm_sql: Invalid operator \"%s\" for attribute %s", row[4], row[2]);
192                         return -1;
193                 }
194
195         } else {
196                 /*
197                  *  Complain about empty or invalid 'op' field
198                  */
199                 operator = T_OP_CMP_EQ;
200                 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
201                 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
202         }
203
204         /*
205          *      The 'Value' field may be empty or NULL
206          */
207         value = row[3];
208         /*
209          *      If we have a new-style quoted string, where the
210          *      *entire* string is quoted, do xlat's.
211          */
212         if (row[3] != NULL &&
213            ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
214            (row[3][0] == row[3][strlen(row[3])-1])) {
215
216                 token = gettoken(&value, buf, sizeof(buf));
217                 switch (token) {
218                         /*
219                          *      Take the unquoted string.
220                          */
221                 case T_SINGLE_QUOTED_STRING:
222                 case T_DOUBLE_QUOTED_STRING:
223                         value = buf;
224                         break;
225
226                         /*
227                          *      Mark the pair to be allocated later.
228                          */
229                 case T_BACK_QUOTED_STRING:
230                         value = NULL;
231                         do_xlat = 1;
232                         break;
233
234                         /*
235                          *      Keep the original string.
236                          */
237                 default:
238                         value = row[3];
239                         break;
240                 }
241         }
242
243         /*
244          *      Create the pair
245          */
246         vp = pairmake(row[2], NULL, operator);
247         if (!vp) {
248                 radlog(L_ERR, "rlm_sql: Failed to create the pair: %s",
249                        fr_strerror());
250                 return -1;
251         }
252         
253         if (do_xlat) {
254                 if (pairmark_xlat(vp, value) < 0) {
255                         radlog(L_ERR, "rlm_sql: Error marking pair for xlat");
256                         
257                         pairbasicfree(vp);
258                         return -1;
259                 }
260         } else {
261                 if (pairparsevalue(vp, value) < 0) {
262                         radlog(L_ERR, "rlm_sql: Error parsing value");
263                         
264                         pairbasicfree(vp);
265                         return -1;
266                 }
267         }
268
269         /*
270          *      Add the pair into the packet
271          */
272         pairadd(head, vp);
273         return 0;
274 }
275
276
277 /*************************************************************************
278  *
279  *      Function: rlm_sql_fetch_row
280  *
281  *      Purpose: call the module's sql_fetch_row and implement re-connect
282  *
283  *************************************************************************/
284 int rlm_sql_fetch_row(rlm_sql_handle_t **handle, rlm_sql_t *inst)
285 {
286         int ret;
287
288         if (!*handle || !(*handle)->conn) {
289                 return -1;
290         }
291         
292         /* 
293          * We can't implement reconnect logic here, because the caller may require
294          * the original connection to free up queries or result sets associated with
295          * that connection.
296          */
297         ret = (inst->module->sql_fetch_row)(*handle, inst->config);
298         
299         if (ret < 0) {
300                 radlog(L_ERR, "rlm_sql (%s): Error fetching row: %s", inst->config->xlat_name,
301                            (inst->module->sql_error)(*handle, inst->config));
302         }
303
304         return ret;
305 }
306
307 /*************************************************************************
308  *
309  *      Function: rlm_sql_query
310  *
311  *      Purpose: call the module's sql_query and implement re-connect
312  *
313  *************************************************************************/
314 int rlm_sql_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char *query)
315 {
316         int ret;
317
318         /*
319          *      If there's no query, return an error.
320          */
321         if (!query || !*query) {
322                 return -1;
323         }
324
325         if (!*handle || !(*handle)->conn) {
326                 ret = -1;
327                 goto sql_down;
328         }
329         
330         while (1) {
331                 DEBUG("rlm_sql (%s): Executing query: '%s'",
332                       inst->config->xlat_name, query);
333
334                 ret = (inst->module->sql_query)(*handle, inst->config, query);
335                 /*
336                  * Run through all available sockets until we exhaust all existing
337                  * sockets in the pool and fail to establish a *new* connection.
338                  */
339                 if (ret == SQL_DOWN) {
340                         sql_down:
341                         *handle = fr_connection_reconnect(inst->pool, *handle);
342                         if (!*handle) return SQL_DOWN;
343                         
344                         continue;
345                 }
346                 
347                 if (ret < 0) {
348                         radlog(L_ERR,
349                                    "rlm_sql (%s): Database query error: '%s'",
350                                    inst->config->xlat_name,
351                                    (inst->module->sql_error)(*handle, inst->config));
352                 }
353                 
354                 return ret;
355         }
356 }
357
358 /*************************************************************************
359  *
360  *      Function: rlm_sql_select_query
361  *
362  *      Purpose: call the module's sql_select_query and implement re-connect
363  *
364  *************************************************************************/
365 int rlm_sql_select_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char *query)
366 {
367         int ret;
368
369         /*
370          *      If there's no query, return an error.
371          */
372         if (!query || !*query) {
373                 return -1;
374         }
375
376         if (!*handle || !(*handle)->conn) {
377                 ret = -1;
378                 goto sql_down;
379         }
380         
381         while (1) {
382                 DEBUG("rlm_sql (%s): Executing query: '%s'",
383                       inst->config->xlat_name, query);
384
385                 ret = (inst->module->sql_select_query)(*handle, inst->config, query);
386                 /*
387                  * Run through all available sockets until we exhaust all existing
388                  * sockets in the pool and fail to establish a *new* connection.
389                  */
390                 if (ret == SQL_DOWN) {
391                         sql_down:
392                         *handle = fr_connection_reconnect(inst->pool, *handle);
393                         if (!*handle) return SQL_DOWN;
394                         
395                         continue;
396                 }
397                 
398                 if (ret < 0) {
399                         radlog(L_ERR,
400                                    "rlm_sql (%s): Database query error '%s'",
401                                    inst->config->xlat_name,
402                                    (inst->module->sql_error)(*handle, inst->config));
403                 }
404                 
405                 return ret;
406         }
407 }
408
409
410 /*************************************************************************
411  *
412  *      Function: sql_getvpdata
413  *
414  *      Purpose: Get any group check or reply pairs
415  *
416  *************************************************************************/
417 int sql_getvpdata(rlm_sql_t * inst, rlm_sql_handle_t **handle, VALUE_PAIR **pair, char *query)
418 {
419         rlm_sql_row_t row;
420         int     rows = 0;
421
422         if (rlm_sql_select_query(handle, inst, query)) {
423                 return -1;
424         }
425
426         while (rlm_sql_fetch_row(handle, inst) == 0) {
427                 row = (*handle)->row;
428                 if (!row)
429                         break;
430                 if (sql_userparse(pair, row) != 0) {
431                         radlog(L_ERR, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
432                         
433                         (inst->module->sql_finish_select_query)(*handle, inst->config);
434                         
435                         return -1;
436                 }
437                 rows++;
438         }
439         (inst->module->sql_finish_select_query)(*handle, inst->config);
440
441         return rows;
442 }
443
444 /*
445  *      Log the query to a file.
446  */
447 void rlm_sql_query_log(rlm_sql_t *inst, REQUEST *request,
448                        sql_acct_section_t *section, char *query)
449 {
450         int fd;
451         const char *filename = NULL;
452         char buffer[8192];
453
454         if (section) filename = section->logfile;
455
456         if (!filename) filename = inst->config->logfile;
457
458         if (!filename) return;
459
460         if (!radius_xlat(buffer, sizeof(buffer), filename, request, NULL, NULL)) {
461                 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
462                        inst->config->xlat_name);
463                 return;
464         }
465
466         fd = open(filename, O_WRONLY | O_APPEND | O_CREAT, 0666);
467         if (fd < 0) {
468                 radlog(L_ERR, "rlm_sql (%s): Couldn't open logfile '%s': %s",
469                        inst->config->xlat_name, buffer, strerror(errno));
470                 return;
471         }
472
473         if ((rad_lockfd(fd, MAX_QUERY_LEN) < 0) ||
474             (write(fd, query, strlen(query)) < 0) ||
475             (write(fd, ";\n", 2) < 0)) {
476                 radlog(L_ERR, "rlm_sql (%s): Failed writing to logfile '%s': %s",
477                        inst->config->xlat_name, buffer, strerror(errno));
478         }
479         close(fd);              /* and release the lock */
480 }