Kill some startup warnings and errors and make some messages more helpful in tracking...
[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 /*! \brief * parses a URI in its components.*/
31 int parse_uri_full(char *uri, const char *scheme, char **user, char **pass,
32                    char **domain, struct uriparams *params, char **headers,
33                    char **residue)
34 {
35         char *userinfo = NULL;
36         char *parameters = NULL;
37         char *endparams = NULL;
38         char *c = NULL;
39         int error = 0;
40
41         /* check for valid input */
42         if (ast_strlen_zero(uri)) {
43                 return -1;
44         }
45
46         if (scheme) {
47                 int l;
48                 char *scheme2 = ast_strdupa(scheme);
49                 char *cur = strsep(&scheme2, ",");
50                 for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
51                         l = strlen(cur);
52                         if (!strncasecmp(uri, cur, l)) {
53                                 uri += l;
54                                 break;
55                         }
56                 }
57                 if (ast_strlen_zero(cur)) {
58                         ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
59                         error = -1;
60                 }
61         }
62
63         if (!domain) {
64                 /* if we don't want to split around domain, keep everything as a
65                  * userinfo - cos thats how old parse_uri operated*/
66                 userinfo = uri;
67         } else {
68                 char *dom = "";
69                 if ((c = strchr(uri, '@'))) {
70                         *c++ = '\0';
71                         dom = c;
72                         userinfo = uri;
73                         uri = c; /* userinfo can contain ? and ; chars so step forward before looking for params and headers */
74                 } else {
75                         /* domain-only URI, according to the SIP RFC. */
76                         dom = uri;
77                         userinfo = "";
78                         }
79
80                 *domain = dom;
81         }
82
83         if (pass && (c = strchr(userinfo, ':'))) {        /* user:password */
84                 *c++ = '\0';
85                 *pass = c;
86         } else if (pass) {
87                 *pass = "";
88         }
89
90         if (user) {
91                 *user = userinfo;
92         }
93
94         parameters = uri;
95         /* strip [?headers] from end of uri  - even if no header pointer exists*/
96         if ((c = strrchr(uri, '?'))) {
97                         *c++ = '\0';
98                 uri = c;
99                 if (headers) {
100                         *headers = c;
101                 }
102                 if ((c = strrchr(uri, ';'))) {
103                         *c++ = '\0';
104                 } else {
105                         c = strrchr(uri, '\0');
106                 }
107                 uri = c; /* residue */
108
109
110         } else if (headers) {
111                 *headers = "";
112         }
113
114         /* parse parameters */
115         endparams = strchr(parameters,'\0');
116         if ((c = strchr(parameters, ';'))) {
117                         *c++ = '\0';
118                 parameters = c;
119         } else {
120                 parameters = endparams;
121                 }
122
123         if (params) {
124                 char *rem = parameters; /* unparsed or unrecognised remainder */
125                 char *label;
126                 char *value;
127                 int lr = 0;
128
129                 params->transport = "";
130                 params->user = "";
131                 params->method = "";
132                 params->ttl = "";
133                 params->maddr = "";
134                 params->lr = 0;
135
136                 rem = parameters;
137
138                 while ((value = strchr(parameters, '=')) || (lr = !strncmp(parameters, "lr", 2))) {
139                         /* The while condition will not continue evaluation to set lr if it matches "lr=" */
140                         if (lr) {
141                                 value = parameters;
142                         } else {
143                                 *value++ = '\0';
144                         }
145                         label = parameters;
146                         if ((c = strchr(value, ';'))) {
147                         *c++ = '\0';
148                                 parameters = c;
149                         } else {
150                                 parameters = endparams;
151                 }
152
153                         if (!strcmp(label, "transport")) {
154                                 if (params) {params->transport=value;}
155                                 rem = parameters;
156                         } else if (!strcmp(label, "user")) {
157                                 if (params) {params->user=value;}
158                                 rem = parameters;
159                         } else if (!strcmp(label, "method")) {
160                                 if (params) {params->method=value;}
161                                 rem = parameters;
162                         } else if (!strcmp(label, "ttl")) {
163                                 if (params) {params->ttl=value;}
164                                 rem = parameters;
165                         } else if (!strcmp(label, "maddr")) {
166                                 if (params) {params->maddr=value;}
167                                 rem = parameters;
168                         /* 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 */
169                         } else if ((!strcmp(label, "lr") && strcmp(value, "no") && strcmp(value, "off") && strcmp(value, "0") && strcmp(value, "")) || ((lr) && strcmp(value, "lr"))) {
170                                 if (params) {params->lr=1;}
171                                 rem = parameters;
172                         } else {
173                                 value--;
174                                 *value = '=';
175                                 if(c) {
176                                 c--;
177                                 *c = ';';
178         }
179                         }
180                 }
181                 if (rem > uri) { /* no headers */
182                         uri = rem;
183                 }
184
185         }
186
187         if (residue) {
188                 *residue = uri;
189         }
190
191         return error;
192 }
193
194
195 AST_TEST_DEFINE(sip_parse_uri_fully_test)
196 {
197         int res = AST_TEST_PASS;
198         char uri[1024];
199         char *user, *pass, *domain, *headers, *residue;
200         struct uriparams params;
201
202         struct testdata {
203                 char *desc;
204                 char *uri;
205                 char **userptr;
206                 char **passptr;
207                 char **domainptr;
208                 char **headersptr;
209                 char **residueptr;
210                 struct uriparams *paramsptr;
211                 char *user;
212                 char *pass;
213                 char *domain;
214                 char *headers;
215                 char *residue;
216                 struct uriparams params;
217                 AST_LIST_ENTRY(testdata) list;
218         };
219
220
221         struct testdata *testdataptr;
222
223         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
224
225         struct testdata td1 = {
226                 .desc = "no headers",
227                 .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;param2=residue",
228                 .userptr = &user,
229                 .passptr = &pass,
230                 .domainptr = &domain,
231                 .headersptr = &headers,
232                 .residueptr = &residue,
233                 .paramsptr = &params,
234                 .user = "user",
235                 .pass = "secret",
236                 .domain = "host:5060",
237                 .headers = "",
238                 .residue = "param2=residue",
239                 .params.transport = "tcp",
240                 .params.lr = 0,
241                 .params.user = ""
242         };
243
244         struct testdata td2 = {
245                 .desc = "with headers",
246                 .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;param2=discard2?header=blah&header2=blah2;param3=residue",
247                 .userptr = &user,
248                 .passptr = &pass,
249                 .domainptr = &domain,
250                 .headersptr = &headers,
251                 .residueptr = &residue,
252                 .paramsptr = &params,
253                 .user = "user",
254                 .pass = "secret",
255                 .domain = "host:5060",
256                 .headers = "header=blah&header2=blah2",
257                 .residue = "param3=residue",
258                 .params.transport = "tcp",
259                 .params.lr = 0,
260                 .params.user = ""
261         };
262
263         struct testdata td3 = {
264                 .desc = "difficult user",
265                 .uri = "sip:-_.!~*'()&=+$,;?/:secret@host:5060;transport=tcp",
266                 .userptr = &user,
267                 .passptr = &pass,
268                 .domainptr = &domain,
269                 .headersptr = &headers,
270                 .residueptr = &residue,
271                 .paramsptr = &params,
272                 .user = "-_.!~*'()&=+$,;?/",
273                 .pass = "secret",
274                 .domain = "host:5060",
275                 .headers = "",
276                 .residue = "",
277                 .params.transport = "tcp",
278                 .params.lr = 0,
279                 .params.user = ""
280         };
281
282         struct testdata td4 = {
283                 .desc = "difficult pass",
284                 .uri = "sip:user:-_.!~*'()&=+$,@host:5060;transport=tcp",
285                 .userptr = &user,
286                 .passptr = &pass,
287                 .domainptr = &domain,
288                 .headersptr = &headers,
289                 .residueptr = &residue,
290                 .paramsptr = &params,
291                 .user = "user",
292                 .pass = "-_.!~*'()&=+$,",
293                 .domain = "host:5060",
294                 .headers = "",
295                 .residue = "",
296                 .params.transport = "tcp",
297                 .params.lr = 0,
298                 .params.user = ""
299         };
300
301         struct testdata td5 = {
302                 .desc = "difficult host",
303                 .uri = "sip:user:secret@1-1.a-1.:5060;transport=tcp",
304                 .userptr = &user,
305                 .passptr = &pass,
306                 .domainptr = &domain,
307                 .headersptr = &headers,
308                 .residueptr = &residue,
309                 .paramsptr = &params,
310                 .user = "user",
311                 .pass = "secret",
312                 .domain = "1-1.a-1.:5060",
313                 .headers = "",
314                 .residue = "",
315                 .params.transport = "tcp",
316                 .params.lr = 0,
317                 .params.user = ""
318         };
319
320         struct testdata td6 = {
321                 .desc = "difficult params near transport",
322                 .uri = "sip:user:secret@host:5060;-_.!~*'()[]/:&+$=-_.!~*'()[]/:&+$;transport=tcp",
323                 .userptr = &user,
324                 .passptr = &pass,
325                 .domainptr = &domain,
326                 .headersptr = &headers,
327                 .residueptr = &residue,
328                 .paramsptr = &params,
329                 .user = "user",
330                 .pass = "secret",
331                 .domain = "host:5060",
332                 .headers = "",
333                 .residue = "",
334                 .params.transport = "tcp",
335                 .params.lr = 0,
336                 .params.user = ""
337         };
338
339         struct testdata td7 = {
340                 .desc = "difficult params near headers",
341                 .uri = "sip:user:secret@host:5060;-_.!~*'()[]/:&+$=-_.!~*'()[]/:&+$?header=blah&header2=blah2;-_.!~*'()[]/:&+$=residue",
342                 .userptr = &user,
343                 .passptr = &pass,
344                 .domainptr = &domain,
345                 .headersptr = &headers,
346                 .residueptr = &residue,
347                 .paramsptr = &params,
348                 .user = "user",
349                 .pass = "secret",
350                 .domain = "host:5060",
351                 .headers = "header=blah&header2=blah2",
352                 .residue = "-_.!~*'()[]/:&+$=residue",
353                 .params.transport = "",
354                 .params.lr = 0,
355                 .params.user = ""
356         };
357
358         struct testdata td8 = {
359                 .desc = "lr parameter",
360                 .uri = "sip:user:secret@host:5060;param=discard;lr?header=blah",
361                 .userptr = &user,
362                 .passptr = &pass,
363                 .domainptr = &domain,
364                 .headersptr = &headers,
365                 .residueptr = &residue,
366                 .paramsptr = &params,
367                 .user = "user",
368                 .pass = "secret",
369                 .domain = "host:5060",
370                 .headers = "header=blah",
371                 .residue = "",
372                 .params.transport = "",
373                 .params.lr = 1,
374                 .params.user = ""
375         };
376
377         struct testdata td9 = {
378                 .desc = "alternative lr parameter",
379                 .uri = "sip:user:secret@host:5060;param=discard;lr=yes?header=blah",
380                 .userptr = &user,
381                 .passptr = &pass,
382                 .domainptr = &domain,
383                 .headersptr = &headers,
384                 .residueptr = &residue,
385                 .paramsptr = &params,
386                 .user = "user",
387                 .pass = "secret",
388                 .domain = "host:5060",
389                 .headers = "header=blah",
390                 .residue = "",
391                 .params.transport = "",
392                 .params.lr = 1,
393                 .params.user = ""
394         };
395
396         struct testdata td10 = {
397                 .desc = "no lr parameter",
398                 .uri = "sip:user:secret@host:5060;paramlr=lr;lr=no;lr=off;lr=0;lr=;=lr;lrextra;lrparam2=lr?header=blah",
399                 .userptr = &user,
400                 .passptr = &pass,
401                 .domainptr = &domain,
402                 .headersptr = &headers,
403                 .residueptr = &residue,
404                 .paramsptr = &params,
405                 .user = "user",
406                 .pass = "secret",
407                 .domain = "host:5060",
408                 .headers = "header=blah",
409                 .residue = "",
410                 .params.transport = "",
411                 .params.lr = 0,
412                 .params.user = ""
413         };
414
415
416         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
417         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
418         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
419         AST_LIST_INSERT_TAIL(&testdatalist, &td4, list);
420         AST_LIST_INSERT_TAIL(&testdatalist, &td5, list);
421         AST_LIST_INSERT_TAIL(&testdatalist, &td6, list);
422         AST_LIST_INSERT_TAIL(&testdatalist, &td7, list);
423         AST_LIST_INSERT_TAIL(&testdatalist, &td8, list);
424         AST_LIST_INSERT_TAIL(&testdatalist, &td9, list);
425         AST_LIST_INSERT_TAIL(&testdatalist, &td10, list);
426
427
428         switch (cmd) {
429         case TEST_INIT:
430                 info->name = "sip_uri_full_parse_test";
431                 info->category = "/channels/chan_sip/";
432                 info->summary = "tests sip full uri parsing";
433                 info->description =
434                         "Tests full parsing of various URIs "
435                         "Verifies output matches expected behavior.";
436                 return AST_TEST_NOT_RUN;
437         case TEST_EXECUTE:
438                 break;
439         }
440
441         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
442                 user = pass = domain = headers = residue = NULL;
443                 params.transport = params.user = params.method = params.ttl = params.maddr = NULL;
444                 params.lr = 0;
445
446                 ast_copy_string(uri,testdataptr->uri,sizeof(uri));
447                 if (parse_uri_full(uri, "sip:,sips:", testdataptr->userptr,
448                                    testdataptr->passptr, testdataptr->domainptr,
449                                    testdataptr->paramsptr,
450                                    testdataptr->headersptr,
451                                    testdataptr->residueptr) ||
452                         ((testdataptr->userptr) && strcmp(testdataptr->user, user)) ||
453                         ((testdataptr->passptr) && strcmp(testdataptr->pass, pass)) ||
454                         ((testdataptr->domainptr) && strcmp(testdataptr->domain, domain)) ||
455                         ((testdataptr->headersptr) && strcmp(testdataptr->headers, headers)) ||
456                         ((testdataptr->residueptr) && strcmp(testdataptr->residue, residue)) ||
457                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.transport,params.transport)) ||
458                         ((testdataptr->paramsptr) && (testdataptr->params.lr != params.lr)) ||
459                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.user,params.user))
460                 ) {
461                                 ast_test_status_update(test, "Sub-Test: %s, failed.\n", testdataptr->desc);
462                                 res = AST_TEST_FAIL;
463                 }
464         }
465
466
467         return res;
468 }
469
470
471 int parse_uri(char *uri, const char *scheme, char **user, char **pass,
472               char **domain, char **transport) {
473         int ret;
474         char *headers;
475         struct uriparams params;
476
477         headers = NULL;
478         ret = parse_uri_full(uri, scheme, user, pass, domain, &params, &headers, NULL);
479         if (transport) {
480                 *transport=params.transport;
481         }
482         return ret;
483 }
484
485 AST_TEST_DEFINE(sip_parse_uri_test)
486 {
487         int res = AST_TEST_PASS;
488         char *name, *pass, *domain, *transport;
489         char uri1[] = "sip:name@host";
490         char uri2[] = "sip:name@host;transport=tcp";
491         char uri3[] = "sip:name:secret@host;transport=tcp";
492         char uri4[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
493         /* test 5 is for NULL input */
494         char uri6[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
495         char uri7[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
496         char uri8[] = "sip:host";
497         char uri9[] = "sip:host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
498         char uri10[] = "host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
499         char uri11[] = "host";
500
501         switch (cmd) {
502         case TEST_INIT:
503                 info->name = "sip_uri_parse_test";
504                 info->category = "/channels/chan_sip/";
505                 info->summary = "tests sip uri parsing";
506                 info->description =
507                                                         "Tests parsing of various URIs "
508                                                         "Verifies output matches expected behavior.";
509                 return AST_TEST_NOT_RUN;
510         case TEST_EXECUTE:
511                 break;
512         }
513
514         /* Test 1, simple URI */
515         name = pass = domain = transport = NULL;
516         if (parse_uri(uri1, "sip:,sips:", &name, &pass, &domain, &transport) ||
517                         strcmp(name, "name")        ||
518                         !ast_strlen_zero(pass)      ||
519                         strcmp(domain, "host")      ||
520                         !ast_strlen_zero(transport)) {
521                 ast_test_status_update(test, "Test 1: simple uri failed. \n");
522                 res = AST_TEST_FAIL;
523         }
524
525         /* Test 2, add tcp transport */
526         name = pass = domain = transport = NULL;
527         if (parse_uri(uri2, "sip:,sips:", &name, &pass, &domain, &transport) ||
528                         strcmp(name, "name")        ||
529                         !ast_strlen_zero(pass)      ||
530                         strcmp(domain, "host")    ||
531                         strcmp(transport, "tcp")) {
532                 ast_test_status_update(test, "Test 2: uri with addtion of tcp transport failed. \n");
533                 res = AST_TEST_FAIL;
534         }
535
536         /* Test 3, add secret */
537         name = pass = domain = transport = NULL;
538         if (parse_uri(uri3, "sip:,sips:", &name, &pass, &domain, &transport) ||
539                         strcmp(name, "name")        ||
540                         strcmp(pass, "secret")      ||
541                         strcmp(domain, "host")    ||
542                         strcmp(transport, "tcp")) {
543                 ast_test_status_update(test, "Test 3: uri with addition of secret failed.\n");
544                 res = AST_TEST_FAIL;
545         }
546
547         /* Test 4, add port and unparsed header field*/
548         name = pass = domain = transport = NULL;
549         if (parse_uri(uri4, "sip:,sips:", &name, &pass, &domain, &transport) ||
550                         strcmp(name, "name")        ||
551                         strcmp(pass, "secret")      ||
552                         strcmp(domain, "host:port") ||
553                         strcmp(transport, "tcp")) {
554                 ast_test_status_update(test, "Test 4: add port and unparsed header field failed.\n");
555                 res = AST_TEST_FAIL;
556         }
557
558         /* Test 5, verify parse_uri does not crash when given a NULL uri */
559         name = pass = domain = transport = NULL;
560         if (!parse_uri(NULL, "sip:,sips:", &name, &pass, &domain, &transport)) {
561                 ast_test_status_update(test, "Test 5: passing a NULL uri failed.\n");
562                 res = AST_TEST_FAIL;
563         }
564
565         /* Test 6, verify parse_uri does not crash when given a NULL output parameters */
566         name = pass = domain = transport = NULL;
567         if (parse_uri(uri6, "sip:,sips:", NULL, NULL, NULL, NULL)) {
568                 ast_test_status_update(test, "Test 6: passing NULL output parameters failed.\n");
569                 res = AST_TEST_FAIL;
570         }
571
572         /* Test 7, verify parse_uri returns user:secret and domain when no port or secret output parameters are supplied. */
573         name = pass = domain = transport = NULL;
574         if (parse_uri(uri7, "sip:,sips:", &name, NULL, &domain, NULL) ||
575                         strcmp(name, "name:secret")        ||
576                         strcmp(domain, "host:port")) {
577
578                 ast_test_status_update(test, "Test 7: providing no port and secret output parameters failed.\n");
579                 res = AST_TEST_FAIL;
580         }
581
582         /* Test 8, verify parse_uri can handle a domain only uri */
583         name = pass = domain = transport = NULL;
584         if (parse_uri(uri8, "sip:,sips:", &name, &pass, &domain, &transport) ||
585                         strcmp(domain, "host") ||
586                         !ast_strlen_zero(name)) {
587                 ast_test_status_update(test, "Test 8: add port and unparsed header field failed.\n");
588                 res = AST_TEST_FAIL;
589         }
590
591         /* Test 9, add port and unparsed header field with domain only uri*/
592         name = pass = domain = transport = NULL;
593         if (parse_uri(uri9, "sip:,sips:", &name, &pass, &domain, &transport) ||
594                         !ast_strlen_zero(name)        ||
595                         !ast_strlen_zero(pass)      ||
596                         strcmp(domain, "host:port")    ||
597                         strcmp(transport, "tcp")) {
598                 ast_test_status_update(test, "Test 9: domain only uri failed \n");
599                 res = AST_TEST_FAIL;
600         }
601
602         /* Test 10, handle invalid/missing "sip:,sips:" scheme
603          * we expect parse_uri to return an error, but still parse
604          * the results correctly here */
605         name = pass = domain = transport = NULL;
606         if (!parse_uri(uri10, "sip:,sips:", &name, &pass, &domain, &transport) ||
607                         !ast_strlen_zero(name)        ||
608                         !ast_strlen_zero(pass)      ||
609                         strcmp(domain, "host:port")    ||
610                         strcmp(transport, "tcp")) {
611                 ast_test_status_update(test, "Test 10: missing \"sip:sips:\" scheme failed\n");
612                 res = AST_TEST_FAIL;
613         }
614
615         /* Test 11, simple domain only URI with missing scheme
616          * we expect parse_uri to return an error, but still parse
617          * the results correctly here */
618         name = pass = domain = transport = NULL;
619         if (!parse_uri(uri11, "sip:,sips:", &name, &pass, &domain, &transport) ||
620                         !ast_strlen_zero(name)      ||
621                         !ast_strlen_zero(pass)      ||
622                         strcmp(domain, "host")      ||
623                         !ast_strlen_zero(transport)) {
624                 ast_test_status_update(test, "Test 11: simple uri with missing scheme failed. \n");
625                 res = AST_TEST_FAIL;
626         }
627
628         return res;
629 }
630
631 /*! \brief  Get caller id name from SIP headers, copy into output buffer
632  *
633  *  \retval input string pointer placed after display-name field if possible
634  */
635 const char *get_calleridname(const char *input, char *output, size_t outputsize)
636 {
637         /* From RFC3261:
638          * 
639          * From           =  ( "From" / "f" ) HCOLON from-spec
640          * from-spec      =  ( name-addr / addr-spec ) *( SEMI from-param )
641          * name-addr      =  [ display-name ] LAQUOT addr-spec RAQUOT
642          * display-name   =  *(token LWS)/ quoted-string
643          * token          =  1*(alphanum / "-" / "." / "!" / "%" / "*"
644          *                     / "_" / "+" / "`" / "'" / "~" )
645          * quoted-string  =  SWS DQUOTE *(qdtext / quoted-pair ) DQUOTE
646          * qdtext         =  LWS / %x21 / %x23-5B / %x5D-7E
647          *                     / UTF8-NONASCII
648          * quoted-pair    =  "\" (%x00-09 / %x0B-0C / %x0E-7F)
649          *
650          * HCOLON         = *WSP ":" SWS
651          * SWS            = [LWS]
652          * LWS            = *[*WSP CRLF] 1*WSP
653          * WSP            = (SP / HTAB)
654          *
655          * Deviations from it:
656          * - following CRLF's in LWS is not done (here at least)
657          * - ascii NUL is never legal as it terminates the C-string
658          * - utf8-nonascii is not checked for validity
659          */
660         char *orig_output = output;
661         const char *orig_input = input;
662
663         /* clear any empty characters in the beginning */
664         input = ast_skip_blanks(input);
665
666         /* no data at all or no storage room? */
667         if (!input || *input == '<' || !outputsize || !output) {
668                 return orig_input;
669         }
670
671         /* make sure the output buffer is initilized */
672         *orig_output = '\0';
673
674         /* make room for '\0' at the end of the output buffer */
675         outputsize--;
676
677         /* quoted-string rules */
678         if (input[0] == '"') {
679                 input++; /* skip the first " */
680
681                 for (;((outputsize > 0) && *input); input++) {
682                         if (*input == '"') {  /* end of quoted-string */
683                                 break;
684                         } else if (*input == 0x5c) { /* quoted-pair = "\" (%x00-09 / %x0B-0C / %x0E-7F) */
685                                 input++;
686                                 if (!*input || (unsigned char)*input > 0x7f || *input == 0xa || *input == 0xd) {
687                                         continue;  /* not a valid quoted-pair, so skip it */
688                                 }
689                         } else if (((*input != 0x9) && ((unsigned char) *input < 0x20)) ||
690                                     (*input == 0x7f)) {
691                                 continue; /* skip this invalid character. */
692                         }
693
694                         *output++ = *input;
695                         outputsize--;
696                 }
697
698                 /* if this is successful, input should be at the ending quote */
699                 if (!input || *input != '"') {
700                         ast_log(LOG_WARNING, "No ending quote for display-name was found\n");
701                         *orig_output = '\0';
702                         return orig_input;
703                 }
704
705                 /* make sure input is past the last quote */
706                 input++;
707
708                 /* terminate outbuf */
709                 *output = '\0';
710         } else {  /* either an addr-spec or tokenLWS-combo */
711                 for (;((outputsize > 0) && *input); input++) {
712                         /* token or WSP (without LWS) */
713                         if ((*input >= '0' && *input <= '9') || (*input >= 'A' && *input <= 'Z')
714                                 || (*input >= 'a' && *input <= 'z') || *input == '-' || *input == '.'
715                                 || *input == '!' || *input == '%' || *input == '*' || *input == '_'
716                                 || *input == '+' || *input == '`' || *input == '\'' || *input == '~'
717                                 || *input == 0x9 || *input == ' ') {
718                                 *output++ = *input;
719                                 outputsize -= 1;
720                         } else if (*input == '<') {   /* end of tokenLWS-combo */
721                                 /* we could assert that the previous char is LWS, but we don't care */
722                                 break;
723                         } else if (*input == ':') {
724                                 /* This invalid character which indicates this is addr-spec rather than display-name. */
725                                 *orig_output = '\0';
726                                 return orig_input;
727                         } else {         /* else, invalid character we can skip. */
728                                 continue;    /* skip this character */
729                         }
730                 }
731
732                 if (*input != '<') {   /* if we never found the start of addr-spec then this is invalid */
733                         *orig_output = '\0';
734                         return orig_input;
735                 }
736
737                 /* set NULL while trimming trailing whitespace */
738                 do {
739                         *output-- = '\0';
740                 } while (*output == 0x9 || *output == ' '); /* we won't go past orig_output as first was a non-space */
741         }
742
743         return input;
744 }
745
746 AST_TEST_DEFINE(get_calleridname_test)
747 {
748         int res = AST_TEST_PASS;
749         const char *in1 = "\" quoted-text internal \\\" quote \"<stuff>";
750         const char *in2 = " token text with no quotes <stuff>";
751         const char *overflow1 = " \"quoted-text overflow 1234567890123456789012345678901234567890\" <stuff>";
752         const char *noendquote = " \"quoted-text no end <stuff>";
753         const char *addrspec = " \"sip:blah@blah <stuff>";
754         const char *no_quotes_no_brackets = "blah@blah";
755         const char *after_dname;
756         char dname[40];
757
758         switch (cmd) {
759         case TEST_INIT:
760                 info->name = "sip_get_calleridname_test";
761                 info->category = "/channels/chan_sip/";
762                 info->summary = "decodes callerid name from sip header";
763                 info->description = "Decodes display-name field of sip header.  Checks for valid output and expected failure cases.";
764                 return AST_TEST_NOT_RUN;
765         case TEST_EXECUTE:
766                 break;
767         }
768
769         /* quoted-text with backslash escaped quote */
770         after_dname = get_calleridname(in1, dname, sizeof(dname));
771         ast_test_status_update(test, "display-name1: %s\nafter: %s\n", dname, after_dname);
772         if (strcmp(dname, " quoted-text internal \" quote ")) {
773                 ast_test_status_update(test, "display-name1 test failed\n");
774                 res = AST_TEST_FAIL;
775         }
776
777         /* token text */
778         after_dname = get_calleridname(in2, dname, sizeof(dname));
779         ast_test_status_update(test, "display-name2: %s\nafter: %s\n", dname, after_dname);
780         if (strcmp(dname, "token text with no quotes")) {
781                 ast_test_status_update(test, "display-name2 test failed\n");
782                 res = AST_TEST_FAIL;
783         }
784
785         /* quoted-text buffer overflow */
786         after_dname = get_calleridname(overflow1, dname, sizeof(dname));
787         ast_test_status_update(test, "overflow display-name1: %s\nafter: %s\n", dname, after_dname);
788         if (*dname != '\0' && after_dname != overflow1) {
789                 ast_test_status_update(test, "overflow display-name1 test failed\n");
790                 res = AST_TEST_FAIL;
791         }
792
793         /* quoted-text buffer with no terminating end quote */
794         after_dname = get_calleridname(noendquote, dname, sizeof(dname));
795         ast_test_status_update(test, "noendquote display-name1: %s\nafter: %s\n", dname, after_dname);
796         if (*dname != '\0' && after_dname != noendquote) {
797                 ast_test_status_update(test, "no end quote for quoted-text display-name failed\n");
798                 res = AST_TEST_FAIL;
799         }
800
801         /* addr-spec rather than display-name. */
802         after_dname = get_calleridname(addrspec, dname, sizeof(dname));
803         ast_test_status_update(test, "noendquote display-name1: %s\nafter: %s\n", dname, after_dname);
804         if (*dname != '\0' && after_dname != addrspec) {
805                 ast_test_status_update(test, "detection of addr-spec failed\n");
806                 res = AST_TEST_FAIL;
807         }
808
809         /* no quotes, no brackets */
810         after_dname = get_calleridname(no_quotes_no_brackets, dname, sizeof(dname));
811         ast_test_status_update(test, "no_quotes_no_brackets display-name1: %s\nafter: %s\n", dname, after_dname);
812         if (*dname != '\0' && after_dname != no_quotes_no_brackets) {
813                 ast_test_status_update(test, "detection of addr-spec failed\n");
814                 res = AST_TEST_FAIL;
815         }
816
817
818         return res;
819 }
820
821 int get_name_and_number(const char *hdr, char **name, char **number)
822 {
823         char header[256];
824         char tmp_name[50] = { 0, };
825         char *tmp_number = NULL;
826         char *domain = NULL;
827         char *dummy = NULL;
828
829         if (!name || !number || ast_strlen_zero(hdr)) {
830                 return -1;
831         }
832
833         *number = NULL;
834         *name = NULL;
835         ast_copy_string(header, hdr, sizeof(header));
836
837         /* strip the display-name portion off the beginning of the header. */
838         get_calleridname(header, tmp_name, sizeof(tmp_name));
839
840         /* get uri within < > brackets */
841         tmp_number = get_in_brackets(header);
842
843         /* parse out the number here */
844         if (parse_uri(tmp_number, "sip:,sips:", &tmp_number, &dummy, &domain, NULL) || ast_strlen_zero(tmp_number)) {
845                 ast_log(LOG_ERROR, "can not parse name and number from sip header.\n");
846                 return -1;
847         }
848
849         /* number is not option, and must be present at this point */
850         *number = ast_strdup(tmp_number);
851         ast_uri_decode(*number);
852
853         /* name is optional and may not be present at this point */
854         if (!ast_strlen_zero(tmp_name)) {
855                 *name = ast_strdup(tmp_name);
856         }
857
858         return 0;
859 }
860
861 AST_TEST_DEFINE(get_name_and_number_test)
862 {
863         int res = AST_TEST_PASS;
864         char *name = NULL;
865         char *number = NULL;
866         const char *in1 = "NAME <sip:NUMBER@place>";
867         const char *in2 = "\"NA><ME\" <sip:NUMBER@place>";
868         const char *in3 = "NAME";
869         const char *in4 = "<sip:NUMBER@place>";
870         const char *in5 = "This is a screwed up string <sip:LOLCLOWNS<sip:>@place>";
871
872         switch (cmd) {
873         case TEST_INIT:
874                 info->name = "sip_get_name_and_number_test";
875                 info->category = "/channels/chan_sip/";
876                 info->summary = "Tests getting name and number from sip header";
877                 info->description =
878                                 "Runs through various test situations in which a name and "
879                                 "and number can be retrieved from a sip header.";
880                 return AST_TEST_NOT_RUN;
881         case TEST_EXECUTE:
882                 break;
883         }
884
885         /* Test 1. get name and number */
886         number = name = NULL;
887         if ((get_name_and_number(in1, &name, &number)) ||
888                 strcmp(name, "NAME") ||
889                 strcmp(number, "NUMBER")) {
890
891                 ast_test_status_update(test, "Test 1, simple get name and number failed.\n");
892                 res = AST_TEST_FAIL;
893         }
894         ast_free(name);
895         ast_free(number);
896
897         /* Test 2. get quoted name and number */
898         number = name = NULL;
899         if ((get_name_and_number(in2, &name, &number)) ||
900                 strcmp(name, "NA><ME") ||
901                 strcmp(number, "NUMBER")) {
902
903                 ast_test_status_update(test, "Test 2, get quoted name and number failed.\n");
904                 res = AST_TEST_FAIL;
905         }
906         ast_free(name);
907         ast_free(number);
908
909         /* Test 3. name only */
910         number = name = NULL;
911         if (!(get_name_and_number(in3, &name, &number))) {
912
913                 ast_test_status_update(test, "Test 3, get name only was expected to fail but did not.\n");
914                 res = AST_TEST_FAIL;
915         }
916         ast_free(name);
917         ast_free(number);
918
919         /* Test 4. number only */
920         number = name = NULL;
921         if ((get_name_and_number(in4, &name, &number)) ||
922                 !ast_strlen_zero(name) ||
923                 strcmp(number, "NUMBER")) {
924
925                 ast_test_status_update(test, "Test 4, get number with no name present failed.\n");
926                 res = AST_TEST_FAIL;
927         }
928         ast_free(name);
929         ast_free(number);
930
931         /* Test 5. malformed string, since number can not be parsed, this should return an error.  */
932         number = name = NULL;
933         if (!(get_name_and_number(in5, &name, &number)) ||
934                 !ast_strlen_zero(name) ||
935                 !ast_strlen_zero(number)) {
936
937                 ast_test_status_update(test, "Test 5, processing malformed string failed.\n");
938                 res = AST_TEST_FAIL;
939         }
940         ast_free(name);
941         ast_free(number);
942
943         /* Test 6. NULL output parameters */
944         number = name = NULL;
945         if (!(get_name_and_number(in5, NULL, NULL))) {
946
947                 ast_test_status_update(test, "Test 6, NULL output parameters failed.\n");
948                 res = AST_TEST_FAIL;
949         }
950
951         /* Test 7. NULL input parameter */
952         number = name = NULL;
953         if (!(get_name_and_number(NULL, &name, &number)) ||
954                 !ast_strlen_zero(name) ||
955                 !ast_strlen_zero(number)) {
956
957                 ast_test_status_update(test, "Test 7, NULL input parameter failed.\n");
958                 res = AST_TEST_FAIL;
959         }
960         ast_free(name);
961         ast_free(number);
962
963         return res;
964 }
965
966 int get_in_brackets_full(char *tmp,char **out,char **residue)
967 {
968         const char *parse = tmp;
969         char *first_bracket;
970         char *second_bracket;
971
972         if (out) {
973                 *out = "";
974         }
975         if (residue) {
976                 *residue = "";
977         }
978
979         if (ast_strlen_zero(tmp)) {
980                 return 1;
981         }
982
983         /*
984          * Skip any quoted text until we find the part in brackets.
985         * On any error give up and return -1
986         */
987         while ( (first_bracket = strchr(parse, '<')) ) {
988                 char *first_quote = strchr(parse, '"');
989                 first_bracket++;
990                 if (!first_quote || first_quote >= first_bracket) {
991                         break; /* no need to look at quoted part */
992                 }
993                 /* the bracket is within quotes, so ignore it */
994                 parse = find_closing_quote(first_quote + 1, NULL);
995                 if (!*parse) {
996                         ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
997                         return  -1;
998                 }
999                 parse++;
1000         }
1001
1002         /* If no first bracket then still look for a second bracket as some other parsing functions
1003         may overwrite first bracket with NULL when terminating a token based display-name. As this
1004         only affects token based display-names there is no danger of brackets being in quotes */
1005         if (first_bracket) {
1006                 parse = first_bracket;
1007                 } else {
1008                 parse = tmp;
1009         }
1010
1011         if ((second_bracket = strchr(parse, '>'))) {
1012                 *second_bracket++ = '\0';
1013                 if (out) {
1014                         *out = first_bracket;
1015                 }
1016                 if (residue) {
1017                         *residue = second_bracket;
1018                 }
1019                 return 0;
1020         }
1021
1022         if ((first_bracket)) {
1023                         ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1024                 return -1;
1025                 }
1026
1027         if (out) {
1028                 *out = tmp;
1029         }
1030
1031         return 1;
1032 }
1033
1034 char *get_in_brackets(char *tmp)
1035 {
1036         char *out;
1037
1038         if ((get_in_brackets_full(tmp, &out, NULL))) {
1039                 return tmp;
1040         }
1041         return out;
1042 }
1043
1044 AST_TEST_DEFINE(get_in_brackets_test)
1045 {
1046         int res = AST_TEST_PASS;
1047         char *in_brackets = "<sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1048         char no_name[] = "<sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1049         char quoted_string[] = "\"I'm a quote stri><ng\" <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1050         char missing_end_quote[] = "\"I'm a quote string <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1051         char name_no_quotes[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
1052         char no_end_bracket[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah";
1053         char no_name_no_brackets[] = "sip:name@host";
1054         char *uri = NULL;
1055
1056         switch (cmd) {
1057         case TEST_INIT:
1058                 info->name = "sip_get_in_brackets_test";
1059                 info->category = "/channels/chan_sip/";
1060                 info->summary = "Tests getting a sip uri in <> brackets within a sip header.";
1061                 info->description =
1062                                 "Runs through various test situations in which a sip uri "
1063                                 "in angle brackets needs to be retrieved";
1064                 return AST_TEST_NOT_RUN;
1065         case TEST_EXECUTE:
1066                 break;
1067         }
1068
1069         /* Test 1, simple get in brackets */
1070         if (!(uri = get_in_brackets(no_name)) || !(strcmp(uri, in_brackets))) {
1071
1072                 ast_test_status_update(test, "Test 1, simple get in brackets failed.\n");
1073                 res = AST_TEST_FAIL;
1074         }
1075
1076         /* Test 2, starts with quoted string */
1077         if (!(uri = get_in_brackets(quoted_string)) || !(strcmp(uri, in_brackets))) {
1078
1079                 ast_test_status_update(test, "Test 2, get in brackets with quoted string in front failed.\n");
1080                 res = AST_TEST_FAIL;
1081         }
1082
1083         /* Test 3, missing end quote */
1084         if (!(uri = get_in_brackets(missing_end_quote)) || !(strcmp(uri, in_brackets))) {
1085
1086                 ast_test_status_update(test, "Test 3, missing end quote failed.\n");
1087                 res = AST_TEST_FAIL;
1088         }
1089
1090         /* Test 4, starts with a name not in quotes */
1091         if (!(uri = get_in_brackets(name_no_quotes)) || !(strcmp(uri, in_brackets))) {
1092
1093                 ast_test_status_update(test, "Test 4, passing name not in quotes failed.\n");
1094                 res = AST_TEST_FAIL;
1095         }
1096
1097         /* Test 5, no end bracket, should just return everything after the first '<'  */
1098         if (!(uri = get_in_brackets(no_end_bracket)) || !(strcmp(uri, in_brackets))) {
1099
1100                 ast_test_status_update(test, "Test 5, no end bracket failed.\n");
1101                 res = AST_TEST_FAIL;
1102         }
1103
1104         /* Test 6, NULL input  */
1105         if ((uri = get_in_brackets(NULL))) {
1106
1107                 ast_test_status_update(test, "Test 6, NULL input failed.\n");
1108                 res = AST_TEST_FAIL;
1109         }
1110
1111         /* Test 7, no name, and no brackets. */
1112         if (!(uri = get_in_brackets(no_name_no_brackets)) || (strcmp(uri, "sip:name@host"))) {
1113
1114                 ast_test_status_update(test, "Test 7 failed. %s\n", uri);
1115                 res = AST_TEST_FAIL;
1116         }
1117
1118         return res;
1119 }
1120
1121
1122 int parse_name_andor_addr(char *uri, const char *scheme, char **name,
1123                           char **user, char **pass, char **domain,
1124                           struct uriparams *params, char **headers,
1125                           char **residue)
1126 {
1127         static char buf[1024];
1128         char **residue2=residue;
1129         int ret;
1130         if (name) {
1131                 get_calleridname(uri,buf,sizeof(buf));
1132                 *name = buf;
1133         }
1134         ret = get_in_brackets_full(uri,&uri,residue);
1135         if (ret == 0) { /* uri is in brackets so do not treat unknown trailing uri parameters as potential messageheader parameters */
1136                 *residue = *residue + 1; /* step over the first semicolon so as per parse uri residue */
1137                 residue2 = NULL;
1138         }
1139
1140         return parse_uri_full(uri, scheme, user, pass, domain, params, headers,
1141                               residue2);
1142 }
1143
1144 AST_TEST_DEFINE(parse_name_andor_addr_test)
1145 {
1146         int res = AST_TEST_PASS;
1147         char uri[1024];
1148         char *name, *user, *pass, *domain, *headers, *residue;
1149         struct uriparams params;
1150
1151         struct testdata {
1152                 char *desc;
1153                 char *uri;
1154                 char **nameptr;
1155                 char **userptr;
1156                 char **passptr;
1157                 char **domainptr;
1158                 char **headersptr;
1159                 char **residueptr;
1160                 struct uriparams *paramsptr;
1161                 char *name;
1162                 char *user;
1163                 char *pass;
1164                 char *domain;
1165                 char *headers;
1166                 char *residue;
1167                 struct uriparams params;
1168                 AST_LIST_ENTRY(testdata) list;
1169         };
1170
1171         struct testdata *testdataptr;
1172
1173         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1174
1175         struct testdata td1 = {
1176                 .desc = "quotes and brackets",
1177                 .uri = "\"name :@ \" <sip:user:secret@host:5060;param=discard;transport=tcp>;tag=tag",
1178                 .nameptr = &name,
1179                 .userptr = &user,
1180                 .passptr = &pass,
1181                 .domainptr = &domain,
1182                 .headersptr = &headers,
1183                 .residueptr = &residue,
1184                 .paramsptr = &params,
1185                 .name =  "name :@ ",
1186                 .user = "user",
1187                 .pass = "secret",
1188                 .domain = "host:5060",
1189                 .headers = "",
1190                 .residue = "tag=tag",
1191                 .params.transport = "tcp",
1192                 .params.lr = 0,
1193                 .params.user = ""
1194         };
1195
1196         struct testdata td2 = {
1197                 .desc = "no quotes",
1198                 .uri = "givenname familyname <sip:user:secret@host:5060;param=discard;transport=tcp>;expires=3600",
1199                 .nameptr = &name,
1200                 .userptr = &user,
1201                 .passptr = &pass,
1202                 .domainptr = &domain,
1203                 .headersptr = &headers,
1204                 .residueptr = &residue,
1205                 .paramsptr = &params,
1206                 .name = "givenname familyname",
1207                 .user = "user",
1208                 .pass = "secret",
1209                 .domain = "host:5060",
1210                 .headers = "",
1211                 .residue = "expires=3600",
1212                 .params.transport = "tcp",
1213                 .params.lr = 0,
1214                 .params.user = ""
1215         };
1216
1217         struct testdata td3 = {
1218                 .desc = "no brackets",
1219                 .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;q=1",
1220                 .nameptr = &name,
1221                 .userptr = &user,
1222                 .passptr = &pass,
1223                 .domainptr = &domain,
1224                 .headersptr = &headers,
1225                 .residueptr = &residue,
1226                 .paramsptr = &params,
1227                 .name = "",
1228                 .user = "user",
1229                 .pass = "secret",
1230                 .domain = "host:5060",
1231                 .headers = "",
1232                 .residue = "q=1",
1233                 .params.transport = "tcp",
1234                 .params.lr = 0,
1235                 .params.user = ""
1236         };
1237
1238         struct testdata td4 = {
1239                 .desc = "just host",
1240                 .uri = "sips:host",
1241                 .nameptr = &name,
1242                 .userptr = &user,
1243                 .passptr = &pass,
1244                 .domainptr = &domain,
1245                 .headersptr = &headers,
1246                 .residueptr = &residue,
1247                 .paramsptr = &params,
1248                 .name = "",
1249                 .user = "",
1250                 .pass = "",
1251                 .domain = "host",
1252                 .headers = "",
1253                 .residue = "",
1254                 .params.transport = "",
1255                 .params.lr = 0,
1256                 .params.user = ""
1257         };
1258
1259
1260         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
1261         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
1262         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
1263         AST_LIST_INSERT_TAIL(&testdatalist, &td4, list);
1264
1265
1266         switch (cmd) {
1267         case TEST_INIT:
1268                 info->name = "parse_name_andor_addr_test";
1269                 info->category = "/channels/chan_sip/";
1270                 info->summary = "tests parsing of name_andor_addr abnf structure";
1271                 info->description =
1272                         "Tests parsing of abnf name-andor-addr = name-addr / addr-spec "
1273                         "Verifies output matches expected behavior.";
1274                 return AST_TEST_NOT_RUN;
1275         case TEST_EXECUTE:
1276                 break;
1277         }
1278
1279         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1280                 name = user = pass = domain = headers = residue = NULL;
1281                 params.transport = params.user = params.method = params.ttl = params.maddr = NULL;
1282                 params.lr = 0;
1283         ast_copy_string(uri,testdataptr->uri,sizeof(uri));
1284                 if (parse_name_andor_addr(uri, "sip:,sips:",
1285                                           testdataptr->nameptr,
1286                                           testdataptr->userptr,
1287                                           testdataptr->passptr,
1288                                           testdataptr->domainptr,
1289                                           testdataptr->paramsptr,
1290                                           testdataptr->headersptr,
1291                                           testdataptr->residueptr) ||
1292                         ((testdataptr->nameptr) && strcmp(testdataptr->name, name)) ||
1293                         ((testdataptr->userptr) && strcmp(testdataptr->user, user)) ||
1294                         ((testdataptr->passptr) && strcmp(testdataptr->pass, pass)) ||
1295                         ((testdataptr->domainptr) && strcmp(testdataptr->domain, domain)) ||
1296                         ((testdataptr->headersptr) && strcmp(testdataptr->headers, headers)) ||
1297                         ((testdataptr->residueptr) && strcmp(testdataptr->residue, residue)) ||
1298                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.transport,params.transport)) ||
1299                         ((testdataptr->paramsptr) && strcmp(testdataptr->params.user,params.user))
1300                 ) {
1301                                 ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1302                                 res = AST_TEST_FAIL;
1303                 }
1304         }
1305
1306
1307         return res;
1308 }
1309
1310 int get_comma(char *in, char **out) {
1311         char *c;
1312         char *parse = in;
1313         if (out) {
1314                 *out = in;
1315         }
1316
1317         /* Skip any quoted text */
1318         while (*parse) {
1319                 if ((c = strchr(parse, '"'))) {
1320                         in = (char *)find_closing_quote((const char *)c + 1, NULL);
1321                         if (!*in) {
1322                                 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", c);
1323                                 return -1;
1324                         } else {
1325                                 break;
1326                         }
1327                 } else {
1328                         break;
1329                 }
1330                 parse++;
1331         }
1332         parse = in;
1333
1334         /* Skip any userinfo components of a uri as they may contain commas */
1335         if ((c = strchr(parse,'@'))) {
1336                 parse = c+1;
1337         }
1338         if ((out) && (c = strchr(parse,','))) {
1339                 *c++ = '\0';
1340                 *out = c;
1341                 return 0;
1342         }
1343         return 1;
1344 }
1345
1346 int parse_contact_header(char *contactheader, struct contactliststruct *contactlist) {
1347         int res;
1348         int last;
1349         char *comma;
1350         char *residue;
1351         char *param;
1352         char *value;
1353         struct contact *contact=NULL;
1354
1355         if (*contactheader == '*') {
1356                 return 1;
1357         }
1358
1359         contact = malloc(sizeof(*contact));
1360
1361         AST_LIST_HEAD_SET_NOLOCK(contactlist, contact);
1362         while ((last = get_comma(contactheader,&comma)) != -1) {
1363
1364                 res = parse_name_andor_addr(contactheader, "sip:,sips:",
1365                                             &contact->name, &contact->user,
1366                                             &contact->pass, &contact->domain,
1367                                             &contact->params, &contact->headers,
1368                                             &residue);
1369                 if (res == -1) {
1370                         return res;
1371                 }
1372
1373                 /* parse contact params */
1374                 contact->expires = contact->q = "";
1375
1376                 while ((value = strchr(residue,'='))) {
1377                         *value++ = '\0';
1378
1379                         param = residue;
1380                         if ((residue = strchr(value,';'))) {
1381                                 *residue++ = '\0';
1382                         } else {
1383                                 residue = "";
1384                         }
1385
1386                         if (!strcmp(param,"expires")) {
1387                                 contact->expires = value;
1388                         } else if (!strcmp(param,"q")) {
1389                                 contact->q = value;
1390                         }
1391                 }
1392
1393                 if(last) {
1394                         return 0;
1395                 }
1396                 contactheader = comma;
1397
1398                 contact = malloc(sizeof(*contact));
1399                 AST_LIST_INSERT_TAIL(contactlist, contact, list);
1400
1401         }
1402         return last;
1403 }
1404
1405 AST_TEST_DEFINE(parse_contact_header_test)
1406 {
1407         int res = AST_TEST_PASS;
1408         char contactheader[1024];
1409         int star;
1410         struct contactliststruct contactlist;
1411         struct contactliststruct *contactlistptr=&contactlist;
1412
1413         struct testdata {
1414                 char *desc;
1415                 char *contactheader;
1416                 int star;
1417                 struct contactliststruct *contactlist;
1418
1419                 AST_LIST_ENTRY(testdata) list;
1420         };
1421
1422         struct testdata *testdataptr;
1423         struct contact *tdcontactptr;
1424         struct contact *contactptr;
1425
1426         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1427         struct contactliststruct contactlist1, contactlist2;
1428
1429         struct testdata td1 = {
1430                 .desc = "single contact",
1431                 .contactheader = "\"name :@;?&,\" <sip:user:secret@host:5082;param=discard;transport=tcp>;expires=3600",
1432                 .contactlist = &contactlist1,
1433                 .star = 0
1434         };
1435         struct contact contact11 = {
1436                 .name = "name :@;?&,",
1437                 .user = "user",
1438                 .pass = "secret",
1439                 .domain = "host:5082",
1440                 .params.transport = "tcp",
1441                 .params.ttl = "",
1442                 .params.lr = 0,
1443                 .headers = "",
1444                 .expires = "3600",
1445                 .q = ""
1446         };
1447
1448         struct testdata td2 = {
1449                 .desc = "multiple contacts",
1450                 .contactheader = "sip:,user1,:,secret1,@host1;ttl=7;q=1;expires=3600,sips:host2",
1451                 .contactlist = &contactlist2,
1452                 .star = 0,
1453         };
1454         struct contact contact21 = {
1455                 .name = "",
1456                 .user = ",user1,",
1457                 .pass = ",secret1,",
1458                 .domain = "host1",
1459                 .params.transport = "",
1460                 .params.ttl = "7",
1461                 .params.lr = 0,
1462                 .headers = "",
1463                 .expires = "3600",
1464                 .q = "1"
1465         };
1466         struct contact contact22 = {
1467                 .name = "",
1468                 .user = "",
1469                 .pass = "",
1470                 .domain = "host2",
1471                 .params.transport = "",
1472                 .params.ttl = "",
1473                 .params.lr = 0,
1474                 .headers = "",
1475                 .expires = "",
1476                 .q = ""
1477         };
1478
1479         struct testdata td3 = {
1480                 .desc = "star - all contacts",
1481                 .contactheader = "*",
1482                 .star = 1,
1483                 .contactlist = NULL
1484         };
1485
1486         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
1487         AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
1488         AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
1489
1490         AST_LIST_HEAD_SET_NOLOCK(&contactlist1, &contact11);
1491
1492         AST_LIST_HEAD_SET_NOLOCK(&contactlist2, &contact21);
1493         AST_LIST_INSERT_TAIL(&contactlist2, &contact22, list);
1494
1495
1496         switch (cmd) {
1497         case TEST_INIT:
1498                 info->name = "parse_contact_header_test";
1499                 info->category = "/channels/chan_sip/";
1500                 info->summary = "tests parsing of sip contact header";
1501                 info->description =
1502                         "Tests parsing of a contact header including those with multiple contacts "
1503                         "Verifies output matches expected behavior.";
1504                 return AST_TEST_NOT_RUN;
1505         case TEST_EXECUTE:
1506                 break;
1507         }
1508
1509         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1510                 ast_copy_string(contactheader,testdataptr->contactheader,sizeof(contactheader));
1511                 star = parse_contact_header(contactheader,contactlistptr);
1512                 if (testdataptr->star) {
1513                         /* expecting star rather than list of contacts */
1514                         if (!star) {
1515                                 ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1516                                 res = AST_TEST_FAIL;
1517                                 break;
1518                         }
1519                 } else {
1520                         contactptr = AST_LIST_FIRST(contactlistptr);
1521                         AST_LIST_TRAVERSE(testdataptr->contactlist, tdcontactptr, list) {
1522                                 if (!contactptr ||
1523                                         strcmp(tdcontactptr->name, contactptr->name) ||
1524                                         strcmp(tdcontactptr->user, contactptr->user) ||
1525                                         strcmp(tdcontactptr->pass, contactptr->pass) ||
1526                                         strcmp(tdcontactptr->domain, contactptr->domain) ||
1527                                         strcmp(tdcontactptr->headers, contactptr->headers) ||
1528                                         strcmp(tdcontactptr->expires, contactptr->expires) ||
1529                                         strcmp(tdcontactptr->q, contactptr->q) ||
1530                                         strcmp(tdcontactptr->params.transport, contactptr->params.transport) ||
1531                                         strcmp(tdcontactptr->params.ttl, contactptr->params.ttl) ||
1532                                         (tdcontactptr->params.lr != contactptr->params.lr)
1533                                 ) {
1534                                         ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
1535                                         res = AST_TEST_FAIL;
1536                                         break;
1537                                 }
1538
1539                         contactptr = AST_LIST_NEXT(contactptr,list);
1540                         }
1541                 }
1542
1543         }
1544
1545         return res;
1546 }
1547
1548 /*!
1549  * \brief Parse supported header in incoming packet
1550  *
1551  * \details This function parses through the options parameters and
1552  * builds a bit field representing all the SIP options in that field. When an
1553  * item is found that is not supported, it is copied to the unsupported
1554  * out buffer.
1555  *
1556  * \param option list
1557  * \param unsupported out buffer (optional)
1558  * \param unsupported out buffer length (optional)
1559  */
1560 unsigned int parse_sip_options(const char *options, char *unsupported, size_t unsupported_len)
1561 {
1562         char *next, *sep;
1563         char *temp;
1564         int i, found, supported;
1565         unsigned int profile = 0;
1566
1567         char *out = unsupported;
1568         size_t outlen = unsupported_len;
1569         char *cur_out = out;
1570
1571         if (out && (outlen > 0)) {
1572                 memset(out, 0, outlen);
1573         }
1574
1575         if (ast_strlen_zero(options) )
1576                 return 0;
1577
1578         temp = ast_strdupa(options);
1579
1580         ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", options);
1581
1582         for (next = temp; next; next = sep) {
1583                 found = FALSE;
1584                 supported = FALSE;
1585                 if ((sep = strchr(next, ',')) != NULL) {
1586                         *sep++ = '\0';
1587                 }
1588
1589                 /* trim leading and trailing whitespace */
1590                 next = ast_strip(next);
1591
1592                 if (ast_strlen_zero(next)) {
1593                         continue; /* if there is a blank argument in there just skip it */
1594                 }
1595
1596                 ast_debug(3, "Found SIP option: -%s-\n", next);
1597                 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
1598                         if (!strcasecmp(next, sip_options[i].text)) {
1599                                 profile |= sip_options[i].id;
1600                                 if (sip_options[i].supported == SUPPORTED) {
1601                                         supported = TRUE;
1602                                 }
1603                                 found = TRUE;
1604                                 ast_debug(3, "Matched SIP option: %s\n", next);
1605                                 break;
1606                         }
1607                 }
1608
1609                 /* If option is not supported, add to unsupported out buffer */
1610                 if (!supported && out && outlen) {
1611                         size_t copylen = strlen(next);
1612                         size_t cur_outlen = strlen(out);
1613                         /* Check to see if there is enough room to store this option.
1614                          * Copy length is string length plus 2 for the ',' and '\0' */
1615                         if ((cur_outlen + copylen + 2) < outlen) {
1616                                 /* if this isn't the first item, add the ',' */
1617                                 if (cur_outlen) {
1618                                         *cur_out = ',';
1619                                         cur_out++;
1620                                         cur_outlen++;
1621                                 }
1622                                 ast_copy_string(cur_out, next, (outlen - cur_outlen));
1623                                 cur_out += copylen;
1624                         }
1625                 }
1626
1627                 if (!found) {
1628                         profile |= SIP_OPT_UNKNOWN;
1629                         if (!strncasecmp(next, "x-", 2))
1630                                 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
1631                         else
1632                                 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1633                 }
1634         }
1635
1636         return profile;
1637 }
1638
1639 AST_TEST_DEFINE(sip_parse_options_test)
1640 {
1641         int res = AST_TEST_PASS;
1642         char unsupported[64];
1643         unsigned int option_profile = 0;
1644         struct testdata {
1645                 char *name;
1646                 char *input_options;
1647                 char *expected_unsupported;
1648                 unsigned int expected_profile;
1649                 AST_LIST_ENTRY(testdata) list;
1650         };
1651
1652         struct testdata *testdataptr;
1653         static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
1654
1655         struct testdata test1 = {
1656                 .name = "test_all_unsupported",
1657                 .input_options = "unsupported1,,, ,unsupported2,unsupported3,unsupported4",
1658                 .expected_unsupported = "unsupported1,unsupported2,unsupported3,unsupported4",
1659                 .expected_profile = SIP_OPT_UNKNOWN,
1660         };
1661         struct testdata test2 = {
1662                 .name = "test_all_unsupported_one_supported",
1663                 .input_options = "  unsupported1, replaces,   unsupported3  , , , ,unsupported4",
1664                 .expected_unsupported = "unsupported1,unsupported3,unsupported4",
1665                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES
1666         };
1667         struct testdata test3 = {
1668                 .name = "test_two_supported_two_unsupported",
1669                 .input_options = ",,  timer  ,replaces     ,unsupported3,unsupported4",
1670                 .expected_unsupported = "unsupported3,unsupported4",
1671                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
1672         };
1673
1674         struct testdata test4 = {
1675                 .name = "test_all_supported",
1676                 .input_options = "timer,replaces",
1677                 .expected_unsupported = "",
1678                 .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
1679         };
1680
1681         struct testdata test5 = {
1682                 .name = "test_all_supported_redundant",
1683                 .input_options = "timer,replaces,timer,replace,timer,replaces",
1684                 .expected_unsupported = "",
1685                 .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
1686         };
1687         struct testdata test6 = {
1688                 .name = "test_buffer_overflow",
1689                 .input_options = "unsupported1,replaces,timer,unsupported4,unsupported_huge____"
1690                 "____________________________________,__________________________________________"
1691                 "________________________________________________",
1692                 .expected_unsupported = "unsupported1,unsupported4",
1693                 .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
1694         };
1695         struct testdata test7 = {
1696                 .name = "test_null_input",
1697                 .input_options = NULL,
1698                 .expected_unsupported = "",
1699                 .expected_profile = 0,
1700         };
1701         struct testdata test8 = {
1702                 .name = "test_whitespace_input",
1703                 .input_options = "         ",
1704                 .expected_unsupported = "",
1705                 .expected_profile = 0,
1706         };
1707         struct testdata test9 = {
1708                 .name = "test_whitespace_plus_option_input",
1709                 .input_options = " , , ,timer , ,  , ,        ,    ",
1710                 .expected_unsupported = "",
1711                 .expected_profile = SIP_OPT_TIMER,
1712         };
1713
1714         switch (cmd) {
1715         case TEST_INIT:
1716                 info->name = "sip_parse_options_test";
1717                 info->category = "/channels/chan_sip/";
1718                 info->summary = "Tests parsing of sip options";
1719                 info->description =
1720                                                         "Tests parsing of SIP options from supported and required "
1721                                                         "header fields.  Verifies when unsupported options are encountered "
1722                                                         "that they are appended to the unsupported out buffer and that the "
1723                                                         "correct bit field representnig the option profile is returned.";
1724                 return AST_TEST_NOT_RUN;
1725         case TEST_EXECUTE:
1726                 break;
1727         }
1728
1729         AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &test1);
1730         AST_LIST_INSERT_TAIL(&testdatalist, &test2, list);
1731         AST_LIST_INSERT_TAIL(&testdatalist, &test3, list);
1732         AST_LIST_INSERT_TAIL(&testdatalist, &test4, list);
1733         AST_LIST_INSERT_TAIL(&testdatalist, &test5, list);
1734         AST_LIST_INSERT_TAIL(&testdatalist, &test6, list);
1735         AST_LIST_INSERT_TAIL(&testdatalist, &test7, list);
1736         AST_LIST_INSERT_TAIL(&testdatalist, &test8, list);
1737         AST_LIST_INSERT_TAIL(&testdatalist, &test9, list);
1738
1739         /* Test with unsupported char buffer */
1740         AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
1741                 option_profile = parse_sip_options(testdataptr->input_options, unsupported, ARRAY_LEN(unsupported));
1742                 if (option_profile != testdataptr->expected_profile ||
1743                         strcmp(unsupported, testdataptr->expected_unsupported)) {
1744                         ast_test_status_update(test, "Test with output buffer \"%s\", expected unsupported: %s actual unsupported:"
1745                                 "%s expected bit profile: %x actual bit profile: %x\n",
1746                                 testdataptr->name,
1747                                 testdataptr->expected_unsupported,
1748                                 unsupported,
1749                                 testdataptr->expected_profile,
1750                                 option_profile);
1751                         res = AST_TEST_FAIL;
1752                 } else {
1753                         ast_test_status_update(test, "\"%s\" passed got expected unsupported: %s and bit profile: %x\n",
1754                                 testdataptr->name,
1755                                 unsupported,
1756                                 option_profile);
1757                 }
1758
1759                 option_profile = parse_sip_options(testdataptr->input_options, NULL, 0);
1760                 if (option_profile != testdataptr->expected_profile) {
1761                         ast_test_status_update(test, "NULL output test \"%s\", expected bit profile: %x actual bit profile: %x\n",
1762                                 testdataptr->name,
1763                                 testdataptr->expected_profile,
1764                                 option_profile);
1765                         res = AST_TEST_FAIL;
1766                 } else {
1767                         ast_test_status_update(test, "\"%s\" with NULL output buf passed, bit profile: %x\n",
1768                                 testdataptr->name,
1769                                 option_profile);
1770                 }
1771         }
1772
1773         return res;
1774 }
1775
1776
1777 void sip_request_parser_register_tests(void)
1778 {
1779         AST_TEST_REGISTER(get_calleridname_test);
1780         AST_TEST_REGISTER(sip_parse_uri_test);
1781         AST_TEST_REGISTER(get_in_brackets_test);
1782         AST_TEST_REGISTER(get_name_and_number_test);
1783         AST_TEST_REGISTER(sip_parse_uri_fully_test);
1784         AST_TEST_REGISTER(parse_name_andor_addr_test);
1785         AST_TEST_REGISTER(parse_contact_header_test);
1786         AST_TEST_REGISTER(sip_parse_options_test);
1787 }
1788 void sip_request_parser_unregister_tests(void)
1789 {
1790         AST_TEST_UNREGISTER(sip_parse_uri_test);
1791         AST_TEST_UNREGISTER(get_calleridname_test);
1792         AST_TEST_UNREGISTER(get_in_brackets_test);
1793         AST_TEST_UNREGISTER(get_name_and_number_test);
1794         AST_TEST_UNREGISTER(sip_parse_uri_fully_test);
1795         AST_TEST_UNREGISTER(parse_name_andor_addr_test);
1796         AST_TEST_UNREGISTER(parse_contact_header_test);
1797         AST_TEST_UNREGISTER(sip_parse_options_test);
1798 }