Index: utils.c
===================================================================
RCS file: /usr/cvsroot/asterisk/utils.c,v
retrieving revision 1.65
diff -u -u -r1.65 utils.c
--- utils.c	23 Aug 2005 17:55:59 -0000	1.65
+++ utils.c	29 Aug 2005 15:59:45 -0000
@@ -382,6 +382,51 @@
 #endif
 }
 
+
+/*--- url_encode: write encoded version of url into buf up to len bytes---*/
+int ast_url_encode(char *url, char *buf, size_t len)
+{
+    char *p;
+    int x = 0;
+    const char urlunsafe[] = " \"#%&+:;<=>?@[\\]^`{|}";
+    const char hex[] = "0123456789ABCDEF";
+
+    memset(buf, 0, len);
+    for( p = url ; *p ; p++) {
+        if (*p < ' ' || *p > '~' || strchr(urlunsafe, *p)) {
+            if ((x + 3) > len) {
+                break;
+            }
+            buf[x++] = '%';
+            buf[x++] = hex[*p >> 4];
+            buf[x++] = hex[*p & 0x0f];
+        } else {
+            buf[x++] = *p;
+        }
+        if (x == len) {
+            break;
+        }
+    }
+    return x;
+}
+
+/*--- url_decode: Decode SIP URL (overwrite the string)  ---*/
+void ast_url_decode(char *s) 
+{
+	char *o;
+	unsigned int tmp;
+
+	for (o = s; *s; s++, o++) {
+		if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
+			/* have '%', two chars and correct parsing */
+			*o = tmp;
+			s += 2;	/* Will be incremented once more when we break out */
+		} else /* all other cases, just copy */
+			*o = *s;
+	}
+	*o = '\0';
+}
+
 /* Recursive thread safe replacement of inet_ntoa */
 const char *ast_inet_ntoa(char *buf, int bufsiz, struct in_addr ia)
 {
@@ -634,9 +679,9 @@
 
 #ifndef HAVE_STRTOQ
 #define LONG_MIN        (-9223372036854775807L-1L)
-                                        /* min value of a "long int" */
+	                                 /* min value of a "long int" */
 #define LONG_MAX        9223372036854775807L
-                                        /* max value of a "long int" */
+	                                 /* max value of a "long int" */
 
 /*
  * Convert a string to a quad integer.
@@ -646,85 +691,85 @@
  */
 uint64_t strtoq(const char *nptr, char **endptr, int base)
 {
-        const char *s;
-        uint64_t acc;
-        unsigned char c;
-        uint64_t qbase, cutoff;
-        int neg, any, cutlim;
-
-        /*
-         * Skip white space and pick up leading +/- sign if any.
-         * If base is 0, allow 0x for hex and 0 for octal, else
-         * assume decimal; if base is already 16, allow 0x.
-         */
-        s = nptr;
-        do {
-                c = *s++;
-        } while (isspace(c));
-        if (c == '-') {
-                neg = 1;
-                c = *s++;
-        } else {
-                neg = 0;
-                if (c == '+')
-                        c = *s++;
-        }
-        if ((base == 0 || base == 16) &&
-            c == '\0' && (*s == 'x' || *s == 'X')) {
-                c = s[1];
-                s += 2;
-                base = 16;
-        }
-        if (base == 0)
-                base = c == '\0' ? 8 : 10;
-
-        /*
-         * Compute the cutoff value between legal numbers and illegal
-         * numbers.  That is the largest legal value, divided by the
-         * base.  An input number that is greater than this value, if
-         * followed by a legal input character, is too big.  One that
-         * is equal to this value may be valid or not; the limit
-         * between valid and invalid numbers is then based on the last
-         * digit.  For instance, if the range for quads is
-         * [-9223372036854775808..9223372036854775807] and the input base
-         * is 10, cutoff will be set to 922337203685477580 and cutlim to
-         * either 7 (neg==0) or 8 (neg==1), meaning that if we have
-         * accumulated a value > 922337203685477580, or equal but the
-         * next digit is > 7 (or 8), the number is too big, and we will
-         * return a range error.
-         *
-         * Set any if any `digits' consumed; make it negative to indicate
-         * overflow.
-         */
-        qbase = (unsigned)base;
-        cutoff = neg ? (uint64_t)-(LONG_MIN + LONG_MAX) + LONG_MAX : LONG_MAX;
-        cutlim = cutoff % qbase;
-        cutoff /= qbase;
-        for (acc = 0, any = 0;; c = *s++) {
-                if (!isascii(c))
-                        break;
-                if (isdigit(c))
-                        c -= '\0';
-                else if (isalpha(c))
-                        c -= isupper(c) ? 'A' - 10 : 'a' - 10;
-                else
-                        break;
-                if (c >= base)
-                        break;
-                if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
-                        any = -1;
-                else {
-                        any = 1;
-                        acc *= qbase;
-                        acc += c;
-                }
-        }
-        if (any < 0) {
-                acc = neg ? LONG_MIN : LONG_MAX;
-        } else if (neg)
-                acc = -acc;
-        if (endptr != 0)
-                *((const char **)endptr) = any ? s - 1 : nptr;
-        return (acc);
+	 const char *s;
+	 uint64_t acc;
+	 unsigned char c;
+	 uint64_t qbase, cutoff;
+	 int neg, any, cutlim;
+
+	 /*
+	  * Skip white space and pick up leading +/- sign if any.
+	  * If base is 0, allow 0x for hex and 0 for octal, else
+	  * assume decimal; if base is already 16, allow 0x.
+	  */
+	 s = nptr;
+	 do {
+	         c = *s++;
+	 } while (isspace(c));
+	 if (c == '-') {
+	         neg = 1;
+	         c = *s++;
+	 } else {
+	         neg = 0;
+	         if (c == '+')
+	                 c = *s++;
+	 }
+	 if ((base == 0 || base == 16) &&
+	     c == '\0' && (*s == 'x' || *s == 'X')) {
+	         c = s[1];
+	         s += 2;
+	         base = 16;
+	 }
+	 if (base == 0)
+	         base = c == '\0' ? 8 : 10;
+
+	 /*
+	  * Compute the cutoff value between legal numbers and illegal
+	  * numbers.  That is the largest legal value, divided by the
+	  * base.  An input number that is greater than this value, if
+	  * followed by a legal input character, is too big.  One that
+	  * is equal to this value may be valid or not; the limit
+	  * between valid and invalid numbers is then based on the last
+	  * digit.  For instance, if the range for quads is
+	  * [-9223372036854775808..9223372036854775807] and the input base
+	  * is 10, cutoff will be set to 922337203685477580 and cutlim to
+	  * either 7 (neg==0) or 8 (neg==1), meaning that if we have
+	  * accumulated a value > 922337203685477580, or equal but the
+	  * next digit is > 7 (or 8), the number is too big, and we will
+	  * return a range error.
+	  *
+	  * Set any if any `digits' consumed; make it negative to indicate
+	  * overflow.
+	  */
+	 qbase = (unsigned)base;
+	 cutoff = neg ? (uint64_t)-(LONG_MIN + LONG_MAX) + LONG_MAX : LONG_MAX;
+	 cutlim = cutoff % qbase;
+	 cutoff /= qbase;
+	 for (acc = 0, any = 0;; c = *s++) {
+	         if (!isascii(c))
+	                 break;
+	         if (isdigit(c))
+	                 c -= '\0';
+	         else if (isalpha(c))
+	                 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
+	         else
+	                 break;
+	         if (c >= base)
+	                 break;
+	         if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
+	                 any = -1;
+	         else {
+	                 any = 1;
+	                 acc *= qbase;
+	                 acc += c;
+	         }
+	 }
+	 if (any < 0) {
+	         acc = neg ? LONG_MIN : LONG_MAX;
+	 } else if (neg)
+	         acc = -acc;
+	 if (endptr != 0)
+	         *((const char **)endptr) = any ? s - 1 : nptr;
+	 return acc;
 }
 #endif
Index: include/asterisk/utils.h
===================================================================
RCS file: /usr/cvsroot/asterisk/include/asterisk/utils.h,v
retrieving revision 1.40
diff -u -u -r1.40 utils.h
--- include/asterisk/utils.h	19 Jul 2005 23:17:02 -0000	1.40
+++ include/asterisk/utils.h	29 Aug 2005 15:59:45 -0000
@@ -128,10 +128,34 @@
 };
 
 extern struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp);
