--- channels/chan_sip2.c.v6A	2004-08-30 15:11:28.000000000 +0200
+++ channels/chan_sip2.c	2004-08-30 23:09:16.924642120 +0200
@@ -1,5 +1,5 @@
 /*
-* Asterisk -- A telephony toolkit for Linux.
+ * Asterisk -- A telephony toolkit for Linux.
  *
  * Implementation of Session Initiation Protocol
  * 
@@ -70,15 +70,40 @@
  *    You can use ACL for autocreatepeer to limit who can create peers
  *  + Templates implemented for users
  *  + Temporary support for MYSQL authentication - will be moved to ODBC
- *	dbname=		Database name
- *	dbpass=		Password
- *	dbhost=		Hostname
- *	dbuser=		Username for DB connection
- *
- *	dbtable=	Table to check		 To be implemented *****
- *	dbfield_user=	Field for peer name
- *	dbfield_pwd=	Field for password
+ *  You need a type like this
  *
+ * CREATE TABLE `sipfriends` (
+ *   `auth` varchar(100) default '',
+ *   `name` varchar(40) NOT NULL default '',
+ *   `username` varchar(40) default '',
+ *   `secret` varchar(40) NOT NULL default '',
+ *   `accountcode` varchar(20) NOT NULL default '',
+ *   `context` varchar(40) NOT NULL default '',
+ *   `sipipaddr` varchar(20) NOT NULL default '',
+ *   `sipport` int(6) NOT NULL default '0',
+ *   `iaxregseconds` int(11) NOT NULL default '0',
+ *   `iaxipaddr` varchar(50) default NULL,
+ *   `iaxport` varchar(10) default NULL,
+ *   `sipregseconds` varchar(10) default NULL,
+ *   PRIMARY KEY  (`name`)
+ * ) TYPE=MyISAM;
+ *
+ * INSERT INTO `sipfriends` VALUES ('4199:blah4199@lesmuids.com', '4199', 'TEST', 'blah4199', '', 'lesmuids', '', 0, 0, NULL, NULL, NULL);
+ * 
+ * A sample [general] section
+ * dbname=asterisk
+ * dbpass=asterisk
+ * dbhost=localhost
+ * dbuser=asterisk
+ * dbfield_auth=auth
+ * dbtable=sipfriends
+ * dbfield_user=username
+ * dbfield_pwd=secret
+ * dbfield_name=name
+ * dbfield_context=context
+ * dbfield_port=sipport
+ * dbfield_ipaddr=sipipaddr
+ * dbfield_regseconds=sipregseconds
  *    Right now defaults to 'subscriber' table, fields 'username' and 'password'
  *
  *    You still need either a peer definition or an autocreatepeer
@@ -457,9 +482,9 @@
 #define FLAG_RESPONSE (1 << 0)
 #define FLAG_FATAL (1 << 1)
 
-static char *desc = "Session Initiation Protocol (SIP), channel v2 beta";
+static char *desc = "Session Initiation Protocol (SIP), channel v2 beta for mysql";
 static char *global_channeltype = "SIP";
-static char *tdesc = "Session Initiation Protocol (SIP), channel v2 beta";
+static char *tdesc = "Session Initiation Protocol (SIP), channel v2 beta for mysql";
 static char *config = "sip.conf";
 static char global_useragent[AST_MAX_EXTENSION] ="Asterisk SIPv2 (http://www.asterisk.org " ASTERISK_VERSION " ) ";  
 static char *contact_text = "Your friendly Asterisk PBX ";
@@ -474,9 +499,15 @@
 #endif
 
 #ifdef MYSQL_AUTH
-static char mydbtable[80] = "subscribers";	/* Table to check in */
-static char mydbfield_peername[80] = "username";/* Username field in db */
-static char mydbfield_secret[80] = "password";	/* Password/secret field in table, cleartext */
+static char mydbtable[80] = "subscribers";			/* Table to check in */
+static char mydbfield_name[80] = "name";			/* name field in db */
+static char mydbfield_peername[80] = "username";	/* Username field in db */
+static char mydbfield_secret[80] = "secret";		/* Password/secret field in table, cleartext */
+static char mydbfield_auth[80] = "auth";			/* auth field in table */
+static char mydbfield_port[80] = "port";			/* port field in table */
+static char mydbfield_ipaddr[80] = "ipaddr";		/* ipaddr field in table */
+static char mydbfield_context[80] = "context";		/* context field in table */
+static char mydbfield_regseconds[80] = "regseconds";/* regseconds field in table */
 #endif
 
 
