linux/net/netfilter/nf_conntrack_sip.c
<<
>>
Prefs
   1/* SIP extension for IP connection tracking.
   2 *
   3 * (C) 2005 by Christian Hentschel <chentschel@arnet.com.ar>
   4 * based on RR's ip_conntrack_ftp.c and other modules.
   5 * (C) 2007 United Security Providers
   6 * (C) 2007, 2008 Patrick McHardy <kaber@trash.net>
   7 *
   8 * This program is free software; you can redistribute it and/or modify
   9 * it under the terms of the GNU General Public License version 2 as
  10 * published by the Free Software Foundation.
  11 */
  12
  13#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  14
  15#include <linux/module.h>
  16#include <linux/ctype.h>
  17#include <linux/skbuff.h>
  18#include <linux/inet.h>
  19#include <linux/in.h>
  20#include <linux/udp.h>
  21#include <linux/tcp.h>
  22#include <linux/netfilter.h>
  23
  24#include <net/netfilter/nf_conntrack.h>
  25#include <net/netfilter/nf_conntrack_core.h>
  26#include <net/netfilter/nf_conntrack_expect.h>
  27#include <net/netfilter/nf_conntrack_helper.h>
  28#include <net/netfilter/nf_conntrack_zones.h>
  29#include <linux/netfilter/nf_conntrack_sip.h>
  30
  31MODULE_LICENSE("GPL");
  32MODULE_AUTHOR("Christian Hentschel <chentschel@arnet.com.ar>");
  33MODULE_DESCRIPTION("SIP connection tracking helper");
  34MODULE_ALIAS("ip_conntrack_sip");
  35MODULE_ALIAS_NFCT_HELPER("sip");
  36
  37#define MAX_PORTS       8
  38static unsigned short ports[MAX_PORTS];
  39static unsigned int ports_c;
  40module_param_array(ports, ushort, &ports_c, 0400);
  41MODULE_PARM_DESC(ports, "port numbers of SIP servers");
  42
  43static unsigned int sip_timeout __read_mostly = SIP_TIMEOUT;
  44module_param(sip_timeout, uint, 0600);
  45MODULE_PARM_DESC(sip_timeout, "timeout for the master SIP session");
  46
  47static int sip_direct_signalling __read_mostly = 1;
  48module_param(sip_direct_signalling, int, 0600);
  49MODULE_PARM_DESC(sip_direct_signalling, "expect incoming calls from registrar "
  50                                        "only (default 1)");
  51
  52static int sip_direct_media __read_mostly = 1;
  53module_param(sip_direct_media, int, 0600);
  54MODULE_PARM_DESC(sip_direct_media, "Expect Media streams between signalling "
  55                                   "endpoints only (default 1)");
  56
  57const struct nf_nat_sip_hooks *nf_nat_sip_hooks;
  58EXPORT_SYMBOL_GPL(nf_nat_sip_hooks);
  59
  60static int string_len(const struct nf_conn *ct, const char *dptr,
  61                      const char *limit, int *shift)
  62{
  63        int len = 0;
  64
  65        while (dptr < limit && isalpha(*dptr)) {
  66                dptr++;
  67                len++;
  68        }
  69        return len;
  70}
  71
  72static int digits_len(const struct nf_conn *ct, const char *dptr,
  73                      const char *limit, int *shift)
  74{
  75        int len = 0;
  76        while (dptr < limit && isdigit(*dptr)) {
  77                dptr++;
  78                len++;
  79        }
  80        return len;
  81}
  82
  83static int iswordc(const char c)
  84{
  85        if (isalnum(c) || c == '!' || c == '"' || c == '%' ||
  86            (c >= '(' && c <= '+') || c == ':' || c == '<' || c == '>' ||
  87            c == '?' || (c >= '[' && c <= ']') || c == '_' || c == '`' ||
  88            c == '{' || c == '}' || c == '~' || (c >= '-' && c <= '/') ||
  89            c == '\'')
  90                return 1;
  91        return 0;
  92}
  93
  94static int word_len(const char *dptr, const char *limit)
  95{
  96        int len = 0;
  97        while (dptr < limit && iswordc(*dptr)) {
  98                dptr++;
  99                len++;
 100        }
 101        return len;
 102}
 103
 104static int callid_len(const struct nf_conn *ct, const char *dptr,
 105                      const char *limit, int *shift)
 106{
 107        int len, domain_len;
 108
 109        len = word_len(dptr, limit);
 110        dptr += len;
 111        if (!len || dptr == limit || *dptr != '@')
 112                return len;
 113        dptr++;
 114        len++;
 115
 116        domain_len = word_len(dptr, limit);
 117        if (!domain_len)
 118                return 0;
 119        return len + domain_len;
 120}
 121
 122/* get media type + port length */
 123static int media_len(const struct nf_conn *ct, const char *dptr,
 124                     const char *limit, int *shift)
 125{
 126        int len = string_len(ct, dptr, limit, shift);
 127
 128        dptr += len;
 129        if (dptr >= limit || *dptr != ' ')
 130                return 0;
 131        len++;
 132        dptr++;
 133
 134        return len + digits_len(ct, dptr, limit, shift);
 135}
 136
 137static int sip_parse_addr(const struct nf_conn *ct, const char *cp,
 138                          const char **endp, union nf_inet_addr *addr,
 139                          const char *limit, bool delim)
 140{
 141        const char *end;
 142        int ret;
 143
 144        if (!ct)
 145                return 0;
 146
 147        memset(addr, 0, sizeof(*addr));
 148        switch (nf_ct_l3num(ct)) {
 149        case AF_INET:
 150                ret = in4_pton(cp, limit - cp, (u8 *)&addr->ip, -1, &end);
 151                if (ret == 0)
 152                        return 0;
 153                break;
 154        case AF_INET6:
 155                if (cp < limit && *cp == '[')
 156                        cp++;
 157                else if (delim)
 158                        return 0;
 159
 160                ret = in6_pton(cp, limit - cp, (u8 *)&addr->ip6, -1, &end);
 161                if (ret == 0)
 162                        return 0;
 163
 164                if (end < limit && *end == ']')
 165                        end++;
 166                else if (delim)
 167                        return 0;
 168                break;
 169        default:
 170                BUG();
 171        }
 172
 173        if (endp)
 174                *endp = end;
 175        return 1;
 176}
 177
 178/* skip ip address. returns its length. */
 179static int epaddr_len(const struct nf_conn *ct, const char *dptr,
 180                      const char *limit, int *shift)
 181{
 182        union nf_inet_addr addr;
 183        const char *aux = dptr;
 184
 185        if (!sip_parse_addr(ct, dptr, &dptr, &addr, limit, true)) {
 186                pr_debug("ip: %s parse failed.!\n", dptr);
 187                return 0;
 188        }
 189
 190        /* Port number */
 191        if (*dptr == ':') {
 192                dptr++;
 193                dptr += digits_len(ct, dptr, limit, shift);
 194        }
 195        return dptr - aux;
 196}
 197
 198/* get address length, skiping user info. */
 199static int skp_epaddr_len(const struct nf_conn *ct, const char *dptr,
 200                          const char *limit, int *shift)
 201{
 202        const char *start = dptr;
 203        int s = *shift;
 204
 205        /* Search for @, but stop at the end of the line.
 206         * We are inside a sip: URI, so we don't need to worry about
 207         * continuation lines. */
 208        while (dptr < limit &&
 209               *dptr != '@' && *dptr != '\r' && *dptr != '\n') {
 210                (*shift)++;
 211                dptr++;
 212        }
 213
 214        if (dptr < limit && *dptr == '@') {
 215                dptr++;
 216                (*shift)++;
 217        } else {
 218                dptr = start;
 219                *shift = s;
 220        }
 221
 222        return epaddr_len(ct, dptr, limit, shift);
 223}
 224
 225/* Parse a SIP request line of the form:
 226 *
 227 * Request-Line = Method SP Request-URI SP SIP-Version CRLF
 228 *
 229 * and return the offset and length of the address contained in the Request-URI.
 230 */
 231int ct_sip_parse_request(const struct nf_conn *ct,
 232                         const char *dptr, unsigned int datalen,
 233                         unsigned int *matchoff, unsigned int *matchlen,
 234                         union nf_inet_addr *addr, __be16 *port)
 235{
 236        const char *start = dptr, *limit = dptr + datalen, *end;
 237        unsigned int mlen;
 238        unsigned int p;
 239        int shift = 0;
 240
 241        /* Skip method and following whitespace */
 242        mlen = string_len(ct, dptr, limit, NULL);
 243        if (!mlen)
 244                return 0;
 245        dptr += mlen;
 246        if (++dptr >= limit)
 247                return 0;
 248
 249        /* Find SIP URI */
 250        for (; dptr < limit - strlen("sip:"); dptr++) {
 251                if (*dptr == '\r' || *dptr == '\n')
 252                        return -1;
 253                if (strncasecmp(dptr, "sip:", strlen("sip:")) == 0) {
 254                        dptr += strlen("sip:");
 255                        break;
 256                }
 257        }
 258        if (!skp_epaddr_len(ct, dptr, limit, &shift))
 259                return 0;
 260        dptr += shift;
 261
 262        if (!sip_parse_addr(ct, dptr, &end, addr, limit, true))
 263                return -1;
 264        if (end < limit && *end == ':') {
 265                end++;
 266                p = simple_strtoul(end, (char **)&end, 10);
 267                if (p < 1024 || p > 65535)
 268                        return -1;
 269                *port = htons(p);
 270        } else
 271                *port = htons(SIP_PORT);
 272
 273        if (end == dptr)
 274                return 0;
 275        *matchoff = dptr - start;
 276        *matchlen = end - dptr;
 277        return 1;
 278}
 279EXPORT_SYMBOL_GPL(ct_sip_parse_request);
 280
 281/* SIP header parsing: SIP headers are located at the beginning of a line, but
 282 * may span several lines, in which case the continuation lines begin with a
 283 * whitespace character. RFC 2543 allows lines to be terminated with CR, LF or
 284 * CRLF, RFC 3261 allows only CRLF, we support both.
 285 *
 286 * Headers are followed by (optionally) whitespace, a colon, again (optionally)
 287 * whitespace and the values. Whitespace in this context means any amount of
 288 * tabs, spaces and continuation lines, which are treated as a single whitespace
 289 * character.
 290 *
 291 * Some headers may appear multiple times. A comma separated list of values is
 292 * equivalent to multiple headers.
 293 */
 294static const struct sip_header ct_sip_hdrs[] = {
 295        [SIP_HDR_CSEQ]                  = SIP_HDR("CSeq", NULL, NULL, digits_len),
 296        [SIP_HDR_FROM]                  = SIP_HDR("From", "f", "sip:", skp_epaddr_len),
 297        [SIP_HDR_TO]                    = SIP_HDR("To", "t", "sip:", skp_epaddr_len),
 298        [SIP_HDR_CONTACT]               = SIP_HDR("Contact", "m", "sip:", skp_epaddr_len),
 299        [SIP_HDR_VIA_UDP]               = SIP_HDR("Via", "v", "UDP ", epaddr_len),
 300        [SIP_HDR_VIA_TCP]               = SIP_HDR("Via", "v", "TCP ", epaddr_len),
 301        [SIP_HDR_EXPIRES]               = SIP_HDR("Expires", NULL, NULL, digits_len),
 302        [SIP_HDR_CONTENT_LENGTH]        = SIP_HDR("Content-Length", "l", NULL, digits_len),
 303        [SIP_HDR_CALL_ID]               = SIP_HDR("Call-Id", "i", NULL, callid_len),
 304};
 305
 306static const char *sip_follow_continuation(const char *dptr, const char *limit)
 307{
 308        /* Walk past newline */
 309        if (++dptr >= limit)
 310                return NULL;
 311
 312        /* Skip '\n' in CR LF */
 313        if (*(dptr - 1) == '\r' && *dptr == '\n') {
 314                if (++dptr >= limit)
 315                        return NULL;
 316        }
 317
 318        /* Continuation line? */
 319        if (*dptr != ' ' && *dptr != '\t')
 320                return NULL;
 321
 322        /* skip leading whitespace */
 323        for (; dptr < limit; dptr++) {
 324                if (*dptr != ' ' && *dptr != '\t')
 325                        break;
 326        }
 327        return dptr;
 328}
 329
 330static const char *sip_skip_whitespace(const char *dptr, const char *limit)
 331{
 332        for (; dptr < limit; dptr++) {
 333                if (*dptr == ' ' || *dptr == '\t')
 334                        continue;
 335                if (*dptr != '\r' && *dptr != '\n')
 336                        break;
 337                dptr = sip_follow_continuation(dptr, limit);
 338                break;
 339        }
 340        return dptr;
 341}
 342
 343/* Search within a SIP header value, dealing with continuation lines */
 344static const char *ct_sip_header_search(const char *dptr, const char *limit,
 345                                        const char *needle, unsigned int len)
 346{
 347        for (limit -= len; dptr < limit; dptr++) {
 348                if (*dptr == '\r' || *dptr == '\n') {
 349                        dptr = sip_follow_continuation(dptr, limit);
 350                        if (dptr == NULL)
 351                                break;
 352                        continue;
 353                }
 354
 355                if (strncasecmp(dptr, needle, len) == 0)
 356                        return dptr;
 357        }
 358        return NULL;
 359}
 360
 361int ct_sip_get_header(const struct nf_conn *ct, const char *dptr,
 362                      unsigned int dataoff, unsigned int datalen,
 363                      enum sip_header_types type,
 364                      unsigned int *matchoff, unsigned int *matchlen)
 365{
 366        const struct sip_header *hdr = &ct_sip_hdrs[type];
 367        const char *start = dptr, *limit = dptr + datalen;
 368        int shift = 0;
 369
 370        for (dptr += dataoff; dptr < limit; dptr++) {
 371                /* Find beginning of line */
 372                if (*dptr != '\r' && *dptr != '\n')
 373                        continue;
 374                if (++dptr >= limit)
 375                        break;
 376                if (*(dptr - 1) == '\r' && *dptr == '\n') {
 377                        if (++dptr >= limit)
 378                                break;
 379                }
 380
 381                /* Skip continuation lines */
 382                if (*dptr == ' ' || *dptr == '\t')
 383                        continue;
 384
 385                /* Find header. Compact headers must be followed by a
 386                 * non-alphabetic character to avoid mismatches. */
 387                if (limit - dptr >= hdr->len &&
 388                    strncasecmp(dptr, hdr->name, hdr->len) == 0)
 389                        dptr += hdr->len;
 390                else if (hdr->cname && limit - dptr >= hdr->clen + 1 &&
 391                         strncasecmp(dptr, hdr->cname, hdr->clen) == 0 &&
 392                         !isalpha(*(dptr + hdr->clen)))
 393                        dptr += hdr->clen;
 394                else
 395                        continue;
 396
 397                /* Find and skip colon */
 398                dptr = sip_skip_whitespace(dptr, limit);
 399                if (dptr == NULL)
 400                        break;
 401                if (*dptr != ':' || ++dptr >= limit)
 402                        break;
 403
 404                /* Skip whitespace after colon */
 405                dptr = sip_skip_whitespace(dptr, limit);
 406                if (dptr == NULL)
 407                        break;
 408
 409                *matchoff = dptr - start;
 410                if (hdr->search) {
 411                        dptr = ct_sip_header_search(dptr, limit, hdr->search,
 412                                                    hdr->slen);
 413                        if (!dptr)
 414                                return -1;
 415                        dptr += hdr->slen;
 416                }
 417
 418                *matchlen = hdr->match_len(ct, dptr, limit, &shift);
 419                if (!*matchlen)
 420                        return -1;
 421                *matchoff = dptr - start + shift;
 422                return 1;
 423        }
 424        return 0;
 425}
 426EXPORT_SYMBOL_GPL(ct_sip_get_header);
 427
 428/* Get next header field in a list of comma separated values */
 429static int ct_sip_next_header(const struct nf_conn *ct, const char *dptr,
 430                              unsigned int dataoff, unsigned int datalen,
 431                              enum sip_header_types type,
 432                              unsigned int *matchoff, unsigned int *matchlen)
 433{
 434        const struct sip_header *hdr = &ct_sip_hdrs[type];
 435        const char *start = dptr, *limit = dptr + datalen;
 436        int shift = 0;
 437
 438        dptr += dataoff;
 439
 440        dptr = ct_sip_header_search(dptr, limit, ",", strlen(","));
 441        if (!dptr)
 442                return 0;
 443
 444        dptr = ct_sip_header_search(dptr, limit, hdr->search, hdr->slen);
 445        if (!dptr)
 446                return 0;
 447        dptr += hdr->slen;
 448
 449        *matchoff = dptr - start;
 450        *matchlen = hdr->match_len(ct, dptr, limit, &shift);
 451        if (!*matchlen)
 452                return -1;
 453        *matchoff += shift;
 454        return 1;
 455}
 456
 457/* Walk through headers until a parsable one is found or no header of the
 458 * given type is left. */
 459static int ct_sip_walk_headers(const struct nf_conn *ct, const char *dptr,
 460                               unsigned int dataoff, unsigned int datalen,
 461                               enum sip_header_types type, int *in_header,
 462                               unsigned int *matchoff, unsigned int *matchlen)
 463{
 464        int ret;
 465
 466        if (in_header && *in_header) {
 467                while (1) {
 468                        ret = ct_sip_next_header(ct, dptr, dataoff, datalen,
 469                                                 type, matchoff, matchlen);
 470                        if (ret > 0)
 471                                return ret;
 472                        if (ret == 0)
 473                                break;
 474                        dataoff += *matchoff;
 475                }
 476                *in_header = 0;
 477        }
 478
 479        while (1) {
 480                ret = ct_sip_get_header(ct, dptr, dataoff, datalen,
 481                                        type, matchoff, matchlen);
 482                if (ret > 0)
 483                        break;
 484                if (ret == 0)
 485                        return ret;
 486                dataoff += *matchoff;
 487        }
 488
 489        if (in_header)
 490                *in_header = 1;
 491        return 1;
 492}
 493
 494/* Locate a SIP header, parse the URI and return the offset and length of
 495 * the address as well as the address and port themselves. A stream of
 496 * headers can be parsed by handing in a non-NULL datalen and in_header
 497 * pointer.
 498 */
 499int ct_sip_parse_header_uri(const struct nf_conn *ct, const char *dptr,
 500                            unsigned int *dataoff, unsigned int datalen,
 501                            enum sip_header_types type, int *in_header,
 502                            unsigned int *matchoff, unsigned int *matchlen,
 503                            union nf_inet_addr *addr, __be16 *port)
 504{
 505        const char *c, *limit = dptr + datalen;
 506        unsigned int p;
 507        int ret;
 508
 509        ret = ct_sip_walk_headers(ct, dptr, dataoff ? *dataoff : 0, datalen,
 510                                  type, in_header, matchoff, matchlen);
 511        WARN_ON(ret < 0);
 512        if (ret == 0)
 513                return ret;
 514
 515        if (!sip_parse_addr(ct, dptr + *matchoff, &c, addr, limit, true))
 516                return -1;
 517        if (*c == ':') {
 518                c++;
 519                p = simple_strtoul(c, (char **)&c, 10);
 520                if (p < 1024 || p > 65535)
 521                        return -1;
 522                *port = htons(p);
 523        } else
 524                *port = htons(SIP_PORT);
 525
 526        if (dataoff)
 527                *dataoff = c - dptr;
 528        return 1;
 529}
 530EXPORT_SYMBOL_GPL(ct_sip_parse_header_uri);
 531
 532static int ct_sip_parse_param(const struct nf_conn *ct, const char *dptr,
 533                              unsigned int dataoff, unsigned int datalen,
 534                              const char *name,
 535                              unsigned int *matchoff, unsigned int *matchlen)
 536{
 537        const char *limit = dptr + datalen;
 538        const char *start;
 539        const char *end;
 540
 541        limit = ct_sip_header_search(dptr + dataoff, limit, ",", strlen(","));
 542        if (!limit)
 543                limit = dptr + datalen;
 544
 545        start = ct_sip_header_search(dptr + dataoff, limit, name, strlen(name));
 546        if (!start)
 547                return 0;
 548        start += strlen(name);
 549
 550        end = ct_sip_header_search(start, limit, ";", strlen(";"));
 551        if (!end)
 552                end = limit;
 553
 554        *matchoff = start - dptr;
 555        *matchlen = end - start;
 556        return 1;
 557}
 558
 559/* Parse address from header parameter and return address, offset and length */
 560int ct_sip_parse_address_param(const struct nf_conn *ct, const char *dptr,
 561                               unsigned int dataoff, unsigned int datalen,
 562                               const char *name,
 563                               unsigned int *matchoff, unsigned int *matchlen,
 564                               union nf_inet_addr *addr, bool delim)
 565{
 566        const char *limit = dptr + datalen;
 567        const char *start, *end;
 568
 569        limit = ct_sip_header_search(dptr + dataoff, limit, ",", strlen(","));
 570        if (!limit)
 571                limit = dptr + datalen;
 572
 573        start = ct_sip_header_search(dptr + dataoff, limit, name, strlen(name));
 574        if (!start)
 575                return 0;
 576
 577        start += strlen(name);
 578        if (!sip_parse_addr(ct, start, &end, addr, limit, delim))
 579                return 0;
 580        *matchoff = start - dptr;
 581        *matchlen = end - start;
 582        return 1;
 583}
 584EXPORT_SYMBOL_GPL(ct_sip_parse_address_param);
 585
 586/* Parse numerical header parameter and return value, offset and length */
 587int ct_sip_parse_numerical_param(const struct nf_conn *ct, const char *dptr,
 588                                 unsigned int dataoff, unsigned int datalen,
 589                                 const char *name,
 590                                 unsigned int *matchoff, unsigned int *matchlen,
 591                                 unsigned int *val)
 592{
 593        const char *limit = dptr + datalen;
 594        const char *start;
 595        char *end;
 596
 597        limit = ct_sip_header_search(dptr + dataoff, limit, ",", strlen(","));
 598        if (!limit)
 599                limit = dptr + datalen;
 600
 601        start = ct_sip_header_search(dptr + dataoff, limit, name, strlen(name));
 602        if (!start)
 603                return 0;
 604
 605        start += strlen(name);
 606        *val = simple_strtoul(start, &end, 0);
 607        if (start == end)
 608                return 0;
 609        if (matchoff && matchlen) {
 610                *matchoff = start - dptr;
 611                *matchlen = end - start;
 612        }
 613        return 1;
 614}
 615EXPORT_SYMBOL_GPL(ct_sip_parse_numerical_param);
 616
 617static int ct_sip_parse_transport(struct nf_conn *ct, const char *dptr,
 618                                  unsigned int dataoff, unsigned int datalen,
 619                                  u8 *proto)
 620{
 621        unsigned int matchoff, matchlen;
 622
 623        if (ct_sip_parse_param(ct, dptr, dataoff, datalen, "transport=",
 624                               &matchoff, &matchlen)) {
 625                if (!strncasecmp(dptr + matchoff, "TCP", strlen("TCP")))
 626                        *proto = IPPROTO_TCP;
 627                else if (!strncasecmp(dptr + matchoff, "UDP", strlen("UDP")))
 628                        *proto = IPPROTO_UDP;
 629                else
 630                        return 0;
 631
 632                if (*proto != nf_ct_protonum(ct))
 633                        return 0;
 634        } else
 635                *proto = nf_ct_protonum(ct);
 636
 637        return 1;
 638}
 639
 640static int sdp_parse_addr(const struct nf_conn *ct, const char *cp,
 641                          const char **endp, union nf_inet_addr *addr,
 642                          const char *limit)
 643{
 644        const char *end;
 645        int ret;
 646
 647        memset(addr, 0, sizeof(*addr));
 648        switch (nf_ct_l3num(ct)) {
 649        case AF_INET:
 650                ret = in4_pton(cp, limit - cp, (u8 *)&addr->ip, -1, &end);
 651                break;
 652        case AF_INET6:
 653                ret = in6_pton(cp, limit - cp, (u8 *)&addr->ip6, -1, &end);
 654                break;
 655        default:
 656                BUG();
 657        }
 658
 659        if (ret == 0)
 660                return 0;
 661        if (endp)
 662                *endp = end;
 663        return 1;
 664}
 665
 666/* skip ip address. returns its length. */
 667static int sdp_addr_len(const struct nf_conn *ct, const char *dptr,
 668                        const char *limit, int *shift)
 669{
 670        union nf_inet_addr addr;
 671        const char *aux = dptr;
 672
 673        if (!sdp_parse_addr(ct, dptr, &dptr, &addr, limit)) {
 674                pr_debug("ip: %s parse failed.!\n", dptr);
 675                return 0;
 676        }
 677
 678        return dptr - aux;
 679}
 680
 681/* SDP header parsing: a SDP session description contains an ordered set of
 682 * headers, starting with a section containing general session parameters,
 683 * optionally followed by multiple media descriptions.
 684 *
 685 * SDP headers always start at the beginning of a line. According to RFC 2327:
 686 * "The sequence CRLF (0x0d0a) is used to end a record, although parsers should
 687 * be tolerant and also accept records terminated with a single newline
 688 * character". We handle both cases.
 689 */
 690static const struct sip_header ct_sdp_hdrs_v4[] = {
 691        [SDP_HDR_VERSION]       = SDP_HDR("v=", NULL, digits_len),
 692        [SDP_HDR_OWNER]         = SDP_HDR("o=", "IN IP4 ", sdp_addr_len),
 693        [SDP_HDR_CONNECTION]    = SDP_HDR("c=", "IN IP4 ", sdp_addr_len),
 694        [SDP_HDR_MEDIA]         = SDP_HDR("m=", NULL, media_len),
 695};
 696
 697static const struct sip_header ct_sdp_hdrs_v6[] = {
 698        [SDP_HDR_VERSION]       = SDP_HDR("v=", NULL, digits_len),
 699        [SDP_HDR_OWNER]         = SDP_HDR("o=", "IN IP6 ", sdp_addr_len),
 700        [SDP_HDR_CONNECTION]    = SDP_HDR("c=", "IN IP6 ", sdp_addr_len),
 701        [SDP_HDR_MEDIA]         = SDP_HDR("m=", NULL, media_len),
 702};
 703
 704/* Linear string search within SDP header values */
 705static const char *ct_sdp_header_search(const char *dptr, const char *limit,
 706                                        const char *needle, unsigned int len)
 707{
 708        for (limit -= len; dptr < limit; dptr++) {
 709                if (*dptr == '\r' || *dptr == '\n')
 710                        break;
 711                if (strncmp(dptr, needle, len) == 0)
 712                        return dptr;
 713        }
 714        return NULL;
 715}
 716
 717/* Locate a SDP header (optionally a substring within the header value),
 718 * optionally stopping at the first occurrence of the term header, parse
 719 * it and return the offset and length of the data we're interested in.
 720 */
 721int ct_sip_get_sdp_header(const struct nf_conn *ct, const char *dptr,
 722                          unsigned int dataoff, unsigned int datalen,
 723                          enum sdp_header_types type,
 724                          enum sdp_header_types term,
 725                          unsigned int *matchoff, unsigned int *matchlen)
 726{
 727        const struct sip_header *hdrs, *hdr, *thdr;
 728        const char *start = dptr, *limit = dptr + datalen;
 729        int shift = 0;
 730
 731        hdrs = nf_ct_l3num(ct) == NFPROTO_IPV4 ? ct_sdp_hdrs_v4 : ct_sdp_hdrs_v6;
 732        hdr = &hdrs[type];
 733        thdr = &hdrs[term];
 734
 735        for (dptr += dataoff; dptr < limit; dptr++) {
 736                /* Find beginning of line */
 737                if (*dptr != '\r' && *dptr != '\n')
 738                        continue;
 739                if (++dptr >= limit)
 740                        break;
 741                if (*(dptr - 1) == '\r' && *dptr == '\n') {
 742                        if (++dptr >= limit)
 743                                break;
 744                }
 745
 746                if (term != SDP_HDR_UNSPEC &&
 747                    limit - dptr >= thdr->len &&
 748                    strncasecmp(dptr, thdr->name, thdr->len) == 0)
 749                        break;
 750                else if (limit - dptr >= hdr->len &&
 751                         strncasecmp(dptr, hdr->name, hdr->len) == 0)
 752                        dptr += hdr->len;
 753                else
 754                        continue;
 755
 756                *matchoff = dptr - start;
 757                if (hdr->search) {
 758                        dptr = ct_sdp_header_search(dptr, limit, hdr->search,
 759                                                    hdr->slen);
 760                        if (!dptr)
 761                                return -1;
 762                        dptr += hdr->slen;
 763                }
 764
 765                *matchlen = hdr->match_len(ct, dptr, limit, &shift);
 766                if (!*matchlen)
 767                        return -1;
 768                *matchoff = dptr - start + shift;
 769                return 1;
 770        }
 771        return 0;
 772}
 773EXPORT_SYMBOL_GPL(ct_sip_get_sdp_header);
 774
 775static int ct_sip_parse_sdp_addr(const struct nf_conn *ct, const char *dptr,
 776                                 unsigned int dataoff, unsigned int datalen,
 777                                 enum sdp_header_types type,
 778                                 enum sdp_header_types term,
 779                                 unsigned int *matchoff, unsigned int *matchlen,
 780                                 union nf_inet_addr *addr)
 781{
 782        int ret;
 783
 784        ret = ct_sip_get_sdp_header(ct, dptr, dataoff, datalen, type, term,
 785                                    matchoff, matchlen);
 786        if (ret <= 0)
 787                return ret;
 788
 789        if (!sdp_parse_addr(ct, dptr + *matchoff, NULL, addr,
 790                            dptr + *matchoff + *matchlen))
 791                return -1;
 792        return 1;
 793}
 794
 795static int refresh_signalling_expectation(struct nf_conn *ct,
 796                                          union nf_inet_addr *addr,
 797                                          u8 proto, __be16 port,
 798                                          unsigned int expires)
 799{
 800        struct nf_conn_help *help = nfct_help(ct);
 801        struct nf_conntrack_expect *exp;
 802        struct hlist_node *next;
 803        int found = 0;
 804
 805        spin_lock_bh(&nf_conntrack_expect_lock);
 806        hlist_for_each_entry_safe(exp, next, &help->expectations, lnode) {
 807                if (exp->class != SIP_EXPECT_SIGNALLING ||
 808                    !nf_inet_addr_cmp(&exp->tuple.dst.u3, addr) ||
 809                    exp->tuple.dst.protonum != proto ||
 810                    exp->tuple.dst.u.udp.port != port)
 811                        continue;
 812                if (!del_timer(&exp->timeout))
 813                        continue;
 814                exp->flags &= ~NF_CT_EXPECT_INACTIVE;
 815                exp->timeout.expires = jiffies + expires * HZ;
 816                add_timer(&exp->timeout);
 817                found = 1;
 818                break;
 819        }
 820        spin_unlock_bh(&nf_conntrack_expect_lock);
 821        return found;
 822}
 823
 824static void flush_expectations(struct nf_conn *ct, bool media)
 825{
 826        struct nf_conn_help *help = nfct_help(ct);
 827        struct nf_conntrack_expect *exp;
 828        struct hlist_node *next;
 829
 830        spin_lock_bh(&nf_conntrack_expect_lock);
 831        hlist_for_each_entry_safe(exp, next, &help->expectations, lnode) {
 832                if ((exp->class != SIP_EXPECT_SIGNALLING) ^ media)
 833                        continue;
 834                if (!del_timer(&exp->timeout))
 835                        continue;
 836                nf_ct_unlink_expect(exp);
 837                nf_ct_expect_put(exp);
 838                if (!media)
 839                        break;
 840        }
 841        spin_unlock_bh(&nf_conntrack_expect_lock);
 842}
 843
 844static int set_expected_rtp_rtcp(struct sk_buff *skb, unsigned int protoff,
 845                                 unsigned int dataoff,
 846                                 const char **dptr, unsigned int *datalen,
 847                                 union nf_inet_addr *daddr, __be16 port,
 848                                 enum sip_expectation_classes class,
 849                                 unsigned int mediaoff, unsigned int medialen)
 850{
 851        struct nf_conntrack_expect *exp, *rtp_exp, *rtcp_exp;
 852        enum ip_conntrack_info ctinfo;
 853        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
 854        struct net *net = nf_ct_net(ct);
 855        enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
 856        union nf_inet_addr *saddr;
 857        struct nf_conntrack_tuple tuple;
 858        int direct_rtp = 0, skip_expect = 0, ret = NF_DROP;
 859        u_int16_t base_port;
 860        __be16 rtp_port, rtcp_port;
 861        const struct nf_nat_sip_hooks *hooks;
 862
 863        saddr = NULL;
 864        if (sip_direct_media) {
 865                if (!nf_inet_addr_cmp(daddr, &ct->tuplehash[dir].tuple.src.u3))
 866                        return NF_ACCEPT;
 867                saddr = &ct->tuplehash[!dir].tuple.src.u3;
 868        }
 869
 870        /* We need to check whether the registration exists before attempting
 871         * to register it since we can see the same media description multiple
 872         * times on different connections in case multiple endpoints receive
 873         * the same call.
 874         *
 875         * RTP optimization: if we find a matching media channel expectation
 876         * and both the expectation and this connection are SNATed, we assume
 877         * both sides can reach each other directly and use the final
 878         * destination address from the expectation. We still need to keep
 879         * the NATed expectations for media that might arrive from the
 880         * outside, and additionally need to expect the direct RTP stream
 881         * in case it passes through us even without NAT.
 882         */
 883        memset(&tuple, 0, sizeof(tuple));
 884        if (saddr)
 885                tuple.src.u3 = *saddr;
 886        tuple.src.l3num         = nf_ct_l3num(ct);
 887        tuple.dst.protonum      = IPPROTO_UDP;
 888        tuple.dst.u3            = *daddr;
 889        tuple.dst.u.udp.port    = port;
 890
 891        rcu_read_lock();
 892        do {
 893                exp = __nf_ct_expect_find(net, nf_ct_zone(ct), &tuple);
 894
 895                if (!exp || exp->master == ct ||
 896                    nfct_help(exp->master)->helper != nfct_help(ct)->helper ||
 897                    exp->class != class)
 898                        break;
 899#ifdef CONFIG_NF_NAT_NEEDED
 900                if (!direct_rtp &&
 901                    (!nf_inet_addr_cmp(&exp->saved_addr, &exp->tuple.dst.u3) ||
 902                     exp->saved_proto.udp.port != exp->tuple.dst.u.udp.port) &&
 903                    ct->status & IPS_NAT_MASK) {
 904                        *daddr                  = exp->saved_addr;
 905                        tuple.dst.u3            = exp->saved_addr;
 906                        tuple.dst.u.udp.port    = exp->saved_proto.udp.port;
 907                        direct_rtp = 1;
 908                } else
 909#endif
 910                        skip_expect = 1;
 911        } while (!skip_expect);
 912
 913        base_port = ntohs(tuple.dst.u.udp.port) & ~1;
 914        rtp_port = htons(base_port);
 915        rtcp_port = htons(base_port + 1);
 916
 917        if (direct_rtp) {
 918                hooks = rcu_dereference(nf_nat_sip_hooks);
 919                if (hooks &&
 920                    !hooks->sdp_port(skb, protoff, dataoff, dptr, datalen,
 921                                     mediaoff, medialen, ntohs(rtp_port)))
 922                        goto err1;
 923        }
 924
 925        if (skip_expect) {
 926                rcu_read_unlock();
 927                return NF_ACCEPT;
 928        }
 929
 930        rtp_exp = nf_ct_expect_alloc(ct);
 931        if (rtp_exp == NULL)
 932                goto err1;
 933        nf_ct_expect_init(rtp_exp, class, nf_ct_l3num(ct), saddr, daddr,
 934                          IPPROTO_UDP, NULL, &rtp_port);
 935
 936        rtcp_exp = nf_ct_expect_alloc(ct);
 937        if (rtcp_exp == NULL)
 938                goto err2;
 939        nf_ct_expect_init(rtcp_exp, class, nf_ct_l3num(ct), saddr, daddr,
 940                          IPPROTO_UDP, NULL, &rtcp_port);
 941
 942        hooks = rcu_dereference(nf_nat_sip_hooks);
 943        if (hooks && ct->status & IPS_NAT_MASK && !direct_rtp)
 944                ret = hooks->sdp_media(skb, protoff, dataoff, dptr,
 945                                       datalen, rtp_exp, rtcp_exp,
 946                                       mediaoff, medialen, daddr);
 947        else {
 948                if (nf_ct_expect_related(rtp_exp) == 0) {
 949                        if (nf_ct_expect_related(rtcp_exp) != 0)
 950                                nf_ct_unexpect_related(rtp_exp);
 951                        else
 952                                ret = NF_ACCEPT;
 953                }
 954        }
 955        nf_ct_expect_put(rtcp_exp);
 956err2:
 957        nf_ct_expect_put(rtp_exp);
 958err1:
 959        rcu_read_unlock();
 960        return ret;
 961}
 962
 963static const struct sdp_media_type sdp_media_types[] = {
 964        SDP_MEDIA_TYPE("audio ", SIP_EXPECT_AUDIO),
 965        SDP_MEDIA_TYPE("video ", SIP_EXPECT_VIDEO),
 966        SDP_MEDIA_TYPE("image ", SIP_EXPECT_IMAGE),
 967};
 968
 969static const struct sdp_media_type *sdp_media_type(const char *dptr,
 970                                                   unsigned int matchoff,
 971                                                   unsigned int matchlen)
 972{
 973        const struct sdp_media_type *t;
 974        unsigned int i;
 975
 976        for (i = 0; i < ARRAY_SIZE(sdp_media_types); i++) {
 977                t = &sdp_media_types[i];
 978                if (matchlen < t->len ||
 979                    strncmp(dptr + matchoff, t->name, t->len))
 980                        continue;
 981                return t;
 982        }
 983        return NULL;
 984}
 985
 986static int process_sdp(struct sk_buff *skb, unsigned int protoff,
 987                       unsigned int dataoff,
 988                       const char **dptr, unsigned int *datalen,
 989                       unsigned int cseq)
 990{
 991        enum ip_conntrack_info ctinfo;
 992        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
 993        unsigned int matchoff, matchlen;
 994        unsigned int mediaoff, medialen;
 995        unsigned int sdpoff;
 996        unsigned int caddr_len, maddr_len;
 997        unsigned int i;
 998        union nf_inet_addr caddr, maddr, rtp_addr;
 999        const struct nf_nat_sip_hooks *hooks;
1000        unsigned int port;
1001        const struct sdp_media_type *t;
1002        int ret = NF_ACCEPT;
1003
1004        hooks = rcu_dereference(nf_nat_sip_hooks);
1005
1006        /* Find beginning of session description */
1007        if (ct_sip_get_sdp_header(ct, *dptr, 0, *datalen,
1008                                  SDP_HDR_VERSION, SDP_HDR_UNSPEC,
1009                                  &matchoff, &matchlen) <= 0)
1010                return NF_ACCEPT;
1011        sdpoff = matchoff;
1012
1013        /* The connection information is contained in the session description
1014         * and/or once per media description. The first media description marks
1015         * the end of the session description. */
1016        caddr_len = 0;
1017        if (ct_sip_parse_sdp_addr(ct, *dptr, sdpoff, *datalen,
1018                                  SDP_HDR_CONNECTION, SDP_HDR_MEDIA,
1019                                  &matchoff, &matchlen, &caddr) > 0)
1020                caddr_len = matchlen;
1021
1022        mediaoff = sdpoff;
1023        for (i = 0; i < ARRAY_SIZE(sdp_media_types); ) {
1024                if (ct_sip_get_sdp_header(ct, *dptr, mediaoff, *datalen,
1025                                          SDP_HDR_MEDIA, SDP_HDR_UNSPEC,
1026                                          &mediaoff, &medialen) <= 0)
1027                        break;
1028
1029                /* Get media type and port number. A media port value of zero
1030                 * indicates an inactive stream. */
1031                t = sdp_media_type(*dptr, mediaoff, medialen);
1032                if (!t) {
1033                        mediaoff += medialen;
1034                        continue;
1035                }
1036                mediaoff += t->len;
1037                medialen -= t->len;
1038
1039                port = simple_strtoul(*dptr + mediaoff, NULL, 10);
1040                if (port == 0)
1041                        continue;
1042                if (port < 1024 || port > 65535) {
1043                        nf_ct_helper_log(skb, ct, "wrong port %u", port);
1044                        return NF_DROP;
1045                }
1046
1047                /* The media description overrides the session description. */
1048                maddr_len = 0;
1049                if (ct_sip_parse_sdp_addr(ct, *dptr, mediaoff, *datalen,
1050                                          SDP_HDR_CONNECTION, SDP_HDR_MEDIA,
1051                                          &matchoff, &matchlen, &maddr) > 0) {
1052                        maddr_len = matchlen;
1053                        memcpy(&rtp_addr, &maddr, sizeof(rtp_addr));
1054                } else if (caddr_len)
1055                        memcpy(&rtp_addr, &caddr, sizeof(rtp_addr));
1056                else {
1057                        nf_ct_helper_log(skb, ct, "cannot parse SDP message");
1058                        return NF_DROP;
1059                }
1060
1061                ret = set_expected_rtp_rtcp(skb, protoff, dataoff,
1062                                            dptr, datalen,
1063                                            &rtp_addr, htons(port), t->class,
1064                                            mediaoff, medialen);
1065                if (ret != NF_ACCEPT) {
1066                        nf_ct_helper_log(skb, ct,
1067                                         "cannot add expectation for voice");
1068                        return ret;
1069                }
1070
1071                /* Update media connection address if present */
1072                if (maddr_len && hooks && ct->status & IPS_NAT_MASK) {
1073                        ret = hooks->sdp_addr(skb, protoff, dataoff,
1074                                              dptr, datalen, mediaoff,
1075                                              SDP_HDR_CONNECTION,
1076                                              SDP_HDR_MEDIA,
1077                                              &rtp_addr);
1078                        if (ret != NF_ACCEPT) {
1079                                nf_ct_helper_log(skb, ct, "cannot mangle SDP");
1080                                return ret;
1081                        }
1082                }
1083                i++;
1084        }
1085
1086        /* Update session connection and owner addresses */
1087        hooks = rcu_dereference(nf_nat_sip_hooks);
1088        if (hooks && ct->status & IPS_NAT_MASK)
1089                ret = hooks->sdp_session(skb, protoff, dataoff,
1090                                         dptr, datalen, sdpoff,
1091                                         &rtp_addr);
1092
1093        return ret;
1094}
1095static int process_invite_response(struct sk_buff *skb, unsigned int protoff,
1096                                   unsigned int dataoff,
1097                                   const char **dptr, unsigned int *datalen,
1098                                   unsigned int cseq, unsigned int code)
1099{
1100        enum ip_conntrack_info ctinfo;
1101        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1102        struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1103
1104        if ((code >= 100 && code <= 199) ||
1105            (code >= 200 && code <= 299))
1106                return process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1107        else if (ct_sip_info->invite_cseq == cseq)
1108                flush_expectations(ct, true);
1109        return NF_ACCEPT;
1110}
1111
1112static int process_update_response(struct sk_buff *skb, unsigned int protoff,
1113                                   unsigned int dataoff,
1114                                   const char **dptr, unsigned int *datalen,
1115                                   unsigned int cseq, unsigned int code)
1116{
1117        enum ip_conntrack_info ctinfo;
1118        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1119        struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1120
1121        if ((code >= 100 && code <= 199) ||
1122            (code >= 200 && code <= 299))
1123                return process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1124        else if (ct_sip_info->invite_cseq == cseq)
1125                flush_expectations(ct, true);
1126        return NF_ACCEPT;
1127}
1128
1129static int process_prack_response(struct sk_buff *skb, unsigned int protoff,
1130                                  unsigned int dataoff,
1131                                  const char **dptr, unsigned int *datalen,
1132                                  unsigned int cseq, unsigned int code)
1133{
1134        enum ip_conntrack_info ctinfo;
1135        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1136        struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1137
1138        if ((code >= 100 && code <= 199) ||
1139            (code >= 200 && code <= 299))
1140                return process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1141        else if (ct_sip_info->invite_cseq == cseq)
1142                flush_expectations(ct, true);
1143        return NF_ACCEPT;
1144}
1145
1146static int process_invite_request(struct sk_buff *skb, unsigned int protoff,
1147                                  unsigned int dataoff,
1148                                  const char **dptr, unsigned int *datalen,
1149                                  unsigned int cseq)
1150{
1151        enum ip_conntrack_info ctinfo;
1152        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1153        struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1154        unsigned int ret;
1155
1156        flush_expectations(ct, true);
1157        ret = process_sdp(skb, protoff, dataoff, dptr, datalen, cseq);
1158        if (ret == NF_ACCEPT)
1159                ct_sip_info->invite_cseq = cseq;
1160        return ret;
1161}
1162
1163static int process_bye_request(struct sk_buff *skb, unsigned int protoff,
1164                               unsigned int dataoff,
1165                               const char **dptr, unsigned int *datalen,
1166                               unsigned int cseq)
1167{
1168        enum ip_conntrack_info ctinfo;
1169        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1170
1171        flush_expectations(ct, true);
1172        return NF_ACCEPT;
1173}
1174
1175/* Parse a REGISTER request and create a permanent expectation for incoming
1176 * signalling connections. The expectation is marked inactive and is activated
1177 * when receiving a response indicating success from the registrar.
1178 */
1179static int process_register_request(struct sk_buff *skb, unsigned int protoff,
1180                                    unsigned int dataoff,
1181                                    const char **dptr, unsigned int *datalen,
1182                                    unsigned int cseq)
1183{
1184        enum ip_conntrack_info ctinfo;
1185        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1186        struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1187        enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
1188        unsigned int matchoff, matchlen;
1189        struct nf_conntrack_expect *exp;
1190        union nf_inet_addr *saddr, daddr;
1191        const struct nf_nat_sip_hooks *hooks;
1192        __be16 port;
1193        u8 proto;
1194        unsigned int expires = 0;
1195        int ret;
1196
1197        /* Expected connections can not register again. */
1198        if (ct->status & IPS_EXPECTED)
1199                return NF_ACCEPT;
1200
1201        /* We must check the expiration time: a value of zero signals the
1202         * registrar to release the binding. We'll remove our expectation
1203         * when receiving the new bindings in the response, but we don't
1204         * want to create new ones.
1205         *
1206         * The expiration time may be contained in Expires: header, the
1207         * Contact: header parameters or the URI parameters.
1208         */
1209        if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_EXPIRES,
1210                              &matchoff, &matchlen) > 0)
1211                expires = simple_strtoul(*dptr + matchoff, NULL, 10);
1212
1213        ret = ct_sip_parse_header_uri(ct, *dptr, NULL, *datalen,
1214                                      SIP_HDR_CONTACT, NULL,
1215                                      &matchoff, &matchlen, &daddr, &port);
1216        if (ret < 0) {
1217                nf_ct_helper_log(skb, ct, "cannot parse contact");
1218                return NF_DROP;
1219        } else if (ret == 0)
1220                return NF_ACCEPT;
1221
1222        /* We don't support third-party registrations */
1223        if (!nf_inet_addr_cmp(&ct->tuplehash[dir].tuple.src.u3, &daddr))
1224                return NF_ACCEPT;
1225
1226        if (ct_sip_parse_transport(ct, *dptr, matchoff + matchlen, *datalen,
1227                                   &proto) == 0)
1228                return NF_ACCEPT;
1229
1230        if (ct_sip_parse_numerical_param(ct, *dptr,
1231                                         matchoff + matchlen, *datalen,
1232                                         "expires=", NULL, NULL, &expires) < 0) {
1233                nf_ct_helper_log(skb, ct, "cannot parse expires");
1234                return NF_DROP;
1235        }
1236
1237        if (expires == 0) {
1238                ret = NF_ACCEPT;
1239                goto store_cseq;
1240        }
1241
1242        exp = nf_ct_expect_alloc(ct);
1243        if (!exp) {
1244                nf_ct_helper_log(skb, ct, "cannot alloc expectation");
1245                return NF_DROP;
1246        }
1247
1248        saddr = NULL;
1249        if (sip_direct_signalling)
1250                saddr = &ct->tuplehash[!dir].tuple.src.u3;
1251
1252        nf_ct_expect_init(exp, SIP_EXPECT_SIGNALLING, nf_ct_l3num(ct),
1253                          saddr, &daddr, proto, NULL, &port);
1254        exp->timeout.expires = sip_timeout * HZ;
1255        exp->helper = nfct_help(ct)->helper;
1256        exp->flags = NF_CT_EXPECT_PERMANENT | NF_CT_EXPECT_INACTIVE;
1257
1258        hooks = rcu_dereference(nf_nat_sip_hooks);
1259        if (hooks && ct->status & IPS_NAT_MASK)
1260                ret = hooks->expect(skb, protoff, dataoff, dptr, datalen,
1261                                    exp, matchoff, matchlen);
1262        else {
1263                if (nf_ct_expect_related(exp) != 0) {
1264                        nf_ct_helper_log(skb, ct, "cannot add expectation");
1265                        ret = NF_DROP;
1266                } else
1267                        ret = NF_ACCEPT;
1268        }
1269        nf_ct_expect_put(exp);
1270
1271store_cseq:
1272        if (ret == NF_ACCEPT)
1273                ct_sip_info->register_cseq = cseq;
1274        return ret;
1275}
1276
1277static int process_register_response(struct sk_buff *skb, unsigned int protoff,
1278                                     unsigned int dataoff,
1279                                     const char **dptr, unsigned int *datalen,
1280                                     unsigned int cseq, unsigned int code)
1281{
1282        enum ip_conntrack_info ctinfo;
1283        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1284        struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1285        enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
1286        union nf_inet_addr addr;
1287        __be16 port;
1288        u8 proto;
1289        unsigned int matchoff, matchlen, coff = 0;
1290        unsigned int expires = 0;
1291        int in_contact = 0, ret;
1292
1293        /* According to RFC 3261, "UAs MUST NOT send a new registration until
1294         * they have received a final response from the registrar for the
1295         * previous one or the previous REGISTER request has timed out".
1296         *
1297         * However, some servers fail to detect retransmissions and send late
1298         * responses, so we store the sequence number of the last valid
1299         * request and compare it here.
1300         */
1301        if (ct_sip_info->register_cseq != cseq)
1302                return NF_ACCEPT;
1303
1304        if (code >= 100 && code <= 199)
1305                return NF_ACCEPT;
1306        if (code < 200 || code > 299)
1307                goto flush;
1308
1309        if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_EXPIRES,
1310                              &matchoff, &matchlen) > 0)
1311                expires = simple_strtoul(*dptr + matchoff, NULL, 10);
1312
1313        while (1) {
1314                unsigned int c_expires = expires;
1315
1316                ret = ct_sip_parse_header_uri(ct, *dptr, &coff, *datalen,
1317                                              SIP_HDR_CONTACT, &in_contact,
1318                                              &matchoff, &matchlen,
1319                                              &addr, &port);
1320                if (ret < 0) {
1321                        nf_ct_helper_log(skb, ct, "cannot parse contact");
1322                        return NF_DROP;
1323                } else if (ret == 0)
1324                        break;
1325
1326                /* We don't support third-party registrations */
1327                if (!nf_inet_addr_cmp(&ct->tuplehash[dir].tuple.dst.u3, &addr))
1328                        continue;
1329
1330                if (ct_sip_parse_transport(ct, *dptr, matchoff + matchlen,
1331                                           *datalen, &proto) == 0)
1332                        continue;
1333
1334                ret = ct_sip_parse_numerical_param(ct, *dptr,
1335                                                   matchoff + matchlen,
1336                                                   *datalen, "expires=",
1337                                                   NULL, NULL, &c_expires);
1338                if (ret < 0) {
1339                        nf_ct_helper_log(skb, ct, "cannot parse expires");
1340                        return NF_DROP;
1341                }
1342                if (c_expires == 0)
1343                        break;
1344                if (refresh_signalling_expectation(ct, &addr, proto, port,
1345                                                   c_expires))
1346                        return NF_ACCEPT;
1347        }
1348
1349flush:
1350        flush_expectations(ct, false);
1351        return NF_ACCEPT;
1352}
1353
1354static const struct sip_handler sip_handlers[] = {
1355        SIP_HANDLER("INVITE", process_invite_request, process_invite_response),
1356        SIP_HANDLER("UPDATE", process_sdp, process_update_response),
1357        SIP_HANDLER("ACK", process_sdp, NULL),
1358        SIP_HANDLER("PRACK", process_sdp, process_prack_response),
1359        SIP_HANDLER("BYE", process_bye_request, NULL),
1360        SIP_HANDLER("REGISTER", process_register_request, process_register_response),
1361};
1362
1363static int process_sip_response(struct sk_buff *skb, unsigned int protoff,
1364                                unsigned int dataoff,
1365                                const char **dptr, unsigned int *datalen)
1366{
1367        enum ip_conntrack_info ctinfo;
1368        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1369        unsigned int matchoff, matchlen, matchend;
1370        unsigned int code, cseq, i;
1371
1372        if (*datalen < strlen("SIP/2.0 200"))
1373                return NF_ACCEPT;
1374        code = simple_strtoul(*dptr + strlen("SIP/2.0 "), NULL, 10);
1375        if (!code) {
1376                nf_ct_helper_log(skb, ct, "cannot get code");
1377                return NF_DROP;
1378        }
1379
1380        if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_CSEQ,
1381                              &matchoff, &matchlen) <= 0) {
1382                nf_ct_helper_log(skb, ct, "cannot parse cseq");
1383                return NF_DROP;
1384        }
1385        cseq = simple_strtoul(*dptr + matchoff, NULL, 10);
1386        if (!cseq && *(*dptr + matchoff) != '0') {
1387                nf_ct_helper_log(skb, ct, "cannot get cseq");
1388                return NF_DROP;
1389        }
1390        matchend = matchoff + matchlen + 1;
1391
1392        for (i = 0; i < ARRAY_SIZE(sip_handlers); i++) {
1393                const struct sip_handler *handler;
1394
1395                handler = &sip_handlers[i];
1396                if (handler->response == NULL)
1397                        continue;
1398                if (*datalen < matchend + handler->len ||
1399                    strncasecmp(*dptr + matchend, handler->method, handler->len))
1400                        continue;
1401                return handler->response(skb, protoff, dataoff, dptr, datalen,
1402                                         cseq, code);
1403        }
1404        return NF_ACCEPT;
1405}
1406
1407static int process_sip_request(struct sk_buff *skb, unsigned int protoff,
1408                               unsigned int dataoff,
1409                               const char **dptr, unsigned int *datalen)
1410{
1411        enum ip_conntrack_info ctinfo;
1412        struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
1413        struct nf_ct_sip_master *ct_sip_info = nfct_help_data(ct);
1414        enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
1415        unsigned int matchoff, matchlen;
1416        unsigned int cseq, i;
1417        union nf_inet_addr addr;
1418        __be16 port;
1419
1420        /* Many Cisco IP phones use a high source port for SIP requests, but
1421         * listen for the response on port 5060.  If we are the local
1422         * router for one of these phones, save the port number from the
1423         * Via: header so that nf_nat_sip can redirect the responses to
1424         * the correct port.
1425         */
1426        if (ct_sip_parse_header_uri(ct, *dptr, NULL, *datalen,
1427                                    SIP_HDR_VIA_UDP, NULL, &matchoff,
1428                                    &matchlen, &addr, &port) > 0 &&
1429            port != ct->tuplehash[dir].tuple.src.u.udp.port &&
1430            nf_inet_addr_cmp(&addr, &ct->tuplehash[dir].tuple.src.u3))
1431                ct_sip_info->forced_dport = port;
1432
1433        for (i = 0; i < ARRAY_SIZE(sip_handlers); i++) {
1434                const struct sip_handler *handler;
1435
1436                handler = &sip_handlers[i];
1437                if (handler->request == NULL)
1438                        continue;
1439                if (*datalen < handler->len + 2 ||
1440                    strncasecmp(*dptr, handler->method, handler->len))
1441                        continue;
1442                if ((*dptr)[handler->len] != ' ' ||
1443                    !isalpha((*dptr)[handler->len+1]))
1444                        continue;
1445
1446                if (ct_sip_get_header(ct, *dptr, 0, *datalen, SIP_HDR_CSEQ,
1447                                      &matchoff, &matchlen) <= 0) {
1448                        nf_ct_helper_log(skb, ct, "cannot parse cseq");
1449                        return NF_DROP;
1450                }
1451                cseq = simple_strtoul(*dptr + matchoff, NULL, 10);
1452                if (!cseq && *(*dptr + matchoff) != '0') {
1453                        nf_ct_helper_log(skb, ct, "cannot get cseq");
1454                        return NF_DROP;
1455                }
1456
1457                return handler->request(skb, protoff, dataoff, dptr, datalen,
1458                                        cseq);
1459        }
1460        return NF_ACCEPT;
1461}
1462
1463static int process_sip_msg(struct sk_buff *skb, struct nf_conn *ct,
1464                           unsigned int protoff, unsigned int dataoff,
1465                           const char **dptr, unsigned int *datalen)
1466{
1467        const struct nf_nat_sip_hooks *hooks;
1468        int ret;
1469
1470        if (strncasecmp(*dptr, "SIP/2.0 ", strlen("SIP/2.0 ")) != 0)
1471                ret = process_sip_request(skb, protoff, dataoff, dptr, datalen);
1472        else
1473                ret = process_sip_response(skb, protoff, dataoff, dptr, datalen);
1474
1475        if (ret == NF_ACCEPT && ct->status & IPS_NAT_MASK) {
1476                hooks = rcu_dereference(nf_nat_sip_hooks);
1477                if (hooks && !hooks->msg(skb, protoff, dataoff,
1478                                         dptr, datalen)) {
1479                        nf_ct_helper_log(skb, ct, "cannot NAT SIP message");
1480                        ret = NF_DROP;
1481                }
1482        }
1483
1484        return ret;
1485}
1486
1487static int sip_help_tcp(struct sk_buff *skb, unsigned int protoff,
1488                        struct nf_conn *ct, enum ip_conntrack_info ctinfo)
1489{
1490        struct tcphdr *th, _tcph;
1491        unsigned int dataoff, datalen;
1492        unsigned int matchoff, matchlen, clen;
1493        unsigned int msglen, origlen;
1494        const char *dptr, *end;
1495        s16 diff, tdiff = 0;
1496        int ret = NF_ACCEPT;
1497        bool term;
1498
1499        if (ctinfo != IP_CT_ESTABLISHED &&
1500            ctinfo != IP_CT_ESTABLISHED_REPLY)
1501                return NF_ACCEPT;
1502
1503        /* No Data ? */
1504        th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
1505        if (th == NULL)
1506                return NF_ACCEPT;
1507        dataoff = protoff + th->doff * 4;
1508        if (dataoff >= skb->len)
1509                return NF_ACCEPT;
1510
1511        nf_ct_refresh(ct, skb, sip_timeout * HZ);
1512
1513        if (unlikely(skb_linearize(skb)))
1514                return NF_DROP;
1515
1516        dptr = skb->data + dataoff;
1517        datalen = skb->len - dataoff;
1518        if (datalen < strlen("SIP/2.0 200"))
1519                return NF_ACCEPT;
1520
1521        while (1) {
1522                if (ct_sip_get_header(ct, dptr, 0, datalen,
1523                                      SIP_HDR_CONTENT_LENGTH,
1524                                      &matchoff, &matchlen) <= 0)
1525                        break;
1526
1527                clen = simple_strtoul(dptr + matchoff, (char **)&end, 10);
1528                if (dptr + matchoff == end)
1529                        break;
1530
1531                term = false;
1532                for (; end + strlen("\r\n\r\n") <= dptr + datalen; end++) {
1533                        if (end[0] == '\r' && end[1] == '\n' &&
1534                            end[2] == '\r' && end[3] == '\n') {
1535                                term = true;
1536                                break;
1537                        }
1538                }
1539                if (!term)
1540                        break;
1541                end += strlen("\r\n\r\n") + clen;
1542
1543                msglen = origlen = end - dptr;
1544                if (msglen > datalen)
1545                        return NF_ACCEPT;
1546
1547                ret = process_sip_msg(skb, ct, protoff, dataoff,
1548                                      &dptr, &msglen);
1549                /* process_sip_* functions report why this packet is dropped */
1550                if (ret != NF_ACCEPT)
1551                        break;
1552                diff     = msglen - origlen;
1553                tdiff   += diff;
1554
1555                dataoff += msglen;
1556                dptr    += msglen;
1557                datalen  = datalen + diff - msglen;
1558        }
1559
1560        if (ret == NF_ACCEPT && ct->status & IPS_NAT_MASK) {
1561                const struct nf_nat_sip_hooks *hooks;
1562
1563                hooks = rcu_dereference(nf_nat_sip_hooks);
1564                if (hooks)
1565                        hooks->seq_adjust(skb, protoff, tdiff);
1566        }
1567
1568        return ret;
1569}
1570
1571static int sip_help_udp(struct sk_buff *skb, unsigned int protoff,
1572                        struct nf_conn *ct, enum ip_conntrack_info ctinfo)
1573{
1574        unsigned int dataoff, datalen;
1575        const char *dptr;
1576
1577        /* No Data ? */
1578        dataoff = protoff + sizeof(struct udphdr);
1579        if (dataoff >= skb->len)
1580                return NF_ACCEPT;
1581
1582        nf_ct_refresh(ct, skb, sip_timeout * HZ);
1583
1584        if (unlikely(skb_linearize(skb)))
1585                return NF_DROP;
1586
1587        dptr = skb->data + dataoff;
1588        datalen = skb->len - dataoff;
1589        if (datalen < strlen("SIP/2.0 200"))
1590                return NF_ACCEPT;
1591
1592        return process_sip_msg(skb, ct, protoff, dataoff, &dptr, &datalen);
1593}
1594
1595static struct nf_conntrack_helper sip[MAX_PORTS * 4] __read_mostly;
1596
1597static const struct nf_conntrack_expect_policy sip_exp_policy[SIP_EXPECT_MAX + 1] = {
1598        [SIP_EXPECT_SIGNALLING] = {
1599                .name           = "signalling",
1600                .max_expected   = 1,
1601                .timeout        = 3 * 60,
1602        },
1603        [SIP_EXPECT_AUDIO] = {
1604                .name           = "audio",
1605                .max_expected   = 2 * IP_CT_DIR_MAX,
1606                .timeout        = 3 * 60,
1607        },
1608        [SIP_EXPECT_VIDEO] = {
1609                .name           = "video",
1610                .max_expected   = 2 * IP_CT_DIR_MAX,
1611                .timeout        = 3 * 60,
1612        },
1613        [SIP_EXPECT_IMAGE] = {
1614                .name           = "image",
1615                .max_expected   = IP_CT_DIR_MAX,
1616                .timeout        = 3 * 60,
1617        },
1618};
1619
1620static void nf_conntrack_sip_fini(void)
1621{
1622        nf_conntrack_helpers_unregister(sip, ports_c * 4);
1623}
1624
1625static int __init nf_conntrack_sip_init(void)
1626{
1627        int i, ret;
1628
1629        if (ports_c == 0)
1630                ports[ports_c++] = SIP_PORT;
1631
1632        for (i = 0; i < ports_c; i++) {
1633                memset(&sip[i], 0, sizeof(sip[i]));
1634
1635                nf_ct_helper_init(&sip[4 * i], AF_INET, IPPROTO_UDP, "sip",
1636                                  SIP_PORT, ports[i], i, sip_exp_policy,
1637                                  SIP_EXPECT_MAX,
1638                                  sizeof(struct nf_ct_sip_master), sip_help_udp,
1639                                  NULL, THIS_MODULE);
1640                nf_ct_helper_init(&sip[4 * i + 1], AF_INET, IPPROTO_TCP, "sip",
1641                                  SIP_PORT, ports[i], i, sip_exp_policy,
1642                                  SIP_EXPECT_MAX,
1643                                  sizeof(struct nf_ct_sip_master), sip_help_tcp,
1644                                  NULL, THIS_MODULE);
1645                nf_ct_helper_init(&sip[4 * i + 2], AF_INET6, IPPROTO_UDP, "sip",
1646                                  SIP_PORT, ports[i], i, sip_exp_policy,
1647                                  SIP_EXPECT_MAX,
1648                                  sizeof(struct nf_ct_sip_master), sip_help_udp,
1649                                  NULL, THIS_MODULE);
1650                nf_ct_helper_init(&sip[4 * i + 3], AF_INET6, IPPROTO_TCP, "sip",
1651                                  SIP_PORT, ports[i], i, sip_exp_policy,
1652                                  SIP_EXPECT_MAX,
1653                                  sizeof(struct nf_ct_sip_master), sip_help_tcp,
1654                                  NULL, THIS_MODULE);
1655        }
1656
1657        ret = nf_conntrack_helpers_register(sip, ports_c * 4);
1658        if (ret < 0) {
1659                pr_err("failed to register helpers\n");
1660                return ret;
1661        }
1662        return 0;
1663}
1664
1665module_init(nf_conntrack_sip_init);
1666module_exit(nf_conntrack_sip_fini);
1667