port fix from branch_1_1
[freeradius.git] / src / modules / rlm_sql / sql.c
index bdaa48f..c0f713a 100644 (file)
  *
  *   You should have received a copy of the GNU General Public License
  *   along with this program; if not, write to the Free Software
- *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
  *
- * Copyright 2001  The FreeRADIUS server project
+ * Copyright 2001,2006  The FreeRADIUS server project
  * Copyright 2000  Mike Machado <mike@innercite.com>
  * Copyright 2000  Alan DeKok <aland@ox.org>
  * Copyright 2001  Chad Miller <cmiller@surfsouth.com>
  */
 
+#include <freeradius-devel/ident.h>
+RCSID("$Id$")
+
+#include       <freeradius-devel/autoconf.h>
 
 #include       <sys/types.h>
 #include       <sys/socket.h>
 #include       <errno.h>
 #include       <sys/wait.h>
 
-#if HAVE_PTHREAD_H
-#include       <pthread.h>
-#endif
-
-#include       "radiusd.h"
-#include       "conffile.h"
+#include       <freeradius-devel/radiusd.h>
 #include       "rlm_sql.h"
 
+#ifdef HAVE_PTHREAD_H
+#endif
+
 
 /*
- * Connect to a server.  If error, set this socket's state to be "sockunconnected"
- * and set a grace period, during which we won't try connecting again (to prevent unduly
- * lagging the server and being impolite to a DB server that may be having other 
- * issues).  If successful in connecting, set state to sockconnected.   - chad
+ * Connect to a server.  If error, set this socket's state to be
+ * "sockunconnected" and set a grace period, during which we won't try
+ * connecting again (to prevent unduly lagging the server and being
+ * impolite to a DB server that may be having other issues).  If
+ * successful in connecting, set state to sockconnected.
+ * - chad
  */
