ipvs: Pass ipvs into conn_out_get
[cascardo/linux.git] / net / netfilter / 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  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
9  *              Peter Kese <peter.kese@ijs.si>
10  *              Julian Anastasov <ja@ssi.bg>
11  *
12  *              This program is free software; you can redistribute it and/or
13  *              modify it under the terms of the GNU General Public License
14  *              as published by the Free Software Foundation; either version
15  *              2 of the License, or (at your option) any later version.
16  *
17  * The IPVS code for kernel 2.2 was done by Wensong Zhang and Peter Kese,
18  * with changes/fixes from Julian Anastasov, Lars Marowsky-Bree, Horms
19  * and others.
20  *
21  * Changes:
22  *      Paul `Rusty' Russell            properly handle non-linear skbs
23  *      Harald Welte                    don't use nfcache
24  *
25  */
26
27 #define KMSG_COMPONENT "IPVS"
28 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
29
30 #include <linux/module.h>
31 #include <linux/kernel.h>
32 #include <linux/ip.h>
33 #include <linux/tcp.h>
34 #include <linux/sctp.h>
35 #include <linux/icmp.h>
36 #include <linux/slab.h>
37
38 #include <net/ip.h>
39 #include <net/tcp.h>
40 #include <net/udp.h>
41 #include <net/icmp.h>                   /* for icmp_send */
42 #include <net/route.h>
43 #include <net/ip6_checksum.h>
44 #include <net/netns/generic.h>          /* net_generic() */
45
46 #include <linux/netfilter.h>
47 #include <linux/netfilter_ipv4.h>
48
49 #ifdef CONFIG_IP_VS_IPV6
50 #include <net/ipv6.h>
51 #include <linux/netfilter_ipv6.h>
52 #include <net/ip6_route.h>
53 #endif
54
55 #include <net/ip_vs.h>
56
57
58 EXPORT_SYMBOL(register_ip_vs_scheduler);
59 EXPORT_SYMBOL(unregister_ip_vs_scheduler);
60 EXPORT_SYMBOL(ip_vs_proto_name);
61 EXPORT_SYMBOL(ip_vs_conn_new);
62 EXPORT_SYMBOL(ip_vs_conn_in_get);
63 EXPORT_SYMBOL(ip_vs_conn_out_get);
64 #ifdef CONFIG_IP_VS_PROTO_TCP
65 EXPORT_SYMBOL(ip_vs_tcp_conn_listen);
66 #endif
67 EXPORT_SYMBOL(ip_vs_conn_put);
68 #ifdef CONFIG_IP_VS_DEBUG
69 EXPORT_SYMBOL(ip_vs_get_debug_level);
70 #endif
71
72 static int ip_vs_net_id __read_mostly;
73 /* netns cnt used for uniqueness */
74 static atomic_t ipvs_netns_cnt = ATOMIC_INIT(0);
75
76 /* ID used in ICMP lookups */
77 #define icmp_id(icmph)          (((icmph)->un).echo.id)
78 #define icmpv6_id(icmph)        (icmph->icmp6_dataun.u_echo.identifier)
79
80 const char *ip_vs_proto_name(unsigned int proto)
81 {
82         static char buf[20];
83
84         switch (proto) {
85         case IPPROTO_IP:
86                 return "IP";
87         case IPPROTO_UDP:
88                 return "UDP";
89         case IPPROTO_TCP:
90                 return "TCP";
91         case IPPROTO_SCTP:
92                 return "SCTP";
93         case IPPROTO_ICMP:
94                 return "ICMP";
95 #ifdef CONFIG_IP_VS_IPV6
96         case IPPROTO_ICMPV6:
97                 return "ICMPv6";
98 #endif
99         default:
100                 sprintf(buf, "IP_%u", proto);
101                 return buf;
102         }
103 }
104
105 void ip_vs_init_hash_table(struct list_head *table, int rows)
106 {
107         while (--rows >= 0)
108                 INIT_LIST_HEAD(&table[rows]);
109 }
110
111 static inline void
112 ip_vs_in_stats(struct ip_vs_conn *cp, struct sk_buff *skb)
113 {
114         struct ip_vs_dest *dest = cp->dest;
115         struct netns_ipvs *ipvs = net_ipvs(skb_net(skb));
116
117         if (dest && (dest->flags & IP_VS_DEST_F_AVAILABLE)) {
118                 struct ip_vs_cpu_stats *s;
119                 struct ip_vs_service *svc;
120
121                 s = this_cpu_ptr(dest->stats.cpustats);
122                 u64_stats_update_begin(&s->syncp);
123                 s->cnt.inpkts++;
124                 s->cnt.inbytes += skb->len;
125                 u64_stats_update_end(&s->syncp);
126
127                 rcu_read_lock();
128                 svc = rcu_dereference(dest->svc);
129                 s = this_cpu_ptr(svc->stats.cpustats);
130                 u64_stats_update_begin(&s->syncp);
131                 s->cnt.inpkts++;
132                 s->cnt.inbytes += skb->len;
133                 u64_stats_update_end(&s->syncp);
134                 rcu_read_unlock();
135
136                 s = this_cpu_ptr(ipvs->tot_stats.cpustats);
137                 u64_stats_update_begin(&s->syncp);
138                 s->cnt.inpkts++;
139                 s->cnt.inbytes += skb->len;
140                 u64_stats_update_end(&s->syncp);
141         }
142 }
143
144
145 static inline void
146 ip_vs_out_stats(struct ip_vs_conn *cp, struct sk_buff *skb)
147 {
148         struct ip_vs_dest *dest = cp->dest;
149         struct netns_ipvs *ipvs = net_ipvs(skb_net(skb));
150
151         if (dest && (dest->flags & IP_VS_DEST_F_AVAILABLE)) {
152                 struct ip_vs_cpu_stats *s;
153                 struct ip_vs_service *svc;
154
155                 s = this_cpu_ptr(dest->stats.cpustats);
156                 u64_stats_update_begin(&s->syncp);
157                 s->cnt.outpkts++;
158                 s->cnt.outbytes += skb->len;
159                 u64_stats_update_end(&s->syncp);
160
161                 rcu_read_lock();
162                 svc = rcu_dereference(dest->svc);
163                 s = this_cpu_ptr(svc->stats.cpustats);
164                 u64_stats_update_begin(&s->syncp);
165                 s->cnt.outpkts++;
166                 s->cnt.outbytes += skb->len;
167                 u64_stats_update_end(&s->syncp);
168                 rcu_read_unlock();
169
170                 s = this_cpu_ptr(ipvs->tot_stats.cpustats);
171                 u64_stats_update_begin(&s->syncp);
172                 s->cnt.outpkts++;
173                 s->cnt.outbytes += skb->len;
174                 u64_stats_update_end(&s->syncp);
175         }
176 }
177
178
179 static inline void
180 ip_vs_conn_stats(struct ip_vs_conn *cp, struct ip_vs_service *svc)
181 {
182         struct netns_ipvs *ipvs = svc->ipvs;
183         struct ip_vs_cpu_stats *s;
184
185         s = this_cpu_ptr(cp->dest->stats.cpustats);
186         u64_stats_update_begin(&s->syncp);
187         s->cnt.conns++;
188         u64_stats_update_end(&s->syncp);
189
190         s = this_cpu_ptr(svc->stats.cpustats);
191         u64_stats_update_begin(&s->syncp);
192         s->cnt.conns++;
193         u64_stats_update_end(&s->syncp);
194
195         s = this_cpu_ptr(ipvs->tot_stats.cpustats);
196         u64_stats_update_begin(&s->syncp);
197         s->cnt.conns++;
198         u64_stats_update_end(&s->syncp);
199 }
200
201
202 static inline void
203 ip_vs_set_state(struct ip_vs_conn *cp, int direction,
204                 const struct sk_buff *skb,
205                 struct ip_vs_proto_data *pd)
206 {
207         if (likely(pd->pp->state_transition))
208                 pd->pp->state_transition(cp, direction, skb, pd);
209 }
210
211 static inline int
212 ip_vs_conn_fill_param_persist(const struct ip_vs_service *svc,
213                               struct sk_buff *skb, int protocol,
214                               const union nf_inet_addr *caddr, __be16 cport,
215                               const union nf_inet_addr *vaddr, __be16 vport,
216                               struct ip_vs_conn_param *p)
217 {
218         ip_vs_conn_fill_param(svc->ipvs, svc->af, protocol, caddr, cport, vaddr,
219                               vport, p);
220         p->pe = rcu_dereference(svc->pe);
221         if (p->pe && p->pe->fill_param)
222                 return p->pe->fill_param(p, skb);
223
224         return 0;
225 }
226
227 /*
228  *  IPVS persistent scheduling function
229  *  It creates a connection entry according to its template if exists,
230  *  or selects a server and creates a connection entry plus a template.
231  *  Locking: we are svc user (svc->refcnt), so we hold all dests too
232  *  Protocols supported: TCP, UDP
233  */
234 static struct ip_vs_conn *
235 ip_vs_sched_persist(struct ip_vs_service *svc,
236                     struct sk_buff *skb, __be16 src_port, __be16 dst_port,
237                     int *ignored, struct ip_vs_iphdr *iph)
238 {
239         struct ip_vs_conn *cp = NULL;
240         struct ip_vs_dest *dest;
241         struct ip_vs_conn *ct;
242         __be16 dport = 0;               /* destination port to forward */
243         unsigned int flags;
244         struct ip_vs_conn_param param;
245         const union nf_inet_addr fwmark = { .ip = htonl(svc->fwmark) };
246         union nf_inet_addr snet;        /* source network of the client,
247                                            after masking */
248         const union nf_inet_addr *src_addr, *dst_addr;
249
250         if (likely(!ip_vs_iph_inverse(iph))) {
251                 src_addr = &iph->saddr;
252                 dst_addr = &iph->daddr;
253         } else {
254                 src_addr = &iph->daddr;
255                 dst_addr = &iph->saddr;
256         }
257
258
259         /* Mask saddr with the netmask to adjust template granularity */
260 #ifdef CONFIG_IP_VS_IPV6
261         if (svc->af == AF_INET6)
262                 ipv6_addr_prefix(&snet.in6, &src_addr->in6,
263                                  (__force __u32) svc->netmask);
264         else
265 #endif
266                 snet.ip = src_addr->ip & svc->netmask;
267
268         IP_VS_DBG_BUF(6, "p-schedule: src %s:%u dest %s:%u "
269                       "mnet %s\n",
270                       IP_VS_DBG_ADDR(svc->af, src_addr), ntohs(src_port),
271                       IP_VS_DBG_ADDR(svc->af, dst_addr), ntohs(dst_port),
272                       IP_VS_DBG_ADDR(svc->af, &snet));
273
274         /*
275          * As far as we know, FTP is a very complicated network protocol, and
276          * it uses control connection and data connections. For active FTP,
277          * FTP server initialize data connection to the client, its source port
278          * is often 20. For passive FTP, FTP server tells the clients the port
279          * that it passively listens to,  and the client issues the data
280          * connection. In the tunneling or direct routing mode, the load
281          * balancer is on the client-to-server half of connection, the port
282          * number is unknown to the load balancer. So, a conn template like
283          * <caddr, 0, vaddr, 0, daddr, 0> is created for persistent FTP
284          * service, and a template like <caddr, 0, vaddr, vport, daddr, dport>
285          * is created for other persistent services.
286          */
287         {
288                 int protocol = iph->protocol;
289                 const union nf_inet_addr *vaddr = dst_addr;
290                 __be16 vport = 0;
291
292                 if (dst_port == svc->port) {
293                         /* non-FTP template:
294                          * <protocol, caddr, 0, vaddr, vport, daddr, dport>
295                          * FTP template:
296                          * <protocol, caddr, 0, vaddr, 0, daddr, 0>
297                          */
298                         if (svc->port != FTPPORT)
299                                 vport = dst_port;
300                 } else {
301                         /* Note: persistent fwmark-based services and
302                          * persistent port zero service are handled here.
303                          * fwmark template:
304                          * <IPPROTO_IP,caddr,0,fwmark,0,daddr,0>
305                          * port zero template:
306                          * <protocol,caddr,0,vaddr,0,daddr,0>
307                          */
308                         if (svc->fwmark) {
309                                 protocol = IPPROTO_IP;
310                                 vaddr = &fwmark;
311                         }
312                 }
313                 /* return *ignored = -1 so NF_DROP can be used */
314                 if (ip_vs_conn_fill_param_persist(svc, skb, protocol, &snet, 0,
315                                                   vaddr, vport, &param) < 0) {
316                         *ignored = -1;
317                         return NULL;
318                 }
319         }
320
321         /* Check if a template already exists */
322         ct = ip_vs_ct_in_get(&param);
323         if (!ct || !ip_vs_check_template(ct)) {
324                 struct ip_vs_scheduler *sched;
325
326                 /*
327                  * No template found or the dest of the connection
328                  * template is not available.
329                  * return *ignored=0 i.e. ICMP and NF_DROP
330                  */
331                 sched = rcu_dereference(svc->scheduler);
332                 if (sched) {
333                         /* read svc->sched_data after svc->scheduler */
334                         smp_rmb();
335                         dest = sched->schedule(svc, skb, iph);
336                 } else {
337                         dest = NULL;
338                 }
339                 if (!dest) {
340                         IP_VS_DBG(1, "p-schedule: no dest found.\n");
341                         kfree(param.pe_data);
342                         *ignored = 0;
343                         return NULL;
344                 }
345
346                 if (dst_port == svc->port && svc->port != FTPPORT)
347                         dport = dest->port;
348
349                 /* Create a template
350                  * This adds param.pe_data to the template,
351                  * and thus param.pe_data will be destroyed
352                  * when the template expires */
353                 ct = ip_vs_conn_new(&param, dest->af, &dest->addr, dport,
354                                     IP_VS_CONN_F_TEMPLATE, dest, skb->mark);
355                 if (ct == NULL) {
356                         kfree(param.pe_data);
357                         *ignored = -1;
358                         return NULL;
359                 }
360
361                 ct->timeout = svc->timeout;
362         } else {
363                 /* set destination with the found template */
364                 dest = ct->dest;
365                 kfree(param.pe_data);
366         }
367
368         dport = dst_port;
369         if (dport == svc->port && dest->port)
370                 dport = dest->port;
371
372         flags = (svc->flags & IP_VS_SVC_F_ONEPACKET
373                  && iph->protocol == IPPROTO_UDP) ?
374                 IP_VS_CONN_F_ONE_PACKET : 0;
375
376         /*
377          *    Create a new connection according to the template
378          */
379         ip_vs_conn_fill_param(svc->ipvs, svc->af, iph->protocol, src_addr,
380                               src_port, dst_addr, dst_port, &param);
381
382         cp = ip_vs_conn_new(&param, dest->af, &dest->addr, dport, flags, dest,
383                             skb->mark);
384         if (cp == NULL) {
385                 ip_vs_conn_put(ct);
386                 *ignored = -1;
387                 return NULL;
388         }
389
390         /*
391          *    Add its control
392          */
393         ip_vs_control_add(cp, ct);
394         ip_vs_conn_put(ct);
395
396         ip_vs_conn_stats(cp, svc);
397         return cp;
398 }
399
400
401 /*
402  *  IPVS main scheduling function
403  *  It selects a server according to the virtual service, and
404  *  creates a connection entry.
405  *  Protocols supported: TCP, UDP
406  *
407  *  Usage of *ignored
408  *
409  * 1 :   protocol tried to schedule (eg. on SYN), found svc but the
410  *       svc/scheduler decides that this packet should be accepted with
411  *       NF_ACCEPT because it must not be scheduled.
412  *
413  * 0 :   scheduler can not find destination, so try bypass or
414  *       return ICMP and then NF_DROP (ip_vs_leave).
415  *
416  * -1 :  scheduler tried to schedule but fatal error occurred, eg.
417  *       ip_vs_conn_new failure (ENOMEM) or ip_vs_sip_fill_param
418  *       failure such as missing Call-ID, ENOMEM on skb_linearize
419  *       or pe_data. In this case we should return NF_DROP without
420  *       any attempts to send ICMP with ip_vs_leave.
421  */
422 struct ip_vs_conn *
423 ip_vs_schedule(struct ip_vs_service *svc, struct sk_buff *skb,
424                struct ip_vs_proto_data *pd, int *ignored,
425                struct ip_vs_iphdr *iph)
426 {
427         struct ip_vs_protocol *pp = pd->pp;
428         struct ip_vs_conn *cp = NULL;
429         struct ip_vs_scheduler *sched;
430         struct ip_vs_dest *dest;
431         __be16 _ports[2], *pptr, cport, vport;
432         const void *caddr, *vaddr;
433         unsigned int flags;
434
435         *ignored = 1;
436         /*
437          * IPv6 frags, only the first hit here.
438          */
439         pptr = frag_safe_skb_hp(skb, iph->len, sizeof(_ports), _ports, iph);
440         if (pptr == NULL)
441                 return NULL;
442
443         if (likely(!ip_vs_iph_inverse(iph))) {
444                 cport = pptr[0];
445                 caddr = &iph->saddr;
446                 vport = pptr[1];
447                 vaddr = &iph->daddr;
448         } else {
449                 cport = pptr[1];
450                 caddr = &iph->daddr;
451                 vport = pptr[0];
452                 vaddr = &iph->saddr;
453         }
454
455         /*
456          * FTPDATA needs this check when using local real server.
457          * Never schedule Active FTPDATA connections from real server.
458          * For LVS-NAT they must be already created. For other methods
459          * with persistence the connection is created on SYN+ACK.
460          */
461         if (cport == FTPDATA) {
462                 IP_VS_DBG_PKT(12, svc->af, pp, skb, iph->off,
463                               "Not scheduling FTPDATA");
464                 return NULL;
465         }
466
467         /*
468          *    Do not schedule replies from local real server.
469          */
470         if ((!skb->dev || skb->dev->flags & IFF_LOOPBACK)) {
471                 iph->hdr_flags ^= IP_VS_HDR_INVERSE;
472                 cp = pp->conn_in_get(svc->ipvs, svc->af, skb, iph);
473                 iph->hdr_flags ^= IP_VS_HDR_INVERSE;
474
475                 if (cp) {
476                         IP_VS_DBG_PKT(12, svc->af, pp, skb, iph->off,
477                                       "Not scheduling reply for existing"
478                                       " connection");
479                         __ip_vs_conn_put(cp);
480                         return NULL;
481                 }
482         }
483
484         /*
485          *    Persistent service
486          */
487         if (svc->flags & IP_VS_SVC_F_PERSISTENT)
488                 return ip_vs_sched_persist(svc, skb, cport, vport, ignored,
489                                            iph);
490
491         *ignored = 0;
492
493         /*
494          *    Non-persistent service
495          */
496         if (!svc->fwmark && vport != svc->port) {
497                 if (!svc->port)
498                         pr_err("Schedule: port zero only supported "
499                                "in persistent services, "
500                                "check your ipvs configuration\n");
501                 return NULL;
502         }
503
504         sched = rcu_dereference(svc->scheduler);
505         if (sched) {
506                 /* read svc->sched_data after svc->scheduler */
507                 smp_rmb();
508                 dest = sched->schedule(svc, skb, iph);
509         } else {
510                 dest = NULL;
511         }
512         if (dest == NULL) {
513                 IP_VS_DBG(1, "Schedule: no dest found.\n");
514                 return NULL;
515         }
516
517         flags = (svc->flags & IP_VS_SVC_F_ONEPACKET
518                  && iph->protocol == IPPROTO_UDP) ?
519                 IP_VS_CONN_F_ONE_PACKET : 0;
520
521         /*
522          *    Create a connection entry.
523          */
524         {
525                 struct ip_vs_conn_param p;
526
527                 ip_vs_conn_fill_param(svc->ipvs, svc->af, iph->protocol,
528                                       caddr, cport, vaddr, vport, &p);
529                 cp = ip_vs_conn_new(&p, dest->af, &dest->addr,
530                                     dest->port ? dest->port : vport,
531                                     flags, dest, skb->mark);
532                 if (!cp) {
533                         *ignored = -1;
534                         return NULL;
535                 }
536         }
537
538         IP_VS_DBG_BUF(6, "Schedule fwd:%c c:%s:%u v:%s:%u "
539                       "d:%s:%u conn->flags:%X conn->refcnt:%d\n",
540                       ip_vs_fwd_tag(cp),
541                       IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
542                       IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
543                       IP_VS_DBG_ADDR(cp->daf, &cp->daddr), ntohs(cp->dport),
544                       cp->flags, atomic_read(&cp->refcnt));
545
546         ip_vs_conn_stats(cp, svc);
547         return cp;
548 }
549
550 #ifdef CONFIG_SYSCTL
551 static inline int ip_vs_addr_is_unicast(struct net *net, int af,
552                                         union nf_inet_addr *addr)
553 {
554 #ifdef CONFIG_IP_VS_IPV6
555         if (af == AF_INET6)
556                 return ipv6_addr_type(&addr->in6) & IPV6_ADDR_UNICAST;
557 #endif
558         return (inet_addr_type(net, addr->ip) == RTN_UNICAST);
559 }
560 #endif
561
562 /*
563  *  Pass or drop the packet.
564  *  Called by ip_vs_in, when the virtual service is available but
565  *  no destination is available for a new connection.
566  */
567 int ip_vs_leave(struct ip_vs_service *svc, struct sk_buff *skb,
568                 struct ip_vs_proto_data *pd, struct ip_vs_iphdr *iph)
569 {
570         __be16 _ports[2], *pptr, dport;
571 #ifdef CONFIG_SYSCTL
572         struct net *net;
573         struct netns_ipvs *ipvs;
574 #endif
575
576         pptr = frag_safe_skb_hp(skb, iph->len, sizeof(_ports), _ports, iph);
577         if (!pptr)
578                 return NF_DROP;
579         dport = likely(!ip_vs_iph_inverse(iph)) ? pptr[1] : pptr[0];
580
581 #ifdef CONFIG_SYSCTL
582         net = skb_net(skb);
583
584
585         /* if it is fwmark-based service, the cache_bypass sysctl is up
586            and the destination is a non-local unicast, then create
587            a cache_bypass connection entry */
588         ipvs = net_ipvs(net);
589         if (ipvs->sysctl_cache_bypass && svc->fwmark &&
590             !(iph->hdr_flags & (IP_VS_HDR_INVERSE | IP_VS_HDR_ICMP)) &&
591             ip_vs_addr_is_unicast(net, svc->af, &iph->daddr)) {
592                 int ret;
593                 struct ip_vs_conn *cp;
594                 unsigned int flags = (svc->flags & IP_VS_SVC_F_ONEPACKET &&
595                                       iph->protocol == IPPROTO_UDP) ?
596                                       IP_VS_CONN_F_ONE_PACKET : 0;
597                 union nf_inet_addr daddr =  { .all = { 0, 0, 0, 0 } };
598
599                 /* create a new connection entry */
600                 IP_VS_DBG(6, "%s(): create a cache_bypass entry\n", __func__);
601                 {
602                         struct ip_vs_conn_param p;
603                         ip_vs_conn_fill_param(svc->ipvs, svc->af, iph->protocol,
604                                               &iph->saddr, pptr[0],
605                                               &iph->daddr, pptr[1], &p);
606                         cp = ip_vs_conn_new(&p, svc->af, &daddr, 0,
607                                             IP_VS_CONN_F_BYPASS | flags,
608                                             NULL, skb->mark);
609                         if (!cp)
610                                 return NF_DROP;
611                 }
612
613                 /* statistics */
614                 ip_vs_in_stats(cp, skb);
615
616                 /* set state */
617                 ip_vs_set_state(cp, IP_VS_DIR_INPUT, skb, pd);
618
619                 /* transmit the first SYN packet */
620                 ret = cp->packet_xmit(skb, cp, pd->pp, iph);
621                 /* do not touch skb anymore */
622
623                 atomic_inc(&cp->in_pkts);
624                 ip_vs_conn_put(cp);
625                 return ret;
626         }
627 #endif
628
629         /*
630          * When the virtual ftp service is presented, packets destined
631          * for other services on the VIP may get here (except services
632          * listed in the ipvs table), pass the packets, because it is
633          * not ipvs job to decide to drop the packets.
634          */
635         if (svc->port == FTPPORT && dport != FTPPORT)
636                 return NF_ACCEPT;
637
638         if (unlikely(ip_vs_iph_icmp(iph)))
639                 return NF_DROP;
640
641         /*
642          * Notify the client that the destination is unreachable, and
643          * release the socket buffer.
644          * Since it is in IP layer, the TCP socket is not actually
645          * created, the TCP RST packet cannot be sent, instead that
646          * ICMP_PORT_UNREACH is sent here no matter it is TCP/UDP. --WZ
647          */
648 #ifdef CONFIG_IP_VS_IPV6
649         if (svc->af == AF_INET6) {
650                 if (!skb->dev) {
651                         struct net *net_ = dev_net(skb_dst(skb)->dev);
652
653                         skb->dev = net_->loopback_dev;
654                 }
655                 icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
656         } else
657 #endif
658                 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
659
660         return NF_DROP;
661 }
662
663 #ifdef CONFIG_SYSCTL
664
665 static int sysctl_snat_reroute(struct sk_buff *skb)
666 {
667         struct netns_ipvs *ipvs = net_ipvs(skb_net(skb));
668         return ipvs->sysctl_snat_reroute;
669 }
670
671 static int sysctl_nat_icmp_send(struct net *net)
672 {
673         struct netns_ipvs *ipvs = net_ipvs(net);
674         return ipvs->sysctl_nat_icmp_send;
675 }
676
677 static int sysctl_expire_nodest_conn(struct netns_ipvs *ipvs)
678 {
679         return ipvs->sysctl_expire_nodest_conn;
680 }
681
682 #else
683
684 static int sysctl_snat_reroute(struct sk_buff *skb) { return 0; }
685 static int sysctl_nat_icmp_send(struct net *net) { return 0; }
686 static int sysctl_expire_nodest_conn(struct netns_ipvs *ipvs) { return 0; }
687
688 #endif
689
690 __sum16 ip_vs_checksum_complete(struct sk_buff *skb, int offset)
691 {
692         return csum_fold(skb_checksum(skb, offset, skb->len - offset, 0));
693 }
694
695 static inline enum ip_defrag_users ip_vs_defrag_user(unsigned int hooknum)
696 {
697         if (NF_INET_LOCAL_IN == hooknum)
698                 return IP_DEFRAG_VS_IN;
699         if (NF_INET_FORWARD == hooknum)
700                 return IP_DEFRAG_VS_FWD;
701         return IP_DEFRAG_VS_OUT;
702 }
703
704 static inline int ip_vs_gather_frags(struct sk_buff *skb, u_int32_t user)
705 {
706         int err;
707
708         local_bh_disable();
709         err = ip_defrag(skb, user);
710         local_bh_enable();
711         if (!err)
712                 ip_send_check(ip_hdr(skb));
713
714         return err;
715 }
716
717 static int ip_vs_route_me_harder(int af, struct sk_buff *skb,
718                                  unsigned int hooknum)
719 {
720         if (!sysctl_snat_reroute(skb))
721                 return 0;
722         /* Reroute replies only to remote clients (FORWARD and LOCAL_OUT) */
723         if (NF_INET_LOCAL_IN == hooknum)
724                 return 0;
725 #ifdef CONFIG_IP_VS_IPV6
726         if (af == AF_INET6) {
727                 struct dst_entry *dst = skb_dst(skb);
728
729                 if (dst->dev && !(dst->dev->flags & IFF_LOOPBACK) &&
730                     ip6_route_me_harder(skb) != 0)
731                         return 1;
732         } else
733 #endif
734                 if (!(skb_rtable(skb)->rt_flags & RTCF_LOCAL) &&
735                     ip_route_me_harder(skb, RTN_LOCAL) != 0)
736                         return 1;
737
738         return 0;
739 }
740
741 /*
742  * Packet has been made sufficiently writable in caller
743  * - inout: 1=in->out, 0=out->in
744  */
745 void ip_vs_nat_icmp(struct sk_buff *skb, struct ip_vs_protocol *pp,
746                     struct ip_vs_conn *cp, int inout)
747 {
748         struct iphdr *iph        = ip_hdr(skb);
749         unsigned int icmp_offset = iph->ihl*4;
750         struct icmphdr *icmph    = (struct icmphdr *)(skb_network_header(skb) +
751                                                       icmp_offset);
752         struct iphdr *ciph       = (struct iphdr *)(icmph + 1);
753
754         if (inout) {
755                 iph->saddr = cp->vaddr.ip;
756                 ip_send_check(iph);
757                 ciph->daddr = cp->vaddr.ip;
758                 ip_send_check(ciph);
759         } else {
760                 iph->daddr = cp->daddr.ip;
761                 ip_send_check(iph);
762                 ciph->saddr = cp->daddr.ip;
763                 ip_send_check(ciph);
764         }
765
766         /* the TCP/UDP/SCTP port */
767         if (IPPROTO_TCP == ciph->protocol || IPPROTO_UDP == ciph->protocol ||
768             IPPROTO_SCTP == ciph->protocol) {
769                 __be16 *ports = (void *)ciph + ciph->ihl*4;
770
771                 if (inout)
772                         ports[1] = cp->vport;
773                 else
774                         ports[0] = cp->dport;
775         }
776
777         /* And finally the ICMP checksum */
778         icmph->checksum = 0;
779         icmph->checksum = ip_vs_checksum_complete(skb, icmp_offset);
780         skb->ip_summed = CHECKSUM_UNNECESSARY;
781
782         if (inout)
783                 IP_VS_DBG_PKT(11, AF_INET, pp, skb, (void *)ciph - (void *)iph,
784                         "Forwarding altered outgoing ICMP");
785         else
786                 IP_VS_DBG_PKT(11, AF_INET, pp, skb, (void *)ciph - (void *)iph,
787                         "Forwarding altered incoming ICMP");
788 }
789
790 #ifdef CONFIG_IP_VS_IPV6
791 void ip_vs_nat_icmp_v6(struct sk_buff *skb, struct ip_vs_protocol *pp,
792                     struct ip_vs_conn *cp, int inout)
793 {
794         struct ipv6hdr *iph      = ipv6_hdr(skb);
795         unsigned int icmp_offset = 0;
796         unsigned int offs        = 0; /* header offset*/
797         int protocol;
798         struct icmp6hdr *icmph;
799         struct ipv6hdr *ciph;
800         unsigned short fragoffs;
801
802         ipv6_find_hdr(skb, &icmp_offset, IPPROTO_ICMPV6, &fragoffs, NULL);
803         icmph = (struct icmp6hdr *)(skb_network_header(skb) + icmp_offset);
804         offs = icmp_offset + sizeof(struct icmp6hdr);
805         ciph = (struct ipv6hdr *)(skb_network_header(skb) + offs);
806
807         protocol = ipv6_find_hdr(skb, &offs, -1, &fragoffs, NULL);
808
809         if (inout) {
810                 iph->saddr = cp->vaddr.in6;
811                 ciph->daddr = cp->vaddr.in6;
812         } else {
813                 iph->daddr = cp->daddr.in6;
814                 ciph->saddr = cp->daddr.in6;
815         }
816
817         /* the TCP/UDP/SCTP port */
818         if (!fragoffs && (IPPROTO_TCP == protocol || IPPROTO_UDP == protocol ||
819                           IPPROTO_SCTP == protocol)) {
820                 __be16 *ports = (void *)(skb_network_header(skb) + offs);
821
822                 IP_VS_DBG(11, "%s() changed port %d to %d\n", __func__,
823                               ntohs(inout ? ports[1] : ports[0]),
824                               ntohs(inout ? cp->vport : cp->dport));
825                 if (inout)
826                         ports[1] = cp->vport;
827                 else
828                         ports[0] = cp->dport;
829         }
830
831         /* And finally the ICMP checksum */
832         icmph->icmp6_cksum = ~csum_ipv6_magic(&iph->saddr, &iph->daddr,
833                                               skb->len - icmp_offset,
834                                               IPPROTO_ICMPV6, 0);
835         skb->csum_start = skb_network_header(skb) - skb->head + icmp_offset;
836         skb->csum_offset = offsetof(struct icmp6hdr, icmp6_cksum);
837         skb->ip_summed = CHECKSUM_PARTIAL;
838
839         if (inout)
840                 IP_VS_DBG_PKT(11, AF_INET6, pp, skb,
841                               (void *)ciph - (void *)iph,
842                               "Forwarding altered outgoing ICMPv6");
843         else
844                 IP_VS_DBG_PKT(11, AF_INET6, pp, skb,
845                               (void *)ciph - (void *)iph,
846                               "Forwarding altered incoming ICMPv6");
847 }
848 #endif
849
850 /* Handle relevant response ICMP messages - forward to the right
851  * destination host.
852  */
853 static int handle_response_icmp(int af, struct sk_buff *skb,
854                                 union nf_inet_addr *snet,
855                                 __u8 protocol, struct ip_vs_conn *cp,
856                                 struct ip_vs_protocol *pp,
857                                 unsigned int offset, unsigned int ihl,
858                                 unsigned int hooknum)
859 {
860         unsigned int verdict = NF_DROP;
861
862         if (IP_VS_FWD_METHOD(cp) != 0) {
863                 pr_err("shouldn't reach here, because the box is on the "
864                        "half connection in the tun/dr module.\n");
865         }
866
867         /* Ensure the checksum is correct */
868         if (!skb_csum_unnecessary(skb) && ip_vs_checksum_complete(skb, ihl)) {
869                 /* Failed checksum! */
870                 IP_VS_DBG_BUF(1, "Forward ICMP: failed checksum from %s!\n",
871                               IP_VS_DBG_ADDR(af, snet));
872                 goto out;
873         }
874
875         if (IPPROTO_TCP == protocol || IPPROTO_UDP == protocol ||
876             IPPROTO_SCTP == protocol)
877                 offset += 2 * sizeof(__u16);
878         if (!skb_make_writable(skb, offset))
879                 goto out;
880
881 #ifdef CONFIG_IP_VS_IPV6
882         if (af == AF_INET6)
883                 ip_vs_nat_icmp_v6(skb, pp, cp, 1);
884         else
885 #endif
886                 ip_vs_nat_icmp(skb, pp, cp, 1);
887
888         if (ip_vs_route_me_harder(af, skb, hooknum))
889                 goto out;
890
891         /* do the statistics and put it back */
892         ip_vs_out_stats(cp, skb);
893
894         skb->ipvs_property = 1;
895         if (!(cp->flags & IP_VS_CONN_F_NFCT))
896                 ip_vs_notrack(skb);
897         else
898                 ip_vs_update_conntrack(skb, cp, 0);
899         verdict = NF_ACCEPT;
900
901 out:
902         __ip_vs_conn_put(cp);
903
904         return verdict;
905 }
906
907 /*
908  *      Handle ICMP messages in the inside-to-outside direction (outgoing).
909  *      Find any that might be relevant, check against existing connections.
910  *      Currently handles error types - unreachable, quench, ttl exceeded.
911  */
912 static int ip_vs_out_icmp(struct sk_buff *skb, int *related,
913                           unsigned int hooknum)
914 {
915         struct netns_ipvs *ipvs = net_ipvs(skb_net(skb));
916         struct iphdr *iph;
917         struct icmphdr  _icmph, *ic;
918         struct iphdr    _ciph, *cih;    /* The ip header contained within the ICMP */
919         struct ip_vs_iphdr ciph;
920         struct ip_vs_conn *cp;
921         struct ip_vs_protocol *pp;
922         unsigned int offset, ihl;
923         union nf_inet_addr snet;
924
925         *related = 1;
926
927         /* reassemble IP fragments */
928         if (ip_is_fragment(ip_hdr(skb))) {
929                 if (ip_vs_gather_frags(skb, ip_vs_defrag_user(hooknum)))
930                         return NF_STOLEN;
931         }
932
933         iph = ip_hdr(skb);
934         offset = ihl = iph->ihl * 4;
935         ic = skb_header_pointer(skb, offset, sizeof(_icmph), &_icmph);
936         if (ic == NULL)
937                 return NF_DROP;
938
939         IP_VS_DBG(12, "Outgoing ICMP (%d,%d) %pI4->%pI4\n",
940                   ic->type, ntohs(icmp_id(ic)),
941                   &iph->saddr, &iph->daddr);
942
943         /*
944          * Work through seeing if this is for us.
945          * These checks are supposed to be in an order that means easy
946          * things are checked first to speed up processing.... however
947          * this means that some packets will manage to get a long way
948          * down this stack and then be rejected, but that's life.
949          */
950         if ((ic->type != ICMP_DEST_UNREACH) &&
951             (ic->type != ICMP_SOURCE_QUENCH) &&
952             (ic->type != ICMP_TIME_EXCEEDED)) {
953                 *related = 0;
954                 return NF_ACCEPT;
955         }
956
957         /* Now find the contained IP header */
958         offset += sizeof(_icmph);
959         cih = skb_header_pointer(skb, offset, sizeof(_ciph), &_ciph);
960         if (cih == NULL)
961                 return NF_ACCEPT; /* The packet looks wrong, ignore */
962
963         pp = ip_vs_proto_get(cih->protocol);
964         if (!pp)
965                 return NF_ACCEPT;
966
967         /* Is the embedded protocol header present? */
968         if (unlikely(cih->frag_off & htons(IP_OFFSET) &&
969                      pp->dont_defrag))
970                 return NF_ACCEPT;
971
972         IP_VS_DBG_PKT(11, AF_INET, pp, skb, offset,
973                       "Checking outgoing ICMP for");
974
975         ip_vs_fill_iph_skb_icmp(AF_INET, skb, offset, true, &ciph);
976
977         /* The embedded headers contain source and dest in reverse order */
978         cp = pp->conn_out_get(ipvs, AF_INET, skb, &ciph);
979         if (!cp)
980                 return NF_ACCEPT;
981
982         snet.ip = iph->saddr;
983         return handle_response_icmp(AF_INET, skb, &snet, cih->protocol, cp,
984                                     pp, ciph.len, ihl, hooknum);
985 }
986
987 #ifdef CONFIG_IP_VS_IPV6
988 static int ip_vs_out_icmp_v6(struct sk_buff *skb, int *related,
989                              unsigned int hooknum, struct ip_vs_iphdr *ipvsh)
990 {
991         struct netns_ipvs *ipvs = net_ipvs(skb_net(skb));
992         struct icmp6hdr _icmph, *ic;
993         struct ip_vs_iphdr ciph = {.flags = 0, .fragoffs = 0};/*Contained IP */
994         struct ip_vs_conn *cp;
995         struct ip_vs_protocol *pp;
996         union nf_inet_addr snet;
997         unsigned int offset;
998
999         *related = 1;
1000         ic = frag_safe_skb_hp(skb, ipvsh->len, sizeof(_icmph), &_icmph, ipvsh);
1001         if (ic == NULL)
1002                 return NF_DROP;
1003
1004         /*
1005          * Work through seeing if this is for us.
1006          * These checks are supposed to be in an order that means easy
1007          * things are checked first to speed up processing.... however
1008          * this means that some packets will manage to get a long way
1009          * down this stack and then be rejected, but that's life.
1010          */
1011         if (ic->icmp6_type & ICMPV6_INFOMSG_MASK) {
1012                 *related = 0;
1013                 return NF_ACCEPT;
1014         }
1015         /* Fragment header that is before ICMP header tells us that:
1016          * it's not an error message since they can't be fragmented.
1017          */
1018         if (ipvsh->flags & IP6_FH_F_FRAG)
1019                 return NF_DROP;
1020
1021         IP_VS_DBG(8, "Outgoing ICMPv6 (%d,%d) %pI6c->%pI6c\n",
1022                   ic->icmp6_type, ntohs(icmpv6_id(ic)),
1023                   &ipvsh->saddr, &ipvsh->daddr);
1024
1025         if (!ip_vs_fill_iph_skb_icmp(AF_INET6, skb, ipvsh->len + sizeof(_icmph),
1026                                      true, &ciph))
1027                 return NF_ACCEPT; /* The packet looks wrong, ignore */
1028
1029         pp = ip_vs_proto_get(ciph.protocol);
1030         if (!pp)
1031                 return NF_ACCEPT;
1032
1033         /* The embedded headers contain source and dest in reverse order */
1034         cp = pp->conn_out_get(ipvs, AF_INET6, skb, &ciph);
1035         if (!cp)
1036                 return NF_ACCEPT;
1037
1038         snet.in6 = ciph.saddr.in6;
1039         offset = ciph.len;
1040         return handle_response_icmp(AF_INET6, skb, &snet, ciph.protocol, cp,
1041                                     pp, offset, sizeof(struct ipv6hdr),
1042                                     hooknum);
1043 }
1044 #endif
1045
1046 /*
1047  * Check if sctp chunc is ABORT chunk
1048  */
1049 static inline int is_sctp_abort(const struct sk_buff *skb, int nh_len)
1050 {
1051         sctp_chunkhdr_t *sch, schunk;
1052         sch = skb_header_pointer(skb, nh_len + sizeof(sctp_sctphdr_t),
1053                         sizeof(schunk), &schunk);
1054         if (sch == NULL)
1055                 return 0;
1056         if (sch->type == SCTP_CID_ABORT)
1057                 return 1;
1058         return 0;
1059 }
1060
1061 static inline int is_tcp_reset(const struct sk_buff *skb, int nh_len)
1062 {
1063         struct tcphdr _tcph, *th;
1064
1065         th = skb_header_pointer(skb, nh_len, sizeof(_tcph), &_tcph);
1066         if (th == NULL)
1067                 return 0;
1068         return th->rst;
1069 }
1070
1071 static inline bool is_new_conn(const struct sk_buff *skb,
1072                                struct ip_vs_iphdr *iph)
1073 {
1074         switch (iph->protocol) {
1075         case IPPROTO_TCP: {
1076                 struct tcphdr _tcph, *th;
1077
1078                 th = skb_header_pointer(skb, iph->len, sizeof(_tcph), &_tcph);
1079                 if (th == NULL)
1080                         return false;
1081                 return th->syn;
1082         }
1083         case IPPROTO_SCTP: {
1084                 sctp_chunkhdr_t *sch, schunk;
1085
1086                 sch = skb_header_pointer(skb, iph->len + sizeof(sctp_sctphdr_t),
1087                                          sizeof(schunk), &schunk);
1088                 if (sch == NULL)
1089                         return false;
1090                 return sch->type == SCTP_CID_INIT;
1091         }
1092         default:
1093                 return false;
1094         }
1095 }
1096
1097 static inline bool is_new_conn_expected(const struct ip_vs_conn *cp,
1098                                         int conn_reuse_mode)
1099 {
1100         /* Controlled (FTP DATA or persistence)? */
1101         if (cp->control)
1102                 return false;
1103
1104         switch (cp->protocol) {
1105         case IPPROTO_TCP:
1106                 return (cp->state == IP_VS_TCP_S_TIME_WAIT) ||
1107                         ((conn_reuse_mode & 2) &&
1108                          (cp->state == IP_VS_TCP_S_FIN_WAIT) &&
1109                          (cp->flags & IP_VS_CONN_F_NOOUTPUT));
1110         case IPPROTO_SCTP:
1111                 return cp->state == IP_VS_SCTP_S_CLOSED;
1112         default:
1113                 return false;
1114         }
1115 }
1116
1117 /* Handle response packets: rewrite addresses and send away...
1118  */
1119 static unsigned int
1120 handle_response(int af, struct sk_buff *skb, struct ip_vs_proto_data *pd,
1121                 struct ip_vs_conn *cp, struct ip_vs_iphdr *iph,
1122                 unsigned int hooknum)
1123 {
1124         struct ip_vs_protocol *pp = pd->pp;
1125
1126         IP_VS_DBG_PKT(11, af, pp, skb, iph->off, "Outgoing packet");
1127
1128         if (!skb_make_writable(skb, iph->len))
1129                 goto drop;
1130
1131         /* mangle the packet */
1132         if (pp->snat_handler && !pp->snat_handler(skb, pp, cp, iph))
1133                 goto drop;
1134
1135 #ifdef CONFIG_IP_VS_IPV6
1136         if (af == AF_INET6)
1137                 ipv6_hdr(skb)->saddr = cp->vaddr.in6;
1138         else
1139 #endif
1140         {
1141                 ip_hdr(skb)->saddr = cp->vaddr.ip;
1142                 ip_send_check(ip_hdr(skb));
1143         }
1144
1145         /*
1146          * nf_iterate does not expect change in the skb->dst->dev.
1147          * It looks like it is not fatal to enable this code for hooks
1148          * where our handlers are at the end of the chain list and
1149          * when all next handlers use skb->dst->dev and not outdev.
1150          * It will definitely route properly the inout NAT traffic
1151          * when multiple paths are used.
1152          */
1153
1154         /* For policy routing, packets originating from this
1155          * machine itself may be routed differently to packets
1156          * passing through.  We want this packet to be routed as
1157          * if it came from this machine itself.  So re-compute
1158          * the routing information.
1159          */
1160         if (ip_vs_route_me_harder(af, skb, hooknum))
1161                 goto drop;
1162
1163         IP_VS_DBG_PKT(10, af, pp, skb, iph->off, "After SNAT");
1164
1165         ip_vs_out_stats(cp, skb);
1166         ip_vs_set_state(cp, IP_VS_DIR_OUTPUT, skb, pd);
1167         skb->ipvs_property = 1;
1168         if (!(cp->flags & IP_VS_CONN_F_NFCT))
1169                 ip_vs_notrack(skb);
1170         else
1171                 ip_vs_update_conntrack(skb, cp, 0);
1172         ip_vs_conn_put(cp);
1173
1174         LeaveFunction(11);
1175         return NF_ACCEPT;
1176
1177 drop:
1178         ip_vs_conn_put(cp);
1179         kfree_skb(skb);
1180         LeaveFunction(11);
1181         return NF_STOLEN;
1182 }
1183
1184 /*
1185  *      Check if outgoing packet belongs to the established ip_vs_conn.
1186  */
1187 static unsigned int
1188 ip_vs_out(unsigned int hooknum, struct sk_buff *skb, int af)
1189 {
1190         struct net *net = NULL;
1191         struct netns_ipvs *ipvs;
1192         struct ip_vs_iphdr iph;
1193         struct ip_vs_protocol *pp;
1194         struct ip_vs_proto_data *pd;
1195         struct ip_vs_conn *cp;
1196
1197         EnterFunction(11);
1198
1199         /* Already marked as IPVS request or reply? */
1200         if (skb->ipvs_property)
1201                 return NF_ACCEPT;
1202
1203         /* Bad... Do not break raw sockets */
1204         if (unlikely(skb->sk != NULL && hooknum == NF_INET_LOCAL_OUT &&
1205                      af == AF_INET)) {
1206                 struct sock *sk = skb->sk;
1207                 struct inet_sock *inet = inet_sk(skb->sk);
1208
1209                 if (inet && sk->sk_family == PF_INET && inet->nodefrag)
1210                         return NF_ACCEPT;
1211         }
1212
1213         if (unlikely(!skb_dst(skb)))
1214                 return NF_ACCEPT;
1215
1216         net = skb_net(skb);
1217         ipvs = net_ipvs(net);
1218         if (!ipvs->enable)
1219                 return NF_ACCEPT;
1220
1221         ip_vs_fill_iph_skb(af, skb, false, &iph);
1222 #ifdef CONFIG_IP_VS_IPV6
1223         if (af == AF_INET6) {
1224                 if (unlikely(iph.protocol == IPPROTO_ICMPV6)) {
1225                         int related;
1226                         int verdict = ip_vs_out_icmp_v6(skb, &related,
1227                                                         hooknum, &iph);
1228
1229                         if (related)
1230                                 return verdict;
1231                 }
1232         } else
1233 #endif
1234                 if (unlikely(iph.protocol == IPPROTO_ICMP)) {
1235                         int related;
1236                         int verdict = ip_vs_out_icmp(skb, &related, hooknum);
1237
1238                         if (related)
1239                                 return verdict;
1240                 }
1241
1242         pd = ip_vs_proto_data_get(ipvs, iph.protocol);
1243         if (unlikely(!pd))
1244                 return NF_ACCEPT;
1245         pp = pd->pp;
1246
1247         /* reassemble IP fragments */
1248 #ifdef CONFIG_IP_VS_IPV6
1249         if (af == AF_INET)
1250 #endif
1251                 if (unlikely(ip_is_fragment(ip_hdr(skb)) && !pp->dont_defrag)) {
1252                         if (ip_vs_gather_frags(skb,
1253                                                ip_vs_defrag_user(hooknum)))
1254                                 return NF_STOLEN;
1255
1256                         ip_vs_fill_iph_skb(AF_INET, skb, false, &iph);
1257                 }
1258
1259         /*
1260          * Check if the packet belongs to an existing entry
1261          */
1262         cp = pp->conn_out_get(ipvs, af, skb, &iph);
1263
1264         if (likely(cp))
1265                 return handle_response(af, skb, pd, cp, &iph, hooknum);
1266         if (sysctl_nat_icmp_send(net) &&
1267             (pp->protocol == IPPROTO_TCP ||
1268              pp->protocol == IPPROTO_UDP ||
1269              pp->protocol == IPPROTO_SCTP)) {
1270                 __be16 _ports[2], *pptr;
1271
1272                 pptr = frag_safe_skb_hp(skb, iph.len,
1273                                          sizeof(_ports), _ports, &iph);
1274                 if (pptr == NULL)
1275                         return NF_ACCEPT;       /* Not for me */
1276                 if (ip_vs_has_real_service(ipvs, af, iph.protocol, &iph.saddr,
1277                                            pptr[0])) {
1278                         /*
1279                          * Notify the real server: there is no
1280                          * existing entry if it is not RST
1281                          * packet or not TCP packet.
1282                          */
1283                         if ((iph.protocol != IPPROTO_TCP &&
1284                              iph.protocol != IPPROTO_SCTP)
1285                              || ((iph.protocol == IPPROTO_TCP
1286                                   && !is_tcp_reset(skb, iph.len))
1287                                  || (iph.protocol == IPPROTO_SCTP
1288                                         && !is_sctp_abort(skb,
1289                                                 iph.len)))) {
1290 #ifdef CONFIG_IP_VS_IPV6
1291                                 if (af == AF_INET6) {
1292                                         if (!skb->dev)
1293                                                 skb->dev = net->loopback_dev;
1294                                         icmpv6_send(skb,
1295                                                     ICMPV6_DEST_UNREACH,
1296                                                     ICMPV6_PORT_UNREACH,
1297                                                     0);
1298                                 } else
1299 #endif
1300                                         icmp_send(skb,
1301                                                   ICMP_DEST_UNREACH,
1302                                                   ICMP_PORT_UNREACH, 0);
1303                                 return NF_DROP;
1304                         }
1305                 }
1306         }
1307         IP_VS_DBG_PKT(12, af, pp, skb, iph.off,
1308                       "ip_vs_out: packet continues traversal as normal");
1309         return NF_ACCEPT;
1310 }
1311
1312 /*
1313  *      It is hooked at the NF_INET_FORWARD and NF_INET_LOCAL_IN chain,
1314  *      used only for VS/NAT.
1315  *      Check if packet is reply for established ip_vs_conn.
1316  */
1317 static unsigned int
1318 ip_vs_reply4(void *priv, struct sk_buff *skb,
1319              const struct nf_hook_state *state)
1320 {
1321         return ip_vs_out(state->hook, skb, AF_INET);
1322 }
1323
1324 /*
1325  *      It is hooked at the NF_INET_LOCAL_OUT chain, used only for VS/NAT.
1326  *      Check if packet is reply for established ip_vs_conn.
1327  */
1328 static unsigned int
1329 ip_vs_local_reply4(void *priv, struct sk_buff *skb,
1330                    const struct nf_hook_state *state)
1331 {
1332         return ip_vs_out(state->hook, skb, AF_INET);
1333 }
1334
1335 #ifdef CONFIG_IP_VS_IPV6
1336
1337 /*
1338  *      It is hooked at the NF_INET_FORWARD and NF_INET_LOCAL_IN chain,
1339  *      used only for VS/NAT.
1340  *      Check if packet is reply for established ip_vs_conn.
1341  */
1342 static unsigned int
1343 ip_vs_reply6(void *priv, struct sk_buff *skb,
1344              const struct nf_hook_state *state)
1345 {
1346         return ip_vs_out(state->hook, skb, AF_INET6);
1347 }
1348
1349 /*
1350  *      It is hooked at the NF_INET_LOCAL_OUT chain, used only for VS/NAT.
1351  *      Check if packet is reply for established ip_vs_conn.
1352  */
1353 static unsigned int
1354 ip_vs_local_reply6(void *priv, struct sk_buff *skb,
1355                    const struct nf_hook_state *state)
1356 {
1357         return ip_vs_out(state->hook, skb, AF_INET6);
1358 }
1359
1360 #endif
1361
1362 static unsigned int
1363 ip_vs_try_to_schedule(int af, struct sk_buff *skb, struct ip_vs_proto_data *pd,
1364                       int *verdict, struct ip_vs_conn **cpp,
1365                       struct ip_vs_iphdr *iph)
1366 {
1367         struct ip_vs_protocol *pp = pd->pp;
1368
1369         if (!iph->fragoffs) {
1370                 /* No (second) fragments need to enter here, as nf_defrag_ipv6
1371                  * replayed fragment zero will already have created the cp
1372                  */
1373
1374                 /* Schedule and create new connection entry into cpp */
1375                 if (!pp->conn_schedule(af, skb, pd, verdict, cpp, iph))
1376                         return 0;
1377         }
1378
1379         if (unlikely(!*cpp)) {
1380                 /* sorry, all this trouble for a no-hit :) */
1381                 IP_VS_DBG_PKT(12, af, pp, skb, iph->off,
1382                               "ip_vs_in: packet continues traversal as normal");
1383                 if (iph->fragoffs) {
1384                         /* Fragment that couldn't be mapped to a conn entry
1385                          * is missing module nf_defrag_ipv6
1386                          */
1387                         IP_VS_DBG_RL("Unhandled frag, load nf_defrag_ipv6\n");
1388                         IP_VS_DBG_PKT(7, af, pp, skb, iph->off,
1389                                       "unhandled fragment");
1390                 }
1391                 *verdict = NF_ACCEPT;
1392                 return 0;
1393         }
1394
1395         return 1;
1396 }
1397
1398 /*
1399  *      Handle ICMP messages in the outside-to-inside direction (incoming).
1400  *      Find any that might be relevant, check against existing connections,
1401  *      forward to the right destination host if relevant.
1402  *      Currently handles error types - unreachable, quench, ttl exceeded.
1403  */
1404 static int
1405 ip_vs_in_icmp(struct sk_buff *skb, int *related, unsigned int hooknum)
1406 {
1407         struct net *net = NULL;
1408         struct netns_ipvs *ipvs;
1409         struct iphdr *iph;
1410         struct icmphdr  _icmph, *ic;
1411         struct iphdr    _ciph, *cih;    /* The ip header contained within the ICMP */
1412         struct ip_vs_iphdr ciph;
1413         struct ip_vs_conn *cp;
1414         struct ip_vs_protocol *pp;
1415         struct ip_vs_proto_data *pd;
1416         unsigned int offset, offset2, ihl, verdict;
1417         bool ipip, new_cp = false;
1418
1419         *related = 1;
1420
1421         /* reassemble IP fragments */
1422         if (ip_is_fragment(ip_hdr(skb))) {
1423                 if (ip_vs_gather_frags(skb, ip_vs_defrag_user(hooknum)))
1424                         return NF_STOLEN;
1425         }
1426
1427         iph = ip_hdr(skb);
1428         offset = ihl = iph->ihl * 4;
1429         ic = skb_header_pointer(skb, offset, sizeof(_icmph), &_icmph);
1430         if (ic == NULL)
1431                 return NF_DROP;
1432
1433         IP_VS_DBG(12, "Incoming ICMP (%d,%d) %pI4->%pI4\n",
1434                   ic->type, ntohs(icmp_id(ic)),
1435                   &iph->saddr, &iph->daddr);
1436
1437         /*
1438          * Work through seeing if this is for us.
1439          * These checks are supposed to be in an order that means easy
1440          * things are checked first to speed up processing.... however
1441          * this means that some packets will manage to get a long way
1442          * down this stack and then be rejected, but that's life.
1443          */
1444         if ((ic->type != ICMP_DEST_UNREACH) &&
1445             (ic->type != ICMP_SOURCE_QUENCH) &&
1446             (ic->type != ICMP_TIME_EXCEEDED)) {
1447                 *related = 0;
1448                 return NF_ACCEPT;
1449         }
1450
1451         /* Now find the contained IP header */
1452         offset += sizeof(_icmph);
1453         cih = skb_header_pointer(skb, offset, sizeof(_ciph), &_ciph);
1454         if (cih == NULL)
1455                 return NF_ACCEPT; /* The packet looks wrong, ignore */
1456
1457         net = skb_net(skb);
1458         ipvs = net_ipvs(net);
1459
1460         /* Special case for errors for IPIP packets */
1461         ipip = false;
1462         if (cih->protocol == IPPROTO_IPIP) {
1463                 if (unlikely(cih->frag_off & htons(IP_OFFSET)))
1464                         return NF_ACCEPT;
1465                 /* Error for our IPIP must arrive at LOCAL_IN */
1466                 if (!(skb_rtable(skb)->rt_flags & RTCF_LOCAL))
1467                         return NF_ACCEPT;
1468                 offset += cih->ihl * 4;
1469                 cih = skb_header_pointer(skb, offset, sizeof(_ciph), &_ciph);
1470                 if (cih == NULL)
1471                         return NF_ACCEPT; /* The packet looks wrong, ignore */
1472                 ipip = true;
1473         }
1474
1475         pd = ip_vs_proto_data_get(ipvs, cih->protocol);
1476         if (!pd)
1477                 return NF_ACCEPT;
1478         pp = pd->pp;
1479
1480         /* Is the embedded protocol header present? */
1481         if (unlikely(cih->frag_off & htons(IP_OFFSET) &&
1482                      pp->dont_defrag))
1483                 return NF_ACCEPT;
1484
1485         IP_VS_DBG_PKT(11, AF_INET, pp, skb, offset,
1486                       "Checking incoming ICMP for");
1487
1488         offset2 = offset;
1489         ip_vs_fill_iph_skb_icmp(AF_INET, skb, offset, !ipip, &ciph);
1490         offset = ciph.len;
1491
1492         /* The embedded headers contain source and dest in reverse order.
1493          * For IPIP this is error for request, not for reply.
1494          */
1495         cp = pp->conn_in_get(ipvs, AF_INET, skb, &ciph);
1496
1497         if (!cp) {
1498                 int v;
1499
1500                 if (!sysctl_schedule_icmp(ipvs))
1501                         return NF_ACCEPT;
1502
1503                 if (!ip_vs_try_to_schedule(AF_INET, skb, pd, &v, &cp, &ciph))
1504                         return v;
1505                 new_cp = true;
1506         }
1507
1508         verdict = NF_DROP;
1509
1510         /* Ensure the checksum is correct */
1511         if (!skb_csum_unnecessary(skb) && ip_vs_checksum_complete(skb, ihl)) {
1512                 /* Failed checksum! */
1513                 IP_VS_DBG(1, "Incoming ICMP: failed checksum from %pI4!\n",
1514                           &iph->saddr);
1515                 goto out;
1516         }
1517
1518         if (ipip) {
1519                 __be32 info = ic->un.gateway;
1520                 __u8 type = ic->type;
1521                 __u8 code = ic->code;
1522
1523                 /* Update the MTU */
1524                 if (ic->type == ICMP_DEST_UNREACH &&
1525                     ic->code == ICMP_FRAG_NEEDED) {
1526                         struct ip_vs_dest *dest = cp->dest;
1527                         u32 mtu = ntohs(ic->un.frag.mtu);
1528                         __be16 frag_off = cih->frag_off;
1529
1530                         /* Strip outer IP and ICMP, go to IPIP header */
1531                         if (pskb_pull(skb, ihl + sizeof(_icmph)) == NULL)
1532                                 goto ignore_ipip;
1533                         offset2 -= ihl + sizeof(_icmph);
1534                         skb_reset_network_header(skb);
1535                         IP_VS_DBG(12, "ICMP for IPIP %pI4->%pI4: mtu=%u\n",
1536                                 &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr, mtu);
1537                         ipv4_update_pmtu(skb, dev_net(skb->dev),
1538                                          mtu, 0, 0, 0, 0);
1539                         /* Client uses PMTUD? */
1540                         if (!(frag_off & htons(IP_DF)))
1541                                 goto ignore_ipip;
1542                         /* Prefer the resulting PMTU */
1543                         if (dest) {
1544                                 struct ip_vs_dest_dst *dest_dst;
1545
1546                                 rcu_read_lock();
1547                                 dest_dst = rcu_dereference(dest->dest_dst);
1548                                 if (dest_dst)
1549                                         mtu = dst_mtu(dest_dst->dst_cache);
1550                                 rcu_read_unlock();
1551                         }
1552                         if (mtu > 68 + sizeof(struct iphdr))
1553                                 mtu -= sizeof(struct iphdr);
1554                         info = htonl(mtu);
1555                 }
1556                 /* Strip outer IP, ICMP and IPIP, go to IP header of
1557                  * original request.
1558                  */
1559                 if (pskb_pull(skb, offset2) == NULL)
1560                         goto ignore_ipip;
1561                 skb_reset_network_header(skb);
1562                 IP_VS_DBG(12, "Sending ICMP for %pI4->%pI4: t=%u, c=%u, i=%u\n",
1563                         &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr,
1564                         type, code, ntohl(info));
1565                 icmp_send(skb, type, code, info);
1566                 /* ICMP can be shorter but anyways, account it */
1567                 ip_vs_out_stats(cp, skb);
1568
1569 ignore_ipip:
1570                 consume_skb(skb);
1571                 verdict = NF_STOLEN;
1572                 goto out;
1573         }
1574
1575         /* do the statistics and put it back */
1576         ip_vs_in_stats(cp, skb);
1577         if (IPPROTO_TCP == cih->protocol || IPPROTO_UDP == cih->protocol ||
1578             IPPROTO_SCTP == cih->protocol)
1579                 offset += 2 * sizeof(__u16);
1580         verdict = ip_vs_icmp_xmit(skb, cp, pp, offset, hooknum, &ciph);
1581
1582 out:
1583         if (likely(!new_cp))
1584                 __ip_vs_conn_put(cp);
1585         else
1586                 ip_vs_conn_put(cp);
1587
1588         return verdict;
1589 }
1590
1591 #ifdef CONFIG_IP_VS_IPV6
1592 static int ip_vs_in_icmp_v6(struct sk_buff *skb, int *related,
1593                             unsigned int hooknum, struct ip_vs_iphdr *iph)
1594 {
1595         struct net *net = NULL;
1596         struct netns_ipvs *ipvs;
1597         struct icmp6hdr _icmph, *ic;
1598         struct ip_vs_iphdr ciph = {.flags = 0, .fragoffs = 0};/*Contained IP */
1599         struct ip_vs_conn *cp;
1600         struct ip_vs_protocol *pp;
1601         struct ip_vs_proto_data *pd;
1602         unsigned int offset, verdict;
1603         bool new_cp = false;
1604
1605         *related = 1;
1606
1607         ic = frag_safe_skb_hp(skb, iph->len, sizeof(_icmph), &_icmph, iph);
1608         if (ic == NULL)
1609                 return NF_DROP;
1610
1611         /*
1612          * Work through seeing if this is for us.
1613          * These checks are supposed to be in an order that means easy
1614          * things are checked first to speed up processing.... however
1615          * this means that some packets will manage to get a long way
1616          * down this stack and then be rejected, but that's life.
1617          */
1618         if (ic->icmp6_type & ICMPV6_INFOMSG_MASK) {
1619                 *related = 0;
1620                 return NF_ACCEPT;
1621         }
1622         /* Fragment header that is before ICMP header tells us that:
1623          * it's not an error message since they can't be fragmented.
1624          */
1625         if (iph->flags & IP6_FH_F_FRAG)
1626                 return NF_DROP;
1627
1628         IP_VS_DBG(8, "Incoming ICMPv6 (%d,%d) %pI6c->%pI6c\n",
1629                   ic->icmp6_type, ntohs(icmpv6_id(ic)),
1630                   &iph->saddr, &iph->daddr);
1631
1632         offset = iph->len + sizeof(_icmph);
1633         if (!ip_vs_fill_iph_skb_icmp(AF_INET6, skb, offset, true, &ciph))
1634                 return NF_ACCEPT;
1635
1636         net = skb_net(skb);
1637         ipvs = net_ipvs(net);
1638         pd = ip_vs_proto_data_get(ipvs, ciph.protocol);
1639         if (!pd)
1640                 return NF_ACCEPT;
1641         pp = pd->pp;
1642
1643         /* Cannot handle fragmented embedded protocol */
1644         if (ciph.fragoffs)
1645                 return NF_ACCEPT;
1646
1647         IP_VS_DBG_PKT(11, AF_INET6, pp, skb, offset,
1648                       "Checking incoming ICMPv6 for");
1649
1650         /* The embedded headers contain source and dest in reverse order
1651          * if not from localhost
1652          */
1653         cp = pp->conn_in_get(ipvs, AF_INET6, skb, &ciph);
1654
1655         if (!cp) {
1656                 int v;
1657
1658                 if (!sysctl_schedule_icmp(ipvs))
1659                         return NF_ACCEPT;
1660
1661                 if (!ip_vs_try_to_schedule(AF_INET6, skb, pd, &v, &cp, &ciph))
1662                         return v;
1663
1664                 new_cp = true;
1665         }
1666
1667         /* VS/TUN, VS/DR and LOCALNODE just let it go */
1668         if ((hooknum == NF_INET_LOCAL_OUT) &&
1669             (IP_VS_FWD_METHOD(cp) != IP_VS_CONN_F_MASQ)) {
1670                 verdict = NF_ACCEPT;
1671                 goto out;
1672         }
1673
1674         /* do the statistics and put it back */
1675         ip_vs_in_stats(cp, skb);
1676
1677         /* Need to mangle contained IPv6 header in ICMPv6 packet */
1678         offset = ciph.len;
1679         if (IPPROTO_TCP == ciph.protocol || IPPROTO_UDP == ciph.protocol ||
1680             IPPROTO_SCTP == ciph.protocol)
1681                 offset += 2 * sizeof(__u16); /* Also mangle ports */
1682
1683         verdict = ip_vs_icmp_xmit_v6(skb, cp, pp, offset, hooknum, &ciph);
1684
1685 out:
1686         if (likely(!new_cp))
1687                 __ip_vs_conn_put(cp);
1688         else
1689                 ip_vs_conn_put(cp);
1690
1691         return verdict;
1692 }
1693 #endif
1694
1695
1696 /*
1697  *      Check if it's for virtual services, look it up,
1698  *      and send it on its way...
1699  */
1700 static unsigned int
1701 ip_vs_in(unsigned int hooknum, struct sk_buff *skb, int af)
1702 {
1703         struct net *net;
1704         struct ip_vs_iphdr iph;
1705         struct ip_vs_protocol *pp;
1706         struct ip_vs_proto_data *pd;
1707         struct ip_vs_conn *cp;
1708         int ret, pkts;
1709         struct netns_ipvs *ipvs;
1710         int conn_reuse_mode;
1711
1712         /* Already marked as IPVS request or reply? */
1713         if (skb->ipvs_property)
1714                 return NF_ACCEPT;
1715
1716         /*
1717          *      Big tappo:
1718          *      - remote client: only PACKET_HOST
1719          *      - route: used for struct net when skb->dev is unset
1720          */
1721         if (unlikely((skb->pkt_type != PACKET_HOST &&
1722                       hooknum != NF_INET_LOCAL_OUT) ||
1723                      !skb_dst(skb))) {
1724                 ip_vs_fill_iph_skb(af, skb, false, &iph);
1725                 IP_VS_DBG_BUF(12, "packet type=%d proto=%d daddr=%s"
1726                               " ignored in hook %u\n",
1727                               skb->pkt_type, iph.protocol,
1728                               IP_VS_DBG_ADDR(af, &iph.daddr), hooknum);
1729                 return NF_ACCEPT;
1730         }
1731         /* ipvs enabled in this netns ? */
1732         net = skb_net(skb);
1733         ipvs = net_ipvs(net);
1734         if (unlikely(sysctl_backup_only(ipvs) || !ipvs->enable))
1735                 return NF_ACCEPT;
1736
1737         ip_vs_fill_iph_skb(af, skb, false, &iph);
1738
1739         /* Bad... Do not break raw sockets */
1740         if (unlikely(skb->sk != NULL && hooknum == NF_INET_LOCAL_OUT &&
1741                      af == AF_INET)) {
1742                 struct sock *sk = skb->sk;
1743                 struct inet_sock *inet = inet_sk(skb->sk);
1744
1745                 if (inet && sk->sk_family == PF_INET && inet->nodefrag)
1746                         return NF_ACCEPT;
1747         }
1748
1749 #ifdef CONFIG_IP_VS_IPV6
1750         if (af == AF_INET6) {
1751                 if (unlikely(iph.protocol == IPPROTO_ICMPV6)) {
1752                         int related;
1753                         int verdict = ip_vs_in_icmp_v6(skb, &related, hooknum,
1754                                                        &iph);
1755
1756                         if (related)
1757                                 return verdict;
1758                 }
1759         } else
1760 #endif
1761                 if (unlikely(iph.protocol == IPPROTO_ICMP)) {
1762                         int related;
1763                         int verdict = ip_vs_in_icmp(skb, &related, hooknum);
1764
1765                         if (related)
1766                                 return verdict;
1767                 }
1768
1769         /* Protocol supported? */
1770         pd = ip_vs_proto_data_get(ipvs, iph.protocol);
1771         if (unlikely(!pd)) {
1772                 /* The only way we'll see this packet again is if it's
1773                  * encapsulated, so mark it with ipvs_property=1 so we
1774                  * skip it if we're ignoring tunneled packets
1775                  */
1776                 if (sysctl_ignore_tunneled(ipvs))
1777                         skb->ipvs_property = 1;
1778
1779                 return NF_ACCEPT;
1780         }
1781         pp = pd->pp;
1782         /*
1783          * Check if the packet belongs to an existing connection entry
1784          */
1785         cp = pp->conn_in_get(ipvs, af, skb, &iph);
1786
1787         conn_reuse_mode = sysctl_conn_reuse_mode(ipvs);
1788         if (conn_reuse_mode && !iph.fragoffs &&
1789             is_new_conn(skb, &iph) && cp &&
1790             ((unlikely(sysctl_expire_nodest_conn(ipvs)) && cp->dest &&
1791               unlikely(!atomic_read(&cp->dest->weight))) ||
1792              unlikely(is_new_conn_expected(cp, conn_reuse_mode)))) {
1793                 if (!atomic_read(&cp->n_control))
1794                         ip_vs_conn_expire_now(cp);
1795                 __ip_vs_conn_put(cp);
1796                 cp = NULL;
1797         }
1798
1799         if (unlikely(!cp)) {
1800                 int v;
1801
1802                 if (!ip_vs_try_to_schedule(af, skb, pd, &v, &cp, &iph))
1803                         return v;
1804         }
1805
1806         IP_VS_DBG_PKT(11, af, pp, skb, iph.off, "Incoming packet");
1807
1808         /* Check the server status */
1809         if (cp->dest && !(cp->dest->flags & IP_VS_DEST_F_AVAILABLE)) {
1810                 /* the destination server is not available */
1811
1812                 if (sysctl_expire_nodest_conn(ipvs)) {
1813                         /* try to expire the connection immediately */
1814                         ip_vs_conn_expire_now(cp);
1815                 }
1816                 /* don't restart its timer, and silently
1817                    drop the packet. */
1818                 __ip_vs_conn_put(cp);
1819                 return NF_DROP;
1820         }
1821
1822         ip_vs_in_stats(cp, skb);
1823         ip_vs_set_state(cp, IP_VS_DIR_INPUT, skb, pd);
1824         if (cp->packet_xmit)
1825                 ret = cp->packet_xmit(skb, cp, pp, &iph);
1826                 /* do not touch skb anymore */
1827         else {
1828                 IP_VS_DBG_RL("warning: packet_xmit is null");
1829                 ret = NF_ACCEPT;
1830         }
1831
1832         /* Increase its packet counter and check if it is needed
1833          * to be synchronized
1834          *
1835          * Sync connection if it is about to close to
1836          * encorage the standby servers to update the connections timeout
1837          *
1838          * For ONE_PKT let ip_vs_sync_conn() do the filter work.
1839          */
1840
1841         if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
1842                 pkts = sysctl_sync_threshold(ipvs);
1843         else
1844                 pkts = atomic_add_return(1, &cp->in_pkts);
1845
1846         if (ipvs->sync_state & IP_VS_STATE_MASTER)
1847                 ip_vs_sync_conn(ipvs, cp, pkts);
1848
1849         ip_vs_conn_put(cp);
1850         return ret;
1851 }
1852
1853 /*
1854  *      AF_INET handler in NF_INET_LOCAL_IN chain
1855  *      Schedule and forward packets from remote clients
1856  */
1857 static unsigned int
1858 ip_vs_remote_request4(void *priv, struct sk_buff *skb,
1859                       const struct nf_hook_state *state)
1860 {
1861         return ip_vs_in(state->hook, skb, AF_INET);
1862 }
1863
1864 /*
1865  *      AF_INET handler in NF_INET_LOCAL_OUT chain
1866  *      Schedule and forward packets from local clients
1867  */
1868 static unsigned int
1869 ip_vs_local_request4(void *priv, struct sk_buff *skb,
1870                      const struct nf_hook_state *state)
1871 {
1872         return ip_vs_in(state->hook, skb, AF_INET);
1873 }
1874
1875 #ifdef CONFIG_IP_VS_IPV6
1876
1877 /*
1878  *      AF_INET6 handler in NF_INET_LOCAL_IN chain
1879  *      Schedule and forward packets from remote clients
1880  */
1881 static unsigned int
1882 ip_vs_remote_request6(void *priv, struct sk_buff *skb,
1883                       const struct nf_hook_state *state)
1884 {
1885         return ip_vs_in(state->hook, skb, AF_INET6);
1886 }
1887
1888 /*
1889  *      AF_INET6 handler in NF_INET_LOCAL_OUT chain
1890  *      Schedule and forward packets from local clients
1891  */
1892 static unsigned int
1893 ip_vs_local_request6(void *priv, struct sk_buff *skb,
1894                      const struct nf_hook_state *state)
1895 {
1896         return ip_vs_in(state->hook, skb, AF_INET6);
1897 }
1898
1899 #endif
1900
1901
1902 /*
1903  *      It is hooked at the NF_INET_FORWARD chain, in order to catch ICMP
1904  *      related packets destined for 0.0.0.0/0.
1905  *      When fwmark-based virtual service is used, such as transparent
1906  *      cache cluster, TCP packets can be marked and routed to ip_vs_in,
1907  *      but ICMP destined for 0.0.0.0/0 cannot not be easily marked and
1908  *      sent to ip_vs_in_icmp. So, catch them at the NF_INET_FORWARD chain
1909  *      and send them to ip_vs_in_icmp.
1910  */
1911 static unsigned int
1912 ip_vs_forward_icmp(void *priv, struct sk_buff *skb,
1913                    const struct nf_hook_state *state)
1914 {
1915         int r;
1916         struct netns_ipvs *ipvs;
1917
1918         if (ip_hdr(skb)->protocol != IPPROTO_ICMP)
1919                 return NF_ACCEPT;
1920
1921         /* ipvs enabled in this netns ? */
1922         ipvs = net_ipvs(state->net);
1923         if (unlikely(sysctl_backup_only(ipvs) || !ipvs->enable))
1924                 return NF_ACCEPT;
1925
1926         return ip_vs_in_icmp(skb, &r, state->hook);
1927 }
1928
1929 #ifdef CONFIG_IP_VS_IPV6
1930 static unsigned int
1931 ip_vs_forward_icmp_v6(void *priv, struct sk_buff *skb,
1932                       const struct nf_hook_state *state)
1933 {
1934         int r;
1935         struct netns_ipvs *ipvs;
1936         struct ip_vs_iphdr iphdr;
1937
1938         ip_vs_fill_iph_skb(AF_INET6, skb, false, &iphdr);
1939         if (iphdr.protocol != IPPROTO_ICMPV6)
1940                 return NF_ACCEPT;
1941
1942         /* ipvs enabled in this netns ? */
1943         ipvs = net_ipvs(state->net);
1944         if (unlikely(sysctl_backup_only(ipvs) || !ipvs->enable))
1945                 return NF_ACCEPT;
1946
1947         return ip_vs_in_icmp_v6(skb, &r, state->hook, &iphdr);
1948 }
1949 #endif
1950
1951
1952 static struct nf_hook_ops ip_vs_ops[] __read_mostly = {
1953         /* After packet filtering, change source only for VS/NAT */
1954         {
1955                 .hook           = ip_vs_reply4,
1956                 .owner          = THIS_MODULE,
1957                 .pf             = NFPROTO_IPV4,
1958                 .hooknum        = NF_INET_LOCAL_IN,
1959                 .priority       = NF_IP_PRI_NAT_SRC - 2,
1960         },
1961         /* After packet filtering, forward packet through VS/DR, VS/TUN,
1962          * or VS/NAT(change destination), so that filtering rules can be
1963          * applied to IPVS. */
1964         {
1965                 .hook           = ip_vs_remote_request4,
1966                 .owner          = THIS_MODULE,
1967                 .pf             = NFPROTO_IPV4,
1968                 .hooknum        = NF_INET_LOCAL_IN,
1969                 .priority       = NF_IP_PRI_NAT_SRC - 1,
1970         },
1971         /* Before ip_vs_in, change source only for VS/NAT */
1972         {
1973                 .hook           = ip_vs_local_reply4,
1974                 .owner          = THIS_MODULE,
1975                 .pf             = NFPROTO_IPV4,
1976                 .hooknum        = NF_INET_LOCAL_OUT,
1977                 .priority       = NF_IP_PRI_NAT_DST + 1,
1978         },
1979         /* After mangle, schedule and forward local requests */
1980         {
1981                 .hook           = ip_vs_local_request4,
1982                 .owner          = THIS_MODULE,
1983                 .pf             = NFPROTO_IPV4,
1984                 .hooknum        = NF_INET_LOCAL_OUT,
1985                 .priority       = NF_IP_PRI_NAT_DST + 2,
1986         },
1987         /* After packet filtering (but before ip_vs_out_icmp), catch icmp
1988          * destined for 0.0.0.0/0, which is for incoming IPVS connections */
1989         {
1990                 .hook           = ip_vs_forward_icmp,
1991                 .owner          = THIS_MODULE,
1992                 .pf             = NFPROTO_IPV4,
1993                 .hooknum        = NF_INET_FORWARD,
1994                 .priority       = 99,
1995         },
1996         /* After packet filtering, change source only for VS/NAT */
1997         {
1998                 .hook           = ip_vs_reply4,
1999                 .owner          = THIS_MODULE,
2000                 .pf             = NFPROTO_IPV4,
2001                 .hooknum        = NF_INET_FORWARD,
2002                 .priority       = 100,
2003         },
2004 #ifdef CONFIG_IP_VS_IPV6
2005         /* After packet filtering, change source only for VS/NAT */
2006         {
2007                 .hook           = ip_vs_reply6,
2008                 .owner          = THIS_MODULE,
2009                 .pf             = NFPROTO_IPV6,
2010                 .hooknum        = NF_INET_LOCAL_IN,
2011                 .priority       = NF_IP6_PRI_NAT_SRC - 2,
2012         },
2013         /* After packet filtering, forward packet through VS/DR, VS/TUN,
2014          * or VS/NAT(change destination), so that filtering rules can be
2015          * applied to IPVS. */
2016         {
2017                 .hook           = ip_vs_remote_request6,
2018                 .owner          = THIS_MODULE,
2019                 .pf             = NFPROTO_IPV6,
2020                 .hooknum        = NF_INET_LOCAL_IN,
2021                 .priority       = NF_IP6_PRI_NAT_SRC - 1,
2022         },
2023         /* Before ip_vs_in, change source only for VS/NAT */
2024         {
2025                 .hook           = ip_vs_local_reply6,
2026                 .owner          = THIS_MODULE,
2027                 .pf             = NFPROTO_IPV6,
2028                 .hooknum        = NF_INET_LOCAL_OUT,
2029                 .priority       = NF_IP6_PRI_NAT_DST + 1,
2030         },
2031         /* After mangle, schedule and forward local requests */
2032         {
2033                 .hook           = ip_vs_local_request6,
2034                 .owner          = THIS_MODULE,
2035                 .pf             = NFPROTO_IPV6,
2036                 .hooknum        = NF_INET_LOCAL_OUT,
2037                 .priority       = NF_IP6_PRI_NAT_DST + 2,
2038         },
2039         /* After packet filtering (but before ip_vs_out_icmp), catch icmp
2040          * destined for 0.0.0.0/0, which is for incoming IPVS connections */
2041         {
2042                 .hook           = ip_vs_forward_icmp_v6,
2043                 .owner          = THIS_MODULE,
2044                 .pf             = NFPROTO_IPV6,
2045                 .hooknum        = NF_INET_FORWARD,
2046                 .priority       = 99,
2047         },
2048         /* After packet filtering, change source only for VS/NAT */
2049         {
2050                 .hook           = ip_vs_reply6,
2051                 .owner          = THIS_MODULE,
2052                 .pf             = NFPROTO_IPV6,
2053                 .hooknum        = NF_INET_FORWARD,
2054                 .priority       = 100,
2055         },
2056 #endif
2057 };
2058 /*
2059  *      Initialize IP Virtual Server netns mem.
2060  */
2061 static int __net_init __ip_vs_init(struct net *net)
2062 {
2063         struct netns_ipvs *ipvs;
2064
2065         ipvs = net_generic(net, ip_vs_net_id);
2066         if (ipvs == NULL)
2067                 return -ENOMEM;
2068
2069         /* Hold the beast until a service is registerd */
2070         ipvs->enable = 0;
2071         ipvs->net = net;
2072         /* Counters used for creating unique names */
2073         ipvs->gen = atomic_read(&ipvs_netns_cnt);
2074         atomic_inc(&ipvs_netns_cnt);
2075         net->ipvs = ipvs;
2076
2077         if (ip_vs_estimator_net_init(ipvs) < 0)
2078                 goto estimator_fail;
2079
2080         if (ip_vs_control_net_init(ipvs) < 0)
2081                 goto control_fail;
2082
2083         if (ip_vs_protocol_net_init(net) < 0)
2084                 goto protocol_fail;
2085
2086         if (ip_vs_app_net_init(ipvs) < 0)
2087                 goto app_fail;
2088
2089         if (ip_vs_conn_net_init(net) < 0)
2090                 goto conn_fail;
2091
2092         if (ip_vs_sync_net_init(ipvs) < 0)
2093                 goto sync_fail;
2094
2095         printk(KERN_INFO "IPVS: Creating netns size=%zu id=%d\n",
2096                          sizeof(struct netns_ipvs), ipvs->gen);
2097         return 0;
2098 /*
2099  * Error handling
2100  */
2101
2102 sync_fail:
2103         ip_vs_conn_net_cleanup(net);
2104 conn_fail:
2105         ip_vs_app_net_cleanup(ipvs);
2106 app_fail:
2107         ip_vs_protocol_net_cleanup(net);
2108 protocol_fail:
2109         ip_vs_control_net_cleanup(ipvs);
2110 control_fail:
2111         ip_vs_estimator_net_cleanup(ipvs);
2112 estimator_fail:
2113         net->ipvs = NULL;
2114         return -ENOMEM;
2115 }
2116
2117 static void __net_exit __ip_vs_cleanup(struct net *net)
2118 {
2119         struct netns_ipvs *ipvs = net_ipvs(net);
2120
2121         ip_vs_service_net_cleanup(ipvs);        /* ip_vs_flush() with locks */
2122         ip_vs_conn_net_cleanup(net);
2123         ip_vs_app_net_cleanup(ipvs);
2124         ip_vs_protocol_net_cleanup(net);
2125         ip_vs_control_net_cleanup(ipvs);
2126         ip_vs_estimator_net_cleanup(ipvs);
2127         IP_VS_DBG(2, "ipvs netns %d released\n", ipvs->gen);
2128         net->ipvs = NULL;
2129 }
2130
2131 static void __net_exit __ip_vs_dev_cleanup(struct net *net)
2132 {
2133         struct netns_ipvs *ipvs = net_ipvs(net);
2134         EnterFunction(2);
2135         ipvs->enable = 0;       /* Disable packet reception */
2136         smp_wmb();
2137         ip_vs_sync_net_cleanup(ipvs);
2138         LeaveFunction(2);
2139 }
2140
2141 static struct pernet_operations ipvs_core_ops = {
2142         .init = __ip_vs_init,
2143         .exit = __ip_vs_cleanup,
2144         .id   = &ip_vs_net_id,
2145         .size = sizeof(struct netns_ipvs),
2146 };
2147
2148 static struct pernet_operations ipvs_core_dev_ops = {
2149         .exit = __ip_vs_dev_cleanup,
2150 };
2151
2152 /*
2153  *      Initialize IP Virtual Server
2154  */
2155 static int __init ip_vs_init(void)
2156 {
2157         int ret;
2158
2159         ret = ip_vs_control_init();
2160         if (ret < 0) {
2161                 pr_err("can't setup control.\n");
2162                 goto exit;
2163         }
2164
2165         ip_vs_protocol_init();
2166
2167         ret = ip_vs_conn_init();
2168         if (ret < 0) {
2169                 pr_err("can't setup connection table.\n");
2170                 goto cleanup_protocol;
2171         }
2172
2173         ret = register_pernet_subsys(&ipvs_core_ops);   /* Alloc ip_vs struct */
2174         if (ret < 0)
2175                 goto cleanup_conn;
2176
2177         ret = register_pernet_device(&ipvs_core_dev_ops);
2178         if (ret < 0)
2179                 goto cleanup_sub;
2180
2181         ret = nf_register_hooks(ip_vs_ops, ARRAY_SIZE(ip_vs_ops));
2182         if (ret < 0) {
2183                 pr_err("can't register hooks.\n");
2184                 goto cleanup_dev;
2185         }
2186
2187         ret = ip_vs_register_nl_ioctl();
2188         if (ret < 0) {
2189                 pr_err("can't register netlink/ioctl.\n");
2190                 goto cleanup_hooks;
2191         }
2192
2193         pr_info("ipvs loaded.\n");
2194
2195         return ret;
2196
2197 cleanup_hooks:
2198         nf_unregister_hooks(ip_vs_ops, ARRAY_SIZE(ip_vs_ops));
2199 cleanup_dev:
2200         unregister_pernet_device(&ipvs_core_dev_ops);
2201 cleanup_sub:
2202         unregister_pernet_subsys(&ipvs_core_ops);
2203 cleanup_conn:
2204         ip_vs_conn_cleanup();
2205 cleanup_protocol:
2206         ip_vs_protocol_cleanup();
2207         ip_vs_control_cleanup();
2208 exit:
2209         return ret;
2210 }
2211
2212 static void __exit ip_vs_cleanup(void)
2213 {
2214         ip_vs_unregister_nl_ioctl();
2215         nf_unregister_hooks(ip_vs_ops, ARRAY_SIZE(ip_vs_ops));
2216         unregister_pernet_device(&ipvs_core_dev_ops);
2217         unregister_pernet_subsys(&ipvs_core_ops);       /* free ip_vs struct */
2218         ip_vs_conn_cleanup();
2219         ip_vs_protocol_cleanup();
2220         ip_vs_control_cleanup();
2221         pr_info("ipvs unloaded.\n");
2222 }
2223
2224 module_init(ip_vs_init);
2225 module_exit(ip_vs_cleanup);
2226 MODULE_LICENSE("GPL");