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>
28 #include <sys/types.h>
29 #include <sys/socket.h>
34 #include <netinet/in.h>
57 * Connect to a server. If error, set this socket's state to be
58 * "sockunconnected" and set a grace period, during which we won't try
59 * connecting again (to prevent unduly lagging the server and being
60 * impolite to a DB server that may be having other issues). If
61 * successful in connecting, set state to sockconnected.
64 static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst)
67 radlog(L_DBG, "rlm_sql (%s): Attempting to connect %s #%d",
68 inst->config->xlat_name, inst->module->name, sqlsocket->id);
70 rcode = (inst->module->sql_init_socket)(sqlsocket, inst->config);
72 radlog(L_DBG, "rlm_sql (%s): Connected new DB handle, #%d",
73 inst->config->xlat_name, sqlsocket->id);
74 sqlsocket->state = sockconnected;
81 radlog(L_CONS | L_ERR, "rlm_sql (%s): Failed to connect DB handle #%d", inst->config->xlat_name, sqlsocket->id);
82 inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
83 sqlsocket->state = sockunconnected;
88 /*************************************************************************
90 * Function: sql_init_socketpool
92 * Purpose: Connect to the sql server, if possible
94 *************************************************************************/
95 int sql_init_socketpool(SQL_INST * inst)
101 inst->connect_after = 0;
102 inst->sqlpool = NULL;
104 for (i = 0; i < inst->config->num_sql_socks; i++) {
105 radlog(L_DBG, "rlm_sql (%s): starting %d",
106 inst->config->xlat_name, i);
108 sqlsocket = rad_malloc(sizeof(SQLSOCK));
109 if (sqlsocket == NULL) {
112 sqlsocket->conn = NULL;
114 sqlsocket->state = sockunconnected;
116 #ifdef HAVE_PTHREAD_H
117 rcode = pthread_mutex_init(&sqlsocket->mutex,NULL);
119 radlog(L_ERR, "rlm_sql: Failed to init lock: %s",
125 if (time(NULL) > inst->connect_after) {
127 * This sets the sqlsocket->state, and
128 * possibly also inst->connect_after
130 if (connect_single_socket(sqlsocket, inst) == 0) {
135 /* Add this socket to the list of sockets */
136 sqlsocket->next = inst->sqlpool;
137 inst->sqlpool = sqlsocket;
139 inst->last_used = NULL;
142 radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
143 inst->config->xlat_name);
149 /*************************************************************************
151 * Function: sql_poolfree
153 * Purpose: Clean up and free sql pool
155 *************************************************************************/
156 void sql_poolfree(SQL_INST * inst)
161 for (cur = inst->sqlpool; cur; cur = next) {
163 sql_close_socket(inst, cur);
166 inst->sqlpool = NULL;
170 /*************************************************************************
172 * Function: sql_close_socket
174 * Purpose: Close and free a sql sqlsocket
176 *************************************************************************/
177 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket)
179 radlog(L_DBG, "rlm_sql (%s): Closing sqlsocket %d",
180 inst->config->xlat_name, sqlsocket->id);
181 if (sqlsocket->state == sockconnected) {
182 (inst->module->sql_close)(sqlsocket, inst->config);
184 if (inst->module->sql_destroy_socket) {
185 (inst->module->sql_destroy_socket)(sqlsocket, inst->config);
187 #ifdef HAVE_PTHREAD_H
188 pthread_mutex_destroy(&sqlsocket->mutex);
195 /*************************************************************************
197 * Function: sql_get_socket
199 * Purpose: Return a SQL sqlsocket from the connection pool
201 *************************************************************************/
202 SQLSOCK * sql_get_socket(SQL_INST * inst)
204 SQLSOCK *cur, *start;
205 int tried_to_connect = 0;
209 * Start at the last place we left off.
211 start = inst->last_used;
212 if (!start) start = inst->sqlpool;
217 #ifdef HAVE_PTHREAD_H
219 * If this socket is in use by another thread,
220 * skip it, and try another socket.
222 * If it isn't used, then grab it ourselves.
224 if (pthread_mutex_trylock(&cur->mutex) != 0) {
226 } /* else we now have the lock */
230 * If we happen upon an unconnected socket, and
231 * this instance's grace period on
232 * (re)connecting has expired, then try to
233 * connect it. This should be really rare.
235 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
236 radlog(L_INFO, "rlm_sql (%s): Trying to (re)connect unconnected handle %d..", inst->config->xlat_name, cur->id);
238 connect_single_socket(cur, inst);
241 /* if we still aren't connected, ignore this handle */
242 if (cur->state == sockunconnected) {
243 radlog(L_DBG, "rlm_sql (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
245 #ifdef HAVE_PTHREAD_H
246 pthread_mutex_unlock(&cur->mutex);
251 /* should be connected, grab it */
252 radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
254 if (unconnected != 0 || tried_to_connect != 0) {
255 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);
259 * The socket is returned in the locked
262 * We also remember where we left off,
263 * so that the next search can start from
266 * Note that multiple threads MAY over-write
267 * the 'inst->last_used' variable. This is OK,
268 * as it's a pointer only used for reading.
270 inst->last_used = cur->next;
273 /* move along the list */
278 * Because we didnt start at the start, once we
279 * hit the end of the linklist, we should go
280 * back to the beginning and work toward the
288 * If we're at the socket we started
295 /* We get here if every DB handle is unconnected and unconnectABLE */
296 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);
300 /*************************************************************************
302 * Function: sql_release_socket
304 * Purpose: Frees a SQL sqlsocket back to the connection pool
306 *************************************************************************/
307 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
309 #ifdef HAVE_PTHREAD_H
310 pthread_mutex_unlock(&sqlsocket->mutex);
313 radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
314 inst->config->xlat_name, sqlsocket->id);
320 /*************************************************************************
322 * Function: sql_userparse
324 * Purpose: Read entries from the database and fill VALUE_PAIR structures
326 *************************************************************************/
327 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row, int querymode)
330 VALUE_PAIR *pair, *check;
334 LRAD_TOKEN xlat, pairmode = T_EOL;
336 if ((attr = dict_attrbyname(row[2])) == (DICT_ATTR *) NULL) {
337 radlog(L_ERR | L_CONS, "rlm_sql: unknown attribute %s",
342 if (row[4] != NULL && strlen(row[4]) > 0) {
344 pairmode = gettoken(&ptr, buf, sizeof(buf));
347 * 'op' fields of NULL are a plague, and a bane on the
348 * existence of mankind.
350 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
351 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
353 if (pairmode <= T_EOL) pairmode = T_OP_CMP_EQ;
356 * If attribute is already there, skip it because we checked usercheck first
357 * and we want user settings to over ride group settings
359 if (pairmode != T_OP_ADD && (check = pairfind(*first_pair, attr->attr)) != NULL &&
361 attr->type != PW_TYPE_ABINARY &&
363 querymode == PW_VP_GROUPDATA)
367 * If we have a new-style quoted string, where the
368 * *entire* string is quoted, do xlat's.
370 if (((row[3][0] == '\'') ||
371 (row[3][0] == '`') ||
372 (row[3][0] == '"')) &&
373 (row[3][0] == row[3][strlen(row[3])-1])) {
376 xlat = gettoken(&ptr, value, sizeof(value));
379 * Make the full pair now.
382 pair = pairmake(row[2], row[3], pairmode);
385 case T_SINGLE_QUOTED_STRING:
386 case T_DOUBLE_QUOTED_STRING:
387 pair = pairmake(row[2], value, pairmode);
391 * Mark the pair to be allocated later.
393 case T_BACK_QUOTED_STRING:
394 pair = pairmake(row[2], NULL, pairmode);
396 pair->flags.do_xlat = 1;
397 strNcpy(pair->strvalue, value, sizeof(pair->strvalue));
403 * String starts and ends differently. Take it literally
405 pair = pairmake(row[2], row[3], pairmode);
407 pairadd(first_pair, pair);
413 /*************************************************************************
415 * Function: rlm_sql_fetch_row
417 * Purpose: call the module's sql_fetch_row and implement re-connect
419 *************************************************************************/
420 int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
424 if (sqlsocket->conn) {
425 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
430 if (ret == SQL_DOWN) {
431 /* close the socket that failed, but only if it was open */
432 if (sqlsocket->conn) {
433 (inst->module->sql_close)(sqlsocket, inst->config);
436 /* reconnect the socket */
437 if (connect_single_socket(sqlsocket, inst) < 0) {
438 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
442 /* retry the query on the newly connected socket */
443 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
446 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
447 inst->config->xlat_name);
455 /*************************************************************************
457 * Function: rlm_sql_query
459 * Purpose: call the module's sql_query and implement re-connect
461 *************************************************************************/
462 int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
467 * If there's no query, return an error.
469 if (!query || !*query) {
473 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
475 if (ret == SQL_DOWN) {
476 /* close the socket that failed */
477 (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 (inst->module->sql_close)(sqlsocket, inst->config);
522 /* reconnect the socket */
523 if (connect_single_socket(sqlsocket, inst) < 0) {
524 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
528 /* retry the query on the newly connected socket */
529 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
532 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
533 inst->config->xlat_name);
542 /*************************************************************************
544 * Function: sql_getvpdata
546 * Purpose: Get any group check or reply pairs
548 *************************************************************************/
549 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query, int mode)
555 * If there's no query, return an error.
557 if (!query || !*query) {
561 if (rlm_sql_select_query(sqlsocket, inst, query)) {
562 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
565 while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
566 row = sqlsocket->row;
569 if (sql_userparse(pair, row, mode) != 0) {
570 radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
571 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
576 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
581 void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
583 FILE *sqlfile = NULL;
585 if (inst->config->sqltrace) {
588 if (!radius_xlat(buffer, sizeof(buffer),
589 inst->config->tracefile, request, NULL)) {
590 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
591 inst->config->xlat_name);
595 if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
596 radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
597 inst->config->xlat_name,
600 int fd = fileno(sqlfile);
602 rad_lockfd(fd, MAX_QUERY_LEN);
603 fputs(querystr, sqlfile);
604 fputs(";\n", sqlfile);
605 fclose(sqlfile); /* and release the lock */