d135e007331d1449e9856f3d6238e4b478dc1e63
[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         /* clear any empty characters in the beginning */
689         input = ast_skip_blanks(input);
690
691         /* no data at all or no storage room? */
692         if (!input || *input == '<' || !outputsize || !output) {
693                 return orig_input;
694         }
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         /* quoted-string rules */
703         if (input[0] == '"') {
704                 input++; /* skip the first " */
705
706                 for (;((outputsize > 0) && *input); input++) {
707                         if (*input == '"') {  /* end of quoted-string */
708                                 break;
709                         } else if (*input == 0x5c) { /* quoted-pair = "\" (%x00-09 / %x0B-0C / %x0E-7F) */
710                                 input++;
711                                 if (!*input || (unsigned char)*input > 0x7f || *input == 0xa || *input == 0xd) {
712                                         continue;  /* not a valid quoted-pair, so skip it */
713                                 }
714                         } else if (((*input != 0x9) && ((unsigned char) *input < 0x20)) ||
715                                     (*input == 0x7f)) {
716                                 continue; /* skip this invalid character. */
717                         }
718
719                         *output++ = *input;
720                         outputsize--;
721                 }
722
723                 /* if this is successful, input should be at the ending quote */
724                 if (!input || *input != '"') {
725                         ast_log(LOG_WARNING, "No ending quote for display-name was found\n");
726                         *orig_output = '\0';
727                         return orig_input;
728                 }
729
730                 /* make sure input is past the last quote */
731                 input++;
732
733                 /* terminate outbuf */
734                 *output = '\0';
735         } else {  /* either an addr-spec or tokenLWS-combo */
736                 for (;((outputsize > 0) && *input); input++) {
737                         /* token or WSP (without LWS) */
738                         if ((*input >= '0' && *input <= '9') || (*input >= 'A' && *input <= 'Z')
739                                 || (*input >= 'a' && *input <= 'z') || *input == '-' || *input == '.'
740                                 || *input == '!' || *input == '%' || *input == '*' || *input == '_'
741                                 || *input == '+' || *input == '`' || *input == '\'' || *input == '~'
742                                 || *input == 0x9 || *input == ' ') {
743                                 *output++ = *input;
744                                 outputsize -= 1;
745                         } else if (*input == '<') {   /* end of tokenLWS-combo */
746                                 /* we could assert that the previous char is LWS, but we don't care */
747                                 break;
748                         } else if (*input == ':') {
749                                 /* This invalid character which indicates this is addr-spec rather than display-name. */
750                                 *orig_output = '\0';
751                                 return orig_input;
752                         } else {         /* else, invalid character we can skip. */
753                                 continue;    /* skip this character */
754                         }
755                 }
756
757                 if (*input != '<') {   /* if we never found the start of addr-spec then this is invalid */
758                         *orig_output = '\0';
759                         return orig_input;
760                 }
761
762                 /* set NULL while trimming trailing whitespace */
763                 do {
764                         *output-- = '\0';
765                 } while (*output == 0x9 || *output == ' '); /* we won't go past orig_output as first was a non-space */
766         }
767
768         return input;
769 }
770
771 AST_TEST_DEFINE(get_calleridname_test)
772 {
773         int res = AST_TEST_PASS;
774         const char *in1 = "\" quoted-text internal \\\" quote \"<stuff>";
775         const char *in2 = " token text with no quotes <stuff>";
776         const char *overflow1 = " \"quoted-text overflow 1234567890123456789012345678901234567890\" <stuff>";
777         const char *noendquote = " \"quoted-text no end <stuff>";
778         const char *addrspec = " \"sip:blah@blah <stuff>";
779         const char *no_quotes_no_brackets = "blah@blah";
780         const char *after_dname;
781         char dname[40];
782
783         switch (cmd) {
784         case TEST_INIT:
785                 info->name = "sip_get_calleridname_test";
786                 info->category = "/channels/chan_sip/";
787                 info->summary = "decodes callerid name from sip header";
788                 info->description = "Decodes display-name field of sip header.  Checks for valid output and expected failure cases.";
789                 return AST_TEST_NOT_RUN;
790         case TEST_EXECUTE:
791                 break;
792         }
793
794         /* quoted-text with backslash escaped quote */
795         after_dname = get_calleridname(in1, dname, sizeof(dname));
796         ast_test_status_update(test, "display-name1: %s\nafter: %s\n", dname, after_dname);
797         if (strcmp(dname, " quoted-text internal \" quote ")) {
798                 ast_test_status_update(test, "display-name1 test failed\n");
799                 res = AST_TEST_FAIL;
800         }
801
802         /* token text */
803         after_dname = get_calleridname(in2, dname, sizeof(dname));
804         ast_test_status_update(test, "display-name2: %s\nafter: %s\n", dname, after_dname);
805         if (strcmp(dname, "token text with no quotes")) {
806                 ast_test_status_update(test, "display-name2 test failed\n");
807                 res = AST_TEST_FAIL;
808         }
809
810         /* quoted-text buffer overflow */
811         after_dname = get_calleridname(overflow1, dname, sizeof(dname));
812         ast_test_status_update(test, "overflow display-name1: %s\nafter: %s\n", dname, after_dname);
813         if (*dname != '\0' && after_dname != overflow1) {
814                 ast_test_status_update(test, "overflow display-name1 test failed\n");
815                 res = AST_TEST_FAIL;
816         }
817
818         /* quoted-text buffer with no terminating end quote */
819         after_dname = get_calleridname(noendquote, dname, sizeof(dname));
820         ast_test_status_update(test, "noendquote display-name1: %s\nafter: %s\n", dname, after_dname);
821         if (*dname != '\0' && after_dname != noendquote) {
822                 ast_test_status_update(test, "no end quote for quoted-text display-name failed\n");
823                 res = AST_TEST_FAIL;
824         }
825
826         /* addr-spec rather than display-name. */
827         after_dname = get_calleridname(addrspec, dname, sizeof(dname));
828         ast_test_status_update(test, "noendquote display-name1: %s\nafter: %s\n", dname, after_dname);
829         if (*dname != '\0' && after_dname != addrspec) {
830                 ast_test_status_update(test, "detection of addr-spec failed\n");
831                 res = AST_TEST_FAIL;
832         }
833
834         /* no quotes, no brackets */
835         after_dname = get_calleridname(no_quotes_no_brackets, dname, sizeof(dname));
836         ast_test_status_update(test, "no_quotes_no_brackets display-name1: %s\nafter: %s\n", dname, after_dname);
837         if (*dname != '\0' && after_dname != no_quotes_no_brackets) {
838                 ast_test_status_update(test, "detection of addr-spec failed\n");
839                 res = AST_TEST_FAIL;
840         }
841
842
843         return res;
844 }
845
846 int get_name_and_number(const char *hdr, char **name, char **number)
847 {
848         char header[256];
849         char tmp_name[50] = { 0, };
850         char *tmp_number = NULL;
851         char *hostport = NULL;
852         char *dummy = NULL;
853
854         if (!name || !number || ast_strlen_zero(hdr)) {
855                 return -1;
856         }
857
858         *number = NULL;
859         *name = NULL;
860         ast_copy_string(header, hdr, sizeof(header));
861
862         /* strip the display-name portion off the beginning of the header. */
863         get_calleridname(header, tmp_name, sizeof(tmp_name));
864
865         /* get uri within < > brackets */
866         tmp_number = get_in_brackets(header);
867
868         /* parse out the number here */
869         if (parse_uri(tmp_number, "sip:,sips:", &tmp_number, &dummy, &hostport, NULL) || ast_strlen_zero(tmp_number)) {
870                 ast_log(LOG_ERROR, "can not parse name and number from sip header.\n");
871                 return -1;
872         }
873
874         /* number is not option, and must be present at this point */
875         *number = ast_strdup(tmp_number);
876         ast_uri_decode(*number, ast_uri_sip_user);
877
878         /* name is optional and may not be present at this point */
879         if (!ast_strlen_zero(tmp_name)) {
880                 *name = ast_strdup(tmp_name);
881         }
882
883         return 0;
884 }
885
886 AST_TEST_DEFINE(get_name_and_number_test)
887 {
888         int res = AST_TEST_PASS;
889         char *name = NULL;
890         char *number = NULL;
891         const char *in1 = "NAME <sip:NUMBER@place>";
892         const char *in2 = "\"NA><ME\" <sip:NUMBER@place>";
893         const char *in3 = "NAME";
894         const char *in4 = "<sip:NUMBER@place>";
895         const char *in5 = "This is a screwed up string <sip:LOLCLOWNS<sip:>@place>";
896
897         switch (cmd) {
898         case TEST_INIT:
899                 info->name = "sip_get_name_and_number_test";
900                 info->category = "/channels/chan_sip/";
901                 info->summary = "Tests getting name and number from sip header";
902                 info->description =
903                                 "Runs through various test situations in which a name and "
904                                 "and number can be retrieved from a sip header.";
905                 return AST_TEST_NOT_RUN;
906         case TEST_EXECUTE:
907                 break;
908         }
909
910         /* Test 1. get name and number */
911         number = name = NULL;
912         if ((get_name_and_number(in1, &name, &number)) ||
913                 strcmp(name, "NAME") ||
914                 strcmp(number, "NUMBER")) {
915
916                 ast_test_status_update(test, "Test 1, simple get name and number failed.\n");
917                 res = AST_TEST_FAIL;
918         }
919         ast_free(name);
920         ast_free(number);
921
922         /* Test 2. get quoted name and number */
923         number = name = NULL;
924         if ((get_name_and_number(in2, &name, &number)) ||
925                 strcmp(name, "NA><ME") ||
926                 strcmp(number, "NUMBER")) {
927
928                 ast_test_status_update(test, "Test 2, get quoted name and number failed.\n");
929                 res = AST_TEST_FAIL;
930         }
931         ast_free(name);
932         ast_free(number);
933
934         /* Test 3. name only */
935         number = name = NULL;
936         if (!(get_name_and_number(in3, &name, &number))) {
937
938                 ast_test_status_update(test, "Test 3, get name only was expected to fail but did not.\n");
939                 res = AST_TEST_FAIL;
940         }
941         ast_free(name);
942         ast_free(number);
943
944         /* Test 4. number only */
945         number = name = NULL;
946         if ((get_name_and_number(in4, &name, &number)) ||
947                 !ast_strlen_zero(name) ||
948                 strcmp(number, "NUMBER")) {
949
950                 ast_test_status_update(test, "Test 4, get number with no name present failed.\n");
951                 res = AST_TEST_FAIL;
952         }
953         ast_free(name);
954         ast_free(number);
955
956         /* Test 5. malformed string, since number can not be parsed, this should return an error.  */
957         number = name = NULL;
958         if (!(get_name_and_number(in5, &name, &number)) ||
959                 !ast_strlen_zero(name) ||
960                 !ast_strlen_zero(number)) {
961
962                 ast_test_status_update(test, "Test 5, processing malformed string failed.\n");
963                 res = AST_TEST_FAIL;
964         }
965         ast_free(name);
966         ast_free(number);
967
968         /* Test 6. NULL output parameters */
969         number = name = NULL;
970         if (!(get_name_and_number(in5, NULL, NULL))) {
971
972                 ast_test_status_update(test, "Test 6, NULL output parameters failed.\n");
973                 res = AST_TEST_FAIL;
974         }
975
976         /* Test 7. NULL input parameter */
977         number = name = NULL;
978         if (!(get_name_and_number(NULL, &name, &number)) ||
979                 !ast_strlen_zero(name) ||
980                 !ast_strlen_zero(number)) {
981
982                 ast_test_status_update(test, "Test 7, NULL input parameter failed.\n");
983                 res = AST_TEST_FAIL;
984         }
985         ast_free(name);
986         ast_free(number);
987
988         return res;
989 }
990
991 int get_in_brackets_full(char *tmp,char **out,char **residue)
992 {
993         const char *parse = tmp;
994         char *first_bracket;
995         char *second_bracket;
996
997         if (out) {
998                 *out = "";
999         }
1000         if (residue) {
1001                 *residue = "";
1002         }
1003
1004         if (ast_strlen_zero(tmp)) {
1005                 return 1;
1006         }
1007
1008         /*
1009          * Skip any quoted text until we find the part in brackets.
1010         * On any error give up and return -1
1011         */
1012         while ( (first_bracket = strchr(parse, '<')) ) {
1013                 char *first_quote = strchr(parse, '"');
1014                 first_bracket++;
1015                 if (!first_quote || first_quote >= first_bracket) {
1016                         break; /* no need to look at quoted part */
1017                 }
1018                 /* the bracket is within quotes, so ignore it */
1019                 parse = find_closing_quote(first_quote + 1, NULL);
1020                 if (!*parse) {
1021                         ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1022                         return  -1;
1023                 }
1024                 parse++;
1025         }
1026
1027         /* If no first bracket then still look for a second bracket as some other parsing functions
1028         may overwrite first bracket with NULL when terminating a token based display-name. As this
1029         only affects token based display-names there is no danger of brackets being in quotes */
1030         if (first_bracket) {
1031                 parse = first_bracket;
1032         } else {
1033                 parse = tmp;
1034         }
1035
1036         if ((second_bracket = strchr(parse, '>'))) {
1037                 *second_bracket++ = '\0';
1038                 if (out) {
1039                         *out = (char *) parse;
1040                 }
1041                 if (residue) {
1042                         *residue = second_bracket;
1043                 }
1044                 return 0;
1045         }
1046
1047         if ((first_bracket)) {
1048                 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1049                 return -1;
1050         }
1051
1052         if (out) {
1053                 *out = tmp;
1054         }
1055
1056         return 1;
1057 }
1058
1059 char *get_in_brackets(char *tmp)
1060 {
1061         char *out;
1062
1063         if ((get_in_brackets_full(tmp, &out, NULL))) {
1064                 return tmp;
1065         }
1066         return out;
1067 }
1068
1069 AST_TEST_DEFINE(get_in_brackets_test)
1070 {
1071         int res = AST_TEST_PASS;
1072         char *in_brackets = "<sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1073         char no_name[] = "<sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1074         char quoted_string[] = "\"I'm a quote stri><ng\" <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1075         char missing_end_quote[] = "\"I'm a quote string <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1076         char name_no_quotes[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1077         char no_end_bracket[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah";
1078         char no_name_no_brackets[] = "sip:name@host";
1079         char missing_start_bracket[] = "name not in quotes sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1080         char *uri = NULL;
1081
1082         switch (cmd) {
1083         case TEST_INIT:
1084                 info->name = "sip_get_in_brackets_test";
1085                 info->category = "/channels/chan_sip/";
1086                 info->summary = "Tests getting a sip uri in <> brackets within a sip header.";
1087                 info->description =
1088                                 "Runs through various test situations in which a sip uri "
1089                                 "in angle brackets needs to be retrieved";
1090                 return AST_TEST_NOT_RUN;
1091         case TEST_EXECUTE:
1092                 break;
1093         }
1094
1095         /* Test 1, simple get in brackets */
1096         if (!(uri = get_in_brackets(no_name)) || !(strcmp(uri, in_brackets))) {
1097
1098                 ast_test_status_update(test, "Test 1, simple get in brackets failed.\n");
1099                 res = AST_TEST_FAIL;
1100         }
1101
1102         /* Test 2, starts with quoted string */
1103         if (!(uri = get_in_brackets(quoted_string)) || !(strcmp(uri, in_brackets))) {
1104
1105                 ast_test_status_update(test, "Test 2, get in brackets with quoted string in front failed.\n");
1106                 res = AST_TEST_FAIL;
1107         }
1108
1109         /* Test 3, missing end quote */
1110         if (!(uri = get_in_brackets(missing_end_quote)) || !(strcmp(uri, in_brackets))) {
1111
1112                 ast_test_status_update(test, "Test 3, missing end quote failed.\n");
1113                 res = AST_TEST_FAIL;
1114         }
1115
1116         /* Test 4, starts with a name not in quotes */
1117         if (!(uri = get_in_brackets(name_no_quotes)) || !(strcmp(uri, in_brackets))) {
1118
1119                 ast_test_status_update(test, "Test 4, passing name not in quotes failed.\n");
1120                 res = AST_TEST_FAIL;
1121         }
1122
1123         /* Test 5, no end bracket, should just return everything after the first '<'  */
1124         if (!(uri = get_in_brackets(no_end_bracket)) || !(strcmp(uri, in_brackets))) {
1125
1126                 ast_test_status_update(test, "Test 5, no end bracket failed.\n");
1127                 res = AST_TEST_FAIL;
1128         }
1129
1130         /* Test 6, NULL input  */
1131         if ((uri = get_in_brackets(NULL))) {
1132
1133                 ast_test_status_update(test, "Test 6, NULL input failed.\n");
1134                 res = AST_TEST_FAIL;
1135         }
1136
1137         /* Test 7, no name, and no brackets. */
1138         if (!(uri = get_in_brackets(no_name_no_brackets)) || (strcmp(uri, "sip:name@host"))) {
1139
1140                 ast_test_status_update(test, "Test 7 failed. %s\n", uri);
1141                 res = AST_TEST_FAIL;
1142         }
1143
1144         /* Test 8, no start bracket, but with ending bracket. */
1145         if (!(uri = get_in_brackets(missing_start_bracket)) || !(strcmp(uri, in_brackets))) {
1146
1147                 ast_test_status_update(test, "Test 8 failed. %s\n", uri);
1148                 res = AST_TEST_FAIL;
1149         }
1150
1151         return res;
1152 }
1153
1154
1155 int parse_name_andor_addr(char *uri, const char *scheme, char **name,
1156                           char **user, char **pass, char **hostport,
1157                           struct uriparams *params, char **headers,
1158                           char **residue)
1159 {
1160         char buf[1024];
1161         char **residue2=residue;
1162         int ret;
1163         if (name) {
1164                 get_calleridname(uri,buf,sizeof(buf));
1165                 *name = buf;
1166         }
1167         ret = get_in_brackets_full(uri,&uri,residue);
1168         if (ret == 0) { /* uri is in brackets so do not treat unknown trailing uri parameters as potential messageheader parameters */
1169                 *residue = *residue + 1; /* step over the first semicolon so as per parse uri residue */
1170                 residue2 = NULL;
1171         }
1172
1173         return parse_uri_full(uri, scheme, user, pass, hostport, params, headers,
1174                               residue2);
1175 }
1176
1177 AST_TEST_DEFINE(parse_name_andor_addr_test)
1178 {
1179         int res = AST_TEST_PASS;
1180         char uri[1024];
1181         char *name, *user, *pass, *hostport, *headers, *residue;
1182         struct uriparams params;
1183
1184         struct testdata {
1185                 char *desc;
1186                 char *uri;
1187                 char **nameptr;
1188                 char **userptr;
1189                 char **passptr;
1190                 char **hostportptr;
1191                 char **headersptr;
1192                 char **residueptr;
1193                 struct uriparams *paramsptr;
1194                 char *name;
1195                 char *user;
1196                 char *pass;
1197                 char *hostport;
1198                 char *headers;
1199                 char *residue;
1200                 struct uriparams params;
1201                 AST_LIST_ENTRY(testdata) list;
1202         };
1203
1204         struct testdata *testdataptr;
1205
1206         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1207
1208         struct testdata td1 = {
1209                 .desc = "quotes and brackets",
1210                 .uri = "\"name :@ \" <sip:user:secret@host:5060;param=discard;transport=tcp>;tag=tag",
1211                 .nameptr = &name,
1212                 .userptr = &user,
1213                 .passptr = &pass,
1214                 .hostportptr = &hostport,
1215                 .headersptr = &headers,
1216                 .residueptr = &residue,
1217                 .paramsptr = &params,
1218                 .name =  "name :@ ",
1219                 .user = "user",
1220                 .pass = "secret",
1221                 .hostport = "host:5060",
1222                 .headers = "",
1223                 .residue = "tag=tag",
1224                 .params.transport = "tcp",
1225                 .params.lr = 0,
1226                 .params.user = ""
1227         };
1228
1229         struct testdata td2 = {
1230                 .desc = "no quotes",
1231                 .uri = "givenname familyname <sip:user:secret@host:5060;param=discard;transport=tcp>;expires=3600",
1232                 .nameptr = &name,
1233                 .userptr = &user,
1234                 .passptr = &pass,
1235                 .hostportptr = &hostport,
1236                 .headersptr = &headers,
1237                 .residueptr = &residue,
1238                 .paramsptr = &params,
1239                 .name = "givenname familyname",
1240                 .user = "user",
1241                 .pass = "secret",
1242                 .hostport = "host:5060",
1243                 .headers = "",
1244                 .residue = "expires=3600",
1245                 .params.transport = "tcp",
1246                 .params.lr = 0,
1247                 .params.user = ""
1248         };
1249
1250         struct testdata td3 = {
1251                 .desc = "no brackets",
1252                 .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;q=1",
1253                 .nameptr = &name,
1254                 .userptr = &user,
1255                 .passptr = &pass,
1256                 .hostportptr = &hostport,
1257                 .headersptr = &headers,
1258                 .residueptr = &residue,
1259                 .paramsptr = &params,
1260                 .name = "",
1261                 .user = "user",
1262                 .pass = "secret",
1263                 .hostport = "host:5060",
1264                 .headers = "",
1265                 .residue = "q=1",
1266                 .params.transport = "tcp",
1267                 .params.lr = 0,
1268                 .params.user = ""
1269         };
1270
1271         struct testdata td4 = {
1272                 .desc = "just host",
1273                 .uri = "sips:host",
1274                 .nameptr = &name,
1275                 .userptr = &user,
1276                 .passptr = &pass,
1277                 .hostportptr = &hostport,
1278                 .headersptr = &headers,
1279                 .residueptr = &residue,
1280                 .paramsptr = &params,
1281                 .name = "",
1282                 .user = "",
1283                 .pass = "",
1284                 .hostport = "host",
1285                 .headers = "",
1286                 .residue = "",
1287                 .params.transport = "",
1288                 .params.lr = 0,
1289                 .params.user = ""
1290         };
1291
1292
1293         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
1294         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
1295         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
1296         AST_LIST_INSERT_TAIL(&testdatalist, &td4, list);
1297
1298
1299         switch (cmd) {
1300         case TEST_INIT:
1301                 info->name = "parse_name_andor_addr_test";
1302                 info->category = "/channels/chan_sip/";
1303                 info->summary = "tests parsing of name_andor_addr abnf structure";
1304                 info->description =
1305                         "Tests parsing of abnf name-andor-addr = name-addr / addr-spec "
1306                         "Verifies output matches expected behavior.";
1307                 return AST_TEST_NOT_RUN;
1308         case TEST_EXECUTE:
1309                 break;
1310         }
1311
1312         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1313                 name = user = pass = hostport = headers = residue = NULL;
1314                 params.transport = params.user = params.method = params.ttl = params.maddr = NULL;
1315                 params.lr = 0;
1316         ast_copy_string(uri,testdataptr->uri,sizeof(uri));
1317                 if (parse_name_andor_addr(uri, "sip:,sips:",
1318                                           testdataptr->nameptr,
1319                                           testdataptr->userptr,
1320                                           testdataptr->passptr,
1321                                           testdataptr->hostportptr,
1322                                           testdataptr->paramsptr,
1323                                           testdataptr->headersptr,
1324                                           testdataptr->residueptr) ||
1325                         ((testdataptr->nameptr) && strcmp(testdataptr->name, name)) ||
1326                         ((testdataptr->userptr) && strcmp(testdataptr->user, user)) ||
1327                         ((testdataptr->passptr) && strcmp(testdataptr->pass, pass)) ||
1328                         ((testdataptr->hostportptr) && strcmp(testdataptr->hostport, hostport)) ||
1329                         ((testdataptr->headersptr) && strcmp(testdataptr->headers, headers)) ||
1330                         ((testdataptr->residueptr) && strcmp(testdataptr->residue, residue)) ||
1331                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.transport,params.transport)) ||
1332                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.user,params.user))
1333                 ) {
1334                                 ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1335                                 res = AST_TEST_FAIL;
1336                 }
1337         }
1338
1339
1340         return res;
1341 }
1342
1343 int get_comma(char *in, char **out) {
1344         char *c;
1345         char *parse = in;
1346         if (out) {
1347                 *out = in;
1348         }
1349
1350         /* Skip any quoted text */
1351         while (*parse) {
1352                 if ((c = strchr(parse, '"'))) {
1353                         in = (char *)find_closing_quote((const char *)c + 1, NULL);
1354                         if (!*in) {
1355                                 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", c);
1356                                 return -1;
1357                         } else {
1358                                 break;
1359                         }
1360                 } else {
1361                         break;
1362                 }
1363                 parse++;
1364         }
1365         parse = in;
1366
1367         /* Skip any userinfo components of a uri as they may contain commas */
1368         if ((c = strchr(parse,'@'))) {
1369                 parse = c+1;
1370         }
1371         if ((out) && (c = strchr(parse,','))) {
1372                 *c++ = '\0';
1373                 *out = c;
1374                 return 0;
1375         }
1376         return 1;
1377 }
1378
1379 int parse_contact_header(char *contactheader, struct contactliststruct *contactlist) {
1380         int res;
1381         int last;
1382         char *comma;
1383         char *residue;
1384         char *param;
1385         char *value;
1386         struct contact *contact=NULL;
1387
1388         if (*contactheader == '*') {
1389                 return 1;
1390         }
1391
1392         contact = malloc(sizeof(*contact));
1393
1394         AST_LIST_HEAD_SET_NOLOCK(contactlist, contact);
1395         while ((last = get_comma(contactheader,&comma)) != -1) {
1396
1397                 res = parse_name_andor_addr(contactheader, "sip:,sips:",
1398                                             &contact->name, &contact->user,
1399                                             &contact->pass, &contact->hostport,
1400                                             &contact->params, &contact->headers,
1401                                             &residue);
1402                 if (res == -1) {
1403                         return res;
1404                 }
1405
1406                 /* parse contact params */
1407                 contact->expires = contact->q = "";
1408
1409                 while ((value = strchr(residue,'='))) {
1410                         *value++ = '\0';
1411
1412                         param = residue;
1413                         if ((residue = strchr(value,';'))) {
1414                                 *residue++ = '\0';
1415                         } else {
1416                                 residue = "";
1417                         }
1418
1419                         if (!strcmp(param,"expires")) {
1420                                 contact->expires = value;
1421                         } else if (!strcmp(param,"q")) {
1422                                 contact->q = value;
1423                         }
1424                 }
1425
1426                 if(last) {
1427                         return 0;
1428                 }
1429                 contactheader = comma;
1430
1431                 contact = malloc(sizeof(*contact));
1432                 AST_LIST_INSERT_TAIL(contactlist, contact, list);
1433
1434         }
1435         return last;
1436 }
1437
1438 AST_TEST_DEFINE(parse_contact_header_test)
1439 {
1440         int res = AST_TEST_PASS;
1441         char contactheader[1024];
1442         int star;
1443         struct contactliststruct contactlist;
1444         struct contactliststruct *contactlistptr=&contactlist;
1445
1446         struct testdata {
1447                 char *desc;
1448                 char *contactheader;
1449                 int star;
1450                 struct contactliststruct *contactlist;
1451
1452                 AST_LIST_ENTRY(testdata) list;
1453         };
1454
1455         struct testdata *testdataptr;
1456         struct contact *tdcontactptr;
1457         struct contact *contactptr;
1458
1459         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1460         struct contactliststruct contactlist1, contactlist2;
1461
1462         struct testdata td1 = {
1463                 .desc = "single contact",
1464                 .contactheader = "\"name :@;?&,\" <sip:user:secret@host:5082;param=discard;transport=tcp>;expires=3600",
1465                 .contactlist = &contactlist1,
1466                 .star = 0
1467         };
1468         struct contact contact11 = {
1469                 .name = "name :@;?&,",
1470                 .user = "user",
1471                 .pass = "secret",
1472                 .hostport = "host:5082",
1473                 .params.transport = "tcp",
1474                 .params.ttl = "",
1475                 .params.lr = 0,
1476                 .headers = "",
1477                 .expires = "3600",
1478                 .q = ""
1479         };
1480
1481         struct testdata td2 = {
1482                 .desc = "multiple contacts",
1483                 .contactheader = "sip:,user1,:,secret1,@host1;ttl=7;q=1;expires=3600,sips:host2",
1484                 .contactlist = &contactlist2,
1485                 .star = 0,
1486         };
1487         struct contact contact21 = {
1488                 .name = "",
1489                 .user = ",user1,",
1490                 .pass = ",secret1,",
1491                 .hostport = "host1",
1492                 .params.transport = "",
1493                 .params.ttl = "7",
1494                 .params.lr = 0,
1495                 .headers = "",
1496                 .expires = "3600",
1497                 .q = "1"
1498         };
1499         struct contact contact22 = {
1500                 .name = "",
1501                 .user = "",
1502                 .pass = "",
1503                 .hostport = "host2",
1504                 .params.transport = "",
1505                 .params.ttl = "",
1506                 .params.lr = 0,
1507                 .headers = "",
1508                 .expires = "",
1509                 .q = ""
1510         };
1511
1512         struct testdata td3 = {
1513                 .desc = "star - all contacts",
1514                 .contactheader = "*",
1515                 .star = 1,
1516                 .contactlist = NULL
1517         };
1518
1519         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
1520         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
1521         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
1522
1523         AST_LIST_HEAD_SET_NOLOCK(&contactlist1, &contact11);
1524
1525         AST_LIST_HEAD_SET_NOLOCK(&contactlist2, &contact21);
1526         AST_LIST_INSERT_TAIL(&contactlist2, &contact22, list);
1527
1528
1529         switch (cmd) {
1530         case TEST_INIT:
1531                 info->name = "parse_contact_header_test";
1532                 info->category = "/channels/chan_sip/";
1533                 info->summary = "tests parsing of sip contact header";
1534                 info->description =
1535                         "Tests parsing of a contact header including those with multiple contacts "
1536                         "Verifies output matches expected behavior.";
1537                 return AST_TEST_NOT_RUN;
1538         case TEST_EXECUTE:
1539                 break;
1540         }
1541
1542         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1543                 ast_copy_string(contactheader,testdataptr->contactheader,sizeof(contactheader));
1544                 star = parse_contact_header(contactheader,contactlistptr);
1545                 if (testdataptr->star) {
1546                         /* expecting star rather than list of contacts */
1547                         if (!star) {
1548                                 ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1549                                 res = AST_TEST_FAIL;
1550                                 break;
1551                         }
1552                 } else {
1553                         contactptr = AST_LIST_FIRST(contactlistptr);
1554                         AST_LIST_TRAVERSE(testdataptr->contactlist, tdcontactptr, list) {
1555                                 if (!contactptr ||
1556                                         strcmp(tdcontactptr->name, contactptr->name) ||
1557                                         strcmp(tdcontactptr->user, contactptr->user) ||
1558                                         strcmp(tdcontactptr->pass, contactptr->pass) ||
1559                                         strcmp(tdcontactptr->hostport, contactptr->hostport) ||
1560                                         strcmp(tdcontactptr->headers, contactptr->headers) ||
1561                                         strcmp(tdcontactptr->expires, contactptr->expires) ||
1562                                         strcmp(tdcontactptr->q, contactptr->q) ||
1563                                         strcmp(tdcontactptr->params.transport, contactptr->params.transport) ||
1564                                         strcmp(tdcontactptr->params.ttl, contactptr->params.ttl) ||
1565                                         (tdcontactptr->params.lr != contactptr->params.lr)
1566                                 ) {
1567                                         ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1568                                         res = AST_TEST_FAIL;
1569                                         break;
1570                                 }
1571
1572                         contactptr = AST_LIST_NEXT(contactptr,list);
1573                         }
1574                 }
1575
1576         }
1577
1578         return res;
1579 }
1580
1581 /*!
1582  * \brief Parse supported header in incoming packet
1583  *
1584  * \details This function parses through the options parameters and
1585  * builds a bit field representing all the SIP options in that field. When an
1586  * item is found that is not supported, it is copied to the unsupported
1587  * out buffer.
1588  *
1589  * \param option list
1590  * \param unsupported out buffer (optional)
1591  * \param unsupported out buffer length (optional)
1592  */
1593 unsigned int parse_sip_options(const char *options, char *unsupported, size_t unsupported_len)
1594 {
1595         char *next, *sep;
1596         char *temp;
1597         int i, found, supported;
1598         unsigned int profile = 0;
1599
1600         char *out = unsupported;
1601         size_t outlen = unsupported_len;
1602         char *cur_out = out;
1603
1604         if (out && (outlen > 0)) {
1605                 memset(out, 0, outlen);
1606         }
1607
1608         if (ast_strlen_zero(options) )
1609                 return 0;
1610
1611         temp = ast_strdupa(options);
1612
1613         ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", options);
1614
1615         for (next = temp; next; next = sep) {
1616                 found = FALSE;
1617                 supported = FALSE;
1618                 if ((sep = strchr(next, ',')) != NULL) {
1619                         *sep++ = '\0';
1620                 }
1621
1622                 /* trim leading and trailing whitespace */
1623                 next = ast_strip(next);
1624
1625                 if (ast_strlen_zero(next)) {
1626                         continue; /* if there is a blank argument in there just skip it */
1627                 }
1628
1629                 ast_debug(3, "Found SIP option: -%s-\n", next);
1630                 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
1631                         if (!strcasecmp(next, sip_options[i].text)) {
1632                                 profile |= sip_options[i].id;
1633                                 if (sip_options[i].supported == SUPPORTED) {
1634                                         supported = TRUE;
1635                                 }
1636                                 found = TRUE;
1637                                 ast_debug(3, "Matched SIP option: %s\n", next);
1638                                 break;
1639                         }
1640                 }
1641
1642                 /* If option is not supported, add to unsupported out buffer */
1643                 if (!supported && out && outlen) {
1644                         size_t copylen = strlen(next);
1645                         size_t cur_outlen = strlen(out);
1646                         /* Check to see if there is enough room to store this option.
1647                          * Copy length is string length plus 2 for the ',' and '\0' */
1648                         if ((cur_outlen + copylen + 2) < outlen) {
1649                                 /* if this isn't the first item, add the ',' */
1650                                 if (cur_outlen) {
1651                                         *cur_out = ',';
1652                                         cur_out++;
1653                                         cur_outlen++;
1654                                 }
1655                                 ast_copy_string(cur_out, next, (outlen - cur_outlen));
1656                                 cur_out += copylen;
1657                         }
1658                 }
1659
1660                 if (!found) {
1661                         profile |= SIP_OPT_UNKNOWN;
1662                         if (!strncasecmp(next, "x-", 2))
1663                                 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
1664                         else
1665                                 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1666                 }
1667         }
1668
1669         return profile;
1670 }
1671
1672 AST_TEST_DEFINE(sip_parse_options_test)
1673 {
1674         int res = AST_TEST_PASS;
1675         char unsupported[64];
1676         unsigned int option_profile = 0;
1677         struct testdata {
1678                 char *name;
1679                 char *input_options;
1680                 char *expected_unsupported;
1681                 unsigned int expected_profile;
1682                 AST_LIST_ENTRY(testdata) list;
1683         };
1684
1685         struct testdata *testdataptr;
1686         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1687
1688         struct testdata test1 = {
1689                 .name = "test_all_unsupported",
1690                 .input_options = "unsupported1,,, ,unsupported2,unsupported3,unsupported4",
1691                 .expected_unsupported = "unsupported1,unsupported2,unsupported3,unsupported4",
1692                 .expected_profile = SIP_OPT_UNKNOWN,
1693         };
1694         struct testdata test2 = {
1695                 .name = "test_all_unsupported_one_supported",
1696                 .input_options = "  unsupported1, replaces,   unsupported3  , , , ,unsupported4",
1697                 .expected_unsupported = "unsupported1,unsupported3,unsupported4",
1698                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES
1699         };
1700         struct testdata test3 = {
1701                 .name = "test_two_supported_two_unsupported",
1702                 .input_options = ",,  timer  ,replaces     ,unsupported3,unsupported4",
1703                 .expected_unsupported = "unsupported3,unsupported4",
1704                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
1705         };
1706
1707         struct testdata test4 = {
1708                 .name = "test_all_supported",
1709                 .input_options = "timer,replaces",
1710                 .expected_unsupported = "",
1711                 .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
1712         };
1713
1714         struct testdata test5 = {
1715                 .name = "test_all_supported_redundant",
1716                 .input_options = "timer,replaces,timer,replace,timer,replaces",
1717                 .expected_unsupported = "",
1718                 .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
1719         };
1720         struct testdata test6 = {
1721                 .name = "test_buffer_overflow",
1722                 .input_options = "unsupported1,replaces,timer,unsupported4,unsupported_huge____"
1723                 "____________________________________,__________________________________________"
1724                 "________________________________________________",
1725                 .expected_unsupported = "unsupported1,unsupported4",
1726                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
1727         };
1728         struct testdata test7 = {
1729                 .name = "test_null_input",
1730                 .input_options = NULL,
1731                 .expected_unsupported = "",
1732                 .expected_profile = 0,
1733         };
1734         struct testdata test8 = {
1735                 .name = "test_whitespace_input",
1736                 .input_options = "         ",
1737                 .expected_unsupported = "",
1738                 .expected_profile = 0,
1739         };
1740         struct testdata test9 = {
1741                 .name = "test_whitespace_plus_option_input",
1742                 .input_options = " , , ,timer , ,  , ,        ,    ",
1743                 .expected_unsupported = "",
1744                 .expected_profile = SIP_OPT_TIMER,
1745         };
1746
1747         switch (cmd) {
1748         case TEST_INIT:
1749                 info->name = "sip_parse_options_test";
1750                 info->category = "/channels/chan_sip/";
1751                 info->summary = "Tests parsing of sip options";
1752                 info->description =
1753                                                         "Tests parsing of SIP options from supported and required "
1754                                                         "header fields.  Verifies when unsupported options are encountered "
1755                                                         "that they are appended to the unsupported out buffer and that the "
1756                                                         "correct bit field representnig the option profile is returned.";
1757                 return AST_TEST_NOT_RUN;
1758         case TEST_EXECUTE:
1759                 break;
1760         }
1761
1762         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &test1);
1763         AST_LIST_INSERT_TAIL(&testdatalist, &test2, list);
1764         AST_LIST_INSERT_TAIL(&testdatalist, &test3, list);
1765         AST_LIST_INSERT_TAIL(&testdatalist, &test4, list);
1766         AST_LIST_INSERT_TAIL(&testdatalist, &test5, list);
1767         AST_LIST_INSERT_TAIL(&testdatalist, &test6, list);
1768         AST_LIST_INSERT_TAIL(&testdatalist, &test7, list);
1769         AST_LIST_INSERT_TAIL(&testdatalist, &test8, list);
1770         AST_LIST_INSERT_TAIL(&testdatalist, &test9, list);
1771
1772         /* Test with unsupported char buffer */
1773         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1774                 option_profile = parse_sip_options(testdataptr->input_options, unsupported, ARRAY_LEN(unsupported));
1775                 if (option_profile != testdataptr->expected_profile ||
1776                         strcmp(unsupported, testdataptr->expected_unsupported)) {
1777                         ast_test_status_update(test, "Test with output buffer \"%s\", expected unsupported: %s actual unsupported:"
1778                                 "%s expected bit profile: %x actual bit profile: %x\n",
1779                                 testdataptr->name,
1780                                 testdataptr->expected_unsupported,
1781                                 unsupported,
1782                                 testdataptr->expected_profile,
1783                                 option_profile);
1784                         res = AST_TEST_FAIL;
1785                 } else {
1786                         ast_test_status_update(test, "\"%s\" passed got expected unsupported: %s and bit profile: %x\n",
1787                                 testdataptr->name,
1788                                 unsupported,
1789                                 option_profile);
1790                 }
1791
1792                 option_profile = parse_sip_options(testdataptr->input_options, NULL, 0);
1793                 if (option_profile != testdataptr->expected_profile) {
1794                         ast_test_status_update(test, "NULL output test \"%s\", expected bit profile: %x actual bit profile: %x\n",
1795                                 testdataptr->name,
1796                                 testdataptr->expected_profile,
1797                                 option_profile);
1798                         res = AST_TEST_FAIL;
1799                 } else {
1800                         ast_test_status_update(test, "\"%s\" with NULL output buf passed, bit profile: %x\n",
1801                                 testdataptr->name,
1802                                 option_profile);
1803                 }
1804         }
1805
1806         return res;
1807 }
1808
1809 /*! \brief helper routine for sip_uri_cmp to compare URI parameters
1810  *
1811  * This takes the parameters from two SIP URIs and determines
1812  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
1813  * 1. If a parameter appears in both URIs, then they must have the same value
1814  *    in order for the URIs to match
1815  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
1816  *    URI must also have that parameter and must have the same value
1817  *    in order for the URIs to match
1818  * 3. All other headers appearing in only one URI are not considered when
1819  *    determining if URIs match
1820  *
1821  * \param input1 Parameters from URI 1
1822  * \param input2 Parameters from URI 2
1823  * \retval 0 URIs' parameters match
1824  * \retval nonzero URIs' parameters do not match
1825  */
1826 static int sip_uri_params_cmp(const char *input1, const char *input2)
1827 {
1828         char *params1 = NULL;
1829         char *params2 = NULL;
1830         char *pos1;
1831         char *pos2;
1832         int zerolength1 = 0;
1833         int zerolength2 = 0;
1834         int maddrmatch = 0;
1835         int ttlmatch = 0;
1836         int usermatch = 0;
1837         int methodmatch = 0;
1838
1839         if (ast_strlen_zero(input1)) {
1840                 zerolength1 = 1;
1841         } else {
1842                 params1 = ast_strdupa(input1);
1843         }
1844         if (ast_strlen_zero(input2)) {
1845                 zerolength2 = 1;
1846         } else {
1847                 params2 = ast_strdupa(input2);
1848         }
1849
1850         /* Quick optimization. If both params are zero-length, then
1851          * they match
1852          */
1853         if (zerolength1 && zerolength2) {
1854                 return 0;
1855         }
1856
1857         for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
1858                 char *value1 = pos1;
1859                 char *name1 = strsep(&value1, "=");
1860                 char *params2dup = NULL;
1861                 int matched = 0;
1862                 if (!value1) {
1863                         value1 = "";
1864                 }
1865                 /* Checkpoint reached. We have the name and value parsed for param1
1866                  * We have to duplicate params2 each time through this loop
1867                  * or else the inner loop below will not work properly.
1868                  */
1869                 if (!zerolength2) {
1870                         params2dup = ast_strdupa(params2);
1871                 }
1872                 for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
1873                         char *name2 = pos2;
1874                         char *value2 = strchr(pos2, '=');
1875                         if (!value2) {
1876                                 value2 = "";
1877                         } else {
1878                                 *value2++ = '\0';
1879                         }
1880                         if (!strcasecmp(name1, name2)) {
1881                                 if (strcasecmp(value1, value2)) {
1882                                         goto fail;
1883                                 } else {
1884                                         matched = 1;
1885                                         break;
1886                                 }
1887                         }
1888                 }
1889                 /* Check to see if the parameter is one of the 'must-match' parameters */
1890                 if (!strcasecmp(name1, "maddr")) {
1891                         if (matched) {
1892                                 maddrmatch = 1;
1893                         } else {
1894                                 goto fail;
1895                         }
1896                 } else if (!strcasecmp(name1, "ttl")) {
1897                         if (matched) {
1898                                 ttlmatch = 1;
1899                         } else {
1900                                 goto fail;
1901                         }
1902                 } else if (!strcasecmp(name1, "user")) {
1903                         if (matched) {
1904                                 usermatch = 1;
1905                         } else {
1906                                 goto fail;
1907                         }
1908                 } else if (!strcasecmp(name1, "method")) {
1909                         if (matched) {
1910                                 methodmatch = 1;
1911                         } else {
1912                                 goto fail;
1913                         }
1914                 }
1915         }
1916
1917         /* We've made it out of that horrible O(m*n) construct and there are no
1918          * failures yet. We're not done yet, though, because params2 could have
1919          * an maddr, ttl, user, or method header and params1 did not.
1920          */
1921         for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
1922                 char *value2 = pos2;
1923                 char *name2 = strsep(&value2, "=");
1924                 if (!value2) {
1925                         value2 = "";
1926                 }
1927                 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
1928                                 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
1929                                 (!strcasecmp(name2, "user") && !usermatch) ||
1930                                 (!strcasecmp(name2, "method") && !methodmatch)) {
1931                         goto fail;
1932                 }
1933         }
1934         return 0;
1935
1936 fail:
1937         return 1;
1938 }
1939
1940 /*! \brief helper routine for sip_uri_cmp to compare URI headers
1941  *
1942  * This takes the headers from two SIP URIs and determines
1943  * if the URIs match. The rules for headers is simple. If a header
1944  * appears in one URI, then it must also appear in the other URI. The
1945  * order in which the headers appear does not matter.
1946  *
1947  * \param input1 Headers from URI 1
1948  * \param input2 Headers from URI 2
1949  * \retval 0 URI headers match
1950  * \retval nonzero URI headers do not match
1951  */
1952 static int sip_uri_headers_cmp(const char *input1, const char *input2)
1953 {
1954         char *headers1 = NULL;
1955         char *headers2 = NULL;
1956         int zerolength1 = 0;
1957         int zerolength2 = 0;
1958         int different = 0;
1959         char *header1;
1960
1961         if (ast_strlen_zero(input1)) {
1962                 zerolength1 = 1;
1963         } else {
1964                 headers1 = ast_strdupa(input1);
1965         }
1966
1967         if (ast_strlen_zero(input2)) {
1968                 zerolength2 = 1;
1969         } else {
1970                 headers2 = ast_strdupa(input2);
1971         }
1972
1973         /* If one URI contains no headers and the other
1974          * does, then they cannot possibly match
1975          */
1976         if (zerolength1 != zerolength2) {
1977                 return 1;
1978         }
1979
1980         if (zerolength1 && zerolength2)
1981                 return 0;
1982
1983         /* At this point, we can definitively state that both inputs are
1984          * not zero-length. First, one more optimization. If the length
1985          * of the headers is not equal, then we definitely have no match
1986          */
1987         if (strlen(headers1) != strlen(headers2)) {
1988                 return 1;
1989         }
1990
1991         for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
1992                 if (!strcasestr(headers2, header1)) {
1993                         different = 1;
1994                         break;
1995                 }
1996         }
1997
1998         return different;
1999 }
2000
2001 /*!
2002  * \brief Compare domain sections of SIP URIs
2003  *
2004  * For hostnames, a case insensitive string comparison is
2005  * used. For IP addresses, a binary comparison is used. This
2006  * is mainly because IPv6 addresses have many ways of writing
2007  * the same address.
2008  *
2009  * For specifics about IP address comparison, see the following
2010  * document: http://tools.ietf.org/html/draft-ietf-sip-ipv6-abnf-fix-05
2011  *
2012  * \param host1 The domain from the first URI
2013  * \param host2 THe domain from the second URI
2014  * \retval 0 The domains match
2015  * \retval nonzero The domains do not match
2016  */
2017 static int sip_uri_domain_cmp(const char *host1, const char *host2)
2018 {
2019         struct ast_sockaddr addr1;
2020         struct ast_sockaddr addr2;
2021         int addr1_parsed;
2022         int addr2_parsed;
2023
2024         addr1_parsed = ast_sockaddr_parse(&addr1, host1, 0);
2025         addr2_parsed = ast_sockaddr_parse(&addr2, host2, 0);
2026
2027         if (addr1_parsed != addr2_parsed) {
2028                 /* One domain was an IP address and the other had
2029                  * a host name. FAIL!
2030                  */
2031                 return 1;
2032         }
2033
2034         /* Both are host names. A string comparison will work
2035          * perfectly here. Specifying the "C" locale ensures that
2036          * The LC_CTYPE conventions use those defined in ANSI C,
2037          * i.e. ASCII.
2038          */
2039         if (!addr1_parsed) {
2040 #ifdef HAVE_XLOCALE_H
2041                 if(!c_locale) {
2042                         return strcasecmp(host1, host2);
2043                 } else {
2044                         return strcasecmp_l(host1, host2, c_locale);
2045                 }
2046 #else
2047                 return strcasecmp(host1, host2);
2048 #endif
2049         }
2050
2051         /* Both contain IP addresses */
2052         return ast_sockaddr_cmp(&addr1, &addr2);
2053 }
2054
2055 int sip_uri_cmp(const char *input1, const char *input2)
2056 {
2057         char *uri1;
2058         char *uri2;
2059         char *uri_scheme1;
2060         char *uri_scheme2;
2061         char *host1;
2062         char *host2;
2063         char *params1;
2064         char *params2;
2065         char *headers1;
2066         char *headers2;
2067
2068         /* XXX It would be really nice if we could just use parse_uri_full() here
2069          * to separate the components of the URI, but unfortunately it is written
2070          * in a way that can cause URI parameters to be discarded.
2071          */
2072
2073         if (!input1 || !input2) {
2074                 return 1;
2075         }
2076
2077         uri1 = ast_strdupa(input1);
2078         uri2 = ast_strdupa(input2);
2079
2080         ast_uri_decode(uri1, ast_uri_sip_user);
2081         ast_uri_decode(uri2, ast_uri_sip_user);
2082
2083         uri_scheme1 = strsep(&uri1, ":");
2084         uri_scheme2 = strsep(&uri2, ":");
2085
2086         if (strcmp(uri_scheme1, uri_scheme2)) {
2087                 return 1;
2088         }
2089
2090         /* This function is tailored for SIP and SIPS URIs. There's no
2091          * need to check uri_scheme2 since we have determined uri_scheme1
2092          * and uri_scheme2 are equivalent already.
2093          */
2094         if (strcmp(uri_scheme1, "sip") && strcmp(uri_scheme1, "sips")) {
2095                 return 1;
2096         }
2097
2098         if (ast_strlen_zero(uri1) || ast_strlen_zero(uri2)) {
2099                 return 1;
2100         }
2101
2102         if ((host1 = strchr(uri1, '@'))) {
2103                 *host1++ = '\0';
2104         }
2105         if ((host2 = strchr(uri2, '@'))) {
2106                 *host2++ = '\0';
2107         }
2108
2109         /* Check for mismatched username and passwords. This is the
2110          * only case-sensitive comparison of a SIP URI
2111          */
2112         if ((host1 && !host2) ||
2113                         (host2 && !host1) ||
2114                         (host1 && host2 && strcmp(uri1, uri2))) {
2115                 return 1;
2116         }
2117
2118         if (!host1) {
2119                 host1 = uri1;
2120         }
2121         if (!host2) {
2122                 host2 = uri2;
2123         }
2124
2125         /* Strip off the parameters and headers so we can compare
2126          * host and port
2127          */
2128
2129         if ((params1 = strchr(host1, ';'))) {
2130                 *params1++ = '\0';
2131         }
2132         if ((params2 = strchr(host2, ';'))) {
2133                 *params2++ = '\0';
2134         }
2135
2136         /* Headers come after parameters, but there may be headers without
2137          * parameters, thus the S_OR
2138          */
2139         if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
2140                 *headers1++ = '\0';
2141         }
2142         if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
2143                 *headers2++ = '\0';
2144         }
2145
2146         if (sip_uri_domain_cmp(host1, host2)) {
2147                 return 1;
2148         }
2149
2150         /* Headers have easier rules to follow, so do those first */
2151         if (sip_uri_headers_cmp(headers1, headers2)) {
2152                 return 1;
2153         }
2154
2155         /* And now the parameters. Ugh */
2156         return sip_uri_params_cmp(params1, params2);
2157 }
2158
2159 #define URI_CMP_MATCH 0
2160 #define URI_CMP_NOMATCH 1
2161
2162 AST_TEST_DEFINE(sip_uri_cmp_test)
2163 {
2164         static const struct {
2165                 const char *uri1;
2166                 const char *uri2;
2167                 int expected_result;
2168         } uri_cmp_tests [] = {
2169                 /* These are identical, so they match */
2170                 { "sip:bob@example.com", "sip:bob@example.com", URI_CMP_MATCH },
2171                 /* Different usernames. No match */
2172                 { "sip:alice@example.com", "sip:bob@example.com", URI_CMP_NOMATCH },
2173                 /* Different hosts. No match */
2174                 { "sip:bob@example.com", "sip:bob@examplez.com", URI_CMP_NOMATCH },
2175                 /* Now start using IP addresses. Identical, so they match */
2176                 { "sip:bob@1.2.3.4", "sip:bob@1.2.3.4", URI_CMP_MATCH },
2177                 /* Two identical IPv4 addresses represented differently. Match */
2178                 { "sip:bob@1.2.3.4", "sip:bob@001.002.003.004", URI_CMP_MATCH },
2179                 /* Logically equivalent IPv4 Address and hostname. No Match */
2180                 { "sip:bob@127.0.0.1", "sip:bob@localhost", URI_CMP_NOMATCH },
2181                 /* Logically equivalent IPv6 address and hostname. No Match */
2182                 { "sip:bob@[::1]", "sip:bob@localhost", URI_CMP_NOMATCH },
2183                 /* Try an IPv6 one as well */
2184                 { "sip:bob@[2001:db8::1234]", "sip:bob@[2001:db8::1234]", URI_CMP_MATCH },
2185                 /* Two identical IPv6 addresses represented differently. Match */
2186                 { "sip:bob@[2001:db8::1234]", "sip:bob@[2001:0db8::1234]", URI_CMP_MATCH },
2187                 /* Different ports. No match */
2188                 { "sip:bob@1.2.3.4:5060", "sip:bob@1.2.3.4:5061", URI_CMP_NOMATCH },
2189                 /* Same port logically, but only one address specifies it. No match */
2190                 { "sip:bob@1.2.3.4:5060", "sip:bob@1.2.3.4", URI_CMP_NOMATCH },
2191                 /* And for safety, try with IPv6 */
2192                 { "sip:bob@[2001:db8:1234]:5060", "sip:bob@[2001:db8:1234]", URI_CMP_NOMATCH },
2193                 /* User comparison is case sensitive. No match */
2194                 { "sip:bob@example.com", "sip:BOB@example.com", URI_CMP_NOMATCH },
2195                 /* Host comparison is case insensitive. Match */
2196                 { "sip:bob@example.com", "sip:bob@EXAMPLE.COM", URI_CMP_MATCH },
2197                 /* Add headers to the URI. Identical, so they match */
2198                 { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com?header1=value1&header2=value2", URI_CMP_MATCH },
2199                 /* Headers in URI 1 are not in URI 2. No Match */
2200                 { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com", URI_CMP_NOMATCH },
2201                 /* Header present in both URIs does not have matching values. No match */
2202                 { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com?header1=value1&header2=value3", URI_CMP_NOMATCH },
2203                 /* Add parameters to the URI. Identical so they match */
2204                 { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com;param1=value1;param2=value2", URI_CMP_MATCH },
2205                 /* Same parameters in both URIs but appear in different order. Match */
2206                 { "sip:bob@example.com;param2=value2;param1=value1", "sip:bob@example.com;param1=value1;param2=value2", URI_CMP_MATCH },
2207                 /* params in URI 1 are not in URI 2. Match */
2208                 { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com", URI_CMP_MATCH },
2209                 /* param present in both URIs does not have matching values. No match */
2210                 { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com;param1=value1;param2=value3", URI_CMP_NOMATCH },
2211                 /* URI 1 has a maddr param but URI 2 does not. No match */
2212                 { "sip:bob@example.com;param1=value1;maddr=192.168.0.1", "sip:bob@example.com;param1=value1", URI_CMP_NOMATCH },
2213                 /* URI 1 and URI 2 both have identical maddr params. Match */
2214                 { "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 },
2215                 /* URI 1 is a SIPS URI and URI 2 is a SIP URI. No Match */
2216                 { "sips:bob@example.com", "sip:bob@example.com", URI_CMP_NOMATCH },
2217                 /* No URI schemes. No match */
2218                 { "bob@example.com", "bob@example.com", URI_CMP_NOMATCH },
2219                 /* Crashiness tests. Just an address scheme. No match */
2220                 { "sip", "sips", URI_CMP_NOMATCH },
2221                 /* Still just an address scheme. Even though they're the same, No match */
2222                 { "sip", "sip", URI_CMP_NOMATCH },
2223                 /* Empty strings. No match */
2224                 { "", "", URI_CMP_NOMATCH },
2225                 /* An empty string and a NULL. No match */
2226                 { "", NULL, URI_CMP_NOMATCH },
2227         };
2228         int i;
2229         int test_res = AST_TEST_PASS;
2230         switch (cmd) {
2231         case TEST_INIT:
2232                 info->name = "sip_uri_cmp_test";
2233                 info->category = "/channels/chan_sip/";
2234                 info->summary = "Tests comparison of SIP URIs";
2235                 info->description = "Several would-be tricky URI comparisons are performed";
2236                 return AST_TEST_NOT_RUN;
2237         case TEST_EXECUTE:
2238                 break;
2239         }
2240
2241         for (i = 0; i < ARRAY_LEN(uri_cmp_tests); ++i) {
2242                 int cmp_res1;
2243                 int cmp_res2;
2244                 if ((cmp_res1 = sip_uri_cmp(uri_cmp_tests[i].uri1, uri_cmp_tests[i].uri2))) {
2245                         /* URI comparison may return -1 or +1 depending on the failure. Standardize
2246                          * the return value to be URI_CMP_NOMATCH on any failure
2247                          */
2248                         cmp_res1 = URI_CMP_NOMATCH;
2249                 }
2250                 if (cmp_res1 != uri_cmp_tests[i].expected_result) {
2251                         ast_test_status_update(test, "Unexpected comparison result for URIs %s and %s. "
2252                                         "Expected %s but got %s\n", uri_cmp_tests[i].uri1, uri_cmp_tests[i].uri2,
2253                                         uri_cmp_tests[i].expected_result == URI_CMP_MATCH ? "Match" : "No Match",
2254                                         cmp_res1 == URI_CMP_MATCH ? "Match" : "No Match");
2255                         test_res = AST_TEST_FAIL;
2256                 }
2257
2258                 /* All URI comparisons are commutative, so for the sake of being thorough, we'll
2259                  * rerun the comparison with the parameters reversed
2260                  */
2261                 if ((cmp_res2 = sip_uri_cmp(uri_cmp_tests[i].uri2, uri_cmp_tests[i].uri1))) {
2262                         /* URI comparison may return -1 or +1 depending on the failure. Standardize
2263                          * the return value to be URI_CMP_NOMATCH on any failure
2264                          */
2265                         cmp_res2 = URI_CMP_NOMATCH;
2266                 }
2267                 if (cmp_res2 != uri_cmp_tests[i].expected_result) {
2268                         ast_test_status_update(test, "Unexpected comparison result for URIs %s and %s. "
2269                                         "Expected %s but got %s\n", uri_cmp_tests[i].uri2, uri_cmp_tests[i].uri1,
2270                                         uri_cmp_tests[i].expected_result == URI_CMP_MATCH ? "Match" : "No Match",
2271                                         cmp_res2 == URI_CMP_MATCH ? "Match" : "No Match");
2272                         test_res = AST_TEST_FAIL;
2273                 }
2274         }
2275
2276         return test_res;
2277 }
2278
2279 void free_via(struct sip_via *v)
2280 {
2281         if (!v) {
2282                 return;
2283         }
2284
2285         ast_free(v->via);
2286         ast_free(v);
2287 }
2288
2289 struct sip_via *parse_via(const char *header)
2290 {
2291         struct sip_via *v = ast_calloc(1, sizeof(*v));
2292         char *via, *parm;
2293
2294         if (!v) {
2295                 return NULL;
2296         }
2297
2298         v->via = ast_strdup(header);
2299         v->ttl = 1;
2300
2301         via = v->via;
2302
2303         if (ast_strlen_zero(via)) {
2304                 ast_log(LOG_ERROR, "received request without a Via header\n");
2305                 free_via(v);
2306                 return NULL;
2307         }
2308
2309         /* seperate the first via-parm */
2310         via = strsep(&via, ",");
2311
2312         /* chop off sent-protocol */
2313         v->protocol = strsep(&via, " \t\r\n");
2314         if (ast_strlen_zero(v->protocol)) {
2315                 ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
2316                 free_via(v);
2317                 return NULL;
2318         }
2319         v->protocol = ast_skip_blanks(v->protocol);
2320
2321         if (via) {
2322                 via = ast_skip_blanks(via);
2323         }
2324
2325         /* chop off sent-by */
2326         v->sent_by = strsep(&via, "; \t\r\n");
2327         if (ast_strlen_zero(v->sent_by)) {
2328                 ast_log(LOG_ERROR, "missing sent-by in Via header\n");
2329                 free_via(v);
2330                 return NULL;
2331         }
2332         v->sent_by = ast_skip_blanks(v->sent_by);
2333
2334         /* store the port, we have to handle ipv6 addresses containing ':'
2335          * characters gracefully */
2336         if (((parm = strchr(v->sent_by, ']')) && *(++parm) == ':') || (parm = strchr(v->sent_by, ':'))) {
2337                 char *endptr;
2338
2339                 v->port = strtol(++parm, &endptr, 10);
2340         }
2341
2342         /* evaluate any via-parms */
2343         while ((parm = strsep(&via, "; \t\r\n"))) {
2344                 char *c;
2345                 if ((c = strstr(parm, "maddr="))) {
2346                         v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
2347                 } else if ((c = strstr(parm, "branch="))) {
2348                         v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
2349                 } else if ((c = strstr(parm, "ttl="))) {
2350                         char *endptr;
2351                         c = ast_skip_blanks(c + sizeof("ttl=") - 1);
2352                         v->ttl = strtol(c, &endptr, 10);
2353
2354                         /* make sure we got a valid ttl value */
2355                         if (c == endptr) {
2356                                 v->ttl = 1;
2357                         }
2358                 }
2359         }
2360
2361         return v;
2362 }
2363
2364 AST_TEST_DEFINE(parse_via_test)
2365 {
2366         int res = AST_TEST_PASS;
2367         int i = 1;
2368         struct sip_via *via;
2369         struct testdata {
2370                 char *in;
2371                 char *expected_protocol;
2372                 char *expected_branch;
2373                 char *expected_sent_by;
2374                 char *expected_maddr;
2375                 unsigned int expected_port;
2376                 unsigned char expected_ttl;
2377                 int expected_null;
2378                 AST_LIST_ENTRY(testdata) list;
2379         };
2380         struct testdata *testdataptr;
2381         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
2382         struct testdata t1 = {
2383                 .in = "SIP/2.0/UDP host:port;branch=thebranch",
2384                 .expected_protocol = "SIP/2.0/UDP",
2385                 .expected_sent_by = "host:port",
2386                 .expected_branch = "thebranch",
2387         };
2388         struct testdata t2 = {
2389                 .in = "SIP/2.0/UDP host:port",
2390                 .expected_protocol = "SIP/2.0/UDP",
2391                 .expected_sent_by = "host:port",
2392                 .expected_branch = "",
2393         };
2394         struct testdata t3 = {
2395                 .in = "SIP/2.0/UDP",
2396                 .expected_null = 1,
2397         };
2398         struct testdata t4 = {
2399                 .in = "BLAH/BLAH/BLAH host:port;branch=",
2400                 .expected_protocol = "BLAH/BLAH/BLAH",
2401                 .expected_sent_by = "host:port",
2402                 .expected_branch = "",
2403         };
2404         struct testdata t5 = {
2405                 .in = "SIP/2.0/UDP host:5060;branch=thebranch;maddr=224.0.0.1;ttl=1",
2406                 .expected_protocol = "SIP/2.0/UDP",
2407                 .expected_sent_by = "host:5060",
2408                 .expected_port = 5060,
2409                 .expected_branch = "thebranch",
2410                 .expected_maddr = "224.0.0.1",
2411                 .expected_ttl = 1,
2412         };
2413         struct testdata t6 = {
2414                 .in = "SIP/2.0/UDP      host:5060;\n   branch=thebranch;\r\n  maddr=224.0.0.1;   ttl=1",
2415                 .expected_protocol = "SIP/2.0/UDP",
2416                 .expected_sent_by = "host:5060",
2417                 .expected_port = 5060,
2418                 .expected_branch = "thebranch",
2419                 .expected_maddr = "224.0.0.1",
2420                 .expected_ttl = 1,
2421         };
2422         struct testdata t7 = {
2423                 .in = "SIP/2.0/UDP [::1]:5060",
2424                 .expected_protocol = "SIP/2.0/UDP",
2425                 .expected_sent_by = "[::1]:5060",
2426                 .expected_port = 5060,
2427                 .expected_branch = "",
2428         };
2429         switch (cmd) {
2430         case TEST_INIT:
2431                 info->name = "parse_via_test";
2432                 info->category = "/channels/chan_sip/";
2433                 info->summary = "Tests parsing the Via header";
2434                 info->description =
2435                                 "Runs through various test situations in which various "
2436                                 " parameters parameter must be extracted from a VIA header";
2437                 return AST_TEST_NOT_RUN;
2438         case TEST_EXECUTE:
2439                 break;
2440         }
2441
2442         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &t1);
2443         AST_LIST_INSERT_TAIL(&testdatalist, &t2, list);
2444         AST_LIST_INSERT_TAIL(&testdatalist, &t3, list);
2445         AST_LIST_INSERT_TAIL(&testdatalist, &t4, list);
2446         AST_LIST_INSERT_TAIL(&testdatalist, &t5, list);
2447         AST_LIST_INSERT_TAIL(&testdatalist, &t6, list);
2448         AST_LIST_INSERT_TAIL(&testdatalist, &t7, list);
2449
2450
2451         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
2452                 via = parse_via(testdataptr->in);
2453                 if (!via) {
2454                         if (!testdataptr->expected_null) {
2455                                 ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2456                                         "failed to parse header\n",
2457                                 i, testdataptr->in);
2458                                 res = AST_TEST_FAIL;
2459                         }
2460                         i++;
2461                         continue;
2462                 }
2463
2464                 if (testdataptr->expected_null) {
2465                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2466                                 "successfully parased invalid via header\n",
2467                         i, testdataptr->in);
2468                         res = AST_TEST_FAIL;
2469                         free_via(via);
2470                         i++;
2471                         continue;
2472                 }
2473
2474                 if ((ast_strlen_zero(via->protocol) && !ast_strlen_zero(testdataptr->expected_protocol))
2475                         || (!ast_strlen_zero(via->protocol) && strcmp(via->protocol, testdataptr->expected_protocol))) {
2476
2477                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2478                                 "parsed protocol = \"%s\"\n"
2479                                 "expected = \"%s\"\n"
2480                                 "failed to parse protocol\n",
2481                         i, testdataptr->in, via->protocol, testdataptr->expected_protocol);
2482                         res = AST_TEST_FAIL;
2483                 }
2484
2485                 if ((ast_strlen_zero(via->sent_by) && !ast_strlen_zero(testdataptr->expected_sent_by))
2486                         || (!ast_strlen_zero(via->sent_by) && strcmp(via->sent_by, testdataptr->expected_sent_by))) {
2487
2488                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2489                                 "parsed sent_by = \"%s\"\n"
2490                                 "expected = \"%s\"\n"
2491                                 "failed to parse sent-by\n",
2492                         i, testdataptr->in, via->sent_by, testdataptr->expected_sent_by);
2493                         res = AST_TEST_FAIL;
2494                 }
2495
2496                 if (testdataptr->expected_port && testdataptr->expected_port != via->port) {
2497                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2498                                 "parsed port = \"%d\"\n"
2499                                 "expected = \"%d\"\n"
2500                                 "failed to parse port\n",
2501                         i, testdataptr->in, via->port, testdataptr->expected_port);
2502                         res = AST_TEST_FAIL;
2503                 }
2504
2505                 if ((ast_strlen_zero(via->branch) && !ast_strlen_zero(testdataptr->expected_branch))
2506                         || (!ast_strlen_zero(via->branch) && strcmp(via->branch, testdataptr->expected_branch))) {
2507
2508                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2509                                 "parsed branch = \"%s\"\n"
2510                                 "expected = \"%s\"\n"
2511                                 "failed to parse branch\n",
2512                         i, testdataptr->in, via->branch, testdataptr->expected_branch);
2513                         res = AST_TEST_FAIL;
2514                 }
2515
2516                 if ((ast_strlen_zero(via->maddr) && !ast_strlen_zero(testdataptr->expected_maddr))
2517                         || (!ast_strlen_zero(via->maddr) && strcmp(via->maddr, testdataptr->expected_maddr))) {
2518
2519                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2520                                 "parsed maddr = \"%s\"\n"
2521                                 "expected = \"%s\"\n"
2522                                 "failed to parse maddr\n",
2523                         i, testdataptr->in, via->maddr, testdataptr->expected_maddr);
2524                         res = AST_TEST_FAIL;
2525                 }
2526
2527                 if (testdataptr->expected_ttl && testdataptr->expected_ttl != via->ttl) {
2528                         ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
2529                                 "parsed ttl = \"%d\"\n"
2530                                 "expected = \"%d\"\n"
2531                                 "failed to parse ttl\n",
2532                         i, testdataptr->in, via->ttl, testdataptr->expected_ttl);
2533                         res = AST_TEST_FAIL;
2534                 }
2535
2536                 free_via(via);
2537                 i++;
2538         }
2539         return res;
2540 }
2541
2542 void sip_request_parser_register_tests(void)
2543 {
2544         AST_TEST_REGISTER(get_calleridname_test);
2545         AST_TEST_REGISTER(sip_parse_uri_test);
2546         AST_TEST_REGISTER(get_in_brackets_test);
2547         AST_TEST_REGISTER(get_name_and_number_test);
2548         AST_TEST_REGISTER(sip_parse_uri_fully_test);
2549         AST_TEST_REGISTER(parse_name_andor_addr_test);
2550         AST_TEST_REGISTER(parse_contact_header_test);
2551         AST_TEST_REGISTER(sip_parse_options_test);
2552         AST_TEST_REGISTER(sip_uri_cmp_test);
2553         AST_TEST_REGISTER(parse_via_test);
2554 }
2555 void sip_request_parser_unregister_tests(void)
2556 {
2557         AST_TEST_UNREGISTER(sip_parse_uri_test);
2558         AST_TEST_UNREGISTER(get_calleridname_test);
2559         AST_TEST_UNREGISTER(get_in_brackets_test);
2560         AST_TEST_UNREGISTER(get_name_and_number_test);
2561         AST_TEST_UNREGISTER(sip_parse_uri_fully_test);
2562         AST_TEST_UNREGISTER(parse_name_andor_addr_test);
2563         AST_TEST_UNREGISTER(parse_contact_header_test);
2564         AST_TEST_UNREGISTER(sip_parse_options_test);
2565         AST_TEST_UNREGISTER(sip_uri_cmp_test);
2566         AST_TEST_UNREGISTER(parse_via_test);
2567 }
2568
2569 int sip_reqresp_parser_init(void)
2570 {
2571 #ifdef HAVE_XLOCALE_H
2572         c_locale = newlocale(LC_CTYPE_MASK, "C", NULL);
2573         if (!c_locale) {
2574                 return -1;
2575         }
2576 #endif
2577         return 0;
2578 }
2579
2580 void sip_reqresp_parser_exit(void)
2581 {
2582 #ifdef HAVE_XLOCALE_H
2583         if (c_locale) {
2584                 freelocale(c_locale);
2585                 c_locale = NULL;
2586         }
2587 #endif
2588 }