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/autoconf.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
38 #include <netinet/in.h>
51 #include <freeradius-devel/radiusd.h>
59 * Connect to a server. If error, set this socket's state to be
60 * "sockunconnected" and set a grace period, during which we won't try
61 * connecting again (to prevent unduly lagging the server and being
62 * impolite to a DB server that may be having other issues). If
63 * successful in connecting, set state to sockconnected.
66 static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst)
69 radlog(L_DBG, "rlm_sql (%s): Attempting to connect %s #%d",
70 inst->config->xlat_name, inst->module->name, sqlsocket->id);
72 rcode = (inst->module->sql_init_socket)(sqlsocket, inst->config);
74 radlog(L_DBG, "rlm_sql (%s): Connected new DB handle, #%d",
75 inst->config->xlat_name, sqlsocket->id);
76 sqlsocket->state = sockconnected;
83 radlog(L_CONS | L_ERR, "rlm_sql (%s): Failed to connect DB handle #%d", inst->config->xlat_name, sqlsocket->id);
84 inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
85 sqlsocket->state = sockunconnected;
90 /*************************************************************************
92 * Function: sql_init_socketpool
94 * Purpose: Connect to the sql server, if possible
96 *************************************************************************/
97 int sql_init_socketpool(SQL_INST * inst)
103 inst->connect_after = 0;
104 inst->sqlpool = NULL;
106 for (i = 0; i < inst->config->num_sql_socks; i++) {
107 radlog(L_DBG, "rlm_sql (%s): starting %d",
108 inst->config->xlat_name, i);
110 sqlsocket = rad_malloc(sizeof(*sqlsocket));
111 if (sqlsocket == NULL) {
114 memset(sqlsocket, 0, sizeof(*sqlsocket));
115 sqlsocket->conn = NULL;
117 sqlsocket->state = sockunconnected;
119 #ifdef HAVE_PTHREAD_H
120 rcode = pthread_mutex_init(&sqlsocket->mutex,NULL);
122 radlog(L_ERR, "rlm_sql: Failed to init lock: %s",
128 if (time(NULL) > inst->connect_after) {
130 * This sets the sqlsocket->state, and
131 * possibly also inst->connect_after
133 if (connect_single_socket(sqlsocket, inst) == 0) {
138 /* Add this socket to the list of sockets */
139 sqlsocket->next = inst->sqlpool;
140 inst->sqlpool = sqlsocket;
142 inst->last_used = NULL;
145 radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
146 inst->config->xlat_name);
152 /*************************************************************************
154 * Function: sql_poolfree
156 * Purpose: Clean up and free sql pool
158 *************************************************************************/
159 void sql_poolfree(SQL_INST * inst)
164 for (cur = inst->sqlpool; cur; cur = next) {
166 sql_close_socket(inst, cur);
169 inst->sqlpool = NULL;
173 /*************************************************************************
175 * Function: sql_close_socket
177 * Purpose: Close and free a sql sqlsocket
179 *************************************************************************/
180 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket)
182 radlog(L_DBG, "rlm_sql (%s): Closing sqlsocket %d",
183 inst->config->xlat_name, sqlsocket->id);
184 if (sqlsocket->state == sockconnected) {
185 (inst->module->sql_close)(sqlsocket, inst->config);
187 if (inst->module->sql_destroy_socket) {
188 (inst->module->sql_destroy_socket)(sqlsocket, inst->config);
190 #ifdef HAVE_PTHREAD_H
191 pthread_mutex_destroy(&sqlsocket->mutex);
198 /*************************************************************************
200 * Function: sql_get_socket
202 * Purpose: Return a SQL sqlsocket from the connection pool
204 *************************************************************************/
205 SQLSOCK * sql_get_socket(SQL_INST * inst)
207 SQLSOCK *cur, *start;
208 int tried_to_connect = 0;
212 * Start at the last place we left off.
214 start = inst->last_used;
215 if (!start) start = inst->sqlpool;
220 #ifdef HAVE_PTHREAD_H
222 * If this socket is in use by another thread,
223 * skip it, and try another socket.
225 * If it isn't used, then grab it ourselves.
227 if (pthread_mutex_trylock(&cur->mutex) != 0) {
229 } /* else we now have the lock */
233 * If we happen upon an unconnected socket, and
234 * this instance's grace period on
235 * (re)connecting has expired, then try to
236 * connect it. This should be really rare.
238 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
239 radlog(L_INFO, "rlm_sql (%s): Trying to (re)connect unconnected handle %d..", inst->config->xlat_name, cur->id);
241 connect_single_socket(cur, inst);
244 /* if we still aren't connected, ignore this handle */
245 if (cur->state == sockunconnected) {
246 radlog(L_DBG, "rlm_sql (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
248 #ifdef HAVE_PTHREAD_H
249 pthread_mutex_unlock(&cur->mutex);
254 /* should be connected, grab it */
255 radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
257 if (unconnected != 0 || tried_to_connect != 0) {
258 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);
262 * The socket is returned in the locked
265 * We also remember where we left off,
266 * so that the next search can start from
269 * Note that multiple threads MAY over-write
270 * the 'inst->last_used' variable. This is OK,
271 * as it's a pointer only used for reading.
273 inst->last_used = cur->next;
276 /* move along the list */
281 * Because we didnt start at the start, once we
282 * hit the end of the linklist, we should go
283 * back to the beginning and work toward the
291 * If we're at the socket we started
298 /* We get here if every DB handle is unconnected and unconnectABLE */
299 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);
303 /*************************************************************************
305 * Function: sql_release_socket
307 * Purpose: Frees a SQL sqlsocket back to the connection pool
309 *************************************************************************/
310 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
312 #ifdef HAVE_PTHREAD_H
313 pthread_mutex_unlock(&sqlsocket->mutex);
316 radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
317 inst->config->xlat_name, sqlsocket->id);
323 /*************************************************************************
325 * Function: sql_userparse
327 * Purpose: Read entries from the database and fill VALUE_PAIR structures
329 *************************************************************************/
330 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row)
334 char buf[MAX_STRING_LEN];
336 LRAD_TOKEN token, operator = T_EOL;
339 * Verify the 'Attribute' field
341 if (row[2] == NULL || row[2][0] == '\0') {
342 radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
347 * Verify the 'op' field
349 if (row[4] != NULL && row[4][0] != '\0') {
351 operator = gettoken(&ptr, buf, sizeof(buf));
353 if (operator <= T_EOL) {
355 * Complain about empty or invalid 'op' field
357 operator = T_OP_CMP_EQ;
358 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
359 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
363 * The 'Value' field may be empty or NULL
367 * If we have a new-style quoted string, where the
368 * *entire* string is quoted, do xlat's.
370 if (row[3] != NULL &&
371 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
372 (row[3][0] == row[3][strlen(row[3])-1])) {
374 token = gettoken(&value, buf, sizeof(buf));
377 * Take the unquoted string.
379 case T_SINGLE_QUOTED_STRING:
380 case T_DOUBLE_QUOTED_STRING:
385 * Mark the pair to be allocated later.
387 case T_BACK_QUOTED_STRING:
393 * Keep the original string.
404 pair = pairmake(row[2], value, operator);
406 radlog(L_ERR, "rlm_sql: Failed to create the pair: %s", librad_errstr);
410 pair->flags.do_xlat = 1;
411 strlcpy(pair->vp_strvalue, buf, sizeof(pair->vp_strvalue));
416 * Add the pair into the packet
418 pairadd(first_pair, pair);
423 /*************************************************************************
425 * Function: rlm_sql_fetch_row
427 * Purpose: call the module's sql_fetch_row and implement re-connect
429 *************************************************************************/
430 int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
434 if (sqlsocket->conn) {
435 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
440 if (ret == SQL_DOWN) {
441 /* close the socket that failed, but only if it was open */
442 if (sqlsocket->conn) {
443 (inst->module->sql_close)(sqlsocket, inst->config);
446 /* reconnect the socket */
447 if (connect_single_socket(sqlsocket, inst) < 0) {
448 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
452 /* retry the query on the newly connected socket */
453 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
456 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
457 inst->config->xlat_name);
465 /*************************************************************************
467 * Function: rlm_sql_query
469 * Purpose: call the module's sql_query and implement re-connect
471 *************************************************************************/
472 int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
477 * If there's no query, return an error.
479 if (!query || !*query) {
483 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
485 if (ret == SQL_DOWN) {
486 /* close the socket that failed */
487 if (sqlsocket->state == sockconnected) {
488 (inst->module->sql_close)(sqlsocket, inst->config);
491 /* reconnect the socket */
492 if (connect_single_socket(sqlsocket, inst) < 0) {
493 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
497 /* retry the query on the newly connected socket */
498 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
501 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
502 inst->config->xlat_name);
510 /*************************************************************************
512 * Function: rlm_sql_select_query
514 * Purpose: call the module's sql_select_query and implement re-connect
516 *************************************************************************/
517 int rlm_sql_select_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
522 * If there's no query, return an error.
524 if (!query || !*query) {
528 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
530 if (ret == SQL_DOWN) {
531 /* close the socket that failed */
532 if (sqlsocket->state == sockconnected) {
533 (inst->module->sql_close)(sqlsocket, inst->config);
536 /* reconnect the socket */
537 if (connect_single_socket(sqlsocket, inst) < 0) {
538 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
542 /* retry the query on the newly connected socket */
543 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
546 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
547 inst->config->xlat_name);
556 /*************************************************************************
558 * Function: sql_getvpdata
560 * Purpose: Get any group check or reply pairs
562 *************************************************************************/
563 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query)
569 * If there's no query, return an error.
571 if (!query || !*query) {
575 if (rlm_sql_select_query(sqlsocket, inst, query)) {
576 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
579 while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
580 row = sqlsocket->row;
583 if (sql_userparse(pair, row) != 0) {
584 radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
585 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
590 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
595 void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
597 FILE *sqlfile = NULL;
599 if (inst->config->sqltrace) {
602 if (!radius_xlat(buffer, sizeof(buffer),
603 inst->config->tracefile, request, NULL)) {
604 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
605 inst->config->xlat_name);
609 if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
610 radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
611 inst->config->xlat_name,
614 int fd = fileno(sqlfile);
616 rad_lockfd(fd, MAX_QUERY_LEN);
617 fputs(querystr, sqlfile);
618 fputs(";\n", sqlfile);
619 fclose(sqlfile); /* and release the lock */