vserver 1.9.3
[linux-2.6.git] / net / ipv4 / ipvs / ip_vs_core.c
1 /*
2  * IPVS         An implementation of the IP virtual server support for the
3  *              LINUX operating system.  IPVS is now implemented as a module
4  *              over the Netfilter framework. IPVS can be used to build a
5  *              high-performance and highly available server based on a
6  *              cluster of servers.
7  *
8  * Version:     $Id: ip_vs_core.c,v 1.34 2003/05/10 03:05:23 wensong Exp $
9  *
10  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
11  *              Peter Kese <peter.kese@ijs.si>
12  *              Julian Anastasov <ja@ssi.bg>
13  *
14  *              This program is free software; you can redistribute it and/or
15  *              modify it under the terms of the GNU General Public License
16  *              as published by the Free Software Foundation; either version
17  *              2 of the License, or (at your option) any later version.
18  *
19  * The IPVS code for kernel 2.2 was done by Wensong Zhang and Peter Kese,
20  * with changes/fixes from Julian Anastasov, Lars Marowsky-Bree, Horms
21  * and others.
22  *
23  * Changes:
24  *      Paul `Rusty' Russell            properly handle non-linear skbs
25  *
26  */
27
28 #include <linux/module.h>
29 #include <linux/kernel.h>
30 #include <linux/ip.h>
31 #include <linux/tcp.h>
32 #include <linux/icmp.h>
33
34 #include <net/ip.h>
35 #include <net/tcp.h>
36 #include <net/udp.h>
37 #include <net/icmp.h>                   /* for icmp_send */
38 #include <net/route.h>
39
40 #include <linux/netfilter.h>
41 #include <linux/netfilter_ipv4.h>
42
43 #include <net/ip_vs.h>
44
45
46 EXPORT_SYMBOL(register_ip_vs_scheduler);
47 EXPORT_SYMBOL(unregister_ip_vs_scheduler);
48 EXPORT_SYMBOL(ip_vs_skb_replace);
49 EXPORT_SYMBOL(ip_vs_proto_name);
50 EXPORT_SYMBOL(ip_vs_conn_new);
51 EXPORT_SYMBOL(ip_vs_conn_in_get);
52 EXPORT_SYMBOL(ip_vs_conn_out_get);
53 #ifdef CONFIG_IP_VS_PROTO_TCP
54 EXPORT_SYMBOL(ip_vs_tcp_conn_listen);
55 #endif
56 EXPORT_SYMBOL(ip_vs_conn_put);
57 #ifdef CONFIG_IP_VS_DEBUG
58 EXPORT_SYMBOL(ip_vs_get_debug_level);
59 #endif
60 EXPORT_SYMBOL(check_for_ip_vs_out);
61 EXPORT_SYMBOL(ip_vs_make_skb_writable);
62
63
64 /* ID used in ICMP lookups */
65 #define icmp_id(icmph)          (((icmph)->un).echo.id)
66
67 const char *ip_vs_proto_name(unsigned proto)
68 {
69         static char buf[20];
70
71         switch (proto) {
72         case IPPROTO_IP:
73                 return "IP";
74         case IPPROTO_UDP:
75                 return "UDP";
76         case IPPROTO_TCP:
77                 return "TCP";
78         case IPPROTO_ICMP:
79                 return "ICMP";
80         default:
81                 sprintf(buf, "IP_%d", proto);
82                 return buf;
83         }
84 }
85
86 void ip_vs_init_hash_table(struct list_head *table, int rows)
87 {
88         while (--rows >= 0)
89                 INIT_LIST_HEAD(&table[rows]);
90 }
91
92 static inline void
93 ip_vs_in_stats(struct ip_vs_conn *cp, struct sk_buff *skb)
94 {
95         struct ip_vs_dest *dest = cp->dest;
96         if (dest && (dest->flags & IP_VS_DEST_F_AVAILABLE)) {
97                 spin_lock(&dest->stats.lock);
98                 dest->stats.inpkts++;
99                 dest->stats.inbytes += skb->len;
100                 spin_unlock(&dest->stats.lock);
101
102                 spin_lock(&dest->svc->stats.lock);
103                 dest->svc->stats.inpkts++;
104                 dest->svc->stats.inbytes += skb->len;
105                 spin_unlock(&dest->svc->stats.lock);
106
107                 spin_lock(&ip_vs_stats.lock);
108                 ip_vs_stats.inpkts++;
109                 ip_vs_stats.inbytes += skb->len;
110                 spin_unlock(&ip_vs_stats.lock);
111         }
112 }
113
114
115 static inline void
116 ip_vs_out_stats(struct ip_vs_conn *cp, struct sk_buff *skb)
117 {
118         struct ip_vs_dest *dest = cp->dest;
119         if (dest && (dest->flags & IP_VS_DEST_F_AVAILABLE)) {
120                 spin_lock(&dest->stats.lock);
121                 dest->stats.outpkts++;
122                 dest->stats.outbytes += skb->len;
123                 spin_unlock(&dest->stats.lock);
124
125                 spin_lock(&dest->svc->stats.lock);
126                 dest->svc->stats.outpkts++;
127                 dest->svc->stats.outbytes += skb->len;
128                 spin_unlock(&dest->svc->stats.lock);
129
130                 spin_lock(&ip_vs_stats.lock);
131                 ip_vs_stats.outpkts++;
132                 ip_vs_stats.outbytes += skb->len;
133                 spin_unlock(&ip_vs_stats.lock);
134         }
135 }
136
137
138 static inline void
139 ip_vs_conn_stats(struct ip_vs_conn *cp, struct ip_vs_service *svc)
140 {
141         spin_lock(&cp->dest->stats.lock);
142         cp->dest->stats.conns++;
143         spin_unlock(&cp->dest->stats.lock);
144
145         spin_lock(&svc->stats.lock);
146         svc->stats.conns++;
147         spin_unlock(&svc->stats.lock);
148
149         spin_lock(&ip_vs_stats.lock);
150         ip_vs_stats.conns++;
151         spin_unlock(&ip_vs_stats.lock);
152 }
153
154
155 static inline int
156 ip_vs_set_state(struct ip_vs_conn *cp, int direction,
157                 const struct sk_buff *skb,
158                 struct ip_vs_protocol *pp)
159 {
160         if (unlikely(!pp->state_transition))
161                 return 0;
162         return pp->state_transition(cp, direction, skb, pp);
163 }
164
165
166 int ip_vs_make_skb_writable(struct sk_buff **pskb, int writable_len)
167 {
168         struct sk_buff *skb = *pskb;
169
170         /* skb is already used, better copy skb and its payload */
171         if (unlikely(skb_shared(skb) || skb->sk))
172                 goto copy_skb;
173
174         /* skb data is already used, copy it */
175         if (unlikely(skb_cloned(skb)))
176                 goto copy_data;
177
178         return pskb_may_pull(skb, writable_len);
179
180   copy_data:
181         if (unlikely(writable_len > skb->len))
182                 return 0;
183         return !pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
184
185   copy_skb:
186         if (unlikely(writable_len > skb->len))
187                 return 0;
188         skb = skb_copy(skb, GFP_ATOMIC);
189         if (!skb)
190                 return 0;
191         BUG_ON(skb_is_nonlinear(skb));
192
193         /* Rest of kernel will get very unhappy if we pass it a
194            suddenly-orphaned skbuff */
195         if ((*pskb)->sk)
196                 skb_set_owner_w(skb, (*pskb)->sk);
197         kfree_skb(*pskb);
198         *pskb = skb;
199         return 1;
200 }
201
202 /*
203  *  IPVS persistent scheduling function
204  *  It creates a connection entry according to its template if exists,
205  *  or selects a server and creates a connection entry plus a template.
206  *  Locking: we are svc user (svc->refcnt), so we hold all dests too
207  *  Protocols supported: TCP, UDP
208  */
209 static struct ip_vs_conn *
210 ip_vs_sched_persist(struct ip_vs_service *svc,
211                     const struct sk_buff *skb,
212                     __u16 ports[2])
213 {
214         struct ip_vs_conn *cp = NULL;
215         struct iphdr *iph = skb->nh.iph;
216         struct ip_vs_dest *dest;
217         struct ip_vs_conn *ct;
218         __u16  dport;    /* destination port to forward */
219         __u32  snet;     /* source network of the client, after masking */
220
221         /* Mask saddr with the netmask to adjust template granularity */
222         snet = iph->saddr & svc->netmask;
223
224         IP_VS_DBG(6, "p-schedule: src %u.%u.%u.%u:%u dest %u.%u.%u.%u:%u "
225                   "mnet %u.%u.%u.%u\n",
226                   NIPQUAD(iph->saddr), ntohs(ports[0]),
227                   NIPQUAD(iph->daddr), ntohs(ports[1]),
228                   NIPQUAD(snet));
229
230         /*
231          * As far as we know, FTP is a very complicated network protocol, and
232          * it uses control connection and data connections. For active FTP,
233          * FTP server initialize data connection to the client, its source port
234          * is often 20. For passive FTP, FTP server tells the clients the port
235          * that it passively listens to,  and the client issues the data
236          * connection. In the tunneling or direct routing mode, the load
237          * balancer is on the client-to-server half of connection, the port
238          * number is unknown to the load balancer. So, a conn template like
239          * <caddr, 0, vaddr, 0, daddr, 0> is created for persistent FTP
240          * service, and a template like <caddr, 0, vaddr, vport, daddr, dport>
241          * is created for other persistent services.
242          */
243         if (ports[1] == svc->port) {
244                 /* Check if a template already exists */
245                 if (svc->port != FTPPORT)
246                         ct = ip_vs_conn_in_get(iph->protocol, snet, 0,
247                                                iph->daddr, ports[1]);
248                 else
249                         ct = ip_vs_conn_in_get(iph->protocol, snet, 0,
250                                                iph->daddr, 0);
251
252                 if (!ct || !ip_vs_check_template(ct)) {
253                         /*
254                          * No template found or the dest of the connection
255                          * template is not available.
256                          */
257                         dest = svc->scheduler->schedule(svc, skb);
258                         if (dest == NULL) {
259                                 IP_VS_DBG(1, "p-schedule: no dest found.\n");
260                                 return NULL;
261                         }
262
263                         /*
264                          * Create a template like <protocol,caddr,0,
265                          * vaddr,vport,daddr,dport> for non-ftp service,
266                          * and <protocol,caddr,0,vaddr,0,daddr,0>
267                          * for ftp service.
268                          */
269                         if (svc->port != FTPPORT)
270                                 ct = ip_vs_conn_new(iph->protocol,
271                                                     snet, 0,
272                                                     iph->daddr,
273                                                     ports[1],
274                                                     dest->addr, dest->port,
275                                                     0,
276                                                     dest);
277                         else
278                                 ct = ip_vs_conn_new(iph->protocol,
279                                                     snet, 0,
280                                                     iph->daddr, 0,
281                                                     dest->addr, 0,
282                                                     0,
283                                                     dest);
284                         if (ct == NULL)
285                                 return NULL;
286
287                         ct->timeout = svc->timeout;
288                 } else {
289                         /* set destination with the found template */
290                         dest = ct->dest;
291                 }
292                 dport = dest->port;
293         } else {
294                 /*
295                  * Note: persistent fwmark-based services and persistent
296                  * port zero service are handled here.
297                  * fwmark template: <IPPROTO_IP,caddr,0,fwmark,0,daddr,0>
298                  * port zero template: <protocol,caddr,0,vaddr,0,daddr,0>
299                  */
300                 if (svc->fwmark)
301                         ct = ip_vs_conn_in_get(IPPROTO_IP, snet, 0,
302                                                htonl(svc->fwmark), 0);
303                 else
304                         ct = ip_vs_conn_in_get(iph->protocol, snet, 0,
305                                                iph->daddr, 0);
306
307                 if (!ct || !ip_vs_check_template(ct)) {
308                         /*
309                          * If it is not persistent port zero, return NULL,
310                          * otherwise create a connection template.
311                          */
312                         if (svc->port)
313                                 return NULL;
314
315                         dest = svc->scheduler->schedule(svc, skb);
316                         if (dest == NULL) {
317                                 IP_VS_DBG(1, "p-schedule: no dest found.\n");
318                                 return NULL;
319                         }
320
321                         /*
322                          * Create a template according to the service
323                          */
324                         if (svc->fwmark)
325                                 ct = ip_vs_conn_new(IPPROTO_IP,
326                                                     snet, 0,
327                                                     htonl(svc->fwmark), 0,
328                                                     dest->addr, 0,
329                                                     0,
330                                                     dest);
331                         else
332                                 ct = ip_vs_conn_new(iph->protocol,
333                                                     snet, 0,
334                                                     iph->daddr, 0,
335                                                     dest->addr, 0,
336                                                     0,
337                                                     dest);
338                         if (ct == NULL)
339                                 return NULL;
340
341                         ct->timeout = svc->timeout;
342                 } else {
343                         /* set destination with the found template */
344                         dest = ct->dest;
345                 }
346                 dport = ports[1];
347         }
348
349         /*
350          *    Create a new connection according to the template
351          */
352         cp = ip_vs_conn_new(iph->protocol,
353                             iph->saddr, ports[0],
354                             iph->daddr, ports[1],
355                             dest->addr, dport,
356                             0,
357                             dest);
358         if (cp == NULL) {
359                 ip_vs_conn_put(ct);
360                 return NULL;
361         }
362
363         /*
364          *    Add its control
365          */
366         ip_vs_control_add(cp, ct);
367         ip_vs_conn_put(ct);
368
369         ip_vs_conn_stats(cp, svc);
370         return cp;
371 }
372
373
374 /*
375  *  IPVS main scheduling function
376  *  It selects a server according to the virtual service, and
377  *  creates a connection entry.
378  *  Protocols supported: TCP, UDP
379  */
380 struct ip_vs_conn *
381 ip_vs_schedule(struct ip_vs_service *svc, const struct sk_buff *skb)
382 {
383         struct ip_vs_conn *cp = NULL;
384         struct iphdr *iph = skb->nh.iph;
385         struct ip_vs_dest *dest;
386         __u16 _ports[2], *pptr;
387
388         pptr = skb_header_pointer(skb, iph->ihl*4,
389                                   sizeof(_ports), _ports);
390         if (pptr == NULL)
391                 return NULL;
392
393         /*
394          *    Persistent service
395          */
396         if (svc->flags & IP_VS_SVC_F_PERSISTENT)
397                 return ip_vs_sched_persist(svc, skb, pptr);
398
399         /*
400          *    Non-persistent service
401          */
402         if (!svc->fwmark && pptr[1] != svc->port) {
403                 if (!svc->port)
404                         IP_VS_ERR("Schedule: port zero only supported "
405                                   "in persistent services, "
406                                   "check your ipvs configuration\n");
407                 return NULL;
408         }
409
410         dest = svc->scheduler->schedule(svc, skb);
411         if (dest == NULL) {
412                 IP_VS_DBG(1, "Schedule: no dest found.\n");
413                 return NULL;
414         }
415
416         /*
417          *    Create a connection entry.
418          */
419         cp = ip_vs_conn_new(iph->protocol,
420                             iph->saddr, pptr[0],
421                             iph->daddr, pptr[1],
422                             dest->addr, dest->port?dest->port:pptr[1],
423                             0,
424                             dest);
425         if (cp == NULL)
426                 return NULL;
427
428         IP_VS_DBG(6, "Schedule fwd:%c c:%u.%u.%u.%u:%u v:%u.%u.%u.%u:%u "
429                   "d:%u.%u.%u.%u:%u flg:%X cnt:%d\n",
430                   ip_vs_fwd_tag(cp),
431                   NIPQUAD(cp->caddr), ntohs(cp->cport),
432                   NIPQUAD(cp->vaddr), ntohs(cp->vport),
433                   NIPQUAD(cp->daddr), ntohs(cp->dport),
434                   cp->flags, atomic_read(&cp->refcnt));
435
436         ip_vs_conn_stats(cp, svc);
437         return cp;
438 }
439
440
441 /*
442  *  Pass or drop the packet.
443  *  Called by ip_vs_in, when the virtual service is available but
444  *  no destination is available for a new connection.
445  */
446 int ip_vs_leave(struct ip_vs_service *svc, struct sk_buff *skb,
447                 struct ip_vs_protocol *pp)
448 {
449         __u16 _ports[2], *pptr;
450         struct iphdr *iph = skb->nh.iph;
451
452         pptr = skb_header_pointer(skb, iph->ihl*4,
453                                   sizeof(_ports), _ports);
454         if (pptr == NULL) {
455                 ip_vs_service_put(svc);
456                 return NF_DROP;
457         }
458
459         /* if it is fwmark-based service, the cache_bypass sysctl is up
460            and the destination is RTN_UNICAST (and not local), then create
461            a cache_bypass connection entry */
462         if (sysctl_ip_vs_cache_bypass && svc->fwmark
463             && (inet_addr_type(iph->daddr) == RTN_UNICAST)) {
464                 int ret, cs;
465                 struct ip_vs_conn *cp;
466
467                 ip_vs_service_put(svc);
468
469                 /* create a new connection entry */
470                 IP_VS_DBG(6, "ip_vs_leave: create a cache_bypass entry\n");
471                 cp = ip_vs_conn_new(iph->protocol,
472                                     iph->saddr, pptr[0],
473                                     iph->daddr, pptr[1],
474                                     0, 0,
475                                     IP_VS_CONN_F_BYPASS,
476                                     NULL);
477                 if (cp == NULL)
478                         return NF_DROP;
479
480                 /* statistics */
481                 ip_vs_in_stats(cp, skb);
482
483                 /* set state */
484                 cs = ip_vs_set_state(cp, IP_VS_DIR_INPUT, skb, pp);
485
486                 /* transmit the first SYN packet */
487                 ret = cp->packet_xmit(skb, cp, pp);
488                 /* do not touch skb anymore */
489
490                 atomic_inc(&cp->in_pkts);
491                 ip_vs_conn_put(cp);
492                 return ret;
493         }
494
495         /*
496          * When the virtual ftp service is presented, packets destined
497          * for other services on the VIP may get here (except services
498          * listed in the ipvs table), pass the packets, because it is
499          * not ipvs job to decide to drop the packets.
500          */
501         if ((svc->port == FTPPORT) && (pptr[1] != FTPPORT)) {
502                 ip_vs_service_put(svc);
503                 return NF_ACCEPT;
504         }
505
506         ip_vs_service_put(svc);
507
508         /*
509          * Notify the client that the destination is unreachable, and
510          * release the socket buffer.
511          * Since it is in IP layer, the TCP socket is not actually
512          * created, the TCP RST packet cannot be sent, instead that
513          * ICMP_PORT_UNREACH is sent here no matter it is TCP/UDP. --WZ
514          */
515         icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
516         return NF_DROP;
517 }
518
519
520 /*
521  *      It is hooked before NF_IP_PRI_NAT_SRC at the NF_IP_POST_ROUTING
522  *      chain, and is used for VS/NAT.
523  *      It detects packets for VS/NAT connections and sends the packets
524  *      immediately. This can avoid that iptable_nat mangles the packets
525  *      for VS/NAT.
526  */
527 static unsigned int ip_vs_post_routing(unsigned int hooknum,
528                                        struct sk_buff **pskb,
529                                        const struct net_device *in,
530                                        const struct net_device *out,
531                                        int (*okfn)(struct sk_buff *))
532 {
533         if (!((*pskb)->nfcache & NFC_IPVS_PROPERTY))
534                 return NF_ACCEPT;
535
536         /* The packet was sent from IPVS, exit this chain */
537         (*okfn)(*pskb);
538
539         return NF_STOLEN;
540 }
541
542 u16 ip_vs_checksum_complete(struct sk_buff *skb, int offset)
543 {
544         return (u16) csum_fold(skb_checksum(skb, offset, skb->len - offset, 0));
545 }
546
547 static inline struct sk_buff *
548 ip_vs_gather_frags(struct sk_buff *skb)
549 {
550         skb = ip_defrag(skb);
551         if (skb)
552                 ip_send_check(skb->nh.iph);
553         return skb;
554 }
555
556 /*
557  * Packet has been made sufficiently writable in caller
558  * - inout: 1=in->out, 0=out->in
559  */
560 void ip_vs_nat_icmp(struct sk_buff *skb, struct ip_vs_protocol *pp,
561                     struct ip_vs_conn *cp, int inout)
562 {
563         struct iphdr *iph        = skb->nh.iph;
564         unsigned int icmp_offset = iph->ihl*4;
565         struct icmphdr *icmph    = (struct icmphdr *)(skb->nh.raw + icmp_offset);
566         struct iphdr *ciph       = (struct iphdr *)(icmph + 1);
567
568         if (inout) {
569                 iph->saddr = cp->vaddr;
570                 ip_send_check(iph);
571                 ciph->daddr = cp->vaddr;
572                 ip_send_check(ciph);
573         } else {
574                 iph->daddr = cp->daddr;
575                 ip_send_check(iph);
576                 ciph->saddr = cp->daddr;
577                 ip_send_check(ciph);
578         }
579
580         /* the TCP/UDP port */
581         if (IPPROTO_TCP == ciph->protocol || IPPROTO_UDP == ciph->protocol) {
582                 __u16 *ports = (void *)ciph + ciph->ihl*4;
583
584                 if (inout)
585                         ports[1] = cp->vport;
586                 else
587                         ports[0] = cp->dport;
588         }
589
590         /* And finally the ICMP checksum */
591         icmph->checksum = 0;
592         icmph->checksum = ip_vs_checksum_complete(skb, icmp_offset);
593         skb->ip_summed = CHECKSUM_UNNECESSARY;
594
595         if (inout)
596                 IP_VS_DBG_PKT(11, pp, skb, (void *)ciph - (void *)iph,
597                         "Forwarding altered outgoing ICMP");
598         else
599                 IP_VS_DBG_PKT(11, pp, skb, (void *)ciph - (void *)iph,
600                         "Forwarding altered incoming ICMP");
601 }
602
603 /*
604  *      Handle ICMP messages in the inside-to-outside direction (outgoing).
605  *      Find any that might be relevant, check against existing connections,
606  *      forward to the right destination host if relevant.
607  *      Currently handles error types - unreachable, quench, ttl exceeded.
608  *      (Only used in VS/NAT)
609  */
610 static int ip_vs_out_icmp(struct sk_buff **pskb, int *related)
611 {
612         struct sk_buff *skb = *pskb;
613         struct iphdr *iph;
614         struct icmphdr  _icmph, *ic;
615         struct iphdr    _ciph, *cih;    /* The ip header contained within the ICMP */
616         struct ip_vs_conn *cp;
617         struct ip_vs_protocol *pp;
618         unsigned int offset, ihl, verdict;
619
620         *related = 1;
621
622         /* reassemble IP fragments */
623         if (skb->nh.iph->frag_off & __constant_htons(IP_MF|IP_OFFSET)) {
624                 skb = ip_vs_gather_frags(skb);
625                 if (!skb)
626                         return NF_STOLEN;
627                 *pskb = skb;
628         }
629
630         iph = skb->nh.iph;
631         offset = ihl = iph->ihl * 4;
632         ic = skb_header_pointer(skb, offset, sizeof(_icmph), &_icmph);
633         if (ic == NULL)
634                 return NF_DROP;
635
636         IP_VS_DBG(12, "Outgoing ICMP (%d,%d) %u.%u.%u.%u->%u.%u.%u.%u\n",
637                   ic->type, ntohs(icmp_id(ic)),
638                   NIPQUAD(iph->saddr), NIPQUAD(iph->daddr));
639
640         /*
641          * Work through seeing if this is for us.
642          * These checks are supposed to be in an order that means easy
643          * things are checked first to speed up processing.... however
644          * this means that some packets will manage to get a long way
645          * down this stack and then be rejected, but that's life.
646          */
647         if ((ic->type != ICMP_DEST_UNREACH) &&
648             (ic->type != ICMP_SOURCE_QUENCH) &&
649             (ic->type != ICMP_TIME_EXCEEDED)) {
650                 *related = 0;
651                 return NF_ACCEPT;
652         }
653
654         /* Now find the contained IP header */
655         offset += sizeof(_icmph);
656         cih = skb_header_pointer(skb, offset, sizeof(_ciph), &_ciph);
657         if (cih == NULL)
658                 return NF_ACCEPT; /* The packet looks wrong, ignore */
659
660         pp = ip_vs_proto_get(cih->protocol);
661         if (!pp)
662                 return NF_ACCEPT;
663
664         /* Is the embedded protocol header present? */
665         if (unlikely(cih->frag_off & __constant_htons(IP_OFFSET) &&
666                      pp->dont_defrag))
667                 return NF_ACCEPT;
668
669         IP_VS_DBG_PKT(11, pp, skb, offset, "Checking outgoing ICMP for");
670
671         offset += cih->ihl * 4;
672
673         /* The embedded headers contain source and dest in reverse order */
674         cp = pp->conn_out_get(skb, pp, cih, offset, 1);
675         if (!cp)
676                 return NF_ACCEPT;
677
678         verdict = NF_DROP;
679
680         if (IP_VS_FWD_METHOD(cp) != 0) {
681                 IP_VS_ERR("shouldn't reach here, because the box is on the"
682                           "half connection in the tun/dr module.\n");
683         }
684
685         /* Ensure the checksum is correct */
686         if (skb->ip_summed != CHECKSUM_UNNECESSARY &&
687             ip_vs_checksum_complete(skb, ihl)) {
688                 /* Failed checksum! */
689                 IP_VS_DBG(1, "Forward ICMP: failed checksum from %d.%d.%d.%d!\n",
690                           NIPQUAD(iph->saddr));
691                 goto out;
692         }
693
694         if (IPPROTO_TCP == cih->protocol || IPPROTO_UDP == cih->protocol)
695                 offset += 2 * sizeof(__u16);
696         if (!ip_vs_make_skb_writable(pskb, offset))
697                 goto out;
698         skb = *pskb;
699
700         ip_vs_nat_icmp(skb, pp, cp, 1);
701
702         /* do the statistics and put it back */
703         ip_vs_out_stats(cp, skb);
704
705         skb->nfcache |= NFC_IPVS_PROPERTY;
706         verdict = NF_ACCEPT;
707
708   out:
709         __ip_vs_conn_put(cp);
710
711         return verdict;
712 }
713
714 static inline int is_tcp_reset(const struct sk_buff *skb)
715 {
716         struct tcphdr _tcph, *th;
717
718         th = skb_header_pointer(skb, skb->nh.iph->ihl * 4,
719                                 sizeof(_tcph), &_tcph);
720         if (th == NULL)
721                 return 0;
722         return th->rst;
723 }
724
725 /*
726  *      It is hooked at the NF_IP_FORWARD chain, used only for VS/NAT.
727  *      Check if outgoing packet belongs to the established ip_vs_conn,
728  *      rewrite addresses of the packet and send it on its way...
729  */
730 static unsigned int
731 ip_vs_out(unsigned int hooknum, struct sk_buff **pskb,
732           const struct net_device *in, const struct net_device *out,
733           int (*okfn)(struct sk_buff *))
734 {
735         struct sk_buff  *skb = *pskb;
736         struct iphdr    *iph;
737         struct ip_vs_protocol *pp;
738         struct ip_vs_conn *cp;
739         int ihl;
740
741         EnterFunction(11);
742
743         if (skb->nfcache & NFC_IPVS_PROPERTY)
744                 return NF_ACCEPT;
745
746         iph = skb->nh.iph;
747         if (unlikely(iph->protocol == IPPROTO_ICMP)) {
748                 int related, verdict = ip_vs_out_icmp(pskb, &related);
749
750                 if (related)
751                         return verdict;
752                 skb = *pskb;
753                 iph = skb->nh.iph;
754         }
755
756         pp = ip_vs_proto_get(iph->protocol);
757         if (unlikely(!pp))
758                 return NF_ACCEPT;
759
760         /* reassemble IP fragments */
761         if (unlikely(iph->frag_off & __constant_htons(IP_MF|IP_OFFSET) &&
762                      !pp->dont_defrag)) {
763                 skb = ip_vs_gather_frags(skb);
764                 if (!skb)
765                         return NF_STOLEN;
766                 iph = skb->nh.iph;
767                 *pskb = skb;
768         }
769
770         ihl = iph->ihl << 2;
771
772         /*
773          * Check if the packet belongs to an existing entry
774          */
775         cp = pp->conn_out_get(skb, pp, iph, ihl, 0);
776
777         if (unlikely(!cp)) {
778                 if (sysctl_ip_vs_nat_icmp_send &&
779                     (pp->protocol == IPPROTO_TCP ||
780                      pp->protocol == IPPROTO_UDP)) {
781                         __u16 _ports[2], *pptr;
782
783                         pptr = skb_header_pointer(skb, ihl,
784                                                   sizeof(_ports), _ports);
785                         if (pptr == NULL)
786                                 return NF_ACCEPT;       /* Not for me */
787                         if (ip_vs_lookup_real_service(iph->protocol,
788                                                       iph->saddr, pptr[0])) {
789                                 /*
790                                  * Notify the real server: there is no
791                                  * existing entry if it is not RST
792                                  * packet or not TCP packet.
793                                  */
794                                 if (iph->protocol != IPPROTO_TCP
795                                     || !is_tcp_reset(skb)) {
796                                         icmp_send(skb,ICMP_DEST_UNREACH,
797                                                   ICMP_PORT_UNREACH, 0);
798                                         return NF_DROP;
799                                 }
800                         }
801                 }
802                 IP_VS_DBG_PKT(12, pp, skb, 0,
803                               "packet continues traversal as normal");
804                 return NF_ACCEPT;
805         }
806
807         IP_VS_DBG_PKT(11, pp, skb, 0, "Outgoing packet");
808
809         if (!ip_vs_make_skb_writable(pskb, ihl))
810                 goto drop;
811
812         /* mangle the packet */
813         if (pp->snat_handler && !pp->snat_handler(pskb, pp, cp))
814                 goto drop;
815         skb = *pskb;
816         skb->nh.iph->saddr = cp->vaddr;
817         ip_send_check(skb->nh.iph);
818
819         IP_VS_DBG_PKT(10, pp, skb, 0, "After SNAT");
820
821         ip_vs_out_stats(cp, skb);
822         ip_vs_set_state(cp, IP_VS_DIR_OUTPUT, skb, pp);
823         ip_vs_conn_put(cp);
824
825         skb->nfcache |= NFC_IPVS_PROPERTY;
826
827         LeaveFunction(11);
828         return NF_ACCEPT;
829
830   drop:
831         ip_vs_conn_put(cp);
832         kfree_skb(*pskb);
833         return NF_STOLEN;
834 }
835
836
837 /*
838  *      Check if the packet is for VS/NAT connections, then send it
839  *      immediately.
840  *      Called by ip_fw_compact to detect packets for VS/NAT before
841  *      they are changed by ipchains masquerading code.
842  */
843 unsigned int
844 check_for_ip_vs_out(struct sk_buff **pskb, int (*okfn)(struct sk_buff *))
845 {
846         unsigned int ret;
847
848         ret = ip_vs_out(NF_IP_FORWARD, pskb, NULL, NULL, NULL);
849         if (ret != NF_ACCEPT) {
850                 return ret;
851         } else {
852                 /* send the packet immediately if it is already mangled
853                    by ip_vs_out */
854                 if ((*pskb)->nfcache & NFC_IPVS_PROPERTY) {
855                         (*okfn)(*pskb);
856                         return NF_STOLEN;
857                 }
858         }
859         return NF_ACCEPT;
860 }
861
862 /*
863  *      Handle ICMP messages in the outside-to-inside direction (incoming).
864  *      Find any that might be relevant, check against existing connections,
865  *      forward to the right destination host if relevant.
866  *      Currently handles error types - unreachable, quench, ttl exceeded.
867  */
868 static int ip_vs_in_icmp(struct sk_buff **pskb, int *related)
869 {
870         struct sk_buff *skb = *pskb;
871         struct iphdr *iph;
872         struct icmphdr  _icmph, *ic;
873         struct iphdr    _ciph, *cih;    /* The ip header contained within the ICMP */
874         struct ip_vs_conn *cp;
875         struct ip_vs_protocol *pp;
876         unsigned int offset, ihl, verdict;
877
878         *related = 1;
879
880         /* reassemble IP fragments */
881         if (skb->nh.iph->frag_off & __constant_htons(IP_MF|IP_OFFSET)) {
882                 skb = ip_vs_gather_frags(skb);
883                 if (!skb)
884                         return NF_STOLEN;
885                 *pskb = skb;
886         }
887
888         iph = skb->nh.iph;
889         offset = ihl = iph->ihl * 4;
890         ic = skb_header_pointer(skb, offset, sizeof(_icmph), &_icmph);
891         if (ic == NULL)
892                 return NF_DROP;
893
894         IP_VS_DBG(12, "Incoming ICMP (%d,%d) %u.%u.%u.%u->%u.%u.%u.%u\n",
895                   ic->type, ntohs(icmp_id(ic)),
896                   NIPQUAD(iph->saddr), NIPQUAD(iph->daddr));
897
898         /*
899          * Work through seeing if this is for us.
900          * These checks are supposed to be in an order that means easy
901          * things are checked first to speed up processing.... however
902          * this means that some packets will manage to get a long way
903          * down this stack and then be rejected, but that's life.
904          */
905         if ((ic->type != ICMP_DEST_UNREACH) &&
906             (ic->type != ICMP_SOURCE_QUENCH) &&
907             (ic->type != ICMP_TIME_EXCEEDED)) {
908                 *related = 0;
909                 return NF_ACCEPT;
910         }
911
912         /* Now find the contained IP header */
913         offset += sizeof(_icmph);
914         cih = skb_header_pointer(skb, offset, sizeof(_ciph), &_ciph);
915         if (cih == NULL)
916                 return NF_ACCEPT; /* The packet looks wrong, ignore */
917
918         pp = ip_vs_proto_get(cih->protocol);
919         if (!pp)
920                 return NF_ACCEPT;
921
922         /* Is the embedded protocol header present? */
923         if (unlikely(cih->frag_off & __constant_htons(IP_OFFSET) &&
924                      pp->dont_defrag))
925                 return NF_ACCEPT;
926
927         IP_VS_DBG_PKT(11, pp, skb, offset, "Checking incoming ICMP for");
928
929         offset += cih->ihl * 4;
930
931         /* The embedded headers contain source and dest in reverse order */
932         cp = pp->conn_in_get(skb, pp, cih, offset, 1);
933         if (!cp)
934                 return NF_ACCEPT;
935
936         verdict = NF_DROP;
937
938         /* Ensure the checksum is correct */
939         if (skb->ip_summed != CHECKSUM_UNNECESSARY &&
940             ip_vs_checksum_complete(skb, ihl)) {
941                 /* Failed checksum! */
942                 IP_VS_DBG(1, "Incoming ICMP: failed checksum from %d.%d.%d.%d!\n",
943                           NIPQUAD(iph->saddr));
944                 goto out;
945         }
946
947         /* do the statistics and put it back */
948         ip_vs_in_stats(cp, skb);
949         if (IPPROTO_TCP == cih->protocol || IPPROTO_UDP == cih->protocol)
950                 offset += 2 * sizeof(__u16);
951         verdict = ip_vs_icmp_xmit(skb, cp, pp, offset);
952         /* do not touch skb anymore */
953
954   out:
955         __ip_vs_conn_put(cp);
956
957         return verdict;
958 }
959
960 /*
961  *      Check if it's for virtual services, look it up,
962  *      and send it on its way...
963  */
964 static unsigned int
965 ip_vs_in(unsigned int hooknum, struct sk_buff **pskb,
966          const struct net_device *in, const struct net_device *out,
967          int (*okfn)(struct sk_buff *))
968 {
969         struct sk_buff  *skb = *pskb;
970         struct iphdr    *iph;
971         struct ip_vs_protocol *pp;
972         struct ip_vs_conn *cp;
973         int ret, restart;
974         int ihl;
975
976         /*
977          *      Big tappo: only PACKET_HOST (neither loopback nor mcasts)
978          *      ... don't know why 1st test DOES NOT include 2nd (?)
979          */
980         if (unlikely(skb->pkt_type != PACKET_HOST
981                      || skb->dev == &loopback_dev || skb->sk)) {
982                 IP_VS_DBG(12, "packet type=%d proto=%d daddr=%d.%d.%d.%d ignored\n",
983                           skb->pkt_type,
984                           skb->nh.iph->protocol,
985                           NIPQUAD(skb->nh.iph->daddr));
986                 return NF_ACCEPT;
987         }
988
989         iph = skb->nh.iph;
990         if (unlikely(iph->protocol == IPPROTO_ICMP)) {
991                 int related, verdict = ip_vs_in_icmp(pskb, &related);
992
993                 if (related)
994                         return verdict;
995                 skb = *pskb;
996                 iph = skb->nh.iph;
997         }
998
999         /* Protocol supported? */
1000         pp = ip_vs_proto_get(iph->protocol);
1001         if (unlikely(!pp))
1002                 return NF_ACCEPT;
1003
1004         ihl = iph->ihl << 2;
1005
1006         /*
1007          * Check if the packet belongs to an existing connection entry
1008          */
1009         cp = pp->conn_in_get(skb, pp, iph, ihl, 0);
1010
1011         if (unlikely(!cp)) {
1012                 int v;
1013
1014                 if (!pp->conn_schedule(skb, pp, &v, &cp))
1015                         return v;
1016         }
1017
1018         if (unlikely(!cp)) {
1019                 /* sorry, all this trouble for a no-hit :) */
1020                 IP_VS_DBG_PKT(12, pp, skb, 0,
1021                               "packet continues traversal as normal");
1022                 return NF_ACCEPT;
1023         }
1024
1025         IP_VS_DBG_PKT(11, pp, skb, 0, "Incoming packet");
1026
1027         /* Check the server status */
1028         if (cp->dest && !(cp->dest->flags & IP_VS_DEST_F_AVAILABLE)) {
1029                 /* the destination server is not availabe */
1030
1031                 if (sysctl_ip_vs_expire_nodest_conn) {
1032                         /* try to expire the connection immediately */
1033                         ip_vs_conn_expire_now(cp);
1034                 } else {
1035                         /* don't restart its timer, and silently
1036                            drop the packet. */
1037                         __ip_vs_conn_put(cp);
1038                 }
1039                 return NF_DROP;
1040         }
1041
1042         ip_vs_in_stats(cp, skb);
1043         restart = ip_vs_set_state(cp, IP_VS_DIR_INPUT, skb, pp);
1044         if (cp->packet_xmit)
1045                 ret = cp->packet_xmit(skb, cp, pp);
1046                 /* do not touch skb anymore */
1047         else {
1048                 IP_VS_DBG_RL("warning: packet_xmit is null");
1049                 ret = NF_ACCEPT;
1050         }
1051
1052         /* increase its packet counter and check if it is needed
1053            to be synchronized */
1054         atomic_inc(&cp->in_pkts);
1055         if ((ip_vs_sync_state & IP_VS_STATE_MASTER) &&
1056             (cp->protocol != IPPROTO_TCP ||
1057              cp->state == IP_VS_TCP_S_ESTABLISHED) &&
1058             (atomic_read(&cp->in_pkts) % sysctl_ip_vs_sync_threshold[1]
1059              == sysctl_ip_vs_sync_threshold[0]))
1060                 ip_vs_sync_conn(cp);
1061
1062         ip_vs_conn_put(cp);
1063         return ret;
1064 }
1065
1066
1067 /*
1068  *      It is hooked at the NF_IP_FORWARD chain, in order to catch ICMP
1069  *      related packets destined for 0.0.0.0/0.
1070  *      When fwmark-based virtual service is used, such as transparent
1071  *      cache cluster, TCP packets can be marked and routed to ip_vs_in,
1072  *      but ICMP destined for 0.0.0.0/0 cannot not be easily marked and
1073  *      sent to ip_vs_in_icmp. So, catch them at the NF_IP_FORWARD chain
1074  *      and send them to ip_vs_in_icmp.
1075  */
1076 static unsigned int
1077 ip_vs_forward_icmp(unsigned int hooknum, struct sk_buff **pskb,
1078                    const struct net_device *in, const struct net_device *out,
1079                    int (*okfn)(struct sk_buff *))
1080 {
1081         int r;
1082
1083         if ((*pskb)->nh.iph->protocol != IPPROTO_ICMP)
1084                 return NF_ACCEPT;
1085
1086         return ip_vs_in_icmp(pskb, &r);
1087 }
1088
1089
1090 /* After packet filtering, forward packet through VS/DR, VS/TUN,
1091    or VS/NAT(change destination), so that filtering rules can be
1092    applied to IPVS. */
1093 static struct nf_hook_ops ip_vs_in_ops = {
1094         .hook           = ip_vs_in,
1095         .owner          = THIS_MODULE,
1096         .pf             = PF_INET,
1097         .hooknum        = NF_IP_LOCAL_IN,
1098         .priority       = 100,
1099 };
1100
1101 /* After packet filtering, change source only for VS/NAT */
1102 static struct nf_hook_ops ip_vs_out_ops = {
1103         .hook           = ip_vs_out,
1104         .owner          = THIS_MODULE,
1105         .pf             = PF_INET,
1106         .hooknum        = NF_IP_FORWARD,
1107         .priority       = 100,
1108 };
1109
1110 /* After packet filtering (but before ip_vs_out_icmp), catch icmp
1111    destined for 0.0.0.0/0, which is for incoming IPVS connections */
1112 static struct nf_hook_ops ip_vs_forward_icmp_ops = {
1113         .hook           = ip_vs_forward_icmp,
1114         .owner          = THIS_MODULE,
1115         .pf             = PF_INET,
1116         .hooknum        = NF_IP_FORWARD,
1117         .priority       = 99,
1118 };
1119
1120 /* Before the netfilter connection tracking, exit from POST_ROUTING */
1121 static struct nf_hook_ops ip_vs_post_routing_ops = {
1122         .hook           = ip_vs_post_routing,
1123         .owner          = THIS_MODULE,
1124         .pf             = PF_INET,
1125         .hooknum        = NF_IP_POST_ROUTING,
1126         .priority       = NF_IP_PRI_NAT_SRC-1,
1127 };
1128
1129
1130 /*
1131  *      Initialize IP Virtual Server
1132  */
1133 static int __init ip_vs_init(void)
1134 {
1135         int ret;
1136
1137         ret = ip_vs_control_init();
1138         if (ret < 0) {
1139                 IP_VS_ERR("can't setup control.\n");
1140                 goto cleanup_nothing;
1141         }
1142
1143         ip_vs_protocol_init();
1144
1145         ret = ip_vs_app_init();
1146         if (ret < 0) {
1147                 IP_VS_ERR("can't setup application helper.\n");
1148                 goto cleanup_protocol;
1149         }
1150
1151         ret = ip_vs_conn_init();
1152         if (ret < 0) {
1153                 IP_VS_ERR("can't setup connection table.\n");
1154                 goto cleanup_app;
1155         }
1156
1157         ret = nf_register_hook(&ip_vs_in_ops);
1158         if (ret < 0) {
1159                 IP_VS_ERR("can't register in hook.\n");
1160                 goto cleanup_conn;
1161         }
1162
1163         ret = nf_register_hook(&ip_vs_out_ops);
1164         if (ret < 0) {
1165                 IP_VS_ERR("can't register out hook.\n");
1166                 goto cleanup_inops;
1167         }
1168         ret = nf_register_hook(&ip_vs_post_routing_ops);
1169         if (ret < 0) {
1170                 IP_VS_ERR("can't register post_routing hook.\n");
1171                 goto cleanup_outops;
1172         }
1173         ret = nf_register_hook(&ip_vs_forward_icmp_ops);
1174         if (ret < 0) {
1175                 IP_VS_ERR("can't register forward_icmp hook.\n");
1176                 goto cleanup_postroutingops;
1177         }
1178
1179         IP_VS_INFO("ipvs loaded.\n");
1180         return ret;
1181
1182   cleanup_postroutingops:
1183         nf_unregister_hook(&ip_vs_post_routing_ops);
1184   cleanup_outops:
1185         nf_unregister_hook(&ip_vs_out_ops);
1186   cleanup_inops:
1187         nf_unregister_hook(&ip_vs_in_ops);
1188   cleanup_conn:
1189         ip_vs_conn_cleanup();
1190   cleanup_app:
1191         ip_vs_app_cleanup();
1192   cleanup_protocol:
1193         ip_vs_protocol_cleanup();
1194         ip_vs_control_cleanup();
1195   cleanup_nothing:
1196         return ret;
1197 }
1198
1199 static void __exit ip_vs_cleanup(void)
1200 {
1201         nf_unregister_hook(&ip_vs_forward_icmp_ops);
1202         nf_unregister_hook(&ip_vs_post_routing_ops);
1203         nf_unregister_hook(&ip_vs_out_ops);
1204         nf_unregister_hook(&ip_vs_in_ops);
1205         ip_vs_conn_cleanup();
1206         ip_vs_app_cleanup();
1207         ip_vs_protocol_cleanup();
1208         ip_vs_control_cleanup();
1209         IP_VS_INFO("ipvs unloaded.\n");
1210 }
1211
1212 module_init(ip_vs_init);
1213 module_exit(ip_vs_cleanup);
1214 MODULE_LICENSE("GPL");