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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * Copyright 2001 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 <sys/types.h>
30 #include <sys/socket.h>
35 #include <netinet/in.h>
58 * Connect to a server. If error, set this socket's state to be
59 * "sockunconnected" and set a grace period, during which we won't try
60 * connecting again (to prevent unduly lagging the server and being
61 * impolite to a DB server that may be having other issues). If
62 * successful in connecting, set state to sockconnected.
65 static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst)
68 radlog(L_DBG, "rlm_sql (%s): Attempting to connect %s #%d",
69 inst->config->xlat_name, inst->module->name, sqlsocket->id);
71 rcode = (inst->module->sql_init_socket)(sqlsocket, inst->config);
73 radlog(L_DBG, "rlm_sql (%s): Connected new DB handle, #%d",
74 inst->config->xlat_name, sqlsocket->id);
75 sqlsocket->state = sockconnected;
82 radlog(L_CONS | L_ERR, "rlm_sql (%s): Failed to connect DB handle #%d", inst->config->xlat_name, sqlsocket->id);
83 inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
84 sqlsocket->state = sockunconnected;
89 /*************************************************************************
91 * Function: sql_init_socketpool
93 * Purpose: Connect to the sql server, if possible
95 *************************************************************************/
96 int sql_init_socketpool(SQL_INST * inst)
102 inst->connect_after = 0;
103 inst->sqlpool = NULL;
105 for (i = 0; i < inst->config->num_sql_socks; i++) {
106 radlog(L_DBG, "rlm_sql (%s): starting %d",
107 inst->config->xlat_name, i);
109 sqlsocket = rad_malloc(sizeof(*sqlsocket);
110 if (sqlsocket == NULL) {
113 memset(sqlsocket, 0, sizeof(*sqlsocket));
114 sqlsocket->conn = NULL;
116 sqlsocket->state = sockunconnected;
118 #ifdef HAVE_PTHREAD_H
119 rcode = pthread_mutex_init(&sqlsocket->mutex,NULL);
121 radlog(L_ERR, "rlm_sql: Failed to init lock: %s",
127 if (time(NULL) > inst->connect_after) {
129 * This sets the sqlsocket->state, and
130 * possibly also inst->connect_after
132 if (connect_single_socket(sqlsocket, inst) == 0) {
137 /* Add this socket to the list of sockets */
138 sqlsocket->next = inst->sqlpool;
139 inst->sqlpool = sqlsocket;
141 inst->last_used = NULL;
144 radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
145 inst->config->xlat_name);
151 /*************************************************************************
153 * Function: sql_poolfree
155 * Purpose: Clean up and free sql pool
157 *************************************************************************/
158 void sql_poolfree(SQL_INST * inst)
163 for (cur = inst->sqlpool; cur; cur = next) {
165 sql_close_socket(inst, cur);
168 inst->sqlpool = NULL;
172 /*************************************************************************
174 * Function: sql_close_socket
176 * Purpose: Close and free a sql sqlsocket
178 *************************************************************************/
179 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket)
181 radlog(L_DBG, "rlm_sql (%s): Closing sqlsocket %d",
182 inst->config->xlat_name, sqlsocket->id);
183 if (sqlsocket->state == sockconnected) {
184 (inst->module->sql_close)(sqlsocket, inst->config);
186 if (inst->module->sql_destroy_socket) {
187 (inst->module->sql_destroy_socket)(sqlsocket, inst->config);
189 #ifdef HAVE_PTHREAD_H
190 pthread_mutex_destroy(&sqlsocket->mutex);
197 /*************************************************************************
199 * Function: sql_get_socket
201 * Purpose: Return a SQL sqlsocket from the connection pool
203 *************************************************************************/
204 SQLSOCK * sql_get_socket(SQL_INST * inst)
206 SQLSOCK *cur, *start;
207 int tried_to_connect = 0;
211 * Start at the last place we left off.
213 start = inst->last_used;
214 if (!start) start = inst->sqlpool;
219 #ifdef HAVE_PTHREAD_H
221 * If this socket is in use by another thread,
222 * skip it, and try another socket.
224 * If it isn't used, then grab it ourselves.
226 if (pthread_mutex_trylock(&cur->mutex) != 0) {
228 } /* else we now have the lock */
232 * If we happen upon an unconnected socket, and
233 * this instance's grace period on
234 * (re)connecting has expired, then try to
235 * connect it. This should be really rare.
237 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
238 radlog(L_INFO, "rlm_sql (%s): Trying to (re)connect unconnected handle %d..", inst->config->xlat_name, cur->id);
240 connect_single_socket(cur, inst);
243 /* if we still aren't connected, ignore this handle */
244 if (cur->state == sockunconnected) {
245 radlog(L_DBG, "rlm_sql (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
247 #ifdef HAVE_PTHREAD_H
248 pthread_mutex_unlock(&cur->mutex);
253 /* should be connected, grab it */
254 radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
256 if (unconnected != 0 || tried_to_connect != 0) {
257 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);
261 * The socket is returned in the locked
264 * We also remember where we left off,
265 * so that the next search can start from
268 * Note that multiple threads MAY over-write
269 * the 'inst->last_used' variable. This is OK,
270 * as it's a pointer only used for reading.
272 inst->last_used = cur->next;
275 /* move along the list */
280 * Because we didnt start at the start, once we
281 * hit the end of the linklist, we should go
282 * back to the beginning and work toward the
290 * If we're at the socket we started
297 /* We get here if every DB handle is unconnected and unconnectABLE */
298 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);
302 /*************************************************************************
304 * Function: sql_release_socket
306 * Purpose: Frees a SQL sqlsocket back to the connection pool
308 *************************************************************************/
309 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
311 #ifdef HAVE_PTHREAD_H
312 pthread_mutex_unlock(&sqlsocket->mutex);
315 radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
316 inst->config->xlat_name, sqlsocket->id);
322 /*************************************************************************
324 * Function: sql_userparse
326 * Purpose: Read entries from the database and fill VALUE_PAIR structures
328 *************************************************************************/
329 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row)
333 char buf[MAX_STRING_LEN];
335 LRAD_TOKEN token, operator = T_EOL;
338 * Verify the 'Attribute' field
340 if (row[2] == NULL || row[2][0] == '\0') {
341 radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
346 * Verify the 'op' field
348 if (row[4] != NULL && row[4][0] != '\0') {
350 operator = gettoken(&ptr, buf, sizeof(buf));
352 if (operator <= T_EOL) {
354 * Complain about empty or invalid 'op' field
356 operator = T_OP_CMP_EQ;
357 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
358 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
362 * The 'Value' field may be empty or NULL
366 * If we have a new-style quoted string, where the
367 * *entire* string is quoted, do xlat's.
369 if (row[3] != NULL &&
370 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
371 (row[3][0] == row[3][strlen(row[3])-1])) {
373 token = gettoken(&value, buf, sizeof(buf));
376 * Take the unquoted string.
378 case T_SINGLE_QUOTED_STRING:
379 case T_DOUBLE_QUOTED_STRING:
384 * Mark the pair to be allocated later.
386 case T_BACK_QUOTED_STRING:
392 * Keep the original string.
403 pair = pairmake(row[2], value, operator);
405 radlog(L_ERR, "rlm_sql: Failed to create the pair: %s", librad_errstr);
409 pair->flags.do_xlat = 1;
410 strNcpy(pair->strvalue, buf, sizeof(pair->strvalue));
415 * Add the pair into the packet
417 pairadd(first_pair, pair);
422 /*************************************************************************
424 * Function: rlm_sql_fetch_row
426 * Purpose: call the module's sql_fetch_row and implement re-connect
428 *************************************************************************/
429 int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
433 if (sqlsocket->conn) {
434 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
439 if (ret == SQL_DOWN) {
440 /* close the socket that failed, but only if it was open */
441 if (sqlsocket->conn) {
442 (inst->module->sql_close)(sqlsocket, inst->config);
445 /* reconnect the socket */
446 if (connect_single_socket(sqlsocket, inst) < 0) {
447 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
451 /* retry the query on the newly connected socket */
452 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
455 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
456 inst->config->xlat_name);
464 /*************************************************************************
466 * Function: rlm_sql_query
468 * Purpose: call the module's sql_query and implement re-connect
470 *************************************************************************/
471 int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
476 * If there's no query, return an error.
478 if (!query || !*query) {
482 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
484 if (ret == SQL_DOWN) {
485 /* close the socket that failed */
486 (inst->module->sql_close)(sqlsocket, inst->config);
488 /* reconnect the socket */
489 if (connect_single_socket(sqlsocket, inst) < 0) {
490 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
494 /* retry the query on the newly connected socket */
495 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
498 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
499 inst->config->xlat_name);
507 /*************************************************************************
509 * Function: rlm_sql_select_query
511 * Purpose: call the module's sql_select_query and implement re-connect
513 *************************************************************************/
514 int rlm_sql_select_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
519 * If there's no query, return an error.
521 if (!query || !*query) {
525 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
527 if (ret == SQL_DOWN) {
528 /* close the socket that failed */
529 (inst->module->sql_close)(sqlsocket, inst->config);
531 /* reconnect the socket */
532 if (connect_single_socket(sqlsocket, inst) < 0) {
533 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
537 /* retry the query on the newly connected socket */
538 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
541 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
542 inst->config->xlat_name);
551 /*************************************************************************
553 * Function: sql_getvpdata
555 * Purpose: Get any group check or reply pairs
557 *************************************************************************/
558 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query)
564 * If there's no query, return an error.
566 if (!query || !*query) {
570 if (rlm_sql_select_query(sqlsocket, inst, query)) {
571 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
574 while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
575 row = sqlsocket->row;
578 if (sql_userparse(pair, row) != 0) {
579 radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
580 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
585 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
590 void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
592 FILE *sqlfile = NULL;
594 if (inst->config->sqltrace) {
597 if (!radius_xlat(buffer, sizeof(buffer),
598 inst->config->tracefile, request, NULL)) {
599 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
600 inst->config->xlat_name);
604 if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
605 radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
606 inst->config->xlat_name,
609 int fd = fileno(sqlfile);
611 rad_lockfd(fd, MAX_QUERY_LEN);
612 fputs(querystr, sqlfile);
613 fputs(";\n", sqlfile);
614 fclose(sqlfile); /* and release the lock */