ip_conntrack_core.c
上传用户:jlfgdled
上传日期:2013-04-10
资源大小:33168k
文件大小:42k
源码类别:

Linux/Unix编程

开发平台:

Unix_Linux

  1. /* Connection state tracking for netfilter.  This is separated from,
  2.    but required by, the NAT layer; it can also be used by an iptables
  3.    extension. */
  4. /* (c) 1999 Paul `Rusty' Russell.  Licenced under the GNU General
  5.  * Public Licence. 
  6.  *
  7.  * 23 Apr 2001: Harald Welte <laforge@gnumonks.org>
  8.  *  - new API and handling of conntrack/nat helpers
  9.  *  - now capable of multiple expectations for one master
  10.  * 16 Jul 2002: Harald Welte <laforge@gnumonks.org>
  11.  *  - add usage/reference counts to ip_conntrack_expect
  12.  * - export ip_conntrack[_expect]_{find_get,put} functions
  13.  * */
  14. #ifdef MODULE
  15. #define __NO_VERSION__
  16. #endif
  17. #include <linux/version.h>
  18. #include <linux/config.h>
  19. #include <linux/types.h>
  20. #include <linux/ip.h>
  21. #include <linux/netfilter.h>
  22. #include <linux/netfilter_ipv4.h>
  23. #include <linux/module.h>
  24. #include <linux/skbuff.h>
  25. #include <linux/proc_fs.h>
  26. #include <linux/vmalloc.h>
  27. #include <linux/brlock.h>
  28. #include <net/checksum.h>
  29. #include <linux/stddef.h>
  30. #include <linux/sysctl.h>
  31. #include <linux/slab.h>
  32. /* For ERR_PTR().  Yeah, I know... --RR */
  33. #include <linux/fs.h>
  34. /* This rwlock protects the main hash table, protocol/helper/expected
  35.    registrations, conntrack timers*/
  36. #define ASSERT_READ_LOCK(x) MUST_BE_READ_LOCKED(&ip_conntrack_lock)
  37. #define ASSERT_WRITE_LOCK(x) MUST_BE_WRITE_LOCKED(&ip_conntrack_lock)
  38. #include <linux/netfilter_ipv4/ip_conntrack.h>
  39. #include <linux/netfilter_ipv4/ip_conntrack_protocol.h>
  40. #include <linux/netfilter_ipv4/ip_conntrack_helper.h>
  41. #include <linux/netfilter_ipv4/ip_conntrack_core.h>
  42. #include <linux/netfilter_ipv4/listhelp.h>
  43. #define IP_CONNTRACK_VERSION "2.1"
  44. #if 0
  45. #define DEBUGP printk
  46. #else
  47. #define DEBUGP(format, args...)
  48. #endif
  49. DECLARE_RWLOCK(ip_conntrack_lock);
  50. DECLARE_RWLOCK(ip_conntrack_expect_tuple_lock);
  51. void (*ip_conntrack_destroyed)(struct ip_conntrack *conntrack) = NULL;
  52. LIST_HEAD(ip_conntrack_expect_list);
  53. LIST_HEAD(protocol_list);
  54. static LIST_HEAD(helpers);
  55. unsigned int ip_conntrack_htable_size = 0;
  56. static int ip_conntrack_max = 0;
  57. static atomic_t ip_conntrack_count = ATOMIC_INIT(0);
  58. struct list_head *ip_conntrack_hash;
  59. static kmem_cache_t *ip_conntrack_cachep;
  60. extern struct ip_conntrack_protocol ip_conntrack_generic_protocol;
  61. static inline int proto_cmpfn(const struct ip_conntrack_protocol *curr,
  62.       u_int8_t protocol)
  63. {
  64. return protocol == curr->proto;
  65. }
  66. struct ip_conntrack_protocol *__ip_ct_find_proto(u_int8_t protocol)
  67. {
  68. struct ip_conntrack_protocol *p;
  69. MUST_BE_READ_LOCKED(&ip_conntrack_lock);
  70. p = LIST_FIND(&protocol_list, proto_cmpfn,
  71.       struct ip_conntrack_protocol *, protocol);
  72. if (!p)
  73. p = &ip_conntrack_generic_protocol;
  74. return p;
  75. }
  76. struct ip_conntrack_protocol *ip_ct_find_proto(u_int8_t protocol)
  77. {
  78. struct ip_conntrack_protocol *p;
  79. READ_LOCK(&ip_conntrack_lock);
  80. p = __ip_ct_find_proto(protocol);
  81. READ_UNLOCK(&ip_conntrack_lock);
  82. return p;
  83. }
  84. inline void 
  85. ip_conntrack_put(struct ip_conntrack *ct)
  86. {
  87. IP_NF_ASSERT(ct);
  88. IP_NF_ASSERT(ct->infos[0].master);
  89. /* nf_conntrack_put wants to go via an info struct, so feed it
  90.            one at random. */
  91. nf_conntrack_put(&ct->infos[0]);
  92. }
  93. static inline u_int32_t
  94. hash_conntrack(const struct ip_conntrack_tuple *tuple)
  95. {
  96. #if 0
  97. dump_tuple(tuple);
  98. #endif
  99. /* ntohl because more differences in low bits. */
  100. /* To ensure that halves of the same connection don't hash
  101.    clash, we add the source per-proto again. */
  102. return (ntohl(tuple->src.ip + tuple->dst.ip
  103.      + tuple->src.u.all + tuple->dst.u.all
  104.      + tuple->dst.protonum)
  105. + ntohs(tuple->src.u.all))
  106. % ip_conntrack_htable_size;
  107. }
  108. inline int
  109. get_tuple(const struct iphdr *iph, size_t len,
  110.   struct ip_conntrack_tuple *tuple,
  111.   struct ip_conntrack_protocol *protocol)
  112. {
  113. int ret;
  114. /* Never happen */
  115. if (iph->frag_off & htons(IP_OFFSET)) {
  116. printk("ip_conntrack_core: Frag of proto %u.n",
  117.        iph->protocol);
  118. return 0;
  119. }
  120. /* Guarantee 8 protocol bytes: if more wanted, use len param */
  121. else if (iph->ihl * 4 + 8 > len)
  122. return 0;
  123. tuple->src.ip = iph->saddr;
  124. tuple->dst.ip = iph->daddr;
  125. tuple->dst.protonum = iph->protocol;
  126. ret = protocol->pkt_to_tuple((u_int32_t *)iph + iph->ihl,
  127.      len - 4*iph->ihl,
  128.      tuple);
  129. return ret;
  130. }
  131. static int
  132. invert_tuple(struct ip_conntrack_tuple *inverse,
  133.      const struct ip_conntrack_tuple *orig,
  134.      const struct ip_conntrack_protocol *protocol)
  135. {
  136. inverse->src.ip = orig->dst.ip;
  137. inverse->dst.ip = orig->src.ip;
  138. inverse->dst.protonum = orig->dst.protonum;
  139. return protocol->invert_tuple(inverse, orig);
  140. }
  141. /* ip_conntrack_expect helper functions */
  142. /* Compare tuple parts depending on mask. */
  143. static inline int expect_cmp(const struct ip_conntrack_expect *i,
  144.      const struct ip_conntrack_tuple *tuple)
  145. {
  146. MUST_BE_READ_LOCKED(&ip_conntrack_expect_tuple_lock);
  147. return ip_ct_tuple_mask_cmp(tuple, &i->tuple, &i->mask);
  148. }
  149. static void
  150. destroy_expect(struct ip_conntrack_expect *exp)
  151. {
  152. DEBUGP("destroy_expect(%p) use=%dn", exp, atomic_read(exp->use));
  153. IP_NF_ASSERT(atomic_read(exp->use));
  154. IP_NF_ASSERT(!timer_pending(&exp->timeout));
  155. kfree(exp);
  156. }
  157. inline void ip_conntrack_expect_put(struct ip_conntrack_expect *exp)
  158. {
  159. IP_NF_ASSERT(exp);
  160. if (atomic_dec_and_test(&exp->use)) {
  161. /* usage count dropped to zero */
  162. destroy_expect(exp);
  163. }
  164. }
  165. static inline struct ip_conntrack_expect *
  166. __ip_ct_expect_find(const struct ip_conntrack_tuple *tuple)
  167. {
  168. MUST_BE_READ_LOCKED(&ip_conntrack_lock);
  169. MUST_BE_READ_LOCKED(&ip_conntrack_expect_tuple_lock);
  170. return LIST_FIND(&ip_conntrack_expect_list, expect_cmp, 
  171.  struct ip_conntrack_expect *, tuple);
  172. }
  173. /* Find a expectation corresponding to a tuple. */
  174. struct ip_conntrack_expect *
  175. ip_conntrack_expect_find_get(const struct ip_conntrack_tuple *tuple)
  176. {
  177. struct ip_conntrack_expect *exp;
  178. READ_LOCK(&ip_conntrack_lock);
  179. READ_LOCK(&ip_conntrack_expect_tuple_lock);
  180. exp = __ip_ct_expect_find(tuple);
  181. if (exp)
  182. atomic_inc(&exp->use);
  183. READ_UNLOCK(&ip_conntrack_expect_tuple_lock);
  184. READ_UNLOCK(&ip_conntrack_lock);
  185. return exp;
  186. }
  187. /* remove one specific expectation from all lists and drop refcount,
  188.  * does _NOT_ delete the timer. */
  189. static void __unexpect_related(struct ip_conntrack_expect *expect)
  190. {
  191. DEBUGP("unexpect_related(%p)n", expect);
  192. MUST_BE_WRITE_LOCKED(&ip_conntrack_lock);
  193. /* we're not allowed to unexpect a confirmed expectation! */
  194. IP_NF_ASSERT(!expect->sibling);
  195. /* delete from global and local lists */
  196. list_del(&expect->list);
  197. list_del(&expect->expected_list);
  198. /* decrement expect-count of master conntrack */
  199. if (expect->expectant)
  200. expect->expectant->expecting--;
  201. ip_conntrack_expect_put(expect);
  202. }
  203. /* remove one specific expecatation from all lists, drop refcount
  204.  * and expire timer. 
  205.  * This function can _NOT_ be called for confirmed expects! */
  206. static void unexpect_related(struct ip_conntrack_expect *expect)
  207. {
  208. IP_NF_ASSERT(expect->expectant);
  209. IP_NF_ASSERT(expect->expectant->helper);
  210. /* if we are supposed to have a timer, but we can't delete
  211.  * it: race condition.  __unexpect_related will
  212.  * be calledd by timeout function */
  213. if (expect->expectant->helper->timeout
  214.     && !del_timer(&expect->timeout))
  215. return;
  216. __unexpect_related(expect);
  217. }
  218. /* delete all unconfirmed expectations for this conntrack */
  219. static void remove_expectations(struct ip_conntrack *ct)
  220. {
  221. struct list_head *exp_entry, *next;
  222. struct ip_conntrack_expect *exp;
  223. DEBUGP("remove_expectations(%p)n", ct);
  224. for (exp_entry = ct->sibling_list.next;
  225.      exp_entry != &ct->sibling_list; exp_entry = next) {
  226. next = exp_entry->next;
  227. exp = list_entry(exp_entry, struct ip_conntrack_expect,
  228.  expected_list);
  229. /* we skip established expectations, as we want to delete
  230.  * the un-established ones only */
  231. if (exp->sibling) {
  232. DEBUGP("remove_expectations: skipping established %p of %pn", exp->sibling, ct);
  233. continue;
  234. }
  235. IP_NF_ASSERT(list_inlist(&ip_conntrack_expect_list, exp));
  236. IP_NF_ASSERT(exp->expectant == ct);
  237. /* delete expectation from global and private lists */
  238. unexpect_related(exp);
  239. }
  240. }
  241. static void
  242. clean_from_lists(struct ip_conntrack *ct)
  243. {
  244. DEBUGP("clean_from_lists(%p)n", ct);
  245. MUST_BE_WRITE_LOCKED(&ip_conntrack_lock);
  246. /* Remove from both hash lists: must not NULL out next ptrs,
  247.            otherwise we'll look unconfirmed.  Fortunately, LIST_DELETE
  248.            doesn't do this. --RR */
  249. LIST_DELETE(&ip_conntrack_hash
  250.     [hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple)],
  251.     &ct->tuplehash[IP_CT_DIR_ORIGINAL]);
  252. LIST_DELETE(&ip_conntrack_hash
  253.     [hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple)],
  254.     &ct->tuplehash[IP_CT_DIR_REPLY]);
  255. /* Destroy all un-established, pending expectations */
  256. remove_expectations(ct);
  257. }
  258. static void
  259. destroy_conntrack(struct nf_conntrack *nfct)
  260. {
  261. struct ip_conntrack *ct = (struct ip_conntrack *)nfct;
  262. struct ip_conntrack_protocol *proto;
  263. DEBUGP("destroy_conntrack(%p)n", ct);
  264. IP_NF_ASSERT(atomic_read(&nfct->use) == 0);
  265. IP_NF_ASSERT(!timer_pending(&ct->timeout));
  266. if (ct->master && master_ct(ct))
  267. ip_conntrack_put(master_ct(ct));
  268. /* To make sure we don't get any weird locking issues here:
  269.  * destroy_conntrack() MUST NOT be called with a write lock
  270.  * to ip_conntrack_lock!!! -HW */
  271. proto = ip_ct_find_proto(ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.protonum);
  272. if (proto && proto->destroy)
  273. proto->destroy(ct);
  274. if (ip_conntrack_destroyed)
  275. ip_conntrack_destroyed(ct);
  276. WRITE_LOCK(&ip_conntrack_lock);
  277. /* Delete our master expectation */
  278. if (ct->master) {
  279. /* can't call __unexpect_related here,
  280.  * since it would screw up expect_list */
  281. list_del(&ct->master->expected_list);
  282. kfree(ct->master);
  283. }
  284. WRITE_UNLOCK(&ip_conntrack_lock);
  285. DEBUGP("destroy_conntrack: returning ct=%p to slabn", ct);
  286. kmem_cache_free(ip_conntrack_cachep, ct);
  287. atomic_dec(&ip_conntrack_count);
  288. }
  289. static void death_by_timeout(unsigned long ul_conntrack)
  290. {
  291. struct ip_conntrack *ct = (void *)ul_conntrack;
  292. WRITE_LOCK(&ip_conntrack_lock);
  293. clean_from_lists(ct);
  294. WRITE_UNLOCK(&ip_conntrack_lock);
  295. ip_conntrack_put(ct);
  296. }
  297. static inline int
  298. conntrack_tuple_cmp(const struct ip_conntrack_tuple_hash *i,
  299.     const struct ip_conntrack_tuple *tuple,
  300.     const struct ip_conntrack *ignored_conntrack)
  301. {
  302. MUST_BE_READ_LOCKED(&ip_conntrack_lock);
  303. return i->ctrack != ignored_conntrack
  304. && ip_ct_tuple_equal(tuple, &i->tuple);
  305. }
  306. static struct ip_conntrack_tuple_hash *
  307. __ip_conntrack_find(const struct ip_conntrack_tuple *tuple,
  308.     const struct ip_conntrack *ignored_conntrack)
  309. {
  310. struct ip_conntrack_tuple_hash *h;
  311. MUST_BE_READ_LOCKED(&ip_conntrack_lock);
  312. h = LIST_FIND(&ip_conntrack_hash[hash_conntrack(tuple)],
  313.       conntrack_tuple_cmp,
  314.       struct ip_conntrack_tuple_hash *,
  315.       tuple, ignored_conntrack);
  316. return h;
  317. }
  318. /* Find a connection corresponding to a tuple. */
  319. struct ip_conntrack_tuple_hash *
  320. ip_conntrack_find_get(const struct ip_conntrack_tuple *tuple,
  321.       const struct ip_conntrack *ignored_conntrack)
  322. {
  323. struct ip_conntrack_tuple_hash *h;
  324. READ_LOCK(&ip_conntrack_lock);
  325. h = __ip_conntrack_find(tuple, ignored_conntrack);
  326. if (h)
  327. atomic_inc(&h->ctrack->ct_general.use);
  328. READ_UNLOCK(&ip_conntrack_lock);
  329. return h;
  330. }
  331. static inline struct ip_conntrack *
  332. __ip_conntrack_get(struct nf_ct_info *nfct, enum ip_conntrack_info *ctinfo)
  333. {
  334. struct ip_conntrack *ct
  335. = (struct ip_conntrack *)nfct->master;
  336. /* ctinfo is the index of the nfct inside the conntrack */
  337. *ctinfo = nfct - ct->infos;
  338. IP_NF_ASSERT(*ctinfo >= 0 && *ctinfo < IP_CT_NUMBER);
  339. return ct;
  340. }
  341. /* Return conntrack and conntrack_info given skb->nfct->master */
  342. struct ip_conntrack *
  343. ip_conntrack_get(struct sk_buff *skb, enum ip_conntrack_info *ctinfo)
  344. {
  345. if (skb->nfct) 
  346. return __ip_conntrack_get(skb->nfct, ctinfo);
  347. return NULL;
  348. }
  349. /* Confirm a connection given skb->nfct; places it in hash table */
  350. int
  351. __ip_conntrack_confirm(struct nf_ct_info *nfct)
  352. {
  353. unsigned int hash, repl_hash;
  354. struct ip_conntrack *ct;
  355. enum ip_conntrack_info ctinfo;
  356. ct = __ip_conntrack_get(nfct, &ctinfo);
  357. /* ipt_REJECT uses ip_conntrack_attach to attach related
  358.    ICMP/TCP RST packets in other direction.  Actual packet
  359.    which created connection will be IP_CT_NEW or for an
  360.    expected connection, IP_CT_RELATED. */
  361. if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
  362. return NF_ACCEPT;
  363. hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
  364. repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
  365. /* We're not in hash table, and we refuse to set up related
  366.    connections for unconfirmed conns.  But packet copies and
  367.    REJECT will give spurious warnings here. */
  368. /* IP_NF_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
  369. /* No external references means noone else could have
  370.            confirmed us. */
  371. IP_NF_ASSERT(!is_confirmed(ct));
  372. DEBUGP("Confirming conntrack %pn", ct);
  373. WRITE_LOCK(&ip_conntrack_lock);
  374. /* See if there's one in the list already, including reverse:
  375.            NAT could have grabbed it without realizing, since we're
  376.            not in the hash.  If there is, we lost race. */
  377. if (!LIST_FIND(&ip_conntrack_hash[hash],
  378.        conntrack_tuple_cmp,
  379.        struct ip_conntrack_tuple_hash *,
  380.        &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple, NULL)
  381.     && !LIST_FIND(&ip_conntrack_hash[repl_hash],
  382.   conntrack_tuple_cmp,
  383.   struct ip_conntrack_tuple_hash *,
  384.   &ct->tuplehash[IP_CT_DIR_REPLY].tuple, NULL)) {
  385. list_prepend(&ip_conntrack_hash[hash],
  386.      &ct->tuplehash[IP_CT_DIR_ORIGINAL]);
  387. list_prepend(&ip_conntrack_hash[repl_hash],
  388.      &ct->tuplehash[IP_CT_DIR_REPLY]);
  389. /* Timer relative to confirmation time, not original
  390.    setting time, otherwise we'd get timer wrap in
  391.    weird delay cases. */
  392. ct->timeout.expires += jiffies;
  393. add_timer(&ct->timeout);
  394. atomic_inc(&ct->ct_general.use);
  395. WRITE_UNLOCK(&ip_conntrack_lock);
  396. return NF_ACCEPT;
  397. }
  398. WRITE_UNLOCK(&ip_conntrack_lock);
  399. return NF_DROP;
  400. }
  401. /* Returns true if a connection correspondings to the tuple (required
  402.    for NAT). */
  403. int
  404. ip_conntrack_tuple_taken(const struct ip_conntrack_tuple *tuple,
  405.  const struct ip_conntrack *ignored_conntrack)
  406. {
  407. struct ip_conntrack_tuple_hash *h;
  408. READ_LOCK(&ip_conntrack_lock);
  409. h = __ip_conntrack_find(tuple, ignored_conntrack);
  410. READ_UNLOCK(&ip_conntrack_lock);
  411. return h != NULL;
  412. }
  413. /* Returns conntrack if it dealt with ICMP, and filled in skb fields */
  414. struct ip_conntrack *
  415. icmp_error_track(struct sk_buff *skb,
  416.  enum ip_conntrack_info *ctinfo,
  417.  unsigned int hooknum)
  418. {
  419. const struct iphdr *iph;
  420. struct icmphdr *hdr;
  421. struct ip_conntrack_tuple innertuple, origtuple;
  422. struct iphdr *inner;
  423. size_t datalen;
  424. struct ip_conntrack_protocol *innerproto;
  425. struct ip_conntrack_tuple_hash *h;
  426. IP_NF_ASSERT(iph->protocol == IPPROTO_ICMP);
  427. IP_NF_ASSERT(skb->nfct == NULL);
  428. iph = skb->nh.iph;
  429. hdr = (struct icmphdr *)((u_int32_t *)iph + iph->ihl);
  430. inner = (struct iphdr *)(hdr + 1);
  431. datalen = skb->len - iph->ihl*4 - sizeof(*hdr);
  432. if (skb->len < iph->ihl * 4 + sizeof(*hdr) + sizeof(*iph)) {
  433. DEBUGP("icmp_error_track: too shortn");
  434. return NULL;
  435. }
  436. if (hdr->type != ICMP_DEST_UNREACH
  437.     && hdr->type != ICMP_SOURCE_QUENCH
  438.     && hdr->type != ICMP_TIME_EXCEEDED
  439.     && hdr->type != ICMP_PARAMETERPROB
  440.     && hdr->type != ICMP_REDIRECT)
  441. return NULL;
  442. /* Ignore ICMP's containing fragments (shouldn't happen) */
  443. if (inner->frag_off & htons(IP_OFFSET)) {
  444. DEBUGP("icmp_error_track: fragment of proto %un",
  445.        inner->protocol);
  446. return NULL;
  447. }
  448. /* Ignore it if the checksum's bogus. */
  449. if (ip_compute_csum((unsigned char *)hdr, sizeof(*hdr) + datalen)) {
  450. DEBUGP("icmp_error_track: bad csumn");
  451. return NULL;
  452. }
  453. innerproto = ip_ct_find_proto(inner->protocol);
  454. /* Are they talking about one of our connections? */
  455. if (inner->ihl * 4 + 8 > datalen
  456.     || !get_tuple(inner, datalen, &origtuple, innerproto)) {
  457. DEBUGP("icmp_error: ! get_tuple p=%u (%u*4+%u dlen=%u)n",
  458.        inner->protocol, inner->ihl, 8,
  459.        datalen);
  460. return NULL;
  461. }
  462. /* Ordinarily, we'd expect the inverted tupleproto, but it's
  463.    been preserved inside the ICMP. */
  464. if (!invert_tuple(&innertuple, &origtuple, innerproto)) {
  465. DEBUGP("icmp_error_track: Can't invert tuplen");
  466. return NULL;
  467. }
  468. *ctinfo = IP_CT_RELATED;
  469. h = ip_conntrack_find_get(&innertuple, NULL);
  470. if (!h) {
  471. /* Locally generated ICMPs will match inverted if they
  472.    haven't been SNAT'ed yet */
  473. /* FIXME: NAT code has to handle half-done double NAT --RR */
  474. if (hooknum == NF_IP_LOCAL_OUT)
  475. h = ip_conntrack_find_get(&origtuple, NULL);
  476. if (!h) {
  477. DEBUGP("icmp_error_track: no matchn");
  478. return NULL;
  479. }
  480. /* Reverse direction from that found */
  481. if (DIRECTION(h) != IP_CT_DIR_REPLY)
  482. *ctinfo += IP_CT_IS_REPLY;
  483. } else {
  484. if (DIRECTION(h) == IP_CT_DIR_REPLY)
  485. *ctinfo += IP_CT_IS_REPLY;
  486. }
  487. /* Update skb to refer to this connection */
  488. skb->nfct = &h->ctrack->infos[*ctinfo];
  489. return h->ctrack;
  490. }
  491. /* There's a small race here where we may free a just-assured
  492.    connection.  Too bad: we're in trouble anyway. */
  493. static inline int unreplied(const struct ip_conntrack_tuple_hash *i)
  494. {
  495. return !(i->ctrack->status & IPS_ASSURED);
  496. }
  497. static int early_drop(struct list_head *chain)
  498. {
  499. /* Traverse backwards: gives us oldest, which is roughly LRU */
  500. struct ip_conntrack_tuple_hash *h;
  501. int dropped = 0;
  502. READ_LOCK(&ip_conntrack_lock);
  503. h = LIST_FIND(chain, unreplied, struct ip_conntrack_tuple_hash *);
  504. if (h)
  505. atomic_inc(&h->ctrack->ct_general.use);
  506. READ_UNLOCK(&ip_conntrack_lock);
  507. if (!h)
  508. return dropped;
  509. if (del_timer(&h->ctrack->timeout)) {
  510. death_by_timeout((unsigned long)h->ctrack);
  511. dropped = 1;
  512. }
  513. ip_conntrack_put(h->ctrack);
  514. return dropped;
  515. }
  516. static inline int helper_cmp(const struct ip_conntrack_helper *i,
  517.      const struct ip_conntrack_tuple *rtuple)
  518. {
  519. return ip_ct_tuple_mask_cmp(rtuple, &i->tuple, &i->mask);
  520. }
  521. struct ip_conntrack_helper *ip_ct_find_helper(const struct ip_conntrack_tuple *tuple)
  522. {
  523. return LIST_FIND(&helpers, helper_cmp,
  524.  struct ip_conntrack_helper *,
  525.  tuple);
  526. }
  527. /* Allocate a new conntrack: we return -ENOMEM if classification
  528.    failed due to stress.  Otherwise it really is unclassifiable. */
  529. static struct ip_conntrack_tuple_hash *
  530. init_conntrack(const struct ip_conntrack_tuple *tuple,
  531.        struct ip_conntrack_protocol *protocol,
  532.        struct sk_buff *skb)
  533. {
  534. struct ip_conntrack *conntrack;
  535. struct ip_conntrack_tuple repl_tuple;
  536. size_t hash, repl_hash;
  537. struct ip_conntrack_expect *expected;
  538. int i;
  539. static unsigned int drop_next = 0;
  540. hash = hash_conntrack(tuple);
  541. if (ip_conntrack_max &&
  542.     atomic_read(&ip_conntrack_count) >= ip_conntrack_max) {
  543. /* Try dropping from random chain, or else from the
  544.                    chain about to put into (in case they're trying to
  545.                    bomb one hash chain). */
  546. unsigned int next = (drop_next++)%ip_conntrack_htable_size;
  547. if (!early_drop(&ip_conntrack_hash[next])
  548.     && !early_drop(&ip_conntrack_hash[hash])) {
  549. if (net_ratelimit())
  550. printk(KERN_WARNING
  551.        "ip_conntrack: table full, dropping"
  552.        " packet.n");
  553. return ERR_PTR(-ENOMEM);
  554. }
  555. }
  556. if (!invert_tuple(&repl_tuple, tuple, protocol)) {
  557. DEBUGP("Can't invert tuple.n");
  558. return NULL;
  559. }
  560. repl_hash = hash_conntrack(&repl_tuple);
  561. conntrack = kmem_cache_alloc(ip_conntrack_cachep, GFP_ATOMIC);
  562. if (!conntrack) {
  563. DEBUGP("Can't allocate conntrack.n");
  564. return ERR_PTR(-ENOMEM);
  565. }
  566. memset(conntrack, 0, sizeof(*conntrack));
  567. atomic_set(&conntrack->ct_general.use, 1);
  568. conntrack->ct_general.destroy = destroy_conntrack;
  569. conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *tuple;
  570. conntrack->tuplehash[IP_CT_DIR_ORIGINAL].ctrack = conntrack;
  571. conntrack->tuplehash[IP_CT_DIR_REPLY].tuple = repl_tuple;
  572. conntrack->tuplehash[IP_CT_DIR_REPLY].ctrack = conntrack;
  573. for (i=0; i < IP_CT_NUMBER; i++)
  574. conntrack->infos[i].master = &conntrack->ct_general;
  575. if (!protocol->new(conntrack, skb->nh.iph, skb->len)) {
  576. kmem_cache_free(ip_conntrack_cachep, conntrack);
  577. return NULL;
  578. }
  579. /* Don't set timer yet: wait for confirmation */
  580. init_timer(&conntrack->timeout);
  581. conntrack->timeout.data = (unsigned long)conntrack;
  582. conntrack->timeout.function = death_by_timeout;
  583. INIT_LIST_HEAD(&conntrack->sibling_list);
  584. /* Mark clearly that it's not in the hash table. */
  585. conntrack->tuplehash[IP_CT_DIR_ORIGINAL].list.next = NULL;
  586. WRITE_LOCK(&ip_conntrack_lock);
  587. /* Need finding and deleting of expected ONLY if we win race */
  588. READ_LOCK(&ip_conntrack_expect_tuple_lock);
  589. expected = LIST_FIND(&ip_conntrack_expect_list, expect_cmp,
  590.      struct ip_conntrack_expect *, tuple);
  591. READ_UNLOCK(&ip_conntrack_expect_tuple_lock);
  592. /* Look up the conntrack helper for master connections only */
  593. if (!expected)
  594. conntrack->helper = ip_ct_find_helper(&repl_tuple);
  595. /* If the expectation is dying, then this is a looser. */
  596. if (expected
  597.     && expected->expectant->helper->timeout
  598.     && ! del_timer(&expected->timeout))
  599. expected = NULL;
  600. /* If master is not in hash table yet (ie. packet hasn't left
  601.    this machine yet), how can other end know about expected?
  602.    Hence these are not the droids you are looking for (if
  603.    master ct never got confirmed, we'd hold a reference to it
  604.    and weird things would happen to future packets). */
  605. if (expected && is_confirmed(expected->expectant)) {
  606. DEBUGP("conntrack: expectation arrives ct=%p exp=%pn",
  607. conntrack, expected);
  608. /* Welcome, Mr. Bond.  We've been expecting you... */
  609. IP_NF_ASSERT(master_ct(conntrack));
  610. conntrack->status = IPS_EXPECTED;
  611. conntrack->master = expected;
  612. expected->sibling = conntrack;
  613. LIST_DELETE(&ip_conntrack_expect_list, expected);
  614. expected->expectant->expecting--;
  615. nf_conntrack_get(&master_ct(conntrack)->infos[0]);
  616. }
  617. atomic_inc(&ip_conntrack_count);
  618. WRITE_UNLOCK(&ip_conntrack_lock);
  619. if (expected && expected->expectfn)
  620. expected->expectfn(conntrack);
  621. return &conntrack->tuplehash[IP_CT_DIR_ORIGINAL];
  622. }
  623. /* On success, returns conntrack ptr, sets skb->nfct and ctinfo */
  624. static inline struct ip_conntrack *
  625. resolve_normal_ct(struct sk_buff *skb,
  626.   struct ip_conntrack_protocol *proto,
  627.   int *set_reply,
  628.   unsigned int hooknum,
  629.   enum ip_conntrack_info *ctinfo)
  630. {
  631. struct ip_conntrack_tuple tuple;
  632. struct ip_conntrack_tuple_hash *h;
  633. IP_NF_ASSERT((skb->nh.iph->frag_off & htons(IP_OFFSET)) == 0);
  634. if (!get_tuple(skb->nh.iph, skb->len, &tuple, proto))
  635. return NULL;
  636. /* look for tuple match */
  637. h = ip_conntrack_find_get(&tuple, NULL);
  638. if (!h) {
  639. h = init_conntrack(&tuple, proto, skb);
  640. if (!h)
  641. return NULL;
  642. if (IS_ERR(h))
  643. return (void *)h;
  644. }
  645. /* It exists; we have (non-exclusive) reference. */
  646. if (DIRECTION(h) == IP_CT_DIR_REPLY) {
  647. *ctinfo = IP_CT_ESTABLISHED + IP_CT_IS_REPLY;
  648. /* Please set reply bit if this packet OK */
  649. *set_reply = 1;
  650. } else {
  651. /* Once we've had two way comms, always ESTABLISHED. */
  652. if (h->ctrack->status & IPS_SEEN_REPLY) {
  653. DEBUGP("ip_conntrack_in: normal packet for %pn",
  654.        h->ctrack);
  655.         *ctinfo = IP_CT_ESTABLISHED;
  656. } else if (h->ctrack->status & IPS_EXPECTED) {
  657. DEBUGP("ip_conntrack_in: related packet for %pn",
  658.        h->ctrack);
  659. *ctinfo = IP_CT_RELATED;
  660. } else {
  661. DEBUGP("ip_conntrack_in: new packet for %pn",
  662.        h->ctrack);
  663. *ctinfo = IP_CT_NEW;
  664. }
  665. *set_reply = 0;
  666. }
  667. skb->nfct = &h->ctrack->infos[*ctinfo];
  668. return h->ctrack;
  669. }
  670. /* Netfilter hook itself. */
  671. unsigned int ip_conntrack_in(unsigned int hooknum,
  672.      struct sk_buff **pskb,
  673.      const struct net_device *in,
  674.      const struct net_device *out,
  675.      int (*okfn)(struct sk_buff *))
  676. {
  677. struct ip_conntrack *ct;
  678. enum ip_conntrack_info ctinfo;
  679. struct ip_conntrack_protocol *proto;
  680. int set_reply;
  681. int ret;
  682. /* FIXME: Do this right please. --RR */
  683. (*pskb)->nfcache |= NFC_UNKNOWN;
  684. /* Doesn't cover locally-generated broadcast, so not worth it. */
  685. #if 0
  686. /* Ignore broadcast: no `connection'. */
  687. if ((*pskb)->pkt_type == PACKET_BROADCAST) {
  688. printk("Broadcast packet!n");
  689. return NF_ACCEPT;
  690. } else if (((*pskb)->nh.iph->daddr & htonl(0x000000FF)) 
  691.    == htonl(0x000000FF)) {
  692. printk("Should bcast: %u.%u.%u.%u->%u.%u.%u.%u (sk=%p, ptype=%u)n",
  693.        NIPQUAD((*pskb)->nh.iph->saddr),
  694.        NIPQUAD((*pskb)->nh.iph->daddr),
  695.        (*pskb)->sk, (*pskb)->pkt_type);
  696. }
  697. #endif
  698. /* Previously seen (loopback)?  Ignore.  Do this before
  699.            fragment check. */
  700. if ((*pskb)->nfct)
  701. return NF_ACCEPT;
  702. /* Gather fragments. */
  703. if ((*pskb)->nh.iph->frag_off & htons(IP_MF|IP_OFFSET)) {
  704. *pskb = ip_ct_gather_frags(*pskb);
  705. if (!*pskb)
  706. return NF_STOLEN;
  707. }
  708. proto = ip_ct_find_proto((*pskb)->nh.iph->protocol);
  709. /* It may be an icmp error... */
  710. if ((*pskb)->nh.iph->protocol == IPPROTO_ICMP 
  711.     && icmp_error_track(*pskb, &ctinfo, hooknum))
  712. return NF_ACCEPT;
  713. if (!(ct = resolve_normal_ct(*pskb, proto,&set_reply,hooknum,&ctinfo)))
  714. /* Not valid part of a connection */
  715. return NF_ACCEPT;
  716. if (IS_ERR(ct))
  717. /* Too stressed to deal. */
  718. return NF_DROP;
  719. IP_NF_ASSERT((*pskb)->nfct);
  720. ret = proto->packet(ct, (*pskb)->nh.iph, (*pskb)->len, ctinfo);
  721. if (ret == -1) {
  722. /* Invalid */
  723. nf_conntrack_put((*pskb)->nfct);
  724. (*pskb)->nfct = NULL;
  725. return NF_ACCEPT;
  726. }
  727. if (ret != NF_DROP && ct->helper) {
  728. ret = ct->helper->help((*pskb)->nh.iph, (*pskb)->len,
  729.        ct, ctinfo);
  730. if (ret == -1) {
  731. /* Invalid */
  732. nf_conntrack_put((*pskb)->nfct);
  733. (*pskb)->nfct = NULL;
  734. return NF_ACCEPT;
  735. }
  736. }
  737. if (set_reply)
  738. set_bit(IPS_SEEN_REPLY_BIT, &ct->status);
  739. return ret;
  740. }
  741. int invert_tuplepr(struct ip_conntrack_tuple *inverse,
  742.    const struct ip_conntrack_tuple *orig)
  743. {
  744. return invert_tuple(inverse, orig, ip_ct_find_proto(orig->dst.protonum));
  745. }
  746. static inline int resent_expect(const struct ip_conntrack_expect *i,
  747.         const struct ip_conntrack_tuple *tuple,
  748.         const struct ip_conntrack_tuple *mask)
  749. {
  750. DEBUGP("resent_expectn");
  751. DEBUGP("   tuple:   "); DUMP_TUPLE(&i->tuple);
  752. DEBUGP("ct_tuple:   "); DUMP_TUPLE(&i->ct_tuple);
  753. DEBUGP("test tuple: "); DUMP_TUPLE(tuple);
  754. return (((i->ct_tuple.dst.protonum == 0 && ip_ct_tuple_equal(&i->tuple, tuple))
  755.          || (i->ct_tuple.dst.protonum && ip_ct_tuple_equal(&i->ct_tuple, tuple)))
  756. && ip_ct_tuple_equal(&i->mask, mask));
  757. }
  758. /* Would two expected things clash? */
  759. static inline int expect_clash(const struct ip_conntrack_expect *i,
  760.        const struct ip_conntrack_tuple *tuple,
  761.        const struct ip_conntrack_tuple *mask)
  762. {
  763. /* Part covered by intersection of masks must be unequal,
  764.            otherwise they clash */
  765. struct ip_conntrack_tuple intersect_mask
  766. = { { i->mask.src.ip & mask->src.ip,
  767.       { i->mask.src.u.all & mask->src.u.all } },
  768.     { i->mask.dst.ip & mask->dst.ip,
  769.       { i->mask.dst.u.all & mask->dst.u.all },
  770.       i->mask.dst.protonum & mask->dst.protonum } };
  771. return ip_ct_tuple_mask_cmp(&i->tuple, tuple, &intersect_mask);
  772. }
  773. inline void ip_conntrack_unexpect_related(struct ip_conntrack_expect *expect)
  774. {
  775. WRITE_LOCK(&ip_conntrack_lock);
  776. unexpect_related(expect);
  777. WRITE_UNLOCK(&ip_conntrack_lock);
  778. }
  779. static void expectation_timed_out(unsigned long ul_expect)
  780. {
  781. struct ip_conntrack_expect *expect = (void *) ul_expect;
  782. DEBUGP("expectation %p timed outn", expect);
  783. WRITE_LOCK(&ip_conntrack_lock);
  784. __unexpect_related(expect);
  785. WRITE_UNLOCK(&ip_conntrack_lock);
  786. }
  787. /* Add a related connection. */
  788. int ip_conntrack_expect_related(struct ip_conntrack *related_to,
  789. struct ip_conntrack_expect *expect)
  790. {
  791. struct ip_conntrack_expect *old, *new;
  792. int ret = 0;
  793. WRITE_LOCK(&ip_conntrack_lock);
  794. /* Because of the write lock, no reader can walk the lists,
  795.  * so there is no need to use the tuple lock too */
  796. DEBUGP("ip_conntrack_expect_related %pn", related_to);
  797. DEBUGP("tuple: "); DUMP_TUPLE(&expect->tuple);
  798. DEBUGP("mask:  "); DUMP_TUPLE(&expect->mask);
  799. old = LIST_FIND(&ip_conntrack_expect_list, resent_expect,
  800.         struct ip_conntrack_expect *, &expect->tuple, 
  801. &expect->mask);
  802. if (old) {
  803. /* Helper private data may contain offsets but no pointers
  804.    pointing into the payload - otherwise we should have to copy 
  805.    the data filled out by the helper over the old one */
  806. DEBUGP("expect_related: resent packetn");
  807. if (related_to->helper->timeout) {
  808. if (!del_timer(&old->timeout)) {
  809. /* expectation is dying. Fall through */
  810. old = NULL;
  811. } else {
  812. old->timeout.expires = jiffies + 
  813. related_to->helper->timeout * HZ;
  814. add_timer(&old->timeout);
  815. }
  816. }
  817. if (old) {
  818. WRITE_UNLOCK(&ip_conntrack_lock);
  819. return -EEXIST;
  820. }
  821. } else if (related_to->helper->max_expected && 
  822.    related_to->expecting >= related_to->helper->max_expected) {
  823. struct list_head *cur_item;
  824. /* old == NULL */
  825.      if (net_ratelimit())
  826.      printk(KERN_WARNING 
  827.             "ip_conntrack: max number of expected "
  828.        "connections %i of %s reached for "
  829.        "%u.%u.%u.%u->%u.%u.%u.%u%sn",
  830.             related_to->helper->max_expected, 
  831.             related_to->helper->name,
  832.             NIPQUAD(related_to->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.ip),
  833.             NIPQUAD(related_to->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.ip),
  834.             related_to->helper->flags & IP_CT_HELPER_F_REUSE_EXPECT ?
  835.             ", reusing" : "");
  836. if (!(related_to->helper->flags & 
  837.       IP_CT_HELPER_F_REUSE_EXPECT)) {
  838. WRITE_UNLOCK(&ip_conntrack_lock);
  839. return -EPERM;
  840. }
  841. /* choose the the oldest expectation to evict */
  842. list_for_each(cur_item, &related_to->sibling_list) { 
  843. struct ip_conntrack_expect *cur;
  844. cur = list_entry(cur_item, 
  845.  struct ip_conntrack_expect,
  846.  expected_list);
  847. if (cur->sibling == NULL) {
  848. old = cur;
  849. break;
  850. }
  851. }
  852. /* (!old) cannot happen, since related_to->expecting is the
  853.  * number of unconfirmed expects */
  854. IP_NF_ASSERT(old);
  855. /* newnat14 does not reuse the real allocated memory
  856.  * structures but rather unexpects the old and
  857.  * allocates a new.  unexpect_related will decrement
  858.  * related_to->expecting. 
  859.  */
  860. unexpect_related(old);
  861. ret = -EPERM;
  862. } else if (LIST_FIND(&ip_conntrack_expect_list, expect_clash,
  863.      struct ip_conntrack_expect *, &expect->tuple, 
  864.      &expect->mask)) {
  865. WRITE_UNLOCK(&ip_conntrack_lock);
  866. DEBUGP("expect_related: busy!n");
  867. return -EBUSY;
  868. }
  869. new = (struct ip_conntrack_expect *) 
  870.       kmalloc(sizeof(struct ip_conntrack_expect), GFP_ATOMIC);
  871. if (!new) {
  872. WRITE_UNLOCK(&ip_conntrack_lock);
  873. DEBUGP("expect_relaed: OOM allocating expectn");
  874. return -ENOMEM;
  875. }
  876. /* Zero out the new structure, then fill out it with the data */
  877. DEBUGP("new expectation %p of conntrack %pn", new, related_to);
  878. memset(new, 0, sizeof(*expect));
  879. INIT_LIST_HEAD(&new->list);
  880. INIT_LIST_HEAD(&new->expected_list);
  881. memcpy(new, expect, sizeof(*expect));
  882. new->expectant = related_to;
  883. new->sibling = NULL;
  884. /* increase usage count. This sucks. The memset above overwrites
  885.  * old usage count [if still present] and we increase to one.  Only
  886.  * works because everything is done under ip_conntrack_lock() */
  887. atomic_inc(&new->use);
  888. /* add to expected list for this connection */
  889. list_add(&new->expected_list, &related_to->sibling_list);
  890. /* add to global list of expectations */
  891. list_prepend(&ip_conntrack_expect_list, &new->list);
  892. /* add and start timer if required */
  893. if (related_to->helper->timeout) {
  894. init_timer(&new->timeout);
  895. new->timeout.data = (unsigned long)new;
  896. new->timeout.function = expectation_timed_out;
  897. new->timeout.expires = jiffies + 
  898. related_to->helper->timeout * HZ;
  899. add_timer(&new->timeout);
  900. }
  901. related_to->expecting++;
  902. WRITE_UNLOCK(&ip_conntrack_lock);
  903. return ret;
  904. }
  905. /* Change tuple in an existing expectation */
  906. int ip_conntrack_change_expect(struct ip_conntrack_expect *expect,
  907.        struct ip_conntrack_tuple *newtuple)
  908. {
  909. int ret;
  910. MUST_BE_READ_LOCKED(&ip_conntrack_lock);
  911. WRITE_LOCK(&ip_conntrack_expect_tuple_lock);
  912. DEBUGP("change_expect:n");
  913. DEBUGP("exp tuple: "); DUMP_TUPLE(&expect->tuple);
  914. DEBUGP("exp mask:  "); DUMP_TUPLE(&expect->mask);
  915. DEBUGP("newtuple:  "); DUMP_TUPLE(newtuple);
  916. if (expect->ct_tuple.dst.protonum == 0) {
  917. /* Never seen before */
  918. DEBUGP("change expect: never seen beforen");
  919. if (!ip_ct_tuple_equal(&expect->tuple, newtuple) 
  920.     && LIST_FIND(&ip_conntrack_expect_list, expect_clash,
  921.          struct ip_conntrack_expect *, newtuple, &expect->mask)) {
  922. /* Force NAT to find an unused tuple */
  923. ret = -1;
  924. } else {
  925. memcpy(&expect->ct_tuple, &expect->tuple, sizeof(expect->tuple));
  926. memcpy(&expect->tuple, newtuple, sizeof(expect->tuple));
  927. ret = 0;
  928. }
  929. } else {
  930. /* Resent packet */
  931. DEBUGP("change expect: resent packetn");
  932. if (ip_ct_tuple_equal(&expect->tuple, newtuple)) {
  933. ret = 0;
  934. } else {
  935. /* Force NAT to choose again the same port */
  936. ret = -1;
  937. }
  938. }
  939. WRITE_UNLOCK(&ip_conntrack_expect_tuple_lock);
  940. return ret;
  941. }
  942. /* Alter reply tuple (maybe alter helper).  If it's already taken,
  943.    return 0 and don't do alteration. */
  944. int ip_conntrack_alter_reply(struct ip_conntrack *conntrack,
  945.      const struct ip_conntrack_tuple *newreply)
  946. {
  947. WRITE_LOCK(&ip_conntrack_lock);
  948. if (__ip_conntrack_find(newreply, conntrack)) {
  949. WRITE_UNLOCK(&ip_conntrack_lock);
  950. return 0;
  951. }
  952. /* Should be unconfirmed, so not in hash table yet */
  953. IP_NF_ASSERT(!is_confirmed(conntrack));
  954. DEBUGP("Altering reply tuple of %p to ", conntrack);
  955. DUMP_TUPLE(newreply);
  956. conntrack->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
  957. if (!conntrack->master)
  958. conntrack->helper = LIST_FIND(&helpers, helper_cmp,
  959.       struct ip_conntrack_helper *,
  960.       newreply);
  961. WRITE_UNLOCK(&ip_conntrack_lock);
  962. return 1;
  963. }
  964. int ip_conntrack_helper_register(struct ip_conntrack_helper *me)
  965. {
  966. MOD_INC_USE_COUNT;
  967. WRITE_LOCK(&ip_conntrack_lock);
  968. list_prepend(&helpers, me);
  969. WRITE_UNLOCK(&ip_conntrack_lock);
  970. return 0;
  971. }
  972. static inline int unhelp(struct ip_conntrack_tuple_hash *i,
  973.  const struct ip_conntrack_helper *me)
  974. {
  975. if (i->ctrack->helper == me) {
  976. /* Get rid of any expected. */
  977. remove_expectations(i->ctrack);
  978. /* And *then* set helper to NULL */
  979. i->ctrack->helper = NULL;
  980. }
  981. return 0;
  982. }
  983. void ip_conntrack_helper_unregister(struct ip_conntrack_helper *me)
  984. {
  985. unsigned int i;
  986. /* Need write lock here, to delete helper. */
  987. WRITE_LOCK(&ip_conntrack_lock);
  988. LIST_DELETE(&helpers, me);
  989. /* Get rid of expecteds, set helpers to NULL. */
  990. for (i = 0; i < ip_conntrack_htable_size; i++)
  991. LIST_FIND_W(&ip_conntrack_hash[i], unhelp,
  992.     struct ip_conntrack_tuple_hash *, me);
  993. WRITE_UNLOCK(&ip_conntrack_lock);
  994. /* Someone could be still looking at the helper in a bh. */
  995. br_write_lock_bh(BR_NETPROTO_LOCK);
  996. br_write_unlock_bh(BR_NETPROTO_LOCK);
  997. MOD_DEC_USE_COUNT;
  998. }
  999. /* Refresh conntrack for this many jiffies. */
  1000. void ip_ct_refresh(struct ip_conntrack *ct, unsigned long extra_jiffies)
  1001. {
  1002. IP_NF_ASSERT(ct->timeout.data == (unsigned long)ct);
  1003. WRITE_LOCK(&ip_conntrack_lock);
  1004. /* If not in hash table, timer will not be active yet */
  1005. if (!is_confirmed(ct))
  1006. ct->timeout.expires = extra_jiffies;
  1007. else {
  1008. /* Need del_timer for race avoidance (may already be dying). */
  1009. if (del_timer(&ct->timeout)) {
  1010. ct->timeout.expires = jiffies + extra_jiffies;
  1011. add_timer(&ct->timeout);
  1012. }
  1013. }
  1014. WRITE_UNLOCK(&ip_conntrack_lock);
  1015. }
  1016. /* Returns new sk_buff, or NULL */
  1017. struct sk_buff *
  1018. ip_ct_gather_frags(struct sk_buff *skb)
  1019. {
  1020. struct sock *sk = skb->sk;
  1021. #ifdef CONFIG_NETFILTER_DEBUG
  1022. unsigned int olddebug = skb->nf_debug;
  1023. #endif
  1024. if (sk) {
  1025. sock_hold(sk);
  1026. skb_orphan(skb);
  1027. }
  1028. local_bh_disable(); 
  1029. skb = ip_defrag(skb);
  1030. local_bh_enable();
  1031. if (!skb) {
  1032. if (sk) sock_put(sk);
  1033. return skb;
  1034. } else if (skb_is_nonlinear(skb) && skb_linearize(skb, GFP_ATOMIC) != 0) {
  1035. kfree_skb(skb);
  1036. if (sk) sock_put(sk);
  1037. return NULL;
  1038. }
  1039. if (sk) {
  1040. skb_set_owner_w(skb, sk);
  1041. sock_put(sk);
  1042. }
  1043. ip_send_check(skb->nh.iph);
  1044. skb->nfcache |= NFC_ALTERED;
  1045. #ifdef CONFIG_NETFILTER_DEBUG
  1046. /* Packet path as if nothing had happened. */
  1047. skb->nf_debug = olddebug;
  1048. #endif
  1049. return skb;
  1050. }
  1051. /* Used by ipt_REJECT. */
  1052. static void ip_conntrack_attach(struct sk_buff *nskb, struct nf_ct_info *nfct)
  1053. {
  1054. struct ip_conntrack *ct;
  1055. enum ip_conntrack_info ctinfo;
  1056. ct = __ip_conntrack_get(nfct, &ctinfo);
  1057. /* This ICMP is in reverse direction to the packet which
  1058.            caused it */
  1059. if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
  1060. ctinfo = IP_CT_RELATED + IP_CT_IS_REPLY;
  1061. else
  1062. ctinfo = IP_CT_RELATED;
  1063. /* Attach new skbuff, and increment count */
  1064. nskb->nfct = &ct->infos[ctinfo];
  1065. atomic_inc(&ct->ct_general.use);
  1066. }
  1067. static inline int
  1068. do_kill(const struct ip_conntrack_tuple_hash *i,
  1069. int (*kill)(const struct ip_conntrack *i, void *data),
  1070. void *data)
  1071. {
  1072. return kill(i->ctrack, data);
  1073. }
  1074. /* Bring out ya dead! */
  1075. static struct ip_conntrack_tuple_hash *
  1076. get_next_corpse(int (*kill)(const struct ip_conntrack *i, void *data),
  1077. void *data)
  1078. {
  1079. struct ip_conntrack_tuple_hash *h = NULL;
  1080. unsigned int i;
  1081. READ_LOCK(&ip_conntrack_lock);
  1082. for (i = 0; !h && i < ip_conntrack_htable_size; i++) {
  1083. h = LIST_FIND(&ip_conntrack_hash[i], do_kill,
  1084.       struct ip_conntrack_tuple_hash *, kill, data);
  1085. }
  1086. if (h)
  1087. atomic_inc(&h->ctrack->ct_general.use);
  1088. READ_UNLOCK(&ip_conntrack_lock);
  1089. return h;
  1090. }
  1091. void
  1092. ip_ct_selective_cleanup(int (*kill)(const struct ip_conntrack *i, void *data),
  1093. void *data)
  1094. {
  1095. struct ip_conntrack_tuple_hash *h;
  1096. /* This is order n^2, by the way. */
  1097. while ((h = get_next_corpse(kill, data)) != NULL) {
  1098. /* Time to push up daises... */
  1099. if (del_timer(&h->ctrack->timeout))
  1100. death_by_timeout((unsigned long)h->ctrack);
  1101. /* ... else the timer will get him soon. */
  1102. ip_conntrack_put(h->ctrack);
  1103. }
  1104. }
  1105. /* Fast function for those who don't want to parse /proc (and I don't
  1106.    blame them). */
  1107. /* Reversing the socket's dst/src point of view gives us the reply
  1108.    mapping. */
  1109. static int
  1110. getorigdst(struct sock *sk, int optval, void *user, int *len)
  1111. {
  1112. struct ip_conntrack_tuple_hash *h;
  1113. struct ip_conntrack_tuple tuple = { { sk->rcv_saddr, { sk->sport } },
  1114.     { sk->daddr, { sk->dport },
  1115.       IPPROTO_TCP } };
  1116. /* We only do TCP at the moment: is there a better way? */
  1117. if (strcmp(sk->prot->name, "TCP") != 0) {
  1118. DEBUGP("SO_ORIGINAL_DST: Not a TCP socketn");
  1119. return -ENOPROTOOPT;
  1120. }
  1121. if ((unsigned int) *len < sizeof(struct sockaddr_in)) {
  1122. DEBUGP("SO_ORIGINAL_DST: len %u not %un",
  1123.        *len, sizeof(struct sockaddr_in));
  1124. return -EINVAL;
  1125. }
  1126. h = ip_conntrack_find_get(&tuple, NULL);
  1127. if (h) {
  1128. struct sockaddr_in sin;
  1129. sin.sin_family = AF_INET;
  1130. sin.sin_port = h->ctrack->tuplehash[IP_CT_DIR_ORIGINAL]
  1131. .tuple.dst.u.tcp.port;
  1132. sin.sin_addr.s_addr = h->ctrack->tuplehash[IP_CT_DIR_ORIGINAL]
  1133. .tuple.dst.ip;
  1134. DEBUGP("SO_ORIGINAL_DST: %u.%u.%u.%u %un",
  1135.        NIPQUAD(sin.sin_addr.s_addr), ntohs(sin.sin_port));
  1136. ip_conntrack_put(h->ctrack);
  1137. if (copy_to_user(user, &sin, sizeof(sin)) != 0)
  1138. return -EFAULT;
  1139. else
  1140. return 0;
  1141. }
  1142. DEBUGP("SO_ORIGINAL_DST: Can't find %u.%u.%u.%u/%u-%u.%u.%u.%u/%u.n",
  1143.        NIPQUAD(tuple.src.ip), ntohs(tuple.src.u.tcp.port),
  1144.        NIPQUAD(tuple.dst.ip), ntohs(tuple.dst.u.tcp.port));
  1145. return -ENOENT;
  1146. }
  1147. static struct nf_sockopt_ops so_getorigdst
  1148. = { { NULL, NULL }, PF_INET,
  1149.     0, 0, NULL, /* Setsockopts */
  1150.     SO_ORIGINAL_DST, SO_ORIGINAL_DST+1, &getorigdst,
  1151.     0, NULL };
  1152. #define NET_IP_CONNTRACK_MAX 2089
  1153. #define NET_IP_CONNTRACK_MAX_NAME "ip_conntrack_max"
  1154. #ifdef CONFIG_SYSCTL
  1155. static struct ctl_table_header *ip_conntrack_sysctl_header;
  1156. static ctl_table ip_conntrack_table[] = {
  1157. { NET_IP_CONNTRACK_MAX, NET_IP_CONNTRACK_MAX_NAME, &ip_conntrack_max,
  1158.   sizeof(ip_conntrack_max), 0644,  NULL, proc_dointvec },
  1159.   { 0 }
  1160. };
  1161. static ctl_table ip_conntrack_dir_table[] = {
  1162. {NET_IPV4, "ipv4", NULL, 0, 0555, ip_conntrack_table, 0, 0, 0, 0, 0},
  1163. { 0 }
  1164. };
  1165. static ctl_table ip_conntrack_root_table[] = {
  1166. {CTL_NET, "net", NULL, 0, 0555, ip_conntrack_dir_table, 0, 0, 0, 0, 0},
  1167. { 0 }
  1168. };
  1169. #endif /*CONFIG_SYSCTL*/
  1170. static int kill_all(const struct ip_conntrack *i, void *data)
  1171. {
  1172. return 1;
  1173. }
  1174. /* Mishearing the voices in his head, our hero wonders how he's
  1175.    supposed to kill the mall. */
  1176. void ip_conntrack_cleanup(void)
  1177. {
  1178. #ifdef CONFIG_SYSCTL
  1179. unregister_sysctl_table(ip_conntrack_sysctl_header);
  1180. #endif
  1181. ip_ct_attach = NULL;
  1182. /* This makes sure all current packets have passed through
  1183.            netfilter framework.  Roll on, two-stage module
  1184.            delete... */
  1185. br_write_lock_bh(BR_NETPROTO_LOCK);
  1186. br_write_unlock_bh(BR_NETPROTO_LOCK);
  1187.  
  1188.  i_see_dead_people:
  1189. ip_ct_selective_cleanup(kill_all, NULL);
  1190. if (atomic_read(&ip_conntrack_count) != 0) {
  1191. schedule();
  1192. goto i_see_dead_people;
  1193. }
  1194. kmem_cache_destroy(ip_conntrack_cachep);
  1195. vfree(ip_conntrack_hash);
  1196. nf_unregister_sockopt(&so_getorigdst);
  1197. }
  1198. static int hashsize = 0;
  1199. MODULE_PARM(hashsize, "i");
  1200. int __init ip_conntrack_init(void)
  1201. {
  1202. unsigned int i;
  1203. int ret;
  1204. /* Idea from tcp.c: use 1/16384 of memory.  On i386: 32MB
  1205.  * machine has 256 buckets.  >= 1GB machines have 8192 buckets. */
  1206.   if (hashsize) {
  1207.   ip_conntrack_htable_size = hashsize;
  1208.   } else {
  1209. ip_conntrack_htable_size
  1210. = (((num_physpages << PAGE_SHIFT) / 16384)
  1211.    / sizeof(struct list_head));
  1212. if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
  1213. ip_conntrack_htable_size = 8192;
  1214. if (ip_conntrack_htable_size < 16)
  1215. ip_conntrack_htable_size = 16;
  1216. }
  1217. ip_conntrack_max = 8 * ip_conntrack_htable_size;
  1218. printk("ip_conntrack version %s (%u buckets, %d max)"
  1219.        " - %d bytes per conntrackn", IP_CONNTRACK_VERSION,
  1220.        ip_conntrack_htable_size, ip_conntrack_max,
  1221.        sizeof(struct ip_conntrack));
  1222. ret = nf_register_sockopt(&so_getorigdst);
  1223. if (ret != 0) {
  1224. printk(KERN_ERR "Unable to register netfilter socket optionn");
  1225. return ret;
  1226. }
  1227. ip_conntrack_hash = vmalloc(sizeof(struct list_head)
  1228.     * ip_conntrack_htable_size);
  1229. if (!ip_conntrack_hash) {
  1230. printk(KERN_ERR "Unable to create ip_conntrack_hashn");
  1231. goto err_unreg_sockopt;
  1232. }
  1233. ip_conntrack_cachep = kmem_cache_create("ip_conntrack",
  1234.                                         sizeof(struct ip_conntrack), 0,
  1235.                                         SLAB_HWCACHE_ALIGN, NULL, NULL);
  1236. if (!ip_conntrack_cachep) {
  1237. printk(KERN_ERR "Unable to create ip_conntrack slab cachen");
  1238. goto err_free_hash;
  1239. }
  1240. /* Don't NEED lock here, but good form anyway. */
  1241. WRITE_LOCK(&ip_conntrack_lock);
  1242. /* Sew in builtin protocols. */
  1243. list_append(&protocol_list, &ip_conntrack_protocol_tcp);
  1244. list_append(&protocol_list, &ip_conntrack_protocol_udp);
  1245. list_append(&protocol_list, &ip_conntrack_protocol_icmp);
  1246. WRITE_UNLOCK(&ip_conntrack_lock);
  1247. for (i = 0; i < ip_conntrack_htable_size; i++)
  1248. INIT_LIST_HEAD(&ip_conntrack_hash[i]);
  1249. /* This is fucking braindead.  There is NO WAY of doing this without
  1250.    the CONFIG_SYSCTL unless you don't want to detect errors.
  1251.    Grrr... --RR */
  1252. #ifdef CONFIG_SYSCTL
  1253. ip_conntrack_sysctl_header
  1254. = register_sysctl_table(ip_conntrack_root_table, 0);
  1255. if (ip_conntrack_sysctl_header == NULL) {
  1256. goto err_free_ct_cachep;
  1257. }
  1258. #endif /*CONFIG_SYSCTL*/
  1259. /* For use by ipt_REJECT */
  1260. ip_ct_attach = ip_conntrack_attach;
  1261. return ret;
  1262. err_free_ct_cachep:
  1263. kmem_cache_destroy(ip_conntrack_cachep);
  1264. err_free_hash:
  1265. vfree(ip_conntrack_hash);
  1266. err_unreg_sockopt:
  1267. nf_unregister_sockopt(&so_getorigdst);
  1268. return -ENOMEM;
  1269. }