-/* ast_md5_hash: Produces MD5 hash based on input string */
+
+/* ast_md5_hash 
+	\brief Produces MD5 hash based on input string */
 extern void ast_md5_hash(char *output, char *input);
+
 extern int ast_base64encode(char *dst, unsigned char *src, int srclen, int max);
 extern int ast_base64decode(unsigned char *dst, char *src, int max);
+
+/*! url_encode
+	\brief Turn text string to URI-encoded %XX version 
+ 	At this point, we're converting from ISO-8859-x (8-bit), not UTF8
+	as in the SIP protocol spec 
+	RFC 2396, section 2.4
+	outbuf needs to have more memory allocated than the instring
+	to have room for the expansion. Every char that is converted
+	is replaced by three ASCII characters.
+	\param string	String to be converted
+	\param outbuf	Resulting encoded string
+	\param buflen	Size of output buffer
+*/
+
+int ast_url_encode(char *url, char *buf, size_t len);
+
+/*!	\brief Decode URL (overwrite string)
+	\param s	String to be decoded 
+ */
+void ast_url_decode(char *s);
+	
 
 extern int test_for_thread_safety(void);
 
Index: channels/chan_sip.c
===================================================================
RCS file: /usr/cvsroot/asterisk/channels/chan_sip.c,v
retrieving revision 1.822
diff -u -u -r1.822 chan_sip.c
--- channels/chan_sip.c	27 Aug 2005 23:55:14 -0000	1.822
+++ channels/chan_sip.c	29 Aug 2005 15:59:58 -0000
@@ -497,7 +497,7 @@
 #define SIP_PAGE2_RTUPDATE 		(1 << 1)
 #define SIP_PAGE2_RTAUTOCLEAR 		(1 << 2)
 #define SIP_PAGE2_RTIGNOREREGEXPIRE       (1 << 3)
