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