Update the GPL boilerplate with the new address of the FSF.
[freeradius.git] / src / modules / rlm_sql / sql.c
index e35301e..295a107 100644 (file)
@@ -1,8 +1,36 @@
+/*
+ *  sql.c              rlm_sql - FreeRADIUS SQL Module
+ *             Main code directly taken from ICRADIUS
+ *
+ * Version:    $Id$
+ *
+ *   This program is free software; you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ *
+ * Copyright 2001  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/autoconf.h>
 
 #include       <sys/types.h>
 #include       <sys/socket.h>
 #include       <sys/time.h>
 #include       <sys/file.h>
+#include       <string.h>
 #include       <sys/stat.h>
 #include       <netinet/in.h>
 
 #include       <errno.h>
 #include       <sys/wait.h>
 
+#include       <freeradius-devel/radiusd.h>
+#include       <freeradius-devel/conffile.h>
 #include       "rlm_sql.h"
-#include       "radiusd.h"
 
+#ifdef HAVE_PTHREAD_H
+#include       <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
+ */
+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);
+}
 
 
 /*************************************************************************
  *
- *     Function: sql_save_acct
+ *     Function: sql_init_socketpool
  *
- *     Purpose: Write data from the sqlrecord structure to the database
+ *     Purpose: Connect to the sql server, if possible
  *
  *************************************************************************/
+int sql_init_socketpool(SQL_INST * inst)
+{
+       int i, rcode;
+       int success = 0;
+       SQLSOCK *sqlsocket;
 
-int sql_save_acct(SQLREC *sqlrecord) {
+       inst->connect_after = 0;
+       inst->sqlpool = NULL;
 
-       char            querystr[2048];
-       FILE            *sqlfile;
-       FILE            *backupfile;
-       int             num = 0;
-       SQL_RES         *result;
-#ifdef NT_DOMAIN_HACK
-       char            *ptr;
-       char            newname[AUTH_STRING_LEN];
+       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(*sqlsocket));
+               if (sqlsocket == NULL) {
+                       return -1;
+               }
+               memset(sqlsocket, 0, sizeof(*sqlsocket));
+               sqlsocket->conn = NULL;
+               sqlsocket->id = i;
+               sqlsocket->state = sockunconnected;
+
+#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 also inst->connect_after
+                        */
+                       if (connect_single_socket(sqlsocket, inst) == 0) {
+                               success = 1;
+                       }
+               }
 
-     if((sqlfile = fopen(QUERYLOG, "a")) == (FILE *)NULL) {
-            log(L_ERR, "Acct: Couldn't open file %s", QUERYLOG);
-     } else { 
-        #if defined(F_LOCK) && !defined(BSD)
-              (void)lockf((int)sqlfile, (int)F_LOCK, (off_t)SQL_LOCK_LEN);
-        #else
-              (void)flock(sqlfile, SQL_LOCK_EX);
-        #endif
-     }
+               /* Add this socket to the list of sockets */
+               sqlsocket->next = inst->sqlpool;
+               inst->sqlpool = sqlsocket;
+       }
+       inst->last_used = NULL;
 
