reqresp_parser.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2010, Digium, Inc.
00005  *
00006  * See http://www.asterisk.org for more information about
00007  * the Asterisk project. Please do not directly contact
00008  * any of the maintainers of this project for assistance;
00009  * the project provides a web site, mailing lists and IRC
00010  * channels for your use.
00011  *
00012  * This program is free software, distributed under the terms of
00013  * the GNU General Public License Version 2. See the LICENSE file
00014  * at the top of the source tree.
00015  */
00016 
00017 /*!
00018  * \file
00019  * \brief sip request parsing functions and unit tests
00020  */
00021 
00022 /*** MODULEINFO
00023    <support_level>extended</support_level>
00024  ***/
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 426868 $")
00029 
00030 #include "include/sip.h"
00031 #include "include/sip_utils.h"
00032 #include "include/reqresp_parser.h"
00033 
00034 #ifdef HAVE_XLOCALE_H
00035 locale_t c_locale;
00036 #endif
00037 
00038 /*! \brief * parses a URI in its components.*/
00039 int parse_uri_full(char *uri, const char *scheme, char **user, char **pass,
00040          char **hostport, struct uriparams *params, char **headers,
00041          char **residue)
00042 {
00043    char *userinfo = NULL;
00044    char *parameters = NULL;
00045    char *endparams = NULL;
00046    char *c = NULL;
00047    int error = 0;
00048    int teluri_scheme = 0;
00049 
00050    /*
00051     * Initialize requested strings - some functions don't care if parse_uri fails
00052     * and will attempt to use string pointers passed into parse_uri even after a
00053     * parse_uri failure
00054     */
00055    if (user) {
00056       *user = "";
00057    }
00058    if (pass) {
00059       *pass = "";
00060    }
00061    if (hostport) {
00062       *hostport = "";
00063    }
00064    if (headers) {
00065       *headers = "";
00066    }
00067    if (residue) {
00068       *residue = "";
00069    }
00070 
00071    /* check for valid input */
00072    if (ast_strlen_zero(uri)) {
00073       return -1;
00074    }
00075 
00076    if (scheme) {
00077       int l;
00078       char *scheme2 = ast_strdupa(scheme);
00079       char *cur = strsep(&scheme2, ",");
00080       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
00081          l = strlen(cur);
00082          if (!strncasecmp(uri, cur, l)) {
00083             teluri_scheme = !strncasecmp(uri, "tel:", 4);   /* TEL URI */
00084             uri += l;
00085             break;
00086          }
00087       }
00088       if (ast_strlen_zero(cur)) {
00089          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
00090          error = -1;
00091       }
00092    }
00093 
00094    if (!hostport) {
00095       /* if we don't want to split around hostport, keep everything as a
00096        * userinfo - cos thats how old parse_uri operated*/
00097       userinfo = uri;
00098    } else if (teluri_scheme) {
00099       /*
00100        * tel: TEL URI INVITE RFC 3966 patch
00101        * See http://www.ietf.org/rfc/rfc3966.txt
00102        *
00103        * Once the full RFC 3966 parsing is implemented,
00104        * the ext= or isub= parameters would be extracted from userinfo.
00105        * When this kind of subaddressing would be implemented, the userinfo must be further parsed.
00106        * Those parameters would be used for ISDN or PSTN local extensions.
00107        *
00108        * Current restrictions:
00109        * We currently consider the ";isub=" or the ";ext=" as part of the userinfo (unparsed).
00110        */
00111 
00112       if ((c = strstr(uri, ";phone-context="))) {
00113          /*
00114           * Local number with context or domain.
00115           * ext= or isub= TEL URI parameters should be upfront.
00116           * All other parameters should come after the ";phone-context=" parameter.
00117           * If other parameters would occur before ";phone-context=" they will be ignored.
00118           */
00119 
00120                         *c = '\0';
00121                         userinfo = uri;
00122                         uri = c + 15;
00123          *hostport = uri;
00124                 } else if ('+' == uri[0]) {
00125          /* Global number without context or domain; possibly followed by RFC 3966 and optional other parameters. */
00126 
00127                         userinfo = uri;
00128          *hostport = uri;
00129       } else {
00130          ast_debug(1, "No RFC 3966 global number or context found in '%s'; returning local number anyway\n", uri);
00131                         userinfo = uri;      /* Return local number anyway */
00132          error = -1;
00133       }
00134    } else {
00135       char *dom = "";
00136       if ((c = strchr(uri, '@'))) {
00137          *c++ = '\0';
00138          dom = c;
00139          userinfo = uri;
00140          uri = c; /* userinfo can contain ? and ; chars so step forward before looking for params and headers */
00141       } else {
00142          /* domain-only URI, according to the SIP RFC. */
00143          dom = uri;
00144          userinfo = "";
00145       }
00146 
00147       *hostport = dom;
00148    }
00149 
00150    if (pass && (c = strchr(userinfo, ':'))) {     /* user:password */
00151       *c++ = '\0';
00152       *pass = c;
00153    } else if (pass) {
00154       *pass = "";
00155    }
00156 
00157    if (user) {
00158       *user = userinfo;
00159    }
00160 
00161    parameters = uri;
00162    /* strip [?headers] from end of uri  - even if no header pointer exists*/
00163    if ((c = strrchr(uri, '?'))) {
00164       *c++ = '\0';
00165       uri = c;
00166       if (headers) {
00167          *headers = c;
00168       }
00169       if ((c = strrchr(uri, ';'))) {
00170          *c++ = '\0';
00171       } else {
00172          c = strrchr(uri, '\0');
00173       }
00174       uri = c; /* residue */
00175 
00176 
00177    } else if (headers) {
00178       *headers = "";
00179    }
00180 
00181    /* parse parameters */
00182    endparams = strchr(parameters,'\0');
00183    if ((c = strchr(parameters, ';'))) {
00184       *c++ = '\0';
00185       parameters = c;
00186    } else {
00187       parameters = endparams;
00188    }
00189 
00190    if (params) {
00191       char *rem = parameters; /* unparsed or unrecognised remainder */
00192       char *label;
00193       char *value;
00194       int lr = 0;
00195 
00196       params->transport = "";
00197       params->user = "";
00198       params->method = "";
00199       params->ttl = "";
00200       params->maddr = "";
00201       params->lr = 0;
00202 
00203       rem = parameters;
00204 
00205       while ((value = strchr(parameters, '=')) || (lr = !strncmp(parameters, "lr", 2))) {
00206          /* The while condition will not continue evaluation to set lr if it matches "lr=" */
00207          if (lr) {
00208             value = parameters;
00209          } else {
00210             *value++ = '\0';
00211          }
00212          label = parameters;
00213          if ((c = strchr(value, ';'))) {
00214             *c++ = '\0';
00215             parameters = c;
00216          } else {
00217             parameters = endparams;
00218          }
00219 
00220          if (!strcmp(label, "transport")) {
00221             params->transport = value;
00222             rem = parameters;
00223          } else if (!strcmp(label, "user")) {
00224             params->user = value;
00225             rem = parameters;
00226          } else if (!strcmp(label, "method")) {
00227             params->method = value;
00228             rem = parameters;
00229          } else if (!strcmp(label, "ttl")) {
00230             params->ttl = value;
00231             rem = parameters;
00232          } else if (!strcmp(label, "maddr")) {
00233             params->maddr = value;
00234             rem = parameters;
00235          /* 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 */
00236          } else if ((!strcmp(label, "lr") && strcmp(value, "no") && strcmp(value, "off") && strcmp(value, "0") && strcmp(value, "")) || ((lr) && strcmp(value, "lr"))) {
00237             params->lr = 1;
00238             rem = parameters;
00239          } else {
00240             value--;
00241             *value = '=';
00242             if (c) {
00243                c--;
00244                *c = ';';
00245             }
00246          }
00247       }
00248       if (rem > uri) { /* no headers */
00249          uri = rem;
00250       }
00251 
00252    }
00253 
00254    if (residue) {
00255       *residue = uri;
00256    }
00257 
00258    return error;
00259 }
00260 
00261 
00262 AST_TEST_DEFINE(sip_parse_uri_full_test)
00263 {
00264    int res = AST_TEST_PASS;
00265    char uri[1024];
00266    char *user, *pass, *hostport, *headers, *residue;
00267    struct uriparams params;
00268 
00269    struct testdata {
00270       char *desc;
00271       char *uri;
00272       char *user;
00273       char *pass;
00274       char *hostport;
00275       char *headers;
00276       char *residue;
00277       struct uriparams params;
00278       AST_LIST_ENTRY(testdata) list;
00279    };
00280 
00281 
00282    struct testdata *testdataptr;
00283 
00284    static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
00285 
00286    struct testdata td1 = {
00287       .desc = "no headers",
00288       .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;param2=residue",
00289       .user = "user",
00290       .pass = "secret",
00291       .hostport = "host:5060",
00292       .headers = "",
00293       .residue = "param2=residue",
00294       .params.transport = "tcp",
00295       .params.lr = 0,
00296       .params.user = ""
00297    };
00298 
00299    struct testdata td2 = {
00300       .desc = "with headers",
00301       .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;param2=discard2?header=blah&header2=blah2;param3=residue",
00302       .user = "user",
00303       .pass = "secret",
00304       .hostport = "host:5060",
00305       .headers = "header=blah&header2=blah2",
00306       .residue = "param3=residue",
00307       .params.transport = "tcp",
00308       .params.lr = 0,
00309       .params.user = ""
00310    };
00311 
00312    struct testdata td3 = {
00313       .desc = "difficult user",
00314       .uri = "sip:-_.!~*'()&=+$,;?/:secret@host:5060;transport=tcp",
00315       .user = "-_.!~*'()&=+$,;?/",
00316       .pass = "secret",
00317       .hostport = "host:5060",
00318       .headers = "",
00319       .residue = "",
00320       .params.transport = "tcp",
00321       .params.lr = 0,
00322       .params.user = ""
00323    };
00324 
00325    struct testdata td4 = {
00326       .desc = "difficult pass",
00327       .uri = "sip:user:-_.!~*'()&=+$,@host:5060;transport=tcp",
00328       .user = "user",
00329       .pass = "-_.!~*'()&=+$,",
00330       .hostport = "host:5060",
00331       .headers = "",
00332       .residue = "",
00333       .params.transport = "tcp",
00334       .params.lr = 0,
00335       .params.user = ""
00336    };
00337 
00338    struct testdata td5 = {
00339       .desc = "difficult host",
00340       .uri = "sip:user:secret@1-1.a-1.:5060;transport=tcp",
00341       .user = "user",
00342       .pass = "secret",
00343       .hostport = "1-1.a-1.:5060",
00344       .headers = "",
00345       .residue = "",
00346       .params.transport = "tcp",
00347       .params.lr = 0,
00348       .params.user = ""
00349    };
00350 
00351    struct testdata td6 = {
00352       .desc = "difficult params near transport",
00353       .uri = "sip:user:secret@host:5060;-_.!~*'()[]/:&+$=-_.!~*'()[]/:&+$;transport=tcp",
00354       .user = "user",
00355       .pass = "secret",
00356       .hostport = "host:5060",
00357       .headers = "",
00358       .residue = "",
00359       .params.transport = "tcp",
00360       .params.lr = 0,
00361       .params.user = ""
00362    };
00363 
00364    struct testdata td7 = {
00365       .desc = "difficult params near headers",
00366       .uri = "sip:user:secret@host:5060;-_.!~*'()[]/:&+$=-_.!~*'()[]/:&+$?header=blah&header2=blah2;-_.!~*'()[]/:&+$=residue",
00367       .user = "user",
00368       .pass = "secret",
00369       .hostport = "host:5060",
00370       .headers = "header=blah&header2=blah2",
00371       .residue = "-_.!~*'()[]/:&+$=residue",
00372       .params.transport = "",
00373       .params.lr = 0,
00374       .params.user = ""
00375    };
00376 
00377    struct testdata td8 = {
00378       .desc = "lr parameter",
00379       .uri = "sip:user:secret@host:5060;param=discard;lr?header=blah",
00380       .user = "user",
00381       .pass = "secret",
00382       .hostport = "host:5060",
00383       .headers = "header=blah",
00384       .residue = "",
00385       .params.transport = "",
00386       .params.lr = 1,
00387       .params.user = ""
00388    };
00389 
00390    struct testdata td9 = {
00391       .desc = "alternative lr parameter",
00392       .uri = "sip:user:secret@host:5060;param=discard;lr=yes?header=blah",
00393       .user = "user",
00394       .pass = "secret",
00395       .hostport = "host:5060",
00396       .headers = "header=blah",
00397       .residue = "",
00398       .params.transport = "",
00399       .params.lr = 1,
00400       .params.user = ""
00401    };
00402 
00403    struct testdata td10 = {
00404       .desc = "no lr parameter",
00405       .uri = "sip:user:secret@host:5060;paramlr=lr;lr=no;lr=off;lr=0;lr=;=lr;lrextra;lrparam2=lr?header=blah",
00406       .user = "user",
00407       .pass = "secret",
00408       .hostport = "host:5060",
00409       .headers = "header=blah",
00410       .residue = "",
00411       .params.transport = "",
00412       .params.lr = 0,
00413       .params.user = ""
00414    };
00415 
00416    /* RFC 3966 TEL URI INVITE */
00417    struct testdata td11 = {
00418       .desc = "tel local number",
00419       .uri = "tel:0987654321;phone-context=+32987654321",
00420       .user = "0987654321",
00421       .pass = "",
00422       .hostport = "+32987654321",
00423       .headers = "",
00424       .residue = "",
00425       .params.transport = "",
00426       .params.lr = 0,
00427       .params.user = ""
00428    };
00429 
00430    struct testdata td12 = {
00431       .desc = "tel global number",
00432       .uri = "tel:+32987654321",
00433       .user = "+32987654321",
00434       .pass = "",
00435       .hostport = "+32987654321",
00436       .headers = "",
00437       .residue = "",
00438       .params.transport = "",
00439       .params.lr = 0,
00440       .params.user = ""
00441    };
00442 
00443    /*
00444     * Once the full RFC 3966 parsing is implemented,
00445     * only the ext= or isub= parameters would be extracted from .user
00446     * Then the ;param=discard would be ignored,
00447     * and the .user would only contain "0987654321"
00448     */
00449    struct testdata td13 = {
00450       .desc = "tel local number",
00451       .uri = "tel:0987654321;ext=1234;param=discard;phone-context=+32987654321;transport=udp;param2=discard2?header=blah&header2=blah2;param3=residue",
00452       .user = "0987654321;ext=1234;param=discard",
00453       .pass = "",
00454       .hostport = "+32987654321",
00455       .headers = "header=blah&header2=blah2",
00456       .residue = "param3=residue",
00457       .params.transport = "udp",
00458       .params.lr = 0,
00459       .params.user = ""
00460    };
00461 
00462    AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
00463    AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
00464    AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
00465    AST_LIST_INSERT_TAIL(&testdatalist, &td4, list);
00466    AST_LIST_INSERT_TAIL(&testdatalist, &td5, list);
00467    AST_LIST_INSERT_TAIL(&testdatalist, &td6, list);
00468    AST_LIST_INSERT_TAIL(&testdatalist, &td7, list);
00469    AST_LIST_INSERT_TAIL(&testdatalist, &td8, list);
00470    AST_LIST_INSERT_TAIL(&testdatalist, &td9, list);
00471    AST_LIST_INSERT_TAIL(&testdatalist, &td10, list);
00472    AST_LIST_INSERT_TAIL(&testdatalist, &td11, list);
00473    AST_LIST_INSERT_TAIL(&testdatalist, &td12, list);
00474    AST_LIST_INSERT_TAIL(&testdatalist, &td13, list);
00475 
00476    switch (cmd) {
00477    case TEST_INIT:
00478       info->name = "sip_uri_full_parse_test";
00479       info->category = "/channels/chan_sip/";
00480       info->summary = "tests sip full uri parsing";
00481       info->description =
00482          "Tests full parsing of various URIs "
00483          "Verifies output matches expected behavior.";
00484       return AST_TEST_NOT_RUN;
00485    case TEST_EXECUTE:
00486       break;
00487    }
00488 
00489    AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
00490       user = pass = hostport = headers = residue = NULL;
00491       params.transport = params.user = params.method = params.ttl = params.maddr = NULL;
00492       params.lr = 0;
00493 
00494       ast_copy_string(uri,testdataptr->uri,sizeof(uri));
00495       if (parse_uri_full(uri, "sip:,sips:,tel:", &user,
00496                &pass, &hostport,
00497                &params,
00498                &headers,
00499                &residue) ||
00500          (user && strcmp(testdataptr->user, user)) ||
00501          (pass && strcmp(testdataptr->pass, pass)) ||
00502          (hostport && strcmp(testdataptr->hostport, hostport)) ||
00503          (headers && strcmp(testdataptr->headers, headers)) ||
00504          (residue && strcmp(testdataptr->residue, residue)) ||
00505          (strcmp(testdataptr->params.transport,params.transport)) ||
00506          (testdataptr->params.lr != params.lr) ||
00507          (strcmp(testdataptr->params.user,params.user))
00508       ) {
00509             ast_test_status_update(test, "Sub-Test: %s, failed.\n", testdataptr->desc);
00510             res = AST_TEST_FAIL;
00511       }
00512    }
00513 
00514 
00515    return res;
00516 }
00517 
00518 
00519 int parse_uri(char *uri, const char *scheme, char **user, char **pass,
00520          char **hostport, char **transport) {
00521    int ret;
00522    char *headers;
00523    struct uriparams params;
00524 
00525    headers = NULL;
00526    ret = parse_uri_full(uri, scheme, user, pass, hostport, &params, &headers, NULL);
00527    if (transport) {
00528       *transport=params.transport;
00529    }
00530    return ret;
00531 }
00532 
00533 AST_TEST_DEFINE(sip_parse_uri_test)
00534 {
00535    int res = AST_TEST_PASS;
00536    char *name, *pass, *hostport, *transport;
00537    char uri1[] = "sip:name@host";
00538    char uri2[] = "sip:name@host;transport=tcp";
00539    char uri3[] = "sip:name:secret@host;transport=tcp";
00540    char uri4[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
00541    /* test 5 is for NULL input */
00542    char uri6[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
00543    char uri7[] = "sip:name:secret@host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
00544    char uri8[] = "sip:host";
00545    char uri9[] = "sip:host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
00546    char uri10[] = "host:port;transport=tcp?headers=%40%40testblah&headers2=blah%20blah";
00547    char uri11[] = "host";
00548    char uri12[] = "tel:911";  /* TEL URI Local number without context or global number */
00549 
00550    switch (cmd) {
00551    case TEST_INIT:
00552       info->name = "sip_uri_parse_test";
00553       info->category = "/channels/chan_sip/";
00554       info->summary = "tests sip uri parsing";
00555       info->description =
00556                      "Tests parsing of various URIs "
00557                      "Verifies output matches expected behavior.";
00558       return AST_TEST_NOT_RUN;
00559    case TEST_EXECUTE:
00560       break;
00561    }
00562 
00563    /* Test 1, simple URI */
00564    name = pass = hostport = transport = NULL;
00565    if (parse_uri(uri1, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00566          strcmp(name, "name")        ||
00567          !ast_strlen_zero(pass)      ||
00568          strcmp(hostport, "host")      ||
00569          !ast_strlen_zero(transport)) {
00570       ast_test_status_update(test, "Test 1: simple uri failed. \n");
00571       res = AST_TEST_FAIL;
00572    }
00573 
00574    /* Test 2, add tcp transport */
00575    name = pass = hostport = transport = NULL;
00576    if (parse_uri(uri2, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00577          strcmp(name, "name")        ||
00578          !ast_strlen_zero(pass)      ||
00579          strcmp(hostport, "host")    ||
00580          strcmp(transport, "tcp")) {
00581       ast_test_status_update(test, "Test 2: uri with addtion of tcp transport failed. \n");
00582       res = AST_TEST_FAIL;
00583    }
00584 
00585    /* Test 3, add secret */
00586    name = pass = hostport = transport = NULL;
00587    if (parse_uri(uri3, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00588          strcmp(name, "name")        ||
00589          strcmp(pass, "secret")      ||
00590          strcmp(hostport, "host")    ||
00591          strcmp(transport, "tcp")) {
00592       ast_test_status_update(test, "Test 3: uri with addition of secret failed.\n");
00593       res = AST_TEST_FAIL;
00594    }
00595 
00596    /* Test 4, add port and unparsed header field*/
00597    name = pass = hostport = transport = NULL;
00598    if (parse_uri(uri4, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00599          strcmp(name, "name")        ||
00600          strcmp(pass, "secret")      ||
00601          strcmp(hostport, "host:port") ||
00602          strcmp(transport, "tcp")) {
00603       ast_test_status_update(test, "Test 4: add port and unparsed header field failed.\n");
00604       res = AST_TEST_FAIL;
00605    }
00606 
00607    /* Test 5, verify parse_uri does not crash when given a NULL uri */
00608    name = pass = hostport = transport = NULL;
00609    if (!parse_uri(NULL, "sip:,sips:", &name, &pass, &hostport, &transport)) {
00610       ast_test_status_update(test, "Test 5: passing a NULL uri failed.\n");
00611       res = AST_TEST_FAIL;
00612    }
00613 
00614    /* Test 6, verify parse_uri does not crash when given a NULL output parameters */
00615    name = pass = hostport = transport = NULL;
00616    if (parse_uri(uri6, "sip:,sips:", NULL, NULL, NULL, NULL)) {
00617       ast_test_status_update(test, "Test 6: passing NULL output parameters failed.\n");
00618       res = AST_TEST_FAIL;
00619    }
00620 
00621    /* Test 7, verify parse_uri returns user:secret and hostport when no port or secret output parameters are supplied. */
00622    name = pass = hostport = transport = NULL;
00623    if (parse_uri(uri7, "sip:,sips:", &name, NULL, &hostport, NULL) ||
00624          strcmp(name, "name:secret")        ||
00625          strcmp(hostport, "host:port")) {
00626 
00627       ast_test_status_update(test, "Test 7: providing no port and secret output parameters failed.\n");
00628       res = AST_TEST_FAIL;
00629    }
00630 
00631    /* Test 8, verify parse_uri can handle a hostport only uri */
00632    name = pass = hostport = transport = NULL;
00633    if (parse_uri(uri8, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00634          strcmp(hostport, "host") ||
00635          !ast_strlen_zero(name)) {
00636       ast_test_status_update(test, "Test 8: add port and unparsed header field failed.\n");
00637       res = AST_TEST_FAIL;
00638    }
00639 
00640    /* Test 9, add port and unparsed header field with hostport only uri*/
00641    name = pass = hostport = transport = NULL;
00642    if (parse_uri(uri9, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00643          !ast_strlen_zero(name)        ||
00644          !ast_strlen_zero(pass)      ||
00645          strcmp(hostport, "host:port")    ||
00646          strcmp(transport, "tcp")) {
00647       ast_test_status_update(test, "Test 9: hostport only uri failed \n");
00648       res = AST_TEST_FAIL;
00649    }
00650 
00651    /* Test 10, handle invalid/missing "sip:,sips:" scheme
00652     * we expect parse_uri to return an error, but still parse
00653     * the results correctly here */
00654    name = pass = hostport = transport = NULL;
00655    if (!parse_uri(uri10, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00656          !ast_strlen_zero(name)        ||
00657          !ast_strlen_zero(pass)      ||
00658          strcmp(hostport, "host:port")    ||
00659          strcmp(transport, "tcp")) {
00660       ast_test_status_update(test, "Test 10: missing \"sip:sips:\" scheme failed\n");
00661       res = AST_TEST_FAIL;
00662    }
00663 
00664    /* Test 11, simple hostport only URI with missing scheme
00665     * we expect parse_uri to return an error, but still parse
00666     * the results correctly here */
00667    name = pass = hostport = transport = NULL;
00668    if (!parse_uri(uri11, "sip:,sips:", &name, &pass, &hostport, &transport) ||
00669          !ast_strlen_zero(name)      ||
00670          !ast_strlen_zero(pass)      ||
00671          strcmp(hostport, "host")      ||
00672          !ast_strlen_zero(transport)) {
00673       ast_test_status_update(test, "Test 11: simple uri with missing scheme failed. \n");
00674       res = AST_TEST_FAIL;
00675    }
00676 
00677    /* Test 12, simple URI */
00678    name = pass = hostport = transport = NULL;
00679    if (!parse_uri(uri12, "sip:,sips:,tel:", &name, &pass, &hostport, &transport) ||
00680          strcmp(name, "911")      ||   /* We return local number anyway */
00681          !ast_strlen_zero(pass)      ||
00682          !ast_strlen_zero(hostport)      ||  /* No global number nor context */
00683          !ast_strlen_zero(transport)) {
00684       ast_test_status_update(test, "Test 12: TEL URI INVITE failed.\n");
00685       res = AST_TEST_FAIL;
00686    }
00687 
00688    return res;
00689 }
00690 
00691 /*! \brief  Get caller id name from SIP headers, copy into output buffer
00692  *
00693  *  \retval input string pointer placed after display-name field if possible
00694  */
00695 const char *get_calleridname(const char *input, char *output, size_t outputsize)
00696 {
00697    /* From RFC3261:
00698     *
00699     * From           =  ( "From" / "f" ) HCOLON from-spec
00700     * from-spec      =  ( name-addr / addr-spec ) *( SEMI from-param )
00701     * name-addr      =  [ display-name ] LAQUOT addr-spec RAQUOT
00702     * display-name   =  *(token LWS)/ quoted-string
00703     * token          =  1*(alphanum / "-" / "." / "!" / "%" / "*"
00704     *                     / "_" / "+" / "`" / "'" / "~" )
00705     * quoted-string  =  SWS DQUOTE *(qdtext / quoted-pair ) DQUOTE
00706     * qdtext         =  LWS / %x21 / %x23-5B / %x5D-7E
00707     *                     / UTF8-NONASCII
00708     * quoted-pair    =  "\" (%x00-09 / %x0B-0C / %x0E-7F)
00709     *
00710     * HCOLON         = *WSP ":" SWS
00711     * SWS            = [LWS]
00712     * LWS            = *[*WSP CRLF] 1*WSP
00713     * WSP            = (SP / HTAB)
00714     *
00715     * Deviations from it:
00716     * - following CRLF's in LWS is not done (here at least)
00717     * - ascii NUL is never legal as it terminates the C-string
00718     * - utf8-nonascii is not checked for validity
00719     */
00720    char *orig_output = output;
00721    const char *orig_input = input;
00722 
00723    if (!output || !outputsize) {
00724       /* Bad output parameters.  Should never happen. */
00725       return input;
00726    }
00727 
00728    /* clear any empty characters in the beginning */
00729    input = ast_skip_blanks(input);
00730 
00731    /* make sure the output buffer is initilized */
00732    *orig_output = '\0';
00733 
00734    /* make room for '\0' at the end of the output buffer */
00735    --outputsize;
00736 
00737    /* no data at all or no display name? */
00738    if (!input || *input == '<') {
00739       return input;
00740    }
00741 
00742    /* quoted-string rules */
00743    if (input[0] == '"') {
00744       input++; /* skip the first " */
00745 
00746       for (; *input; ++input) {
00747          if (*input == '"') {  /* end of quoted-string */
00748             break;
00749          } else if (*input == 0x5c) { /* quoted-pair = "\" (%x00-09 / %x0B-0C / %x0E-7F) */
00750             ++input;
00751             if (!*input) {
00752                break;
00753             }
00754             if ((unsigned char) *input > 0x7f || *input == 0xa || *input == 0xd) {
00755                continue;  /* not a valid quoted-pair, so skip it */
00756             }
00757          } else if ((*input != 0x9 && (unsigned char) *input < 0x20)
00758             || *input == 0x7f) {
00759             continue; /* skip this invalid character. */
00760          }
00761 
00762          if (0 < outputsize) {
00763             /* We still have room for the output display-name. */
00764             *output++ = *input;
00765             --outputsize;
00766          }
00767       }
00768 
00769       /* if this is successful, input should be at the ending quote */
00770       if (*input != '"') {
00771          ast_log(LOG_WARNING, "No ending quote for display-name was found\n");
00772          *orig_output = '\0';
00773          return orig_input;
00774       }
00775 
00776       /* make sure input is past the last quote */
00777       ++input;
00778 
00779       /* terminate output */
00780       *output = '\0';
00781    } else {  /* either an addr-spec or tokenLWS-combo */
00782       for (; *input; ++input) {
00783          /* token or WSP (without LWS) */
00784          if ((*input >= '0' && *input <= '9') || (*input >= 'A' && *input <= 'Z')
00785             || (*input >= 'a' && *input <= 'z') || *input == '-' || *input == '.'
00786             || *input == '!' || *input == '%' || *input == '*' || *input == '_'
00787             || *input == '+' || *input == '`' || *input == '\'' || *input == '~'
00788             || *input == 0x9 || *input == ' ') {
00789             if (0 < outputsize) {
00790                /* We still have room for the output display-name. */
00791                *output++ = *input;
00792                --outputsize;
00793             }
00794          } else if (*input == '<') {   /* end of tokenLWS-combo */
00795             /* we could assert that the previous char is LWS, but we don't care */
00796             break;
00797          } else if (*input == ':') {
00798             /* This invalid character which indicates this is addr-spec rather than display-name. */
00799             *orig_output = '\0';
00800             return orig_input;
00801          } else {         /* else, invalid character we can skip. */
00802             continue;    /* skip this character */
00803          }
00804       }
00805 
00806       if (*input != '<') {   /* if we never found the start of addr-spec then this is invalid */
00807          *orig_output = '\0';
00808          return orig_input;
00809       }
00810 
00811       /* terminate output while trimming any trailing whitespace */
00812       do {
00813          *output-- = '\0';
00814       } while (orig_output <= output && (*output == 0x9 || *output == ' '));
00815    }
00816 
00817    return input;
00818 }
00819 
00820 AST_TEST_DEFINE(get_calleridname_test)
00821 {
00822    int res = AST_TEST_PASS;
00823    const char *in1 = " \" quoted-text internal \\\" quote \"<stuff>";
00824    const char *in2 = " token text with no quotes <stuff>";
00825    const char *overflow1 = " \"quoted-text overflow 1234567890123456789012345678901234567890\" <stuff>";
00826    const char *overflow2 = " non-quoted text overflow 1234567890123456789012345678901234567890 <stuff>";
00827    const char *noendquote = " \"quoted-text no end <stuff>";
00828    const char *addrspec = " sip:blah@blah";
00829    const char *no_quotes_no_brackets = "blah@blah";
00830    const char *after_dname;
00831    char dname[40];
00832 
00833    switch (cmd) {
00834    case TEST_INIT:
00835       info->name = "sip_get_calleridname_test";
00836       info->category = "/channels/chan_sip/";
00837       info->summary = "decodes callerid name from sip header";
00838       info->description = "Decodes display-name field of sip header.  Checks for valid output and expected failure cases.";
00839       return AST_TEST_NOT_RUN;
00840    case TEST_EXECUTE:
00841       break;
00842    }
00843 
00844    /* quoted-text with backslash escaped quote */
00845    after_dname = get_calleridname(in1, dname, sizeof(dname));
00846    ast_test_status_update(test, "display-name1: %s\nafter: %s\n", dname, after_dname);
00847    if (strcmp(dname, " quoted-text internal \" quote ")) {
00848       ast_test_status_update(test, "display-name1 test failed\n");
00849       res = AST_TEST_FAIL;
00850    }
00851 
00852    /* token text */
00853    after_dname = get_calleridname(in2, dname, sizeof(dname));
00854    ast_test_status_update(test, "display-name2: %s\nafter: %s\n", dname, after_dname);
00855    if (strcmp(dname, "token text with no quotes")) {
00856       ast_test_status_update(test, "display-name2 test failed\n");
00857       res = AST_TEST_FAIL;
00858    }
00859 
00860    /* quoted-text buffer overflow */
00861    after_dname = get_calleridname(overflow1, dname, sizeof(dname));
00862    ast_test_status_update(test, "overflow display-name1: %s\nafter: %s\n", dname, after_dname);
00863    if (strcmp(dname, "quoted-text overflow 123456789012345678")) {
00864       ast_test_status_update(test, "overflow display-name1 test failed\n");
00865       res = AST_TEST_FAIL;
00866    }
00867 
00868    /* non-quoted-text buffer overflow */
00869    after_dname = get_calleridname(overflow2, dname, sizeof(dname));
00870    ast_test_status_update(test, "overflow display-name2: %s\nafter: %s\n", dname, after_dname);
00871    if (strcmp(dname, "non-quoted text overflow 12345678901234")) {
00872       ast_test_status_update(test, "overflow display-name2 test failed\n");
00873       res = AST_TEST_FAIL;
00874    }
00875 
00876    /* quoted-text buffer with no terminating end quote */
00877    after_dname = get_calleridname(noendquote, dname, sizeof(dname));
00878    ast_test_status_update(test, "noendquote display-name1: %s\nafter: %s\n", dname, after_dname);
00879    if (*dname != '\0' && after_dname != noendquote) {
00880       ast_test_status_update(test, "no end quote for quoted-text display-name failed\n");
00881       res = AST_TEST_FAIL;
00882    }
00883 
00884    /* addr-spec rather than display-name. */
00885    after_dname = get_calleridname(addrspec, dname, sizeof(dname));
00886    ast_test_status_update(test, "addr-spec display-name1: %s\nafter: %s\n", dname, after_dname);
00887    if (*dname != '\0' && after_dname != addrspec) {
00888       ast_test_status_update(test, "detection of addr-spec failed\n");
00889       res = AST_TEST_FAIL;
00890    }
00891 
00892    /* no quotes, no brackets */
00893    after_dname = get_calleridname(no_quotes_no_brackets, dname, sizeof(dname));
00894    ast_test_status_update(test, "no_quotes_no_brackets display-name1: %s\nafter: %s\n", dname, after_dname);
00895    if (*dname != '\0' && after_dname != no_quotes_no_brackets) {
00896       ast_test_status_update(test, "detection of addr-spec failed\n");
00897       res = AST_TEST_FAIL;
00898    }
00899 
00900    return res;
00901 }
00902 
00903 int get_name_and_number(const char *hdr, char **name, char **number)
00904 {
00905    char header[256];
00906    char tmp_name[256];
00907    char *tmp_number = NULL;
00908    char *hostport = NULL;
00909    char *dummy = NULL;
00910 
00911    if (!name || !number || ast_strlen_zero(hdr)) {
00912       return -1;
00913    }
00914 
00915    *number = NULL;
00916    *name = NULL;
00917    ast_copy_string(header, hdr, sizeof(header));
00918 
00919    /* strip the display-name portion off the beginning of the header. */
00920    get_calleridname(header, tmp_name, sizeof(tmp_name));
00921 
00922    /* get uri within < > brackets */
00923    tmp_number = get_in_brackets(header);
00924 
00925    /* parse out the number here */
00926    if (parse_uri(tmp_number, "sip:,sips:", &tmp_number, &dummy, &hostport, NULL) || ast_strlen_zero(tmp_number)) {
00927       ast_log(LOG_ERROR, "can not parse name and number from sip header.\n");
00928       return -1;
00929    }
00930 
00931    /* number is not option, and must be present at this point */
00932    *number = ast_strdup(tmp_number);
00933    ast_uri_decode(*number, ast_uri_sip_user);
00934 
00935    /* name is optional and may not be present at this point */
00936    if (!ast_strlen_zero(tmp_name)) {
00937       *name = ast_strdup(tmp_name);
00938    }
00939 
00940    return 0;
00941 }
00942 
00943 AST_TEST_DEFINE(get_name_and_number_test)
00944 {
00945    int res = AST_TEST_PASS;
00946    char *name = NULL;
00947    char *number = NULL;
00948    const char *in1 = "NAME <sip:NUMBER@place>";
00949    const char *in2 = "\"NA><ME\" <sip:NUMBER@place>";
00950    const char *in3 = "NAME";
00951    const char *in4 = "<sip:NUMBER@place>";
00952    const char *in5 = "This is a screwed up string <sip:LOLCLOWNS<sip:>@place>";
00953 
00954    switch (cmd) {
00955    case TEST_INIT:
00956       info->name = "sip_get_name_and_number_test";
00957       info->category = "/channels/chan_sip/";
00958       info->summary = "Tests getting name and number from sip header";
00959       info->description =
00960             "Runs through various test situations in which a name and "
00961             "and number can be retrieved from a sip header.";
00962       return AST_TEST_NOT_RUN;
00963    case TEST_EXECUTE:
00964       break;
00965    }
00966 
00967    /* Test 1. get name and number */
00968    number = name = NULL;
00969    if ((get_name_and_number(in1, &name, &number)) ||
00970       strcmp(name, "NAME") ||
00971       strcmp(number, "NUMBER")) {
00972 
00973       ast_test_status_update(test, "Test 1, simple get name and number failed.\n");
00974       res = AST_TEST_FAIL;
00975    }
00976    ast_free(name);
00977    ast_free(number);
00978 
00979    /* Test 2. get quoted name and number */
00980    number = name = NULL;
00981    if ((get_name_and_number(in2, &name, &number)) ||
00982       strcmp(name, "NA><ME") ||
00983       strcmp(number, "NUMBER")) {
00984 
00985       ast_test_status_update(test, "Test 2, get quoted name and number failed.\n");
00986       res = AST_TEST_FAIL;
00987    }
00988    ast_free(name);
00989    ast_free(number);
00990 
00991    /* Test 3. name only */
00992    number = name = NULL;
00993    if (!(get_name_and_number(in3, &name, &number))) {
00994 
00995       ast_test_status_update(test, "Test 3, get name only was expected to fail but did not.\n");
00996       res = AST_TEST_FAIL;
00997    }
00998    ast_free(name);
00999    ast_free(number);
01000 
01001    /* Test 4. number only */
01002    number = name = NULL;
01003    if ((get_name_and_number(in4, &name, &number)) ||
01004       !ast_strlen_zero(name) ||
01005       strcmp(number, "NUMBER")) {
01006 
01007       ast_test_status_update(test, "Test 4, get number with no name present failed.\n");
01008       res = AST_TEST_FAIL;
01009    }
01010    ast_free(name);
01011    ast_free(number);
01012 
01013    /* Test 5. malformed string, since number can not be parsed, this should return an error.  */
01014    number = name = NULL;
01015    if (!(get_name_and_number(in5, &name, &number)) ||
01016       !ast_strlen_zero(name) ||
01017       !ast_strlen_zero(number)) {
01018 
01019       ast_test_status_update(test, "Test 5, processing malformed string failed.\n");
01020       res = AST_TEST_FAIL;
01021    }
01022    ast_free(name);
01023    ast_free(number);
01024 
01025    /* Test 6. NULL output parameters */
01026    number = name = NULL;
01027    if (!(get_name_and_number(in5, NULL, NULL))) {
01028 
01029       ast_test_status_update(test, "Test 6, NULL output parameters failed.\n");
01030       res = AST_TEST_FAIL;
01031    }
01032 
01033    /* Test 7. NULL input parameter */
01034    number = name = NULL;
01035    if (!(get_name_and_number(NULL, &name, &number)) ||
01036       !ast_strlen_zero(name) ||
01037       !ast_strlen_zero(number)) {
01038 
01039       ast_test_status_update(test, "Test 7, NULL input parameter failed.\n");
01040       res = AST_TEST_FAIL;
01041    }
01042    ast_free(name);
01043    ast_free(number);
01044 
01045    return res;
01046 }
01047 
01048 int get_in_brackets_const(const char *src,const char **start,int *length)
01049 {
01050    const char *parse = src;
01051    const char *first_bracket;
01052    const char *second_bracket;
01053 
01054    if (start == NULL) {
01055       return -1;
01056    }
01057    if (length == NULL) {
01058       return -1;
01059    }
01060    *start = NULL;
01061    *length = -1;
01062    if (ast_strlen_zero(src)) {
01063       return 1;
01064    }
01065 
01066    /*
01067     * Skip any quoted text until we find the part in brackets.
01068     * On any error give up and return -1
01069     */
01070    while ( (first_bracket = strchr(parse, '<')) ) {
01071       const char *first_quote = strchr(parse, '"');
01072       first_bracket++;
01073       if (!first_quote || first_quote >= first_bracket) {
01074          break; /* no need to look at quoted part */
01075       }
01076       /* the bracket is within quotes, so ignore it */
01077       parse = find_closing_quote(first_quote + 1, NULL);
01078       if (!*parse) {
01079          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", src);
01080          return  -1;
01081       }
01082       parse++;
01083    }
01084 
01085    /* Require a first bracket.  Unlike get_in_brackets_full, this procedure is passed a const,
01086     * so it can expect a pointer to an original value */
01087    if (!first_bracket) {
01088       ast_log(LOG_WARNING, "No opening bracket found in '%s'\n", src);
01089       return 1;
01090    }
01091 
01092    if ((second_bracket = strchr(first_bracket, '>'))) {
01093       *start = first_bracket;
01094       *length = second_bracket - first_bracket;
01095       return 0;
01096    }
01097    ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", src);
01098    return -1;
01099 }
01100 
01101 int get_in_brackets_full(char *tmp,char **out,char **residue)
01102 {
01103    const char *parse = tmp;
01104    char *first_bracket;
01105    char *second_bracket;
01106 
01107    if (out) {
01108       *out = "";
01109    }
01110    if (residue) {
01111       *residue = "";
01112    }
01113 
01114    if (ast_strlen_zero(tmp)) {
01115       return 1;
01116    }
01117 
01118    /*
01119     * Skip any quoted text until we find the part in brackets.
01120    * On any error give up and return -1
01121    */
01122    while ( (first_bracket = strchr(parse, '<')) ) {
01123       char *first_quote = strchr(parse, '"');
01124       first_bracket++;
01125       if (!first_quote || first_quote >= first_bracket) {
01126          break; /* no need to look at quoted part */
01127       }
01128       /* the bracket is within quotes, so ignore it */
01129       parse = find_closing_quote(first_quote + 1, NULL);
01130       if (!*parse) {
01131          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
01132          return  -1;
01133       }
01134       parse++;
01135    }
01136 
01137    /* If no first bracket then still look for a second bracket as some other parsing functions
01138    may overwrite first bracket with NULL when terminating a token based display-name. As this
01139    only affects token based display-names there is no danger of brackets being in quotes */
01140    if (first_bracket) {
01141       parse = first_bracket;
01142    } else {
01143       parse = tmp;
01144    }
01145 
01146    if ((second_bracket = strchr(parse, '>'))) {
01147       *second_bracket++ = '\0';
01148       if (out) {
01149          *out = (char *) parse;
01150       }
01151       if (residue) {
01152          *residue = second_bracket;
01153       }
01154       return 0;
01155    }
01156 
01157    if ((first_bracket)) {
01158       ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
01159       return -1;
01160    }
01161 
01162    if (out) {
01163       *out = tmp;
01164    }
01165 
01166    return 1;
01167 }
01168 
01169 char *get_in_brackets(char *tmp)
01170 {
01171    char *out;
01172 
01173    if ((get_in_brackets_full(tmp, &out, NULL))) {
01174       return tmp;
01175    }
01176    return out;
01177 }
01178 
01179 AST_TEST_DEFINE(get_in_brackets_test)
01180 {
01181    int res = AST_TEST_PASS;
01182    char in_brackets[] = "sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah";
01183    char no_name[] = "<sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
01184    char quoted_string[] = "\"I'm a quote stri><ng\" <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
01185    char missing_end_quote[] = "\"I'm a quote string <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
01186    char name_no_quotes[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
01187    char no_end_bracket[] = "name not in quotes <sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah";
01188    char no_name_no_brackets[] = "sip:name@host";
01189    char missing_start_bracket[] = "sip:name:secret@host:port;transport=tcp?headers=testblah&headers2=blahblah>";
01190    char *uri = NULL;
01191 
01192    switch (cmd) {
01193    case TEST_INIT:
01194       info->name = "sip_get_in_brackets_test";
01195       info->category = "/channels/chan_sip/";
01196       info->summary = "Tests getting a sip uri in <> brackets within a sip header.";
01197       info->description =
01198             "Runs through various test situations in which a sip uri "
01199             "in angle brackets needs to be retrieved";
01200       return AST_TEST_NOT_RUN;
01201    case TEST_EXECUTE:
01202       break;
01203    }
01204 
01205    /* Test 1, simple get in brackets */
01206    if (!(uri = get_in_brackets(no_name)) || strcmp(uri, in_brackets)) {
01207       ast_test_status_update(test, "Test 1, simple get in brackets failed. %s\n", uri);
01208       res = AST_TEST_FAIL;
01209    }
01210 
01211    /* Test 2, starts with quoted string */
01212    if (!(uri = get_in_brackets(quoted_string)) || strcmp(uri, in_brackets)) {
01213       ast_test_status_update(test, "Test 2, get in brackets with quoted string in front failed. %s\n", uri);
01214       res = AST_TEST_FAIL;
01215    }
01216 
01217    /* Test 3, missing end quote */
01218    if (!(uri = get_in_brackets(missing_end_quote)) || !strcmp(uri, in_brackets)) {
01219       ast_test_status_update(test, "Test 3, missing end quote failed. %s\n", uri);
01220       res = AST_TEST_FAIL;
01221    }
01222 
01223    /* Test 4, starts with a name not in quotes */
01224    if (!(uri = get_in_brackets(name_no_quotes)) || strcmp(uri, in_brackets)) {
01225       ast_test_status_update(test, "Test 4, passing name not in quotes failed. %s\n", uri);
01226       res = AST_TEST_FAIL;
01227    }
01228 
01229    /* Test 5, no end bracket, should just return everything after the first '<'  */
01230    if (!(uri = get_in_brackets(no_end_bracket)) || !strcmp(uri, in_brackets)) {
01231       ast_test_status_update(test, "Test 5, no end bracket failed. %s\n", uri);
01232       res = AST_TEST_FAIL;
01233    }
01234 
01235    /* Test 6, NULL input  */
01236    if (get_in_brackets(NULL)) {
01237       ast_test_status_update(test, "Test 6, NULL input failed.\n");
01238       res = AST_TEST_FAIL;
01239    }
01240 
01241    /* Test 7, no name, and no brackets. */
01242    if (!(uri = get_in_brackets(no_name_no_brackets)) || strcmp(uri, "sip:name@host")) {
01243       ast_test_status_update(test, "Test 7 failed. %s\n", uri);
01244       res = AST_TEST_FAIL;
01245    }
01246 
01247    /* Test 8, no start bracket, but with ending bracket. */
01248    if (!(uri = get_in_brackets(missing_start_bracket)) || strcmp(uri, in_brackets)) {
01249       ast_test_status_update(test, "Test 8 failed. %s\n", uri);
01250       res = AST_TEST_FAIL;
01251    }
01252 
01253    return res;
01254 }
01255 
01256 
01257 int parse_name_andor_addr(char *uri, const char *scheme, char **name,
01258            char **user, char **pass, char **hostport,
01259            struct uriparams *params, char **headers,
01260            char **residue)
01261 {
01262    char buf[1024];
01263    char **residue2 = residue;
01264    char *orig_uri = uri;
01265    int ret;
01266 
01267    buf[0] = '\0';
01268    if (name) {
01269       uri = (char *) get_calleridname(uri, buf, sizeof(buf));
01270    }
01271    ret = get_in_brackets_full(uri, &uri, residue);
01272    if (ret == 0) {
01273       /*
01274        * The uri is in brackets so do not treat unknown trailing uri
01275        * parameters as potential message header parameters.
01276        */
01277       if (residue && **residue) {
01278          /* step over the first semicolon as per parse_uri_full residue */
01279          *residue = *residue + 1;
01280       }
01281       residue2 = NULL;
01282    }
01283 
01284    if (name) {
01285       if (buf[0]) {
01286          /*
01287           * There is always room at orig_uri for the display-name because
01288           * at least one character has always been removed.  A '"' or '<'
01289           * has been removed.
01290           */
01291          strcpy(orig_uri, buf);
01292          *name = orig_uri;
01293       } else {
01294          *name = "";
01295       }
01296    }
01297 
01298    return parse_uri_full(uri, scheme, user, pass, hostport, params, headers, residue2);
01299 }
01300 
01301 AST_TEST_DEFINE(parse_name_andor_addr_test)
01302 {
01303    int res = AST_TEST_PASS;
01304    char uri[1024];
01305    char *name, *user, *pass, *hostport, *headers, *residue;
01306    struct uriparams params;
01307 
01308    struct testdata {
01309       char *desc;
01310       char *uri;
01311       char *name;
01312       char *user;
01313       char *pass;
01314       char *hostport;
01315       char *headers;
01316       char *residue;
01317       struct uriparams params;
01318       AST_LIST_ENTRY(testdata) list;
01319    };
01320 
01321    struct testdata *testdataptr;
01322 
01323    static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
01324 
01325    struct testdata td1 = {
01326       .desc = "quotes and brackets",
01327       .uri = "\"name :@ \" <sip:user:secret@host:5060;param=discard;transport=tcp>;tag=tag",
01328       .name =  "name :@ ",
01329       .user = "user",
01330       .pass = "secret",
01331       .hostport = "host:5060",
01332       .headers = "",
01333       .residue = "tag=tag",
01334       .params.transport = "tcp",
01335       .params.lr = 0,
01336       .params.user = ""
01337    };
01338 
01339    struct testdata td2 = {
01340       .desc = "no quotes",
01341       .uri = "givenname familyname <sip:user:secret@host:5060;param=discard;transport=tcp>;expires=3600",
01342       .name = "givenname familyname",
01343       .user = "user",
01344       .pass = "secret",
01345       .hostport = "host:5060",
01346       .headers = "",
01347       .residue = "expires=3600",
01348       .params.transport = "tcp",
01349       .params.lr = 0,
01350       .params.user = ""
01351    };
01352 
01353    struct testdata td3 = {
01354       .desc = "no brackets",
01355       .uri = "sip:user:secret@host:5060;param=discard;transport=tcp;q=1",
01356       .name = "",
01357       .user = "user",
01358       .pass = "secret",
01359       .hostport = "host:5060",
01360       .headers = "",
01361       .residue = "q=1",
01362       .params.transport = "tcp",
01363       .params.lr = 0,
01364       .params.user = ""
01365    };
01366 
01367    struct testdata td4 = {
01368       .desc = "just host",
01369       .uri = "sips:host",
01370       .name = "",
01371       .user = "",
01372       .pass = "",
01373       .hostport = "host",
01374       .headers = "",
01375       .residue = "",
01376       .params.transport = "",
01377       .params.lr = 0,
01378       .params.user = ""
01379    };
01380 
01381 
01382    AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
01383    AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
01384    AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
01385    AST_LIST_INSERT_TAIL(&testdatalist, &td4, list);
01386 
01387 
01388    switch (cmd) {
01389    case TEST_INIT:
01390       info->name = "parse_name_andor_addr_test";
01391       info->category = "/channels/chan_sip/";
01392       info->summary = "tests parsing of name_andor_addr abnf structure";
01393       info->description =
01394          "Tests parsing of abnf name-andor-addr = name-addr / addr-spec "
01395          "Verifies output matches expected behavior.";
01396       return AST_TEST_NOT_RUN;
01397    case TEST_EXECUTE:
01398       break;
01399    }
01400 
01401    AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
01402       name = user = pass = hostport = headers = residue = NULL;
01403       params.transport = params.user = params.method = params.ttl = params.maddr = NULL;
01404       params.lr = 0;
01405       ast_copy_string(uri,testdataptr->uri,sizeof(uri));
01406       if (parse_name_andor_addr(uri, "sip:,sips:",
01407                  &name,
01408                  &user,
01409                  &pass,
01410                  &hostport,
01411                  &params,
01412                  &headers,
01413                  &residue) ||
01414          (name && strcmp(testdataptr->name, name)) ||
01415          (user && strcmp(testdataptr->user, user)) ||
01416          (pass && strcmp(testdataptr->pass, pass)) ||
01417          (hostport && strcmp(testdataptr->hostport, hostport)) ||
01418          (headers && strcmp(testdataptr->headers, headers)) ||
01419          (residue && strcmp(testdataptr->residue, residue)) ||
01420          (strcmp(testdataptr->params.transport,params.transport)) ||
01421          (strcmp(testdataptr->params.user,params.user))
01422          ) {
01423          ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
01424          res = AST_TEST_FAIL;
01425       }
01426    }
01427 
01428    return res;
01429 }
01430 
01431 int get_comma(char *in, char **out)
01432 {
01433    char *c;
01434    char *parse = in;
01435    if (out) {
01436       *out = in;
01437    }
01438 
01439    /* Skip any quoted text */
01440    while (*parse) {
01441       if ((c = strchr(parse, '"'))) {
01442          in = (char *)find_closing_quote((const char *)c + 1, NULL);
01443          if (!*in) {
01444             ast_log(LOG_WARNING, "No closing quote found in '%s'\n", c);
01445             return -1;
01446          } else {
01447             break;
01448          }
01449       } else {
01450          break;
01451       }
01452       parse++;
01453    }
01454    parse = in;
01455 
01456    /* Skip any userinfo components of a uri as they may contain commas */
01457    if ((c = strchr(parse,'@'))) {
01458       parse = c+1;
01459    }
01460    if ((out) && (c = strchr(parse,','))) {
01461       *c++ = '\0';
01462       *out = c;
01463       return 0;
01464    }
01465    return 1;
01466 }
01467 
01468 int parse_contact_header(char *contactheader, struct contactliststruct *contactlist)
01469 {
01470    int res;
01471    int last;
01472    char *comma;
01473    char *residue;
01474    char *param;
01475    char *value;
01476    struct contact *split_contact = NULL;
01477 
01478    if (*contactheader == '*') {
01479       return 1;
01480    }
01481 
01482    split_contact = ast_calloc(1, sizeof(*split_contact));
01483 
01484    AST_LIST_HEAD_SET_NOLOCK(contactlist, split_contact);
01485    while ((last = get_comma(contactheader, &comma)) != -1) {
01486       res = parse_name_andor_addr(contactheader, "sip:,sips:",
01487          &split_contact->name, &split_contact->user,
01488          &split_contact->pass, &split_contact->hostport,
01489          &split_contact->params, &split_contact->headers,
01490          &residue);
01491       if (res == -1) {
01492          return res;
01493       }
01494 
01495       /* parse contact params */
01496       split_contact->expires = split_contact->q = "";
01497 
01498       while ((value = strchr(residue,'='))) {
01499          *value++ = '\0';
01500 
01501          param = residue;
01502          if ((residue = strchr(value,';'))) {
01503             *residue++ = '\0';
01504          } else {
01505             residue = "";
01506          }
01507 
01508          if (!strcmp(param,"expires")) {
01509             split_contact->expires = value;
01510          } else if (!strcmp(param,"q")) {
01511             split_contact->q = value;
01512          }
01513       }
01514 
01515       if (last) {
01516          return 0;
01517       }
01518       contactheader = comma;
01519 
01520       split_contact = ast_calloc(1, sizeof(*split_contact));
01521       AST_LIST_INSERT_TAIL(contactlist, split_contact, list);
01522    }
01523    return last;
01524 }
01525 
01526 AST_TEST_DEFINE(parse_contact_header_test)
01527 {
01528    int res = AST_TEST_PASS;
01529    char contactheader[1024];
01530    int star;
01531    struct contactliststruct contactlist;
01532    struct contactliststruct *contactlistptr=&contactlist;
01533 
01534    struct testdata {
01535       char *desc;
01536       char *contactheader;
01537       int star;
01538       struct contactliststruct *contactlist;
01539 
01540       AST_LIST_ENTRY(testdata) list;
01541    };
01542 
01543    struct testdata *testdataptr;
01544    struct contact *tdcontactptr;
01545    struct contact *contactptr;
01546 
01547    static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
01548    struct contactliststruct contactlist1, contactlist2;
01549 
01550    struct testdata td1 = {
01551       .desc = "single contact",
01552       .contactheader = "\"name :@;?&,\" <sip:user:secret@host:5082;param=discard;transport=tcp>;expires=3600",
01553       .contactlist = &contactlist1,
01554       .star = 0
01555    };
01556    struct contact contact11 = {
01557       .name = "name :@;?&,",
01558       .user = "user",
01559       .pass = "secret",
01560       .hostport = "host:5082",
01561       .params.transport = "tcp",
01562       .params.ttl = "",
01563       .params.lr = 0,
01564       .headers = "",
01565       .expires = "3600",
01566       .q = ""
01567    };
01568 
01569    struct testdata td2 = {
01570       .desc = "multiple contacts",
01571       .contactheader = "sip:,user1,:,secret1,@host1;ttl=7;q=1;expires=3600,sips:host2",
01572       .contactlist = &contactlist2,
01573       .star = 0,
01574    };
01575    struct contact contact21 = {
01576       .name = "",
01577       .user = ",user1,",
01578       .pass = ",secret1,",
01579       .hostport = "host1",
01580       .params.transport = "",
01581       .params.ttl = "7",
01582       .params.lr = 0,
01583       .headers = "",
01584       .expires = "3600",
01585       .q = "1"
01586    };
01587    struct contact contact22 = {
01588       .name = "",
01589       .user = "",
01590       .pass = "",
01591       .hostport = "host2",
01592       .params.transport = "",
01593       .params.ttl = "",
01594       .params.lr = 0,
01595       .headers = "",
01596       .expires = "",
01597       .q = ""
01598    };
01599 
01600    struct testdata td3 = {
01601       .desc = "star - all contacts",
01602       .contactheader = "*",
01603       .star = 1,
01604       .contactlist = NULL
01605    };
01606 
01607    AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &td1);
01608    AST_LIST_INSERT_TAIL(&testdatalist, &td2, list);
01609    AST_LIST_INSERT_TAIL(&testdatalist, &td3, list);
01610 
01611    AST_LIST_HEAD_SET_NOLOCK(&contactlist1, &contact11);
01612 
01613    AST_LIST_HEAD_SET_NOLOCK(&contactlist2, &contact21);
01614    AST_LIST_INSERT_TAIL(&contactlist2, &contact22, list);
01615 
01616 
01617    switch (cmd) {
01618    case TEST_INIT:
01619       info->name = "parse_contact_header_test";
01620       info->category = "/channels/chan_sip/";
01621       info->summary = "tests parsing of sip contact header";
01622       info->description =
01623          "Tests parsing of a contact header including those with multiple contacts "
01624          "Verifies output matches expected behavior.";
01625       return AST_TEST_NOT_RUN;
01626    case TEST_EXECUTE:
01627       break;
01628    }
01629 
01630    AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
01631       ast_copy_string(contactheader,testdataptr->contactheader,sizeof(contactheader));
01632       star = parse_contact_header(contactheader,contactlistptr);
01633       if (testdataptr->star) {
01634          /* expecting star rather than list of contacts */
01635          if (!star) {
01636             ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
01637             res = AST_TEST_FAIL;
01638             break;
01639          }
01640       } else {
01641          contactptr = AST_LIST_FIRST(contactlistptr);
01642          AST_LIST_TRAVERSE(testdataptr->contactlist, tdcontactptr, list) {
01643             if (!contactptr ||
01644                strcmp(tdcontactptr->name, contactptr->name) ||
01645                strcmp(tdcontactptr->user, contactptr->user) ||
01646                strcmp(tdcontactptr->pass, contactptr->pass) ||
01647                strcmp(tdcontactptr->hostport, contactptr->hostport) ||
01648                strcmp(tdcontactptr->headers, contactptr->headers) ||
01649                strcmp(tdcontactptr->expires, contactptr->expires) ||
01650                strcmp(tdcontactptr->q, contactptr->q) ||
01651                strcmp(tdcontactptr->params.transport, contactptr->params.transport) ||
01652                strcmp(tdcontactptr->params.ttl, contactptr->params.ttl) ||
01653                (tdcontactptr->params.lr != contactptr->params.lr)
01654                ) {
01655                ast_test_status_update(test, "Sub-Test: %s,failed.\n", testdataptr->desc);
01656                res = AST_TEST_FAIL;
01657                break;
01658             }
01659 
01660             contactptr = AST_LIST_NEXT(contactptr,list);
01661          }
01662 
01663          while ((contactptr = AST_LIST_REMOVE_HEAD(contactlistptr,list))) {
01664             ast_free(contactptr);
01665          }
01666       }
01667    }
01668 
01669    return res;
01670 }
01671 
01672 /*!
01673  * \brief Parse supported header in incoming packet
01674  *
01675  * \details This function parses through the options parameters and
01676  * builds a bit field representing all the SIP options in that field. When an
01677  * item is found that is not supported, it is copied to the unsupported
01678  * out buffer.
01679  *
01680  * \param options list
01681  * \param unsupported out buffer (optional)
01682  * \param unsupported_len out buffer length (optional)
01683  */
01684 unsigned int parse_sip_options(const char *options, char *unsupported, size_t unsupported_len)
01685 {
01686    char *next, *sep;
01687    char *temp;
01688    int i, found, supported;
01689    unsigned int profile = 0;
01690 
01691    char *out = unsupported;
01692    size_t outlen = unsupported_len;
01693    char *cur_out = out;
01694 
01695    if (ast_strlen_zero(options) )
01696       return 0;
01697 
01698    temp = ast_strdupa(options);
01699 
01700    ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", options);
01701    for (next = temp; next; next = sep) {
01702       found = FALSE;
01703       supported = FALSE;
01704       if ((sep = strchr(next, ',')) != NULL) {
01705          *sep++ = '\0';
01706       }
01707 
01708       /* trim leading and trailing whitespace */
01709       next = ast_strip(next);
01710 
01711       if (ast_strlen_zero(next)) {
01712          continue; /* if there is a blank argument in there just skip it */
01713       }
01714 
01715       ast_debug(3, "Found SIP option: -%s-\n", next);
01716       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
01717          if (!strcasecmp(next, sip_options[i].text)) {
01718             profile |= sip_options[i].id;
01719             if (sip_options[i].supported == SUPPORTED) {
01720                supported = TRUE;
01721             }
01722             found = TRUE;
01723             ast_debug(3, "Matched SIP option: %s\n", next);
01724             break;
01725          }
01726       }
01727 
01728       /* If option is not supported, add to unsupported out buffer */
01729       if (!supported && out && outlen) {
01730          size_t copylen = strlen(next);
01731          size_t cur_outlen = strlen(out);
01732          /* Check to see if there is enough room to store this option.
01733           * Copy length is string length plus 2 for the ',' and '\0' */
01734          if ((cur_outlen + copylen + 2) < outlen) {
01735             /* if this isn't the first item, add the ',' */
01736             if (cur_outlen) {
01737                *cur_out = ',';
01738                cur_out++;
01739                cur_outlen++;
01740             }
01741             ast_copy_string(cur_out, next, (outlen - cur_outlen));
01742             cur_out += copylen;
01743          }
01744       }
01745 
01746       if (!found) {
01747          profile |= SIP_OPT_UNKNOWN;
01748          if (!strncasecmp(next, "x-", 2))
01749             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
01750          else
01751             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
01752       }
01753    }
01754 
01755    return profile;
01756 }
01757 
01758 AST_TEST_DEFINE(sip_parse_options_test)
01759 {
01760    int res = AST_TEST_PASS;
01761    char unsupported[64];
01762    unsigned int option_profile = 0;
01763    struct testdata {
01764       char *name;
01765       char *input_options;
01766       char *expected_unsupported;
01767       unsigned int expected_profile;
01768       AST_LIST_ENTRY(testdata) list;
01769    };
01770 
01771    struct testdata *testdataptr;
01772    static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
01773 
01774    struct testdata test1 = {
01775       .name = "test_all_unsupported",
01776       .input_options = "unsupported1,,, ,unsupported2,unsupported3,unsupported4",
01777       .expected_unsupported = "unsupported1,unsupported2,unsupported3,unsupported4",
01778       .expected_profile = SIP_OPT_UNKNOWN,
01779    };
01780    struct testdata test2 = {
01781       .name = "test_all_unsupported_one_supported",
01782       .input_options = "  unsupported1, replaces,   unsupported3  , , , ,unsupported4",
01783       .expected_unsupported = "unsupported1,unsupported3,unsupported4",
01784       .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES
01785    };
01786    struct testdata test3 = {
01787       .name = "test_two_supported_two_unsupported",
01788       .input_options = ",,  timer  ,replaces     ,unsupported3,unsupported4",
01789       .expected_unsupported = "unsupported3,unsupported4",
01790       .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
01791    };
01792 
01793    struct testdata test4 = {
01794       .name = "test_all_supported",
01795       .input_options = "timer,replaces",
01796       .expected_unsupported = "",
01797       .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
01798    };
01799 
01800    struct testdata test5 = {
01801       .name = "test_all_supported_redundant",
01802       .input_options = "timer,replaces,timer,replace,timer,replaces",
01803       .expected_unsupported = "",
01804       .expected_profile = SIP_OPT_REPLACES | SIP_OPT_TIMER,
01805    };
01806    struct testdata test6 = {
01807       .name = "test_buffer_overflow",
01808       .input_options = "unsupported1,replaces,timer,unsupported4,unsupported_huge____"
01809       "____________________________________,__________________________________________"
01810       "________________________________________________",
01811       .expected_unsupported = "unsupported1,unsupported4",
01812       .expected_profile = SIP_OPT_UNKNOWN | SIP_OPT_REPLACES | SIP_OPT_TIMER,
01813    };
01814    struct testdata test7 = {
01815       .name = "test_null_input",
01816       .input_options = NULL,
01817       .expected_unsupported = "",
01818       .expected_profile = 0,
01819    };
01820    struct testdata test8 = {
01821       .name = "test_whitespace_input",
01822       .input_options = "         ",
01823       .expected_unsupported = "",
01824       .expected_profile = 0,
01825    };
01826    struct testdata test9 = {
01827       .name = "test_whitespace_plus_option_input",
01828       .input_options = " , , ,timer , ,  , ,        ,    ",
01829       .expected_unsupported = "",
01830       .expected_profile = SIP_OPT_TIMER,
01831    };
01832 
01833    switch (cmd) {
01834    case TEST_INIT:
01835       info->name = "sip_parse_options_test";
01836       info->category = "/channels/chan_sip/";
01837       info->summary = "Tests parsing of sip options";
01838       info->description =
01839                      "Tests parsing of SIP options from supported and required "
01840                      "header fields.  Verifies when unsupported options are encountered "
01841                      "that they are appended to the unsupported out buffer and that the "
01842                      "correct bit field representnig the option profile is returned.";
01843       return AST_TEST_NOT_RUN;
01844    case TEST_EXECUTE:
01845       break;
01846    }
01847 
01848    AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &test1);
01849    AST_LIST_INSERT_TAIL(&testdatalist, &test2, list);
01850    AST_LIST_INSERT_TAIL(&testdatalist, &test3, list);
01851    AST_LIST_INSERT_TAIL(&testdatalist, &test4, list);
01852    AST_LIST_INSERT_TAIL(&testdatalist, &test5, list);
01853    AST_LIST_INSERT_TAIL(&testdatalist, &test6, list);
01854    AST_LIST_INSERT_TAIL(&testdatalist, &test7, list);
01855    AST_LIST_INSERT_TAIL(&testdatalist, &test8, list);
01856    AST_LIST_INSERT_TAIL(&testdatalist, &test9, list);
01857 
01858    /* Test with unsupported char buffer */
01859    AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
01860       memset(unsupported, 0, sizeof(unsupported));
01861       option_profile = parse_sip_options(testdataptr->input_options, unsupported, ARRAY_LEN(unsupported));
01862       if (option_profile != testdataptr->expected_profile ||
01863          strcmp(unsupported, testdataptr->expected_unsupported)) {
01864          ast_test_status_update(test, "Test with output buffer \"%s\", expected unsupported: %s actual unsupported:"
01865             "%s expected bit profile: %x actual bit profile: %x\n",
01866             testdataptr->name,
01867             testdataptr->expected_unsupported,
01868             unsupported,
01869             testdataptr->expected_profile,
01870             option_profile);
01871          res = AST_TEST_FAIL;
01872       } else {
01873          ast_test_status_update(test, "\"%s\" passed got expected unsupported: %s and bit profile: %x\n",
01874             testdataptr->name,
01875             unsupported,
01876             option_profile);
01877       }
01878 
01879       option_profile = parse_sip_options(testdataptr->input_options, NULL, 0);
01880       if (option_profile != testdataptr->expected_profile) {
01881          ast_test_status_update(test, "NULL output test \"%s\", expected bit profile: %x actual bit profile: %x\n",
01882             testdataptr->name,
01883             testdataptr->expected_profile,
01884             option_profile);
01885          res = AST_TEST_FAIL;
01886       } else {
01887          ast_test_status_update(test, "\"%s\" with NULL output buf passed, bit profile: %x\n",
01888             testdataptr->name,
01889             option_profile);
01890       }
01891    }
01892 
01893    return res;
01894 }
01895 
01896 /*! \brief helper routine for sip_uri_cmp to compare URI parameters
01897  *
01898  * This takes the parameters from two SIP URIs and determines
01899  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
01900  * 1. If a parameter appears in both URIs, then they must have the same value
01901  *    in order for the URIs to match
01902  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
01903  *    URI must also have that parameter and must have the same value
01904  *    in order for the URIs to match
01905  * 3. All other headers appearing in only one URI are not considered when
01906  *    determining if URIs match
01907  *
01908  * \param input1 Parameters from URI 1
01909  * \param input2 Parameters from URI 2
01910  * \retval 0 URIs' parameters match
01911  * \retval nonzero URIs' parameters do not match
01912  */
01913 static int sip_uri_params_cmp(const char *input1, const char *input2)
01914 {
01915    char *params1 = NULL;
01916    char *params2 = NULL;
01917    char *pos1;
01918    char *pos2;
01919    int zerolength1 = 0;
01920    int zerolength2 = 0;
01921    int maddrmatch = 0;
01922    int ttlmatch = 0;
01923    int usermatch = 0;
01924    int methodmatch = 0;
01925 
01926    if (ast_strlen_zero(input1)) {
01927       zerolength1 = 1;
01928    } else {
01929       params1 = ast_strdupa(input1);
01930    }
01931    if (ast_strlen_zero(input2)) {
01932       zerolength2 = 1;
01933    } else {
01934       params2 = ast_strdupa(input2);
01935    }
01936 
01937    /* Quick optimization. If both params are zero-length, then
01938     * they match
01939     */
01940    if (zerolength1 && zerolength2) {
01941       return 0;
01942    }
01943 
01944    for (pos1 = strsep(&params1, ";"); pos1; pos1 = strsep(&params1, ";")) {
01945       char *value1 = pos1;
01946       char *name1 = strsep(&value1, "=");
01947       char *params2dup = NULL;
01948       int matched = 0;
01949       if (!value1) {
01950          value1 = "";
01951       }
01952       /* Checkpoint reached. We have the name and value parsed for param1
01953        * We have to duplicate params2 each time through this loop
01954        * or else the inner loop below will not work properly.
01955        */
01956       if (!zerolength2) {
01957          params2dup = ast_strdupa(params2);
01958       }
01959       for (pos2 = strsep(&params2dup, ";"); pos2; pos2 = strsep(&params2dup, ";")) {
01960          char *name2 = pos2;
01961          char *value2 = strchr(pos2, '=');
01962          if (!value2) {
01963             value2 = "";
01964          } else {
01965             *value2++ = '\0';
01966          }
01967          if (!strcasecmp(name1, name2)) {
01968             if (strcasecmp(value1, value2)) {
01969                goto fail;
01970             } else {
01971                matched = 1;
01972                break;
01973             }
01974          }
01975       }
01976       /* Check to see if the parameter is one of the 'must-match' parameters */
01977       if (!strcasecmp(name1, "maddr")) {
01978          if (matched) {
01979             maddrmatch = 1;
01980          } else {
01981             goto fail;
01982          }
01983       } else if (!strcasecmp(name1, "ttl")) {
01984          if (matched) {
01985             ttlmatch = 1;
01986          } else {
01987             goto fail;
01988          }
01989       } else if (!strcasecmp(name1, "user")) {
01990          if (matched) {
01991             usermatch = 1;
01992          } else {
01993             goto fail;
01994          }
01995       } else if (!strcasecmp(name1, "method")) {
01996          if (matched) {
01997             methodmatch = 1;
01998          } else {
01999             goto fail;
02000          }
02001       }
02002    }
02003 
02004    /* We've made it out of that horrible O(m*n) construct and there are no
02005     * failures yet. We're not done yet, though, because params2 could have
02006     * an maddr, ttl, user, or method header and params1 did not.
02007     */
02008    for (pos2 = strsep(&params2, ";"); pos2; pos2 = strsep(&params2, ";")) {
02009       char *value2 = pos2;
02010       char *name2 = strsep(&value2, "=");
02011       if (!value2) {
02012          value2 = "";
02013       }
02014       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
02015             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
02016             (!strcasecmp(name2, "user") && !usermatch) ||
02017             (!strcasecmp(name2, "method") && !methodmatch)) {
02018          goto fail;
02019       }
02020    }
02021    return 0;
02022 
02023 fail:
02024    return 1;
02025 }
02026 
02027 /*! \brief helper routine for sip_uri_cmp to compare URI headers
02028  *
02029  * This takes the headers from two SIP URIs and determines
02030  * if the URIs match. The rules for headers is simple. If a header
02031  * appears in one URI, then it must also appear in the other URI. The
02032  * order in which the headers appear does not matter.
02033  *
02034  * \param input1 Headers from URI 1
02035  * \param input2 Headers from URI 2
02036  * \retval 0 URI headers match
02037  * \retval nonzero URI headers do not match
02038  */
02039 static int sip_uri_headers_cmp(const char *input1, const char *input2)
02040 {
02041    char *headers1 = NULL;
02042    char *headers2 = NULL;
02043    int zerolength1 = 0;
02044    int zerolength2 = 0;
02045    int different = 0;
02046    char *header1;
02047 
02048    if (ast_strlen_zero(input1)) {
02049       zerolength1 = 1;
02050    } else {
02051       headers1 = ast_strdupa(input1);
02052    }
02053 
02054    if (ast_strlen_zero(input2)) {
02055       zerolength2 = 1;
02056    } else {
02057       headers2 = ast_strdupa(input2);
02058    }
02059 
02060    /* If one URI contains no headers and the other
02061     * does, then they cannot possibly match
02062     */
02063    if (zerolength1 != zerolength2) {
02064       return 1;
02065    }
02066 
02067    if (zerolength1 && zerolength2)
02068       return 0;
02069 
02070    /* At this point, we can definitively state that both inputs are
02071     * not zero-length. First, one more optimization. If the length
02072     * of the headers is not equal, then we definitely have no match
02073     */
02074    if (strlen(headers1) != strlen(headers2)) {
02075       return 1;
02076    }
02077 
02078    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
02079       if (!strcasestr(headers2, header1)) {
02080          different = 1;
02081          break;
02082       }
02083    }
02084 
02085    return different;
02086 }
02087 
02088 /*!
02089  * \brief Compare domain sections of SIP URIs
02090  *
02091  * For hostnames, a case insensitive string comparison is
02092  * used. For IP addresses, a binary comparison is used. This
02093  * is mainly because IPv6 addresses have many ways of writing
02094  * the same address.
02095  *
02096  * For specifics about IP address comparison, see the following
02097  * document: http://tools.ietf.org/html/draft-ietf-sip-ipv6-abnf-fix-05
02098  *
02099  * \param host1 The domain from the first URI
02100  * \param host2 THe domain from the second URI
02101  * \retval 0 The domains match
02102  * \retval nonzero The domains do not match
02103  */
02104 static int sip_uri_domain_cmp(const char *host1, const char *host2)
02105 {
02106    struct ast_sockaddr addr1;
02107    struct ast_sockaddr addr2;
02108    int addr1_parsed;
02109    int addr2_parsed;
02110 
02111    addr1_parsed = ast_sockaddr_parse(&addr1, host1, 0);
02112    addr2_parsed = ast_sockaddr_parse(&addr2, host2, 0);
02113 
02114    if (addr1_parsed != addr2_parsed) {
02115       /* One domain was an IP address and the other had
02116        * a host name. FAIL!
02117        */
02118       return 1;
02119    }
02120 
02121    /* Both are host names. A string comparison will work
02122     * perfectly here. Specifying the "C" locale ensures that
02123     * The LC_CTYPE conventions use those defined in ANSI C,
02124     * i.e. ASCII.
02125     */
02126    if (!addr1_parsed) {
02127 #ifdef HAVE_XLOCALE_H
02128       if(!c_locale) {
02129          return strcasecmp(host1, host2);
02130       } else {
02131          return strcasecmp_l(host1, host2, c_locale);
02132       }
02133 #else
02134       return strcasecmp(host1, host2);
02135 #endif
02136    }
02137 
02138    /* Both contain IP addresses */
02139    return ast_sockaddr_cmp(&addr1, &addr2);
02140 }
02141 
02142 int sip_uri_cmp(const char *input1, const char *input2)
02143 {
02144    char *uri1;
02145    char *uri2;
02146    char *uri_scheme1;
02147    char *uri_scheme2;
02148    char *host1;
02149    char *host2;
02150    char *params1;
02151    char *params2;
02152    char *headers1;
02153    char *headers2;
02154 
02155    /* XXX It would be really nice if we could just use parse_uri_full() here
02156     * to separate the components of the URI, but unfortunately it is written
02157     * in a way that can cause URI parameters to be discarded.
02158     */
02159 
02160    if (!input1 || !input2) {
02161       return 1;
02162    }
02163 
02164    uri1 = ast_strdupa(input1);
02165    uri2 = ast_strdupa(input2);
02166 
02167    ast_uri_decode(uri1, ast_uri_sip_user);
02168    ast_uri_decode(uri2, ast_uri_sip_user);
02169 
02170    uri_scheme1 = strsep(&uri1, ":");
02171    uri_scheme2 = strsep(&uri2, ":");
02172 
02173    if (strcmp(uri_scheme1, uri_scheme2)) {
02174       return 1;
02175    }
02176 
02177    /* This function is tailored for SIP and SIPS URIs. There's no
02178     * need to check uri_scheme2 since we have determined uri_scheme1
02179     * and uri_scheme2 are equivalent already.
02180     */
02181    if (strcmp(uri_scheme1, "sip") && strcmp(uri_scheme1, "sips")) {
02182       return 1;
02183    }
02184 
02185    if (ast_strlen_zero(uri1) || ast_strlen_zero(uri2)) {
02186       return 1;
02187    }
02188 
02189    if ((host1 = strchr(uri1, '@'))) {
02190       *host1++ = '\0';
02191    }
02192    if ((host2 = strchr(uri2, '@'))) {
02193       *host2++ = '\0';
02194    }
02195 
02196    /* Check for mismatched username and passwords. This is the
02197     * only case-sensitive comparison of a SIP URI
02198     */
02199    if ((host1 && !host2) ||
02200          (host2 && !host1) ||
02201          (host1 && host2 && strcmp(uri1, uri2))) {
02202       return 1;
02203    }
02204 
02205    if (!host1) {
02206       host1 = uri1;
02207    }
02208    if (!host2) {
02209       host2 = uri2;
02210    }
02211 
02212    /* Strip off the parameters and headers so we can compare
02213     * host and port
02214     */
02215 
02216    if ((params1 = strchr(host1, ';'))) {
02217       *params1++ = '\0';
02218    }
02219    if ((params2 = strchr(host2, ';'))) {
02220       *params2++ = '\0';
02221    }
02222 
02223    /* Headers come after parameters, but there may be headers without
02224     * parameters, thus the S_OR
02225     */
02226    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
02227       *headers1++ = '\0';
02228    }
02229    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
02230       *headers2++ = '\0';
02231    }
02232 
02233    if (sip_uri_domain_cmp(host1, host2)) {
02234       return 1;
02235    }
02236 
02237    /* Headers have easier rules to follow, so do those first */
02238    if (sip_uri_headers_cmp(headers1, headers2)) {
02239       return 1;
02240    }
02241 
02242    /* And now the parameters. Ugh */
02243    return sip_uri_params_cmp(params1, params2);
02244 }
02245 
02246 #define URI_CMP_MATCH 0
02247 #define URI_CMP_NOMATCH 1
02248 
02249 AST_TEST_DEFINE(sip_uri_cmp_test)
02250 {
02251    static const struct {
02252       const char *uri1;
02253       const char *uri2;
02254       int expected_result;
02255    } uri_cmp_tests [] = {
02256       /* These are identical, so they match */
02257       { "sip:bob@example.com", "sip:bob@example.com", URI_CMP_MATCH },
02258       /* Different usernames. No match */
02259       { "sip:alice@example.com", "sip:bob@example.com", URI_CMP_NOMATCH },
02260       /* Different hosts. No match */
02261       { "sip:bob@example.com", "sip:bob@examplez.com", URI_CMP_NOMATCH },
02262       /* Now start using IP addresses. Identical, so they match */
02263       { "sip:bob@1.2.3.4", "sip:bob@1.2.3.4", URI_CMP_MATCH },
02264       /* Two identical IPv4 addresses represented differently. Match */
02265       { "sip:bob@1.2.3.4", "sip:bob@001.002.003.004", URI_CMP_MATCH },
02266       /* Logically equivalent IPv4 Address and hostname. No Match */
02267       { "sip:bob@127.0.0.1", "sip:bob@localhost", URI_CMP_NOMATCH },
02268       /* Logically equivalent IPv6 address and hostname. No Match */
02269       { "sip:bob@[::1]", "sip:bob@localhost", URI_CMP_NOMATCH },
02270       /* Try an IPv6 one as well */
02271       { "sip:bob@[2001:db8::1234]", "sip:bob@[2001:db8::1234]", URI_CMP_MATCH },
02272       /* Two identical IPv6 addresses represented differently. Match */
02273       { "sip:bob@[2001:db8::1234]", "sip:bob@[2001:0db8::1234]", URI_CMP_MATCH },
02274       /* Different ports. No match */
02275       { "sip:bob@1.2.3.4:5060", "sip:bob@1.2.3.4:5061", URI_CMP_NOMATCH },
02276       /* Same port logically, but only one address specifies it. No match */
02277       { "sip:bob@1.2.3.4:5060", "sip:bob@1.2.3.4", URI_CMP_NOMATCH },
02278       /* And for safety, try with IPv6 */
02279       { "sip:bob@[2001:db8:1234]:5060", "sip:bob@[2001:db8:1234]", URI_CMP_NOMATCH },
02280       /* User comparison is case sensitive. No match */
02281       { "sip:bob@example.com", "sip:BOB@example.com", URI_CMP_NOMATCH },
02282       /* Host comparison is case insensitive. Match */
02283       { "sip:bob@example.com", "sip:bob@EXAMPLE.COM", URI_CMP_MATCH },
02284       /* Add headers to the URI. Identical, so they match */
02285       { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com?header1=value1&header2=value2", URI_CMP_MATCH },
02286       /* Headers in URI 1 are not in URI 2. No Match */
02287       { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com", URI_CMP_NOMATCH },
02288       /* Header present in both URIs does not have matching values. No match */
02289       { "sip:bob@example.com?header1=value1&header2=value2", "sip:bob@example.com?header1=value1&header2=value3", URI_CMP_NOMATCH },
02290       /* Add parameters to the URI. Identical so they match */
02291       { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com;param1=value1;param2=value2", URI_CMP_MATCH },
02292       /* Same parameters in both URIs but appear in different order. Match */
02293       { "sip:bob@example.com;param2=value2;param1=value1", "sip:bob@example.com;param1=value1;param2=value2", URI_CMP_MATCH },
02294       /* params in URI 1 are not in URI 2. Match */
02295       { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com", URI_CMP_MATCH },
02296       /* param present in both URIs does not have matching values. No match */
02297       { "sip:bob@example.com;param1=value1;param2=value2", "sip:bob@example.com;param1=value1;param2=value3", URI_CMP_NOMATCH },
02298       /* URI 1 has a maddr param but URI 2 does not. No match */
02299       { "sip:bob@example.com;param1=value1;maddr=192.168.0.1", "sip:bob@example.com;param1=value1", URI_CMP_NOMATCH },
02300       /* URI 1 and URI 2 both have identical maddr params. Match */
02301       { "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 },
02302       /* URI 1 is a SIPS URI and URI 2 is a SIP URI. No Match */
02303       { "sips:bob@example.com", "sip:bob@example.com", URI_CMP_NOMATCH },
02304       /* No URI schemes. No match */
02305       { "bob@example.com", "bob@example.com", URI_CMP_NOMATCH },
02306       /* Crashiness tests. Just an address scheme. No match */
02307       { "sip", "sips", URI_CMP_NOMATCH },
02308       /* Still just an address scheme. Even though they're the same, No match */
02309       { "sip", "sip", URI_CMP_NOMATCH },
02310       /* Empty strings. No match */
02311       { "", "", URI_CMP_NOMATCH },
02312       /* An empty string and a NULL. No match */
02313       { "", NULL, URI_CMP_NOMATCH },
02314    };
02315    int i;
02316    int test_res = AST_TEST_PASS;
02317    switch (cmd) {
02318    case TEST_INIT:
02319       info->name = "sip_uri_cmp_test";
02320       info->category = "/channels/chan_sip/";
02321       info->summary = "Tests comparison of SIP URIs";
02322       info->description = "Several would-be tricky URI comparisons are performed";
02323       return AST_TEST_NOT_RUN;
02324    case TEST_EXECUTE:
02325       break;
02326    }
02327 
02328    for (i = 0; i < ARRAY_LEN(uri_cmp_tests); ++i) {
02329       int cmp_res1;
02330       int cmp_res2;
02331       if ((cmp_res1 = sip_uri_cmp(uri_cmp_tests[i].uri1, uri_cmp_tests[i].uri2))) {
02332          /* URI comparison may return -1 or +1 depending on the failure. Standardize
02333           * the return value to be URI_CMP_NOMATCH on any failure
02334           */
02335          cmp_res1 = URI_CMP_NOMATCH;
02336       }
02337       if (cmp_res1 != uri_cmp_tests[i].expected_result) {
02338          ast_test_status_update(test, "Unexpected comparison result for URIs %s and %s. "
02339                "Expected %s but got %s\n", uri_cmp_tests[i].uri1, uri_cmp_tests[i].uri2,
02340                uri_cmp_tests[i].expected_result == URI_CMP_MATCH ? "Match" : "No Match",
02341                cmp_res1 == URI_CMP_MATCH ? "Match" : "No Match");
02342          test_res = AST_TEST_FAIL;
02343       }
02344 
02345       /* All URI comparisons are commutative, so for the sake of being thorough, we'll
02346        * rerun the comparison with the parameters reversed
02347        */
02348       if ((cmp_res2 = sip_uri_cmp(uri_cmp_tests[i].uri2, uri_cmp_tests[i].uri1))) {
02349          /* URI comparison may return -1 or +1 depending on the failure. Standardize
02350           * the return value to be URI_CMP_NOMATCH on any failure
02351           */
02352          cmp_res2 = URI_CMP_NOMATCH;
02353       }
02354       if (cmp_res2 != uri_cmp_tests[i].expected_result) {
02355          ast_test_status_update(test, "Unexpected comparison result for URIs %s and %s. "
02356                "Expected %s but got %s\n", uri_cmp_tests[i].uri2, uri_cmp_tests[i].uri1,
02357                uri_cmp_tests[i].expected_result == URI_CMP_MATCH ? "Match" : "No Match",
02358                cmp_res2 == URI_CMP_MATCH ? "Match" : "No Match");
02359          test_res = AST_TEST_FAIL;
02360       }
02361    }
02362 
02363    return test_res;
02364 }
02365 
02366 void free_via(struct sip_via *v)
02367 {
02368    if (!v) {
02369       return;
02370    }
02371 
02372    ast_free(v->via);
02373    ast_free(v);
02374 }
02375 
02376 struct sip_via *parse_via(const char *header)
02377 {
02378    struct sip_via *v = ast_calloc(1, sizeof(*v));
02379    char *via, *parm;
02380 
02381    if (!v) {
02382       return NULL;
02383    }
02384 
02385    v->via = ast_strdup(header);
02386    v->ttl = 1;
02387 
02388    via = v->via;
02389 
02390    if (ast_strlen_zero(via)) {
02391       ast_log(LOG_ERROR, "received request without a Via header\n");
02392       free_via(v);
02393       return NULL;
02394    }
02395 
02396    /* seperate the first via-parm */
02397    via = strsep(&via, ",");
02398 
02399    /* chop off sent-protocol */
02400    v->protocol = strsep(&via, " \t\r\n");
02401    if (ast_strlen_zero(v->protocol)) {
02402       ast_log(LOG_ERROR, "missing sent-protocol in Via header\n");
02403       free_via(v);
02404       return NULL;
02405    }
02406    v->protocol = ast_skip_blanks(v->protocol);
02407 
02408    if (via) {
02409       via = ast_skip_blanks(via);
02410    }
02411 
02412    /* chop off sent-by */
02413    v->sent_by = strsep(&via, "; \t\r\n");
02414    if (ast_strlen_zero(v->sent_by)) {
02415       ast_log(LOG_ERROR, "missing sent-by in Via header\n");
02416       free_via(v);
02417       return NULL;
02418    }
02419    v->sent_by = ast_skip_blanks(v->sent_by);
02420 
02421    /* store the port, we have to handle ipv6 addresses containing ':'
02422     * characters gracefully */
02423    if (((parm = strchr(v->sent_by, ']')) && *(++parm) == ':') || (parm = strchr(v->sent_by, ':'))) {
02424       char *endptr;
02425 
02426       v->port = strtol(++parm, &endptr, 10);
02427    }
02428 
02429    /* evaluate any via-parms */
02430    while ((parm = strsep(&via, "; \t\r\n"))) {
02431       char *c;
02432       if ((c = strstr(parm, "maddr="))) {
02433          v->maddr = ast_skip_blanks(c + sizeof("maddr=") - 1);
02434       } else if ((c = strstr(parm, "branch="))) {
02435          v->branch = ast_skip_blanks(c + sizeof("branch=") - 1);
02436       } else if ((c = strstr(parm, "ttl="))) {
02437          char *endptr;
02438          c = ast_skip_blanks(c + sizeof("ttl=") - 1);
02439          v->ttl = strtol(c, &endptr, 10);
02440 
02441          /* make sure we got a valid ttl value */
02442          if (c == endptr) {
02443             v->ttl = 1;
02444          }
02445       }
02446    }
02447 
02448    return v;
02449 }
02450 
02451 AST_TEST_DEFINE(parse_via_test)
02452 {
02453    int res = AST_TEST_PASS;
02454    int i = 1;
02455    struct sip_via *via;
02456    struct testdata {
02457       char *in;
02458       char *expected_protocol;
02459       char *expected_branch;
02460       char *expected_sent_by;
02461       char *expected_maddr;
02462       unsigned int expected_port;
02463       unsigned char expected_ttl;
02464       int expected_null;
02465       AST_LIST_ENTRY(testdata) list;
02466    };
02467    struct testdata *testdataptr;
02468    static AST_LIST_HEAD_NOLOCK(testdataliststruct, testdata) testdatalist;
02469    struct testdata t1 = {
02470       .in = "SIP/2.0/UDP host:port;branch=thebranch",
02471       .expected_protocol = "SIP/2.0/UDP",
02472       .expected_sent_by = "host:port",
02473       .expected_branch = "thebranch",
02474    };
02475    struct testdata t2 = {
02476       .in = "SIP/2.0/UDP host:port",
02477       .expected_protocol = "SIP/2.0/UDP",
02478       .expected_sent_by = "host:port",
02479       .expected_branch = "",
02480    };
02481    struct testdata t3 = {
02482       .in = "SIP/2.0/UDP",
02483       .expected_null = 1,
02484    };
02485    struct testdata t4 = {
02486       .in = "BLAH/BLAH/BLAH host:port;branch=",
02487       .expected_protocol = "BLAH/BLAH/BLAH",
02488       .expected_sent_by = "host:port",
02489       .expected_branch = "",
02490    };
02491    struct testdata t5 = {
02492       .in = "SIP/2.0/UDP host:5060;branch=thebranch;maddr=224.0.0.1;ttl=1",
02493       .expected_protocol = "SIP/2.0/UDP",
02494       .expected_sent_by = "host:5060",
02495       .expected_port = 5060,
02496       .expected_branch = "thebranch",
02497       .expected_maddr = "224.0.0.1",
02498       .expected_ttl = 1,
02499    };
02500    struct testdata t6 = {
02501       .in = "SIP/2.0/UDP      host:5060;\n   branch=thebranch;\r\n  maddr=224.0.0.1;   ttl=1",
02502       .expected_protocol = "SIP/2.0/UDP",
02503       .expected_sent_by = "host:5060",
02504       .expected_port = 5060,
02505       .expected_branch = "thebranch",
02506       .expected_maddr = "224.0.0.1",
02507       .expected_ttl = 1,
02508    };
02509    struct testdata t7 = {
02510       .in = "SIP/2.0/UDP [::1]:5060",
02511       .expected_protocol = "SIP/2.0/UDP",
02512       .expected_sent_by = "[::1]:5060",
02513       .expected_port = 5060,
02514       .expected_branch = "",
02515    };
02516    switch (cmd) {
02517    case TEST_INIT:
02518       info->name = "parse_via_test";
02519       info->category = "/channels/chan_sip/";
02520       info->summary = "Tests parsing the Via header";
02521       info->description =
02522             "Runs through various test situations in which various "
02523             " parameters parameter must be extracted from a VIA header";
02524       return AST_TEST_NOT_RUN;
02525    case TEST_EXECUTE:
02526       break;
02527    }
02528 
02529    AST_LIST_HEAD_SET_NOLOCK(&testdatalist, &t1);
02530    AST_LIST_INSERT_TAIL(&testdatalist, &t2, list);
02531    AST_LIST_INSERT_TAIL(&testdatalist, &t3, list);
02532    AST_LIST_INSERT_TAIL(&testdatalist, &t4, list);
02533    AST_LIST_INSERT_TAIL(&testdatalist, &t5, list);
02534    AST_LIST_INSERT_TAIL(&testdatalist, &t6, list);
02535    AST_LIST_INSERT_TAIL(&testdatalist, &t7, list);
02536 
02537 
02538    AST_LIST_TRAVERSE(&testdatalist, testdataptr, list) {
02539       via = parse_via(testdataptr->in);
02540       if (!via) {
02541               if (!testdataptr->expected_null) {
02542             ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02543                "failed to parse header\n",
02544             i, testdataptr->in);
02545             res = AST_TEST_FAIL;
02546          }
02547          i++;
02548          continue;
02549       }
02550 
02551       if (testdataptr->expected_null) {
02552          ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02553             "successfully parased invalid via header\n",
02554          i, testdataptr->in);
02555          res = AST_TEST_FAIL;
02556          free_via(via);
02557          i++;
02558          continue;
02559       }
02560 
02561       if ((ast_strlen_zero(via->protocol) && !ast_strlen_zero(testdataptr->expected_protocol))
02562          || (!ast_strlen_zero(via->protocol) && strcmp(via->protocol, testdataptr->expected_protocol))) {
02563 
02564          ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02565             "parsed protocol = \"%s\"\n"
02566             "expected = \"%s\"\n"
02567             "failed to parse protocol\n",
02568          i, testdataptr->in, via->protocol, testdataptr->expected_protocol);
02569          res = AST_TEST_FAIL;
02570       }
02571 
02572       if ((ast_strlen_zero(via->sent_by) && !ast_strlen_zero(testdataptr->expected_sent_by))
02573          || (!ast_strlen_zero(via->sent_by) && strcmp(via->sent_by, testdataptr->expected_sent_by))) {
02574 
02575          ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02576             "parsed sent_by = \"%s\"\n"
02577             "expected = \"%s\"\n"
02578             "failed to parse sent-by\n",
02579          i, testdataptr->in, via->sent_by, testdataptr->expected_sent_by);
02580          res = AST_TEST_FAIL;
02581       }
02582 
02583       if (testdataptr->expected_port && testdataptr->expected_port != via->port) {
02584          ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02585             "parsed port = \"%u\"\n"
02586             "expected = \"%u\"\n"
02587             "failed to parse port\n",
02588          i, testdataptr->in, via->port, testdataptr->expected_port);
02589          res = AST_TEST_FAIL;
02590       }
02591 
02592       if ((ast_strlen_zero(via->branch) && !ast_strlen_zero(testdataptr->expected_branch))
02593          || (!ast_strlen_zero(via->branch) && strcmp(via->branch, testdataptr->expected_branch))) {
02594 
02595          ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02596             "parsed branch = \"%s\"\n"
02597             "expected = \"%s\"\n"
02598             "failed to parse branch\n",
02599          i, testdataptr->in, via->branch, testdataptr->expected_branch);
02600          res = AST_TEST_FAIL;
02601       }
02602 
02603       if ((ast_strlen_zero(via->maddr) && !ast_strlen_zero(testdataptr->expected_maddr))
02604          || (!ast_strlen_zero(via->maddr) && strcmp(via->maddr, testdataptr->expected_maddr))) {
02605 
02606          ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02607             "parsed maddr = \"%s\"\n"
02608             "expected = \"%s\"\n"
02609             "failed to parse maddr\n",
02610          i, testdataptr->in, via->maddr, testdataptr->expected_maddr);
02611          res = AST_TEST_FAIL;
02612       }
02613 
02614       if (testdataptr->expected_ttl && testdataptr->expected_ttl != via->ttl) {
02615          ast_test_status_update(test, "TEST#%d FAILED: VIA = \"%s\"\n"
02616             "parsed ttl = \"%d\"\n"
02617             "expected = \"%d\"\n"
02618             "failed to parse ttl\n",
02619          i, testdataptr->in, via->ttl, testdataptr->expected_ttl);
02620          res = AST_TEST_FAIL;
02621       }
02622 
02623       free_via(via);
02624       i++;
02625    }
02626    return res;
02627 }
02628 
02629 void sip_request_parser_register_tests(void)
02630 {
02631    AST_TEST_REGISTER(get_calleridname_test);
02632    AST_TEST_REGISTER(sip_parse_uri_test);
02633    AST_TEST_REGISTER(get_in_brackets_test);
02634    AST_TEST_REGISTER(get_name_and_number_test);
02635    AST_TEST_REGISTER(sip_parse_uri_full_test);
02636    AST_TEST_REGISTER(parse_name_andor_addr_test);
02637    AST_TEST_REGISTER(parse_contact_header_test);
02638    AST_TEST_REGISTER(sip_parse_options_test);
02639    AST_TEST_REGISTER(sip_uri_cmp_test);
02640    AST_TEST_REGISTER(parse_via_test);
02641 }
02642 void sip_request_parser_unregister_tests(void)
02643 {
02644    AST_TEST_UNREGISTER(sip_parse_uri_test);
02645    AST_TEST_UNREGISTER(get_calleridname_test);
02646    AST_TEST_UNREGISTER(get_in_brackets_test);
02647    AST_TEST_UNREGISTER(get_name_and_number_test);
02648    AST_TEST_UNREGISTER(sip_parse_uri_full_test);
02649    AST_TEST_UNREGISTER(parse_name_andor_addr_test);
02650    AST_TEST_UNREGISTER(parse_contact_header_test);
02651    AST_TEST_UNREGISTER(sip_parse_options_test);
02652    AST_TEST_UNREGISTER(sip_uri_cmp_test);
02653    AST_TEST_UNREGISTER(parse_via_test);
02654 }
02655 
02656 int sip_reqresp_parser_init(void)
02657 {
02658 #ifdef HAVE_XLOCALE_H
02659    c_locale = newlocale(LC_CTYPE_MASK, "C", NULL);
02660    if (!c_locale) {
02661       return -1;
02662    }
02663 #endif
02664    return 0;
02665 }
02666 
02667 void sip_reqresp_parser_exit(void)
02668 {
02669 #ifdef HAVE_XLOCALE_H
02670    if (c_locale) {
02671       freelocale(c_locale);
02672       c_locale = NULL;
02673    }
02674 #endif
02675 }

Generated on Thu Apr 16 06:27:44 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6