-
+#define SIP_PAGE2_RT_FROMCONTACT		(1 << 4)
 static int global_rtautoclear = 120;
 
 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call  */
@@ -528,6 +528,7 @@
 	int sessionid;				/* SDP Session ID */
 	int sessionversion;			/* SDP Session Version */
 	struct sockaddr_in sa;			/* Our peer */
+	struct sockaddr_in defaddr;			/* Our peer */
 	struct sockaddr_in redirip;		/* Where our RTP should be going if not to us */
 	struct sockaddr_in vredirip;		/* Where our Video RTP should be going if not to us */
 	int redircodecs;			/* Redirect codecs */
@@ -564,6 +565,7 @@
 	char cid_name[256];			/* Caller*ID */
 	char via[256];				/* Via: header */
 	char fullcontact[128];			/* The Contact: that the UA registers with us */
+	char rtfullcontact[128];			/* The last loaded fullcontact from realtime*/
 	char accountcode[AST_MAX_ACCOUNT_CODE];	/* Account code */
 	char our_contact[256];			/* Our contact header */
 	char realm[MAXHOSTNAMELEN];		/* Authorization realm */
@@ -670,6 +672,7 @@
 	char fromuser[80];		/* From: user when calling this peer */
 	char fromdomain[MAXHOSTNAMELEN];	/* From: domain when calling this peer */
 	char fullcontact[256];		/* Contact registred with us (not in sip.conf) */
+	char rtfullcontact[128];			/* The last loaded fullcontact from realtime*/
 	char cid_num[80];		/* Caller ID num */
 	char cid_name[80];		/* Caller ID name */
 	int callingpres;		/* Calling id presentation */
@@ -836,6 +839,7 @@
 static void append_date(struct sip_request *req);	/* Append date to SIP packet */
 static int determine_firstline_parts(struct sip_request *req);
 static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to LOG_DEBUG at end of dialog, before destroying data */
+static void reg_source_db(struct sip_peer *peer);
 
 /* Definition of this channel for channel registration */
 static const struct ast_channel_tech sip_tech = {
@@ -951,12 +955,21 @@
 	int res;
 	char iabuf[INET_ADDRSTRLEN];
 
-	if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
+	if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) {
+		if (!ntohs(p->recv.sin_port)) {
+			p->recv.sin_port = p->defaddr.sin_port;
+		}
 		res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
-	else
+	} else {
+		if (!ntohs(p->sa.sin_port)) {
+			p->sa.sin_port = p->defaddr.sin_port;
+		}
 		res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
+	}
+
 	if (res != len) {
-		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), res, strerror(errno));
+		
+		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), res, ntohs(p->sa.sin_port), strerror(errno));
 	}
 	return res;
 }
@@ -1407,23 +1420,6 @@
 	return res;
 }
 
