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;
66 handle->log_ctx = talloc_pool(handle, 2048);
67 if (!handle->log_ctx) {
73 * Handle requires a pointer to the SQL inst so the
74 * destructor has access to the module configuration.
79 * When something frees this handle the destructor set by
80 * the driver will be called first, closing any open sockets.
81 * Then we call our destructor to trigger an modules.sql.close
82 * event, then all the memory is freed.
84 talloc_set_destructor(handle, _mod_conn_free);
86 rcode = (inst->module->sql_socket_init)(handle, inst->config);
89 exec_trigger(NULL, inst->cs, "modules.sql.fail", true);
92 * Destroy any half opened connections.
98 if (inst->config->connect_query) {
99 if (rlm_sql_select_query(inst, NULL, &handle, inst->config->connect_query)) {
102 (inst->module->sql_finish_select_query)(handle, inst->config);
105 exec_trigger(NULL, inst->cs, "modules.sql.open", false);
109 /*************************************************************************
111 * Function: sql_userparse
113 * Purpose: Read entries from the database and fill VALUE_PAIR structures
115 *************************************************************************/
116 int sql_userparse(TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **head, rlm_sql_row_t row)
119 char const *ptr, *value;
120 char buf[MAX_STRING_LEN];
122 FR_TOKEN token, operator = T_EOL;
125 * Verify the 'Attribute' field
127 if (!row[2] || row[2][0] == '\0') {
128 REDEBUG("The 'Attribute' field is empty or NULL, skipping the entire row");
133 * Verify the 'op' field
135 if (row[4] != NULL && row[4][0] != '\0') {
137 operator = gettoken(&ptr, buf, sizeof(buf), false);
138 if ((operator < T_OP_ADD) ||
139 (operator > T_OP_CMP_EQ)) {
140 REDEBUG("Invalid operator \"%s\" for attribute %s", row[4], row[2]);
146 * Complain about empty or invalid 'op' field
148 operator = T_OP_CMP_EQ;
149 REDEBUG("The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
150 REDEBUG("You MUST FIX THIS if you want the configuration to behave as you expect");
154 * The 'Value' field may be empty or NULL
158 * If we have a new-style quoted string, where the
159 * *entire* string is quoted, do xlat's.
161 if (row[3] != NULL &&
162 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
163 (row[3][0] == row[3][strlen(row[3])-1])) {
165 token = gettoken(&value, buf, sizeof(buf), false);
168 * Take the unquoted string.
170 case T_SINGLE_QUOTED_STRING:
171 case T_DOUBLE_QUOTED_STRING:
176 * Mark the pair to be allocated later.
178 case T_BACK_QUOTED_STRING:
184 * Keep the original string.
195 vp = pairmake(ctx, NULL, row[2], NULL, operator);
197 REDEBUG("Failed to create the pair: %s", fr_strerror());
202 if (pairmark_xlat(vp, value) < 0) {
203 REDEBUG("Error marking pair for xlat");
209 if (pairparsevalue(vp, value, -1) < 0) {
210 REDEBUG("Error parsing value: %s", fr_strerror());
218 * Add the pair into the packet
224 /** Call the driver's sql_fetch_row function
226 * Calls the driver's sql_fetch_row logging any errors. On success, will
227 * write row data to (*handle)->row.
229 * @param inst Instance of rlm_sql.
230 * @param request The Current request, may be NULL.
231 * @param handle Handle to retrieve errors for.
232 * @return on success RLM_SQL_OK, other sql_rcode_t constants on error.
234 sql_rcode_t rlm_sql_fetch_row(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle)
238 if (!*handle || !(*handle)->conn) return RLM_SQL_ERROR;
241 * We can't implement reconnect logic here, because the caller
242 * may require the original connection to free up queries or
243 * result sets associated with that connection.
245 ret = (inst->module->sql_fetch_row)(*handle, inst->config);
247 ROPTIONAL(RERROR, ERROR, "Error fetching row");
249 rlm_sql_print_error(inst, request, *handle, false);
255 /** Retrieve any errors from the SQL driver
257 * Retrieves errors from the driver from the last operation and writes them to
258 * to request/global log, in the ERROR, WARN, INFO and DEBUG categories.
260 * @param inst Instance of rlm_sql.
261 * @param request Current request, may be NULL.
262 * @param handle Handle to retrieve errors for.
263 * @param force_debug Force all errors to be logged as debug messages.
265 void rlm_sql_print_error(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t *handle, bool force_debug)
268 sql_log_entry_t log[20];
271 num = (inst->module->sql_error)(handle->log_ctx, log, (sizeof(log) / sizeof(*log)), handle, inst->config);
273 ROPTIONAL(RERROR, ERROR, "Unknown error");
277 driver = inst->config->sql_driver_name;
279 for (i = 0; i < num; i++) {
280 if (force_debug) goto debug;
282 switch (log[i].type) {
284 ROPTIONAL(RERROR, ERROR, "%s: %s", driver, log[i].msg);
288 ROPTIONAL(RWARN, WARN, "%s: %s", driver, log[i].msg);
292 ROPTIONAL(RINFO, INFO, "%s: %s", driver, log[i].msg);
298 ROPTIONAL(RDEBUG, DEBUG, "%s: %s", driver, log[i].msg);
303 talloc_free_children(handle->log_ctx);
306 /** Call the driver's sql_query method, reconnecting if necessary.
308 * @param handle to query the database with. *handle should not be NULL, as this indicates
309 * previous reconnection attempt has failed.
310 * @param request Current request.
311 * @param inst rlm_sql instance data.
312 * @param query to execute. Should not be zero length.
313 * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required (also sets *handle = NULL),
314 * RLM_SQL_QUERY_INVALID/RLM_SQL_ERROR on invalid query or connection error, RLM_SQL_ALT_QUERY on constraints
317 sql_rcode_t rlm_sql_query(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle, char const *query)
319 int ret = RLM_SQL_ERROR;
322 /* There's no query to run, return an error */
323 if (query[0] == '\0') {
324 if (request) REDEBUG("Zero length query");
325 return RLM_SQL_QUERY_INVALID;
328 /* There's no handle, we need a new one */
329 if (!*handle) return RLM_SQL_RECONNECT;
332 * inst->pool may be NULL is this function is called by mod_conn_create.
334 count = inst->pool ? fr_connection_get_num(inst->pool) : 0;
337 * Here we try with each of the existing connections, then try to create
338 * a new connection, then give up.
340 for (i = 0; i < (count + 1); i++) {
341 ROPTIONAL(RDEBUG2, DEBUG2, "Executing query: %s", query);
343 ret = (inst->module->sql_query)(*handle, inst->config, query);
349 * Run through all available sockets until we exhaust all existing
350 * sockets in the pool and fail to establish a *new* connection.
352 case RLM_SQL_RECONNECT:
353 *handle = fr_connection_reconnect(inst->pool, *handle);
354 /* Reconnection failed */
355 if (!*handle) return RLM_SQL_RECONNECT;
356 /* Reconnection succeeded, try again with the new handle */
360 * These are bad and should make rlm_sql return invalid
362 case RLM_SQL_QUERY_INVALID:
363 rlm_sql_print_error(inst, request, *handle, false);
367 * Server or client errors.
369 * If the driver claims to be able to distinguish between
370 * duplicate row errors and other errors, and we hit a
371 * general error treat it as a failure.
373 * Otherwise rewrite it to RLM_SQL_ALT_QUERY.
376 if (inst->module->flags & RLM_SQL_RCODE_FLAGS_ALT_QUERY) {
377 rlm_sql_print_error(inst, request, *handle, false);
380 ret = RLM_SQL_ALT_QUERY;
383 * Driver suggested using an alternative query
385 case RLM_SQL_ALT_QUERY:
386 rlm_sql_print_error(inst, request, *handle, true);
394 ROPTIONAL(RERROR, ERROR, "Hit reconnection limit");
396 return RLM_SQL_ERROR;
399 /** Call the driver's sql_select_query method, reconnecting if necessary.
401 * @param inst rlm_sql instance data.
402 * @param request Current request.
403 * @param handle to query the database with. *handle should not be NULL, as this indicates
404 * previous reconnection attempt has failed.
405 * @param query to execute. Should not be zero length.
406 * @return RLM_SQL_OK on success, RLM_SQL_RECONNECT if a new handle is required (also sets *handle = NULL),
407 * RLM_SQL_QUERY_INVALID/RLM_SQL_ERROR on invalid query or connection error.
409 sql_rcode_t rlm_sql_select_query(rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle, char const *query)
411 int ret = RLM_SQL_ERROR;
414 /* There's no query to run, return an error */
415 if (query[0] == '\0') {
416 if (request) REDEBUG("Zero length query");
418 return RLM_SQL_QUERY_INVALID;
422 * inst->pool may be NULL is this function is called by mod_conn_create.
424 count = inst->pool ? fr_connection_get_num(inst->pool) : 0;
427 * For sanity, for when no connections are viable, and we can't make a new one
429 for (i = 0; i < (count + 1); i++) {
430 ROPTIONAL(RDEBUG2, DEBUG2, "Executing select query: %s", query);
432 ret = (inst->module->sql_select_query)(*handle, inst->config, query);
438 * Run through all available sockets until we exhaust all existing
439 * sockets in the pool and fail to establish a *new* connection.
441 case RLM_SQL_RECONNECT:
442 *handle = fr_connection_reconnect(inst->pool, *handle);
443 /* Reconnection failed */
444 if (!*handle) return RLM_SQL_RECONNECT;
445 /* Reconnection succeeded, try again with the new handle */
448 case RLM_SQL_QUERY_INVALID:
451 rlm_sql_print_error(inst, request, *handle, false);
458 ROPTIONAL(RERROR, ERROR, "Hit reconnection limit");
460 return RLM_SQL_ERROR;
464 /*************************************************************************
466 * Function: sql_getvpdata
468 * Purpose: Get any group check or reply pairs
470 *************************************************************************/
471 int sql_getvpdata(TALLOC_CTX *ctx, rlm_sql_t *inst, REQUEST *request, rlm_sql_handle_t **handle,
472 VALUE_PAIR **pair, char const *query)
480 rcode = rlm_sql_select_query(inst, request, handle, query);
481 if (rcode != RLM_SQL_OK) return -1; /* error handled by rlm_sql_select_query */
483 while (rlm_sql_fetch_row(inst, request, handle) == 0) {
484 row = (*handle)->row;
486 if (sql_userparse(ctx, request, pair, row) != 0) {
487 REDEBUG("Error parsing user data from database result");
489 (inst->module->sql_finish_select_query)(*handle, inst->config);
495 (inst->module->sql_finish_select_query)(*handle, inst->config);
501 * Log the query to a file.
503 void rlm_sql_query_log(rlm_sql_t *inst, REQUEST *request,
504 sql_acct_section_t *section, char const *query)
507 char const *filename = NULL;
508 char *expanded = NULL;
510 bool failed = false; /* Write the log message outside of the critical region */
513 filename = section->logfile;
515 filename = inst->config->logfile;
522 if (radius_axlat(&expanded, request, filename, NULL, NULL) < 0) {
526 fd = exfile_open(inst->ef, filename, 0640, true);
528 ERROR("rlm_sql (%s): Couldn't open logfile '%s': %s", inst->name,
529 expanded, fr_syserror(errno));
531 talloc_free(expanded);
536 if ((write(fd, query, len) < 0) || (write(fd, ";\n", 2) < 0)) {
541 ERROR("rlm_sql (%s): Failed writing to logfile '%s': %s", inst->name, expanded,
545 talloc_free(expanded);
546 exfile_close(inst->ef, fd);