Index: channels/chan_sip.c
===================================================================
RCS file: /usr/cvsroot/asterisk/channels/chan_sip.c,v
retrieving revision 1.747
diff -u -r1.747 chan_sip.c
--- channels/chan_sip.c	30 May 2005 13:51:04 -0000	1.747
+++ channels/chan_sip.c	3 Jun 2005 14:14:48 -0000
@@ -742,6 +754,45 @@
 	return res;
 }
 
+static char *skip_blanks(char *c)
+{
+	while (*c && *c < 33)
+		c++;
+	return c;
+}
+
+static char *trim_blanks(char *c)
+{
+	while (*c && *c < 33)
+		c--;
+	return c;
+}
+
+static char *skip_nonblanks(char *c)
+{
+	while (*c && *c > 32)
+		c++;
+	return c;
+}
+
+/*
+ * If there is a string in <brackets>, strip everything around and return
+ * the content. Otherwise return the original argument.
+ */
+static char *get_in_brackets(char *c)
+{
+	char *n = strchr(c, '<');
+
+	if (n) {
+		c = n + 1;
+		n = strchr(c, '>');
+		/* Lose the part after the > */
+		if (n) 
+			*n = '\0';
+	}
+	return c;
+}
+
 /*--- sip_debug_test_addr: See if we pass debug IP filter */
 static inline int sip_debug_test_addr(struct sockaddr_in *addr) 
 {
@@ -1053,8 +1096,7 @@
 		}
 		cur = p->packets;
 		ast_copy_string(method, p->packets->data, sizeof(method));
-		c = method;
-		while(*c && (*c < 33)) c++;
+		c = skip_blanks(method);
 		*c = '\0';
 		__sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
 	}
@@ -1164,27 +1206,19 @@
 	return res;
 }
 
-/*--- url_decode: Decode SIP URL  ---*/
+/*--- url_decode: Decode SIP URL (overwrite the string)  ---*/
 static void url_decode(char *s) 
 {
-	char *o = s;
+	char *o;
 	unsigned int tmp;
-	while(*s) {
-		switch(*s) {
-		case '%':
-			if (strlen(s) > 2) {
-				if (sscanf(s + 1, "%2x", &tmp) == 1) {
-					*o = tmp;
-					s += 2;	/* Will be incremented once more when we break out */
-					break;
-				}
-			}
-			/* Fall through if something wasn't right with the formatting */
-		default:
+
+	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;
-		}
-		s++;
-		o++;
 	}
 	*o = '\0';
 }
@@ -2449,10 +2481,7 @@
 static char* get_sdp_by_line(char* line, char *name, int nameLen)
 {
 	if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
-		char* r = line + nameLen + 1;
-		while (*r && (*r < 33)) 
-			++r;
-		return r;
+		return skip_blanks(line + nameLen + 1);
 	}
 	return "";
 }
@@ -2493,49 +2522,45 @@
 	return "";
 }
 
