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