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