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 struct timeval timeout;
171 int tried_to_connect = 0;
173 while (inst->used == inst->config->num_sql_socks) {
174 radlog(L_ERR, "rlm_sql: All sockets are being used! Please increase the maximum number of sockets!");
178 for (cur = inst->sqlpool; cur; cur = cur->next) {
180 /* if we happen upon an unconnected socket, and this instance's grace
181 * period on (re)connecting has expired, then try to connect it. This
182 * should be really rare. - chad
184 if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
185 tried_to_connect = 1;
186 radlog(L_INFO, "rlm_sql: Trying to (re)connect an unconnected handle...");
187 connect_single_socket(cur, inst);
190 /* if we still aren't connected, ignore this handle */
191 if (cur->state == sockunconnected) {
192 radlog(L_DBG, "rlm_sql: Ignoring unconnected handle");
197 if (sem_trywait(cur->semaphore) == 0) {
199 if (cur->in_use == SQLSOCK_UNLOCKED) {
203 cur->in_use = SQLSOCK_LOCKED;
205 radlog(L_DBG, "rlm_sql: Reserving sql socket id: %d", cur->id);
210 /* We get here if every DB handle is unconnected and unconnectABLE */
211 radlog((tried_to_connect = 0) ? (L_DBG) : (L_CONS | L_ERR), "rlm_sql: There are no DB handles to use!");
215 /*************************************************************************
217 * Function: sql_release_socket
219 * Purpose: Frees a SQL sqlsocket back to the connection pool
221 *************************************************************************/
222 int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket) {
226 sem_post(sqlsocket->semaphore);
228 sqlsocket->in_use = SQLSOCK_UNLOCKED;
231 radlog(L_DBG, "rlm_sql: Released sql socket id: %d", sqlsocket->id);
237 /*************************************************************************
239 * Function: sql_userparse
241 * Purpose: Read entries from the database and fill VALUE_PAIR structures
243 *************************************************************************/
244 int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row, int mode) {
247 VALUE_PAIR *pair, *check;
249 if ((attr = dict_attrbyname(row[2])) == (DICT_ATTR *) NULL) {
250 radlog(L_ERR | L_CONS, "rlm_sql: unknown attribute %s", row[2]);
255 * If attribute is already there, skip it because we checked usercheck first
256 * and we want user settings to over ride group settings
258 if ((check = pairfind(*first_pair, attr->attr)) != NULL &&
259 #if defined( BINARY_FILTERS )
260 attr->type != PW_TYPE_ABINARY &&
262 mode == PW_VP_GROUPDATA)
265 pair = pairmake(row[2], row[3], T_OP_CMP_EQ);
266 pairadd(first_pair, pair);
268 vp_printlist(stderr, *first_pair);
274 /*************************************************************************
276 * Function: sql_getvpdata
278 * Purpose: Get any group check or reply pairs
280 *************************************************************************/
281 int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query, int mode) {
286 if ((inst->module->sql_select_query)(sqlsocket, inst->config, query) < 0) {
287 radlog(L_ERR, "rlm_sql_getvpdata: database query error");
290 while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
291 if (sql_userparse(pair, row, mode) != 0) {
292 radlog(L_ERR | L_CONS, "rlm_sql: Error getting data from database");
293 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
298 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
310 /*************************************************************************
312 * Function: sql_check_ts
314 * Purpose: Checks the terminal server for a spacific login entry
316 *************************************************************************/
317 static int sql_check_ts(SQL_ROW row) {
324 void (*handler) (int);
329 if ((nas = nas_find(ip_addr(row[4]))) == NULL) {
330 radlog(L_ERR, "rlm_sql: unknown NAS [%s]", row[4]);
337 handler = signal(SIGCHLD, SIG_DFL);
338 if ((pid = fork()) < 0) {
339 radlog(L_ERR, "rlm_sql: fork: %s", strerror(errno));
340 signal(SIGCHLD, handler);
346 * Parent - Wait for checkrad to terminate.
347 * We timeout in 10 seconds.
350 signal(SIGALRM, alrm_handler);
352 while ((e = waitpid(pid, &st, 0)) != pid)
353 if (e < 0 && (errno != EINTR || got_alrm))
356 signal(SIGCHLD, handler);
361 radlog(L_ERR, "rlm_sql: Check-TS: timeout waiting for checkrad");
365 radlog(L_ERR, "rlm_sql: Check-TS: unknown error in waitpid()");
368 return WEXITSTATUS(st);
372 * Child - exec checklogin with the right parameters.
374 for (n = 32; n >= 3; n--)
377 sprintf(session_id, "%.8s", row[1]);
380 execl(CHECKRAD2, "checkrad", nas->nastype, row[4], row[5],
381 row[2], session_id, NULL);
382 if (errno == ENOENT) {
384 execl(CHECKRAD1, "checklogin", nas->nastype, row[4], row[5],
385 row[2], session_id, NULL);
387 radlog(L_ERR, "rlm_sql: Check-TS: exec %s: %s", s, strerror(errno));
390 * Exit - 2 means "some error occured".
397 /*************************************************************************
399 * Function: sql_check_multi
401 * Purpose: Check radius accounting for duplicate logins
403 *************************************************************************/
404 int sql_check_multi(SQL_INST * inst, SQLSOCK * sqlsocket, char *name, VALUE_PAIR * request, int maxsimul) {
406 char querystr[MAX_QUERY_LEN];
414 sprintf(authstr, "UserName = '%s'", name);
415 sprintf(querystr, "SELECT COUNT(*) FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
416 if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
417 radlog(L_ERR, "sql_check_multi: database query error");
421 row = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
422 count = atoi(row[0]);
423 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
425 if (count < maxsimul)
429 * * Setup some stuff, like for MPP detection.
431 if ((fra = pairfind(request, PW_FRAMED_IP_ADDRESS)) != NULL)
432 ipno = htonl(fra->lvalue);
435 sprintf(querystr, "SELECT * FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
436 if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
437 radlog(L_ERR, "sql_check_multi: database query error");
440 while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
441 int check = sql_check_ts(row);
446 if (ipno && atoi(row[19]) == ipno)
449 } else if (check == 2)
450 radlog(L_ERR, "rlm_sql: Problem with checkrad [%s] (from nas %s)", name, row[4]);
453 * False record - zap it
456 if (inst->config->deletestalesessions) {
459 radlog(L_ERR, "rlm_sql: Deleteing stale session [%s] (from nas %s/%s)", row[2], row[4], row[5]);
460 sqlsocket1 = sql_get_socket(inst);
461 sprintf(querystr, "DELETE FROM %s WHERE RadAcctId = '%s'", inst->config->sql_acct_table, row[0]);
462 (inst->module->sql_query)(sqlsocket1, inst->config, querystr);
463 (inst->module->sql_finish_query)(sqlsocket1, inst->config);
464 sql_release_socket(inst, sqlsocket1);
468 (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
470 return (count < maxsimul) ? 0 : mpp;
473 void query_log(SQL_INST * inst, char *querystr) {
476 if (inst->config->sqltrace) {
477 if ((sqlfile = fopen(inst->config->tracefile, "a")) == (FILE *) NULL) {
478 radlog(L_ERR, "rlm_sql: Couldn't open file %s",
479 inst->config->tracefile);
481 #if defined(F_LOCK) && !defined(BSD)
482 (void) lockf((int) sqlfile, (int) F_LOCK, (off_t) MAX_QUERY_LEN);
484 (void) flock(sqlfile, SQL_LOCK_EX);
486 fputs(querystr, sqlfile);
487 fputs(";\n", sqlfile);
493 int sql_set_user(SQL_INST *inst, REQUEST *request, char *sqlusername, char *username) {
495 char tmpuser[MAX_STRING_LEN];
500 /* Remove any user attr we added previously */
501 pairdelete(&request->packet->vps, PW_SQL_USER_NAME);
504 strNcpy(tmpuser, username, MAX_STRING_LEN);
505 } else if(strlen(inst->config->query_user)) {
506 radius_xlat(tmpuser, MAX_STRING_LEN, inst->config->query_user, request, NULL);
511 if(strlen(tmpuser)) {
512 sql_escape_string(sqlusername, tmpuser, MAX_STRING_LEN);
513 DEBUG2("sql_set_user: escaped user --> '%s'", sqlusername);
514 vp = pairmake("SQL-User-Name", sqlusername, 0);
516 radlog(L_ERR, "%s", librad_errstr);
520 pairadd(&request->packet->vps, vp);
527 * Purpose: Esacpe "'" and any other wierd charactors
529 int sql_escape_string(char *to, char *from, int length) {
532 DEBUG2("sql_escape in: '%s'", from);
534 for(x=0, y=0; (x < length) && (from[x]!='\0'); x++) {
564 /* Ascii file separator */
575 DEBUG2("sql_escape out: '%s'", to);