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(*sqlsocket));
109 if (sqlsocket == NULL) {
112 memset(sqlsocket, 0, sizeof(*sqlsocket));
113 sqlsocket->conn = NULL;
115 sqlsocket->state = sockunconnected;
117 #ifdef HAVE_PTHREAD_H
118 rcode = pthread_mutex_init(&sqlsocket->mutex,NULL);
120 radlog(L_ERR, "rlm_sql: Failed to init lock: %s",
126 if (time(NULL) > inst->connect_after) {
128 * This sets the sqlsocket->state, and
129 * possibly also inst->connect_after
131 if (connect_single_socket(sqlsocket, inst) == 0) {
136 /* Add this socket to the list of sockets */
137 sqlsocket->next = inst->sqlpool;
138 inst->sqlpool = sqlsocket;
140 inst->last_used = NULL;
143 radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
144 inst->config->xlat_name);
150 /*************************************************************************
152 * Function: sql_poolfree
154 * Purpose: Clean up and free sql pool
156 *************************************************************************/
157 void sql_poolfree(SQL_INST * inst)
162 for (cur = inst->sqlpool; cur; cur = next) {
164 sql_close_socket(inst, cur);
167 inst->sqlpool = NULL;
171 /*************************************************************************
173 * Function: sql_close_socket
175 * Purpose: Close and free a sql sqlsocket
177 *************************************************************************/
178 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket)
180 radlog(L_DBG, "rlm_sql (%s): Closing sqlsocket %d",
181 inst->config->xlat_name, sqlsocket->id);
182 if (sqlsocket->state == sockconnected) {
183 (inst->module->sql_close)(sqlsocket, inst->config);
185 if (inst->module->sql_destroy_socket) {
186 (inst->module->sql_destroy_socket)(sqlsocket, inst->config);
188 #ifdef HAVE_PTHREAD_H
189 pthread_mutex_destroy(&sqlsocket->mutex);
196 /*************************************************************************
198 * Function: sql_get_socket
200 * Purpose: Return a SQL sqlsocket from the connection pool
202 *************************************************************************/
203 SQLSOCK * sql_get_socket(SQL_INST * inst)
205 SQLSOCK *cur, *start;
206 int tried_to_connect = 0;
210 * Start at the last place we left off.
212 start = inst->last_used;
213 if (!start) start = inst->sqlpool;
218 #ifdef HAVE_PTHREAD_H
220 * If this socket is in use by another thread,
221 * skip it, and try another socket.
223 * If it isn't used, then grab it ourselves.
225 if (pthread_mutex_trylock(&cur->mutex) != 0) {
227 } /* else we now have the lock */
231 * If we happen upon an unconnected socket, and
232 * this instance's grace period on
233 * (re)connecting has expired, then try to
234 * connect it. This should be really rare.
236 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
237 radlog(L_INFO, "rlm_sql (%s): Trying to (re)connect unconnected handle %d..", inst->config->xlat_name, cur->id);
239 connect_single_socket(cur, inst);
242 /* if we still aren't connected, ignore this handle */
243 if (cur->state == sockunconnected) {
244 radlog(L_DBG, "rlm_sql (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
246 #ifdef HAVE_PTHREAD_H
247 pthread_mutex_unlock(&cur->mutex);
252 /* should be connected, grab it */
253 radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
255 if (unconnected != 0 || tried_to_connect != 0) {
256 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);
260 * The socket is returned in the locked
263 * We also remember where we left off,
264 * so that the next search can start from
267 * Note that multiple threads MAY over-write
268 * the 'inst->last_used' variable. This is OK,
269 * as it's a pointer only used for reading.
271 inst->last_used = cur->next;
274 /* move along the list */
279 * Because we didnt start at the start, once we
280 * hit the end of the linklist, we should go
281 * back to the beginning and work toward the
289 * If we're at the socket we started
296 /* We get here if every DB handle is unconnected and unconnectABLE */
297 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);
301 /*************************************************************************
303 * Function: sql_release_socket
305 * Purpose: Frees a SQL sqlsocket back to the connection pool
307 *************************************************************************/
308 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
310 #ifdef HAVE_PTHREAD_H
311 pthread_mutex_unlock(&sqlsocket->mutex);
314 radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
315 inst->config->xlat_name, sqlsocket->id);
321 /*************************************************************************
323 * Function: sql_userparse
325 * Purpose: Read entries from the database and fill VALUE_PAIR structures
327 *************************************************************************/
328 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row, int querymode)
330 VALUE_PAIR *pair, *check;
332 char buf[MAX_STRING_LEN];
334 LRAD_TOKEN token, operator = T_EOL;
337 * Verify the 'Attribute' field
339 if (row[2] == NULL || row[2][0] == '\0') {
340 radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
345 * Verify the 'op' field
347 if (row[4] != NULL && row[4][0] != '\0') {
349 operator = gettoken(&ptr, buf, sizeof(buf));
351 if (operator <= T_EOL) {
353 * Complain about empty or invalid 'op' field
355 operator = T_OP_CMP_EQ;
356 radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
357 radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
361 * The 'Value' field may be empty or NULL
365 * If we have a new-style quoted string, where the
366 * *entire* string is quoted, do xlat's.
368 if (row[3] != NULL &&
369 ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
370 (row[3][0] == row[3][strlen(row[3])-1])) {
372 token = gettoken(&value, buf, sizeof(buf));
375 * Take the unquoted string.
377 case T_SINGLE_QUOTED_STRING:
378 case T_DOUBLE_QUOTED_STRING:
383 * Mark the pair to be allocated later.
385 case T_BACK_QUOTED_STRING:
391 * Keep the original string.
402 pair = pairmake(row[2], value, operator);
404 radlog(L_ERR, "rlm_sql: Failed to create the pair: %s", librad_errstr);
408 pair->flags.do_xlat = 1;
409 strNcpy(pair->strvalue, buf, sizeof(pair->strvalue));
414 * If attribute is already there, skip it because we
415 * checked usercheck first and we want user settings to
416 * override group settings
418 if (operator != T_OP_ADD && (check = pairfind(*first_pair, pair->attribute)) != NULL &&
420 pair->type != PW_TYPE_ABINARY &&
422 querymode == PW_VP_GROUPDATA) {
428 * Add the pair into the packet
430 pairadd(first_pair, pair);
435 /*************************************************************************
437 * Function: rlm_sql_fetch_row
439 * Purpose: call the module's sql_fetch_row and implement re-connect
441 *************************************************************************/
442 int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
446 if (sqlsocket->conn) {
447 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
452 if (ret == SQL_DOWN) {
453 /* close the socket that failed, but only if it was open */
454 if (sqlsocket->conn) {
455 (inst->module->sql_close)(sqlsocket, inst->config);
458 /* reconnect the socket */
459 if (connect_single_socket(sqlsocket, inst) < 0) {
460 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
464 /* retry the query on the newly connected socket */
465 ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
468 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
469 inst->config->xlat_name);
477 /*************************************************************************
479 * Function: rlm_sql_query
481 * Purpose: call the module's sql_query and implement re-connect
483 *************************************************************************/
484 int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
489 * If there's no query, return an error.
491 if (!query || !*query) {
495 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
497 if (ret == SQL_DOWN) {
498 /* close the socket that failed */
499 if (sqlsocket->state == sockconnected) {
500 (inst->module->sql_close)(sqlsocket, inst->config);
503 /* reconnect the socket */
504 if (connect_single_socket(sqlsocket, inst) < 0) {
505 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
509 /* retry the query on the newly connected socket */
510 ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
513 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
514 inst->config->xlat_name);
522 /*************************************************************************
524 * Function: rlm_sql_select_query
526 * Purpose: call the module's sql_select_query and implement re-connect
528 *************************************************************************/
529 int rlm_sql_select_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
534 * If there's no query, return an error.
536 if (!query || !*query) {
540 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
542 if (ret == SQL_DOWN) {
543 /* close the socket that failed */
544 if (sqlsocket->state == sockconnected) {
545 (inst->module->sql_close)(sqlsocket, inst->config);
548 /* reconnect the socket */
549 if (connect_single_socket(sqlsocket, inst) < 0) {
550 radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
554 /* retry the query on the newly connected socket */
555 ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
558 radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
559 inst->config->xlat_name);
568 /*************************************************************************
570 * Function: sql_getvpdata
572 * Purpose: Get any group check or reply pairs
574 *************************************************************************/
575 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query, int mode)
581 * If there's no query, return an error.
583 if (!query || !*query) {
587 if (rlm_sql_select_query(sqlsocket, inst, query)) {
588 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
591 while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
592 row = sqlsocket->row;
595 if (sql_userparse(pair, row, mode) != 0) {
596 radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
597 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
602 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
607 void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
609 FILE *sqlfile = NULL;
611 if (inst->config->sqltrace) {
614 if (!radius_xlat(buffer, sizeof(buffer),
615 inst->config->tracefile, request, NULL)) {
616 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
617 inst->config->xlat_name);
621 if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
622 radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
623 inst->config->xlat_name,
626 int fd = fileno(sqlfile);
628 rad_lockfd(fd, MAX_QUERY_LEN);
629 fputs(querystr, sqlfile);
630 fputs(";\n", sqlfile);
631 fclose(sqlfile); /* and release the lock */