-#ifdef NT_DOMAIN_HACK
-       /*
-        *      Windows NT machines often authenticate themselves as
-        *      NT_DOMAIN\username. Try to be smart about this.
-        *
-        *      FIXME: should we handle this as a REALM ?
-        */
-       if ((ptr = strchr(sqlrecord->UserName, '\\')) != NULL) {
-               strncpy(newname, ptr + 1, sizeof(newname));
-               newname[sizeof(newname) - 1] = 0;
-               strcpy(sqlrecord->UserName, newname);
+       if (!success) {
+               radlog(L_DBG, "rlm_sql (%s): Failed to connect to any SQL server.",
+                      inst->config->xlat_name);
        }
-#endif /* NT_DOMAIN_HACK */
 
- if (sql_checksocket("Acct")) {
+       return 1;
+}
 
-     if (sqlrecord->AcctStatusTypeId == PW_STATUS_ACCOUNTING_ON || sqlrecord->AcctStatusTypeId == PW_STATUS_ACCOUNTING_OFF) {
-        log(L_INFO, "Portmaster %s rebooted at %s", sqlrecord->NASIPAddress, sqlrecord->AcctTimeStamp);
-  
-         /* The Terminal server informed us that it was rebooted
-         * STOP all records from this NAS */
+/*************************************************************************
+ *
+ *     Function: sql_poolfree
+ *
+ *     Purpose: Clean up and free sql pool
+ *
+ *************************************************************************/
+void sql_poolfree(SQL_INST * inst)
+{
+       SQLSOCK *cur;
+       SQLSOCK *next;
 
-         sprintf(querystr, "UPDATE %s SET AcctStopTime='%s', AcctSessionTime=unix_timestamp('%s') - unix_timestamp(AcctStartTime), AcctTerminateCause='%s' WHERE AcctSessionTime=0 AND AcctStopTime=0 AND NASIPAddress= '%s' AND AcctStartTime <= '%s'", sql->config.sql_acct_table, sqlrecord->AcctTimeStamp, sqlrecord->AcctTimeStamp, sqlrecord->AcctTerminateCause, sqlrecord->NASIPAddress, sqlrecord->AcctTimeStamp);
+       for (cur = inst->sqlpool; cur; cur = next) {
+               next = cur->next;
+               sql_close_socket(inst, cur);
+       }
 
-                if (sql_query(sql->AcctSock, (const char *) querystr) < 0)
-             log(L_ERR, "Acct: Couldn't update SQL accounting after NAS reboot - %s", sql_error(sql->AcctSock));
+       inst->sqlpool = NULL;
+}
 
-         if (sqlfile) {
-              fputs(querystr, sqlfile);
-              fputs(";\n", sqlfile);
-              fclose(sqlfile);
-          }
-          return 0;
-      } 
 
-       if (sqlrecord->AcctStatusTypeId == PW_STATUS_ALIVE) {
-               sprintf(querystr, "UPDATE %s SET Framed-IP-Address = '%s' WHERE AcctSessionId = '%s' AND UserName = '%s' AND NASIPAddress= '%s'", sql->config.sql_acct_table, sqlrecord->FramedIPAddress, sqlrecord->AcctSessionId, sqlrecord->UserName, sqlrecord->NASIPAddress);
-               if (sql_query(sql->AcctSock, (const char *) querystr) < 0)
-               log(L_ERR, "Acct: Couldn't update SQL accounting after NAS reboot - %s", sql_error(sql->AcctSock));
+/*************************************************************************
+ *
+ *     Function: sql_close_socket
+ *
+ *     Purpose: Close and free a sql sqlsocket
+ *
+ *************************************************************************/
+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;
+}
 
-               if (sqlfile) {
-                       fputs(querystr, sqlfile);
-                       fputs(";\n", sqlfile);
-                       fclose(sqlfile);
+
+/*************************************************************************
+ *
+ *     Function: sql_get_socket
+ *
+ *     Purpose: Return a SQL sqlsocket from the connection pool
+ *
+ *************************************************************************/
+SQLSOCK * sql_get_socket(SQL_INST * inst)
+{
+       SQLSOCK *cur, *start;
+       int tried_to_connect = 0;
+       int unconnected = 0;
+
+       /*
+        *      Start at the last place we left off.
+        */
+       start = inst->last_used;
+       if (!start) start = inst->sqlpool;
+
+       cur = start;
+
+       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.
+                */
+               if ((cur->state == sockunconnected) && (time(NULL) > inst->connect_after)) {
+                       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 (%s): Ignoring unconnected handle %d..", inst->config->xlat_name, cur->id);
+                       unconnected++;
+#ifdef HAVE_PTHREAD_H
+                       pthread_mutex_unlock(&cur->mutex);
+#endif
+                       goto next;
                }
-               return 0;
-       }
 
+               /* should be connected, grab it */
+               radlog(L_DBG, "rlm_sql (%s): Reserving sql socket id: %d", inst->config->xlat_name, cur->id);
 
-          /* Got start record */
-          if(sqlrecord->AcctStatusTypeId == PW_STATUS_START) {
-             
-             /* Set start time on record with only a stop record */
-            snprintf(querystr, 2048, "UPDATE %s SET AcctStartTime = '%s' WHERE AcctSessionId = '%s' AND UserName = '%s' AND NASIPAddress = '%s'", 
-            sql->config.sql_acct_table,
-             sqlrecord->AcctTimeStamp,
-             sqlrecord->AcctSessionId,
-             sqlrecord->UserName,
-             sqlrecord->NASIPAddress
-             );
-                    if (sql_query(sql->AcctSock, (const char *) querystr) < 0)
-               log(L_ERR, "Acct: Couldn't update SQL accounting START record - %s", sql_error(sql->AcctSock));
-
-             num = sql_affected_rows(sql->AcctSock);
-             if (num == 0) {
-
-                /* Insert new record with blank stop time until stop record is got */
-                snprintf(querystr, 2048, "INSERT INTO %s VALUES (0, '%s', '%s', '%s', '%s', %ld, '%s', '%s', 0, 0, '%s', '%s', 0, 0, '%s', '%s', '', '%s', '%s', '%s', %ld)",
-                sql->config.sql_acct_table,
-                sqlrecord->AcctSessionId,
-                sqlrecord->UserName,
-                sqlrecord->Realm,
-                sqlrecord->NASIPAddress,
-                sqlrecord->NASPortId,
-                sqlrecord->NASPortType,
-                sqlrecord->AcctTimeStamp,
-                sqlrecord->AcctAuthentic,
-                sqlrecord->ConnectInfo,
-                sqlrecord->CalledStationId,
-                sqlrecord->CallingStationId,
-                sqlrecord->ServiceType,
-                sqlrecord->FramedProtocol,
-                sqlrecord->FramedIPAddress,
-                sqlrecord->AcctDelayTime
-                );                  
-
-                       if (sql_query(sql->AcctSock, (const char *) querystr) < 0)
-                 log(L_ERR, "Acct: Couldn't insert SQL accounting START record - %s", sql_error(sql->AcctSock));
-             }
-
-           /* Got stop record */
-           } else {
-
-             sprintf(querystr, "SELECT RadAcctId FROM %s WHERE AcctSessionId='%s' AND NASIPAddress='%s' AND UserName='%s'", sql->config.sql_acct_table, sqlrecord->AcctSessionId, sqlrecord->NASIPAddress, sqlrecord->UserName);
-              sql_query(sql->AcctSock, querystr);
-              if (!(result = sql_store_result(sql->AcctSock)) && sql_num_fields(sql->AcctSock)) {
-                   log(L_ERR,"SQL Error: Cannot get result");
-                   log(L_ERR,"SQL error: %s",sql_error(sql->AcctSock));
-                    sql_close(sql->AcctSock);
-                    sql->AcctSock = NULL;
-              } else {
-                    num = sql_num_rows(result);
-                   sql_free_result(result);
-              }
-
-             if (num > 0) {
-
-                /* Set stop time on matching record with start time */
-               snprintf(querystr, 2048, "UPDATE %s SET AcctStopTime = '%s', AcctSessionTime = '%lu', AcctInputOctets = '%u', AcctOutputOctets = '%u', AcctTerminateCause = '%s' WHERE AcctSessionId = '%s' AND UserName = '%s' AND NASIPAddress = '%s'", 
-               sql->config.sql_acct_table,
-                sqlrecord->AcctTimeStamp,
-                sqlrecord->AcctSessionTime,
-                sqlrecord->AcctInputOctets,
-                sqlrecord->AcctOutputOctets,
-                sqlrecord->AcctTerminateCause,
-                sqlrecord->AcctSessionId,
-                sqlrecord->UserName,
-                sqlrecord->NASIPAddress
-                );
-
-
-                       if (sql_query(sql->config.AcctSock, (const char *) querystr) < 0)
-                  log(L_ERR, "Acct: Couldn't update SQL accounting STOP record - %s", sql_error(sql->AcctSock));
-
-             } else if (num == 0) {
-
-            
-                /* Insert record with no start time until matching start record comes */
-                snprintf(querystr, 2048, "INSERT INTO %s VALUES (0, '%s', '%s', '%s', '%s', %ld, '%s', 0, '%s', '%lu', '%s', '%s', '%u', '%u', '%s', '%s', '%s', '%s', '%s', '%s', %ld)",
-                sql->config.sql_acct_table,
-                sqlrecord->AcctSessionId,
-                sqlrecord->UserName,
-                sqlrecord->Realm,
-                sqlrecord->NASIPAddress,
-                sqlrecord->NASPortId,
-                sqlrecord->NASPortType,
-               sqlrecord->AcctTimeStamp,
-               sqlrecord->AcctSessionTime,
-                sqlrecord->AcctAuthentic,
-                sqlrecord->ConnectInfo,
-               sqlrecord->AcctInputOctets,
-               sqlrecord->AcctOutputOctets,
-                sqlrecord->CalledStationId,
-                sqlrecord->CallingStationId,
-               sqlrecord->AcctTerminateCause,
-                sqlrecord->ServiceType,
-                sqlrecord->FramedProtocol,
-                sqlrecord->FramedIPAddress,
-                sqlrecord->AcctDelayTime
-                );                  
-
-                       if (sql->config.sql_query(sql->AcctSock, (const char *) querystr) < 0)
-                  log(L_ERR, "Acct: Couldn't insert SQL accounting STOP record - %s", sql_error(sql->AcctSock));
-             }
-
-          }
-          if (sqlfile) {
-                fputs(querystr, sqlfile);
-                fputs(";\n", sqlfile);
-                fflush(sqlfile);
-                fclose(sqlfile);
-          }
-
-
-       } else {
-
-           /*
-            *  The database is down for some reason
-             *  So open up the backup file to save records in
-            */
-
-             if((backupfile = fopen(SQLBACKUP, "a")) == (FILE *)NULL) {
-                 log(L_ERR, "Acct: Couldn't open file %s", SQLBACKUP);
-             } else {
-                  /*
-                   * Lock the sql backup file, prefer lockf() over flock().
-                   */
-                   #if defined(F_LOCK) && !defined(BSD)
-                       (void)lockf((int)backupfile, (int)F_LOCK, (off_t)SQL_LOCK_LEN);
-                   #else
-                       (void)flock(backupfile, SQL_LOCK_EX);
-                   #endif
-                   if(fwrite(sqlrecord, sizeof(SQLREC), 1, backupfile) < 1) {
-                       log(L_ERR, "Acct: Couldn't write to file %s", SQLBACKUP);
-                   }
-                   fclose(backupfile);
-              }
+               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;
+               }
        }