-static char *__get_header(struct sip_request *req, char *name, int *start)
+static char *find_alias(const char *name, char *_default)
 {
 	int x;
-	int len = strlen(name);
-	char *r;
-	if (pedanticsipchecking) {
-		/* Technically you can place arbitrary whitespace both before and after the ':' in
-		   a header, although RFC3261 clearly says you shouldn't before, and place just
-		   one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
-		   a good idea to say you can do it, and if you can do it, why in the hell would 
-		   you say you shouldn't.  */
+	for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
+		if (!strcasecmp(aliases[x].fullname, name))
+			return aliases[x].shortname;
+	return _default;
+}
+
+static char *__get_header(struct sip_request *req, char *name, int *start)
+{
+	int pass;
+
+	/*
+	 * Technically you can place arbitrary whitespace both before and after the ':' in
+	 * a header, although RFC3261 clearly says you shouldn't before, and place just
+	 * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
+	 * a good idea to say you can do it, and if you can do it, why in the hell would.
+	 * you say you shouldn't.
+	 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
+	 * and we always allow spaces after that for compatibility.
+	 */
+	for (pass = 0; name && pass < 2;pass++) {
+		int x, len = strlen(name);
 		for (x=*start; x<req->headers; x++) {
 			if (!strncasecmp(req->header[x], name, len)) {
-				r = req->header[x] + len;
-				while(*r && (*r < 33))
-					r++;
+				char *r = req->header[x] + len;	/* skip name */
+				if (pedanticsipchecking)
+					r = skip_blanks(r);
+
 				if (*r == ':') {
-					r++ ;
-					while(*r && (*r < 33))
-						r++;
 					*start = x+1;
-					return r;
+					return skip_blanks(r+1);
 				}
 			}
 		}
-	} else {
-		/* We probably shouldn't even bother counting whitespace afterwards but
-		   I guess for backwards compatibility we will */
-		for (x=*start;x<req->headers;x++) {
-			if (!strncasecmp(req->header[x], name, len) && 
-					(req->header[x][len] == ':')) {
-				r = req->header[x] + len + 1;
-				while(*r && (*r < 33))
-					r++;
-				*start = x+1;
-				return r;
-			}
-		}
+		if (pass == 0) /* Try aliases */
+			name = find_alias(name, NULL);
 	}
-	/* Try aliases */
-	for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
-		if (!strcasecmp(aliases[x].fullname, name))
-			return __get_header(req, aliases[x].shortname, start);
 
 	/* Don't return NULL, so get_header is always a valid pointer */
 	return "";
@@ -3032,9 +3057,7 @@
 				if (debug)
 					ast_verbose("Found RTP audio format %d\n", codec);
 				ast_rtp_set_m_type(p->rtp, codec);
-				codecs += len;
-				/* Skip over any whitespace */
-				while(*codecs && (*codecs < 33)) codecs++;
+				codecs = skip_blanks(codecs + len);
 			}
 		}
 		if (p->vrtp)
@@ -3054,9 +3077,7 @@
 				if (debug)
 					ast_verbose("Found video format %s\n", ast_getformatname(codec));
 				ast_rtp_set_m_type(p->vrtp, codec);
-				codecs += len;
-				/* Skip over any whitespace */
-				while(*codecs && (*codecs < 33)) codecs++;
+				codecs = skip_blanks(codecs + len);
 			}
 		}
 		if (!found )
