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>
27 #include <freeradius-devel/ident.h>
30 #include <freeradius-devel/radiusd.h>
44 * Connect to a server. If error, set this socket's state to be
45 * "sockunconnected" and set a grace period, during which we won't try
46 * connecting again (to prevent unduly lagging the server and being
47 * impolite to a DB server that may be having other issues). If
48 * successful in connecting, set state to sockconnected.
51 static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst)
54 radlog(L_DBG, "rlm_sql (%s): Attempting to connect %s #%d",
55 inst->config->xlat_name, inst->module->name, sqlsocket->id);
56 rcode = (inst->module->sql_init_socket)(sqlsocket, inst->config);
58 radlog(L_DBG, "rlm_sql (%s): Connected new DB handle, #%d",
59 inst->config->xlat_name, sqlsocket->id);
60 sqlsocket->state = sockconnected;
61 if (inst->config->lifetime) time(&sqlsocket->connected);
62 sqlsocket->queries = 0;
69 radlog(L_CONS | L_ERR, "rlm_sql (%s): Failed to connect DB handle #%d", inst->config->xlat_name, sqlsocket->id);
70 inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
71 sqlsocket->state = sockunconnected;
76 /*************************************************************************
78 * Function: sql_init_socketpool
80 * Purpose: Connect to the sql server, if possible
82 *************************************************************************/
83 int sql_init_socketpool(SQL_INST * inst)
89 inst->connect_after = 0;
92 for (i = 0; i < inst->config->num_sql_socks; i++) {
93 radlog(L_DBG, "rlm_sql (%s): starting %d",
94 inst->config->xlat_name, i);
96 sqlsocket = rad_malloc(sizeof(*sqlsocket));
97 if (sqlsocket == NULL) {
100 memset(sqlsocket, 0, sizeof(*sqlsocket));
101 sqlsocket->conn = NULL;
103 sqlsocket->state = sockunconnected;
105 #ifdef HAVE_PTHREAD_H
106 rcode = pthread_mutex_init(&sqlsocket->mutex,NULL);
109 radlog(L_ERR, "rlm_sql: Failed to init lock: %s",
115 if (time(NULL) > inst->connect_after) {
117 * This sets the sqlsocket->state, and
118 * possibly also inst->connect_after
120 if (connect_single_socket(sqlsocket, inst) == 0) {
125 /* Add this socket to the list of sockets */
126 sqlsocket->next = inst->sqlpool;
127 inst->sqlpool = sqlsocket;
129 inst->last_used = NULL;
132 radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
133 inst->config->xlat_name);
139 /*************************************************************************
141 * Function: sql_poolfree
143 * Purpose: Clean up and free sql pool
145 *************************************************************************/
146 void sql_poolfree(SQL_INST * inst)
151 for (cur = inst->sqlpool; cur; cur = next) {
153 sql_close_socket(inst, cur);
156 inst->sqlpool = NULL;
160 /*************************************************************************
162 * Function: sql_close_socket
164 * Purpose: Close and free a sql sqlsocket
166 *************************************************************************/
167 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket)
169 radlog(L_DBG, "rlm_sql (%s): Closing sqlsocket %d",
170 inst->config->xlat_name, sqlsocket->id);
171 if (sqlsocket->state == sockconnected) {
172 (inst->module->sql_close)(sqlsocket, inst->config);
174 if (inst->module->sql_destroy_socket) {
175 (inst->module->sql_destroy_socket)(sqlsocket, inst->config);
177 #ifdef HAVE_PTHREAD_H
178 pthread_mutex_destroy(&sqlsocket->mutex);
184 static time_t last_logged_failure = 0;
187 /*************************************************************************
189 * Function: sql_get_socket
191 * Purpose: Return a SQL sqlsocket from the connection pool
193 *************************************************************************/
194 SQLSOCK * sql_get_socket(SQL_INST * inst)
196 SQLSOCK *cur, *start;
197 int tried_to_connect = 0;
199 time_t now = time(NULL);
202 * Start at the last place we left off.
204 start = inst->last_used;
205 if (!start) start = inst->sqlpool;
210 #ifdef HAVE_PTHREAD_H
212 * If this socket is in use by another thread,
213 * skip it, and try another socket.
215 * If it isn't used, then grab it ourselves.
217 if (pthread_mutex_trylock(&cur->mutex) != 0) {
219 } /* else we now have the lock */
223 * If the socket has outlived its lifetime, and
224 * is connected, close it, and mark it as open for
227 if (inst->config->lifetime && (cur->state == sockconnected) &&
228 ((cur->connected + inst->config->lifetime) < now)) {
229 (inst->module->sql_close)(cur, inst->config);
230 cur->state = sockunconnected;
235 * If we have performed too many queries over this
236 * socket, then close it.
238 if (inst->config->max_queries && (cur->state == sockconnected) &&
239 (cur->queries >= inst->config->max_queries)) {
240 (inst->module->sql_close)(cur, inst->config);
241 cur->state = sockunconnected;
246 * If we happen upon an unconnected socket, and
247 * this instance's grace period on
248 * (re)connecting has expired, then try to
249 * connect it. This should be really rare.
251 if ((cur->state == sockunconnected) && (now > inst->connect_after)) {
253 radlog(L_INFO, "rlm_sql (%s): Trying to (re)connect unconnected handle %d..", inst->config->xlat_name, cur->id);
255 connect_single_socket(cur, inst);
258 /* if we still aren't connected, ignore this handle */
259 if (cur->state == sockunconnected) {
260 radlog(L_DBG, "rlm_sql (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
262 #ifdef HAVE_PTHREAD_H
263 pthread_mutex_unlock(&cur->mutex);
268 /* should be connected, grab it */
269 radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
271 if (unconnected != 0 || tried_to_connect != 0) {
272 radlog(L_INFO, "rlm_sql (%s): got socket %d after skipping %d unconnected handles, tried to reconnect %d though", inst->config->xlat_name, cur->id, unconnected, tried_to_connect);
276 * The socket is returned in the locked
279 * We also remember where we left off,
280 * so that the next search can start from
283 * Note that multiple threads MAY over-write
284 * the 'inst->last_used' variable. This is OK,
285 * as it's a pointer only used for reading.
287 inst->last_used = cur->next;
291 /* move along the list */
296 * Because we didnt start at the start, once we
297 * hit the end of the linklist, we should go
298 * back to the beginning and work toward the
306 * If we're at the socket we started
314 * Suppress most of the log messages. We don't want to
315 * flood the log with this message for EVERY packet.
316 * Instead, write to the log only once a second or so.
318 * This code has race conditions when threaded, but the
319 * only result is that a few more messages are logged.
321 if (now <= last_logged_failure) return NULL;
322 last_logged_failure = now;
324 /* We get here if every DB handle is unconnected and unconnectABLE */
325 radlog(L_INFO, "rlm_sql (%s): There are no DB handles to use! skipped %d, tried to connect %d", inst->config->xlat_name, unconnected, tried_to_connect);
329 /*************************************************************************
331 * Function: sql_release_socket
333 * Purpose: Frees a SQL sqlsocket back to the connection pool
335 *************************************************************************/
336 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
338 #ifdef HAVE_PTHREAD_H
339 pthread_mutex_unlock(&sqlsocket->mutex);
342 radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
343 inst->config->xlat_name, sqlsocket->id);
349 /*************************************************************************
351 * Function: sql_userparse
353 * Purpose: Read entries from the database and fill VALUE_PAIR structures
355 *************************************************************************/
356 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row)
359 const char *ptr, *value;
360 char buf[MAX_STRING_LEN];
362 FR_TOKEN token, operator = T_EOL;
365 * Verify the 'Attribute' field
367 if (row[2] == NULL || row[2][0] == '\0') {
368 radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
373 * Verify the 'op' field
375 if (row[4] != NULL && row[4][0] != '\0') {
377 operator = gettoken(&ptr, buf, sizeof(buf));
378 if ((operator < T_OP_ADD) ||
379 (operator > T_OP_CMP_EQ)) {
380 radlog(L_ERR, "rlm_sql: Invalid operator \"%s\" for attribute %s", row[4], row[2]);
386 * Complain about empty or invalid 'op' field
388 operator = T_OP_CMP_EQ;
389 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
390 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
394 * The 'Value' field may be empty or NULL
398 * If we have a new-style quoted string, where the
399 * *entire* string is quoted, do xlat's.
401 if (row[3] != NULL &&
402 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
403 (row[3][0] == row[3][strlen(row[3])-1])) {
405 token = gettoken(&value, buf, sizeof(buf));
408 * Take the unquoted string.
410 case T_SINGLE_QUOTED_STRING:
411 case T_DOUBLE_QUOTED_STRING:
416 * Mark the pair to be allocated later.
418 case T_BACK_QUOTED_STRING:
424 * Keep the original string.
435 pair = pairmake(row[2], value, operator);
437 radlog(L_ERR, "rlm_sql: Failed to create the pair: %s", fr_strerror());
441 pair->flags.do_xlat = 1;
442 strlcpy(pair->vp_strvalue, buf, sizeof(pair->vp_strvalue));
447 * Add the pair into the packet
449 pairadd(first_pair, pair);
454 /*************************************************************************
456 * Function: rlm_sql_fetch_row
458 * Purpose: call the module's sql_fetch_row and implement re-connect
460 *************************************************************************/
461 int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
465 if (sqlsocket->conn) {
466 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
471 if (ret == SQL_DOWN) {
472 /* close the socket that failed, but only if it was open */
473 if (sqlsocket->conn) {
474 (inst->module->sql_close)(sqlsocket, inst->config);
477 /* reconnect the socket */
478 if (connect_single_socket(sqlsocket, inst) < 0) {
479 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
483 /* retry the query on the newly connected socket */
484 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
487 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
488 inst->config->xlat_name);
496 /*************************************************************************
498 * Function: rlm_sql_query
500 * Purpose: call the module's sql_query and implement re-connect
502 *************************************************************************/
503 int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
508 * If there's no query, return an error.
510 if (!query || !*query) {
514 if (sqlsocket->conn) {
515 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
520 if (ret == SQL_DOWN) {
521 /* close the socket that failed */
522 if (sqlsocket->state == sockconnected) {
523 (inst->module->sql_close)(sqlsocket, inst->config);
526 /* reconnect the socket */
527 if (connect_single_socket(sqlsocket, inst) < 0) {
528 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
532 /* retry the query on the newly connected socket */
533 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
536 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
537 inst->config->xlat_name);
545 /*************************************************************************
547 * Function: rlm_sql_select_query
549 * Purpose: call the module's sql_select_query and implement re-connect
551 *************************************************************************/
552 int rlm_sql_select_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
557 * If there's no query, return an error.
559 if (!query || !*query) {
563 if (sqlsocket->conn) {
564 ret = (inst->module->sql_select_query)(sqlsocket, inst->config,
570 if (ret == SQL_DOWN) {
571 /* close the socket that failed */
572 if (sqlsocket->state == sockconnected) {
573 (inst->module->sql_close)(sqlsocket, inst->config);
576 /* reconnect the socket */
577 if (connect_single_socket(sqlsocket, inst) < 0) {
578 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
582 /* retry the query on the newly connected socket */
583 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
586 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
587 inst->config->xlat_name);
596 /*************************************************************************
598 * Function: sql_getvpdata
600 * Purpose: Get any group check or reply pairs
602 *************************************************************************/
603 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query)
608 if (rlm_sql_select_query(sqlsocket, inst, query)) {
609 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
612 while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
613 row = sqlsocket->row;
616 if (sql_userparse(pair, row) != 0) {
617 radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
618 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
623 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
628 void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
630 FILE *sqlfile = NULL;
632 if (inst->config->sqltrace) {
635 if (!radius_xlat(buffer, sizeof(buffer),
636 inst->config->tracefile, request, NULL)) {
637 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
638 inst->config->xlat_name);
642 if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
643 radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
644 inst->config->xlat_name,
647 int fd = fileno(sqlfile);
649 rad_lockfd(fd, MAX_QUERY_LEN);
650 fputs(querystr, sqlfile);
651 fputs(";\n", sqlfile);
652 fclose(sqlfile); /* and release the lock */