-        
-     return 0;
 
+       /* We get here if every DB handle is unconnected and unconnectABLE */
+       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;
+}
+
+/*************************************************************************
+ *
+ *     Function: sql_release_socket
+ *
+ *     Purpose: Frees a SQL sqlsocket back to the connection pool
+ *
+ *************************************************************************/
+int sql_release_socket(SQL_INST * inst, SQLSOCK * sqlsocket)
+{
+#ifdef HAVE_PTHREAD_H
+       pthread_mutex_unlock(&sqlsocket->mutex);
+#endif
+
+       radlog(L_DBG, "rlm_sql (%s): Released sql socket id: %d",
+              inst->config->xlat_name, sqlsocket->id);
+
+       return 0;
 }
 
 
@@ -258,340 +326,292 @@ int sql_save_acct(SQLREC *sqlrecord) {
  *     Purpose: Read entries from the database and fill VALUE_PAIR structures
  *
  *************************************************************************/
-int sql_userparse(VALUE_PAIR **first_pair, SQL_ROW row) {
-
-       int x;
-       char            *s;
-       DICT_ATTR       *attr = NULL;
-       DICT_VALUE      *dval;
-       VALUE_PAIR      *pair, *pair2, *check;
-       struct tm       *tm;
-       time_t          timeval;
-
-
-       if((attr = dict_attrfind(row[2])) == (DICT_ATTR *)NULL) {
-#if 1 /* Be quiet. */
-               log(L_ERR|L_CONS, "unknown attribute %s", row[2]);
-#endif 
-               return(-1);
-       }                              
-
-       /* If attribute is already there, skip it because we checked usercheck first 
-          and we want user settings to over ride group settings */
-       if ((check = pairfind(*first_pair, attr->value)) != NULL)
-               return 0;
-
-       if((pair = (VALUE_PAIR *)malloc(sizeof(VALUE_PAIR))) == (VALUE_PAIR *)NULL) {
-               log(L_CONS|L_ERR, "sql_userparse: no memory");
-               exit(1);
+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;
+
+       /*
+        *      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;
+       }
+
+       /*
+        *      Verify the 'op' field
+        */
+       if (row[4] != NULL && row[4][0] != '\0') {
+               ptr = row[4];
+               operator = gettoken(&ptr, buf, sizeof(buf));
        }
-       strcpy(pair->name, attr->name);
-       pair->attribute = attr->value;
-       pair->type = attr->type;
-       pair->operator = PW_OPERATOR_EQUAL;
-       switch(pair->type) {
-
-               case PW_TYPE_STRING:
-                       strcpy(pair->strvalue, row[3]);
-                       pair->length = strlen(pair->strvalue);
+       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.");
+       }
+
+       /*
+        *      The 'Value' field may be empty or NULL
+        */
+       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])) {
+
+               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;
 
-               case PW_TYPE_INTEGER:
-                       /*
-                        *      For PW_NAS_PORT_ID, allow a
-                        *      port range instead of just a port.
-                        */
-                        if (attr->value == PW_NAS_PORT_ID) {
-                              for(s = row[3]; *s; s++)
-                                   if (!isdigit(*s)) break;
-                                   if (*s) {
-                                       pair->type = PW_TYPE_STRING;
-                                       strcpy(pair->strvalue, row[3]);
-                                       pair->length = strlen(pair->strvalue);
-                                       break;
-                                   }
-                        }
-                        if (isdigit(*row[3])) {
-                                   pair->lvalue = atoi(row[3]);
-                                   pair->length = 4;
-                        }
-                        else if((dval = dict_valfind(row[3])) == (DICT_VALUE *)NULL) {
-                                   free(pair);
-                                   log(L_ERR|L_CONS, "unknown value %s", row[3]);
-                                   return(-1);
-                        }
-                        else {
-                                   pair->lvalue = dval->value;
-                                   pair->length = 4;
-                        }
-                        break;
-
-               case PW_TYPE_IPADDR:
-                       if (pair->attribute != PW_FRAMED_IP_ADDRESS) {
-                                   pair->lvalue = get_ipaddr(row[3]);
-                                   break;
-                        }
-
-                       /*
-                        *      We allow a "+" at the end to
-                        *      indicate that we should add the
-                        *      portno. to the IP address.
-                        */
-                        x = 0;
-                        if (row[3][0]) {
-                               for(s = row[3]; s[1]; s++) ;
-                                    if (*s == '+') {
-                                        *s = 0;
-                                        x = 1;
-                                    }
-                        }
-                        pair->lvalue = get_ipaddr(row[3]);
-                        pair->length = 4;
-
-                       /*
-                        *      Add an extra (hidden) attribute.
-                        */
-                        if((pair2 = malloc(sizeof(VALUE_PAIR))) == NULL) {
-                               log(L_CONS|L_ERR, "no memory");
-                               exit(1);
-                        }
-                        strcpy(pair2->name, "Add-Port-To-IP-Address");
-                        pair2->attribute = PW_ADD_PORT_TO_IP_ADDRESS;
-                        pair2->type = PW_TYPE_INTEGER;
-                        pair2->lvalue = x;
-                        pair2->length = 4;
-                        pairadd(first_pair, pair2);
-                        break;
-
-               case PW_TYPE_DATE:
-                        timeval = time(0);
-                        tm = localtime(&timeval);
-                        user_gettime(row[3], tm);
-#ifdef TIMELOCAL
-                        pair->lvalue = (UINT4)timelocal(tm);
-#else
-                        pair->lvalue = (UINT4)mktime(tm);
-#endif
-                        pair->length = 4;
-                        break;
+                       /*
+                        *      Mark the pair to be allocated later.
+                        */
+               case T_BACK_QUOTED_STRING:
+                       value = NULL;
+                       do_xlat = 1;
+                       break;
 
+                       /*
+                        *      Keep the original string.
+                        */
                default:
-                        free(pair);
-#if 1 /* Yeah yeah */
-                        log(L_ERR|L_CONS, "unknown attr. type %d", pair->type);
-#endif
-                        return(-1);
+                       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;
+               strNcpy(pair->vp_strvalue, buf, sizeof(pair->vp_strvalue));
+               pair->length = 0;
        }