-static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst) {
-       if ((inst->module->sql_init_socket)(sqlsocket, inst->config) < 0) {
-               radlog(L_CONS | L_ERR, "rlm_sql:  Failed to connect DB handle #%d", sqlsocket->id);
-               inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
-               sqlsocket->state = sockunconnected;
-               return(-1);
-       } else {
-               radlog(L_DBG, "rlm_sql:  Connected new DB handle, #%d", sqlsocket->id);
+static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst)
+{
+       int rcode;
+       radlog(L_DBG, "rlm_sql (%s): Attempting to connect %s #%d",
+              inst->config->xlat_name, inst->module->name, sqlsocket->id);
+
+       rcode = (inst->module->sql_init_socket)(sqlsocket, inst->config);
+       if (rcode == 0) {
+               radlog(L_DBG, "rlm_sql (%s): Connected new DB handle, #%d",
+                      inst->config->xlat_name, sqlsocket->id);
                sqlsocket->state = sockconnected;
                return(0);
        }
+
+       /*
+        *  Error, or SQL_DOWN.
+        */
+       radlog(L_CONS | L_ERR, "rlm_sql (%s): Failed to connect DB handle #%d", inst->config->xlat_name, sqlsocket->id);
+       inst->connect_after = time(NULL) + inst->config->connect_failure_retry_delay;
+       sqlsocket->state = sockunconnected;
+       return(-1);
 }
 
 
@@ -80,47 +94,57 @@ static int connect_single_socket(SQLSOCK *sqlsocket, SQL_INST *inst) {
  *     Purpose: Connect to the sql server, if possible
  *
  *************************************************************************/
-int sql_init_socketpool(SQL_INST * inst) {
-
+int sql_init_socketpool(SQL_INST * inst)
+{
+       int i, rcode;
+       int success = 0;
        SQLSOCK *sqlsocket;
-       int     i;
 
        inst->connect_after = 0;
-       inst->used = 0;
        inst->sqlpool = NULL;
-       inst->socknr = 0;
 
        for (i = 0; i < inst->config->num_sql_socks; i++) {
+               radlog(L_DBG, "rlm_sql (%s): starting %d",
+                      inst->config->xlat_name, i);
 
-               sqlsocket = rad_malloc(sizeof(SQLSOCK));
+               sqlsocket = rad_malloc(sizeof(*sqlsocket));
                if (sqlsocket == NULL) {
                        return -1;
                }
+               memset(sqlsocket, 0, sizeof(*sqlsocket));
                sqlsocket->conn = NULL;
                sqlsocket->id = i;
                sqlsocket->state = sockunconnected;
 
-#if HAVE_SEMAPHORE_H
-               /*
-                *  FIXME! Check return codes!
-                */
-               sqlsocket->semaphore = (sem_t *) rad_malloc(sizeof(sem_t));
-               sem_init(sqlsocket->semaphore, 0, SQLSOCK_UNLOCKED);
-#else
-               sqlsocket->in_use = SQLSOCK_UNLOCKED;
+#ifdef HAVE_PTHREAD_H
+               rcode = pthread_mutex_init(&sqlsocket->mutex,NULL);
+               if (rcode != 0) {
+                       radlog(L_ERR, "rlm_sql: Failed to init lock: %s",
+                              strerror(errno));
+                       return 0;
+               }
 #endif
 
                if (time(NULL) > inst->connect_after) {
-                       /* this sets the sqlsocket->state, and possibly sets inst->connect_after */
-                       connect_single_socket(sqlsocket, inst);
+                       /*
+                        *      This sets the sqlsocket->state, and
+                        *      possibly also inst->connect_after
+                        */
+                       if (connect_single_socket(sqlsocket, inst) == 0) {
+                               success = 1;
+                       }
                }
 
                /* Add this socket to the list of sockets */
                sqlsocket->next = inst->sqlpool;
                inst->sqlpool = sqlsocket;
        }
+       inst->last_used = NULL;
 
-       pthread_mutex_init(&inst->mutex, NULL);
+       if (!success) {
+               radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
+                      inst->config->xlat_name);
+       }
 
        return 1;
 }
@@ -132,14 +156,17 @@ int sql_init_socketpool(SQL_INST * inst) {
  *     Purpose: Clean up and free sql pool
  *
  *************************************************************************/
-void sql_poolfree(SQL_INST * inst) {
-
+void sql_poolfree(SQL_INST * inst)
+{
        SQLSOCK *cur;
+       SQLSOCK *next;
 
-       for (cur = inst->sqlpool; cur; cur = cur->next) {
+       for (cur = inst->sqlpool; cur; cur = next) {
+               next = cur->next;
                sql_close_socket(inst, cur);
        }
-       pthread_mutex_destroy(&inst->mutex);
+
+       inst->sqlpool = NULL;
 }
 
 
@@ -150,12 +177,18 @@ void sql_poolfree(SQL_INST * inst) {
  *     Purpose: Close and free a sql sqlsocket
  *
  *************************************************************************/
-int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket) {
-
-       radlog(L_DBG, "rlm_sql: Closing sqlsocket %d", sqlsocket->id);
-       (inst->module->sql_close)(sqlsocket, inst->config);
-#if HAVE_SEMAPHORE_H
-       sem_destroy(sqlsocket->semaphore);
+int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket)
+{
+       radlog(L_DBG, "rlm_sql (%s): Closing sqlsocket %d",
+              inst->config->xlat_name, sqlsocket->id);
+       if (sqlsocket->state == sockconnected) {
+               (inst->module->sql_close)(sqlsocket, inst->config);
+       }
+       if (inst->module->sql_destroy_socket) {
+               (inst->module->sql_destroy_socket)(sqlsocket, inst->config);
+       }
+#ifdef HAVE_PTHREAD_H
+       pthread_mutex_destroy(&sqlsocket->mutex);
 #endif
        free(sqlsocket);
        return 1;
@@ -166,67 +199,104 @@ int sql_close_socket(SQL_INST *inst, SQLSOCK * sqlsocket) {
  *
  *     Function: sql_get_socket
  *
- *     Purpose: Return a SQL sqlsocket from the connection pool           
+ *     Purpose: Return a SQL sqlsocket from the connection pool
  *
  *************************************************************************/
-SQLSOCK * sql_get_socket(SQL_INST * inst) {
-       SQLSOCK *cur, *cur2;
+SQLSOCK * sql_get_socket(SQL_INST * inst)
+{
+       SQLSOCK *cur, *start;
        int tried_to_connect = 0;
-
-       while (inst->used == inst->config->num_sql_socks) {
-               radlog(L_ERR, "rlm_sql: All sockets are being used! Please increase the maximum number of sockets!");
-               return NULL;
-       }
+       int unconnected = 0;
 
        /*
-        * Rotating the socket so that all get used and none get closed due to
-        * inactivity from the SQL server ( such as mySQL ).
+        *      Start at the last place we left off.
         */
-       pthread_mutex_lock(&inst->mutex);
-       if(inst->socknr == 0) {
-               inst->socknr = inst->config->num_sql_socks;
-       }
-       inst->socknr--;
-       cur2 = inst->sqlpool;
-       while (inst->socknr != cur2->id) {
-               cur2 = cur2->next;
-       }
-       pthread_mutex_unlock(&inst->mutex);
+       start = inst->last_used;
+       if (!start) start = inst->sqlpool;
+
+       cur = start;
 
-       for (cur = cur2; cur; cur = cur->next) {
+       while (cur) {
+#ifdef HAVE_PTHREAD_H
+               /*
+                *      If this socket is in use by another thread,
+                *      skip it, and try another socket.
+                *
+                *      If it isn't used, then grab it ourselves.
+                */
+               if (pthread_mutex_trylock(&cur->mutex) != 0) {
+                       goto next;
+               } /* else we now have the lock */
+#endif
 
-               /* if we happen upon an unconnected socket, and this instance's grace 
-                * period on (re)connecting has expired, then try to connect it.  This 
-                * should be really rare.  - chad
+               /*
+                *      If we happen upon an unconnected socket, and
+                *      this instance's grace period on
+                *      (re)connecting has expired, then try to
+                *      connect it.  This should be really rare.
                 */
                if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
-                       tried_to_connect = 1;
-                       radlog(L_INFO, "rlm_sql: Trying to (re)connect an unconnected handle...");
+                       radlog(L_INFO, "rlm_sql (%s): Trying to (re)connect unconnected handle %d..", inst->config->xlat_name, cur->id);
+                       tried_to_connect++;
                        connect_single_socket(cur, inst);
                }
 
                /* if we still aren't connected, ignore this handle */
                if (cur->state == sockunconnected) {
-                       radlog(L_DBG, "rlm_sql: Ignoring unconnected handle");
-                       continue;
+                       radlog(L_DBG, "rlm_sql (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
+                       unconnected++;
+#ifdef HAVE_PTHREAD_H
+                       pthread_mutex_unlock(&cur->mutex);
+#endif
+                       goto next;
                }
 
-#if HAVE_SEMAPHORE_H
-               if (sem_trywait(cur->semaphore) == 0) {
-#else
-               if (cur->in_use == SQLSOCK_UNLOCKED) {
-#endif
-                       (inst->used)++;
-#ifndef HAVE_SEMAPHORE_H
-                       cur->in_use = SQLSOCK_LOCKED;
-#endif
-                       radlog(L_DBG, "rlm_sql: Reserving sql socket id: %d", cur->id);
-                       return cur;
+               /* should be connected, grab it */
+               radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
+
+               if (unconnected != 0 || tried_to_connect != 0) {
+                       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);
+               }
+
+               /*
+                *      The socket is returned in the locked
+                *      state.
+                *
+                *      We also remember where we left off,
+                *      so that the next search can start from
+                *      here.
+                *
+                *      Note that multiple threads MAY over-write
+                *      the 'inst->last_used' variable.  This is OK,
+                *      as it's a pointer only used for reading.
+                */
+               inst->last_used = cur->next;
+               return cur;
+
+               /* move along the list */
+       next:
+               cur = cur->next;
+
+               /*
+                *      Because we didnt start at the start, once we
+                *      hit the end of the linklist, we should go
+                *      back to the beginning and work toward the
+                *      middle!
+                */
+               if (!cur) {
+                       cur = inst->sqlpool;
+               }
+
+               /*
+                *      If we're at the socket we started
+                */
+               if (cur == start) {
+                       break;
                }
        }
 
        /* We get here if every DB handle is unconnected and unconnectABLE */
-       radlog((tried_to_connect = 0) ? (L_DBG) : (L_CONS | L_ERR), "rlm_sql:  There are no DB handles to use!");
+       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);
        return NULL;
 }
 
@@ -234,21 +304,19 @@ SQLSOCK * sql_get_socket(SQL_INST * inst) {
  *
  *     Function: sql_release_socket
  *
- *     Purpose: Frees a SQL sqlsocket back to the connection pool           
+ *     Purpose: Frees a SQL sqlsocket back to the connection pool
  *
  *************************************************************************/
-int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket) {
-
-       (inst->used)--;
-#if HAVE_SEMAPHORE_H
-       sem_post(sqlsocket->semaphore);
-#else
-       sqlsocket->in_use = SQLSOCK_UNLOCKED;
+int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
+{
+#ifdef HAVE_PTHREAD_H
+       pthread_mutex_unlock(&sqlsocket->mutex);
 #endif
 
-       radlog(L_DBG, "rlm_sql: Released sql socket id: %d", sqlsocket->id);
+       radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
+              inst->config->xlat_name, sqlsocket->id);
 
-       return 1;
+       return 0;
 }
 
 
@@ -259,252 +327,292 @@ int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket) {
  *     Purpose: Read entries from the database and fill VALUE_PAIR structures
  *
  *************************************************************************/
-int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row, int querymode) {
+int sql_userparse(VALUE_PAIR ** first_pair, SQL_ROW row)
+{
+       VALUE_PAIR *pair;
+       char *ptr, *value;
+       char buf[MAX_STRING_LEN];
+       char do_xlat = 0;
+       LRAD_TOKEN token, operator = T_EOL;
 
-       DICT_ATTR *attr;
-       VALUE_PAIR *pair, *check;
-       char *ptr;
-       char buf[128];
-       int pairmode = T_EOL;
-
-       if ((attr = dict_attrbyname(row[2])) == (DICT_ATTR *) NULL) {
-               radlog(L_ERR | L_CONS, "rlm_sql: unknown attribute %s", row[2]);
-               return (-1);
+       /*
+        *      Verify the 'Attribute' field
+        */
+       if (row[2] == NULL || row[2][0] == '\0') {
+               radlog(L_ERR, "rlm_sql: The 'Attribute' field is empty or NULL, skipping the entire row.");
+               return -1;
        }
 
-       if (row[4] != NULL && strlen(row[4]) > 0) {
+       /*
+        *      Verify the 'op' field
+        */
+       if (row[4] != NULL && row[4][0] != '\0') {
                ptr = row[4];
-               pairmode = gettoken(&ptr, buf, sizeof(buf));
+               operator = gettoken(&ptr, buf, sizeof(buf));
+       }
+       if (operator <= T_EOL) {
+               /*
+                *  Complain about empty or invalid 'op' field
+                */
+               operator = T_OP_CMP_EQ;
+               radlog(L_ERR, "rlm_sql: The 'op' field for attribute '%s = %s' is NULL, or non-existent.", row[2], row[3]);
+               radlog(L_ERR, "rlm_sql: You MUST FIX THIS if you want the configuration to behave as you expect.");
        }
-       if (pairmode <= T_EOL) pairmode = T_OP_CMP_EQ;
 
        /*
-        * If attribute is already there, skip it because we checked usercheck first 
-        * and we want user settings to over ride group settings 
+        *      The 'Value' field may be empty or NULL
         */
-       if (pairmode != T_OP_ADD && (check = pairfind(*first_pair, attr->attr)) != NULL &&
-#ifdef ASCEND_BINARY
-                       attr->type != PW_TYPE_ABINARY &&
-#endif
-                       querymode == PW_VP_GROUPDATA)
-               return 0;
+       value = row[3];
+       /*
+        *      If we have a new-style quoted string, where the
+        *      *entire* string is quoted, do xlat's.
+        */
+       if (row[3] != NULL &&
+          ((row[3][0] == '\'') || (row[3][0] == '`') || (row[3][0] == '"')) &&
+          (row[3][0] == row[3][strlen(row[3])-1])) {
 
-       pair = pairmake(row[2], row[3], pairmode);
-       pairadd(first_pair, pair);
+               token = gettoken(&value, buf, sizeof(buf));
+               switch (token) {
+                       /*
+                        *      Take the unquoted string.
+                        */
+               case T_SINGLE_QUOTED_STRING:
+               case T_DOUBLE_QUOTED_STRING:
+                       value = buf;
+                       break;
+
+                       /*
+                        *      Mark the pair to be allocated later.
+                        */
+               case T_BACK_QUOTED_STRING:
+                       value = NULL;
+                       do_xlat = 1;
+                       break;
+
+                       /*
+                        *      Keep the original string.
+                        */
+               default:
+                       value = row[3];
+                       break;
+               }
+       }
+
+       /*
+        *      Create the pair
+        */
+       pair = pairmake(row[2], value, operator);
+       if (pair == NULL) {
+               radlog(L_ERR, "rlm_sql: Failed to create the pair: %s", librad_errstr);
+               return -1;
+       }
+       if (do_xlat) {
+               pair->flags.do_xlat = 1;
+               strlcpy(pair->vp_strvalue, buf, sizeof(pair->vp_strvalue));
+               pair->length = 0;
+       }
 
+       /*
+        *      Add the pair into the packet
+        */
+       pairadd(first_pair, pair);
        return 0;
 }
 
 
 /*************************************************************************
  *
- *     Function: sql_getvpdata
+ *     Function: rlm_sql_fetch_row
  *
- *     Purpose: Get any group check or reply pairs
+ *     Purpose: call the module's sql_fetch_row and implement re-connect
  *
  *************************************************************************/
-int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query, int mode) {
+int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
+{
+       int ret;
 
-       SQL_ROW row;
-       int     rows = 0;
-
-       if ((inst->module->sql_select_query)(sqlsocket, inst->config, query) < 0) {
-               radlog(L_ERR, "rlm_sql_getvpdata: database query error");
-               return -1;
+       if (sqlsocket->conn) {
+               ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
+       } else {
+               ret = SQL_DOWN;
        }
-       while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
-               if (sql_userparse(pair, row, mode) != 0) {
-                       radlog(L_ERR | L_CONS, "rlm_sql:  Error getting data from database");
-                       (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
+
+       if (ret == SQL_DOWN) {
+               /* close the socket that failed, but only if it was open */
+               if (sqlsocket->conn) {
+                       (inst->module->sql_close)(sqlsocket, inst->config);
+               }
+
+               /* reconnect the socket */
+               if (connect_single_socket(sqlsocket, inst) < 0) {
+                       radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
                        return -1;
                }
-               rows++;
-       }
-       (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
 
-       return rows;
-}
+               /* retry the query on the newly connected socket */
+               ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
 
+               if (ret) {
+                       radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
+                              inst->config->xlat_name);
+                       return -1;
+               }
+       }
 
-static int got_alrm;
-static void
-alrm_handler(int i) {
-       got_alrm = 1;
+       return ret;
 }
 
 /*************************************************************************
  *
- *     Function: sql_check_ts
+ *     Function: rlm_sql_query
  *
- *     Purpose: Checks the terminal server for a spacific login entry
+ *     Purpose: call the module's sql_query and implement re-connect
  *
  *************************************************************************/
-static int sql_check_ts(SQL_ROW row) {
-
-       int     pid, st, e;
-       int     n;
-       NAS    *nas;
-       char    session_id[12];
-       char   *s;
-       void    (*handler) (int);
+int rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
+{
+       int ret;
 
        /*
-        *      Find NAS type.
+        *      If there's no query, return an error.
         */
-       if ((nas = nas_find(ip_addr(row[4]))) == NULL) {
-               radlog(L_ERR, "rlm_sql:  unknown NAS [%s]", row[4]);
+       if (!query || !*query) {
                return -1;
        }
 
-       /*
-        *      Fork.
-        */
-       handler = signal(SIGCHLD, SIG_DFL);
-       if ((pid = fork()) < 0) {
-               radlog(L_ERR, "rlm_sql: fork: %s", strerror(errno));
-               signal(SIGCHLD, handler);
-               return -1;
-       }
+       ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
 
-       if (pid > 0) {
-               /*
-                *      Parent - Wait for checkrad to terminate.
-                *      We timeout in 10 seconds.
-                */
-               got_alrm = 0;
-               signal(SIGALRM, alrm_handler);
-               alarm(10);
-               while ((e = waitpid(pid, &st, 0)) != pid)
-                       if (e < 0 && (errno != EINTR || got_alrm))
-                               break;
-               alarm(0);
-               signal(SIGCHLD, handler);
-               if (got_alrm) {
-                       kill(pid, SIGTERM);
-                       sleep(1);
-                       kill(pid, SIGKILL);
-                       radlog(L_ERR, "rlm_sql:  Check-TS: timeout waiting for checkrad");
-                       return 2;
+       if (ret == SQL_DOWN) {
+               /* close the socket that failed */
+               if (sqlsocket->state == sockconnected) {
+                       (inst->module->sql_close)(sqlsocket, inst->config);
                }
-               if (e < 0) {
-                       radlog(L_ERR, "rlm_sql:  Check-TS: unknown error in waitpid()");
-                       return 2;
+
+               /* reconnect the socket */
+               if (connect_single_socket(sqlsocket, inst) < 0) {
+                       radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
+                       return -1;
                }
-               return WEXITSTATUS(st);
-       }
 
-       /*
-        *      Child - exec checklogin with the right parameters.
-        */
-       for (n = 32; n >= 3; n--)
-               close(n);
-
-       sprintf(session_id, "%.8s", row[1]);
-
-       s = CHECKRAD2;
-       execl(CHECKRAD2, "checkrad", nas->nastype, row[4], row[5],
-                       row[2], session_id, NULL);
-       if (errno == ENOENT) {
-               s = CHECKRAD1;
-               execl(CHECKRAD1, "checklogin", nas->nastype, row[4], row[5],
-                               row[2], session_id, NULL);
+               /* retry the query on the newly connected socket */
+               ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
+
+               if (ret) {
+                       radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
+                              inst->config->xlat_name);
+                       return -1;
+               }
        }
-       radlog(L_ERR, "rlm_sql:  Check-TS: exec %s: %s", s, strerror(errno));
 
-       /*
-        *      Exit - 2 means "some error occured".
-        */
-       exit(2);
-       return -1;
+       return ret;
 }
 
-
 /*************************************************************************
  *
- *     Function: sql_check_multi
+ *     Function: rlm_sql_select_query
  *
- *     Purpose: Check radius accounting for duplicate logins
+ *     Purpose: call the module's sql_select_query and implement re-connect
  *
  *************************************************************************/
-int sql_check_multi(SQL_INST * inst, SQLSOCK * sqlsocket, char *name, VALUE_PAIR * request, int maxsimul) {
+int rlm_sql_select_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
+{
+       int ret;
 
-       char    querystr[MAX_QUERY_LEN];
-       char    authstr[256];
-       VALUE_PAIR *fra;
-       SQL_ROW row;
-       int     count = 0;
-       uint32_t ipno = 0;
-       int     mpp = 1;
-
-       sprintf(authstr, "UserName = '%s'", name);
-       sprintf(querystr, "SELECT COUNT(*) FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
-       if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
-               radlog(L_ERR, "sql_check_multi: database query error");
+       /*
+        *      If there's no query, return an error.
+        */
+       if (!query || !*query) {
                return -1;
        }
 
-       row = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
-       count = atoi(row[0]);
-       (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
+       ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
 
-       if (count < maxsimul)
-               return 0;
+       if (ret == SQL_DOWN) {
+               /* close the socket that failed */
+               if (sqlsocket->state == sockconnected) {
+                       (inst->module->sql_close)(sqlsocket, inst->config);
+               }
 
-       /*
-        * *      Setup some stuff, like for MPP detection.
-        */
-       if ((fra = pairfind(request, PW_FRAMED_IP_ADDRESS)) != NULL)
-               ipno = htonl(fra->lvalue);
+               /* reconnect the socket */
+               if (connect_single_socket(sqlsocket, inst) < 0) {
+                       radlog(L_ERR, "rlm_sql (%s): reconnect failed, database down?", inst->config->xlat_name);
+                       return -1;
+               }
 
-       count = 0;
-       sprintf(querystr, "SELECT * FROM %s WHERE %s AND AcctStopTime = 0", inst->config->sql_acct_table, authstr);
-       if ((inst->module->sql_select_query)(sqlsocket, inst->config, querystr) < 0) {
-               radlog(L_ERR, "sql_check_multi: database query error");
-               return -1;
+               /* retry the query on the newly connected socket */
+               ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
+
+               if (ret) {
+                       radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
+                              inst->config->xlat_name);
+                       return -1;
+               }
        }
-       while ((row = (inst->module->sql_fetch_row)(sqlsocket, inst->config))) {
-               int     check = sql_check_ts(row);
 
-               if (check == 1) {
-                       count++;
+       return ret;
+}
 
-                       if (ipno && atoi(row[19]) == ipno)
-                               mpp = 2;
 
-               } else if (check == 2)
-                       radlog(L_ERR, "rlm_sql:  Problem with checkrad [%s] (from nas %s)", name, row[4]);
-               else {
-                       /*
-                        *      False record - zap it
-                        */
+/*************************************************************************
+ *
+ *     Function: sql_getvpdata
+ *
+ *     Purpose: Get any group check or reply pairs
+ *
+ *************************************************************************/
+int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query)
+{
+       SQL_ROW row;
+       int     rows = 0;
 
-                       if (inst->config->deletestalesessions) {
-                               SQLSOCK *sqlsocket1;
+       /*
+        *      If there's no query, return an error.
+        */
+       if (!query || !*query) {
+               return -1;
+       }
 
-                               radlog(L_ERR, "rlm_sql:  Deleteing stale session [%s] (from nas %s/%s)", row[2], row[4], row[5]);
-                               sqlsocket1 = sql_get_socket(inst);
-                               sprintf(querystr, "DELETE FROM %s WHERE RadAcctId = '%s'", inst->config->sql_acct_table, row[0]);
-                               (inst->module->sql_query)(sqlsocket1, inst->config, querystr);
-                               (inst->module->sql_finish_query)(sqlsocket1, inst->config);
-                               sql_release_socket(inst, sqlsocket1);
-                       }
+       if (rlm_sql_select_query(sqlsocket, inst, query)) {
+               radlog(L_ERR, "rlm_sql_getvpdata: database query error");
+               return -1;
+       }
+       while (rlm_sql_fetch_row(sqlsocket, inst)==0) {
+               row = sqlsocket->row;
+               if (!row)
+                       break;
+               if (sql_userparse(pair, row) != 0) {
+                       radlog(L_ERR | L_CONS, "rlm_sql (%s): Error getting data from database", inst->config->xlat_name);
+                       (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
+                       return -1;
                }
+               rows++;
        }
        (inst->module->sql_finish_select_query)(sqlsocket, inst->config);
 
-       return (count < maxsimul) ? 0 : mpp;
+       return rows;
 }
 
-void query_log(SQL_INST * inst, char *querystr) {
+void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
+{
        FILE   *sqlfile = NULL;
 
        if (inst->config->sqltrace) {
-               if ((sqlfile = fopen(inst->config->tracefile, "a")) == (FILE *) NULL) {
-                       radlog(L_ERR, "rlm_sql: Couldn't open file %s",
-                                       inst->config->tracefile);
+               char buffer[8192];
+
+               if (!radius_xlat(buffer, sizeof(buffer),
+                                inst->config->tracefile, request, NULL)) {
+                 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
+                        inst->config->xlat_name);
+                 return;
+               }
+
+               if ((sqlfile = fopen(buffer, "a")) == (FILE *) NULL) {
+                       radlog(L_ERR, "rlm_sql (%s): Couldn't open file %s",
+                              inst->config->xlat_name,
+                              buffer);
                } else {
                        int fd = fileno(sqlfile);
-                       
+
                        rad_lockfd(fd, MAX_QUERY_LEN);
                        fputs(querystr, sqlfile);
                        fputs(";\n", sqlfile);