@@ -913,7 +944,7 @@
 #endif
 #ifdef MYSQL_FRIENDS
 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin);
-static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username);
+static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry);
 #endif
 
 /*--- The user list: Users and friends ---*/
@@ -4808,7 +4839,7 @@
 	pvt->expiry = expiry;
 #ifdef MYSQL_FRIENDS
         if (p->temponly)
-             mysql_update_peer(p->name, &p->addr, p->peerusername);
+             mysql_update_peer(p->name, &p->addr, p->peerusername, expiry );
 #endif
         snprintf(data, sizeof(data), "%s:%d:%d:%s", ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry, p->peerusername);
         ast_db_put("SIP/Registry", p->name, data);
@@ -5254,7 +5285,7 @@
                  strncpy(tmpsecret,get_secret(peer),sizeof(tmpsecret));
 
                  /* DEBUG DEBUG DEBUG Ouch, we're printing the SECRET. But debugging is debugging */
-                  ast_log(LOG_NOTICE, "SIP peer %s/%s got secret %s from SQL database \n", peer->name,peer->username,tmpsecret);
+                  ast_log(LOG_NOTICE, "SIP peer %s/%s got secret %s from SQL database \n", peer->name,peer->peerusername,tmpsecret);
              }
 #endif
 
@@ -5829,7 +5860,6 @@
 	/* If we have authentication header, use username from that header *REGARDLESS* of username in AOR (From: ) */
 	/* This enables you to authenticate regardless of From: address */
 	authuser = getdigestusername(req);
-
 	of = get_header(req, "From");
 	strncpy(from, of, sizeof(from) - 1);
 	memset(calleridname,0,sizeof(calleridname));
@@ -5884,6 +5914,7 @@
 	if (option_debug)
 	   ast_log(LOG_NOTICE,"Looking for user \"%s\" for this request (IP address %s )\n",of, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr) );
 
+	ast_log(LOG_NOTICE, "We try find_user('%s')\n",authuser);
 	user = find_user(authuser);
 	if (authuser != of && !ast_strlen_zero(authuser) )
 		free(authuser);
@@ -5977,7 +6008,6 @@
 			/* 	with a lot of users behind another proxy */
 			
 			/* Take the peer */
-			ast_log(LOG_NOTICE,"Using peer name %s for this request\n",peer->name);
 			p->nat = peer->nat;
 			p->symmetricrtp = peer->symmetricrtp;
 
@@ -9315,6 +9345,7 @@
 
 /*-------------------------------------------------------------------------*/
 static char get_secret_buf[80]; 
+static char get_secret_auth_buf[100]; 
 
 /*--- get_secret: Get secret from mysql database ---*/
 static char *get_secret(struct sip_peer *peer)
@@ -9349,8 +9380,9 @@
       mysql_real_escape_string(sqlhandle, name, peer->name, strlen(peer->name));
 
       /* Look for password */
-      snprintf(query, sizeof(query), "SELECT %s FROM %s WHERE %s=\"%s\"", dbfield_secret, mydbtable, dbfield_username,name);
 
