patch-2_6_7-vs1_9_1_12
[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];
387
388         if (skb_copy_bits(skb, iph->ihl*4, ports, sizeof(ports)) < 0)
389                 return NULL;
390
391         /*
392          *    Persistent service
393          */
394         if (svc->flags & IP_VS_SVC_F_PERSISTENT)
395                 return ip_vs_sched_persist(svc, skb, ports);
396
397         /*
398          *    Non-persistent service
399          */
400         if (!svc->fwmark && ports[1] != svc->port) {
401                 if (!svc->port)
402                         IP_VS_ERR("Schedule: port zero only supported "
403                                   "in persistent services, "
404                                   "check your ipvs configuration\n");
405                 return NULL;
406         }
407
408         dest = svc->scheduler->schedule(svc, skb);
409         if (dest == NULL) {
410                 IP_VS_DBG(1, "Schedule: no dest found.\n");
411                 return NULL;
412         }
413
414         /*
415          *    Create a connection entry.
416          */
417         cp = ip_vs_conn_new(iph->protocol,
418                             iph->saddr, ports[0],
419                             iph->daddr, ports[1],
420                             dest->addr, dest->port?dest->port:ports[1],
421                             0,
422                             dest);
423         if (cp == NULL)
424                 return NULL;
425
426         IP_VS_DBG(6, "Schedule fwd:%c c:%u.%u.%u.%u:%u v:%u.%u.%u.%u:%u "
427                   "d:%u.%u.%u.%u:%u flg:%X cnt:%d\n",
428                   ip_vs_fwd_tag(cp),
429                   NIPQUAD(cp->caddr), ntohs(cp->cport),
430                   NIPQUAD(cp->vaddr), ntohs(cp->vport),
431                   NIPQUAD(cp->daddr), ntohs(cp->dport),
432                   cp->flags, atomic_read(&cp->refcnt));
433
434         ip_vs_conn_stats(cp, svc);
435         return cp;
436 }
437
438
439 /*
440  *  Pass or drop the packet.
441  *  Called by ip_vs_in, when the virtual service is available but
442  *  no destination is available for a new connection.
443  */
444 int ip_vs_leave(struct ip_vs_service *svc, struct sk_buff *skb,
445                 struct ip_vs_protocol *pp)
446 {
447         __u16 ports[2];
448         struct iphdr *iph = skb->nh.iph;
449
450         if (skb_copy_bits(skb, iph->ihl*4, ports, sizeof(ports)) < 0) {
451                 ip_vs_service_put(svc);
452                 return NF_DROP;
453         }
454
455         /* if it is fwmark-based service, the cache_bypass sysctl is up
456            and the destination is RTN_UNICAST (and not local), then create
457            a cache_bypass connection entry */
458         if (sysctl_ip_vs_cache_bypass && svc->fwmark
459             && (inet_addr_type(iph->daddr) == RTN_UNICAST)) {
460                 int ret, cs;
461                 struct ip_vs_conn *cp;
462
463                 ip_vs_service_put(svc);
464
465                 /* create a new connection entry */
466                 IP_VS_DBG(6, "ip_vs_leave: create a cache_bypass entry\n");
467                 cp = ip_vs_conn_new(iph->protocol,
468                                     iph->saddr, ports[0],
469                                     iph->daddr, ports[1],
470                                     0, 0,
471                                     IP_VS_CONN_F_BYPASS,
472                                     NULL);
473                 if (cp == NULL)
474                         return NF_DROP;
475
476                 /* statistics */
477                 ip_vs_in_stats(cp, skb);
478
479                 /* set state */
480                 cs = ip_vs_set_state(cp, IP_VS_DIR_INPUT, skb, pp);
481
482                 /* transmit the first SYN packet */
483                 ret = cp->packet_xmit(skb, cp, pp);
484                 /* do not touch skb anymore */
485
486                 atomic_inc(&cp->in_pkts);
487                 ip_vs_conn_put(cp);
488                 return ret;
489         }
490
491         /*
492          * When the virtual ftp service is presented, packets destined
493          * for other services on the VIP may get here (except services
494          * listed in the ipvs table), pass the packets, because it is
495          * not ipvs job to decide to drop the packets.
496          */
497         if ((svc->port == FTPPORT) && (ports[1] != FTPPORT)) {
498                 ip_vs_service_put(svc);
499                 return NF_ACCEPT;
500         }
501
502         ip_vs_service_put(svc);
503
504         /*
505          * Notify the client that the destination is unreachable, and
506          * release the socket buffer.
507          * Since it is in IP layer, the TCP socket is not actually
508          * created, the TCP RST packet cannot be sent, instead that
509          * ICMP_PORT_UNREACH is sent here no matter it is TCP/UDP. --WZ
510          */
511         icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
512         return NF_DROP;
513 }
514
515
516 /*
517  *      It is hooked before NF_IP_PRI_NAT_SRC at the NF_IP_POST_ROUTING
518  *      chain, and is used for VS/NAT.
519  *      It detects packets for VS/NAT connections and sends the packets
520  *      immediately. This can avoid that iptable_nat mangles the packets
521  *      for VS/NAT.
522  */
523 static unsigned int ip_vs_post_routing(unsigned int hooknum,
524                                        struct sk_buff **pskb,
525                                        const struct net_device *in,
526                                        const struct net_device *out,
527                                        int (*okfn)(struct sk_buff *))
528 {
529         if (!((*pskb)->nfcache & NFC_IPVS_PROPERTY))
530                 return NF_ACCEPT;
531
532         /* The packet was sent from IPVS, exit this chain */
533         (*okfn)(*pskb);
534
535         return NF_STOLEN;
536 }
537
538 u16 ip_vs_checksum_complete(struct sk_buff *skb, int offset)
539 {
540         return (u16) csum_fold(skb_checksum(skb, offset, skb->len - offset, 0));
541 }
542
543 static inline struct sk_buff *
544 ip_vs_gather_frags(struct sk_buff *skb)
545 {
546         skb = ip_defrag(skb);
547         if (skb)
548                 ip_send_check(skb->nh.iph);
549         return skb;
550 }
551
552 /*
553  * Packet has been made sufficiently writable in caller
554  * - inout: 1=in->out, 0=out->in
555  */
556 void ip_vs_nat_icmp(struct sk_buff *skb, struct ip_vs_protocol *pp,
557                     struct ip_vs_conn *cp, int inout)
558 {
559         struct iphdr *iph        = skb->nh.iph;
560         unsigned int icmp_offset = iph->ihl*4;
561         struct icmphdr *icmph    = (struct icmphdr *)(skb->nh.raw + icmp_offset);
562         struct iphdr *ciph       = (struct iphdr *)(icmph + 1);
563
564         if (inout) {
565                 iph->saddr = cp->vaddr;
566                 ip_send_check(iph);
567                 ciph->daddr = cp->vaddr;
568                 ip_send_check(ciph);
569         } else {
570                 iph->daddr = cp->daddr;
571                 ip_send_check(iph);
572                 ciph->saddr = cp->daddr;
573                 ip_send_check(ciph);
574         }
575
576         /* the TCP/UDP port */
577         if (IPPROTO_TCP == ciph->protocol || IPPROTO_UDP == ciph->protocol) {
578                 __u16 *ports = (void *)ciph + ciph->ihl*4;
579
580                 if (inout)
581                         ports[1] = cp->vport;
582                 else
583                         ports[0] = cp->dport;
584         }
585
586         /* And finally the ICMP checksum */
587         icmph->checksum = 0;
588         icmph->checksum = ip_vs_checksum_complete(skb, icmp_offset);
589         skb->ip_summed = CHECKSUM_UNNECESSARY;
590
591         if (inout)
592                 IP_VS_DBG_PKT(11, pp, skb, (void *)ciph - (void *)iph,
593                         "Forwarding altered outgoing ICMP");
594         else
595                 IP_VS_DBG_PKT(11, pp, skb, (void *)ciph - (void *)iph,
596                         "Forwarding altered incoming ICMP");
597 }
598
599 /*
600  *      Handle ICMP messages in the inside-to-outside direction (outgoing).
601  *      Find any that might be relevant, check against existing connections,
602  *      forward to the right destination host if relevant.
603  *      Currently handles error types - unreachable, quench, ttl exceeded.
604  *      (Only used in VS/NAT)
605  */
606 static int ip_vs_out_icmp(struct sk_buff **pskb, int *related)
607 {
608         struct sk_buff *skb = *pskb;
609         struct iphdr *iph;
610         struct icmphdr  icmph;
611         struct iphdr    ciph;   /* The ip header contained within the ICMP */
612         struct ip_vs_conn *cp;
613         struct ip_vs_protocol *pp;
614         unsigned int offset, ihl, verdict;
615
616         *related = 1;
617
618         /* reassemble IP fragments */
619         if (skb->nh.iph->frag_off & __constant_htons(IP_MF|IP_OFFSET)) {
620                 skb = ip_vs_gather_frags(skb);
621                 if (!skb)
622                         return NF_STOLEN;
623                 *pskb = skb;
624         }
625
626         iph = skb->nh.iph;
627         offset = ihl = iph->ihl * 4;
628         if (skb_copy_bits(skb, offset, &icmph, sizeof(icmph)) < 0)
629                 return NF_DROP;
630
631         IP_VS_DBG(12, "Outgoing ICMP (%d,%d) %u.%u.%u.%u->%u.%u.%u.%u\n",
632                   icmph.type, ntohs(icmp_id(&icmph)),
633                   NIPQUAD(iph->saddr), NIPQUAD(iph->daddr));
634
635         /*
636          * Work through seeing if this is for us.
637          * These checks are supposed to be in an order that means easy
638          * things are checked first to speed up processing.... however
639          * this means that some packets will manage to get a long way
640          * down this stack and then be rejected, but that's life.
641          */
642         if ((icmph.type != ICMP_DEST_UNREACH) &&
643             (icmph.type != ICMP_SOURCE_QUENCH) &&
644             (icmph.type != ICMP_TIME_EXCEEDED)) {
645                 *related = 0;
646                 return NF_ACCEPT;
647         }
648
649         /* Now find the contained IP header */
650         offset += sizeof(icmph);
651         if (skb_copy_bits(skb, offset, &ciph, sizeof(ciph)) < 0)
652                 return NF_ACCEPT; /* The packet looks wrong, ignore */
653
654         pp = ip_vs_proto_get(ciph.protocol);
655         if (!pp)
656                 return NF_ACCEPT;
657
658         /* Is the embedded protocol header present? */
659         if (unlikely(ciph.frag_off & __constant_htons(IP_OFFSET) &&
660                      pp->dont_defrag))
661                 return NF_ACCEPT;
662
663         IP_VS_DBG_PKT(11, pp, skb, offset, "Checking outgoing ICMP for");
664
665         offset += ciph.ihl * 4;
666
667         /* The embedded headers contain source and dest in reverse order */
668         cp = pp->conn_out_get(skb, pp, &ciph, offset, 1);
669         if (!cp)
670                 return NF_ACCEPT;
671
672         verdict = NF_DROP;
673
674         if (IP_VS_FWD_METHOD(cp) != 0) {
675                 IP_VS_ERR("shouldn't reach here, because the box is on the"
676                           "half connection in the tun/dr module.\n");
677         }
678
679         /* Ensure the checksum is correct */
680         if (skb->ip_summed != CHECKSUM_UNNECESSARY &&
681             ip_vs_checksum_complete(skb, ihl)) {
682                 /* Failed checksum! */
683                 IP_VS_DBG(1, "Forward ICMP: failed checksum from %d.%d.%d.%d!\n",
684                           NIPQUAD(iph->saddr));
685                 goto out;
686         }
687
688         if (IPPROTO_TCP == ciph.protocol || IPPROTO_UDP == ciph.protocol)
689                 offset += 2 * sizeof(__u16);
690         if (!ip_vs_make_skb_writable(pskb, offset))
691                 goto out;
692         skb = *pskb;
693
694         ip_vs_nat_icmp(skb, pp, cp, 1);
695
696         /* do the statistics and put it back */
697         ip_vs_out_stats(cp, skb);
698
699         skb->nfcache |= NFC_IPVS_PROPERTY;
700         verdict = NF_ACCEPT;
701
702   out:
703         __ip_vs_conn_put(cp);
704
705         return verdict;
706 }
707
708 static inline int is_tcp_reset(const struct sk_buff *skb)
709 {
710         struct tcphdr tcph;
711
712         if (skb_copy_bits(skb, skb->nh.iph->ihl * 4, &tcph, sizeof(tcph)) < 0)
713                 return 0;
714         return tcph.rst;
715 }
716
717 /*
718  *      It is hooked at the NF_IP_FORWARD chain, used only for VS/NAT.
719  *      Check if outgoing packet belongs to the established ip_vs_conn,
720  *      rewrite addresses of the packet and send it on its way...
721  */
722 static unsigned int
723 ip_vs_out(unsigned int hooknum, struct sk_buff **pskb,
724           const struct net_device *in, const struct net_device *out,
725           int (*okfn)(struct sk_buff *))
726 {
727         struct sk_buff  *skb = *pskb;
728         struct iphdr    *iph;
729         struct ip_vs_protocol *pp;
730         struct ip_vs_conn *cp;
731         int ihl;
732
733         EnterFunction(11);
734
735         if (skb->nfcache & NFC_IPVS_PROPERTY)
736                 return NF_ACCEPT;
737
738         if (skb->ip_summed == CHECKSUM_HW) {
739                 if (skb_checksum_help(pskb, (out == NULL)))
740                         return NF_DROP;
741                 if (skb != *pskb)
742                         skb = *pskb;
743         }
744
745         iph = skb->nh.iph;
746         if (unlikely(iph->protocol == IPPROTO_ICMP)) {
747                 int related, verdict = ip_vs_out_icmp(pskb, &related);
748
749                 if (related)
750                         return verdict;
751                 skb = *pskb;
752                 iph = skb->nh.iph;
753         }
754
755         pp = ip_vs_proto_get(iph->protocol);
756         if (unlikely(!pp))
757                 return NF_ACCEPT;
758
759         /* reassemble IP fragments */
760         if (unlikely(iph->frag_off & __constant_htons(IP_MF|IP_OFFSET) &&
761                      !pp->dont_defrag)) {
762                 skb = ip_vs_gather_frags(skb);
763                 if (!skb)
764                         return NF_STOLEN;
765                 iph = skb->nh.iph;
766                 *pskb = skb;
767         }
768
769         ihl = iph->ihl << 2;
770
771         /*
772          * Check if the packet belongs to an existing entry
773          */
774         cp = pp->conn_out_get(skb, pp, iph, ihl, 0);
775
776         if (unlikely(!cp)) {
777                 if (sysctl_ip_vs_nat_icmp_send &&
778                     (pp->protocol == IPPROTO_TCP ||
779                      pp->protocol == IPPROTO_UDP)) {
780                         __u16 ports[2];
781
782                         if (skb_copy_bits(skb, ihl, ports, sizeof(ports)) < 0)
783                                 return NF_ACCEPT;       /* Not for me */
784                         if (ip_vs_lookup_real_service(iph->protocol,
785                                                       iph->saddr, ports[0])) {
786                                 /*
787                                  * Notify the real server: there is no
788                                  * existing entry if it is not RST
789                                  * packet or not TCP packet.
790                                  */
791                                 if (iph->protocol != IPPROTO_TCP
792                                     || !is_tcp_reset(skb)) {
793                                         icmp_send(skb,ICMP_DEST_UNREACH,
794                                                   ICMP_PORT_UNREACH, 0);
795                                         return NF_DROP;
796                                 }
797                         }
798                 }
799                 IP_VS_DBG_PKT(12, pp, skb, 0,
800                               "packet continues traversal as normal");
801                 return NF_ACCEPT;
802         }
803
804         IP_VS_DBG_PKT(11, pp, skb, 0, "Outgoing packet");
805
806         if (!ip_vs_make_skb_writable(pskb, ihl))
807                 goto drop;
808
809         /* mangle the packet */
810         if (pp->snat_handler && !pp->snat_handler(pskb, pp, cp))
811                 goto drop;
812         skb = *pskb;
813         skb->nh.iph->saddr = cp->vaddr;
814         ip_send_check(skb->nh.iph);
815
816         IP_VS_DBG_PKT(10, pp, skb, 0, "After SNAT");
817
818         ip_vs_out_stats(cp, skb);
819         ip_vs_set_state(cp, IP_VS_DIR_OUTPUT, skb, pp);
820         ip_vs_conn_put(cp);
821
822         skb->nfcache |= NFC_IPVS_PROPERTY;
823
824         LeaveFunction(11);
825         return NF_ACCEPT;
826
827   drop:
828         ip_vs_conn_put(cp);
829         kfree_skb(*pskb);
830         return NF_STOLEN;
831 }
832
833
834 /*
835  *      Check if the packet is for VS/NAT connections, then send it
836  *      immediately.
837  *      Called by ip_fw_compact to detect packets for VS/NAT before
838  *      they are changed by ipchains masquerading code.
839  */
840 unsigned int
841 check_for_ip_vs_out(struct sk_buff **pskb, int (*okfn)(struct sk_buff *))
842 {
843         unsigned int ret;
844
845         ret = ip_vs_out(NF_IP_FORWARD, pskb, NULL, NULL, NULL);
846         if (ret != NF_ACCEPT) {
847                 return ret;
848         } else {
849                 /* send the packet immediately if it is already mangled
850                    by ip_vs_out */
851                 if ((*pskb)->nfcache & NFC_IPVS_PROPERTY) {
852                         (*okfn)(*pskb);
853                         return NF_STOLEN;
854                 }
855         }
856         return NF_ACCEPT;
857 }
858
859 /*
860  *      Handle ICMP messages in the outside-to-inside direction (incoming).
861  *      Find any that might be relevant, check against existing connections,
862  *      forward to the right destination host if relevant.
863  *      Currently handles error types - unreachable, quench, ttl exceeded.
864  */
865 static int ip_vs_in_icmp(struct sk_buff **pskb, int *related)
866 {
867         struct sk_buff *skb = *pskb;
868         struct iphdr *iph;
869         struct icmphdr  icmph;
870         struct iphdr    ciph;   /* The ip header contained within the ICMP */
871         struct ip_vs_conn *cp;
872         struct ip_vs_protocol *pp;
873         unsigned int offset, ihl, verdict;
874
875         *related = 1;
876
877         /* reassemble IP fragments */
878         if (skb->nh.iph->frag_off & __constant_htons(IP_MF|IP_OFFSET)) {
879                 skb = ip_vs_gather_frags(skb);
880                 if (!skb)
881                         return NF_STOLEN;
882                 *pskb = skb;
883         }
884
885         iph = skb->nh.iph;
886         offset = ihl = iph->ihl * 4;
887         if (skb_copy_bits(skb, offset, &icmph, sizeof(icmph)) < 0)
888                 return NF_DROP;
889
890         IP_VS_DBG(12, "Incoming ICMP (%d,%d) %u.%u.%u.%u->%u.%u.%u.%u\n",
891                   icmph.type, ntohs(icmp_id(&icmph)),
892                   NIPQUAD(iph->saddr), NIPQUAD(iph->daddr));
893
894         /*
895          * Work through seeing if this is for us.
896          * These checks are supposed to be in an order that means easy
897          * things are checked first to speed up processing.... however
898          * this means that some packets will manage to get a long way
899          * down this stack and then be rejected, but that's life.
900          */
901         if ((icmph.type != ICMP_DEST_UNREACH) &&
902             (icmph.type != ICMP_SOURCE_QUENCH) &&
903             (icmph.type != ICMP_TIME_EXCEEDED)) {
904                 *related = 0;
905                 return NF_ACCEPT;
906         }
907
908         /* Now find the contained IP header */
909         offset += sizeof(icmph);
910         if (skb_copy_bits(skb, offset, &ciph, sizeof(ciph)) < 0)
911                 return NF_ACCEPT; /* The packet looks wrong, ignore */
912
913         pp = ip_vs_proto_get(ciph.protocol);
914         if (!pp)
915                 return NF_ACCEPT;
916
917         /* Is the embedded protocol header present? */
918         if (unlikely(ciph.frag_off & __constant_htons(IP_OFFSET) &&
919                      pp->dont_defrag))
920                 return NF_ACCEPT;
921
922         IP_VS_DBG_PKT(11, pp, skb, offset, "Checking incoming ICMP for");
923
924         offset += ciph.ihl * 4;
925
926         /* The embedded headers contain source and dest in reverse order */
927         cp = pp->conn_in_get(skb, pp, &ciph, offset, 1);
928         if (!cp)
929                 return NF_ACCEPT;
930
931         verdict = NF_DROP;
932
933         /* Ensure the checksum is correct */
934         if (skb->ip_summed != CHECKSUM_UNNECESSARY &&
935             ip_vs_checksum_complete(skb, ihl)) {
936                 /* Failed checksum! */
937                 IP_VS_DBG(1, "Incoming ICMP: failed checksum from %d.%d.%d.%d!\n",
938                           NIPQUAD(iph->saddr));
939                 goto out;
940         }
941
942         /* do the statistics and put it back */
943         ip_vs_in_stats(cp, skb);
944         if (IPPROTO_TCP == ciph.protocol || IPPROTO_UDP == ciph.protocol)
945                 offset += 2 * sizeof(__u16);
946         verdict = ip_vs_icmp_xmit(skb, cp, pp, offset);
947         /* do not touch skb anymore */
948
949   out:
950         __ip_vs_conn_put(cp);
951
952         return verdict;
953 }
954
955 /*
956  *      Check if it's for virtual services, look it up,
957  *      and send it on its way...
958  */
959 static unsigned int
960 ip_vs_in(unsigned int hooknum, struct sk_buff **pskb,
961          const struct net_device *in, const struct net_device *out,
962          int (*okfn)(struct sk_buff *))
963 {
964         struct sk_buff  *skb = *pskb;
965         struct iphdr    *iph;
966         struct ip_vs_protocol *pp;
967         struct ip_vs_conn *cp;
968         int ret, restart;
969         int ihl;
970
971         /*
972          *      Big tappo: only PACKET_HOST (neither loopback nor mcasts)
973          *      ... don't know why 1st test DOES NOT include 2nd (?)
974          */
975         if (unlikely(skb->pkt_type != PACKET_HOST
976                      || skb->dev == &loopback_dev || skb->sk)) {
977                 IP_VS_DBG(12, "packet type=%d proto=%d daddr=%d.%d.%d.%d ignored\n",
978                           skb->pkt_type,
979                           skb->nh.iph->protocol,
980                           NIPQUAD(skb->nh.iph->daddr));
981                 return NF_ACCEPT;
982         }
983
984         if (skb->ip_summed == CHECKSUM_HW) {
985                 if (skb_checksum_help(pskb, (out == NULL)))
986                         return NF_DROP;
987                 if (skb != *pskb)
988                         skb = *pskb;
989         }
990
991         iph = skb->nh.iph;
992         if (unlikely(iph->protocol == IPPROTO_ICMP)) {
993                 int related, verdict = ip_vs_in_icmp(pskb, &related);
994
995                 if (related)
996                         return verdict;
997                 skb = *pskb;
998                 iph = skb->nh.iph;
999         }
1000
1001         /* Protocol supported? */
1002         pp = ip_vs_proto_get(iph->protocol);
1003         if (unlikely(!pp))
1004                 return NF_ACCEPT;
1005
1006         ihl = iph->ihl << 2;
1007
1008         /*
1009          * Check if the packet belongs to an existing connection entry
1010          */
1011         cp = pp->conn_in_get(skb, pp, iph, ihl, 0);
1012
1013         if (unlikely(!cp)) {
1014                 int v;
1015
1016                 if (!pp->conn_schedule(skb, pp, &v, &cp))
1017                         return v;
1018         }
1019
1020         if (unlikely(!cp)) {
1021                 /* sorry, all this trouble for a no-hit :) */
1022                 IP_VS_DBG_PKT(12, pp, skb, 0,
1023                               "packet continues traversal as normal");
1024                 return NF_ACCEPT;
1025         }
1026
1027         IP_VS_DBG_PKT(11, pp, skb, 0, "Incoming packet");
1028
1029         /* Check the server status */
1030         if (cp->dest && !(cp->dest->flags & IP_VS_DEST_F_AVAILABLE)) {
1031                 /* the destination server is not availabe */
1032
1033                 if (sysctl_ip_vs_expire_nodest_conn) {
1034                         /* try to expire the connection immediately */
1035                         ip_vs_conn_expire_now(cp);
1036                 } else {
1037                         /* don't restart its timer, and silently
1038                            drop the packet. */
1039                         __ip_vs_conn_put(cp);
1040                 }
1041                 return NF_DROP;
1042         }
1043
1044         ip_vs_in_stats(cp, skb);
1045         restart = ip_vs_set_state(cp, IP_VS_DIR_INPUT, skb, pp);
1046         if (cp->packet_xmit)
1047                 ret = cp->packet_xmit(skb, cp, pp);
1048                 /* do not touch skb anymore */
1049         else {
1050                 IP_VS_DBG_RL("warning: packet_xmit is null");
1051                 ret = NF_ACCEPT;
1052         }
1053
1054         /* increase its packet counter and check if it is needed
1055            to be synchronized */
1056         atomic_inc(&cp->in_pkts);
1057         if ((ip_vs_sync_state & IP_VS_STATE_MASTER) &&
1058             (cp->protocol != IPPROTO_TCP ||
1059              cp->state == IP_VS_TCP_S_ESTABLISHED) &&
1060             (atomic_read(&cp->in_pkts) % sysctl_ip_vs_sync_threshold[1]
1061              == sysctl_ip_vs_sync_threshold[0]))
1062                 ip_vs_sync_conn(cp);
1063
1064         ip_vs_conn_put(cp);
1065         return ret;
1066 }
1067
1068
1069 /*
1070  *      It is hooked at the NF_IP_FORWARD chain, in order to catch ICMP
1071  *      related packets destined for 0.0.0.0/0.
1072  *      When fwmark-based virtual service is used, such as transparent
1073  *      cache cluster, TCP packets can be marked and routed to ip_vs_in,
1074  *      but ICMP destined for 0.0.0.0/0 cannot not be easily marked and
1075  *      sent to ip_vs_in_icmp. So, catch them at the NF_IP_FORWARD chain
1076  *      and send them to ip_vs_in_icmp.
1077  */
1078 static unsigned int
1079 ip_vs_forward_icmp(unsigned int hooknum, struct sk_buff **pskb,
1080                    const struct net_device *in, const struct net_device *out,
1081                    int (*okfn)(struct sk_buff *))
1082 {
1083         int r;
1084
1085         if ((*pskb)->nh.iph->protocol != IPPROTO_ICMP)
1086                 return NF_ACCEPT;
1087
1088         return ip_vs_in_icmp(pskb, &r);
1089 }
1090
1091
1092 /* After packet filtering, forward packet through VS/DR, VS/TUN,
1093    or VS/NAT(change destination), so that filtering rules can be
1094    applied to IPVS. */
1095 static struct nf_hook_ops ip_vs_in_ops = {
1096         .hook           = ip_vs_in,
1097         .owner          = THIS_MODULE,
1098         .pf             = PF_INET,
1099         .hooknum        = NF_IP_LOCAL_IN,
1100         .priority       = 100,
1101 };
1102
1103 /* After packet filtering, change source only for VS/NAT */
1104 static struct nf_hook_ops ip_vs_out_ops = {
1105         .hook           = ip_vs_out,
1106         .owner          = THIS_MODULE,
1107         .pf             = PF_INET,
1108         .hooknum        = NF_IP_FORWARD,
1109         .priority       = 100,
1110 };
1111
1112 /* After packet filtering (but before ip_vs_out_icmp), catch icmp
1113    destined for 0.0.0.0/0, which is for incoming IPVS connections */
1114 static struct nf_hook_ops ip_vs_forward_icmp_ops = {
1115         .hook           = ip_vs_forward_icmp,
1116         .owner          = THIS_MODULE,
1117         .pf             = PF_INET,
1118         .hooknum        = NF_IP_FORWARD,
1119         .priority       = 99,
1120 };
1121
1122 /* Before the netfilter connection tracking, exit from POST_ROUTING */
1123 static struct nf_hook_ops ip_vs_post_routing_ops = {
1124         .hook           = ip_vs_post_routing,
1125         .owner          = THIS_MODULE,
1126         .pf             = PF_INET,
1127         .hooknum        = NF_IP_POST_ROUTING,
1128         .priority       = NF_IP_PRI_NAT_SRC-1,
1129 };
1130
1131
1132 /*
1133  *      Initialize IP Virtual Server
1134  */
1135 static int __init ip_vs_init(void)
1136 {
1137         int ret;
1138
1139         ret = ip_vs_control_init();
1140         if (ret < 0) {
1141                 IP_VS_ERR("can't setup control.\n");
1142                 goto cleanup_nothing;
1143         }
1144
1145         ip_vs_protocol_init();
1146
1147         ret = ip_vs_app_init();
1148         if (ret < 0) {
1149                 IP_VS_ERR("can't setup application helper.\n");
1150                 goto cleanup_protocol;
1151         }
1152
1153         ret = ip_vs_conn_init();
1154         if (ret < 0) {
1155                 IP_VS_ERR("can't setup connection table.\n");
1156                 goto cleanup_app;
1157         }
1158
1159         ret = nf_register_hook(&ip_vs_in_ops);
1160         if (ret < 0) {
1161                 IP_VS_ERR("can't register in hook.\n");
1162                 goto cleanup_conn;
1163         }
1164
1165         ret = nf_register_hook(&ip_vs_out_ops);
1166         if (ret < 0) {
1167                 IP_VS_ERR("can't register out hook.\n");
1168                 goto cleanup_inops;
1169         }
1170         ret = nf_register_hook(&ip_vs_post_routing_ops);
1171         if (ret < 0) {
1172                 IP_VS_ERR("can't register post_routing hook.\n");
1173                 goto cleanup_outops;
1174         }
1175         ret = nf_register_hook(&ip_vs_forward_icmp_ops);
1176         if (ret < 0) {
1177                 IP_VS_ERR("can't register forward_icmp hook.\n");
1178                 goto cleanup_postroutingops;
1179         }
1180
1181         IP_VS_INFO("ipvs loaded.\n");
1182         return ret;
1183
1184   cleanup_postroutingops:
1185         nf_unregister_hook(&ip_vs_post_routing_ops);
1186   cleanup_outops:
1187         nf_unregister_hook(&ip_vs_out_ops);
1188   cleanup_inops:
1189         nf_unregister_hook(&ip_vs_in_ops);
1190   cleanup_conn:
1191         ip_vs_conn_cleanup();
1192   cleanup_app:
1193         ip_vs_app_cleanup();
1194   cleanup_protocol:
1195         ip_vs_protocol_cleanup();
1196         ip_vs_control_cleanup();
1197   cleanup_nothing:
1198         return ret;
1199 }
1200
1201 static void __exit ip_vs_cleanup(void)
1202 {
1203         nf_unregister_hook(&ip_vs_forward_icmp_ops);
1204         nf_unregister_hook(&ip_vs_post_routing_ops);
1205         nf_unregister_hook(&ip_vs_out_ops);
1206         nf_unregister_hook(&ip_vs_in_ops);
1207         ip_vs_conn_cleanup();
1208         ip_vs_app_cleanup();
1209         ip_vs_protocol_cleanup();
1210         ip_vs_control_cleanup();
1211         IP_VS_INFO("ipvs unloaded.\n");
1212 }
1213
1214 module_init(ip_vs_init);
1215 module_exit(ip_vs_cleanup);
1216 MODULE_LICENSE("GPL");