-/*--- url_decode: Decode SIP URL (overwrite the string)  ---*/
-static void url_decode(char *s) 
-{
-	char *o;
-	unsigned int tmp;
-
-	for (o = s; *s; s++, o++) {
-		if (*s == '%' && strlen(s) > 2 && sscanf(s + 1, "%2x", &tmp) == 1) {
-			/* have '%', two chars and correct parsing */
-			*o = tmp;
-			s += 2;	/* Will be incremented once more when we break out */
-		} else /* all other cases, just copy */
-			*o = *s;
-	}
-	*o = '\0';
-}
-
 /*--- get_in_brackets: Pick out text in brackets from character string ---*/
 /* returns pointer to terminated stripped string. modifies input string. */
 static char *get_in_brackets(char *tmp)
@@ -1568,6 +1564,7 @@
 	struct ast_variable *var;
 	struct ast_variable *tmp;
 	char *newpeername = (char *) peername;
+	char *fullcontact = NULL;
 	char iabuf[80] = "";
 
 	/* First check on peer name */
@@ -1592,6 +1589,10 @@
 		} else if (!newpeername && !strcasecmp(tmp->name, "name")) {
 			newpeername = tmp->value;
 		}
+		if (!strcasecmp(tmp->name, "fullcontact")) {
+			fullcontact = ast_strdupa(tmp->value);
+			ast_url_decode(fullcontact);
+		}
 		tmp = tmp->next;
 	}
 	
@@ -1600,17 +1601,23 @@
 		ast_variables_destroy(var);
 		return (struct sip_peer *) NULL;
 	}
-		
 	/* Peer found in realtime, now build it in memory */
-	peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
-
-	if (!peer) {
+	
+	if ((peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)))) {
+		if (fullcontact) {
+			ast_copy_string(peer->rtfullcontact, fullcontact, sizeof(peer->rtfullcontact));
+		}
+	} else {
 		ast_variables_destroy(var);
 		return (struct sip_peer *) NULL;
 	}
+
+	ast_set_flag((&peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT);
+
 	if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
 		/* Cache peer */
 		ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
+
 		if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
 			if (peer->expire > -1) {
 				ast_sched_del(sched, peer->expire);
@@ -1622,6 +1629,10 @@
 		ast_set_flag(peer, SIP_REALTIME);
 	}
 	ast_variables_destroy(var);
+
+	if(fullcontact) {
+		reg_source_db(peer);
+	}
 	return peer;
 }
 
@@ -1735,6 +1746,10 @@
 {
 	char *callhost;
 
+
+	r->defaddr.sin_addr = peer->defaddr.sin_addr;
+	r->defaddr.sin_port = peer->defaddr.sin_port;
+
 	if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
 	    (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
 		if (peer->addr.sin_addr.s_addr) {
@@ -4348,15 +4363,16 @@
 		snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip));
 }
 
