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