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 "sockunconnected"
58 * and set a grace period, during which we won't try connecting again (to prevent unduly
59 * lagging the server and being impolite to a DB server that may be having other
60 * issues). If successful in connecting, set state to sockconnected. - chad
62 static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst) {
63 if ((inst->module->sql_init_socket)(sqlsocket, inst->config) < 0) {
64 radlog(L_CONS | L_ERR, "rlm_sql: Failed to connect DB handle #%d", sqlsocket->id);
65 inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
66 sqlsocket->state = sockunconnected;
69 radlog(L_DBG, "rlm_sql: Connected new DB handle, #%d", sqlsocket->id);
70 sqlsocket->state = sockconnected;
76 /*************************************************************************
78 * Function: sql_init_socketpool
80 * Purpose: Connect to the sql server, if possible
82 *************************************************************************/
83 int sql_init_socketpool(SQL_INST * inst) {
88 inst->connect_after = 0;
92 for (i = 0; i < inst->config->num_sql_socks; i++) {
94 sqlsocket = rad_malloc(sizeof(SQLSOCK));
95 if (sqlsocket == NULL) {
98 sqlsocket->conn = NULL;
100 sqlsocket->state = sockunconnected;
104 * FIXME! Check return codes!
106 sqlsocket->semaphore = (sem_t *) rad_malloc(sizeof(sem_t));
107 sem_init(sqlsocket->semaphore, 0, SQLSOCK_UNLOCKED);
109 sqlsocket->in_use = SQLSOCK_UNLOCKED;
112 if (time(NULL) > inst->connect_after) {
113 /* this sets the sqlsocket->state, and possibly sets inst->connect_after */
114 connect_single_socket(sqlsocket, inst);
117 /* Add this socket to the list of sockets */
118 sqlsocket->next = inst->sqlpool;
119 inst->sqlpool = sqlsocket;
125 /*************************************************************************
127 * Function: sql_poolfree
129 * Purpose: Clean up and free sql pool
131 *************************************************************************/
132 void sql_poolfree(SQL_INST * inst) {
136 for (cur = inst->sqlpool; cur; cur = cur->next) {
137 sql_close_socket(inst, cur);
142 /*************************************************************************
144 * Function: sql_close_socket
146 * Purpose: Close and free a sql sqlsocket
148 *************************************************************************/
149 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket) {
151 radlog(L_DBG, "rlm_sql: Closing sqlsocket %d", sqlsocket->id);
152 (inst->module->sql_close)(sqlsocket, inst->config);
154 sem_destroy(sqlsocket->semaphore);
161 /*************************************************************************
163 * Function: sql_get_socket
165 * Purpose: Return a SQL sqlsocket from the connection pool
167 *************************************************************************/
168 SQLSOCK * sql_get_socket(SQL_INST * inst) {
170 int tried_to_connect = 0;
172 while (inst->used == inst->config->num_sql_socks) {
173 radlog(L_ERR, "rlm_sql: All sockets are being used! Please increase the maximum number of sockets!");
177 for (cur = inst->sqlpool; cur; cur = cur->next) {
179 /* if we happen upon an unconnected socket, and this instance's grace
180 * period on (re)connecting has expired, then try to connect it. This
181 * should be really rare. - chad
183 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
184 tried_to_connect = 1;
185 radlog(L_INFO, "rlm_sql: Trying to (re)connect an unconnected handle...");
186 connect_single_socket(cur, inst);
189 /* if we still aren't connected, ignore this handle */
190 if (cur->state == sockunconnected) {
191 radlog(L_DBG, "rlm_sql: Ignoring unconnected handle");
196 if (sem_trywait(cur->semaphore) == 0) {
198 if (cur->in_use == SQLSOCK_UNLOCKED) {
201 #ifndef HAVE_SEMAPHORE_H
202 cur->in_use = SQLSOCK_LOCKED;
204 radlog(L_DBG, "rlm_sql: Reserving sql socket id: %d", cur->id);
209 /* We get here if every DB handle is unconnected and unconnectABLE */
210 radlog((tried_to_connect = 0) ? (L_DBG) : (L_CONS | L_ERR), "rlm_sql: There are no DB handles to use!");
214 /*************************************************************************
216 * Function: sql_release_socket
218 * Purpose: Frees a SQL sqlsocket back to the connection pool
220 *************************************************************************/
221 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket) {
225 sem_post(sqlsocket->semaphore);
227 sqlsocket->in_use = SQLSOCK_UNLOCKED;
230 radlog(L_DBG, "rlm_sql: Released sql socket id: %d", sqlsocket->id);
236 /*************************************************************************
238 * Function: sql_userparse
240 * Purpose: Read entries from the database and fill VALUE_PAIR structures
242 *************************************************************************/
243 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row, int querymode) {
246 VALUE_PAIR *pair, *check;
249 int pairmode = T_EOL;
251 if ((attr = dict_attrbyname(row[2])) == (DICT_ATTR *) NULL) {
252 radlog(L_ERR | L_CONS, "rlm_sql: unknown attribute %s", row[2]);
256 if (row[4] != NULL && strlen(row[4]) > 0) {
258 pairmode = gettoken(&ptr, buf, sizeof(buf));
260 if (pairmode <= T_EOL) pairmode = T_OP_CMP_EQ;
263 * If attribute is already there, skip it because we checked usercheck first
264 * and we want user settings to over ride group settings
266 if (pairmode != T_OP_ADD && (check = pairfind(*first_pair, attr->attr)) != NULL &&
268 attr->type != PW_TYPE_ABINARY &&
270 querymode == PW_VP_GROUPDATA)
273 pair = pairmake(row[2], row[3], pairmode);
274 pairadd(first_pair, pair);
280 /*************************************************************************
282 * Function: sql_getvpdata
284 * Purpose: Get any group check or reply pairs
286 *************************************************************************/
287 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query, int mode) {
292 if ((inst->module->sql_select_query)(sqlsocket, inst->config, query) < 0) {
293 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
296 while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
297 if (sql_userparse(pair, row, mode) != 0) {
298 radlog(L_ERR | L_CONS, "rlm_sql: Error getting data from database");
299 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
304 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
316 /*************************************************************************
318 * Function: sql_check_ts
320 * Purpose: Checks the terminal server for a spacific login entry
322 *************************************************************************/
323 static int sql_check_ts(SQL_ROW row) {
330 void (*handler) (int);
335 if ((nas = nas_find(ip_addr(row[4]))) == NULL) {
336 radlog(L_ERR, "rlm_sql: unknown NAS [%s]", row[4]);
343 handler = signal(SIGCHLD, SIG_DFL);
344 if ((pid = fork()) < 0) {
345 radlog(L_ERR, "rlm_sql: fork: %s", strerror(errno));
346 signal(SIGCHLD, handler);
352 * Parent - Wait for checkrad to terminate.
353 * We timeout in 10 seconds.
356 signal(SIGALRM, alrm_handler);
358 while ((e = waitpid(pid, &st, 0)) != pid)
359 if (e < 0 && (errno != EINTR || got_alrm))
362 signal(SIGCHLD, handler);
367 radlog(L_ERR, "rlm_sql: Check-TS: timeout waiting for checkrad");
371 radlog(L_ERR, "rlm_sql: Check-TS: unknown error in waitpid()");
374 return WEXITSTATUS(st);
378 * Child - exec checklogin with the right parameters.
380 for (n = 32; n >= 3; n--)
383 sprintf(session_id, "%.8s", row[1]);
386 execl(CHECKRAD2, "checkrad", nas->nastype, row[4], row[5],
387 row[2], session_id, NULL);
388 if (errno == ENOENT) {
390 execl(CHECKRAD1, "checklogin", nas->nastype, row[4], row[5],
391 row[2], session_id, NULL);
393 radlog(L_ERR, "rlm_sql: Check-TS: exec %s: %s", s, strerror(errno));
396 * Exit - 2 means "some error occured".
403 /*************************************************************************
405 * Function: sql_check_multi
407 * Purpose: Check radius accounting for duplicate logins
409 *************************************************************************/
410 int sql_check_multi(SQL_INST * inst, SQLSOCK * sqlsocket, char *name, VALUE_PAIR * request, int maxsimul) {
412 char querystr[MAX_QUERY_LEN];
420 sprintf(authstr, "UserName = '%s'", name);
421 sprintf(querystr, "SELECT COUNT(*) FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
422 if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
423 radlog(L_ERR, "sql_check_multi: database query error");
427 row = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
428 count = atoi(row[0]);
429 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
431 if (count < maxsimul)
435 * * Setup some stuff, like for MPP detection.
437 if ((fra = pairfind(request, PW_FRAMED_IP_ADDRESS)) != NULL)
438 ipno = htonl(fra->lvalue);
441 sprintf(querystr, "SELECT * FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
442 if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
443 radlog(L_ERR, "sql_check_multi: database query error");
446 while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
447 int check = sql_check_ts(row);
452 if (ipno && atoi(row[19]) == ipno)
455 } else if (check == 2)
456 radlog(L_ERR, "rlm_sql: Problem with checkrad [%s] (from nas %s)", name, row[4]);
459 * False record - zap it
462 if (inst->config->deletestalesessions) {
465 radlog(L_ERR, "rlm_sql: Deleteing stale session [%s] (from nas %s/%s)", row[2], row[4], row[5]);
466 sqlsocket1 = sql_get_socket(inst);
467 sprintf(querystr, "DELETE FROM %s WHERE RadAcctId = '%s'", inst->config->sql_acct_table, row[0]);
468 (inst->module->sql_query)(sqlsocket1, inst->config, querystr);
469 (inst->module->sql_finish_query)(sqlsocket1, inst->config);
470 sql_release_socket(inst, sqlsocket1);
474 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
476 return (count < maxsimul) ? 0 : mpp;
479 void query_log(SQL_INST * inst, char *querystr) {
480 FILE *sqlfile = NULL;
482 if (inst->config->sqltrace) {
483 if ((sqlfile = fopen(inst->config->tracefile, "a")) == (FILE *) NULL) {
484 radlog(L_ERR, "rlm_sql: Couldn't open file %s",
485 inst->config->tracefile);
487 int fd = fileno(sqlfile);
489 rad_lockfd(fd, MAX_QUERY_LEN);
490 fputs(querystr, sqlfile);
491 fputs(";\n", sqlfile);
492 fclose(sqlfile); /* and release the lock */