-/*--- initreqprep: Initiate SIP request to peer/user ---*/
+/*--- initreqprep: Initiate new SIP request to peer/user ---*/
 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, char *vxml_url)
 {
-	char invite[256]="";
+	char invite[256] = "";
 	char from[256];
 	char to[256];
-	char tmp[80];
+	char tmp[BUFSIZ/2];
+	char tmp2[BUFSIZ/2];
 	char iabuf[INET_ADDRSTRLEN];
-	char *l = default_callerid, *n=NULL;
+	char *l = default_callerid, *n = NULL;
 	int x;
 	char urioptions[256]="";
 
@@ -4372,7 +4388,7 @@
         	if (p->username && p->username[0] == '+')
 			x=1;
 
-		for (; x<strlen(p->username); x++) {
+		for (; x < strlen(p->username); x++) {
 			if (!strchr(AST_DIGIT_ANYNUM, p->username[x])) {
                 		onlydigits = 0;
 				break;
@@ -4403,17 +4419,24 @@
 	/* Allow user to be overridden */
 	if (!ast_strlen_zero(p->fromuser))
 		l = p->fromuser;
-	else /* Save for any further attempts */
+	else /* Save for any further attempts */ {
 		ast_copy_string(p->fromuser, l, sizeof(p->fromuser));
-
+	}
 	/* Allow user to be overridden */
 	if (!ast_strlen_zero(p->fromname))
 		n = p->fromname;
-	else /* Save for any further attempts */
+	else /* Save for any further attempts */ {
 		ast_copy_string(p->fromname, n, sizeof(p->fromname));
+	}
+	if (pedanticsipchecking) {
+		ast_url_encode(n, tmp, sizeof(tmp));
+		n = tmp;
+		ast_url_encode(l, tmp2, sizeof(tmp2));
+		l = tmp2;
+	}
 
 	if ((ourport != 5060) && ast_strlen_zero(p->fromdomain))	/* Needs to be 5060 */
-		snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, ourport, p->tag);
+		snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", tmp, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, ourport, p->tag);
 	else
 		snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, p->tag);
 
@@ -4421,22 +4444,42 @@
 	if (!ast_strlen_zero(p->fullcontact)) {
 		/* If we have full contact, trust it */
 		ast_copy_string(invite, p->fullcontact, sizeof(invite));
-	/* Otherwise, use the username while waiting for registration */
+		/* If we have RT full contact, trust it */
+	} else if (!ast_strlen_zero(p->rtfullcontact)) {
+		char *ptr = p->rtfullcontact;
+		int x = 0;
+		while ((ptr = strchr(ptr, ':'))) {
+			ptr++;
+			x++;
+			if (x == 4) {
+				break;
+			}
+		}
+		if (ptr) {
+			ast_copy_string(invite, ptr, sizeof(invite));
+		}
+		/* Otherwise, use the username while waiting for registration */
 	} else if (!ast_strlen_zero(p->username)) {
+		n = p->username;
+		if (pedanticsipchecking) {
+			ast_url_encode(n, tmp, sizeof(tmp));
+			n = tmp;
+		}
 		if (ntohs(p->sa.sin_port) != 5060) {		/* Needs to be 5060 */
-			snprintf(invite, sizeof(invite), "sip:%s@%s:%d%s",p->username, p->tohost, ntohs(p->sa.sin_port), urioptions);
+			snprintf(invite, sizeof(invite), "sip:%s@%s:%d%s", n, p->tohost, ntohs(p->sa.sin_port), urioptions);
 		} else {
-			snprintf(invite, sizeof(invite), "sip:%s@%s%s",p->username, p->tohost, urioptions);
+			snprintf(invite, sizeof(invite), "sip:%s@%s%s", n, p->tohost, urioptions);
 		}
 	} else if (ntohs(p->sa.sin_port) != 5060) {		/* Needs to be 5060 */
 		snprintf(invite, sizeof(invite), "sip:%s:%d%s", p->tohost, ntohs(p->sa.sin_port), urioptions);
 	} else {
 		snprintf(invite, sizeof(invite), "sip:%s%s", p->tohost, urioptions);
 	}
+
 	ast_copy_string(p->uri, invite, sizeof(p->uri));
+
 	/* If there is a VXML URL append it to the SIP URL */
-	if (vxml_url)
-	{
+	if (vxml_url) {
 		snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
 	} else {
 		snprintf(to, sizeof(to), "<%s>", invite);
@@ -5122,7 +5165,15 @@
 	struct sip_peer *peer = data;
 
 	memset(&peer->addr, 0, sizeof(peer->addr));
-	ast_db_del("SIP/Registry", peer->name);
+	
+	if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT)) {
+		if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_RTIGNOREREGEXPIRE)) {
+			ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", NULL);
+		}
+	} else {
+		ast_db_del("SIP/Registry", peer->name);
+	}
+
 	manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
 	register_peer_exten(peer, 0);
 	peer->expire = -1;
@@ -5155,8 +5206,13 @@
 	int port;
 	char *scan, *addr, *port_str, *expiry_str, *username, *contact;
 
-	if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
-		return;
+	if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT)) {
+		if (!ast_strlen_zero(peer->rtfullcontact)) {
+			ast_copy_string(data, peer->rtfullcontact, sizeof(data));
+		}
+	} else {
+		ast_db_get("SIP/Registry", peer->name, data, sizeof(data));
+	}
 
 	scan = data;
 	addr = strsep(&scan, ":");