+	  snprintf(query, sizeof(query), "SELECT %s,%s FROM %s WHERE %s=\"%s\"", mydbfield_secret, mydbfield_auth, mydbtable, mydbfield_name,name);
+		ast_log(LOG_NOTICE, "DEBUG: Execute SQL Query: %s\n",query);
       ast_mutex_lock(&mysqllock);	/* Lock thread */
       mysql_query(sqlhandle, query);
       if ((result = mysql_store_result(sqlhandle))) {
@@ -9359,11 +9391,15 @@
                fields = mysql_fetch_fields(result);
                for (x=0;x<numfields;x++) {
                     if (rowval[x]) {
-                       if (!strcasecmp(fields[x].name, field_secret)) {
-
+                       if (!strcasecmp(fields[x].name, mydbfield_secret)) {
                             strncpy(get_secret_buf, rowval[x], sizeof(peer->secret));
-       				ast_log(LOG_NOTICE, "DEBUG: get_secret Password: %s ...\n",get_secret_buf);
+       						ast_log(LOG_NOTICE, "DEBUG: get_secret Password: %s ...\n",get_secret_buf);
                         }
+					   if (!strcasecmp(fields[x].name, mydbfield_auth)) {
+						    strncpy(get_secret_auth_buf, rowval[x], sizeof(get_secret_auth_buf));
+							peer->auth = add_realm_authentication(peer->auth, rowval[x], 0);
+							ast_log(LOG_NOTICE, "DEBUG: get_secret Auth: %s ...\n",get_secret_auth_buf);
+					   }
 		    }
                 }	/* For loop */
          } /* if mysql_fetch_row */
@@ -9383,7 +9419,7 @@
 
  
 /*--- mysql_update_peer: Update peer from database ---*/
-static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username)
+static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
 {
 	char iabuf[INET_ADDRSTRLEN];
 
@@ -9391,14 +9427,20 @@
                 char query[512];
                 char *name;
                 char *uname;
-                time_t nowtime;
+                time_t exptime;
                 name = alloca(strlen(peer) * 2 + 1);
                 uname = alloca(strlen(username) * 2 + 1);
-                time(&nowtime);
+                time(&exptime);
+				//We set the expiration time in DB rather than registration time because it will be easier to compare
+				exptime += expiry;
                 mysql_real_escape_string(sqlhandle, name, peer, strlen(peer));
 		mysql_real_escape_string(sqlhandle, uname, username, strlen(username));
-                snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",  ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), nowtime, uname, name);
-
+	
+                snprintf(query, sizeof(query), "UPDATE %s SET %s=\"%s\", %s=\"%d\", %s=\"%ld\" WHERE %s=\"%s\"",
+							mydbtable,mydbfield_ipaddr,
+							ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), mydbfield_port, ntohs(sin->sin_port), 
+							mydbfield_regseconds, exptime, mydbfield_name, name);
+				ast_log(LOG_DEBUG, "DEBUG: Executing SQL query: %s ...\n",query);
                 ast_mutex_lock(&mysqllock);
                 if (mysql_real_query(sqlhandle, query, strlen(query)))
                         ast_log(LOG_WARNING, "Unable to update database for peer %s\n", peer);
@@ -9414,6 +9456,7 @@
 	int success = 0;
 	char iabuf[INET_ADDRSTRLEN];
 
+	   
        p = malloc(sizeof(struct sip_peer));
        memset(p, 0, sizeof(struct sip_peer));
 
@@ -9433,19 +9476,26 @@
                p->nat = global_nat;
                p->symmetricrtp = global_symmetricrtp;
                p->dtmfmode = globaldtmfmode;
