vserver 1.9.3
[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, int *work)
173 {
174         if (work)
175                 *work -= skb->truesize;
176         atomic_sub(skb->truesize, &ip_frag_mem);
177         kfree_skb(skb);
178 }
179
180 static __inline__ void frag_free_queue(struct ipq *qp, int *work)
181 {
182         if (work)
183                 *work -= sizeof(struct ipq);
184         atomic_sub(sizeof(struct ipq), &ip_frag_mem);
185         kfree(qp);
186 }
187
188 static __inline__ struct ipq *frag_alloc_queue(void)
189 {
190         struct ipq *qp = kmalloc(sizeof(struct ipq), GFP_ATOMIC);
191
192         if(!qp)
193                 return NULL;
194         atomic_add(sizeof(struct ipq), &ip_frag_mem);
195         return qp;
196 }
197
198
199 /* Destruction primitives. */
200
201 /* Complete destruction of ipq. */
202 static void ip_frag_destroy(struct ipq *qp, int *work)
203 {
204         struct sk_buff *fp;
205
206         BUG_TRAP(qp->last_in&COMPLETE);
207         BUG_TRAP(del_timer(&qp->timer) == 0);
208
209         /* Release all fragment data. */
210         fp = qp->fragments;
211         while (fp) {
212                 struct sk_buff *xp = fp->next;
213
214                 frag_kfree_skb(fp, work);
215                 fp = xp;
216         }
217
218         /* Finally, release the queue descriptor itself. */
219         frag_free_queue(qp, work);
220 }
221
222 static __inline__ void ipq_put(struct ipq *ipq, int *work)
223 {
224         if (atomic_dec_and_test(&ipq->refcnt))
225                 ip_frag_destroy(ipq, work);
226 }
227
228 /* Kill ipq entry. It is not destroyed immediately,
229  * because caller (and someone more) holds reference count.
230  */
231 static void ipq_kill(struct ipq *ipq)
232 {
233         if (del_timer(&ipq->timer))
234                 atomic_dec(&ipq->refcnt);
235
236         if (!(ipq->last_in & COMPLETE)) {
237                 ipq_unlink(ipq);
238                 atomic_dec(&ipq->refcnt);
239                 ipq->last_in |= COMPLETE;
240         }
241 }
242
243 /* Memory limiting on fragments.  Evictor trashes the oldest 
244  * fragment queue until we are back under the threshold.
245  */
246 static void __ip_evictor(int threshold)
247 {
248         struct ipq *qp;
249         struct list_head *tmp;
250         int work;
251
252         work = atomic_read(&ip_frag_mem) - threshold;
253         if (work <= 0)
254                 return;
255
256         while (work > 0) {
257                 read_lock(&ipfrag_lock);
258                 if (list_empty(&ipq_lru_list)) {
259                         read_unlock(&ipfrag_lock);
260                         return;
261                 }
262                 tmp = ipq_lru_list.next;
263                 qp = list_entry(tmp, struct ipq, lru_list);
264                 atomic_inc(&qp->refcnt);
265                 read_unlock(&ipfrag_lock);
266
267                 spin_lock(&qp->lock);
268                 if (!(qp->last_in&COMPLETE))
269                         ipq_kill(qp);
270                 spin_unlock(&qp->lock);
271
272                 ipq_put(qp, &work);
273                 IP_INC_STATS_BH(IPSTATS_MIB_REASMFAILS);
274         }
275 }
276
277 static inline void ip_evictor(void)
278 {
279         __ip_evictor(sysctl_ipfrag_low_thresh);
280 }
281
282 /*
283  * Oops, a fragment queue timed out.  Kill it and send an ICMP reply.
284  */
285 static void ip_expire(unsigned long arg)
286 {
287         struct ipq *qp = (struct ipq *) arg;
288
289         spin_lock(&qp->lock);
290
291         if (qp->last_in & COMPLETE)
292                 goto out;
293
294         ipq_kill(qp);
295
296         IP_INC_STATS_BH(IPSTATS_MIB_REASMTIMEOUT);
297         IP_INC_STATS_BH(IPSTATS_MIB_REASMFAILS);
298
299         if ((qp->last_in&FIRST_IN) && qp->fragments != NULL) {
300                 struct sk_buff *head = qp->fragments;
301                 /* Send an ICMP "Fragment Reassembly Timeout" message. */
302                 if ((head->dev = dev_get_by_index(qp->iif)) != NULL) {
303                         icmp_send(head, ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, 0);
304                         dev_put(head->dev);
305                 }
306         }
307 out:
308         spin_unlock(&qp->lock);
309         ipq_put(qp, NULL);
310 }
311
312 /* Creation primitives. */
313
314 static struct ipq *ip_frag_intern(unsigned int hash, struct ipq *qp_in)
315 {
316         struct ipq *qp;
317
318         write_lock(&ipfrag_lock);
319 #ifdef CONFIG_SMP
320         /* With SMP race we have to recheck hash table, because
321          * such entry could be created on other cpu, while we
322          * promoted read lock to write lock.
323          */
324         for(qp = ipq_hash[hash]; qp; qp = qp->next) {
325                 if(qp->id == qp_in->id          &&
326                    qp->saddr == qp_in->saddr    &&
327                    qp->daddr == qp_in->daddr    &&
328                    qp->protocol == qp_in->protocol) {
329                         atomic_inc(&qp->refcnt);
330                         write_unlock(&ipfrag_lock);
331                         qp_in->last_in |= COMPLETE;
332                         ipq_put(qp_in, NULL);
333                         return qp;
334                 }
335         }
336 #endif
337         qp = qp_in;
338
339         if (!mod_timer(&qp->timer, jiffies + sysctl_ipfrag_time))
340                 atomic_inc(&qp->refcnt);
341
342         atomic_inc(&qp->refcnt);
343         if((qp->next = ipq_hash[hash]) != NULL)
344                 qp->next->pprev = &qp->next;
345         ipq_hash[hash] = qp;
346         qp->pprev = &ipq_hash[hash];
347         INIT_LIST_HEAD(&qp->lru_list);
348         list_add_tail(&qp->lru_list, &ipq_lru_list);
349         ip_frag_nqueues++;
350         write_unlock(&ipfrag_lock);
351         return qp;
352 }
353
354 /* Add an entry to the 'ipq' queue for a newly received IP datagram. */
355 static struct ipq *ip_frag_create(unsigned hash, struct iphdr *iph)
356 {
357         struct ipq *qp;
358
359         if ((qp = frag_alloc_queue()) == NULL)
360                 goto out_nomem;
361
362         qp->protocol = iph->protocol;
363         qp->last_in = 0;
364         qp->id = iph->id;
365         qp->saddr = iph->saddr;
366         qp->daddr = iph->daddr;
367         qp->len = 0;
368         qp->meat = 0;
369         qp->fragments = NULL;
370         qp->iif = 0;
371
372         /* Initialize a timer for this entry. */
373         init_timer(&qp->timer);
374         qp->timer.data = (unsigned long) qp;    /* pointer to queue     */
375         qp->timer.function = ip_expire;         /* expire function      */
376         qp->lock = SPIN_LOCK_UNLOCKED;
377         atomic_set(&qp->refcnt, 1);
378
379         return ip_frag_intern(hash, qp);
380
381 out_nomem:
382         NETDEBUG(if (net_ratelimit()) printk(KERN_ERR "ip_frag_create: no memory left !\n"));
383         return NULL;
384 }
385
386 /* Find the correct entry in the "incomplete datagrams" queue for
387  * this IP datagram, and create new one, if nothing is found.
388  */
389 static inline struct ipq *ip_find(struct iphdr *iph)
390 {
391         __u16 id = iph->id;
392         __u32 saddr = iph->saddr;
393         __u32 daddr = iph->daddr;
394         __u8 protocol = iph->protocol;
395         unsigned int hash = ipqhashfn(id, saddr, daddr, protocol);
396         struct ipq *qp;
397
398         read_lock(&ipfrag_lock);
399         for(qp = ipq_hash[hash]; qp; qp = qp->next) {
400                 if(qp->id == id         &&
401                    qp->saddr == saddr   &&
402                    qp->daddr == daddr   &&
403                    qp->protocol == protocol) {
404                         atomic_inc(&qp->refcnt);
405                         read_unlock(&ipfrag_lock);
406                         return qp;
407                 }
408         }
409         read_unlock(&ipfrag_lock);
410
411         return ip_frag_create(hash, iph);
412 }
413
414 /* Add new segment to existing queue. */
415 static void ip_frag_queue(struct ipq *qp, struct sk_buff *skb)
416 {
417         struct sk_buff *prev, *next;
418         int flags, offset;
419         int ihl, end;
420
421         if (qp->last_in & COMPLETE)
422                 goto err;
423
424         offset = ntohs(skb->nh.iph->frag_off);
425         flags = offset & ~IP_OFFSET;
426         offset &= IP_OFFSET;
427         offset <<= 3;           /* offset is in 8-byte chunks */
428         ihl = skb->nh.iph->ihl * 4;
429
430         /* Determine the position of this fragment. */
431         end = offset + skb->len - ihl;
432
433         /* Is this the final fragment? */
434         if ((flags & IP_MF) == 0) {
435                 /* If we already have some bits beyond end
436                  * or have different end, the segment is corrrupted.
437                  */
438                 if (end < qp->len ||
439                     ((qp->last_in & LAST_IN) && end != qp->len))
440                         goto err;
441                 qp->last_in |= LAST_IN;
442                 qp->len = end;
443         } else {
444                 if (end&7) {
445                         end &= ~7;
446                         if (skb->ip_summed != CHECKSUM_UNNECESSARY)
447                                 skb->ip_summed = CHECKSUM_NONE;
448                 }
449                 if (end > qp->len) {
450                         /* Some bits beyond end -> corruption. */
451                         if (qp->last_in & LAST_IN)
452                                 goto err;
453                         qp->len = end;
454                 }
455         }
456         if (end == offset)
457                 goto err;
458
459         if (pskb_pull(skb, ihl) == NULL)
460                 goto err;
461         if (pskb_trim(skb, end-offset))
462                 goto err;
463
464         /* Find out which fragments are in front and at the back of us
465          * in the chain of fragments so far.  We must know where to put
466          * this fragment, right?
467          */
468         prev = NULL;
469         for(next = qp->fragments; next != NULL; next = next->next) {
470                 if (FRAG_CB(next)->offset >= offset)
471                         break;  /* bingo! */
472                 prev = next;
473         }
474
475         /* We found where to put this one.  Check for overlap with
476          * preceding fragment, and, if needed, align things so that
477          * any overlaps are eliminated.
478          */
479         if (prev) {
480                 int i = (FRAG_CB(prev)->offset + prev->len) - offset;
481
482                 if (i > 0) {
483                         offset += i;
484                         if (end <= offset)
485                                 goto err;
486                         if (!pskb_pull(skb, i))
487                                 goto err;
488                         if (skb->ip_summed != CHECKSUM_UNNECESSARY)
489                                 skb->ip_summed = CHECKSUM_NONE;
490                 }
491         }
492
493         while (next && FRAG_CB(next)->offset < end) {
494                 int i = end - FRAG_CB(next)->offset; /* overlap is 'i' bytes */
495
496                 if (i < next->len) {
497                         /* Eat head of the next overlapped fragment
498                          * and leave the loop. The next ones cannot overlap.
499                          */
500                         if (!pskb_pull(next, i))
501                                 goto err;
502                         FRAG_CB(next)->offset += i;
503                         qp->meat -= i;
504                         if (next->ip_summed != CHECKSUM_UNNECESSARY)
505                                 next->ip_summed = CHECKSUM_NONE;
506                         break;
507                 } else {
508                         struct sk_buff *free_it = next;
509
510                         /* Old fragmnet is completely overridden with
511                          * new one drop it.
512                          */
513                         next = next->next;
514
515                         if (prev)
516                                 prev->next = next;
517                         else
518                                 qp->fragments = next;
519
520                         qp->meat -= free_it->len;
521                         frag_kfree_skb(free_it, NULL);
522                 }
523         }
524
525         FRAG_CB(skb)->offset = offset;
526
527         /* Insert this fragment in the chain of fragments. */
528         skb->next = next;
529         if (prev)
530                 prev->next = skb;
531         else
532                 qp->fragments = skb;
533
534         if (skb->dev)
535                 qp->iif = skb->dev->ifindex;
536         skb->dev = NULL;
537         qp->stamp = skb->stamp;
538         qp->meat += skb->len;
539         atomic_add(skb->truesize, &ip_frag_mem);
540         if (offset == 0)
541                 qp->last_in |= FIRST_IN;
542
543         write_lock(&ipfrag_lock);
544         list_move_tail(&qp->lru_list, &ipq_lru_list);
545         write_unlock(&ipfrag_lock);
546
547         return;
548
549 err:
550         kfree_skb(skb);
551 }
552
553
554 /* Build a new IP datagram from all its fragments. */
555
556 static struct sk_buff *ip_frag_reasm(struct ipq *qp, struct net_device *dev)
557 {
558         struct iphdr *iph;
559         struct sk_buff *fp, *head = qp->fragments;
560         int len;
561         int ihlen;
562
563         ipq_kill(qp);
564
565         BUG_TRAP(head != NULL);
566         BUG_TRAP(FRAG_CB(head)->offset == 0);
567
568         /* Allocate a new buffer for the datagram. */
569         ihlen = head->nh.iph->ihl*4;
570         len = ihlen + qp->len;
571
572         if(len > 65535)
573                 goto out_oversize;
574
575         /* Head of list must not be cloned. */
576         if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC))
577                 goto out_nomem;
578
579         /* If the first fragment is fragmented itself, we split
580          * it to two chunks: the first with data and paged part
581          * and the second, holding only fragments. */
582         if (skb_shinfo(head)->frag_list) {
583                 struct sk_buff *clone;
584                 int i, plen = 0;
585
586                 if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL)
587                         goto out_nomem;
588                 clone->next = head->next;
589                 head->next = clone;
590                 skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
591                 skb_shinfo(head)->frag_list = NULL;
592                 for (i=0; i<skb_shinfo(head)->nr_frags; i++)
593                         plen += skb_shinfo(head)->frags[i].size;
594                 clone->len = clone->data_len = head->data_len - plen;
595                 head->data_len -= clone->len;
596                 head->len -= clone->len;
597                 clone->csum = 0;
598                 clone->ip_summed = head->ip_summed;
599                 atomic_add(clone->truesize, &ip_frag_mem);
600         }
601
602         skb_shinfo(head)->frag_list = head->next;
603         skb_push(head, head->data - head->nh.raw);
604         atomic_sub(head->truesize, &ip_frag_mem);
605
606         for (fp=head->next; fp; fp = fp->next) {
607                 head->data_len += fp->len;
608                 head->len += fp->len;
609                 if (head->ip_summed != fp->ip_summed)
610                         head->ip_summed = CHECKSUM_NONE;
611                 else if (head->ip_summed == CHECKSUM_HW)
612                         head->csum = csum_add(head->csum, fp->csum);
613                 head->truesize += fp->truesize;
614                 atomic_sub(fp->truesize, &ip_frag_mem);
615         }
616
617         head->next = NULL;
618         head->dev = dev;
619         head->stamp = qp->stamp;
620
621         iph = head->nh.iph;
622         iph->frag_off = 0;
623         iph->tot_len = htons(len);
624         IP_INC_STATS_BH(IPSTATS_MIB_REASMOKS);
625         qp->fragments = NULL;
626         return head;
627
628 out_nomem:
629         NETDEBUG(if (net_ratelimit())
630                  printk(KERN_ERR 
631                         "IP: queue_glue: no memory for gluing queue %p\n",
632                         qp));
633         goto out_fail;
634 out_oversize:
635         if (net_ratelimit())
636                 printk(KERN_INFO
637                         "Oversized IP packet from %d.%d.%d.%d.\n",
638                         NIPQUAD(qp->saddr));
639 out_fail:
640         IP_INC_STATS_BH(IPSTATS_MIB_REASMFAILS);
641         return NULL;
642 }
643
644 /* Process an incoming IP datagram fragment. */
645 struct sk_buff *ip_defrag(struct sk_buff *skb)
646 {
647         struct iphdr *iph = skb->nh.iph;
648         struct ipq *qp;
649         struct net_device *dev;
650         
651         IP_INC_STATS_BH(IPSTATS_MIB_REASMREQDS);
652
653         /* Start by cleaning up the memory. */
654         if (atomic_read(&ip_frag_mem) > sysctl_ipfrag_high_thresh)
655                 ip_evictor();
656
657         dev = skb->dev;
658
659         /* Lookup (or create) queue header */
660         if ((qp = ip_find(iph)) != NULL) {
661                 struct sk_buff *ret = NULL;
662
663                 spin_lock(&qp->lock);
664
665                 ip_frag_queue(qp, skb);
666
667                 if (qp->last_in == (FIRST_IN|LAST_IN) &&
668                     qp->meat == qp->len)
669                         ret = ip_frag_reasm(qp, dev);
670
671                 spin_unlock(&qp->lock);
672                 ipq_put(qp, NULL);
673                 return ret;
674         }
675
676         IP_INC_STATS_BH(IPSTATS_MIB_REASMFAILS);
677         kfree_skb(skb);
678         return NULL;
679 }
680
681 void ipfrag_init(void)
682 {
683         ipfrag_hash_rnd = (u32) ((num_physpages ^ (num_physpages>>7)) ^
684                                  (jiffies ^ (jiffies >> 6)));
685
686         init_timer(&ipfrag_secret_timer);
687         ipfrag_secret_timer.function = ipfrag_secret_rebuild;
688         ipfrag_secret_timer.expires = jiffies + sysctl_ipfrag_secret_interval;
689         add_timer(&ipfrag_secret_timer);
690 }
691
692 void ipfrag_flush(void)
693 {
694         __ip_evictor(0);
695 }
696
697 EXPORT_SYMBOL(ip_defrag);
698 EXPORT_SYMBOL(ipfrag_flush);