@@ -5164,7 +5220,7 @@
 	expiry_str = strsep(&scan, ":");
 	username = strsep(&scan, ":");
 	contact = scan;	/* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
-
+	ast_log(LOG_DEBUG,"Ouer Contact from db is:%s",contact);
 	if (!inet_aton(addr, &in))
 		return;
 
@@ -5309,7 +5365,15 @@
 		if (p->expire > -1)
 			ast_sched_del(sched, p->expire);
 		p->expire = -1;
-		ast_db_del("SIP/Registry", p->name);
+
+		if (ast_test_flag(&(p->flags_page2), SIP_PAGE2_RT_FROMCONTACT)) {
+			if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_RTIGNOREREGEXPIRE)) {
+				ast_update_realtime("sippeers", "name", p->name, "fullcontact", "", NULL);
+			}
+		} else {
+			ast_db_del("SIP/Registry", p->name);
+		}
+		
 		register_peer_exten(p, 0);
 		p->fullcontact[0] = '\0';
 		p->useragent[0] = '\0';
@@ -5322,6 +5386,11 @@
 		return 0;
 	}
 	ast_copy_string(p->fullcontact, c, sizeof(p->fullcontact));
+	if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE)) {
+		char buf[128];
+		ast_url_encode(c, buf, sizeof(buf));
+		ast_update_realtime("sippeers", "name", p->name, "fullcontact", buf, NULL);
+	}
 	/* For the 200 OK, we should use the received contact */
 	snprintf(pvt->our_contact, sizeof(pvt->our_contact) - 1, "<%s>", c);
 	/* Make sure it's a SIP URL */
@@ -5382,8 +5451,13 @@
 		p->expire = -1;
 	pvt->expiry = expiry;
 	snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry, p->username, p->fullcontact);
-	if (!(ast_test_flag(p, SIP_REALTIME) && ast_test_flag((&p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)))
+	if (ast_test_flag((&p->flags_page2), SIP_PAGE2_RT_FROMCONTACT)) {
+		char buf[128];
+		ast_url_encode(data, buf, sizeof(buf));
+		ast_update_realtime("sippeers", "name", p->name, "fullcontact", buf, NULL);
+	} else {
 		ast_db_put("SIP/Registry", p->name, data);
+	}
 	manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", p->name);
 	if (inaddrcmp(&p->addr, &oldsin)) {
 		sip_poke_peer(p);
@@ -5756,7 +5830,7 @@
 /*--- register_verify: Verify registration of user */
 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri, int ignore)
 {
-	int res = -1;
+	int res = -3;
 	struct sip_peer *peer;
 	char tmp[256] = "";
 	char iabuf[INET_ADDRSTRLEN];
@@ -5770,6 +5844,9 @@
 	*t = '\0';
 	
 	ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
+	if (pedanticsipchecking)
+		ast_url_decode(tmp);
+
 	c = get_in_brackets(tmp);
 	/* Ditch ;user=phone */
 	name = strchr(c, ';');
@@ -5838,7 +5915,7 @@
 		switch (res) {
 		case -1:
 			/* Wrong password in authentication. Go away, don't try again until you fixed it */
-			transmit_response(p, "403 Forbidden", &p->initreq);
+			transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
 			break;
 		case -2:
 			/* Username and digest username does not match. 
@@ -5847,6 +5924,13 @@
 			   proper authentication by digest auth name */
 			transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
 			break;
+		case -3:
+			/* URI not found */
+			transmit_response(p, "404 Not found", &p->initreq);
+			break;
+		}
+		if (option_debug > 1) {
+			ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n", peer->name, (res == -1) ? "Bad password" : ((res == -2 ) ? "Bad digest user" : "Peer not found"));
 		}
 	}
 	if (peer)
@@ -5894,10 +5978,16 @@
 		req = &p->initreq;
 	if (req->rlPart2)
 		ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
-	c = get_in_brackets(tmp);
 	
 	ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
+
+	if (pedanticsipchecking) {
+		ast_url_decode(tmp);
+		ast_url_decode(tmpf);
+	}
+
 	fr = get_in_brackets(tmpf);
+	c = get_in_brackets(tmp);
 	
 	if (strncmp(c, "sip:", 4)) {
 		ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
@@ -5930,7 +6020,7 @@
 			ast_copy_string(p->fromdomain, fr, sizeof(p->fromdomain));
 	}
 	if (pedanticsipchecking)
-		url_decode(c);
+		ast_url_decode(c);
 	if (sip_debug_test_pvt(p))
 		ast_verbose("Looking for %s in %s\n", c, p->context);
 	if (ast_exists_extension(NULL, p->context, c, 1, fr) ||
@@ -6004,6 +6094,9 @@
 		ast_log(LOG_WARNING, "No Referrred-By Header That's not illegal\n");
 		return -1;
 	} else {
+		if (pedanticsipchecking) {
+			ast_url_decode(h_referred_by);
+		}
 		referred_by = get_in_brackets(h_referred_by);
 	}
 	h_contact = get_header(req, "Contact");
@@ -6035,7 +6128,7 @@
 			   replaces_header = ast_strdupa(replace_callid); 
 			   -anthm
 			*/
-			url_decode(replace_callid);
+			ast_url_decode(replace_callid);
 			if ((ptr = strchr(replace_callid, '%'))) 
 				*ptr = '\0';
 			if ((ptr = strchr(replace_callid, ';'))) 
@@ -6291,7 +6384,11 @@
 		t++;
 	*t = '\0';
 	of = get_header(req, "From");
+	if (pedanticsipchecking)
+		ast_url_decode(of);
+
 	ast_copy_string(from, of, sizeof(from));
+	
 	memset(calleridname,0,sizeof(calleridname));
 	get_calleridname(from, calleridname, sizeof(calleridname));
 
@@ -6478,6 +6575,7 @@
 				if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name)) 
 					ast_copy_string(p->cid_name, peer->cid_name, sizeof(p->cid_name));
 				ast_copy_string(p->fullcontact, peer->fullcontact, sizeof(p->fullcontact));