-	       strncpy(p->musicclass, globalmusicclass, sizeof(p->musicclass);
-	       strncpy(p->language, globallanguage, sizeof(p->language);
+	        strncpy(p->musicclass, globalmusicclass, sizeof(p->musicclass));
+	        strncpy(p->language, global_language, sizeof(p->language));
 
                p->insecure = 1;
                p->expire = -1;
+
                if (peer) {
                        name = alloca(strlen(peer) * 2 + 1);
                        mysql_real_escape_string(sqlhandle, name, peer, strlen(peer));
                }
                if (sin)
-+			snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
+				snprintf(query, sizeof(query), "SELECT %s, %s, %s, %s, %s, %s, %s, %s FROM %s WHERE %s=\"%s\" AND %s=\"%d\"",
+								mydbfield_name, mydbfield_secret,mydbfield_auth,mydbfield_context,mydbfield_peername,mydbfield_ipaddr,mydbfield_port,mydbfield_regseconds,
+								mydbtable,mydbfield_ipaddr,	ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr),
+								mydbfield_port, ntohs(sin->sin_port));
                else
-+			snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
+				snprintf(query, sizeof(query), "SELECT %s, %s, %s, %s, %s, %s, %s, %s FROM %s WHERE %s=\"%s\"",
+								mydbfield_name, mydbfield_secret,mydbfield_auth,mydbfield_context,mydbfield_peername,mydbfield_ipaddr,mydbfield_port,mydbfield_regseconds,
+								mydbtable,mydbfield_name, name);
+			   ast_log(LOG_DEBUG, "Executing SQL Query %s\n", query);
                ast_mutex_lock(&mysqllock);
                mysql_query(sqlhandle, query);
                if ((result = mysql_store_result(sqlhandle))) {
@@ -9456,29 +9506,31 @@
 				p->addr.sin_family = AF_INET;
               			for (x=0;x<numfields;x++) {
                                        if (rowval[x]) {
-                                               if (!strcasecmp(fields[x].name, "secret")) {
+                                               if (!strcasecmp(fields[x].name, mydbfield_secret)) {
                                                        strncpy(p->secret, rowval[x], sizeof(p->secret));
-                                               } else if (!strcasecmp(fields[x].name, "name")) {
+                                               } else if (!strcasecmp(fields[x].name, mydbfield_name )) {
                                                        strncpy(p->name, rowval[x], sizeof(p->name) - 1);
-                                               } else if (!strcasecmp(fields[x].name, "username")) {
-                                                       strncpy(p->username, rowval[x], sizeof(p->username) - 1);
-                                               } else if (!strcasecmp(fields[x].name, "context")) {
+                                               } else if (!strcasecmp(fields[x].name, mydbfield_peername )) {
+                                                       strncpy(p->peerusername, rowval[x], sizeof(p->peerusername) - 1);
+                                               } else if (!strcasecmp(fields[x].name, mydbfield_context )) {
                                                        strncpy(p->context, rowval[x], sizeof(p->context) - 1);
-                                               } else if (!strcasecmp(fields[x].name, "ipaddr")) {
-                                                       inet_aton(rowval[x], &p->addr.sin_addr);
-                                               } else if (!strcasecmp(fields[x].name, "port")) {
-                                                       if (sscanf(rowval[x], "%i", &port) != 1)
-                                                               port = 0;
-                                                       p->addr.sin_port = htons(port);
-                                               } else if (!strcasecmp(fields[x].name, "regseconds")) {
+                                               } else if (!strcasecmp(fields[x].name, mydbfield_port )) {
+												   if (sscanf(rowval[x], "%i", &port) != 1)
+                                                               p->addr.sin_port = htons((u_short)0);
+															   p->addr.sin_port = htons((u_short)port);
+											   } else if (!strcasecmp(fields[x].name, mydbfield_ipaddr )) {
+														inet_aton(rowval[x], &p->addr.sin_addr);
+                                               } else if (!strcasecmp(fields[x].name, mydbfield_regseconds )) {
                                                        if (sscanf(rowval[x], "%li", &regseconds) != 1)
                                                                regseconds = 0;
+                                               } else if (!strcasecmp(fields[x].name, mydbfield_auth)) {
+                                                       p->auth = add_realm_authentication(p->auth, rowval[x], 0);
                                                }
                                        }
                                }
                                time(&nowtime);
                                if (nowtime > regseconds)
-                                       memset(&p->addr, 0, sizeof(p->addr));
+                                      memset(&p->addr, 0, sizeof(p->addr));
                        }
 			mysql_free_result(result);
 			result = NULL;
@@ -9490,9 +9542,8 @@
                p = NULL;
        }  else {
           p->temponly = 1;
-
        }
-       return p;
+	  return p;
 }
 
 
