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