2 * sql.c rlm_sql - FreeRADIUS SQL Module
3 * Main code directly taken from ICRADIUS
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.
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.
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
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>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/rad_assert.h>
42 static int sql_conn_destructor(void *conn)
44 rlm_sql_handle_t *handle = conn;
45 rlm_sql_t *inst = handle->inst;
49 exec_trigger(NULL, inst->cs, "modules.sql.close", false);
54 static void *mod_conn_create(void *instance)
57 rlm_sql_t *inst = instance;
58 rlm_sql_handle_t *handle;
60 handle = talloc_zero(instance, rlm_sql_handle_t);
63 * Handle requires a pointer to the SQL inst so the
64 * destructor has access to the module configuration.
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.
74 talloc_set_destructor((void *) handle, sql_conn_destructor);
76 rcode = (inst->module->sql_socket_init)(handle, inst->config);
79 exec_trigger(NULL, inst->cs, "modules.sql.fail", true);
82 * Destroy any half opened connections.
88 if (inst->config->open_query && *inst->config->open_query) {
89 if (rlm_sql_select_query(&handle, inst, inst->config->open_query)) {
92 (inst->module->sql_finish_select_query)(handle, inst->config);
95 exec_trigger(NULL, inst->cs, "modules.sql.open", false);
100 * @todo Calls to this should eventually go away.
102 static int mod_conn_delete(UNUSED void *instance, void *handle)
104 return talloc_free(handle);
107 /*************************************************************************
109 * Function: sql_socket_pool_init
111 * Purpose: Connect to the sql server, if possible
113 *************************************************************************/
114 int sql_socket_pool_init(rlm_sql_t * inst)
116 inst->pool = fr_connection_pool_init(inst->cs, inst,
117 mod_conn_create, NULL, mod_conn_delete,
119 if (!inst->pool) return -1;
124 /*************************************************************************
126 * Function: sql_poolfree
128 * Purpose: Clean up and free sql pool
130 *************************************************************************/
131 void sql_poolfree(rlm_sql_t * inst)
133 fr_connection_pool_delete(inst->pool);
137 /*************************************************************************
139 * Function: sql_get_socket
141 * Purpose: Return a SQL handle from the connection pool
143 *************************************************************************/
144 rlm_sql_handle_t * sql_get_socket(rlm_sql_t * inst)
146 return fr_connection_get(inst->pool);
149 /*************************************************************************
151 * Function: sql_release_socket
153 * Purpose: Frees a SQL handle back to the connection pool
155 *************************************************************************/
156 int sql_release_socket(rlm_sql_t * inst, rlm_sql_handle_t * handle)
158 fr_connection_release(inst->pool, handle);
163 /*************************************************************************
165 * Function: sql_userparse
167 * Purpose: Read entries from the database and fill VALUE_PAIR structures
169 *************************************************************************/
170 int sql_userparse(TALLOC_CTX *ctx, VALUE_PAIR **head, rlm_sql_row_t row)
173 char const *ptr, *value;
174 char buf[MAX_STRING_LEN];
176 FR_TOKEN token, operator = T_EOL;
179 * Verify the 'Attribute' field
181 if (!row[2] || row[2][0] == '\0') {
182 ERROR("rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row");
187 * Verify the 'op' field
189 if (row[4] != NULL && row[4][0] != '\0') {
191 operator = gettoken(&ptr, buf, sizeof(buf), false);
192 if ((operator < T_OP_ADD) ||
193 (operator > T_OP_CMP_EQ)) {
194 ERROR("rlm_sql: Invalid operator \"%s\" for attribute %s", row[4], row[2]);
200 * Complain about empty or invalid 'op' field
202 operator = T_OP_CMP_EQ;
203 ERROR("rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
204 ERROR("rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect");
208 * The 'Value' field may be empty or NULL
212 * If we have a new-style quoted string, where the
213 * *entire* string is quoted, do xlat's.
215 if (row[3] != NULL &&
216 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
217 (row[3][0] == row[3][strlen(row[3])-1])) {
219 token = gettoken(&value, buf, sizeof(buf), false);
222 * Take the unquoted string.
224 case T_SINGLE_QUOTED_STRING:
225 case T_DOUBLE_QUOTED_STRING:
230 * Mark the pair to be allocated later.
232 case T_BACK_QUOTED_STRING:
238 * Keep the original string.
249 vp = pairmake(ctx, NULL, row[2], NULL, operator);
251 ERROR("rlm_sql: Failed to create the pair: %s",
257 if (pairmark_xlat(vp, value) < 0) {
258 ERROR("rlm_sql: Error marking pair for xlat");
264 if (!pairparsevalue(vp, value)) {
265 ERROR("rlm_sql: Error parsing value: %s", fr_strerror());
273 * Add the pair into the packet
280 /*************************************************************************
282 * Function: rlm_sql_fetch_row
284 * Purpose: call the module's sql_fetch_row and implement re-connect
286 *************************************************************************/
287 int rlm_sql_fetch_row(rlm_sql_handle_t **handle, rlm_sql_t *inst)
291 if (!*handle || !(*handle)->conn) {
296 * We can't implement reconnect logic here, because the caller may require
297 * the original connection to free up queries or result sets associated with
300 ret = (inst->module->sql_fetch_row)(*handle, inst->config);
302 char const *error = (inst->module->sql_error)(*handle, inst->config);
303 ERROR("rlm_sql (%s): Error fetching row: %s",
304 inst->config->xlat_name, error ? error : "<UNKNOWN>");
310 static void rlm_sql_query_error(rlm_sql_handle_t *handle, rlm_sql_t *inst)
314 p = (inst->module->sql_error)(handle, inst->config);
316 ERROR("rlm_sql (%s): Unknown query error", inst->config->xlat_name);
321 * Some drivers are nice and provide us with a ^ pointer to
322 * the place in the query string where the error occurred.
324 * For this to be useful we need to split log messages on
325 * \n and output each of the lines individually.
327 while ((q = strchr(p, '\n'))) {
328 ERROR("rlm_sql (%s): %.*s", inst->config->xlat_name, (int) (q - p), p);
333 ERROR("rlm_sql (%s): %s", inst->config->xlat_name, p);
337 static void rlm_sql_query_debug(rlm_sql_handle_t *handle, rlm_sql_t *inst)
341 p = (inst->module->sql_error)(handle, inst->config);
347 * Some drivers are nice and provide us with a ^ pointer to
348 * the place in the query string where the error occurred.
350 * For this to be useful we need to split log messages on
351 * \n and output each of the lines individually.
353 while ((q = strchr(p, '\n'))) {
354 DEBUG2("rlm_sql (%s): %.*s", inst->config->xlat_name, (int) (q - p), p);
359 DEBUG2("rlm_sql (%s): %s", inst->config->xlat_name, p);
363 /** Call the driver's sql_query method, reconnecting if necessary.
365 * @param handle to query the database with. *handle should not be NULL, as this indicates
366 * previous reconnection attempt has failed.
367 * @param inst rlm_sql instance data.
368 * @param query to execute. Should not be zero length.
369 * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required (also sets *handle = NULL),
370 * RLM_SQL_QUERY_ERROR/RLM_SQL_ERROR on invalid query or connection error, RLM_SQL_DUPLICATE on constraints
373 sql_rcode_t rlm_sql_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char const *query)
375 int ret = RLM_SQL_ERROR;
378 /* There's no query to run, return an error */
379 if (query[0] == '\0') return RLM_SQL_QUERY_ERROR;
381 /* There's no handle, we need a new one */
382 if (!*handle) return RLM_SQL_RECONNECT;
384 /* There's a SQL handle but the connection handle has been invalidated */
385 if (!(*handle)->conn) goto sql_down;
387 /* For sanity, for when no connections are viable, and we can't make a new one */
388 for (i = fr_connection_get_num(inst->pool); i >= 0; i--) {
389 DEBUG("rlm_sql (%s): Executing query: '%s'", inst->config->xlat_name, query);
391 ret = (inst->module->sql_query)(*handle, inst->config, query);
397 * Run through all available sockets until we exhaust all existing
398 * sockets in the pool and fail to establish a *new* connection.
400 case RLM_SQL_RECONNECT:
402 *handle = fr_connection_reconnect(inst->pool, *handle);
403 /* Reconnection failed */
404 if (!*handle) return RLM_SQL_RECONNECT;
405 /* Reconnection succeeded, try again with the new handle */
408 case RLM_SQL_QUERY_ERROR:
410 rlm_sql_query_error(*handle, inst);
413 case RLM_SQL_DUPLICATE:
414 rlm_sql_query_debug(*handle, inst);
422 ERROR("rlm_sql (%s): Hit reconnection limit", inst->config->xlat_name);
424 return RLM_SQL_ERROR;
427 /** Call the driver's sql_select_query method, reconnecting if necessary.
429 * @param handle to query the database with. *handle should not be NULL, as this indicates
430 * previous reconnection attempt has failed.
431 * @param inst rlm_sql instance data.
432 * @param query to execute. Should not be zero length.
433 * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required (also sets *handle = NULL),
434 * RLM_SQL_QUERY_ERROR/RLM_SQL_ERROR on invalid query or connection error.
436 sql_rcode_t rlm_sql_select_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char const *query)
438 int ret = RLM_SQL_ERROR;
441 /* There's no query to run, return an error */
442 if (query[0] == '\0') return RLM_SQL_QUERY_ERROR;
444 /* There's no handle, we need a new one */
445 if (!*handle) return RLM_SQL_RECONNECT;
447 /* There's a SQL handle but the connection handle has been invalidated */
448 if (!(*handle)->conn) goto sql_down;
450 /* For sanity, for when no connections are viable, and we can't make a new one */
451 for (i = fr_connection_get_num(inst->pool); i >= 0; i--) {
452 DEBUG("rlm_sql (%s): Executing query: '%s'", inst->config->xlat_name, query);
454 ret = (inst->module->sql_select_query)(*handle, inst->config, query);
460 * Run through all available sockets until we exhaust all existing
461 * sockets in the pool and fail to establish a *new* connection.
463 case RLM_SQL_RECONNECT:
465 *handle = fr_connection_reconnect(inst->pool, *handle);
466 /* Reconnection failed */
467 if (!*handle) return RLM_SQL_RECONNECT;
468 /* Reconnection succeeded, try again with the new handle */
471 case RLM_SQL_QUERY_ERROR:
474 rlm_sql_query_error(*handle, inst);
481 ERROR("rlm_sql (%s): Hit reconnection limit", inst->config->xlat_name);
483 return RLM_SQL_ERROR;
487 /*************************************************************************
489 * Function: sql_getvpdata
491 * Purpose: Get any group check or reply pairs
493 *************************************************************************/
494 int sql_getvpdata(rlm_sql_t * inst, rlm_sql_handle_t **handle,
495 TALLOC_CTX *ctx, VALUE_PAIR **pair, char const *query)
500 if (rlm_sql_select_query(handle, inst, query)) {
504 while (rlm_sql_fetch_row(handle, inst) == 0) {
505 row = (*handle)->row;
508 if (sql_userparse(ctx, pair, row) != 0) {
509 ERROR("rlm_sql (%s): Error parsing user data from database result", inst->config->xlat_name);
511 (inst->module->sql_finish_select_query)(*handle, inst->config);
517 (inst->module->sql_finish_select_query)(*handle, inst->config);
523 * Log the query to a file.
525 void rlm_sql_query_log(rlm_sql_t *inst, REQUEST *request,
526 sql_acct_section_t *section, char const *query)
529 char const *filename = NULL;
530 char *expanded = NULL;
532 bool failed = false; /* Write the log message outside of the critical region */
535 filename = section->logfile;
537 filename = inst->config->logfile;
544 if (radius_axlat(&expanded, request, filename, NULL, NULL) < 0) {
548 fd = fr_logfile_open(inst->lf, filename, 0640);
550 ERROR("rlm_sql (%s): Couldn't open logfile '%s': %s", inst->config->xlat_name,
551 expanded, fr_syserror(errno));
553 talloc_free(expanded);
558 if ((write(fd, query, len) < 0) || (write(fd, ";\n", 2) < 0)) {
563 ERROR("rlm_sql (%s): Failed writing to logfile '%s': %s", inst->config->xlat_name, expanded,
567 talloc_free(expanded);
568 fr_logfile_close(inst->lf, fd);