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 _mod_conn_free(rlm_sql_handle_t *conn)
44 rlm_sql_t *inst = conn->inst;
48 exec_trigger(NULL, inst->cs, "modules.sql.close", false);
53 void *mod_conn_create(TALLOC_CTX *ctx, void *instance)
56 rlm_sql_t *inst = instance;
57 rlm_sql_handle_t *handle;
60 * Connections cannot be alloced from the inst or
61 * pool contexts due to threading issues.
63 handle = talloc_zero(ctx, rlm_sql_handle_t);
64 if (!handle) return NULL;
67 * Handle requires a pointer to the SQL inst so the
68 * destructor has access to the module configuration.
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.
78 talloc_set_destructor(handle, _mod_conn_free);
80 rcode = (inst->module->sql_socket_init)(handle, inst->config);
83 exec_trigger(NULL, inst->cs, "modules.sql.fail", true);
86 * Destroy any half opened connections.
92 if (inst->config->open_query) {
93 if (rlm_sql_select_query(&handle, inst, inst->config->open_query)) {
96 (inst->module->sql_finish_select_query)(handle, inst->config);
99 exec_trigger(NULL, inst->cs, "modules.sql.open", false);
103 /*************************************************************************
105 * Function: sql_userparse
107 * Purpose: Read entries from the database and fill VALUE_PAIR structures
109 *************************************************************************/
110 int sql_userparse(TALLOC_CTX *ctx, VALUE_PAIR **head, rlm_sql_row_t row)
113 char const *ptr, *value;
114 char buf[MAX_STRING_LEN];
116 FR_TOKEN token, operator = T_EOL;
119 * Verify the 'Attribute' field
121 if (!row[2] || row[2][0] == '\0') {
122 ERROR("rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row");
127 * Verify the 'op' field
129 if (row[4] != NULL && row[4][0] != '\0') {
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]);
140 * Complain about empty or invalid 'op' field
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");
148 * The 'Value' field may be empty or NULL
152 * If we have a new-style quoted string, where the
153 * *entire* string is quoted, do xlat's.
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])) {
159 token = gettoken(&value, buf, sizeof(buf), false);
162 * Take the unquoted string.
164 case T_SINGLE_QUOTED_STRING:
165 case T_DOUBLE_QUOTED_STRING:
170 * Mark the pair to be allocated later.
172 case T_BACK_QUOTED_STRING:
178 * Keep the original string.
189 vp = pairmake(ctx, NULL, row[2], NULL, operator);
191 ERROR("rlm_sql: Failed to create the pair: %s",
197 if (pairmark_xlat(vp, value) < 0) {
198 ERROR("rlm_sql: Error marking pair for xlat");
204 if (pairparsevalue(vp, value, -1) < 0) {
205 ERROR("rlm_sql: Error parsing value: %s", fr_strerror());
213 * Add the pair into the packet
220 /*************************************************************************
222 * Function: rlm_sql_fetch_row
224 * Purpose: call the module's sql_fetch_row and implement re-connect
226 *************************************************************************/
227 int rlm_sql_fetch_row(rlm_sql_handle_t **handle, rlm_sql_t *inst)
231 if (!*handle || !(*handle)->conn) {
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
240 ret = (inst->module->sql_fetch_row)(*handle, inst->config);
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>");
250 static void rlm_sql_query_error(rlm_sql_handle_t *handle, rlm_sql_t *inst)
254 p = (inst->module->sql_error)(handle, inst->config);
256 ERROR("rlm_sql (%s): Unknown query error", inst->config->xlat_name);
261 * Some drivers are nice and provide us with a ^ pointer to
262 * the place in the query string where the error occurred.
264 * For this to be useful we need to split log messages on
265 * \n and output each of the lines individually.
267 while ((q = strchr(p, '\n'))) {
268 ERROR("rlm_sql (%s): %.*s", inst->config->xlat_name, (int) (q - p), p);
273 ERROR("rlm_sql (%s): %s", inst->config->xlat_name, p);
277 static void rlm_sql_query_debug(rlm_sql_handle_t *handle, rlm_sql_t *inst)
281 p = (inst->module->sql_error)(handle, inst->config);
287 * Some drivers are nice and provide us with a ^ pointer to
288 * the place in the query string where the error occurred.
290 * For this to be useful we need to split log messages on
291 * \n and output each of the lines individually.
293 while ((q = strchr(p, '\n'))) {
294 DEBUG2("rlm_sql (%s): %.*s", inst->config->xlat_name, (int) (q - p), p);
299 DEBUG2("rlm_sql (%s): %s", inst->config->xlat_name, p);
303 /** Call the driver's sql_query method, reconnecting if necessary.
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
313 sql_rcode_t rlm_sql_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char const *query)
315 int ret = RLM_SQL_ERROR;
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;
324 /* There's no handle, we need a new one */
325 if (!*handle) return RLM_SQL_RECONNECT;
328 * inst->pool may be NULL is this function is called by mod_conn_create.
330 count = inst->pool ? fr_connection_get_num(inst->pool) : 0;
333 * Here we try with each of the existing connections, then try to create
334 * a new connection, then give up.
336 for (i = 0; i < (count + 1); i++) {
337 DEBUG("rlm_sql (%s): Executing query: '%s'", inst->config->xlat_name, query);
339 ret = (inst->module->sql_query)(*handle, inst->config, query);
345 * Run through all available sockets until we exhaust all existing
346 * sockets in the pool and fail to establish a *new* connection.
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 */
355 case RLM_SQL_QUERY_ERROR:
357 rlm_sql_query_error(*handle, inst);
360 case RLM_SQL_DUPLICATE:
361 rlm_sql_query_debug(*handle, inst);
369 ERROR("rlm_sql (%s): Hit reconnection limit", inst->config->xlat_name);
371 return RLM_SQL_ERROR;
374 /** Call the driver's sql_select_query method, reconnecting if necessary.
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.
383 sql_rcode_t rlm_sql_select_query(rlm_sql_handle_t **handle, rlm_sql_t *inst, char const *query)
385 int ret = RLM_SQL_ERROR;
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;
395 * inst->pool may be NULL is this function is called by mod_conn_create.
397 count = inst->pool ? fr_connection_get_num(inst->pool) : 0;
400 * For sanity, for when no connections are viable, and we can't make a new one
402 for (i = 0; i < (count + 1); i++) {
403 DEBUG("rlm_sql (%s): Executing query: '%s'", inst->config->xlat_name, query);
405 ret = (inst->module->sql_select_query)(*handle, inst->config, query);
411 * Run through all available sockets until we exhaust all existing
412 * sockets in the pool and fail to establish a *new* connection.
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 */
421 case RLM_SQL_QUERY_ERROR:
424 rlm_sql_query_error(*handle, inst);
431 ERROR("rlm_sql (%s): Hit reconnection limit", inst->config->xlat_name);
433 return RLM_SQL_ERROR;
437 /*************************************************************************
439 * Function: sql_getvpdata
441 * Purpose: Get any group check or reply pairs
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)
451 rcode = rlm_sql_select_query(handle, inst, query);
452 if (rcode != RLM_SQL_OK) return -1; /* error handled by rlm_sql_select_query */
454 while (rlm_sql_fetch_row(handle, inst) == 0) {
455 row = (*handle)->row;
457 if (sql_userparse(ctx, pair, row) != 0) {
458 REDEBUG("Error parsing user data from database result");
460 (inst->module->sql_finish_select_query)(*handle, inst->config);
466 (inst->module->sql_finish_select_query)(*handle, inst->config);
472 * Log the query to a file.
474 void rlm_sql_query_log(rlm_sql_t *inst, REQUEST *request,
475 sql_acct_section_t *section, char const *query)
478 char const *filename = NULL;
479 char *expanded = NULL;
481 bool failed = false; /* Write the log message outside of the critical region */
484 filename = section->logfile;
486 filename = inst->config->logfile;
493 if (radius_axlat(&expanded, request, filename, NULL, NULL) < 0) {
497 fd = exfile_open(inst->ef, filename, 0640);
499 ERROR("rlm_sql (%s): Couldn't open logfile '%s': %s", inst->config->xlat_name,
500 expanded, fr_syserror(errno));
502 talloc_free(expanded);
507 if ((write(fd, query, len) < 0) || (write(fd, ";\n", 2) < 0)) {
512 ERROR("rlm_sql (%s): Failed writing to logfile '%s': %s", inst->config->xlat_name, expanded,
516 talloc_free(expanded);
517 exfile_close(inst->ef, fd);