@@ -9505,7 +9556,7 @@
 {
 #ifdef MYSQL_FRIENDS
         if (p->temponly)
-                mysql_update_peer(p->name, &p->addr, p->username, expiry);
+                mysql_update_peer(p->name, &p->addr, p->peerusername, expiry );
 #endif
         return;
 }
@@ -9564,7 +9615,6 @@
 		}
                 u = u->next;
         }
-
         return(u);
 }
 
@@ -9592,7 +9642,7 @@
 	if (!strncasecmp(name, "template-", 9)) {
 		template=1;
 		name = &name[9]; 
-		ast_log(LOG_DEBUG,"Found peer template: %s\n", peer->name);
+		ast_log(LOG_DEBUG,"Found peer template: %s\n", name);
 	}
 
 	/* Does the peer exist already ? (Reload case or duplicate) */
@@ -9630,7 +9680,6 @@
 	/* Autocreatepeer template? */
 	if (!strcasecmp(name,"autocreatepeer")) {
 	   autocreatepeertemplate = peer;		/* Set pointer */
-		ast_log(LOG_DEBUG,"Found autocreatepeer template: %s\n", peer->name);
 	}
 
 	if (peer) {
@@ -9988,6 +10037,7 @@
 		
 		} else if (!strcasecmp(v->name, "autocreatepeer")) {
 			autocreatepeer = ast_true(v->value);
+			ast_log(LOG_NOTICE, "now we have autocreatepeer= %i\n", autocreatepeer );
 		} else if (!strcasecmp(v->name, "trustrpid")) {
 			globaltrustrpid = ast_true(v->value);
 		} else if (!strcasecmp(v->name, "progressinband")) {
@@ -10084,9 +10134,21 @@
 #ifdef MYSQL_GENERIC
                 } else if (!strcasecmp(v->name, "dbfield_secret")) {
                         strncpy(mydbfield_secret, v->value, sizeof(mydbfield_secret) - 1);
+                }  else if (!strcasecmp(v->name, "dbfield_auth")) {
+                        strncpy(mydbfield_auth, v->value, sizeof(mydbfield_auth) - 1);
+                }  else if (!strcasecmp(v->name, "dbfield_name")) {
+                        strncpy(mydbfield_name, v->value, sizeof(mydbfield_name) - 1);
+                }  else if (!strcasecmp(v->name, "dbfield_regseconds")) {
+                        strncpy(mydbfield_regseconds, v->value, sizeof(mydbfield_regseconds) - 1);
+                }  else if (!strcasecmp(v->name, "dbfield_port")) {
+                        strncpy(mydbfield_port, v->value, sizeof(mydbfield_port) - 1);
+                }  else if (!strcasecmp(v->name, "dbfield_ipaddr")) {
+                        strncpy(mydbfield_ipaddr, v->value, sizeof(mydbfield_ipaddr) - 1);
                 } else if (!strcasecmp(v->name, "dbfield_user")) {
                         strncpy(mydbfield_peername, v->value, sizeof(mydbfield_peername) - 1);
-                } else if (!strcasecmp(v->name, "dbtable")) {
+                } else if (!strcasecmp(v->name, "dbfield_context")) {
+                        strncpy(mydbfield_context, v->value, sizeof(mydbfield_context) - 1);
+				} else if (!strcasecmp(v->name, "dbtable")) {
                         strncpy(mydbtable, v->value, sizeof(mydbtable) - 1);
                 } else if (!strcasecmp(v->name, "dbuser")) {
                         strncpy(mydbuser, v->value, sizeof(mydbuser) - 1);
@@ -10425,7 +10487,7 @@
 		pbx_builtin_setvar_helper (chan, varname, content);
 		ast_log(LOG_NOTICE,"SIP Header %s added to variable %s\n", header, varname);
 	} else {
-		ast_log(LOG_WARNING,"SIP Header %s not found\n", header, varname);
+		ast_log(LOG_WARNING,"SIP Header %s not found, variable %s\n", header, varname);
 		chan->priority += 100;
 	}
 	