+				ast_copy_string(p->rtfullcontact, peer->rtfullcontact, sizeof(p->rtfullcontact));
 				if (!ast_strlen_zero(peer->context))
 					ast_copy_string(p->context, peer->context, sizeof(p->context));
 				ast_copy_string(p->peersecret, peer->secret, sizeof(p->peersecret));
@@ -7253,6 +7351,7 @@
 		ast_cli(fd, "%s\n",status);
  		ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
  		ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
+ 		ast_cli(fd, "  RT data      : %s\n", peer->rtfullcontact);
 		if (peer->chanvars) {
  			ast_cli(fd, "  Variables    :\n");
 			for (v = peer->chanvars ; v ; v = v->next)
@@ -9832,7 +9931,7 @@
 
 	/* Use this as the basis */
 	if (debug)
-		ast_verbose("Using latest request as basis request\n");
+		ast_verbose("Using latest REGISTER request as basis request\n");
 	copy_request(&p->initreq, req);
 	check_via(p, req);
 	if ((res = register_verify(p, sin, req, e, ignore)) < 0) 
@@ -10942,12 +11041,16 @@
 			continue;
 		}
 
-		if (realtime && !strcasecmp(v->name, "regseconds")) {
+		if (!strcasecmp(v->name, "regseconds")) {
 			if (sscanf(v->value, "%li", &regseconds) != 1)
 				regseconds = 0;
-		} else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
+		} else if (!strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
 			inet_aton(v->value, &(peer->addr.sin_addr));
-		} else if (realtime && !strcasecmp(v->name, "name"))
+			if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTIGNOREREGEXPIRE)) {
+				inet_aton(v->value, &(peer->defaddr.sin_addr));
+				found++;
+			}
+		} else if (!strcasecmp(v->name, "name"))
 			ast_copy_string(peer->name, v->value, sizeof(peer->name));
 		else if (!strcasecmp(v->name, "secret")) 
 			ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
@@ -11099,18 +11202,20 @@
 		 */
 		v=v->next;
 	}
-	if (realtime && !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTIGNOREREGEXPIRE) && ast_test_flag(peer, SIP_DYNAMIC)) {
+
+	if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_RTIGNOREREGEXPIRE) && ast_test_flag(peer, SIP_DYNAMIC)) {
 		time_t nowtime;
 
 		time(&nowtime);
 		if ((nowtime - regseconds) > 0) {
 			memset(&peer->addr, 0, sizeof(peer->addr));
+			ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", NULL);
 			if (option_debug)
 				ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
 		}
 	}
 	ast_copy_flags(peer, &peerflags, mask.flags);
-	if (!found && ast_test_flag(peer, SIP_DYNAMIC) && !ast_test_flag(peer, SIP_REALTIME))
+	if (!found && ast_test_flag(peer, SIP_DYNAMIC) && !ast_test_flag(peer, SIP_REALTIME)) 
 		reg_source_db(peer);
 	ASTOBJ_UNMARK(peer);
 	ast_free_ha(oldha);
@@ -11199,6 +11304,7 @@
 	/* Read the [general] config section of sip.conf (or from realtime config) */
 	v = ast_variable_browse(cfg, "general");
 	while(v) {
+
 		if (handle_common_options(&global_flags, &dummy, v)) {
 			v = v->next;
 			continue;
