patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / net / ipv4 / ip_fragment.c
1 /*
2  * INET         An implementation of the TCP/IP protocol suite for the LINUX
3  *              operating system.  INET is implemented using the  BSD Socket
4  *              interface as the means of communication with the user level.
5  *
6  *              The IP fragmentation functionality.
7  *              
8  * Version:     $Id: ip_fragment.c,v 1.59 2002/01/12 07:54:56 davem Exp $
9  *
10  * Authors:     Fred N. van Kempen <waltje@uWalt.NL.Mugnet.ORG>
11  *              Alan Cox <Alan.Cox@linux.org>
12  *
13  * Fixes:
14  *              Alan Cox        :       Split from ip.c , see ip_input.c for history.
15  *              David S. Miller :       Begin massive cleanup...
16  *              Andi Kleen      :       Add sysctls.
17  *              xxxx            :       Overlapfrag bug.
18  *              Ultima          :       ip_expire() kernel panic.
19  *              Bill Hawes      :       Frag accounting and evictor fixes.
20  *              John McDonald   :       0 length frag bug.
21  *              Alexey Kuznetsov:       SMP races, threading, cleanup.
22  *              Patrick McHardy :       LRU queue of frag heads for evictor.
23  */
24
25 #include <linux/config.h>
26 #include <linux/module.h>
27 #include <linux/types.h>
28 #include <linux/mm.h>
29 #include <linux/jiffies.h>
30 #include <linux/skbuff.h>
31 #include <linux/list.h>
32 #include <linux/ip.h>
33 #include <linux/icmp.h>
34 #include <linux/netdevice.h>
35 #include <linux/jhash.h>
36 #include <linux/random.h>
37 #include <net/sock.h>
38 #include <net/ip.h>
39 #include <net/icmp.h>
40 #include <net/checksum.h>
41 #include <linux/tcp.h>
42 #include <linux/udp.h>
43 #include <linux/inet.h>
44 #include <linux/netfilter_ipv4.h>
45
46 /* NOTE. Logic of IP defragmentation is parallel to corresponding IPv6
47  * code now. If you change something here, _PLEASE_ update ipv6/reassembly.c
48  * as well. Or notify me, at least. --ANK
49  */
50
51 /* Fragment cache limits. We will commit 256K at one time. Should we
52  * cross that limit we will prune down to 192K. This should cope with
53  * even the most extreme cases without allowing an attacker to measurably
54  * harm machine performance.
55  */
56 int sysctl_ipfrag_high_thresh = 256*1024;
57 int sysctl_ipfrag_low_thresh = 192*1024;
58
59 /* Important NOTE! Fragment queue must be destroyed before MSL expires.
60  * RFC791 is wrong proposing to prolongate timer each fragment arrival by TTL.
61  */
62 int sysctl_ipfrag_time = IP_FRAG_TIME;
63
64 struct ipfrag_skb_cb
65 {
66         struct inet_skb_parm    h;
67         int                     offset;
68 };
69
70 #define FRAG_CB(skb)    ((struct ipfrag_skb_cb*)((skb)->cb))
71
72 /* Describe an entry in the "incomplete datagrams" queue. */
73 struct ipq {
74         struct ipq      *next;          /* linked list pointers                 */
75         struct list_head lru_list;      /* lru list member                      */
76         u32             saddr;
77         u32             daddr;
78         u16             id;
79         u8              protocol;
80         u8              last_in;
81 #define COMPLETE                4
82 #define FIRST_IN                2
83 #define LAST_IN                 1
84
85         struct sk_buff  *fragments;     /* linked list of received fragments    */
86         int             len;            /* total length of original datagram    */
87         int             meat;
88         spinlock_t      lock;
89         atomic_t        refcnt;
90         struct timer_list timer;        /* when will this queue expire?         */
91         struct ipq      **pprev;
92         int             iif;
93         struct timeval  stamp;
94 };
95
96 /* Hash table. */
97
98 #define IPQ_HASHSZ      64
99
100 /* Per-bucket lock is easy to add now. */
101 static struct ipq *ipq_hash[IPQ_HASHSZ];
102 static rwlock_t ipfrag_lock = RW_LOCK_UNLOCKED;
103 static u32 ipfrag_hash_rnd;
104 static LIST_HEAD(ipq_lru_list);
105 int ip_frag_nqueues = 0;
106
107 static __inline__ void __ipq_unlink(struct ipq *qp)
108 {
109         if(qp->next)
110                 qp->next->pprev = qp->pprev;
111         *qp->pprev = qp->next;
112         list_del(&qp->lru_list);
113         ip_frag_nqueues--;
114 }
115
116 static __inline__ void ipq_unlink(struct ipq *ipq)
117 {
118         write_lock(&ipfrag_lock);
119         __ipq_unlink(ipq);
120         write_unlock(&ipfrag_lock);
121 }
122
123 static unsigned int ipqhashfn(u16 id, u32 saddr, u32 daddr, u8 prot)
124 {
125         return jhash_3words((u32)id << 16 | prot, saddr, daddr,
126                             ipfrag_hash_rnd) & (IPQ_HASHSZ - 1);
127 }
128
129 static struct timer_list ipfrag_secret_timer;
130 int sysctl_ipfrag_secret_interval = 10 * 60 * HZ;
131
132 static void ipfrag_secret_rebuild(unsigned long dummy)
133 {
134         unsigned long now = jiffies;
135         int i;
136
137         write_lock(&ipfrag_lock);
138         get_random_bytes(&ipfrag_hash_rnd, sizeof(u32));
139         for (i = 0; i < IPQ_HASHSZ; i++) {
140                 struct ipq *q;
141
142                 q = ipq_hash[i];
143                 while (q) {
144                         struct ipq *next = q->next;
145                         unsigned int hval = ipqhashfn(q->id, q->saddr,
146                                                       q->daddr, q->protocol);
147
148                         if (hval != i) {
149                                 /* Unlink. */
150                                 if (q->next)
151                                         q->next->pprev = q->pprev;
152                                 *q->pprev = q->next;
153
154                                 /* Relink to new hash chain. */
155                                 if ((q->next = ipq_hash[hval]) != NULL)
156                                         q->next->pprev = &q->next;
157                                 ipq_hash[hval] = q;
158                                 q->pprev = &ipq_hash[hval];
159                         }
160
161                         q = next;
162                 }
163         }
164         write_unlock(&ipfrag_lock);
165
166         mod_timer(&ipfrag_secret_timer, now + sysctl_ipfrag_secret_interval);
167 }
168
169 atomic_t ip_frag_mem = ATOMIC_INIT(0);  /* Memory used for fragments */
170
171 /* Memory Tracking Functions. */
172 static __inline__ void frag_kfree_skb(struct sk_buff *skb)
173 {
174         atomic_sub(skb->truesize, &ip_frag_mem);
175         kfree_skb(skb);
176 }
177
178 static __inline__ void frag_free_queue(struct ipq *qp)
179 {
180         atomic_sub(sizeof(struct ipq), &ip_frag_mem);
181         kfree(qp);
182 }
183
184 static __inline__ struct ipq *frag_alloc_queue(void)
185 {
186         struct ipq *qp = kmalloc(sizeof(struct ipq), GFP_ATOMIC);
187
188         if(!qp)
189                 return NULL;
190         atomic_add(sizeof(struct ipq), &ip_frag_mem);
191         return qp;
192 }
193
194
195 /* Destruction primitives. */
196
197 /* Complete destruction of ipq. */
198 static void ip_frag_destroy(struct ipq *qp)
199 {
200         struct sk_buff *fp;
201
202         BUG_TRAP(qp->last_in&COMPLETE);
203         BUG_TRAP(del_timer(&qp->timer) == 0);
204
205         /* Release all fragment data. */
206         fp = qp->fragments;
207         while (fp) {
208                 struct sk_buff *xp = fp->next;
209
210                 frag_kfree_skb(fp);
211                 fp = xp;
212         }
213
214         /* Finally, release the queue descriptor itself. */
215         frag_free_queue(qp);
216 }
217
218 static __inline__ void ipq_put(struct ipq *ipq)
219 {
220         if (atomic_dec_and_test(&ipq->refcnt))
221                 ip_frag_destroy(ipq);
222 }
223
224 /* Kill ipq entry. It is not destroyed immediately,
225  * because caller (and someone more) holds reference count.
226  */
227 static void ipq_kill(struct ipq *ipq)
228 {
229         if (del_timer(&ipq->timer))
230                 atomic_dec(&ipq->refcnt);
231
232         if (!(ipq->last_in & COMPLETE)) {
233                 ipq_unlink(ipq);
234                 atomic_dec(&ipq->refcnt);
235                 ipq->last_in |= COMPLETE;
236         }
237 }
238
239 /* Memory limiting on fragments.  Evictor trashes the oldest 
240  * fragment queue until we are back under the low threshold.
241  */
242 static void ip_evictor(void)
243 {
244         struct ipq *qp;
245         struct list_head *tmp;
246
247         for(;;) {
248                 if (atomic_read(&ip_frag_mem) <= sysctl_ipfrag_low_thresh)
249                         return;
250                 read_lock(&ipfrag_lock);
251                 if (list_empty(&ipq_lru_list)) {
252                         read_unlock(&ipfrag_lock);
253                         return;
254                 }
255                 tmp = ipq_lru_list.next;
256                 qp = list_entry(tmp, struct ipq, lru_list);
257                 atomic_inc(&qp->refcnt);
258                 read_unlock(&ipfrag_lock);
259
260                 spin_lock(&qp->lock);
261                 if (!(qp->last_in&COMPLETE))
262                         ipq_kill(qp);
263                 spin_unlock(&qp->lock);
264
265                 ipq_put(qp);
266                 IP_INC_STATS_BH(ReasmFails);
267         }
268 }
269
270 /*
271  * Oops, a fragment queue timed out.  Kill it and send an ICMP reply.
272  */
273 static void ip_expire(unsigned long arg)
274 {
275         struct ipq *qp = (struct ipq *) arg;
276
277         spin_lock(&qp->lock);
278
279         if (qp->last_in & COMPLETE)
280                 goto out;
281
282         ipq_kill(qp);
283
284         IP_INC_STATS_BH(ReasmTimeout);
285         IP_INC_STATS_BH(ReasmFails);
286
287         if ((qp->last_in&FIRST_IN) && qp->fragments != NULL) {
288                 struct sk_buff *head = qp->fragments;
289                 /* Send an ICMP "Fragment Reassembly Timeout" message. */
290                 if ((head->dev = dev_get_by_index(qp->iif)) != NULL) {
291                         icmp_send(head, ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, 0);
292                         dev_put(head->dev);
293                 }
294         }
295 out:
296         spin_unlock(&qp->lock);
297         ipq_put(qp);
298 }
299
300 /* Creation primitives. */
301
302 static struct ipq *ip_frag_intern(unsigned int hash, struct ipq *qp_in)
303 {
304         struct ipq *qp;
305
306         write_lock(&ipfrag_lock);
307 #ifdef CONFIG_SMP
308         /* With SMP race we have to recheck hash table, because
309          * such entry could be created on other cpu, while we
310          * promoted read lock to write lock.
311          */
312         for(qp = ipq_hash[hash]; qp; qp = qp->next) {
313                 if(qp->id == qp_in->id          &&
314                    qp->saddr == qp_in->saddr    &&
315                    qp->daddr == qp_in->daddr    &&
316                    qp->protocol == qp_in->protocol) {
317                         atomic_inc(&qp->refcnt);
318                         write_unlock(&ipfrag_lock);
319                         qp_in->last_in |= COMPLETE;
320                         ipq_put(qp_in);
321                         return qp;
322                 }
323         }
324 #endif
325         qp = qp_in;
326
327         if (!mod_timer(&qp->timer, jiffies + sysctl_ipfrag_time))
328                 atomic_inc(&qp->refcnt);
329
330         atomic_inc(&qp->refcnt);
331         if((qp->next = ipq_hash[hash]) != NULL)
332                 qp->next->pprev = &qp->next;
333         ipq_hash[hash] = qp;
334         qp->pprev = &ipq_hash[hash];
335         INIT_LIST_HEAD(&qp->lru_list);
336         list_add_tail(&qp->lru_list, &ipq_lru_list);
337         ip_frag_nqueues++;
338         write_unlock(&ipfrag_lock);
339         return qp;
340 }
341
342 /* Add an entry to the 'ipq' queue for a newly received IP datagram. */
343 static struct ipq *ip_frag_create(unsigned hash, struct iphdr *iph)
344 {
345         struct ipq *qp;
346
347         if ((qp = frag_alloc_queue()) == NULL)
348                 goto out_nomem;
349
350         qp->protocol = iph->protocol;
351         qp->last_in = 0;
352         qp->id = iph->id;
353         qp->saddr = iph->saddr;
354         qp->daddr = iph->daddr;
355         qp->len = 0;
356         qp->meat = 0;
357         qp->fragments = NULL;
358         qp->iif = 0;
359
360         /* Initialize a timer for this entry. */
361         init_timer(&qp->timer);
362         qp->timer.data = (unsigned long) qp;    /* pointer to queue     */
363         qp->timer.function = ip_expire;         /* expire function      */
364         qp->lock = SPIN_LOCK_UNLOCKED;
365         atomic_set(&qp->refcnt, 1);
366
367         return ip_frag_intern(hash, qp);
368
369 out_nomem:
370         NETDEBUG(if (net_ratelimit()) printk(KERN_ERR "ip_frag_create: no memory left !\n"));
371         return NULL;
372 }
373
374 /* Find the correct entry in the "incomplete datagrams" queue for
375  * this IP datagram, and create new one, if nothing is found.
376  */
377 static inline struct ipq *ip_find(struct iphdr *iph)
378 {
379         __u16 id = iph->id;
380         __u32 saddr = iph->saddr;
381         __u32 daddr = iph->daddr;
382         __u8 protocol = iph->protocol;
383         unsigned int hash = ipqhashfn(id, saddr, daddr, protocol);
384         struct ipq *qp;
385
386         read_lock(&ipfrag_lock);
387         for(qp = ipq_hash[hash]; qp; qp = qp->next) {
388                 if(qp->id == id         &&
389                    qp->saddr == saddr   &&
390                    qp->daddr == daddr   &&
391                    qp->protocol == protocol) {
392                         atomic_inc(&qp->refcnt);
393                         read_unlock(&ipfrag_lock);
394                         return qp;
395                 }
396         }
397         read_unlock(&ipfrag_lock);
398
399         return ip_frag_create(hash, iph);
400 }
401
402 /* Add new segment to existing queue. */
403 static void ip_frag_queue(struct ipq *qp, struct sk_buff *skb)
404 {
405         struct sk_buff *prev, *next;
406         int flags, offset;
407         int ihl, end;
408
409         if (qp->last_in & COMPLETE)
410                 goto err;
411
412         offset = ntohs(skb->nh.iph->frag_off);
413         flags = offset & ~IP_OFFSET;
414         offset &= IP_OFFSET;
415         offset <<= 3;           /* offset is in 8-byte chunks */
416         ihl = skb->nh.iph->ihl * 4;
417
418         /* Determine the position of this fragment. */
419         end = offset + skb->len - ihl;
420
421         /* Is this the final fragment? */
422         if ((flags & IP_MF) == 0) {
423                 /* If we already have some bits beyond end
424                  * or have different end, the segment is corrrupted.
425                  */
426                 if (end < qp->len ||
427                     ((qp->last_in & LAST_IN) && end != qp->len))
428                         goto err;
429                 qp->last_in |= LAST_IN;
430                 qp->len = end;
431         } else {
432                 if (end&7) {
433                         end &= ~7;
434                         if (skb->ip_summed != CHECKSUM_UNNECESSARY)
435                                 skb->ip_summed = CHECKSUM_NONE;
436                 }
437                 if (end > qp->len) {
438                         /* Some bits beyond end -> corruption. */
439                         if (qp->last_in & LAST_IN)
440                                 goto err;
441                         qp->len = end;
442                 }
443         }
444         if (end == offset)
445                 goto err;
446
447         if (pskb_pull(skb, ihl) == NULL)
448                 goto err;
449         if (pskb_trim(skb, end-offset))
450                 goto err;
451
452         /* Find out which fragments are in front and at the back of us
453          * in the chain of fragments so far.  We must know where to put
454          * this fragment, right?
455          */
456         prev = NULL;
457         for(next = qp->fragments; next != NULL; next = next->next) {
458                 if (FRAG_CB(next)->offset >= offset)
459                         break;  /* bingo! */
460                 prev = next;
461         }
462
463         /* We found where to put this one.  Check for overlap with
464          * preceding fragment, and, if needed, align things so that
465          * any overlaps are eliminated.
466          */
467         if (prev) {
468                 int i = (FRAG_CB(prev)->offset + prev->len) - offset;
469
470                 if (i > 0) {
471                         offset += i;
472                         if (end <= offset)
473                                 goto err;
474                         if (!pskb_pull(skb, i))
475                                 goto err;
476                         if (skb->ip_summed != CHECKSUM_UNNECESSARY)
477                                 skb->ip_summed = CHECKSUM_NONE;
478                 }
479         }
480
481         while (next && FRAG_CB(next)->offset < end) {
482                 int i = end - FRAG_CB(next)->offset; /* overlap is 'i' bytes */
483
484                 if (i < next->len) {
485                         /* Eat head of the next overlapped fragment
486                          * and leave the loop. The next ones cannot overlap.
487                          */
488                         if (!pskb_pull(next, i))
489                                 goto err;
490                         FRAG_CB(next)->offset += i;
491                         qp->meat -= i;
492                         if (next->ip_summed != CHECKSUM_UNNECESSARY)
493                                 next->ip_summed = CHECKSUM_NONE;
494                         break;
495                 } else {
496                         struct sk_buff *free_it = next;
497
498                         /* Old fragmnet is completely overridden with
499                          * new one drop it.
500                          */
501                         next = next->next;
502
503                         if (prev)
504                                 prev->next = next;
505                         else
506                                 qp->fragments = next;
507
508                         qp->meat -= free_it->len;
509                         frag_kfree_skb(free_it);
510                 }
511         }
512
513         FRAG_CB(skb)->offset = offset;
514
515         /* Insert this fragment in the chain of fragments. */
516         skb->next = next;
517         if (prev)
518                 prev->next = skb;
519         else
520                 qp->fragments = skb;
521
522         if (skb->dev)
523                 qp->iif = skb->dev->ifindex;
524         skb->dev = NULL;
525         qp->stamp = skb->stamp;
526         qp->meat += skb->len;
527         atomic_add(skb->truesize, &ip_frag_mem);
528         if (offset == 0)
529                 qp->last_in |= FIRST_IN;
530
531         write_lock(&ipfrag_lock);
532         list_move_tail(&qp->lru_list, &ipq_lru_list);
533         write_unlock(&ipfrag_lock);
534
535         return;
536
537 err:
538         kfree_skb(skb);
539 }
540
541
542 /* Build a new IP datagram from all its fragments. */
543
544 static struct sk_buff *ip_frag_reasm(struct ipq *qp, struct net_device *dev)
545 {
546         struct iphdr *iph;
547         struct sk_buff *fp, *head = qp->fragments;
548         int len;
549         int ihlen;
550
551         ipq_kill(qp);
552
553         BUG_TRAP(head != NULL);
554         BUG_TRAP(FRAG_CB(head)->offset == 0);
555
556         /* Allocate a new buffer for the datagram. */
557         ihlen = head->nh.iph->ihl*4;
558         len = ihlen + qp->len;
559
560         if(len > 65535)
561                 goto out_oversize;
562
563         /* Head of list must not be cloned. */
564         if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC))
565                 goto out_nomem;
566
567         /* If the first fragment is fragmented itself, we split
568          * it to two chunks: the first with data and paged part
569          * and the second, holding only fragments. */
570         if (skb_shinfo(head)->frag_list) {
571                 struct sk_buff *clone;
572                 int i, plen = 0;
573
574                 if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL)
575                         goto out_nomem;
576                 clone->next = head->next;
577                 head->next = clone;
578                 skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
579                 skb_shinfo(head)->frag_list = NULL;
580                 for (i=0; i<skb_shinfo(head)->nr_frags; i++)
581                         plen += skb_shinfo(head)->frags[i].size;
582                 clone->len = clone->data_len = head->data_len - plen;
583                 head->data_len -= clone->len;
584                 head->len -= clone->len;
585                 clone->csum = 0;
586                 clone->ip_summed = head->ip_summed;
587                 atomic_add(clone->truesize, &ip_frag_mem);
588         }
589
590         skb_shinfo(head)->frag_list = head->next;
591         skb_push(head, head->data - head->nh.raw);
592         atomic_sub(head->truesize, &ip_frag_mem);
593
594         for (fp=head->next; fp; fp = fp->next) {
595                 head->data_len += fp->len;
596                 head->len += fp->len;
597                 if (head->ip_summed != fp->ip_summed)
598                         head->ip_summed = CHECKSUM_NONE;
599                 else if (head->ip_summed == CHECKSUM_HW)
600                         head->csum = csum_add(head->csum, fp->csum);
601                 head->truesize += fp->truesize;
602                 atomic_sub(fp->truesize, &ip_frag_mem);
603         }
604
605         head->next = NULL;
606         head->dev = dev;
607         head->stamp = qp->stamp;
608
609         iph = head->nh.iph;
610         iph->frag_off = 0;
611         iph->tot_len = htons(len);
612         IP_INC_STATS_BH(ReasmOKs);
613         qp->fragments = NULL;
614         return head;
615
616 out_nomem:
617         NETDEBUG(if (net_ratelimit())
618                  printk(KERN_ERR 
619                         "IP: queue_glue: no memory for gluing queue %p\n",
620                         qp));
621         goto out_fail;
622 out_oversize:
623         if (net_ratelimit())
624                 printk(KERN_INFO
625                         "Oversized IP packet from %d.%d.%d.%d.\n",
626                         NIPQUAD(qp->saddr));
627 out_fail:
628         IP_INC_STATS_BH(ReasmFails);
629         return NULL;
630 }
631
632 /* Process an incoming IP datagram fragment. */
633 struct sk_buff *ip_defrag(struct sk_buff *skb)
634 {
635         struct iphdr *iph = skb->nh.iph;
636         struct ipq *qp;
637         struct net_device *dev;
638         
639         IP_INC_STATS_BH(ReasmReqds);
640
641         /* Start by cleaning up the memory. */
642         if (atomic_read(&ip_frag_mem) > sysctl_ipfrag_high_thresh)
643                 ip_evictor();
644
645         dev = skb->dev;
646
647         /* Lookup (or create) queue header */
648         if ((qp = ip_find(iph)) != NULL) {
649                 struct sk_buff *ret = NULL;
650
651                 spin_lock(&qp->lock);
652
653                 ip_frag_queue(qp, skb);
654
655                 if (qp->last_in == (FIRST_IN|LAST_IN) &&
656                     qp->meat == qp->len)
657                         ret = ip_frag_reasm(qp, dev);
658
659                 spin_unlock(&qp->lock);
660                 ipq_put(qp);
661                 return ret;
662         }
663
664         IP_INC_STATS_BH(ReasmFails);
665         kfree_skb(skb);
666         return NULL;
667 }
668
669 void ipfrag_init(void)
670 {
671         ipfrag_hash_rnd = (u32) ((num_physpages ^ (num_physpages>>7)) ^
672                                  (jiffies ^ (jiffies >> 6)));
673
674         init_timer(&ipfrag_secret_timer);
675         ipfrag_secret_timer.function = ipfrag_secret_rebuild;
676         ipfrag_secret_timer.expires = jiffies + sysctl_ipfrag_secret_interval;
677         add_timer(&ipfrag_secret_timer);
678 }
679
680 EXPORT_SYMBOL(ip_defrag);