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>
47 * Connect to a server. If error, set this socket's state to be
48 * "sockunconnected" and set a grace period, during which we won't try
49 * connecting again (to prevent unduly lagging the server and being
50 * impolite to a DB server that may be having other issues). If
51 * successful in connecting, set state to sockconnected.
54 static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst)
57 radlog(L_DBG, "rlm_sql (%s): Attempting to connect %s #%d",
58 inst->config->xlat_name, inst->module->name, sqlsocket->id);
60 rcode = (inst->module->sql_init_socket)(sqlsocket, inst->config);
62 radlog(L_DBG, "rlm_sql (%s): Connected new DB handle, #%d",
63 inst->config->xlat_name, sqlsocket->id);
64 sqlsocket->state = sockconnected;
71 radlog(L_CONS | L_ERR, "rlm_sql (%s): Failed to connect DB handle #%d", inst->config->xlat_name, sqlsocket->id);
72 inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
73 sqlsocket->state = sockunconnected;
78 /*************************************************************************
80 * Function: sql_init_socketpool
82 * Purpose: Connect to the sql server, if possible
84 *************************************************************************/
85 int sql_init_socketpool(SQL_INST * inst)
91 inst->connect_after = 0;
94 for (i = 0; i < inst->config->num_sql_socks; i++) {
95 radlog(L_DBG, "rlm_sql (%s): starting %d",
96 inst->config->xlat_name, i);
98 sqlsocket = rad_malloc(sizeof(*sqlsocket));
99 if (sqlsocket == NULL) {
102 memset(sqlsocket, 0, sizeof(*sqlsocket));
103 sqlsocket->conn = NULL;
105 sqlsocket->state = sockunconnected;
107 #ifdef HAVE_PTHREAD_H
108 rcode = pthread_mutex_init(&sqlsocket->mutex,NULL);
110 radlog(L_ERR, "rlm_sql: Failed to init lock: %s",
116 if (time(NULL) > inst->connect_after) {
118 * This sets the sqlsocket->state, and
119 * possibly also inst->connect_after
121 if (connect_single_socket(sqlsocket, inst) == 0) {
126 /* Add this socket to the list of sockets */
127 sqlsocket->next = inst->sqlpool;
128 inst->sqlpool = sqlsocket;
130 inst->last_used = NULL;
133 radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
134 inst->config->xlat_name);
140 /*************************************************************************
142 * Function: sql_poolfree
144 * Purpose: Clean up and free sql pool
146 *************************************************************************/
147 void sql_poolfree(SQL_INST * inst)
152 for (cur = inst->sqlpool; cur; cur = next) {
154 sql_close_socket(inst, cur);
157 inst->sqlpool = NULL;
161 /*************************************************************************
163 * Function: sql_close_socket
165 * Purpose: Close and free a sql sqlsocket
167 *************************************************************************/
168 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket)
170 radlog(L_DBG, "rlm_sql (%s): Closing sqlsocket %d",
171 inst->config->xlat_name, sqlsocket->id);
172 if (sqlsocket->state == sockconnected) {
173 (inst->module->sql_close)(sqlsocket, inst->config);
175 if (inst->module->sql_destroy_socket) {
176 (inst->module->sql_destroy_socket)(sqlsocket, inst->config);
178 #ifdef HAVE_PTHREAD_H
179 pthread_mutex_destroy(&sqlsocket->mutex);
186 /*************************************************************************
188 * Function: sql_get_socket
190 * Purpose: Return a SQL sqlsocket from the connection pool
192 *************************************************************************/
193 SQLSOCK * sql_get_socket(SQL_INST * inst)
195 SQLSOCK *cur, *start;
196 int tried_to_connect = 0;
200 * Start at the last place we left off.
202 start = inst->last_used;
203 if (!start) start = inst->sqlpool;
208 #ifdef HAVE_PTHREAD_H
210 * If this socket is in use by another thread,
211 * skip it, and try another socket.
213 * If it isn't used, then grab it ourselves.
215 if (pthread_mutex_trylock(&cur->mutex) != 0) {
217 } /* else we now have the lock */
221 * If we happen upon an unconnected socket, and
222 * this instance's grace period on
223 * (re)connecting has expired, then try to
224 * connect it. This should be really rare.
226 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
227 radlog(L_INFO, "rlm_sql (%s): Trying to (re)connect unconnected handle %d..", inst->config->xlat_name, cur->id);
229 connect_single_socket(cur, inst);
232 /* if we still aren't connected, ignore this handle */
233 if (cur->state == sockunconnected) {
234 radlog(L_DBG, "rlm_sql (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
236 #ifdef HAVE_PTHREAD_H
237 pthread_mutex_unlock(&cur->mutex);
242 /* should be connected, grab it */
243 radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
245 if (unconnected != 0 || tried_to_connect != 0) {
246 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);
250 * The socket is returned in the locked
253 * We also remember where we left off,
254 * so that the next search can start from
257 * Note that multiple threads MAY over-write
258 * the 'inst->last_used' variable. This is OK,
259 * as it's a pointer only used for reading.
261 inst->last_used = cur->next;
264 /* move along the list */
269 * Because we didnt start at the start, once we
270 * hit the end of the linklist, we should go
271 * back to the beginning and work toward the
279 * If we're at the socket we started
286 /* We get here if every DB handle is unconnected and unconnectABLE */
287 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);
291 /*************************************************************************
293 * Function: sql_release_socket
295 * Purpose: Frees a SQL sqlsocket back to the connection pool
297 *************************************************************************/
298 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
300 #ifdef HAVE_PTHREAD_H
301 pthread_mutex_unlock(&sqlsocket->mutex);
304 radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
305 inst->config->xlat_name, sqlsocket->id);
311 /*************************************************************************
313 * Function: sql_userparse
315 * Purpose: Read entries from the database and fill VALUE_PAIR structures
317 *************************************************************************/
318 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row)
322 char buf[MAX_STRING_LEN];
324 LRAD_TOKEN token, operator = T_EOL;
327 * Verify the 'Attribute' field
329 if (row[2] == NULL || row[2][0] == '\0') {
330 radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
335 * Verify the 'op' field
337 if (row[4] != NULL && row[4][0] != '\0') {
339 operator = gettoken(&ptr, buf, sizeof(buf));
341 if (operator <= T_EOL) {
343 * Complain about empty or invalid 'op' field
345 operator = T_OP_CMP_EQ;
346 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
347 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
351 * The 'Value' field may be empty or NULL
355 * If we have a new-style quoted string, where the
356 * *entire* string is quoted, do xlat's.
358 if (row[3] != NULL &&
359 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
360 (row[3][0] == row[3][strlen(row[3])-1])) {
362 token = gettoken(&value, buf, sizeof(buf));
365 * Take the unquoted string.
367 case T_SINGLE_QUOTED_STRING:
368 case T_DOUBLE_QUOTED_STRING:
373 * Mark the pair to be allocated later.
375 case T_BACK_QUOTED_STRING:
381 * Keep the original string.
392 pair = pairmake(row[2], value, operator);
394 radlog(L_ERR, "rlm_sql: Failed to create the pair: %s", librad_errstr);
398 pair->flags.do_xlat = 1;
399 strlcpy(pair->vp_strvalue, buf, sizeof(pair->vp_strvalue));
404 * Add the pair into the packet
406 pairadd(first_pair, pair);
411 /*************************************************************************
413 * Function: rlm_sql_fetch_row
415 * Purpose: call the module's sql_fetch_row and implement re-connect
417 *************************************************************************/
418 int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
422 if (sqlsocket->conn) {
423 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
428 if (ret == SQL_DOWN) {
429 /* close the socket that failed, but only if it was open */
430 if (sqlsocket->conn) {
431 (inst->module->sql_close)(sqlsocket, inst->config);
434 /* reconnect the socket */
435 if (connect_single_socket(sqlsocket, inst) < 0) {
436 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
440 /* retry the query on the newly connected socket */
441 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
444 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
445 inst->config->xlat_name);
453 /*************************************************************************
455 * Function: rlm_sql_query
457 * Purpose: call the module's sql_query and implement re-connect
459 *************************************************************************/
460 int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
465 * If there's no query, return an error.
467 if (!query || !*query) {
471 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
473 if (ret == SQL_DOWN) {
474 /* close the socket that failed */
475 if (sqlsocket->state == sockconnected) {
476 (inst->module->sql_close)(sqlsocket, inst->config);
479 /* reconnect the socket */
480 if (connect_single_socket(sqlsocket, inst) < 0) {
481 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
485 /* retry the query on the newly connected socket */
486 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
489 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
490 inst->config->xlat_name);
498 /*************************************************************************
500 * Function: rlm_sql_select_query
502 * Purpose: call the module's sql_select_query and implement re-connect
504 *************************************************************************/
505 int rlm_sql_select_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
510 * If there's no query, return an error.
512 if (!query || !*query) {
516 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
518 if (ret == SQL_DOWN) {
519 /* close the socket that failed */
520 if (sqlsocket->state == sockconnected) {
521 (inst->module->sql_close)(sqlsocket, inst->config);
524 /* reconnect the socket */
525 if (connect_single_socket(sqlsocket, inst) < 0) {
526 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
530 /* retry the query on the newly connected socket */
531 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
534 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
535 inst->config->xlat_name);
544 /*************************************************************************
546 * Function: sql_getvpdata
548 * Purpose: Get any group check or reply pairs
550 *************************************************************************/
551 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query)
557 * If there's no query, return an error.
559 if (!query || !*query) {
563 if (rlm_sql_select_query(sqlsocket, inst, query)) {
564 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
567 while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
568 row = sqlsocket->row;
571 if (sql_userparse(pair, row) != 0) {
572 radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
573 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
578 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
583 void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
585 FILE *sqlfile = NULL;
587 if (inst->config->sqltrace) {
590 if (!radius_xlat(buffer, sizeof(buffer),
591 inst->config->tracefile, request, NULL)) {
592 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
593 inst->config->xlat_name);
597 if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
598 radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
599 inst->config->xlat_name,
602 int fd = fileno(sqlfile);
604 rad_lockfd(fd, MAX_QUERY_LEN);
605 fputs(querystr, sqlfile);
606 fputs(";\n", sqlfile);
607 fclose(sqlfile); /* and release the lock */