Merged revisions 321155 via svnmerge from
[asterisk/asterisk.git] / channels / sip / reqresp_parser.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2010, Digium, Inc.
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*!
18  * \file
19  * \brief sip request parsing functions and unit tests
20  */
21
22 #include "asterisk.h"
23
24 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
25
26 #include "include/sip.h"
27 #include "include/sip_utils.h"
28 #include "include/reqresp_parser.h"
29
30 #ifdef HAVE_XLOCALE_H
31 locale_t c_locale;
32 #endif
33
34 /*! \brief * parses a URI in its components.*/
35 int parse_uri_full(char *uri, const char *scheme, char **user, char **pass,
36                    char **domain, struct uriparams *params, char **headers,
37                    char **residue)
38 {
39         char *userinfo = NULL;
40         char *parameters = NULL;
41         char *endparams = NULL;
42         char *c = NULL;
43         int error = 0;
44
45         /* check for valid input */
46         if (ast_strlen_zero(uri)) {
47                 /* make sure we leave nothing undefined after we exit */
48                 if (user) {
49                         *user = "";
50                 }
51                 if (pass) {
52                         *pass = "";
53                 }
54                 if (domain) {
55                         *domain = "";
56                 }
57                 if (headers) {
58                         *headers = "";
59                 }
60                 if (residue) {
61                         *residue = "";
62                 }
63
64                 return -1;
65         }
66
67         if (scheme) {
68                 int l;
69                 char *scheme2 = ast_strdupa(scheme);
70                 char *cur = strsep(&scheme2, ",");
71                 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
72                         l = strlen(cur);
73                         if (!strncasecmp(uri, cur, l)) {
74                                 uri += l;
75                                 break;
76                         }
77                 }
78                 if (ast_strlen_zero(cur)) {
79                         ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
80                         error = -1;
81                 }
82         }
83
84         if (!domain) {
85                 /* if we don't want to split around domain, keep everything as a
86                  * userinfo - cos thats how old parse_uri operated*/
87                 userinfo = uri;
88         } else {
89                 char *dom = "";
90                 if ((c = strchr(uri, '@'))) {
91                         *c++ = '\0';
92                         dom = c;
93                         userinfo = uri;
94                         uri = c; /* userinfo can contain ? and ; chars so step forward before looking for params and headers */
95                 } else {
96                         /* domain-only URI, according to the SIP RFC. */
97                         dom = uri;
98                         userinfo = "";
99                 }
100
101                 *domain = dom;
102         }
103
104         if (pass && (c = strchr(userinfo, ':'))) {        /* user:password */
105                 *c++ = '\0';
106                 *pass = c;
107         } else if (pass) {
108                 *pass = "";
109         }
110
111         if (user) {
112                 *user = userinfo;
113         }
114
115         parameters = uri;
116         /* strip [?headers] from end of uri  - even if no header pointer exists*/
117         if ((c = strrchr(uri, '?'))) {
118                 *c++ = '\0';
119                 uri = c;
120                 if (headers) {
121                         *headers = c;
122                 }
123                 if ((c = strrchr(uri, ';'))) {
124                         *c++ = '\0';
125                 } else {
126                         c = strrchr(uri, '\0');
127                 }
128                 uri = c; /* residue */
129
130
131         } else if (headers) {
132                 *headers = "";
133         }
134
135         /* parse parameters */
136         endparams = strchr(parameters,'\0');
137         if ((c = strchr(parameters, ';'))) {
138                 *c++ = '\0';
139                 parameters = c;
140         } else {
141                 parameters = endparams;
142         }
143
144         if (params) {
145                 char *rem = parameters; /* unparsed or unrecognised remainder */
146                 char *label;
147                 char *value;
148                 int lr = 0;
149
150                 params->transport = "";
151                 params->user = "";
152                 params->method = "";
153                 params->ttl = "";
154                 params->maddr = "";
155                 params->lr = 0;
156
157                 rem = parameters;
158
159                 while ((value = strchr(parameters, '=')) || (lr = !strncmp(parameters, "lr", 2))) {
160                         /* The while condition will not continue evaluation to set lr if it matches "lr=" */
161                         if (lr) {
162                                 value = parameters;
163                         } else {
164                                 *value++ = '\0';
165                         }
166                         label = parameters;
167                         if ((c = strchr(value, ';'))) {
168                                 *c++ = '\0';
169                                 parameters = c;
170                         } else {
171                                 parameters = endparams;
172                         }
173
174                         if (!strcmp(label, "transport")) {
175                                 if (params) {params->transport=value;}
176                                 rem = parameters;
177                         } else if (!strcmp(label, "user")) {
178                                 if (params) {params->user=value;}
179                                 rem = parameters;
180                         } else if (!strcmp(label, "method")) {
181                                 if (params) {params->method=value;}
182                                 rem = parameters;
183                         } else if (!strcmp(label, "ttl")) {
184                                 if (params) {params->ttl=value;}
185                                 rem = parameters;
186                         } else if (!strcmp(label, "maddr")) {
187                                 if (params) {params->maddr=value;}
188                                 rem = parameters;
189                         /* Treat "lr", "lr=yes", "lr=on", "lr=1", "lr=almostanything" as lr enabled and "", "lr=no", "lr=off", "lr=0", "lr=" and "lranything" as lr disabled */
190                         } else if ((!strcmp(label, "lr") && strcmp(value, "no") && strcmp(value, "off") && strcmp(value, "0") && strcmp(value, "")) || ((lr) && strcmp(value, "lr"))) {
191                                 if (params) {params->lr=1;}
192                                 rem = parameters;
193                         } else {
194                                 value--;
195                                 *value = '=';
196                                 if (c) {
197                                         c--;
198                                         *c = ';';
199                                 }
200                         }
201                 }
202                 if (rem > uri) { /* no headers */
203                         uri = rem;
204                 }
205
206         }
207
208         if (residue) {
209                 *residue = uri;
210         }
211
212         return error;
213 }
214
215
216 AST_TEST_DEFINE(sip_parse_uri_fully_test)
217 {
218         int res = AST_TEST_PASS;
219         char uri[1024];
220         char *user, *pass, *domain, *headers, *residue;
221         struct uriparams params;
222
223         struct testdata {
224                 char *desc;
225                 char *uri;
226                 char **userptr;
227                 char **passptr;
228                 char **domainptr;
229                 char **headersptr;
230                 char **residueptr;
231                 struct uriparams *paramsptr;
232                 char *user;
233                 char *pass;
234                 char *domain;
235                 char *headers;
236                 char *residue;
237                 struct uriparams params;
238                 AST_LIST_ENTRY(testdata) list;
239         };
240
241
242         struct testdata *testdataptr;
243
244         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
245
246         struct testdata td1 = {
247                 .desc = "no headers",
248                 .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;param2=residue",
249                 .userptr = &user,
250                 .passptr = &pass,
251                 .domainptr = &domain,
252                 .headersptr = &headers,
253                 .residueptr = &residue,
254                 .paramsptr = &params,
255                 .user = "user",
256                 .pass = "secret",
257                 .domain = "host:5060",
258                 .headers = "",
259                 .residue = "param2=residue",
260                 .params.transport = "tcp",
261                 .params.lr = 0,
262                 .params.user = ""
263         };
264
265         struct testdata td2 = {
266                 .desc = "with headers",
267                 .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;param2=discard2?header=blah&header2=blah2;param3=residue",
268                 .userptr = &user,
269                 .passptr = &pass,
270                 .domainptr = &domain,
271                 .headersptr = &headers,
272                 .residueptr = &residue,
273                 .paramsptr = &params,
274                 .user = "user",
275                 .pass = "secret",
276                 .domain = "host:5060",
277                 .headers = "header=blah&header2=blah2",
278                 .residue = "param3=residue",
279                 .params.transport = "tcp",
280                 .params.lr = 0,
281                 .params.user = ""
282         };
283
284         struct testdata td3 = {
285                 .desc = "difficult user",
286                 .uri = "sip:-_.!~*'()&=+$,;?/:secret@host:5060;transport=tcp",
287                 .userptr = &user,
288                 .passptr = &pass,
289                 .domainptr = &domain,
290                 .headersptr = &headers,
291                 .residueptr = &residue,
292                 .paramsptr = &params,
293                 .user = "-_.!~*'()&=+$,;?/",
294                 .pass = "secret",
295                 .domain = "host:5060",
296                 .headers = "",
297                 .residue = "",
298                 .params.transport = "tcp",
299                 .params.lr = 0,
300                 .params.user = ""
301         };
302
303         struct testdata td4 = {
304                 .desc = "difficult pass",
305                 .uri = "sip:user:-_.!~*'()&=+$,@host:5060;transport=tcp",
306                 .userptr = &user,
307                 .passptr = &pass,
308                 .domainptr = &domain,
309                 .headersptr = &headers,
310                 .residueptr = &residue,
311                 .paramsptr = &params,
312                 .user = "user",
313                 .pass = "-_.!~*'()&=+$,",
314                 .domain = "host:5060",
315                 .headers = "",
316                 .residue = "",
317                 .params.transport = "tcp",
318                 .params.lr = 0,
319                 .params.user = ""
320         };
321
322         struct testdata td5 = {
323                 .desc = "difficult host",
324                 .uri = "sip:user:secret@1-1.a-1.:5060;transport=tcp",
325                 .userptr = &user,
326                 .passptr = &pass,
327                 .domainptr = &domain,
328                 .headersptr = &headers,
329                 .residueptr = &residue,
330                 .paramsptr = &params,
331                 .user = "user",
332                 .pass = "secret",
333                 .domain = "1-1.a-1.:5060",
334                 .headers = "",
335                 .residue = "",
336                 .params.transport = "tcp",
337                 .params.lr = 0,
338                 .params.user = ""
339         };
340
341         struct testdata td6 = {
342                 .desc = "difficult params near transport",
343                 .uri = "sip:user:secret@host:5060;-_.!~*'()[]/:&+$=-_.!~*'()[]/:&+$;transport=tcp",
344                 .userptr = &user,
345                 .passptr = &pass,
346                 .domainptr = &domain,
347                 .headersptr = &headers,
348                 .residueptr = &residue,
349                 .paramsptr = &params,
350                 .user = "user",
351                 .pass = "secret",
352                 .domain = "host:5060",
353                 .headers = "",
354                 .residue = "",
355                 .params.transport = "tcp",
356                 .params.lr = 0,
357                 .params.user = ""
358         };
359
360         struct testdata td7 = {
361                 .desc = "difficult params near headers",
362                 .uri = "sip:user:secret@host:5060;-_.!~*'()[]/:&+$=-_.!~*'()[]/:&+$?header=blah&header2=blah2;-_.!~*'()[]/:&+$=residue",
363                 .userptr = &user,
364                 .passptr = &pass,
365                 .domainptr = &domain,
366                 .headersptr = &headers,
367                 .residueptr = &residue,
368                 .paramsptr = &params,
369                 .user = "user",
370                 .pass = "secret",
371                 .domain = "host:5060",
372                 .headers = "header=blah&header2=blah2",
373                 .residue = "-_.!~*'()[]/:&+$=residue",
374                 .params.transport = "",
375                 .params.lr = 0,
376                 .params.user = ""
377         };
378
379         struct testdata td8 = {
380                 .desc = "lr parameter",
381                 .uri = "sip:user:secret@host:5060;param=discard;lr?header=blah",
382                 .userptr = &user,
383                 .passptr = &pass,
384                 .domainptr = &domain,
385                 .headersptr = &headers,
386                 .residueptr = &residue,
387                 .paramsptr = &params,
388                 .user = "user",
389                 .pass = "secret",
390                 .domain = "host:5060",
391                 .headers = "header=blah",
392                 .residue = "",
393                 .params.transport = "",
394                 .params.lr = 1,
395                 .params.user = ""
396         };
397
398         struct testdata td9 = {
399                 .desc = "alternative lr parameter",
400                 .uri = "sip:user:secret@host:5060;param=discard;lr=yes?header=blah",
401                 .userptr = &user,
402                 .passptr = &pass,
403                 .domainptr = &domain,
404                 .headersptr = &headers,
405                 .residueptr = &residue,
406                 .paramsptr = &params,
407                 .user = "user",
408                 .pass = "secret",
409                 .domain = "host:5060",
410                 .headers = "header=blah",
411                 .residue = "",
412                 .params.transport = "",
413                 .params.lr = 1,
414                 .params.user = ""
415         };
416
417         struct testdata td10 = {
418                 .desc = "no lr parameter",
419                 .uri = "sip:user:secret@host:5060;paramlr=lr;lr=no;lr=off;lr=0;lr=;=lr;lrextra;lrparam2=lr?header=blah",
420                 .userptr = &user,
421                 .passptr = &pass,
422                 .domainptr = &domain,
423                 .headersptr = &headers,
424                 .residueptr = &residue,
425                 .paramsptr = &params,
426                 .user = "user",
427                 .pass = "secret",
428                 .domain = "host:5060",
429                 .headers = "header=blah",
430                 .residue = "",
431                 .params.transport = "",
432                 .params.lr = 0,
433                 .params.user = ""
434         };
435
436
437         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
438         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
439         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
440         AST_LIST_INSERT_TAIL(&testdatalist, &td4, list);
441         AST_LIST_INSERT_TAIL(&testdatalist, &td5, list);
442         AST_LIST_INSERT_TAIL(&testdatalist, &td6, list);
443         AST_LIST_INSERT_TAIL(&testdatalist, &td7, list);
444         AST_LIST_INSERT_TAIL(&testdatalist, &td8, list);
445         AST_LIST_INSERT_TAIL(&testdatalist, &td9, list);
446         AST_LIST_INSERT_TAIL(&testdatalist, &td10, list);
447
448
449         switch (cmd) {
450         case TEST_INIT:
451                 info->name = "sip_uri_full_parse_test";
452                 info->category = "/channels/chan_sip/";
453                 info->summary = "tests sip full uri parsing";
454                 info->description =
455                         "Tests full parsing of various URIs "
456                         "Verifies output matches expected behavior.";
457                 return AST_TEST_NOT_RUN;
458         case TEST_EXECUTE:
459                 break;
460         }
461
462         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
463                 user = pass = domain = headers = residue = NULL;
464                 params.transport = params.user = params.method = params.ttl = params.maddr = NULL;
465                 params.lr = 0;
466
467                 ast_copy_string(uri,testdataptr->uri,sizeof(uri));
468                 if (parse_uri_full(uri, "sip:,sips:", testdataptr->userptr,
469                                    testdataptr->passptr, testdataptr->domainptr,
470                                    testdataptr->paramsptr,
471                                    testdataptr->headersptr,
472                                    testdataptr->residueptr) ||
473                         ((testdataptr->userptr) && strcmp(testdataptr->user, user)) ||
474                         ((testdataptr->passptr) && strcmp(testdataptr->pass, pass)) ||
475                         ((testdataptr->domainptr) && strcmp(testdataptr->domain, domain)) ||
476                         ((testdataptr->headersptr) && strcmp(testdataptr->headers, headers)) ||
477                         ((testdataptr->residueptr) && strcmp(testdataptr->residue, residue)) ||
478                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.transport,params.transport)) ||
479                         ((testdataptr->paramsptr) && (testdataptr->params.lr != params.lr)) ||
480                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.user,params.user))
481                 ) {
482                                 ast_test_status_update(test, "Sub-Test: %s, failed.\n", testdataptr->desc);
483                                 res = AST_TEST_FAIL;
484                 }
485         }
486
487
488         return res;
489 }
490
491
492 int parse_uri(char *uri, const char *scheme, char **user, char **pass,
493               char **domain, char **transport) {
494         int ret;
495         char *headers;
496         struct uriparams params;
497
498         headers = NULL;
499         ret = parse_uri_full(uri, scheme, user, pass, domain, &params, &headers, NULL);
500         if (transport) {
501                 *transport=params.transport;
502         }
503         return ret;
504 }
505
506 AST_TEST_DEFINE(sip_parse_uri_test)
507 {
508         int res = AST_TEST_PASS;
509         char *name, *pass, *domain, *transport;
510         char uri1[] = "sip:name@host";
511         char uri2[] = "sip:name@host;transport=tcp";
512         char uri3[] = "sip:name:secret@host;transport=tcp";
513         char uri4[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
514         /* test 5 is for NULL input */
515         char uri6[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
516         char uri7[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
517         char uri8[] = "sip:host";
518         char uri9[] = "sip:host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
519         char uri10[] = "host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
520         char uri11[] = "host";
521
522         switch (cmd) {
523         case TEST_INIT:
524                 info->name = "sip_uri_parse_test";
525                 info->category = "/channels/chan_sip/";
526                 info->summary = "tests sip uri parsing";
527                 info->description =
528                                                         "Tests parsing of various URIs "
529                                                         "Verifies output matches expected behavior.";
530                 return AST_TEST_NOT_RUN;
531         case TEST_EXECUTE:
532                 break;
533         }
534
535         /* Test 1, simple URI */
536         name = pass = domain = transport = NULL;
537         if (parse_uri(uri1, "sip:,sips:", &name, &pass, &domain, &transport) ||
538                         strcmp(name, "name")        ||
539                         !ast_strlen_zero(pass)      ||
540                         strcmp(domain, "host")      ||
541                         !ast_strlen_zero(transport)) {
542                 ast_test_status_update(test, "Test 1: simple uri failed. \n");
543                 res = AST_TEST_FAIL;
544         }
545
546         /* Test 2, add tcp transport */
547         name = pass = domain = transport = NULL;
548         if (parse_uri(uri2, "sip:,sips:", &name, &pass, &domain, &transport) ||
549                         strcmp(name, "name")        ||
550                         !ast_strlen_zero(pass)      ||
551                         strcmp(domain, "host")    ||
552                         strcmp(transport, "tcp")) {
553                 ast_test_status_update(test, "Test 2: uri with addtion of tcp transport failed. \n");
554                 res = AST_TEST_FAIL;
555         }
556
557         /* Test 3, add secret */
558         name = pass = domain = transport = NULL;
559         if (parse_uri(uri3, "sip:,sips:", &name, &pass, &domain, &transport) ||
560                         strcmp(name, "name")        ||
561                         strcmp(pass, "secret")      ||
562                         strcmp(domain, "host")    ||
563                         strcmp(transport, "tcp")) {
564                 ast_test_status_update(test, "Test 3: uri with addition of secret failed.\n");
565                 res = AST_TEST_FAIL;
566         }
567
568         /* Test 4, add port and unparsed header field*/
569         name = pass = domain = transport = NULL;
570         if (parse_uri(uri4, "sip:,sips:", &name, &pass, &domain, &transport) ||
571                         strcmp(name, "name")        ||
572                         strcmp(pass, "secret")      ||
573                         strcmp(domain, "host:port") ||
574                         strcmp(transport, "tcp")) {
575                 ast_test_status_update(test, "Test 4: add port and unparsed header field failed.\n");
576                 res = AST_TEST_FAIL;
577         }
578
579         /* Test 5, verify parse_uri does not crash when given a NULL uri */
580         name = pass = domain = transport = NULL;
581         if (!parse_uri(NULL, "sip:,sips:", &name, &pass, &domain, &transport)) {
582                 ast_test_status_update(test, "Test 5: passing a NULL uri failed.\n");
583                 res = AST_TEST_FAIL;
584         }
585
586         /* Test 6, verify parse_uri does not crash when given a NULL output parameters */
587         name = pass = domain = transport = NULL;
588         if (parse_uri(uri6, "sip:,sips:", NULL, NULL, NULL, NULL)) {
589                 ast_test_status_update(test, "Test 6: passing NULL output parameters failed.\n");
590                 res = AST_TEST_FAIL;
591         }
592
593         /* Test 7, verify parse_uri returns user:secret and domain when no port or secret output parameters are supplied. */
594         name = pass = domain = transport = NULL;
595         if (parse_uri(uri7, "sip:,sips:", &name, NULL, &domain, NULL) ||
596                         strcmp(name, "name:secret")        ||
597                         strcmp(domain, "host:port")) {
598
599                 ast_test_status_update(test, "Test 7: providing no port and secret output parameters failed.\n");
600                 res = AST_TEST_FAIL;
601         }
602
603         /* Test 8, verify parse_uri can handle a domain only uri */
604         name = pass = domain = transport = NULL;
605         if (parse_uri(uri8, "sip:,sips:", &name, &pass, &domain, &transport) ||
606                         strcmp(domain, "host") ||
607                         !ast_strlen_zero(name)) {
608                 ast_test_status_update(test, "Test 8: add port and unparsed header field failed.\n");
609                 res = AST_TEST_FAIL;
610         }
611
612         /* Test 9, add port and unparsed header field with domain only uri*/
613         name = pass = domain = transport = NULL;
614         if (parse_uri(uri9, "sip:,sips:", &name, &pass, &domain, &transport) ||
615                         !ast_strlen_zero(name)        ||
616                         !ast_strlen_zero(pass)      ||
617                         strcmp(domain, "host:port")    ||
618                         strcmp(transport, "tcp")) {
619                 ast_test_status_update(test, "Test 9: domain only uri failed \n");
620                 res = AST_TEST_FAIL;
621         }
622
623         /* Test 10, handle invalid/missing "sip:,sips:" scheme
624          * we expect parse_uri to return an error, but still parse
625          * the results correctly here */
626         name = pass = domain = transport = NULL;
627         if (!parse_uri(uri10, "sip:,sips:", &name, &pass, &domain, &transport) ||
628                         !ast_strlen_zero(name)        ||
629                         !ast_strlen_zero(pass)      ||
630                         strcmp(domain, "host:port")    ||
631                         strcmp(transport, "tcp")) {
632                 ast_test_status_update(test, "Test 10: missing \"sip:sips:\" scheme failed\n");
633                 res = AST_TEST_FAIL;
634         }
635
636         /* Test 11, simple domain only URI with missing scheme
637          * we expect parse_uri to return an error, but still parse
638          * the results correctly here */
639         name = pass = domain = transport = NULL;
640         if (!parse_uri(uri11, "sip:,sips:", &name, &pass, &domain, &transport) ||
641                         !ast_strlen_zero(name)      ||
642                         !ast_strlen_zero(pass)      ||
643                         strcmp(domain, "host")      ||
644                         !ast_strlen_zero(transport)) {
645                 ast_test_status_update(test, "Test 11: simple uri with missing scheme failed. \n");
646                 res = AST_TEST_FAIL;
647         }
648
649         return res;
650 }
651
652 /*! \brief  Get caller id name from SIP headers, copy into output buffer
653  *
654  *  \retval input string pointer placed after display-name field if possible
655  */
656 const char *get_calleridname(const char *input, char *output, size_t outputsize)
657 {
658         /* From RFC3261:
659          *
660          * From           =  ( "From" / "f" ) HCOLON from-spec
661          * from-spec      =  ( name-addr / addr-spec ) *( SEMI from-param )
662          * name-addr      =  [ display-name ] LAQUOT addr-spec RAQUOT
663          * display-name   =  *(token LWS)/ quoted-string
664          * token          =  1*(alphanum / "-" / "." / "!" / "%" / "*"
665          *                     / "_" / "+" / "`" / "'" / "~" )
666          * quoted-string  =  SWS DQUOTE *(qdtext / quoted-pair ) DQUOTE
667          * qdtext         =  LWS / %x21 / %x23-5B / %x5D-7E
668          *                     / UTF8-NONASCII
669          * quoted-pair    =  "\" (%x00-09 / %x0B-0C / %x0E-7F)
670          *
671          * HCOLON         = *WSP ":" SWS
672          * SWS            = [LWS]
673          * LWS            = *[*WSP CRLF] 1*WSP
674          * WSP            = (SP / HTAB)
675          *
676          * Deviations from it:
677          * - following CRLF's in LWS is not done (here at least)
678          * - ascii NUL is never legal as it terminates the C-string
679          * - utf8-nonascii is not checked for validity
680          */
681         char *orig_output = output;
682         const char *orig_input = input;
683
684         /* clear any empty characters in the beginning */
685         input = ast_skip_blanks(input);
686
687         /* no data at all or no storage room? */
688         if (!input || *input == '<' || !outputsize || !output) {
689                 return orig_input;
690         }
691
692         /* make sure the output buffer is initilized */
693         *orig_output = '\0';
694
695         /* make room for '\0' at the end of the output buffer */
696         outputsize--;
697
698         /* quoted-string rules */
699         if (input[0] == '"') {
700                 input++; /* skip the first " */
701
702                 for (;((outputsize > 0) && *input); input++) {
703                         if (*input == '"') {  /* end of quoted-string */
704                                 break;
705                         } else if (*input == 0x5c) { /* quoted-pair = "\" (%x00-09 / %x0B-0C / %x0E-7F) */
706                                 input++;
707                                 if (!*input || (unsigned char)*input > 0x7f || *input == 0xa || *input == 0xd) {
708                                         continue;  /* not a valid quoted-pair, so skip it */
709                                 }
710                         } else if (((*input != 0x9) && ((unsigned char) *input < 0x20)) ||
711                                     (*input == 0x7f)) {
712                                 continue; /* skip this invalid character. */
713                         }
714
715                         *output++ = *input;
716                         outputsize--;
717                 }
718
719                 /* if this is successful, input should be at the ending quote */
720                 if (!input || *input != '"') {
721                         ast_log(LOG_WARNING, "No ending quote for display-name was found\n");
722                         *orig_output = '\0';
723                         return orig_input;
724                 }
725
726                 /* make sure input is past the last quote */
727                 input++;
728
729                 /* terminate outbuf */
730                 *output = '\0';
731         } else {  /* either an addr-spec or tokenLWS-combo */
732                 for (;((outputsize > 0) && *input); input++) {
733                         /* token or WSP (without LWS) */
734                         if ((*input >= '0' && *input <= '9') || (*input >= 'A' && *input <= 'Z')
735                                 || (*input >= 'a' && *input <= 'z') || *input == '-' || *input == '.'
736                                 || *input == '!' || *input == '%' || *input == '*' || *input == '_'
737                                 || *input == '+' || *input == '`' || *input == '\'' || *input == '~'
738                                 || *input == 0x9 || *input == ' ') {
739                                 *output++ = *input;
740                                 outputsize -= 1;
741                         } else if (*input == '<') {   /* end of tokenLWS-combo */
742                                 /* we could assert that the previous char is LWS, but we don't care */
743                                 break;
744                         } else if (*input == ':') {
745                                 /* This invalid character which indicates this is addr-spec rather than display-name. */
746                                 *orig_output = '\0';
747                                 return orig_input;
748                         } else {         /* else, invalid character we can skip. */
749                                 continue;    /* skip this character */
750                         }
751                 }
752
753                 if (*input != '<') {   /* if we never found the start of addr-spec then this is invalid */
754                         *orig_output = '\0';
755                         return orig_input;
756                 }
757
758                 /* set NULL while trimming trailing whitespace */
759                 do {
760                         *output-- = '\0';
761                 } while (*output == 0x9 || *output == ' '); /* we won't go past orig_output as first was a non-space */
762         }
763
764         return input;
765 }
766
767 AST_TEST_DEFINE(get_calleridname_test)
768 {
769         int res = AST_TEST_PASS;
770         const char *in1 = "\" quoted-text internal \\\" quote \"<stuff>";
771         const char *in2 = " token text with no quotes <stuff>";
772         const char *overflow1 = " \"quoted-text overflow 1234567890123456789012345678901234567890\" <stuff>";
773         const char *noendquote = " \"quoted-text no end <stuff>";
774         const char *addrspec = " \"sip:blah@blah <stuff>";
775         const char *no_quotes_no_brackets = "blah@blah";
776         const char *after_dname;
777         char dname[40];
778
779         switch (cmd) {
780         case TEST_INIT:
781                 info->name = "sip_get_calleridname_test";
782                 info->category = "/channels/chan_sip/";
783                 info->summary = "decodes callerid name from sip header";
784                 info->description = "Decodes display-name field of sip header.  Checks for valid output and expected failure cases.";
785                 return AST_TEST_NOT_RUN;
786         case TEST_EXECUTE:
787                 break;
788         }
789
790         /* quoted-text with backslash escaped quote */
791         after_dname = get_calleridname(in1, dname, sizeof(dname));
792         ast_test_status_update(test, "display-name1: %s\nafter: %s\n", dname, after_dname);
793         if (strcmp(dname, " quoted-text internal \" quote ")) {
794                 ast_test_status_update(test, "display-name1 test failed\n");
795                 res = AST_TEST_FAIL;
796         }
797
798         /* token text */
799         after_dname = get_calleridname(in2, dname, sizeof(dname));
800         ast_test_status_update(test, "display-name2: %s\nafter: %s\n", dname, after_dname);
801         if (strcmp(dname, "token text with no quotes")) {
802                 ast_test_status_update(test, "display-name2 test failed\n");
803                 res = AST_TEST_FAIL;
804         }
805
806         /* quoted-text buffer overflow */
807         after_dname = get_calleridname(overflow1, dname, sizeof(dname));
808         ast_test_status_update(test, "overflow display-name1: %s\nafter: %s\n", dname, after_dname);
809         if (*dname != '\0' && after_dname != overflow1) {
810                 ast_test_status_update(test, "overflow display-name1 test failed\n");
811                 res = AST_TEST_FAIL;
812         }
813
814         /* quoted-text buffer with no terminating end quote */
815         after_dname = get_calleridname(noendquote, dname, sizeof(dname));
816         ast_test_status_update(test, "noendquote display-name1: %s\nafter: %s\n", dname, after_dname);
817         if (*dname != '\0' && after_dname != noendquote) {
818                 ast_test_status_update(test, "no end quote for quoted-text display-name failed\n");
819                 res = AST_TEST_FAIL;
820         }
821
822         /* addr-spec rather than display-name. */
823         after_dname = get_calleridname(addrspec, dname, sizeof(dname));
824         ast_test_status_update(test, "noendquote display-name1: %s\nafter: %s\n", dname, after_dname);
825         if (*dname != '\0' && after_dname != addrspec) {
826                 ast_test_status_update(test, "detection of addr-spec failed\n");
827                 res = AST_TEST_FAIL;
828         }
829
830         /* no quotes, no brackets */
831         after_dname = get_calleridname(no_quotes_no_brackets, dname, sizeof(dname));
832         ast_test_status_update(test, "no_quotes_no_brackets display-name1: %s\nafter: %s\n", dname, after_dname);
833         if (*dname != '\0' && after_dname != no_quotes_no_brackets) {
834                 ast_test_status_update(test, "detection of addr-spec failed\n");
835                 res = AST_TEST_FAIL;
836         }
837
838
839         return res;
840 }
841
842 int get_name_and_number(const char *hdr, char **name, char **number)
843 {
844         char header[256];
845         char tmp_name[50] = { 0, };
846         char *tmp_number = NULL;
847         char *domain = NULL;
848         char *dummy = NULL;
849
850         if (!name || !number || ast_strlen_zero(hdr)) {
851                 return -1;
852         }
853
854         *number = NULL;
855         *name = NULL;
856         ast_copy_string(header, hdr, sizeof(header));
857
858         /* strip the display-name portion off the beginning of the header. */
859         get_calleridname(header, tmp_name, sizeof(tmp_name));
860
861         /* get uri within < > brackets */
862         tmp_number = get_in_brackets(header);
863
864         /* parse out the number here */
865         if (parse_uri(tmp_number, "sip:,sips:", &tmp_number, &dummy, &domain, NULL) || ast_strlen_zero(tmp_number)) {
866                 ast_log(LOG_ERROR, "can not parse name and number from sip header.\n");
867                 return -1;
868         }
869
870         /* number is not option, and must be present at this point */
871         *number = ast_strdup(tmp_number);
872         ast_uri_decode(*number, ast_uri_sip_user);
873
874         /* name is optional and may not be present at this point */
875         if (!ast_strlen_zero(tmp_name)) {
876                 *name = ast_strdup(tmp_name);
877         }
878
879         return 0;
880 }
881
882 AST_TEST_DEFINE(get_name_and_number_test)
883 {
884         int res = AST_TEST_PASS;
885         char *name = NULL;
886         char *number = NULL;
887         const char *in1 = "NAME <sip:NUMBER@place>";
888         const char *in2 = "\"NA><ME\" <sip:NUMBER@place>";
889         const char *in3 = "NAME";
890         const char *in4 = "<sip:NUMBER@place>";
891         const char *in5 = "This is a screwed up string <sip:LOLCLOWNS<sip:>@place>";
892
893         switch (cmd) {
894         case TEST_INIT:
895                 info->name = "sip_get_name_and_number_test";
896                 info->category = "/channels/chan_sip/";
897                 info->summary = "Tests getting name and number from sip header";
898                 info->description =
899                                 "Runs through various test situations in which a name and "
900                                 "and number can be retrieved from a sip header.";
901                 return AST_TEST_NOT_RUN;
902         case TEST_EXECUTE:
903                 break;
904         }
905
906         /* Test 1. get name and number */
907         number = name = NULL;
908         if ((get_name_and_number(in1, &name, &number)) ||
909                 strcmp(name, "NAME") ||
910                 strcmp(number, "NUMBER")) {
911
912                 ast_test_status_update(test, "Test 1, simple get name and number failed.\n");
913                 res = AST_TEST_FAIL;
914         }
915         ast_free(name);
916         ast_free(number);
917
918         /* Test 2. get quoted name and number */
919         number = name = NULL;
920         if ((get_name_and_number(in2, &name, &number)) ||
921                 strcmp(name, "NA><ME") ||
922                 strcmp(number, "NUMBER")) {
923
924                 ast_test_status_update(test, "Test 2, get quoted name and number failed.\n");
925                 res = AST_TEST_FAIL;
926         }
927         ast_free(name);
928         ast_free(number);
929
930         /* Test 3. name only */
931         number = name = NULL;
932         if (!(get_name_and_number(in3, &name, &number))) {
933
934                 ast_test_status_update(test, "Test 3, get name only was expected to fail but did not.\n");
935                 res = AST_TEST_FAIL;
936         }
937         ast_free(name);
938         ast_free(number);
939
940         /* Test 4. number only */
941         number = name = NULL;
942         if ((get_name_and_number(in4, &name, &number)) ||
943                 !ast_strlen_zero(name) ||
944                 strcmp(number, "NUMBER")) {
945
946                 ast_test_status_update(test, "Test 4, get number with no name present failed.\n");
947                 res = AST_TEST_FAIL;
948         }
949         ast_free(name);
950         ast_free(number);
951
952         /* Test 5. malformed string, since number can not be parsed, this should return an error.  */
953         number = name = NULL;
954         if (!(get_name_and_number(in5, &name, &number)) ||
955                 !ast_strlen_zero(name) ||
956                 !ast_strlen_zero(number)) {
957
958                 ast_test_status_update(test, "Test 5, processing malformed string failed.\n");
959                 res = AST_TEST_FAIL;
960         }
961         ast_free(name);
962         ast_free(number);
963
964         /* Test 6. NULL output parameters */
965         number = name = NULL;
966         if (!(get_name_and_number(in5, NULL, NULL))) {
967
968                 ast_test_status_update(test, "Test 6, NULL output parameters failed.\n");
969                 res = AST_TEST_FAIL;
970         }
971
972         /* Test 7. NULL input parameter */
973         number = name = NULL;
974         if (!(get_name_and_number(NULL, &name, &number)) ||
975                 !ast_strlen_zero(name) ||
976                 !ast_strlen_zero(number)) {
977
978                 ast_test_status_update(test, "Test 7, NULL input parameter failed.\n");
979                 res = AST_TEST_FAIL;
980         }
981         ast_free(name);
982         ast_free(number);
983
984         return res;
985 }
986
987 int get_in_brackets_full(char *tmp,char **out,char **residue)
988 {
989         const char *parse = tmp;
990         char *first_bracket;
991         char *second_bracket;
992
993         if (out) {
994                 *out = "";
995         }
996         if (residue) {
997                 *residue = "";
998         }
999
1000         if (ast_strlen_zero(tmp)) {
1001                 return 1;
1002         }
1003
1004         /*
1005          * Skip any quoted text until we find the part in brackets.
1006         * On any error give up and return -1
1007         */
1008         while ( (first_bracket = strchr(parse, '<')) ) {
1009                 char *first_quote = strchr(parse, '"');
1010                 first_bracket++;
1011                 if (!first_quote || first_quote >= first_bracket) {
1012                         break; /* no need to look at quoted part */
1013                 }
1014                 /* the bracket is within quotes, so ignore it */
1015                 parse = find_closing_quote(first_quote + 1, NULL);
1016                 if (!*parse) {
1017                         ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1018                         return  -1;
1019                 }
1020                 parse++;
1021         }
1022
1023         /* If no first bracket then still look for a second bracket as some other parsing functions
1024         may overwrite first bracket with NULL when terminating a token based display-name. As this
1025         only affects token based display-names there is no danger of brackets being in quotes */
1026         if (first_bracket) {
1027                 parse = first_bracket;
1028                 } else {
1029                 parse = tmp;
1030         }
1031
1032         if ((second_bracket = strchr(parse, '>'))) {
1033                 *second_bracket++ = '\0';
1034                 if (out) {
1035                         *out = first_bracket;
1036                 }
1037                 if (residue) {
1038                         *residue = second_bracket;
1039                 }
1040                 return 0;
1041         }
1042
1043         if ((first_bracket)) {
1044                         ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1045                 return -1;
1046                 }
1047
1048         if (out) {
1049                 *out = tmp;
1050         }
1051
1052         return 1;
1053 }
1054
1055 char *get_in_brackets(char *tmp)
1056 {
1057         char *out;
1058
1059         if ((get_in_brackets_full(tmp, &out, NULL))) {
1060                 return tmp;
1061         }
1062         return out;
1063 }
1064
1065 AST_TEST_DEFINE(get_in_brackets_test)
1066 {
1067         int res = AST_TEST_PASS;
1068         char *in_brackets = "<sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1069         char no_name[] = "<sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1070         char quoted_string[] = "\"I'm a quote stri><ng\" <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1071         char missing_end_quote[] = "\"I'm a quote string <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1072         char name_no_quotes[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1073         char no_end_bracket[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah";
1074         char no_name_no_brackets[] = "sip:name@host";
1075         char *uri = NULL;
1076
1077         switch (cmd) {
1078         case TEST_INIT:
1079                 info->name = "sip_get_in_brackets_test";
1080                 info->category = "/channels/chan_sip/";
1081                 info->summary = "Tests getting a sip uri in <> brackets within a sip header.";
1082                 info->description =
1083                                 "Runs through various test situations in which a sip uri "
1084                                 "in angle brackets needs to be retrieved";
1085                 return AST_TEST_NOT_RUN;
1086         case TEST_EXECUTE:
1087                 break;
1088         }
1089
1090         /* Test 1, simple get in brackets */
1091         if (!(uri = get_in_brackets(no_name)) || !(strcmp(uri, in_brackets))) {
1092
1093                 ast_test_status_update(test, "Test 1, simple get in brackets failed.\n");
1094                 res = AST_TEST_FAIL;
1095         }
1096
1097         /* Test 2, starts with quoted string */
1098         if (!(uri = get_in_brackets(quoted_string)) || !(strcmp(uri, in_brackets))) {
1099
1100                 ast_test_status_update(test, "Test 2, get in brackets with quoted string in front failed.\n");
1101                 res = AST_TEST_FAIL;
1102         }
1103
1104         /* Test 3, missing end quote */
1105         if (!(uri = get_in_brackets(missing_end_quote)) || !(strcmp(uri, in_brackets))) {
1106
1107                 ast_test_status_update(test, "Test 3, missing end quote failed.\n");
1108                 res = AST_TEST_FAIL;
1109         }
1110
1111         /* Test 4, starts with a name not in quotes */
1112         if (!(uri = get_in_brackets(name_no_quotes)) || !(strcmp(uri, in_brackets))) {
1113
1114                 ast_test_status_update(test, "Test 4, passing name not in quotes failed.\n");
1115                 res = AST_TEST_FAIL;
1116         }
1117
1118         /* Test 5, no end bracket, should just return everything after the first '<'  */
1119         if (!(uri = get_in_brackets(no_end_bracket)) || !(strcmp(uri, in_brackets))) {
1120
1121                 ast_test_status_update(test, "Test 5, no end bracket failed.\n");
1122                 res = AST_TEST_FAIL;
1123         }
1124
1125         /* Test 6, NULL input  */
1126         if ((uri = get_in_brackets(NULL))) {
1127
1128                 ast_test_status_update(test, "Test 6, NULL input failed.\n");
1129                 res = AST_TEST_FAIL;
1130         }
1131
1132         /* Test 7, no name, and no brackets. */
1133         if (!(uri = get_in_brackets(no_name_no_brackets)) || (strcmp(uri, "sip:name@host"))) {
1134
1135                 ast_test_status_update(test, "Test 7 failed. %s\n", uri);
1136                 res = AST_TEST_FAIL;
1137         }
1138
1139         return res;
1140 }
1141
1142
1143 int parse_name_andor_addr(char *uri, const char *scheme, char **name,
1144                           char **user, char **pass, char **domain,
1145                           struct uriparams *params, char **headers,
1146                           char **residue)
1147 {
1148         char buf[1024];
1149         char **residue2=residue;
1150         int ret;
1151         if (name) {
1152                 get_calleridname(uri,buf,sizeof(buf));
1153                 *name = buf;
1154         }
1155         ret = get_in_brackets_full(uri,&uri,residue);
1156         if (ret == 0) { /* uri is in brackets so do not treat unknown trailing uri parameters as potential messageheader parameters */
1157                 *residue = *residue + 1; /* step over the first semicolon so as per parse uri residue */
1158                 residue2 = NULL;
1159         }
1160
1161         return parse_uri_full(uri, scheme, user, pass, domain, params, headers,
1162                               residue2);
1163 }
1164
1165 AST_TEST_DEFINE(parse_name_andor_addr_test)
1166 {
1167         int res = AST_TEST_PASS;
1168         char uri[1024];
1169         char *name, *user, *pass, *domain, *headers, *residue;
1170         struct uriparams params;
1171
1172         struct testdata {
1173                 char *desc;
1174                 char *uri;
1175                 char **nameptr;
1176                 char **userptr;
1177                 char **passptr;
1178                 char **domainptr;
1179                 char **headersptr;
1180                 char **residueptr;
1181                 struct uriparams *paramsptr;
1182                 char *name;
1183                 char *user;
1184                 char *pass;
1185                 char *domain;
1186                 char *headers;
1187                 char *residue;
1188                 struct uriparams params;
1189                 AST_LIST_ENTRY(testdata) list;
1190         };
1191
1192         struct testdata *testdataptr;
1193
1194         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1195
1196         struct testdata td1 = {
1197                 .desc = "quotes and brackets",
1198                 .uri = "\"name :@ \" <sip:user:secret@host:5060;param=discard;transport=tcp>;tag=tag",
1199                 .nameptr = &name,
1200                 .userptr = &user,
1201                 .passptr = &pass,
1202                 .domainptr = &domain,
1203                 .headersptr = &headers,
1204                 .residueptr = &residue,
1205                 .paramsptr = &params,
1206                 .name =  "name :@ ",
1207                 .user = "user",
1208                 .pass = "secret",
1209                 .domain = "host:5060",
1210                 .headers = "",
1211                 .residue = "tag=tag",
1212                 .params.transport = "tcp",
1213                 .params.lr = 0,
1214                 .params.user = ""
1215         };
1216
1217         struct testdata td2 = {
1218                 .desc = "no quotes",
1219                 .uri = "givenname familyname <sip:user:secret@host:5060;param=discard;transport=tcp>;expires=3600",
1220                 .nameptr = &name,
1221                 .userptr = &user,
1222                 .passptr = &pass,
1223                 .domainptr = &domain,
1224                 .headersptr = &headers,
1225                 .residueptr = &residue,
1226                 .paramsptr = &params,
1227                 .name = "givenname familyname",
1228                 .user = "user",
1229                 .pass = "secret",
1230                 .domain = "host:5060",
1231                 .headers = "",
1232                 .residue = "expires=3600",
1233                 .params.transport = "tcp",
1234                 .params.lr = 0,
1235                 .params.user = ""
1236         };
1237
1238         struct testdata td3 = {
1239                 .desc = "no brackets",
1240                 .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;q=1",
1241                 .nameptr = &name,
1242                 .userptr = &user,
1243                 .passptr = &pass,
1244                 .domainptr = &domain,
1245                 .headersptr = &headers,
1246                 .residueptr = &residue,
1247                 .paramsptr = &params,
1248                 .name = "",
1249                 .user = "user",
1250                 .pass = "secret",
1251                 .domain = "host:5060",
1252                 .headers = "",
1253                 .residue = "q=1",
1254                 .params.transport = "tcp",
1255                 .params.lr = 0,
1256                 .params.user = ""
1257         };
1258
1259         struct testdata td4 = {
1260                 .desc = "just host",
1261                 .uri = "sips:host",
1262                 .nameptr = &name,
1263                 .userptr = &user,
1264                 .passptr = &pass,
1265                 .domainptr = &domain,
1266                 .headersptr = &headers,
1267                 .residueptr = &residue,
1268                 .paramsptr = &params,
1269                 .name = "",
1270                 .user = "",
1271                 .pass = "",
1272                 .domain = "host",
1273                 .headers = "",
1274                 .residue = "",
1275                 .params.transport = "",
1276                 .params.lr = 0,
1277                 .params.user = ""
1278         };
1279
1280
1281         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
1282         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
1283         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
1284         AST_LIST_INSERT_TAIL(&testdatalist, &td4, list);
1285
1286
1287         switch (cmd) {
1288         case TEST_INIT:
1289                 info->name = "parse_name_andor_addr_test";
1290                 info->category = "/channels/chan_sip/";
1291                 info->summary = "tests parsing of name_andor_addr abnf structure";
1292                 info->description =
1293                         "Tests parsing of abnf name-andor-addr = name-addr / addr-spec "
1294                         "Verifies output matches expected behavior.";
1295                 return AST_TEST_NOT_RUN;
1296         case TEST_EXECUTE:
1297                 break;
1298         }
1299
1300         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1301                 name = user = pass = domain = headers = residue = NULL;
1302                 params.transport = params.user = params.method = params.ttl = params.maddr = NULL;
1303                 params.lr = 0;
1304         ast_copy_string(uri,testdataptr->uri,sizeof(uri));
1305                 if (parse_name_andor_addr(uri, "sip:,sips:",
1306                                           testdataptr->nameptr,
1307                                           testdataptr->userptr,
1308                                           testdataptr->passptr,
1309                                           testdataptr->domainptr,
1310                                           testdataptr->paramsptr,
1311                                           testdataptr->headersptr,
1312                                           testdataptr->residueptr) ||
1313                         ((testdataptr->nameptr) && strcmp(testdataptr->name, name)) ||
1314                         ((testdataptr->userptr) && strcmp(testdataptr->user, user)) ||
1315                         ((testdataptr->passptr) && strcmp(testdataptr->pass, pass)) ||
1316                         ((testdataptr->domainptr) && strcmp(testdataptr->domain, domain)) ||
1317                         ((testdataptr->headersptr) && strcmp(testdataptr->headers, headers)) ||
1318                         ((testdataptr->residueptr) && strcmp(testdataptr->residue, residue)) ||
1319                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.transport,params.transport)) ||
1320                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.user,params.user))
1321                 ) {
1322                                 ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1323                                 res = AST_TEST_FAIL;
1324                 }
1325         }
1326
1327
1328         return res;
1329 }
1330
1331 int get_comma(char *in, char **out) {
1332         char *c;
1333         char *parse = in;
1334         if (out) {
1335                 *out = in;
1336         }
1337
1338         /* Skip any quoted text */
1339         while (*parse) {
1340                 if ((c = strchr(parse, '"'))) {
1341                         in = (char *)find_closing_quote((const char *)c + 1, NULL);
1342                         if (!*in) {
1343                                 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", c);
1344                                 return -1;
1345                         } else {
1346                                 break;
1347                         }
1348                 } else {
1349                         break;
1350                 }
1351                 parse++;
1352         }
1353         parse = in;
1354
1355         /* Skip any userinfo components of a uri as they may contain commas */
1356         if ((c = strchr(parse,'@'))) {
1357                 parse = c+1;
1358         }
1359         if ((out) && (c = strchr(parse,','))) {
1360                 *c++ = '\0';
1361                 *out = c;
1362                 return 0;
1363         }
1364         return 1;
1365 }
1366
1367 int parse_contact_header(char *contactheader, struct contactliststruct *contactlist) {
1368         int res;
1369         int last;
1370         char *comma;
1371         char *residue;
1372         char *param;
1373         char *value;
1374         struct contact *contact=NULL;
1375
1376         if (*contactheader == '*') {
1377                 return 1;
1378         }
1379
1380         contact = malloc(sizeof(*contact));
1381
1382         AST_LIST_HEAD_SET_NOLOCK(contactlist, contact);
1383         while ((last = get_comma(contactheader,&comma)) != -1) {
1384
1385                 res = parse_name_andor_addr(contactheader, "sip:,sips:",
1386                                             &contact->name, &contact->user,
1387                                             &contact->pass, &contact->domain,
1388                                             &contact->params, &contact->headers,
1389                                             &residue);
1390                 if (res == -1) {
1391                         return res;
1392                 }
1393
1394                 /* parse contact params */
1395                 contact->expires = contact->q = "";
1396
1397                 while ((value = strchr(residue,'='))) {
1398                         *value++ = '\0';
1399
1400                         param = residue;
1401                         if ((residue = strchr(value,';'))) {
1402                                 *residue++ = '\0';
1403                         } else {
1404                                 residue = "";
1405                         }
1406
1407                         if (!strcmp(param,"expires")) {
1408                                 contact->expires = value;
1409                         } else if (!strcmp(param,"q")) {
1410                                 contact->q = value;
1411                         }
1412                 }
1413
1414                 if(last) {
1415                         return 0;
1416                 }
1417                 contactheader = comma;
1418
1419                 contact = malloc(sizeof(*contact));
1420                 AST_LIST_INSERT_TAIL(contactlist, contact, list);
1421
1422         }
1423         return last;
1424 }
1425
1426 AST_TEST_DEFINE(parse_contact_header_test)
1427 {
1428         int res = AST_TEST_PASS;
1429         char contactheader[1024];
1430         int star;
1431         struct contactliststruct contactlist;
1432         struct contactliststruct *contactlistptr=&contactlist;
1433
1434         struct testdata {
1435                 char *desc;
1436                 char *contactheader;
1437                 int star;
1438                 struct contactliststruct *contactlist;
1439
1440                 AST_LIST_ENTRY(testdata) list;
1441         };
1442
1443         struct testdata *testdataptr;
1444         struct contact *tdcontactptr;
1445         struct contact *contactptr;
1446
1447         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1448         struct contactliststruct contactlist1, contactlist2;
1449
1450         struct testdata td1 = {
1451                 .desc = "single contact",
1452                 .contactheader = "\"name :@;?&,\" <sip:user:secret@host:5082;param=discard;transport=tcp>;expires=3600",
1453                 .contactlist = &contactlist1,
1454                 .star = 0
1455         };
1456         struct contact contact11 = {
1457                 .name = "name :@;?&,",
1458                 .user = "user",
1459                 .pass = "secret",
1460                 .domain = "host:5082",
1461                 .params.transport = "tcp",
1462                 .params.ttl = "",
1463                 .params.lr = 0,
1464                 .headers = "",
1465                 .expires = "3600",
1466                 .q = ""
1467         };
1468
1469         struct testdata td2 = {
1470                 .desc = "multiple contacts",
1471                 .contactheader = "sip:,user1,:,secret1,@host1;ttl=7;q=1;expires=3600,sips:host2",
1472                 .contactlist = &contactlist2,
1473                 .star = 0,
1474         };
1475         struct contact contact21 = {
1476                 .name = "",
1477                 .user = ",user1,",
1478                 .pass = ",secret1,",
1479                 .domain = "host1",
1480                 .params.transport = "",
1481                 .params.ttl = "7",
1482                 .params.lr = 0,
1483                 .headers = "",
1484                 .expires = "3600",
1485                 .q = "1"
1486         };
1487         struct contact contact22 = {
1488                 .name = "",
1489                 .user = "",
1490                 .pass = "",
1491                 .domain = "host2",
1492                 .params.transport = "",
1493                 .params.ttl = "",
1494                 .params.lr = 0,
1495                 .headers = "",
1496                 .expires = "",
1497                 .q = ""
1498         };
1499
1500         struct testdata td3 = {
1501                 .desc = "star - all contacts",
1502                 .contactheader = "*",
1503                 .star = 1,
1504                 .contactlist = NULL
1505         };
1506
1507         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
1508         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
1509         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
1510
1511         AST_LIST_HEAD_SET_NOLOCK(&contactlist1, &contact11);
1512
1513         AST_LIST_HEAD_SET_NOLOCK(&contactlist2, &contact21);
1514         AST_LIST_INSERT_TAIL(&contactlist2, &contact22, list);
1515
1516
1517         switch (cmd) {
1518         case TEST_INIT:
1519                 info->name = "parse_contact_header_test";
1520                 info->category = "/channels/chan_sip/";
1521                 info->summary = "tests parsing of sip contact header";
1522                 info->description =
1523                         "Tests parsing of a contact header including those with multiple contacts "
1524                         "Verifies output matches expected behavior.";
1525                 return AST_TEST_NOT_RUN;
1526         case TEST_EXECUTE:
1527                 break;
1528         }
1529
1530         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1531                 ast_copy_string(contactheader,testdataptr->contactheader,sizeof(contactheader));
1532                 star = parse_contact_header(contactheader,contactlistptr);
1533                 if (testdataptr->star) {
1534                         /* expecting star rather than list of contacts */
1535                         if (!star) {
1536                                 ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1537                                 res = AST_TEST_FAIL;
1538                                 break;
1539                         }
1540                 } else {
1541                         contactptr = AST_LIST_FIRST(contactlistptr);
1542                         AST_LIST_TRAVERSE(testdataptr->contactlist, tdcontactptr, list) {
1543                                 if (!contactptr ||
1544                                         strcmp(tdcontactptr->name, contactptr->name) ||
1545                                         strcmp(tdcontactptr->user, contactptr->user) ||
1546                                         strcmp(tdcontactptr->pass, contactptr->pass) ||
1547                                         strcmp(tdcontactptr->domain, contactptr->domain) ||
1548                                         strcmp(tdcontactptr->headers, contactptr->headers) ||
1549                                         strcmp(tdcontactptr->expires, contactptr->expires) ||
1550                                         strcmp(tdcontactptr->q, contactptr->q) ||
1551                                         strcmp(tdcontactptr->params.transport, contactptr->params.transport) ||
1552                                         strcmp(tdcontactptr->params.ttl, contactptr->params.ttl) ||
1553                                         (tdcontactptr->params.lr != contactptr->params.lr)
1554                                 ) {
1555                                         ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1556                                         res = AST_TEST_FAIL;
1557                                         break;
1558                                 }
1559
1560                         contactptr = AST_LIST_NEXT(contactptr,list);
1561                         }
1562                 }
1563
1564         }
1565
1566         return res;
1567 }
1568
1569 /*!
1570  * \brief Parse supported header in incoming packet
1571  *
1572  * \details This function parses through the options parameters and
1573  * builds a bit field representing all the SIP options in that field. When an
1574  * item is found that is not supported, it is copied to the unsupported
1575  * out buffer.
1576  *
1577  * \param option list
1578  * \param unsupported out buffer (optional)
1579  * \param unsupported out buffer length (optional)
1580  */
1581 unsigned int parse_sip_options(const char *options, char *unsupported, size_t unsupported_len)
1582 {
1583         char *next, *sep;
1584         char *temp;
1585         int i, found, supported;
1586         unsigned int profile = 0;
1587
1588         char *out = unsupported;
1589         size_t outlen = unsupported_len;
1590         char *cur_out = out;
1591
1592         if (out && (outlen > 0)) {
1593                 memset(out, 0, outlen);
1594         }
1595
1596         if (ast_strlen_zero(options) )
1597                 return 0;
1598
1599         temp = ast_strdupa(options);
1600
1601         ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", options);
1602
1603         for (next = temp; next; next = sep) {
1604                 found = FALSE;
1605                 supported = FALSE;
1606                 if ((sep = strchr(next, ',')) != NULL) {
1607                         *sep++ = '\0';
1608                 }
1609
1610                 /* trim leading and trailing whitespace */
1611                 next = ast_strip(next);
1612
1613                 if (ast_strlen_zero(next)) {
1614                         continue; /* if there is a blank argument in there just skip it */
1615                 }
1616
1617                 ast_debug(3, "Found SIP option: -%s-\n", next);
1618                 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
1619                         if (!strcasecmp(next, sip_options[i].text)) {
1620                                 profile |= sip_options[i].id;
1621                                 if (sip_options[i].supported == SUPPORTED) {
1622                                         supported = TRUE;
1623                                 }
1624                                 found = TRUE;
1625                                 ast_debug(3, "Matched SIP option: %s\n", next);
1626                                 break;
1627                         }
1628                 }
1629
1630                 /* If option is not supported, add to unsupported out buffer */
1631                 if (!supported && out && outlen) {
1632                         size_t copylen = strlen(next);
1633                         size_t cur_outlen = strlen(out);
1634                         /* Check to see if there is enough room to store this option.
1635                          * Copy length is string length plus 2 for the ',' and '\0' */
1636                         if ((cur_outlen + copylen + 2) < outlen) {
1637                                 /* if this isn't the first item, add the ',' */
1638                                 if (cur_outlen) {
1639                                         *cur_out = ',';
1640                                         cur_out++;
1641                                         cur_outlen++;
1642                                 }
1643                                 ast_copy_string(cur_out, next, (outlen - cur_outlen));
1644                                 cur_out += copylen;
1645                         }
1646                 }
1647
1648                 if (!found) {
1649                         profile |= SIP_OPT_UNKNOWN;
1650                         if (!strncasecmp(next, "x-", 2))
1651                                 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
1652                         else
1653                                 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1654                 }
1655         }
1656
1657         return profile;
1658 }
1659
1660 AST_TEST_DEFINE(sip_parse_options_test)
1661 {
1662         int res = AST_TEST_PASS;
1663         char unsupported[64];
1664         unsigned int option_profile = 0;
1665         struct testdata {
1666                 char *name;
1667                 char *input_options;
1668                 char *expected_unsupported;
1669                 unsigned int expected_profile;
1670                 AST_LIST_ENTRY(testdata) list;
1671         };
1672
1673         struct testdata *testdataptr;
1674         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1675
1676         struct testdata test1 = {
1677                 .name = "test_all_unsupported",
1678                 .input_options = "unsupported1,,, ,unsupported2,unsupported3,unsupported4",
1679                 .expected_unsupported = "unsupported1,unsupported2,unsupported3,unsupported4",
1680                 .expected_profile = SIP_OPT_UNKNOWN,
1681         };
1682         struct testdata test2 = {
1683                 .name = "test_all_unsupported_one_supported",
1684                 .input_options = "  unsupported1, replaces,   unsupported3  , , , ,unsupported4",
1685                 .expected_unsupported = "unsupported1,unsupported3,unsupported4",
1686                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES
1687         };
1688         struct testdata test3 = {
1689                 .name = "test_two_supported_two_unsupported",
1690                 .input_options = ",,  timer  ,replaces     ,unsupported3,unsupported4",
1691                 .expected_unsupported = "unsupported3,unsupported4",
1692                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
1693         };
1694
1695         struct testdata test4 = {
1696                 .name = "test_all_supported",
1697                 .input_options = "timer,replaces",
1698                 .expected_unsupported = "",
1699                 .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
1700         };
1701
1702         struct testdata test5 = {
1703                 .name = "test_all_supported_redundant",
1704                 .input_options = "timer,replaces,timer,replace,timer,replaces",
1705                 .expected_unsupported = "",
1706                 .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
1707         };
1708         struct testdata test6 = {
1709                 .name = "test_buffer_overflow",
1710                 .input_options = "unsupported1,replaces,timer,unsupported4,unsupported_huge____"
1711                 "____________________________________,__________________________________________"
1712                 "________________________________________________",
1713                 .expected_unsupported = "unsupported1,unsupported4",
1714                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
1715         };
1716         struct testdata test7 = {
1717                 .name = "test_null_input",
1718                 .input_options = NULL,
1719                 .expected_unsupported = "",
1720                 .expected_profile = 0,
1721         };
1722         struct testdata test8 = {
1723                 .name = "test_whitespace_input",
1724                 .input_options = "         ",
1725                 .expected_unsupported = "",
1726                 .expected_profile = 0,
1727         };
1728         struct testdata test9 = {
1729                 .name = "test_whitespace_plus_option_input",
1730                 .input_options = " , , ,timer , ,  , ,        ,    ",
1731                 .expected_unsupported = "",
1732                 .expected_profile = SIP_OPT_TIMER,
1733         };
1734
1735         switch (cmd) {
1736         case TEST_INIT:
1737                 info->name = "sip_parse_options_test";
1738                 info->category = "/channels/chan_sip/";
1739                 info->summary = "Tests parsing of sip options";
1740                 info->description =
1741                                                         "Tests parsing of SIP options from supported and required "
1742                                                         "header fields.  Verifies when unsupported options are encountered "
1743                                                         "that they are appended to the unsupported out buffer and that the "
1744                                                         "correct bit field representnig the option profile is returned.";
1745                 return AST_TEST_NOT_RUN;
1746         case TEST_EXECUTE:
1747                 break;
1748         }
1749
1750         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &test1);
1751         AST_LIST_INSERT_TAIL(&testdatalist, &test2, list);
1752         AST_LIST_INSERT_TAIL(&testdatalist, &test3, list);
1753         AST_LIST_INSERT_TAIL(&testdatalist, &test4, list);
1754         AST_LIST_INSERT_TAIL(&testdatalist, &test5, list);
1755         AST_LIST_INSERT_TAIL(&testdatalist, &test6, list);
1756         AST_LIST_INSERT_TAIL(&testdatalist, &test7, list);
1757         AST_LIST_INSERT_TAIL(&testdatalist, &test8, list);
1758         AST_LIST_INSERT_TAIL(&testdatalist, &test9, list);
1759
1760         /* Test with unsupported char buffer */
1761         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1762                 option_profile = parse_sip_options(testdataptr->input_options, unsupported, ARRAY_LEN(unsupported));
1763                 if (option_profile != testdataptr->expected_profile ||
1764                         strcmp(unsupported, testdataptr->expected_unsupported)) {
1765                         ast_test_status_update(test, "Test with output buffer \"%s\", expected unsupported: %s actual unsupported:"
1766                                 "%s expected bit profile: %x actual bit profile: %x\n",
1767                                 testdataptr->name,
1768                                 testdataptr->expected_unsupported,
1769                                 unsupported,
1770                                 testdataptr->expected_profile,
1771                                 option_profile);
1772                         res = AST_TEST_FAIL;
1773                 } else {
1774                         ast_test_status_update(test, "\"%s\" passed got expected unsupported: %s and bit profile: %x\n",
1775                                 testdataptr->name,
1776                                 unsupported,
1777                                 option_profile);
1778                 }
1779
1780                 option_profile = parse_sip_options(testdataptr->input_options, NULL, 0);
1781                 if (option_profile != testdataptr->expected_profile) {
1782                         ast_test_status_update(test, "NULL output test \"%s\", expected bit profile: %x actual bit profile: %x\n",
1783                                 testdataptr->name,
1784                                 testdataptr->expected_profile,
1785                                 option_profile);
1786                         res = AST_TEST_FAIL;
1787                 } else {
1788                         ast_test_status_update(test, "\"%s\" with NULL output buf passed, bit profile: %x\n",
1789                                 testdataptr->name,
1790                                 option_profile);
1791                 }
1792         }
1793
1794         return res;
1795 }
1796
1797 /*! \brief helper routine for sip_uri_cmp to compare URI parameters
1798  *
1799  * This takes the parameters from two SIP URIs and determines
1800  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
1801  * 1. If a parameter appears in both URIs, then they must have the same value
1802  *    in order for the URIs to match
1803  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
1804  *    URI must also have that parameter and must have the same value
1805  *    in order for the URIs to match
1806  * 3. All other headers appearing in only one URI are not considered when
1807  *    determining if URIs match
1808  *
1809  * \param input1 Parameters from URI 1
1810  * \param input2 Parameters from URI 2
1811  * \retval 0 URIs' parameters match
1812  * \retval nonzero URIs' parameters do not match
1813  */
1814 static int sip_uri_params_cmp(const char *input1, const char *input2)
1815 {
1816         char *params1 = NULL;
1817         char *params2 = NULL;
1818         char *pos1;
1819         char *pos2;
1820         int zerolength1 = 0;
1821         int zerolength2 = 0;
1822         int maddrmatch = 0;
1823         int ttlmatch = 0;
1824         int usermatch = 0;
1825         int methodmatch = 0;
1826
1827         if (ast_strlen_zero(input1)) {
1828                 zerolength1 = 1;
1829         } else {
1830                 params1 = ast_strdupa(input1);
1831         }
1832         if (ast_strlen_zero(input2)) {
1833                 zerolength2 = 1;
1834         } else {
1835                 params2 = ast_strdupa(input2);
1836         }
1837
1838         /* Quick optimization. If both params are zero-length, then
1839          * they match
1840          */
1841         if (zerolength1 && zerolength2) {
1842                 return 0;
1843         }
1844
1845         for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
1846                 char *value1 = pos1;
1847                 char *name1 = strsep(&value1, "=");
1848                 char *params2dup = NULL;
1849                 int matched = 0;
1850                 if (!value1) {
1851                         value1 = "";
1852                 }
1853                 /* Checkpoint reached. We have the name and value parsed for param1
1854                  * We have to duplicate params2 each time through this loop
1855                  * or else the inner loop below will not work properly.
1856                  */
1857                 if (!zerolength2) {
1858                         params2dup = ast_strdupa(params2);
1859                 }
1860                 for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
1861                         char *name2 = pos2;
1862                         char *value2 = strchr(pos2, '=');
1863                         if (!value2) {
1864                                 value2 = "";
1865                         } else {
1866                                 *value2++ = '\0';
1867                         }
1868                         if (!strcasecmp(name1, name2)) {
1869                                 if (strcasecmp(value1, value2)) {
1870                                         goto fail;
1871                                 } else {
1872                                         matched = 1;
1873                                         break;
1874                                 }
1875                         }
1876                 }
1877                 /* Check to see if the parameter is one of the 'must-match' parameters */
1878                 if (!strcasecmp(name1, "maddr")) {
1879                         if (matched) {
1880                                 maddrmatch = 1;
1881                         } else {
1882                                 goto fail;
1883                         }
1884                 } else if (!strcasecmp(name1, "ttl")) {
1885                         if (matched) {
1886                                 ttlmatch = 1;
1887                         } else {
1888                                 goto fail;
1889                         }
1890                 } else if (!strcasecmp(name1, "user")) {
1891                         if (matched) {
1892                                 usermatch = 1;
1893                         } else {
1894                                 goto fail;
1895                         }
1896                 } else if (!strcasecmp(name1, "method")) {
1897                         if (matched) {
1898                                 methodmatch = 1;
1899                         } else {
1900                                 goto fail;
1901                         }
1902                 }
1903         }
1904
1905         /* We've made it out of that horrible O(m*n) construct and there are no
1906          * failures yet. We're not done yet, though, because params2 could have
1907          * an maddr, ttl, user, or method header and params1 did not.
1908          */
1909         for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
1910                 char *value2 = pos2;
1911                 char *name2 = strsep(&value2, "=");
1912                 if (!value2) {
1913                         value2 = "";
1914                 }
1915                 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
1916                                 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
1917                                 (!strcasecmp(name2, "user") && !usermatch) ||
1918                                 (!strcasecmp(name2, "method") && !methodmatch)) {
1919                         goto fail;
1920                 }
1921         }
1922         return 0;
1923
1924 fail:
1925         return 1;
1926 }
1927
1928 /*! \brief helper routine for sip_uri_cmp to compare URI headers
1929  *
1930  * This takes the headers from two SIP URIs and determines
1931  * if the URIs match. The rules for headers is simple. If a header
1932  * appears in one URI, then it must also appear in the other URI. The
1933  * order in which the headers appear does not matter.
1934  *
1935  * \param input1 Headers from URI 1
1936  * \param input2 Headers from URI 2
1937  * \retval 0 URI headers match
1938  * \retval nonzero URI headers do not match
1939  */
1940 static int sip_uri_headers_cmp(const char *input1, const char *input2)
1941 {
1942         char *headers1 = NULL;
1943         char *headers2 = NULL;
1944         int zerolength1 = 0;
1945         int zerolength2 = 0;
1946         int different = 0;
1947         char *header1;
1948
1949         if (ast_strlen_zero(input1)) {
1950                 zerolength1 = 1;
1951         } else {
1952                 headers1 = ast_strdupa(input1);
1953         }
1954
1955         if (ast_strlen_zero(input2)) {
1956                 zerolength2 = 1;
1957         } else {
1958                 headers2 = ast_strdupa(input2);
1959         }
1960
1961         /* If one URI contains no headers and the other
1962          * does, then they cannot possibly match
1963          */
1964         if (zerolength1 != zerolength2) {
1965                 return 1;
1966         }
1967
1968         if (zerolength1 && zerolength2)
1969                 return 0;
1970
1971         /* At this point, we can definitively state that both inputs are
1972          * not zero-length. First, one more optimization. If the length
1973          * of the headers is not equal, then we definitely have no match
1974          */
1975         if (strlen(headers1) != strlen(headers2)) {
1976                 return 1;
1977         }
1978
1979         for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
1980                 if (!strcasestr(headers2, header1)) {
1981                         different = 1;
1982                         break;
1983                 }
1984         }
1985
1986         return different;
1987 }
1988
1989 /*!
1990  * \brief Compare domain sections of SIP URIs
1991  *
1992  * For hostnames, a case insensitive string comparison is
1993  * used. For IP addresses, a binary comparison is used. This
1994  * is mainly because IPv6 addresses have many ways of writing
1995  * the same address.
1996  *
1997  * For specifics about IP address comparison, see the following
1998  * document: http://tools.ietf.org/html/draft-ietf-sip-ipv6-abnf-fix-05
1999  *
2000  * \param host1 The domain from the first URI
2001  * \param host2 THe domain from the second URI
2002  * \retval 0 The domains match
2003  * \retval nonzero The domains do not match
2004  */
2005 static int sip_uri_domain_cmp(const char *host1, const char *host2)
2006 {
2007         struct ast_sockaddr addr1;
2008         struct ast_sockaddr addr2;
2009         int addr1_parsed;
2010         int addr2_parsed;
2011
2012         addr1_parsed = ast_sockaddr_parse(&addr1, host1, 0);
2013         addr2_parsed = ast_sockaddr_parse(&addr2, host2, 0);
2014
2015         if (addr1_parsed != addr2_parsed) {
2016                 /* One domain was an IP address and the other had
2017                  * a host name. FAIL!
2018                  */
2019                 return 1;
2020         }
2021
2022         /* Both are host names. A string comparison will work
2023          * perfectly here. Specifying the "C" locale ensures that
2024          * The LC_CTYPE conventions use those defined in ANSI C,
2025          * i.e. ASCII.
2026          */
2027         if (!addr1_parsed) {
2028 #ifdef HAVE_XLOCALE_H
2029                 if(!c_locale) {
2030                         return strcasecmp(host1, host2);
2031                 } else {
2032                         return strcasecmp_l(host1, host2, c_locale);
2033                 }
2034 #else
2035                 return strcasecmp(host1, host2);
2036 #endif
2037         }
2038
2039         /* Both contain IP addresses */
2040         return ast_sockaddr_cmp(&addr1, &addr2);
2041 }
2042
2043 int sip_uri_cmp(const char *input1, const char *input2)
2044 {
2045         char *uri1;
2046         char *uri2;
2047         char *uri_scheme1;
2048         char *uri_scheme2;
2049         char *host1;
2050         char *host2;
2051         char *params1;
2052         char *params2;
2053         char *headers1;
2054         char *headers2;
2055
2056         /* XXX It would be really nice if we could just use parse_uri_full() here
2057          * to separate the components of the URI, but unfortunately it is written
2058          * in a way that can cause URI parameters to be discarded.
2059          */
2060
2061         if (!input1 || !input2) {
2062                 return 1;
2063         }
2064
2065         uri1 = ast_strdupa(input1);
2066         uri2 = ast_strdupa(input2);
2067
2068         ast_uri_decode(uri1, ast_uri_sip_user);
2069         ast_uri_decode(uri2, ast_uri_sip_user);
2070
2071         uri_scheme1 = strsep(&uri1, ":");
2072         uri_scheme2 = strsep(&uri2, ":");
2073
2074         if (strcmp(uri_scheme1, uri_scheme2)) {
2075                 return 1;
2076         }
2077
2078         /* This function is tailored for SIP and SIPS URIs. There's no
2079          * need to check uri_scheme2 since we have determined uri_scheme1
2080          * and uri_scheme2 are equivalent already.
2081          */
2082         if (strcmp(uri_scheme1, "sip") && strcmp(uri_scheme1, "sips")) {
2083                 return 1;
2084         }
2085
2086         if (ast_strlen_zero(uri1) || ast_strlen_zero(uri2)) {
2087                 return 1;
2088         }
2089
2090         if ((host1 = strchr(uri1, '@'))) {
2091                 *host1++ = '\0';
2092         }
2093         if ((host2 = strchr(uri2, '@'))) {
2094                 *host2++ = '\0';
2095         }
2096
2097         /* Check for mismatched username and passwords. This is the
2098          * only case-sensitive comparison of a SIP URI
2099          */
2100         if ((host1 && !host2) ||
2101                         (host2 && !host1) ||
2102                         (host1 && host2 && strcmp(uri1, uri2))) {
2103                 return 1;
2104         }
2105
2106         if (!host1) {
2107                 host1 = uri1;
2108         }
2109         if (!host2) {
2110                 host2 = uri2;
2111         }
2112
2113         /* Strip off the parameters and headers so we can compare
2114          * host and port
2115          */
2116
2117         if ((params1 = strchr(host1, ';'))) {
2118                 *params1++ = '\0';
2119         }
2120         if ((params2 = strchr(host2, ';'))) {
2121                 *params2++ = '\0';
2122         }
2123
2124         /* Headers come after parameters, but there may be headers without
2125          * parameters, thus the S_OR
2126          */
2127         if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
2128                 *headers1++ = '\0';
2129         }
2130         if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
2131                 *headers2++ = '\0';
2132         }
2133
2134         if (sip_uri_domain_cmp(host1, host2)) {
2135                 return 1;
2136         }
2137
2138         /* Headers have easier rules to follow, so do those first */
2139         if (sip_uri_headers_cmp(headers1, headers2)) {
2140                 return 1;
2141         }
2142
2143         /* And now the parameters. Ugh */
2144         return sip_uri_params_cmp(params1, params2);
2145 }
2146
2147 #define URI_CMP_MATCH 0
2148 #define URI_CMP_NOMATCH 1
2149
2150 AST_TEST_DEFINE(sip_uri_cmp_test)
2151 {
2152         static const struct {
2153                 const char *uri1;
2154                 const char *uri2;
2155                 int expected_result;
2156         } uri_cmp_tests [] = {
2157                 /* These are identical, so they match */
2158                 { "sip:bob@example.com", "sip:bob@example.com", URI_CMP_MATCH },
2159                 /* Different usernames. No match */
2160                 { "sip:alice@example.com", "sip:bob@example.com", URI_CMP_NOMATCH },
2161                 /* Different hosts. No match */
2162                 { "sip:bob@example.com", "sip:bob@examplez.com", URI_CMP_NOMATCH },
2163                 /* Now start using IP addresses. Identical, so they match */
2164                 { "sip:bob@1.2.3.4", "sip:bob@1.2.3.4", URI_CMP_MATCH },
2165                 /* Two identical IPv4 addresses represented differently. Match */
2166                 { "sip:bob@1.2.3.4", "sip:bob@001.002.003.004", URI_CMP_MATCH },
2167                 /* Logically equivalent IPv4 Address and hostname. No Match */
2168                 { "sip:bob@127.0.0.1", "sip:bob@localhost", URI_CMP_NOMATCH },
2169                 /* Logically equivalent IPv6 address and hostname. No Match */
2170                 { "sip:bob@[::1]", "sip:bob@localhost", URI_CMP_NOMATCH },
2171                 /* Try an IPv6 one as well */
2172                 { "sip:bob@[2001:db8::1234]", "sip:bob@[2001:db8::1234]", URI_CMP_MATCH },
2173                 /* Two identical IPv6 addresses represented differently. Match */
2174                 { "sip:bob@[2001:db8::1234]", "sip:bob@[2001:0db8::1234]", URI_CMP_MATCH },
2175                 /* Different ports. No match */
2176                 { "sip:bob@1.2.3.4:5060", "sip:bob@1.2.3.4:5061", URI_CMP_NOMATCH },
2177                 /* Same port logically, but only one address specifies it. No match */
2178                 { "sip:bob@1.2.3.4:5060", "sip:bob@1.2.3.4", URI_CMP_NOMATCH },
2179                 /* And for safety, try with IPv6 */
2180                 { "sip:bob@[2001:db8:1234]:5060", "sip:bob@[2001:db8:1234]", URI_CMP_NOMATCH },
2181                 /* User comparison is case sensitive. No match */
2182                 { "sip:bob@example.com", "sip:BOB@example.com", URI_CMP_NOMATCH },
2183                 /* Host comparison is case insensitive. Match */
2184                 { "sip:bob@example.com", "sip:bob@EXAMPLE.COM", URI_CMP_MATCH },
2185                 /* Add headers to the URI. Identical, so they match */
2186                 { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com?header1=value1&header2=value2", URI_CMP_MATCH },
2187                 /* Headers in URI 1 are not in URI 2. No Match */
2188                 { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com", URI_CMP_NOMATCH },
2189                 /* Header present in both URIs does not have matching values. No match */
2190                 { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com?header1=value1&header2=value3", URI_CMP_NOMATCH },
2191                 /* Add parameters to the URI. Identical so they match */
2192                 { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com;param1=value1;param2=value2", URI_CMP_MATCH },
2193                 /* Same parameters in both URIs but appear in different order. Match */
2194                 { "sip:bob@example.com;param2=value2;param1=value1", "sip:bob@example.com;param1=value1;param2=value2", URI_CMP_MATCH },
2195                 /* params in URI 1 are not in URI 2. Match */
2196                 { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com", URI_CMP_MATCH },
2197                 /* param present in both URIs does not have matching values. No match */
2198                 { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com;param1=value1;param2=value3", URI_CMP_NOMATCH },
2199                 /* URI 1 has a maddr param but URI 2 does not. No match */
2200                 { "sip:bob@example.com;param1=value1;maddr=192.168.0.1", "sip:bob@example.com;param1=value1", URI_CMP_NOMATCH },
2201                 /* URI 1 and URI 2 both have identical maddr params. Match */
2202                 { "sip:bob@example.com;param1=value1;maddr=192.168.0.1", "sip:bob@example.com;param1=value1;maddr=192.168.0.1", URI_CMP_MATCH },
2203                 /* URI 1 is a SIPS URI and URI 2 is a SIP URI. No Match */
2204                 { "sips:bob@example.com", "sip:bob@example.com", URI_CMP_NOMATCH },
2205                 /* No URI schemes. No match */
2206                 { "bob@example.com", "bob@example.com", URI_CMP_NOMATCH },
2207                 /* Crashiness tests. Just an address scheme. No match */
2208                 { "sip", "sips", URI_CMP_NOMATCH },
2209                 /* Still just an address scheme. Even though they're the same, No match */
2210                 { "sip", "sip", URI_CMP_NOMATCH },
2211                 /* Empty strings. No match */
2212                 { "", "", URI_CMP_NOMATCH },
2213                 /* An empty string and a NULL. No match */
2214                 { "", NULL, URI_CMP_NOMATCH },
2215         };
2216         int i;
2217         int test_res = AST_TEST_PASS;
2218         switch (cmd) {
2219         case TEST_INIT:
2220                 info->name = "sip_uri_cmp_test";
2221                 info->category = "/channels/chan_sip/";
2222                 info->summary = "Tests comparison of SIP URIs";
2223                 info->description = "Several would-be tricky URI comparisons are performed";
2224                 return AST_TEST_NOT_RUN;
2225         case TEST_EXECUTE:
2226                 break;
2227         }
2228
2229         for (i = 0; i < ARRAY_LEN(uri_cmp_tests); ++i) {
2230                 int cmp_res1;
2231                 int cmp_res2;
2232                 if ((cmp_res1 = sip_uri_cmp(uri_cmp_tests[i].uri1, uri_cmp_tests[i].uri2))) {
2233                         /* URI comparison may return -1 or +1 depending on the failure. Standardize
2234                          * the return value to be URI_CMP_NOMATCH on any failure
2235                          */
2236                         cmp_res1 = URI_CMP_NOMATCH;
2237                 }
2238                 if (cmp_res1 != uri_cmp_tests[i].expected_result) {
2239                         ast_test_status_update(test, "Unexpected comparison result for URIs %s and %s. "
2240                                         "Expected %s but got %s\n", uri_cmp_tests[i].uri1, uri_cmp_tests[i].uri2,
2241                                         uri_cmp_tests[i].expected_result == URI_CMP_MATCH ? "Match" : "No Match",
2242                                         cmp_res1 == URI_CMP_MATCH ? "Match" : "No Match");
2243                         test_res = AST_TEST_FAIL;
2244                 }
2245
2246                 /* All URI comparisons are commutative, so for the sake of being thorough, we'll
2247                  * rerun the comparison with the parameters reversed
2248                  */
2249                 if ((cmp_res2 = sip_uri_cmp(uri_cmp_tests[i].uri2, uri_cmp_tests[i].uri1))) {
2250                         /* URI comparison may return -1 or +1 depending on the failure. Standardize
2251                          * the return value to be URI_CMP_NOMATCH on any failure
2252                          */
2253                         cmp_res2 = URI_CMP_NOMATCH;
2254                 }
2255                 if (cmp_res2 != uri_cmp_tests[i].expected_result) {
2256                         ast_test_status_update(test, "Unexpected comparison result for URIs %s and %s. "
2257                                         "Expected %s but got %s\n", uri_cmp_tests[i].uri2, uri_cmp_tests[i].uri1,
2258                                         uri_cmp_tests[i].expected_result == URI_CMP_MATCH ? "Match" : "No Match",
2259                                         cmp_res2 == URI_CMP_MATCH ? "Match" : "No Match");
2260                         test_res = AST_TEST_FAIL;
2261                 }
2262         }
2263
2264         return test_res;
2265 }
2266
2267 void free_via(struct sip_via *v)
2268 {
2269         if (!v) {
2270                 return;
2271         }
2272
2273         ast_free(v->via);
2274         ast_free(v);
2275 }
2276
2277 struct sip_via *parse_via(const char *header)
2278 {
2279         struct sip_via *v = ast_calloc(1, sizeof(*v));
2280         char *via, *parm;
2281
2282         if (!v) {
2283                 return NULL;
2284         }
2285
2286         v->via = ast_strdup(header);
2287         v->ttl = 1;
2288
2289         via = v->via;
2290
2291         if (ast_strlen_zero(via)) {
2292                 ast_log(LOG_ERROR, "received request without a Via header\n");
2293                 free_via(v);
2294                 return NULL;
2295         }
2296
2297         /* seperate the first via-parm */
2298         via = strsep(&via, ",");
2299
2300         /* chop off sent-protocol */
2301         v->protocol = strsep(&via, " \t\r\n");
2302         if (ast_strlen_zero(v->protocol)) {
2303                 ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
2304                 free_via(v);
2305                 return NULL;
2306         }
2307         v->protocol = ast_skip_blanks(v->protocol);
2308
2309         if (via) {
2310                 via = ast_skip_blanks(via);
2311         }
2312
2313         /* chop off sent-by */
2314         v->sent_by = strsep(&via, "; \t\r\n");
2315         if (ast_strlen_zero(v->sent_by)) {
2316                 ast_log(LOG_ERROR, "missing sent-by in Via header\n");
2317                 free_via(v);
2318                 return NULL;
2319         }
2320         v->sent_by = ast_skip_blanks(v->sent_by);
2321
2322         /* store the port, we have to handle ipv6 addresses containing ':'
2323          * characters gracefully */
2324         if (((parm = strchr(v->sent_by, ']')) && *(++parm) == ':') || (parm = strchr(v->sent_by, ':'))) {
2325                 char *endptr;
2326
2327                 v->port = strtol(++parm, &endptr, 10);
2328         }
2329
2330         /* evaluate any via-parms */
2331         while ((parm = strsep(&via, "; \t\r\n"))) {
2332                 char *c;
2333                 if ((c = strstr(parm, "maddr="))) {
2334                         v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
2335                 } else if ((c = strstr(parm, "branch="))) {
2336                         v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
2337                 } else if ((c = strstr(parm, "ttl="))) {
2338                         char *endptr;
2339                         c = ast_skip_blanks(c + sizeof("ttl=") - 1);
2340                         v->ttl = strtol(c, &endptr, 10);
2341
2342                         /* make sure we got a valid ttl value */
2343                         if (c == endptr) {
2344                                 v->ttl = 1;
2345                         }
2346                 }
2347         }
2348
2349         return v;
2350 }
2351
2352 AST_TEST_DEFINE(parse_via_test)
2353 {
2354         int res = AST_TEST_PASS;
2355         int i = 1;
2356         struct sip_via *via;
2357         struct testdata {
2358                 char *in;
2359                 char *expected_protocol;
2360                 char *expected_branch;
2361                 char *expected_sent_by;
2362                 char *expected_maddr;
2363                 unsigned int expected_port;
2364                 unsigned char expected_ttl;
2365                 int expected_null;
2366                 AST_LIST_ENTRY(testdata) list;
2367         };
2368         struct testdata *testdataptr;
2369         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
2370         struct testdata t1 = {
2371                 .in = "SIP/2.0/UDP host:port;branch=thebranch",
2372                 .expected_protocol = "SIP/2.0/UDP",
2373                 .expected_sent_by = "host:port",
2374                 .expected_branch = "thebranch",
2375         };
2376         struct testdata t2 = {
2377                 .in = "SIP/2.0/UDP host:port",
2378                 .expected_protocol = "SIP/2.0/UDP",
2379                 .expected_sent_by = "host:port",
2380                 .expected_branch = "",
2381         };
2382         struct testdata t3 = {
2383                 .in = "SIP/2.0/UDP",
2384                 .expected_null = 1,
2385         };
2386         struct testdata t4 = {
2387                 .in = "BLAH/BLAH/BLAH host:port;branch=",
2388                 .expected_protocol = "BLAH/BLAH/BLAH",
2389                 .expected_sent_by = "host:port",
2390                 .expected_branch = "",
2391         };
2392         struct testdata t5 = {
2393                 .in = "SIP/2.0/UDP host:5060;branch=thebranch;maddr=224.0.0.1;ttl=1",
2394                 .expected_protocol = "SIP/2.0/UDP",
2395                 .expected_sent_by = "host:5060",
2396                 .expected_port = 5060,
2397                 .expected_branch = "thebranch",
2398                 .expected_maddr = "224.0.0.1",
2399                 .expected_ttl = 1,
2400         };
2401         struct testdata t6 = {
2402                 .in = "SIP/2.0/UDP      host:5060;\n   branch=thebranch;\r\n  maddr=224.0.0.1;   ttl=1",
2403                 .expected_protocol = "SIP/2.0/UDP",
2404                 .expected_sent_by = "host:5060",
2405                 .expected_port = 5060,
2406                 .expected_branch = "thebranch",
2407                 .expected_maddr = "224.0.0.1",
2408                 .expected_ttl = 1,
2409         };
2410         struct testdata t7 = {
2411                 .in = "SIP/2.0/UDP [::1]:5060",
2412                 .expected_protocol = "SIP/2.0/UDP",
2413                 .expected_sent_by = "[::1]:5060",
2414                 .expected_port = 5060,
2415                 .expected_branch = "",
2416         };
2417         switch (cmd) {
2418         case TEST_INIT:
2419                 info->name = "parse_via_test";
2420                 info->category = "/channels/chan_sip/";
2421                 info->summary = "Tests parsing the Via header";
2422                 info->description =
2423                                 "Runs through various test situations in which various "
2424                                 " parameters parameter must be extracted from a VIA header";
2425                 return AST_TEST_NOT_RUN;
2426         case TEST_EXECUTE:
2427                 break;
2428         }
2429
2430         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &t1);
2431         AST_LIST_INSERT_TAIL(&testdatalist, &t2, list);
2432         AST_LIST_INSERT_TAIL(&testdatalist, &t3, list);
2433         AST_LIST_INSERT_TAIL(&testdatalist, &t4, list);
2434         AST_LIST_INSERT_TAIL(&testdatalist, &t5, list);
2435         AST_LIST_INSERT_TAIL(&testdatalist, &t6, list);
2436         AST_LIST_INSERT_TAIL(&testdatalist, &t7, list);
2437
2438
2439         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
2440                 via = parse_via(testdataptr->in);
2441                 if (!via) {
2442                         if (!testdataptr->expected_null) {
2443                                 ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2444                                         "failed to parse header\n",
2445                                 i, testdataptr->in);
2446                                 res = AST_TEST_FAIL;
2447                         }
2448                         i++;
2449                         continue;
2450                 }
2451
2452                 if (testdataptr->expected_null) {
2453                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2454                                 "successfully parased invalid via header\n",
2455                         i, testdataptr->in);
2456                         res = AST_TEST_FAIL;
2457                         free_via(via);
2458                         i++;
2459                         continue;
2460                 }
2461
2462                 if ((ast_strlen_zero(via->protocol) && !ast_strlen_zero(testdataptr->expected_protocol))
2463                         || (!ast_strlen_zero(via->protocol) && strcmp(via->protocol, testdataptr->expected_protocol))) {
2464
2465                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2466                                 "parsed protocol = \"%s\"\n"
2467                                 "expected = \"%s\"\n"
2468                                 "failed to parse protocol\n",
2469                         i, testdataptr->in, via->protocol, testdataptr->expected_protocol);
2470                         res = AST_TEST_FAIL;
2471                 }
2472
2473                 if ((ast_strlen_zero(via->sent_by) && !ast_strlen_zero(testdataptr->expected_sent_by))
2474                         || (!ast_strlen_zero(via->sent_by) && strcmp(via->sent_by, testdataptr->expected_sent_by))) {
2475
2476                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2477                                 "parsed sent_by = \"%s\"\n"
2478                                 "expected = \"%s\"\n"
2479                                 "failed to parse sent-by\n",
2480                         i, testdataptr->in, via->sent_by, testdataptr->expected_sent_by);
2481                         res = AST_TEST_FAIL;
2482                 }
2483
2484                 if (testdataptr->expected_port && testdataptr->expected_port != via->port) {
2485                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2486                                 "parsed port = \"%d\"\n"
2487                                 "expected = \"%d\"\n"
2488                                 "failed to parse port\n",
2489                         i, testdataptr->in, via->port, testdataptr->expected_port);
2490                         res = AST_TEST_FAIL;
2491                 }
2492
2493                 if ((ast_strlen_zero(via->branch) && !ast_strlen_zero(testdataptr->expected_branch))
2494                         || (!ast_strlen_zero(via->branch) && strcmp(via->branch, testdataptr->expected_branch))) {
2495
2496                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2497                                 "parsed branch = \"%s\"\n"
2498                                 "expected = \"%s\"\n"
2499                                 "failed to parse branch\n",
2500                         i, testdataptr->in, via->branch, testdataptr->expected_branch);
2501                         res = AST_TEST_FAIL;
2502                 }
2503
2504                 if ((ast_strlen_zero(via->maddr) && !ast_strlen_zero(testdataptr->expected_maddr))
2505                         || (!ast_strlen_zero(via->maddr) && strcmp(via->maddr, testdataptr->expected_maddr))) {
2506
2507                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2508                                 "parsed maddr = \"%s\"\n"
2509                                 "expected = \"%s\"\n"
2510                                 "failed to parse maddr\n",
2511                         i, testdataptr->in, via->maddr, testdataptr->expected_maddr);
2512                         res = AST_TEST_FAIL;
2513                 }
2514
2515                 if (testdataptr->expected_ttl && testdataptr->expected_ttl != via->ttl) {
2516                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2517                                 "parsed ttl = \"%d\"\n"
2518                                 "expected = \"%d\"\n"
2519                                 "failed to parse ttl\n",
2520                         i, testdataptr->in, via->ttl, testdataptr->expected_ttl);
2521                         res = AST_TEST_FAIL;
2522                 }
2523
2524                 free_via(via);
2525                 i++;
2526         }
2527         return res;
2528 }
2529
2530 void sip_request_parser_register_tests(void)
2531 {
2532         AST_TEST_REGISTER(get_calleridname_test);
2533         AST_TEST_REGISTER(sip_parse_uri_test);
2534         AST_TEST_REGISTER(get_in_brackets_test);
2535         AST_TEST_REGISTER(get_name_and_number_test);
2536         AST_TEST_REGISTER(sip_parse_uri_fully_test);
2537         AST_TEST_REGISTER(parse_name_andor_addr_test);
2538         AST_TEST_REGISTER(parse_contact_header_test);
2539         AST_TEST_REGISTER(sip_parse_options_test);
2540         AST_TEST_REGISTER(sip_uri_cmp_test);
2541         AST_TEST_REGISTER(parse_via_test);
2542 }
2543 void sip_request_parser_unregister_tests(void)
2544 {
2545         AST_TEST_UNREGISTER(sip_parse_uri_test);
2546         AST_TEST_UNREGISTER(get_calleridname_test);
2547         AST_TEST_UNREGISTER(get_in_brackets_test);
2548         AST_TEST_UNREGISTER(get_name_and_number_test);
2549         AST_TEST_UNREGISTER(sip_parse_uri_fully_test);
2550         AST_TEST_UNREGISTER(parse_name_andor_addr_test);
2551         AST_TEST_UNREGISTER(parse_contact_header_test);
2552         AST_TEST_UNREGISTER(sip_parse_options_test);
2553         AST_TEST_UNREGISTER(sip_uri_cmp_test);
2554         AST_TEST_UNREGISTER(parse_via_test);
2555 }
2556
2557 int sip_reqresp_parser_init(void)
2558 {
2559 #ifdef HAVE_XLOCALE_H
2560         c_locale = newlocale(LC_CTYPE_MASK, "C", NULL);
2561         if (!c_locale) {
2562                 return -1;
2563         }
2564 #endif
2565         return 0;
2566 }
2567
2568 void sip_reqresp_parser_exit(void)
2569 {
2570 #ifdef HAVE_XLOCALE_H
2571         if (c_locale) {
2572                 freelocale(c_locale);
2573                 c_locale = NULL;
2574         }
2575 #endif
2576 }