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 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/autoconf.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
35 #include <netinet/in.h>
48 #include <freeradius-devel/radiusd.h>
56 * Connect to a server. If error, set this socket's state to be
57 * "sockunconnected" and set a grace period, during which we won't try
58 * connecting again (to prevent unduly lagging the server and being
59 * impolite to a DB server that may be having other issues). If
60 * successful in connecting, set state to sockconnected.
63 static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst)
66 radlog(L_DBG, "rlm_sql (%s): Attempting to connect %s #%d",
67 inst->config->xlat_name, inst->module->name, sqlsocket->id);
69 rcode = (inst->module->sql_init_socket)(sqlsocket, inst->config);
71 radlog(L_DBG, "rlm_sql (%s): Connected new DB handle, #%d",
72 inst->config->xlat_name, sqlsocket->id);
73 sqlsocket->state = sockconnected;
80 radlog(L_CONS | L_ERR, "rlm_sql (%s): Failed to connect DB handle #%d", inst->config->xlat_name, sqlsocket->id);
81 inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
82 sqlsocket->state = sockunconnected;
87 /*************************************************************************
89 * Function: sql_init_socketpool
91 * Purpose: Connect to the sql server, if possible
93 *************************************************************************/
94 int sql_init_socketpool(SQL_INST * inst)
100 inst->connect_after = 0;
101 inst->sqlpool = NULL;
103 for (i = 0; i < inst->config->num_sql_socks; i++) {
104 radlog(L_DBG, "rlm_sql (%s): starting %d",
105 inst->config->xlat_name, i);
107 sqlsocket = rad_malloc(sizeof(*sqlsocket));
108 if (sqlsocket == NULL) {
111 memset(sqlsocket, 0, sizeof(*sqlsocket));
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)
331 char buf[MAX_STRING_LEN];
333 LRAD_TOKEN token, operator = T_EOL;
336 * Verify the 'Attribute' field
338 if (row[2] == NULL || row[2][0] == '\0') {
339 radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
344 * Verify the 'op' field
346 if (row[4] != NULL && row[4][0] != '\0') {
348 operator = gettoken(&ptr, buf, sizeof(buf));
350 if (operator <= T_EOL) {
352 * Complain about empty or invalid 'op' field
354 operator = T_OP_CMP_EQ;
355 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
356 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
360 * The 'Value' field may be empty or NULL
364 * If we have a new-style quoted string, where the
365 * *entire* string is quoted, do xlat's.
367 if (row[3] != NULL &&
368 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
369 (row[3][0] == row[3][strlen(row[3])-1])) {
371 token = gettoken(&value, buf, sizeof(buf));
374 * Take the unquoted string.
376 case T_SINGLE_QUOTED_STRING:
377 case T_DOUBLE_QUOTED_STRING:
382 * Mark the pair to be allocated later.
384 case T_BACK_QUOTED_STRING:
390 * Keep the original string.
401 pair = pairmake(row[2], value, operator);
403 radlog(L_ERR, "rlm_sql: Failed to create the pair: %s", librad_errstr);
407 pair->flags.do_xlat = 1;
408 strNcpy(pair->vp_strvalue, buf, sizeof(pair->vp_strvalue));
413 * Add the pair into the packet
415 pairadd(first_pair, pair);
420 /*************************************************************************
422 * Function: rlm_sql_fetch_row
424 * Purpose: call the module's sql_fetch_row and implement re-connect
426 *************************************************************************/
427 int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
431 if (sqlsocket->conn) {
432 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
437 if (ret == SQL_DOWN) {
438 /* close the socket that failed, but only if it was open */
439 if (sqlsocket->conn) {
440 (inst->module->sql_close)(sqlsocket, inst->config);
443 /* reconnect the socket */
444 if (connect_single_socket(sqlsocket, inst) < 0) {
445 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
449 /* retry the query on the newly connected socket */
450 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
453 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
454 inst->config->xlat_name);
462 /*************************************************************************
464 * Function: rlm_sql_query
466 * Purpose: call the module's sql_query and implement re-connect
468 *************************************************************************/
469 int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
474 * If there's no query, return an error.
476 if (!query || !*query) {
480 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
482 if (ret == SQL_DOWN) {
483 /* close the socket that failed */
484 (inst->module->sql_close)(sqlsocket, inst->config);
486 /* reconnect the socket */
487 if (connect_single_socket(sqlsocket, inst) < 0) {
488 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
492 /* retry the query on the newly connected socket */
493 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
496 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
497 inst->config->xlat_name);
505 /*************************************************************************
507 * Function: rlm_sql_select_query
509 * Purpose: call the module's sql_select_query and implement re-connect
511 *************************************************************************/
512 int rlm_sql_select_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
517 * If there's no query, return an error.
519 if (!query || !*query) {
523 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
525 if (ret == SQL_DOWN) {
526 /* close the socket that failed */
527 (inst->module->sql_close)(sqlsocket, inst->config);
529 /* reconnect the socket */
530 if (connect_single_socket(sqlsocket, inst) < 0) {
531 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
535 /* retry the query on the newly connected socket */
536 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
539 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
540 inst->config->xlat_name);
549 /*************************************************************************
551 * Function: sql_getvpdata
553 * Purpose: Get any group check or reply pairs
555 *************************************************************************/
556 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query)
562 * If there's no query, return an error.
564 if (!query || !*query) {
568 if (rlm_sql_select_query(sqlsocket, inst, query)) {
569 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
572 while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
573 row = sqlsocket->row;
576 if (sql_userparse(pair, row) != 0) {
577 radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
578 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
583 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
588 void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
590 FILE *sqlfile = NULL;
592 if (inst->config->sqltrace) {
595 if (!radius_xlat(buffer, sizeof(buffer),
596 inst->config->tracefile, request, NULL)) {
597 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
598 inst->config->xlat_name);
602 if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
603 radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
604 inst->config->xlat_name,
607 int fd = fileno(sqlfile);
609 rad_lockfd(fd, MAX_QUERY_LEN);
610 fputs(querystr, sqlfile);
611 fputs(";\n", sqlfile);
612 fclose(sqlfile); /* and release the lock */