Move ident.h macros into build.h
[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 *sql_conn_create(void *ctx)
55 {
56         int rcode;
57         rlm_sql_t *inst = ctx;
58         rlm_sql_handle_t *handle;
59
60         handle = talloc_zero(ctx, 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                 exec_trigger(NULL, inst->cs, "modules.sql.open", FALSE);
79                 
80                 return handle;
81         }
82
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 /*
93  *      @todo Calls to this should eventually go away.
94  */
95 static int sql_conn_delete(UNUSED void *ctx, void *conn)
96 {       
97         return talloc_free(conn);
98 }
99
100 /*************************************************************************
101  *
102  *      Function: sql_socket_pool_init
103  *
104  *      Purpose: Connect to the sql server, if possible
105  *
106  *************************************************************************/
107 int sql_socket_pool_init(rlm_sql_t * inst)
108 {
109         inst->pool = fr_connection_pool_init(inst->cs, inst,
110                                              sql_conn_create,
111                                              NULL,
112                                              sql_conn_delete);
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         const char *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                 radlog(L_ERR, "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));
186                 if ((operator < T_OP_ADD) ||
187                     (operator > T_OP_CMP_EQ)) {
188                         radlog(L_ERR, "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                 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
198                 radlog(L_ERR, "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));
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                 radlog(L_ERR, "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                         radlog(L_ERR, "rlm_sql: Error marking pair for xlat");
253                         
254                         pairbasicfree(vp);
255                         return -1;
256                 }
257         } else {
258                 if (pairparsevalue(vp, value) < 0) {
259                         radlog(L_ERR, "rlm_sql: Error parsing value");
260                         
261                         pairbasicfree(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         
296         if (ret < 0) {
297                 radlog(L_ERR, "rlm_sql (%s): Error fetching row: %s", inst->config->xlat_name,
298                            (inst->module->sql_error)(*handle, inst->config));
299         }
300
301         return ret;
302 }
303
304 /*************************************************************************
305  *
306  *      Function: rlm_sql_query
307  *
308  *      Purpose: call the module's sql_query and implement re-connect
309  *
310  *************************************************************************/
311 int rlm_sql_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char *query)
312 {
313         int ret;
314
315         /*
316          *      If there's no query, return an error.
317          */
318         if (!query || !*query) {
319                 return -1;
320         }
321
322         if (!*handle || !(*handle)->conn) {
323                 ret = -1;
324                 goto sql_down;
325         }
326         
327         while (1) {
328                 DEBUG("rlm_sql (%s): Executing query: '%s'",
329                       inst->config->xlat_name, query);
330
331                 ret = (inst->module->sql_query)(*handle, inst->config, query);
332                 /*
333                  * Run through all available sockets until we exhaust all existing
334                  * sockets in the pool and fail to establish a *new* connection.
335                  */
336                 if (ret == SQL_DOWN) {
337                         sql_down:
338                         *handle = fr_connection_reconnect(inst->pool, *handle);
339                         if (!*handle) return SQL_DOWN;
340                         
341                         continue;
342                 }
343                 
344                 if (ret < 0) {
345                         radlog(L_ERR,
346                                    "rlm_sql (%s): Database query error: '%s'",
347                                    inst->config->xlat_name,
348                                    (inst->module->sql_error)(*handle, inst->config));
349                 }
350                 
351                 return ret;
352         }
353 }
354
355 /*************************************************************************
356  *
357  *      Function: rlm_sql_select_query
358  *
359  *      Purpose: call the module's sql_select_query and implement re-connect
360  *
361  *************************************************************************/
362 int rlm_sql_select_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char *query)
363 {
364         int ret;
365
366         /*
367          *      If there's no query, return an error.
368          */
369         if (!query || !*query) {
370                 return -1;
371         }
372
373         if (!*handle || !(*handle)->conn) {
374                 ret = -1;
375                 goto sql_down;
376         }
377         
378         while (1) {
379                 DEBUG("rlm_sql (%s): Executing query: '%s'",
380                       inst->config->xlat_name, query);
381
382                 ret = (inst->module->sql_select_query)(*handle, inst->config, query);
383                 /*
384                  * Run through all available sockets until we exhaust all existing
385                  * sockets in the pool and fail to establish a *new* connection.
386                  */
387                 if (ret == SQL_DOWN) {
388                         sql_down:
389                         *handle = fr_connection_reconnect(inst->pool, *handle);
390                         if (!*handle) return SQL_DOWN;
391                         
392                         continue;
393                 }
394                 
395                 if (ret < 0) {
396                         radlog(L_ERR,
397                                    "rlm_sql (%s): Database query error '%s'",
398                                    inst->config->xlat_name,
399                                    (inst->module->sql_error)(*handle, inst->config));
400                 }
401                 
402                 return ret;
403         }
404 }
405
406
407 /*************************************************************************
408  *
409  *      Function: sql_getvpdata
410  *
411  *      Purpose: Get any group check or reply pairs
412  *
413  *************************************************************************/
414 int sql_getvpdata(rlm_sql_t * inst, rlm_sql_handle_t **handle,
415                   TALLOC_CTX *ctx, VALUE_PAIR **pair, char *query)
416 {
417         rlm_sql_row_t row;
418         int     rows = 0;
419
420         if (rlm_sql_select_query(handle, inst, query)) {
421                 return -1;
422         }
423
424         while (rlm_sql_fetch_row(handle, inst) == 0) {
425                 row = (*handle)->row;
426                 if (!row)
427                         break;
428                 if (sql_userparse(ctx, pair, row) != 0) {
429                         radlog(L_ERR, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
430                         
431                         (inst->module->sql_finish_select_query)(*handle, inst->config);
432                         
433                         return -1;
434                 }
435                 rows++;
436         }
437         (inst->module->sql_finish_select_query)(*handle, inst->config);
438
439         return rows;
440 }
441
442 /*
443  *      Log the query to a file.
444  */
445 void rlm_sql_query_log(rlm_sql_t *inst, REQUEST *request,
446                        sql_acct_section_t *section, char *query)
447 {
448         int fd;
449         const char *filename = NULL;
450         char buffer[8192];
451
452         if (section) filename = section->logfile;
453
454         if (!filename) filename = inst->config->logfile;
455
456         if (!filename) return;
457
458         if (!radius_xlat(buffer, sizeof(buffer), filename, request, NULL, NULL)) {
459                 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
460                        inst->config->xlat_name);
461                 return;
462         }
463
464         fd = open(filename, O_WRONLY | O_APPEND | O_CREAT, 0666);
465         if (fd < 0) {
466                 radlog(L_ERR, "rlm_sql (%s): Couldn't open logfile '%s': %s",
467                        inst->config->xlat_name, buffer, strerror(errno));
468                 return;
469         }
470
471         if ((rad_lockfd(fd, MAX_QUERY_LEN) < 0) ||
472             (write(fd, query, strlen(query)) < 0) ||
473             (write(fd, ";\n", 2) < 0)) {
474                 radlog(L_ERR, "rlm_sql (%s): Failed writing to logfile '%s': %s",
475                        inst->config->xlat_name, buffer, strerror(errno));
476         }
477         close(fd);              /* and release the lock */
478 }