-       pairadd(first_pair, pair);
 
+       /*
+        *      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(char *table, VALUE_PAIR **vp, char *user, int mode) {
-
-       char            querystr[256];
-       SQL_RES         *result;
-       SQL_ROW         row;
-       int             rows;
-
-       if (mode == PW_VP_USERDATA)
-               sprintf(querystr, "SELECT * FROM %s WHERE UserName = '%s'", table, user);
-       else if (mode == PW_VP_GROUPDATA)
-               sprintf(querystr, "SELECT %s.* FROM %s, %s WHERE %s.UserName = '%s' AND %s.GroupName = %s.GroupName ORDER BY %s.id", table, table, sql->config.sql_usergroup_table, sql->config.sql_usergroup_table, user, sql->config.sql_usergroup_table, table, table);
-       else if (mode == PW_VP_REALMDATA)
-               sprintf(querystr, "SELECT %s.* FROM %s, %s WHERE %s.RealmName = '%s' AND %s.GroupName = %s.GroupName ORDER BY %s.id", table, table, sql->config.sql_realmgroup_table, sql->config.sql_realmgroup_table, user, sql->config.sql_realmgroup_table, table, table);
-        sql_checksocket("Auth");
-       sql_query(sql->AuthSock, querystr);
-       if ((result = sql_store_result(sql->AuthSock)) && sql_num_fields(sql->AuthSock)) {
-               rows = sql_num_rows(result);
-               while ((row = sql_fetch_row(result))) {
-
-                       if (sql_userparse(vp, row) != 0) {
-                               log(L_ERR|L_CONS, "Error getting data from SQL database");
-                               sql_free_result(result);
-                               return -1;
-                       }
-               }
-               sql_free_result(result);
+int rlm_sql_fetch_row(SQLSOCK *sqlsocket, SQL_INST *inst)
+{
+       int ret;
+
+       if (sqlsocket->conn) {
+               ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
+       } else {
+               ret = SQL_DOWN;
        }
 
-       return rows;
+       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;
+               }
 
+               /* retry the query on the newly connected socket */
+               ret = (inst->module->sql_fetch_row)(sqlsocket, inst->config);
 
