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