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