@@ -3595,26 +3609,15 @@
 		c = p->uri;
 	} else {
 		/* We have no URI, use To: or From:  header as URI (depending on direction) */
-		if (ast_test_flag(p, SIP_OUTGOING))
-			ast_copy_string(stripped, get_header(orig, "To"), sizeof(stripped));
-		else
-			ast_copy_string(stripped, get_header(orig, "From"), sizeof(stripped));
-		
-		c = strchr(stripped, '<');
-		if (c) 
-			c++;
-		else
-			c = stripped;
-		n = strchr(c, '>');
-		if (n)
-			*n = '\0';
+		c = get_header(orig, (ast_test_flag(p, SIP_OUTGOING)) ? "To" : "From");
+		ast_copy_string(stripped, c, sizeof(stripped));
+		c = get_in_brackets(stripped);
 		n = strchr(c, ';');
 		if (n)
 			*n = '\0';
 	}	
 	init_req(req, sipmethod, c);
 
	snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
 
 	add_header(req, "Via", p->via);
 	if (p->route) {
@@ -3990,29 +3985,17 @@
 	char *e, *cmd;
 	int len;
   
-	cmd = req->header[0];
-	while(*cmd && (*cmd < 33)) {
-		cmd++;
-	}
-	if (!*cmd) {
+	cmd = skip_blanks(req->header[0]);
+	if (!*cmd)
 		return -1;
-	}
-	e = cmd;
-	while(*e && (*e > 32)) {
-		e++;
-	}
-	/* Get the command */
-	if (*e) {
-		*e = '\0';
-		e++;
-	}
 	req->rlPart1 = cmd;
-	while( *e && ( *e < 33 ) ) {
-		e++; 
-	}
-	if ( !*e ) {
+	e = skip_nonblanks(cmd);
+	/* Get the command */
+	if (*e)
+		*e++ = '\0';
+	e = skip_blanks(e);
+	if ( !*e )
 		return -1;
-	}
     
 	if ( !strcasecmp(cmd, "SIP/2.0") ) {
 		/* We have a response */
@@ -4021,10 +4004,7 @@
 		if ( len < 2 ) { 
 			return -1;
 		}
-		e+= len - 1;
-		while( *e && *e < 33 ) {
-			e--; 
-		}
+		e = trim_blanks(e + len - 1);
 		*(++e)= '\0';
 	} else {
 		/* We have a request */
@@ -4082,14 +4062,7 @@
 	char stripped[256]="";
 	char *c, *n;
 	ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
-	c = strchr(stripped, '<');
-	if (c) 
-		c++;
-	else
-		c = stripped;
-	n = strchr(c, '>');
-	if (n)
-		*n = '\0';
+	c = get_in_brackets(stripped);
 	n = strchr(c, ';');
 	if (n)
 		*n = '\0';
@@ -4957,16 +4923,7 @@
 
 	/* Look for brackets */
 	ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
-	c = contact;
-	
-	if ((n=strchr(c, '<'))) {
-		c = n + 1;
-		n = strchr(c, '>');
-		/* Lose the part after the > */
-		if (n) 
-			*n = '\0';
-	}
-
+	c = get_in_brackets(contact);
 
 	/* Save full contact to call pvt for later bye or re-invite */
 	ast_copy_string(pvt->fullcontact, c, sizeof(pvt->fullcontact));	
@@ -5051,15 +5008,8 @@
 	}
 	/* Look for brackets */
 	ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
-	c = contact;
-	
-	if ((n=strchr(c, '<'))) {
-		c = n + 1;
-		n = strchr(c, '>');
-		/* Lose the part after the > */
-		if (n) 
-			*n = '\0';
-	}
+	c = get_in_brackets(contact);
+
 	if (!strcasecmp(c, "*") || !expiry) {	/* Unregister this peer */
 		/* This means remove all registrations and return OK */
 		memset(&p->addr, 0, sizeof(p->addr));
@@ -5370,7 +5320,7 @@
 		c = tmp;
 
 		while(c) {
-			while (*c && (*c < 33)) c++;
+			c = skip_blanks(c);
 			if (!*c)
 				break;
 			if (!strncasecmp(c, "response=", strlen("response="))) {
@@ -5611,33 +5563,20 @@
 	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) ||
		!strcmp(c, ast_pickup_ext())) {
 		if (!oreq)
 			ast_copy_string(p->exten, c, sizeof(p->exten));
 		return 0;
 	}
 
 	if (ast_canmatch_extension(NULL, p->context, c, 1, fr) ||
	    !strncmp(c, ast_pickup_ext(),strlen(c))) {
 		return 1;
 	}
 	
 	return -1;
 }
 
-/*--- hex2int: Convert hex code to integer ---*/
-static int hex2int(char a)
-{
-	if ((a >= '0') && (a <= '9')) {
-		return a - '0';
-	} else if ((a >= 'a') && (a <= 'f')) {
-		return a - 'a' + 10;
-	} else if ((a >= 'A') && (a <= 'F')) {
-		return a - 'A' + 10;
-	}
-	return 0;
-}
-
 /*--- get_sip_pvt_byid_locked: Lock interface lock and find matching pvt lock  ---*/
 static struct sip_pvt *get_sip_pvt_byid_locked(char *callid) 
 {
@@ -5667,27 +5606,6 @@
 	return sip_pvt_ptr;
 }
 
-/*--- sip_unescape_uri: Turn %XX into and ascii char ---*/
-static int sip_unescape_uri(char *uri) 
-{
-	char *ptr = uri;
-	int replaced = 0;
-
-	while ((ptr = strchr(ptr, '%'))) {
-		/* un-escape urlencoded text */
-		if (strlen(ptr) < 3)
-			break;
-		*ptr = hex2int(ptr[1]) * 16 + hex2int(ptr[2]);
-		memmove(ptr+1, ptr+3, strlen(ptr+3) + 1);
-		ptr++;
-		replaced++;
-	}
-
-	return replaced;
-}
-
-
-
 /*--- get_refer_info: Call transfer support (the REFER method) ---*/
 static int get_refer_info(struct sip_pvt *sip_pvt, struct sip_request *outgoing_req)
 {
@@ -5738,19 +5656,21 @@
 		*ptr = '\0';
 		ptr++;
 		if (!strncasecmp(ptr, "REPLACES=", 9)) {
+			char *p;
 			replace_callid = ast_strdupa(ptr + 9);
 			/* someday soon to support invite/replaces properly!
 			   replaces_header = ast_strdupa(replace_callid); 
 			   -anthm
 			*/
-			sip_unescape_uri(replace_callid);
+			url_decode(replace_callid);
 			if ((ptr = strchr(replace_callid, '%'))) 
 				*ptr = '\0';
 			if ((ptr = strchr(replace_callid, ';'))) 
 				*ptr = '\0';
-			/* Skip leading whitespace */
-			while(replace_callid[0] && (replace_callid[0] < 33))
-				memmove(replace_callid, replace_callid+1, strlen(replace_callid));
+			/* Skip leading whitespace XXX memmove behaviour with overlaps ? */
+			p = skip_blanks(replace_callid);
+			if (p != replace_callid)
+				memmove(replace_callid, p, strlen(p));
 		}
 	}
 	
@@ -5876,18 +5796,14 @@
 	c = strchr(via, ' ');
 	if (c) {
 		*c = '\0';
-		c++;
-		while(*c && (*c < 33))
-			c++;
+		c = skip_blanks(c+1);
 		if (strcmp(via, "SIP/2.0/UDP")) {
 			ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
 			return -1;
 		}
 		pt = strchr(c, ':');
-		if (pt) {
-			*pt = '\0';
-			pt++;
-		}
+		if (pt)
+			*pt++ = '\0';	/* remeber port pointer */
 		hp = ast_gethostbyname(c, &ahp);
 		if (!hp) {
 			ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
@@ -5898,13 +5814,11 @@
 		memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
 		p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
 		c = strstr(via, ";rport");
-		if (c && (c[6] != '='))
+		if (c && (c[6] != '='))	/* XXX some special hack ? */
 			ast_set_flag(p, SIP_NAT_ROUTE);
 		if (sip_debug_test_pvt(p)) {
-			if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
-				ast_verbose("Sending to %s : %d (NAT)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
-			else
-				ast_verbose("Sending to %s : %d (non-NAT)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
+			c = (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? "NAT" : "non-NAT";
+			ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), c);
 		}
 	}
 	return 0;
@@ -5933,8 +5847,7 @@
 	} else {
 		/* we didn't find "name" */
 		/* clear the empty characters in the begining*/
-		while(*input && (*input < 33))
-			input++;
+		input = skip_blanks(input);
 		/* clear the empty characters in the end */
 		while(*end && (*end < 33) && end > input)
 			end--;
@@ -9184,8 +9068,7 @@
 		ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
 		return -1;
 	}
-	/* Get the command */
-	cseq += len;
+	/* Get the command XXX */
 
 	cmd = req->rlPart1;
 	e = req->rlPart2;
@@ -9212,8 +9095,7 @@
 		}
 	
 		extract_uri(p, req);
-		while(*e && (*e < 33)) 
-			e++;
+		e = skip_blanks(e);
 		if (sscanf(e, "%d %n", &respid, &len) != 1) {
 			ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
 		} else {
@@ -9221,7 +9103,7 @@
 		}
 		return 0;
 	}
-
+	/* XXX what if not SIP/2.0 ? */
 	/* New SIP request coming in 
 	   (could be new request in existing SIP dialog as well...) 
 	 */			
