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;
93 for (i = 0; i < inst->config->num_sql_socks; i++) {
95 sqlsocket = rad_malloc(sizeof(SQLSOCK));
96 if (sqlsocket == NULL) {
99 sqlsocket->conn = NULL;
101 sqlsocket->state = sockunconnected;
105 * FIXME! Check return codes!
107 sqlsocket->semaphore = (sem_t *) rad_malloc(sizeof(sem_t));
108 sem_init(sqlsocket->semaphore, 0, SQLSOCK_UNLOCKED);
110 sqlsocket->in_use = SQLSOCK_UNLOCKED;
113 if (time(NULL) > inst->connect_after) {
114 /* this sets the sqlsocket->state, and possibly sets inst->connect_after */
115 connect_single_socket(sqlsocket, inst);
118 /* Add this socket to the list of sockets */
119 sqlsocket->next = inst->sqlpool;
120 inst->sqlpool = sqlsocket;
124 pthread_mutex_init(&inst->mutex, NULL);
130 /*************************************************************************
132 * Function: sql_poolfree
134 * Purpose: Clean up and free sql pool
136 *************************************************************************/
137 void sql_poolfree(SQL_INST * inst) {
141 for (cur = inst->sqlpool; cur; cur = cur->next) {
142 sql_close_socket(inst, cur);
145 pthread_mutex_destroy(&inst->mutex);
150 /*************************************************************************
152 * Function: sql_close_socket
154 * Purpose: Close and free a sql sqlsocket
156 *************************************************************************/
157 int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket) {
159 radlog(L_DBG, "rlm_sql: Closing sqlsocket %d", sqlsocket->id);
160 (inst->module->sql_close)(sqlsocket, inst->config);
162 sem_destroy(sqlsocket->semaphore);
169 /*************************************************************************
171 * Function: sql_get_socket
173 * Purpose: Return a SQL sqlsocket from the connection pool
175 *************************************************************************/
176 SQLSOCK * sql_get_socket(SQL_INST * inst) {
178 int tried_to_connect = 0;
180 while (inst->used == inst->config->num_sql_socks) {
181 radlog(L_ERR, "rlm_sql: All sockets are being used! Please increase the maximum number of sockets!");
186 * Rotating the socket so that all get used and none get closed due to
187 * inactivity from the SQL server ( such as mySQL ).
190 pthread_mutex_lock(&inst->mutex);
193 if(inst->socknr == 0) {
194 inst->socknr = inst->config->num_sql_socks;
197 cur2 = inst->sqlpool;
198 while (inst->socknr != cur2->id) {
202 pthread_mutex_unlock(&inst->mutex);
205 for (cur = cur2; cur; cur = cur->next) {
207 /* if we happen upon an unconnected socket, and this instance's grace
208 * period on (re)connecting has expired, then try to connect it. This
209 * should be really rare. - chad
211 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
212 tried_to_connect = 1;
213 radlog(L_INFO, "rlm_sql: Trying to (re)connect an unconnected handle...");
214 connect_single_socket(cur, inst);
217 /* if we still aren't connected, ignore this handle */
218 if (cur->state == sockunconnected) {
219 radlog(L_DBG, "rlm_sql: Ignoring unconnected handle");
224 if (sem_trywait(cur->semaphore) == 0) {
226 if (cur->in_use == SQLSOCK_UNLOCKED) {
229 #ifndef HAVE_SEMAPHORE_H
230 cur->in_use = SQLSOCK_LOCKED;
232 radlog(L_DBG, "rlm_sql: Reserving sql socket id: %d", cur->id);
237 /* We get here if every DB handle is unconnected and unconnectABLE */
238 radlog((tried_to_connect = 0) ? (L_DBG) : (L_CONS | L_ERR), "rlm_sql: There are no DB handles to use!");
242 /*************************************************************************
244 * Function: sql_release_socket
246 * Purpose: Frees a SQL sqlsocket back to the connection pool
248 *************************************************************************/
249 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket) {
253 sem_post(sqlsocket->semaphore);
255 sqlsocket->in_use = SQLSOCK_UNLOCKED;
258 radlog(L_DBG, "rlm_sql: Released sql socket id: %d", sqlsocket->id);
264 /*************************************************************************
266 * Function: sql_userparse
268 * Purpose: Read entries from the database and fill VALUE_PAIR structures
270 *************************************************************************/
271 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row, int querymode) {
274 VALUE_PAIR *pair, *check;
277 int pairmode = T_EOL;
279 if ((attr = dict_attrbyname(row[2])) == (DICT_ATTR *) NULL) {
280 radlog(L_ERR | L_CONS, "rlm_sql: unknown attribute %s", row[2]);
284 if (row[4] != NULL && strlen(row[4]) > 0) {
286 pairmode = gettoken(&ptr, buf, sizeof(buf));
288 if (pairmode <= T_EOL) pairmode = T_OP_CMP_EQ;
291 * If attribute is already there, skip it because we checked usercheck first
292 * and we want user settings to over ride group settings
294 if (pairmode != T_OP_ADD && (check = pairfind(*first_pair, attr->attr)) != NULL &&
296 attr->type != PW_TYPE_ABINARY &&
298 querymode == PW_VP_GROUPDATA)
301 pair = pairmake(row[2], row[3], pairmode);
302 pairadd(first_pair, pair);
308 /*************************************************************************
310 * Function: sql_getvpdata
312 * Purpose: Get any group check or reply pairs
314 *************************************************************************/
315 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query, int mode) {
320 if ((inst->module->sql_select_query)(sqlsocket, inst->config, query) < 0) {
321 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
324 while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
325 if (sql_userparse(pair, row, mode) != 0) {
326 radlog(L_ERR | L_CONS, "rlm_sql: Error getting data from database");
327 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
332 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
340 alrm_handler(int i) {
344 /*************************************************************************
346 * Function: sql_check_ts
348 * Purpose: Checks the terminal server for a spacific login entry
350 *************************************************************************/
351 static int sql_check_ts(SQL_ROW row) {
358 void (*handler) (int);
363 if ((nas = nas_find(ip_addr(row[4]))) == NULL) {
364 radlog(L_ERR, "rlm_sql: unknown NAS [%s]", row[4]);
371 handler = signal(SIGCHLD, SIG_DFL);
372 if ((pid = fork()) < 0) {
373 radlog(L_ERR, "rlm_sql: fork: %s", strerror(errno));
374 signal(SIGCHLD, handler);
380 * Parent - Wait for checkrad to terminate.
381 * We timeout in 10 seconds.
384 signal(SIGALRM, alrm_handler);
386 while ((e = waitpid(pid, &st, 0)) != pid)
387 if (e < 0 && (errno != EINTR || got_alrm))
390 signal(SIGCHLD, handler);
395 radlog(L_ERR, "rlm_sql: Check-TS: timeout waiting for checkrad");
399 radlog(L_ERR, "rlm_sql: Check-TS: unknown error in waitpid()");
402 return WEXITSTATUS(st);
406 * Child - exec checklogin with the right parameters.
408 for (n = 32; n >= 3; n--)
411 sprintf(session_id, "%.8s", row[1]);
414 execl(CHECKRAD2, "checkrad", nas->nastype, row[4], row[5],
415 row[2], session_id, NULL);
416 if (errno == ENOENT) {
418 execl(CHECKRAD1, "checklogin", nas->nastype, row[4], row[5],
419 row[2], session_id, NULL);
421 radlog(L_ERR, "rlm_sql: Check-TS: exec %s: %s", s, strerror(errno));
424 * Exit - 2 means "some error occured".
431 /*************************************************************************
433 * Function: sql_check_multi
435 * Purpose: Check radius accounting for duplicate logins
437 *************************************************************************/
438 int sql_check_multi(SQL_INST * inst, SQLSOCK * sqlsocket, char *name, VALUE_PAIR * request, int maxsimul) {
440 char querystr[MAX_QUERY_LEN];
448 sprintf(authstr, "UserName = '%s'", name);
449 sprintf(querystr, "SELECT COUNT(*) FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
450 if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
451 radlog(L_ERR, "sql_check_multi: database query error");
455 row = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
456 count = atoi(row[0]);
457 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
459 if (count < maxsimul)
463 * * Setup some stuff, like for MPP detection.
465 if ((fra = pairfind(request, PW_FRAMED_IP_ADDRESS)) != NULL)
466 ipno = htonl(fra->lvalue);
469 sprintf(querystr, "SELECT * FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
470 if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
471 radlog(L_ERR, "sql_check_multi: database query error");
474 while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
475 int check = sql_check_ts(row);
480 if (ipno && atoi(row[19]) == ipno)
483 } else if (check == 2)
484 radlog(L_ERR, "rlm_sql: Problem with checkrad [%s] (from nas %s)", name, row[4]);
487 * False record - zap it
490 if (inst->config->deletestalesessions) {
493 radlog(L_ERR, "rlm_sql: Deleteing stale session [%s] (from nas %s/%s)", row[2], row[4], row[5]);
494 sqlsocket1 = sql_get_socket(inst);
495 sprintf(querystr, "DELETE FROM %s WHERE RadAcctId = '%s'", inst->config->sql_acct_table, row[0]);
496 (inst->module->sql_query)(sqlsocket1, inst->config, querystr);
497 (inst->module->sql_finish_query)(sqlsocket1, inst->config);
498 sql_release_socket(inst, sqlsocket1);
502 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
504 return (count < maxsimul) ? 0 : mpp;
507 void query_log(SQL_INST * inst, char *querystr) {
508 FILE *sqlfile = NULL;
510 if (inst->config->sqltrace) {
511 if ((sqlfile = fopen(inst->config->tracefile, "a")) == (FILE *) NULL) {
512 radlog(L_ERR, "rlm_sql: Couldn't open file %s",
513 inst->config->tracefile);
515 int fd = fileno(sqlfile);
517 rad_lockfd(fd, MAX_QUERY_LEN);
518 fputs(querystr, sqlfile);
519 fputs(";\n", sqlfile);
520 fclose(sqlfile); /* and release the lock */