-static int got_alrm;
-static void alrm_handler()
-{
-       got_alrm = 1;
+               if (ret) {
+                       radlog(L_ERR, "rlm_sql (%s): failed after re-connect",
+                              inst->config->xlat_name);
+                       return -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 rlm_sql_query(SQLSOCK *sqlsocket, SQL_INST *inst, char *query)
+{
+       int ret;
+
+       /*
+        *      If there's no query, return an error.
+        */
+       if (!query || !*query) {
+               return -1;
+       }
+
+       ret = (inst->module->sql_query)(sqlsocket, inst->config, query);
+
+       if (ret == SQL_DOWN) {
+               /* close the socket that failed */
+               (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;
+               }
 
-       int     pid, st, e;
-       int     n;
-       NAS     *nas;
-       char    session_id[12];
-       char    *s;
-       void    (*handler)(int);
+               /* 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;
+               }
+       }
+
+       return ret;
+}
+
+/*************************************************************************
+ *
+ *     Function: rlm_sql_select_query
+ *
+ *     Purpose: call the module's sql_select_query and implement re-connect
+ *
+ *************************************************************************/
+int rlm_sql_select_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(ipstr2long(row[3]))) == NULL) {
-                log(L_ERR, "Accounting: unknown NAS [%s]", row[3]);
-                return -1;
-        }
-
-        /*
-         *      Fork.
-         */
-        handler = signal(SIGCHLD, SIG_DFL);
-        if ((pid = fork()) < 0) {
-                log(L_ERR, "Accounting: fork: %s", strerror(errno));
-                signal(SIGCHLD, handler);
-                return -1;
-        }
-
-        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);
-                        log(L_ERR, "Check-TS: timeout waiting for checkrad");
-                        return 2;
-                }
-                if (e < 0) {
-                        log(L_ERR, "Check-TS: unknown error in waitpid()");
-                        return 2;
-                }
-                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);
-        }
-        log(L_ERR, "Check-TS: exec %s: %s", s, strerror(errno));
-
-        /*
-         *      Exit - 2 means "some error occured".
-         */
-        exit(2); 
+       if (!query || !*query) {
+               return -1;
+       }
+
+       ret = (inst->module->sql_select_query)(sqlsocket, inst->config, query);
+
+       if (ret == SQL_DOWN) {
+               /* close the socket that failed */
+               (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;
+               }
 
+               /* 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;
+               }
+       }
+
+       return ret;
 }
 
 
 /*************************************************************************
  *
- *     Function: sql_check_multi
+ *     Function: sql_getvpdata
  *
- *     Purpose: Check radius accounting for duplicate logins
+ *     Purpose: Get any group check or reply pairs
  *
  *************************************************************************/
-int sql_check_multi(char *name, VALUE_PAIR *request, int maxsimul) {
-
-       char            querystr[256];
-       VALUE_PAIR      *fra;
-       SQL_RES         *result;
-       SQL_ROW         row;
-       int             count = 0;
-       UINT4           ipno = 0;
-       int             mpp = 1;
-
-       if (!sql_checksocket("Auth"))
-               return 0;
-       sprintf(querystr, "SELECT COUNT(*) FROM %s WHERE UserName = '%s' AND AcctStopTime = 0", sql->config.sql_acct_table, name);
-       sql_query(sql->AuthSock, querystr);
-       if (!(result = sql_store_result(sql->AuthSock)) && sql_num_fields(sql->AuthSock)) {
-               log(L_ERR,"SQL Error: Cannot get result");
-               log(L_ERR,"SQL error: %s",sql_error(sql->AuthSock));
-               sql_close(sql->AuthSock);
-               sql->AuthSock = NULL;
-       } else {
-               row = sql_fetch_row(result);
-               count = atoi(row[0]);
-               sql_free_result(result);
+int sql_getvpdata(SQL_INST * inst, SQLSOCK * sqlsocket, VALUE_PAIR **pair, char *query)
+{
+       SQL_ROW row;
+       int     rows = 0;
+
+       /*
+        *      If there's no query, return an error.
+        */
+       if (!query || !*query) {
+               return -1;
        }
 
-       if (count < maxsimul)
-               return 0;
+       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);
 
-       /*
-       *      Setup some stuff, like for MPP detection.
-       */
-       if ((fra = pairfind(request, PW_FRAMED_IP_ADDRESS)) != NULL)
-               ipno = htonl(fra->lvalue);
-
-       count = 0;
-       sprintf(querystr, "SELECT * FROM %s WHERE UserName = '%s' AND AcctStopTime = 0", sql->config.sql_acct_table, name);
-       sql_query(sql->AuthSock, querystr);
-       if (!(result = sql_store_result(sql->AuthSock)) && sql_num_fields(sql->AuthSock)) {
-               log(L_ERR,"SQL Error: Cannot get result");
-               log(L_ERR,"SQL error: %s",sql_error(sql->AuthSock));
-               sql_close(sql->AuthSock);
-               sql->AuthSock = NULL;
-       } else {
-               while ((row = sql_fetch_row(result))) {
-                       if (sql_check_ts(row) == 1) {
-                               count++;
+       return rows;
+}
 
-                               if (ipno && atoi(row[18]) == ipno)
-                                       mpp = 2;   
+void query_log(REQUEST *request, SQL_INST *inst, char *querystr)
+{
+       FILE   *sqlfile = NULL;
 
-                       } else {
-                               /*
-                                *      False record - zap it
-                                */
+       if (inst->config->sqltrace) {
+               char buffer[8192];
 
-                               sprintf(querystr, "DELETE FROM %s WHERE RadAcctId = '%s'", sql->config.sql_acct_table, row[0]);
-                               sql_query(sql->AuthSock, querystr);
-                               
-                       }
+               if (!radius_xlat(buffer, sizeof(buffer),
+                                inst->config->tracefile, request, NULL)) {
+                 radlog(L_ERR, "rlm_sql (%s): xlat failed.",
+                        inst->config->xlat_name);
+                 return;
                }
-               sql_free_result(result);
-       }
 
-       return (count < maxsimul) ? 0 : mpp; 
+               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);
+                       fclose(sqlfile); /* and release the lock */
+               }
+       }
 }