Browse code

core: parse content length - consider multi line header format

- safety checks for log message when not parsing the message buffer

(cherry picked from commit baed515e8aed8e5b505ff716eb57d0c60e582632)
(cherry picked from commit c19e43e7bfa7d88b49312f1e83c3aae0756e4ae5)

Daniel-Constantin Mierla authored on 06/09/2021 10:59:34
Showing 1 changed files
... ...
@@ -219,6 +219,10 @@ char* parse_content_length(char* const buffer, const char* const end,
219 219
 	int  size;
220 220
 
221 221
 	p = buffer;
222
+	if(buffer>=end) {
223
+		LM_ERR("empty input buffer: %p - %p\n", buffer, end);
224
+		goto error;
225
+	}
222 226
 	/* search the begining of the number */
223 227
 	while ( p<end && (*p==' ' || *p=='\t' ||
224 228
 	(*p=='\n' && (*(p+1)==' '||*(p+1)=='\t')) ))
... ...
@@ -235,20 +239,40 @@ char* parse_content_length(char* const buffer, const char* const end,
235 239
 	}
236 240
 	if (p==end || size==0)
237 241
 		goto error;
238
-	/* now we should have only spaces at the end */
239
-	while ( p<end && (*p==' ' || *p=='\t' ||
240
-	(*p=='\n' && (*(p+1)==' '||*(p+1)=='\t')) ))
241
-		p++;
242
-	if (p==end)
243
-		goto error;
244
-	/* the header ends proper? */
245
-	if ( (*(p++)!='\n') && (*(p-1)!='\r' || *(p++)!='\n' ) )
246
-		goto error;
242
+	do {
243
+		/* only spaces till the end-of-header */
244
+		while (p<end && (*p==' ' || *p=='\t')) p++;
245
+		if (p==end)
246
+			goto error;
247
+		/* EOH with \n or \r\n */
248
+		if(*p=='\n') {
249
+			p++;
250
+		} else if (p+1<end && *p=='\r' && *(p+1)=='\n') {
251
+			p += 2;
252
+		} else {
253
+			/* no valid EOH */
254
+			goto error;
255
+		}
256
+		if(p<end) {
257
+			/* multi line header body */
258
+			if(*p==' ' || *p=='\t') {
259
+				p++;
260
+				if (p==end)
261
+					goto error;
262
+			} else {
263
+				break;
264
+			}
265
+		}
266
+	} while(p<end);
247 267
 
248 268
 	*length = number;
249 269
 	return p;
250 270
 error:
251
-	LM_ERR("parse error near char [%d][%c]\n", *p, *p);
271
+	if(p<end) {
272
+		LM_ERR("parse error near char [%d][%c]\n", *p, *p);
273
+	} else {
274
+		LM_ERR("parse error over the end of input: %p - %p\n", buffer, end);
275
+	}
252 276
 	return 0;
253 277
 }
254 278