GNU Linux-libre 4.19.314-gnu1
[releases.git] / net / netfilter / ipvs / ip_vs_ctl.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  * Changes:
18  *
19  */
20
21 #define KMSG_COMPONENT "IPVS"
22 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
23
24 #include <linux/module.h>
25 #include <linux/init.h>
26 #include <linux/types.h>
27 #include <linux/capability.h>
28 #include <linux/fs.h>
29 #include <linux/sysctl.h>
30 #include <linux/proc_fs.h>
31 #include <linux/workqueue.h>
32 #include <linux/swap.h>
33 #include <linux/seq_file.h>
34 #include <linux/slab.h>
35
36 #include <linux/netfilter.h>
37 #include <linux/netfilter_ipv4.h>
38 #include <linux/mutex.h>
39
40 #include <net/net_namespace.h>
41 #include <linux/nsproxy.h>
42 #include <net/ip.h>
43 #ifdef CONFIG_IP_VS_IPV6
44 #include <net/ipv6.h>
45 #include <net/ip6_route.h>
46 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
47 #endif
48 #include <net/route.h>
49 #include <net/sock.h>
50 #include <net/genetlink.h>
51
52 #include <linux/uaccess.h>
53
54 #include <net/ip_vs.h>
55
56 /* semaphore for IPVS sockopts. And, [gs]etsockopt may sleep. */
57 static DEFINE_MUTEX(__ip_vs_mutex);
58
59 /* sysctl variables */
60
61 #ifdef CONFIG_IP_VS_DEBUG
62 static int sysctl_ip_vs_debug_level = 0;
63
64 int ip_vs_get_debug_level(void)
65 {
66         return sysctl_ip_vs_debug_level;
67 }
68 #endif
69
70
71 /*  Protos */
72 static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup);
73
74
75 #ifdef CONFIG_IP_VS_IPV6
76 /* Taken from rt6_fill_node() in net/ipv6/route.c, is there a better way? */
77 static bool __ip_vs_addr_is_local_v6(struct net *net,
78                                      const struct in6_addr *addr)
79 {
80         struct flowi6 fl6 = {
81                 .daddr = *addr,
82         };
83         struct dst_entry *dst = ip6_route_output(net, NULL, &fl6);
84         bool is_local;
85
86         is_local = !dst->error && dst->dev && (dst->dev->flags & IFF_LOOPBACK);
87
88         dst_release(dst);
89         return is_local;
90 }
91 #endif
92
93 #ifdef CONFIG_SYSCTL
94 /*
95  *      update_defense_level is called from keventd and from sysctl,
96  *      so it needs to protect itself from softirqs
97  */
98 static void update_defense_level(struct netns_ipvs *ipvs)
99 {
100         struct sysinfo i;
101         int availmem;
102         int nomem;
103         int to_change = -1;
104
105         /* we only count free and buffered memory (in pages) */
106         si_meminfo(&i);
107         availmem = i.freeram + i.bufferram;
108         /* however in linux 2.5 the i.bufferram is total page cache size,
109            we need adjust it */
110         /* si_swapinfo(&i); */
111         /* availmem = availmem - (i.totalswap - i.freeswap); */
112
113         nomem = (availmem < ipvs->sysctl_amemthresh);
114
115         local_bh_disable();
116
117         /* drop_entry */
118         spin_lock(&ipvs->dropentry_lock);
119         switch (ipvs->sysctl_drop_entry) {
120         case 0:
121                 atomic_set(&ipvs->dropentry, 0);
122                 break;
123         case 1:
124                 if (nomem) {
125                         atomic_set(&ipvs->dropentry, 1);
126                         ipvs->sysctl_drop_entry = 2;
127                 } else {
128                         atomic_set(&ipvs->dropentry, 0);
129                 }
130                 break;
131         case 2:
132                 if (nomem) {
133                         atomic_set(&ipvs->dropentry, 1);
134                 } else {
135                         atomic_set(&ipvs->dropentry, 0);
136                         ipvs->sysctl_drop_entry = 1;
137                 }
138                 break;
139         case 3:
140                 atomic_set(&ipvs->dropentry, 1);
141                 break;
142         }
143         spin_unlock(&ipvs->dropentry_lock);
144
145         /* drop_packet */
146         spin_lock(&ipvs->droppacket_lock);
147         switch (ipvs->sysctl_drop_packet) {
148         case 0:
149                 ipvs->drop_rate = 0;
150                 break;
151         case 1:
152                 if (nomem) {
153                         ipvs->drop_rate = ipvs->drop_counter
154                                 = ipvs->sysctl_amemthresh /
155                                 (ipvs->sysctl_amemthresh-availmem);
156                         ipvs->sysctl_drop_packet = 2;
157                 } else {
158                         ipvs->drop_rate = 0;
159                 }
160                 break;
161         case 2:
162                 if (nomem) {
163                         ipvs->drop_rate = ipvs->drop_counter
164                                 = ipvs->sysctl_amemthresh /
165                                 (ipvs->sysctl_amemthresh-availmem);
166                 } else {
167                         ipvs->drop_rate = 0;
168                         ipvs->sysctl_drop_packet = 1;
169                 }
170                 break;
171         case 3:
172                 ipvs->drop_rate = ipvs->sysctl_am_droprate;
173                 break;
174         }
175         spin_unlock(&ipvs->droppacket_lock);
176
177         /* secure_tcp */
178         spin_lock(&ipvs->securetcp_lock);
179         switch (ipvs->sysctl_secure_tcp) {
180         case 0:
181                 if (ipvs->old_secure_tcp >= 2)
182                         to_change = 0;
183                 break;
184         case 1:
185                 if (nomem) {
186                         if (ipvs->old_secure_tcp < 2)
187                                 to_change = 1;
188                         ipvs->sysctl_secure_tcp = 2;
189                 } else {
190                         if (ipvs->old_secure_tcp >= 2)
191                                 to_change = 0;
192                 }
193                 break;
194         case 2:
195                 if (nomem) {
196                         if (ipvs->old_secure_tcp < 2)
197                                 to_change = 1;
198                 } else {
199                         if (ipvs->old_secure_tcp >= 2)
200                                 to_change = 0;
201                         ipvs->sysctl_secure_tcp = 1;
202                 }
203                 break;
204         case 3:
205                 if (ipvs->old_secure_tcp < 2)
206                         to_change = 1;
207                 break;
208         }
209         ipvs->old_secure_tcp = ipvs->sysctl_secure_tcp;
210         if (to_change >= 0)
211                 ip_vs_protocol_timeout_change(ipvs,
212                                               ipvs->sysctl_secure_tcp > 1);
213         spin_unlock(&ipvs->securetcp_lock);
214
215         local_bh_enable();
216 }
217
218
219 /*
220  *      Timer for checking the defense
221  */
222 #define DEFENSE_TIMER_PERIOD    1*HZ
223
224 static void defense_work_handler(struct work_struct *work)
225 {
226         struct netns_ipvs *ipvs =
227                 container_of(work, struct netns_ipvs, defense_work.work);
228
229         update_defense_level(ipvs);
230         if (atomic_read(&ipvs->dropentry))
231                 ip_vs_random_dropentry(ipvs);
232         schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD);
233 }
234 #endif
235
236 int
237 ip_vs_use_count_inc(void)
238 {
239         return try_module_get(THIS_MODULE);
240 }
241
242 void
243 ip_vs_use_count_dec(void)
244 {
245         module_put(THIS_MODULE);
246 }
247
248
249 /*
250  *      Hash table: for virtual service lookups
251  */
252 #define IP_VS_SVC_TAB_BITS 8
253 #define IP_VS_SVC_TAB_SIZE (1 << IP_VS_SVC_TAB_BITS)
254 #define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1)
255
256 /* the service table hashed by <protocol, addr, port> */
257 static struct hlist_head ip_vs_svc_table[IP_VS_SVC_TAB_SIZE];
258 /* the service table hashed by fwmark */
259 static struct hlist_head ip_vs_svc_fwm_table[IP_VS_SVC_TAB_SIZE];
260
261
262 /*
263  *      Returns hash value for virtual service
264  */
265 static inline unsigned int
266 ip_vs_svc_hashkey(struct netns_ipvs *ipvs, int af, unsigned int proto,
267                   const union nf_inet_addr *addr, __be16 port)
268 {
269         register unsigned int porth = ntohs(port);
270         __be32 addr_fold = addr->ip;
271         __u32 ahash;
272
273 #ifdef CONFIG_IP_VS_IPV6
274         if (af == AF_INET6)
275                 addr_fold = addr->ip6[0]^addr->ip6[1]^
276                             addr->ip6[2]^addr->ip6[3];
277 #endif
278         ahash = ntohl(addr_fold);
279         ahash ^= ((size_t) ipvs >> 8);
280
281         return (proto ^ ahash ^ (porth >> IP_VS_SVC_TAB_BITS) ^ porth) &
282                IP_VS_SVC_TAB_MASK;
283 }
284
285 /*
286  *      Returns hash value of fwmark for virtual service lookup
287  */
288 static inline unsigned int ip_vs_svc_fwm_hashkey(struct netns_ipvs *ipvs, __u32 fwmark)
289 {
290         return (((size_t)ipvs>>8) ^ fwmark) & IP_VS_SVC_TAB_MASK;
291 }
292
293 /*
294  *      Hashes a service in the ip_vs_svc_table by <netns,proto,addr,port>
295  *      or in the ip_vs_svc_fwm_table by fwmark.
296  *      Should be called with locked tables.
297  */
298 static int ip_vs_svc_hash(struct ip_vs_service *svc)
299 {
300         unsigned int hash;
301
302         if (svc->flags & IP_VS_SVC_F_HASHED) {
303                 pr_err("%s(): request for already hashed, called from %pS\n",
304                        __func__, __builtin_return_address(0));
305                 return 0;
306         }
307
308         if (svc->fwmark == 0) {
309                 /*
310                  *  Hash it by <netns,protocol,addr,port> in ip_vs_svc_table
311                  */
312                 hash = ip_vs_svc_hashkey(svc->ipvs, svc->af, svc->protocol,
313                                          &svc->addr, svc->port);
314                 hlist_add_head_rcu(&svc->s_list, &ip_vs_svc_table[hash]);
315         } else {
316                 /*
317                  *  Hash it by fwmark in svc_fwm_table
318                  */
319                 hash = ip_vs_svc_fwm_hashkey(svc->ipvs, svc->fwmark);
320                 hlist_add_head_rcu(&svc->f_list, &ip_vs_svc_fwm_table[hash]);
321         }
322
323         svc->flags |= IP_VS_SVC_F_HASHED;
324         /* increase its refcnt because it is referenced by the svc table */
325         atomic_inc(&svc->refcnt);
326         return 1;
327 }
328
329
330 /*
331  *      Unhashes a service from svc_table / svc_fwm_table.
332  *      Should be called with locked tables.
333  */
334 static int ip_vs_svc_unhash(struct ip_vs_service *svc)
335 {
336         if (!(svc->flags & IP_VS_SVC_F_HASHED)) {
337                 pr_err("%s(): request for unhash flagged, called from %pS\n",
338                        __func__, __builtin_return_address(0));
339                 return 0;
340         }
341
342         if (svc->fwmark == 0) {
343                 /* Remove it from the svc_table table */
344                 hlist_del_rcu(&svc->s_list);
345         } else {
346                 /* Remove it from the svc_fwm_table table */
347                 hlist_del_rcu(&svc->f_list);
348         }
349
350         svc->flags &= ~IP_VS_SVC_F_HASHED;
351         atomic_dec(&svc->refcnt);
352         return 1;
353 }
354
355
356 /*
357  *      Get service by {netns, proto,addr,port} in the service table.
358  */
359 static inline struct ip_vs_service *
360 __ip_vs_service_find(struct netns_ipvs *ipvs, int af, __u16 protocol,
361                      const union nf_inet_addr *vaddr, __be16 vport)
362 {
363         unsigned int hash;
364         struct ip_vs_service *svc;
365
366         /* Check for "full" addressed entries */
367         hash = ip_vs_svc_hashkey(ipvs, af, protocol, vaddr, vport);
368
369         hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[hash], s_list) {
370                 if ((svc->af == af)
371                     && ip_vs_addr_equal(af, &svc->addr, vaddr)
372                     && (svc->port == vport)
373                     && (svc->protocol == protocol)
374                     && (svc->ipvs == ipvs)) {
375                         /* HIT */
376                         return svc;
377                 }
378         }
379
380         return NULL;
381 }
382
383
384 /*
385  *      Get service by {fwmark} in the service table.
386  */
387 static inline struct ip_vs_service *
388 __ip_vs_svc_fwm_find(struct netns_ipvs *ipvs, int af, __u32 fwmark)
389 {
390         unsigned int hash;
391         struct ip_vs_service *svc;
392
393         /* Check for fwmark addressed entries */
394         hash = ip_vs_svc_fwm_hashkey(ipvs, fwmark);
395
396         hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[hash], f_list) {
397                 if (svc->fwmark == fwmark && svc->af == af
398                     && (svc->ipvs == ipvs)) {
399                         /* HIT */
400                         return svc;
401                 }
402         }
403
404         return NULL;
405 }
406
407 /* Find service, called under RCU lock */
408 struct ip_vs_service *
409 ip_vs_service_find(struct netns_ipvs *ipvs, int af, __u32 fwmark, __u16 protocol,
410                    const union nf_inet_addr *vaddr, __be16 vport)
411 {
412         struct ip_vs_service *svc;
413
414         /*
415          *      Check the table hashed by fwmark first
416          */
417         if (fwmark) {
418                 svc = __ip_vs_svc_fwm_find(ipvs, af, fwmark);
419                 if (svc)
420                         goto out;
421         }
422
423         /*
424          *      Check the table hashed by <protocol,addr,port>
425          *      for "full" addressed entries
426          */
427         svc = __ip_vs_service_find(ipvs, af, protocol, vaddr, vport);
428
429         if (!svc && protocol == IPPROTO_TCP &&
430             atomic_read(&ipvs->ftpsvc_counter) &&
431             (vport == FTPDATA || ntohs(vport) >= inet_prot_sock(ipvs->net))) {
432                 /*
433                  * Check if ftp service entry exists, the packet
434                  * might belong to FTP data connections.
435                  */
436                 svc = __ip_vs_service_find(ipvs, af, protocol, vaddr, FTPPORT);
437         }
438
439         if (svc == NULL
440             && atomic_read(&ipvs->nullsvc_counter)) {
441                 /*
442                  * Check if the catch-all port (port zero) exists
443                  */
444                 svc = __ip_vs_service_find(ipvs, af, protocol, vaddr, 0);
445         }
446
447   out:
448         IP_VS_DBG_BUF(9, "lookup service: fwm %u %s %s:%u %s\n",
449                       fwmark, ip_vs_proto_name(protocol),
450                       IP_VS_DBG_ADDR(af, vaddr), ntohs(vport),
451                       svc ? "hit" : "not hit");
452
453         return svc;
454 }
455
456
457 static inline void
458 __ip_vs_bind_svc(struct ip_vs_dest *dest, struct ip_vs_service *svc)
459 {
460         atomic_inc(&svc->refcnt);
461         rcu_assign_pointer(dest->svc, svc);
462 }
463
464 static void ip_vs_service_free(struct ip_vs_service *svc)
465 {
466         free_percpu(svc->stats.cpustats);
467         kfree(svc);
468 }
469
470 static void ip_vs_service_rcu_free(struct rcu_head *head)
471 {
472         struct ip_vs_service *svc;
473
474         svc = container_of(head, struct ip_vs_service, rcu_head);
475         ip_vs_service_free(svc);
476 }
477
478 static void __ip_vs_svc_put(struct ip_vs_service *svc, bool do_delay)
479 {
480         if (atomic_dec_and_test(&svc->refcnt)) {
481                 IP_VS_DBG_BUF(3, "Removing service %u/%s:%u\n",
482                               svc->fwmark,
483                               IP_VS_DBG_ADDR(svc->af, &svc->addr),
484                               ntohs(svc->port));
485                 if (do_delay)
486                         call_rcu(&svc->rcu_head, ip_vs_service_rcu_free);
487                 else
488                         ip_vs_service_free(svc);
489         }
490 }
491
492
493 /*
494  *      Returns hash value for real service
495  */
496 static inline unsigned int ip_vs_rs_hashkey(int af,
497                                             const union nf_inet_addr *addr,
498                                             __be16 port)
499 {
500         register unsigned int porth = ntohs(port);
501         __be32 addr_fold = addr->ip;
502
503 #ifdef CONFIG_IP_VS_IPV6
504         if (af == AF_INET6)
505                 addr_fold = addr->ip6[0]^addr->ip6[1]^
506                             addr->ip6[2]^addr->ip6[3];
507 #endif
508
509         return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth)
510                 & IP_VS_RTAB_MASK;
511 }
512
513 /* Hash ip_vs_dest in rs_table by <proto,addr,port>. */
514 static void ip_vs_rs_hash(struct netns_ipvs *ipvs, struct ip_vs_dest *dest)
515 {
516         unsigned int hash;
517
518         if (dest->in_rs_table)
519                 return;
520
521         /*
522          *      Hash by proto,addr,port,
523          *      which are the parameters of the real service.
524          */
525         hash = ip_vs_rs_hashkey(dest->af, &dest->addr, dest->port);
526
527         hlist_add_head_rcu(&dest->d_list, &ipvs->rs_table[hash]);
528         dest->in_rs_table = 1;
529 }
530
531 /* Unhash ip_vs_dest from rs_table. */
532 static void ip_vs_rs_unhash(struct ip_vs_dest *dest)
533 {
534         /*
535          * Remove it from the rs_table table.
536          */
537         if (dest->in_rs_table) {
538                 hlist_del_rcu(&dest->d_list);
539                 dest->in_rs_table = 0;
540         }
541 }
542
543 /* Check if real service by <proto,addr,port> is present */
544 bool ip_vs_has_real_service(struct netns_ipvs *ipvs, int af, __u16 protocol,
545                             const union nf_inet_addr *daddr, __be16 dport)
546 {
547         unsigned int hash;
548         struct ip_vs_dest *dest;
549
550         /* Check for "full" addressed entries */
551         hash = ip_vs_rs_hashkey(af, daddr, dport);
552
553         hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
554                 if (dest->port == dport &&
555                     dest->af == af &&
556                     ip_vs_addr_equal(af, &dest->addr, daddr) &&
557                     (dest->protocol == protocol || dest->vfwmark)) {
558                         /* HIT */
559                         return true;
560                 }
561         }
562
563         return false;
564 }
565
566 /* Find real service record by <proto,addr,port>.
567  * In case of multiple records with the same <proto,addr,port>, only
568  * the first found record is returned.
569  *
570  * To be called under RCU lock.
571  */
572 struct ip_vs_dest *ip_vs_find_real_service(struct netns_ipvs *ipvs, int af,
573                                            __u16 protocol,
574                                            const union nf_inet_addr *daddr,
575                                            __be16 dport)
576 {
577         unsigned int hash;
578         struct ip_vs_dest *dest;
579
580         /* Check for "full" addressed entries */
581         hash = ip_vs_rs_hashkey(af, daddr, dport);
582
583         hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
584                 if (dest->port == dport &&
585                     dest->af == af &&
586                     ip_vs_addr_equal(af, &dest->addr, daddr) &&
587                         (dest->protocol == protocol || dest->vfwmark)) {
588                         /* HIT */
589                         return dest;
590                 }
591         }
592
593         return NULL;
594 }
595
596 /* Lookup destination by {addr,port} in the given service
597  * Called under RCU lock.
598  */
599 static struct ip_vs_dest *
600 ip_vs_lookup_dest(struct ip_vs_service *svc, int dest_af,
601                   const union nf_inet_addr *daddr, __be16 dport)
602 {
603         struct ip_vs_dest *dest;
604
605         /*
606          * Find the destination for the given service
607          */
608         list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
609                 if ((dest->af == dest_af) &&
610                     ip_vs_addr_equal(dest_af, &dest->addr, daddr) &&
611                     (dest->port == dport)) {
612                         /* HIT */
613                         return dest;
614                 }
615         }
616
617         return NULL;
618 }
619
620 /*
621  * Find destination by {daddr,dport,vaddr,protocol}
622  * Created to be used in ip_vs_process_message() in
623  * the backup synchronization daemon. It finds the
624  * destination to be bound to the received connection
625  * on the backup.
626  * Called under RCU lock, no refcnt is returned.
627  */
628 struct ip_vs_dest *ip_vs_find_dest(struct netns_ipvs *ipvs, int svc_af, int dest_af,
629                                    const union nf_inet_addr *daddr,
630                                    __be16 dport,
631                                    const union nf_inet_addr *vaddr,
632                                    __be16 vport, __u16 protocol, __u32 fwmark,
633                                    __u32 flags)
634 {
635         struct ip_vs_dest *dest;
636         struct ip_vs_service *svc;
637         __be16 port = dport;
638
639         svc = ip_vs_service_find(ipvs, svc_af, fwmark, protocol, vaddr, vport);
640         if (!svc)
641                 return NULL;
642         if (fwmark && (flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ)
643                 port = 0;
644         dest = ip_vs_lookup_dest(svc, dest_af, daddr, port);
645         if (!dest)
646                 dest = ip_vs_lookup_dest(svc, dest_af, daddr, port ^ dport);
647         return dest;
648 }
649
650 void ip_vs_dest_dst_rcu_free(struct rcu_head *head)
651 {
652         struct ip_vs_dest_dst *dest_dst = container_of(head,
653                                                        struct ip_vs_dest_dst,
654                                                        rcu_head);
655
656         dst_release(dest_dst->dst_cache);
657         kfree(dest_dst);
658 }
659
660 /* Release dest_dst and dst_cache for dest in user context */
661 static void __ip_vs_dst_cache_reset(struct ip_vs_dest *dest)
662 {
663         struct ip_vs_dest_dst *old;
664
665         old = rcu_dereference_protected(dest->dest_dst, 1);
666         if (old) {
667                 RCU_INIT_POINTER(dest->dest_dst, NULL);
668                 call_rcu(&old->rcu_head, ip_vs_dest_dst_rcu_free);
669         }
670 }
671
672 /*
673  *  Lookup dest by {svc,addr,port} in the destination trash.
674  *  The destination trash is used to hold the destinations that are removed
675  *  from the service table but are still referenced by some conn entries.
676  *  The reason to add the destination trash is when the dest is temporary
677  *  down (either by administrator or by monitor program), the dest can be
678  *  picked back from the trash, the remaining connections to the dest can
679  *  continue, and the counting information of the dest is also useful for
680  *  scheduling.
681  */
682 static struct ip_vs_dest *
683 ip_vs_trash_get_dest(struct ip_vs_service *svc, int dest_af,
684                      const union nf_inet_addr *daddr, __be16 dport)
685 {
686         struct ip_vs_dest *dest;
687         struct netns_ipvs *ipvs = svc->ipvs;
688
689         /*
690          * Find the destination in trash
691          */
692         spin_lock_bh(&ipvs->dest_trash_lock);
693         list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
694                 IP_VS_DBG_BUF(3, "Destination %u/%s:%u still in trash, "
695                               "dest->refcnt=%d\n",
696                               dest->vfwmark,
697                               IP_VS_DBG_ADDR(dest->af, &dest->addr),
698                               ntohs(dest->port),
699                               refcount_read(&dest->refcnt));
700                 if (dest->af == dest_af &&
701                     ip_vs_addr_equal(dest_af, &dest->addr, daddr) &&
702                     dest->port == dport &&
703                     dest->vfwmark == svc->fwmark &&
704                     dest->protocol == svc->protocol &&
705                     (svc->fwmark ||
706                      (ip_vs_addr_equal(svc->af, &dest->vaddr, &svc->addr) &&
707                       dest->vport == svc->port))) {
708                         /* HIT */
709                         list_del(&dest->t_list);
710                         goto out;
711                 }
712         }
713
714         dest = NULL;
715
716 out:
717         spin_unlock_bh(&ipvs->dest_trash_lock);
718
719         return dest;
720 }
721
722 static void ip_vs_dest_free(struct ip_vs_dest *dest)
723 {
724         struct ip_vs_service *svc = rcu_dereference_protected(dest->svc, 1);
725
726         __ip_vs_dst_cache_reset(dest);
727         __ip_vs_svc_put(svc, false);
728         free_percpu(dest->stats.cpustats);
729         ip_vs_dest_put_and_free(dest);
730 }
731
732 /*
733  *  Clean up all the destinations in the trash
734  *  Called by the ip_vs_control_cleanup()
735  *
736  *  When the ip_vs_control_clearup is activated by ipvs module exit,
737  *  the service tables must have been flushed and all the connections
738  *  are expired, and the refcnt of each destination in the trash must
739  *  be 1, so we simply release them here.
740  */
741 static void ip_vs_trash_cleanup(struct netns_ipvs *ipvs)
742 {
743         struct ip_vs_dest *dest, *nxt;
744
745         del_timer_sync(&ipvs->dest_trash_timer);
746         /* No need to use dest_trash_lock */
747         list_for_each_entry_safe(dest, nxt, &ipvs->dest_trash, t_list) {
748                 list_del(&dest->t_list);
749                 ip_vs_dest_free(dest);
750         }
751 }
752
753 static void
754 ip_vs_copy_stats(struct ip_vs_kstats *dst, struct ip_vs_stats *src)
755 {
756 #define IP_VS_SHOW_STATS_COUNTER(c) dst->c = src->kstats.c - src->kstats0.c
757
758         spin_lock_bh(&src->lock);
759
760         IP_VS_SHOW_STATS_COUNTER(conns);
761         IP_VS_SHOW_STATS_COUNTER(inpkts);
762         IP_VS_SHOW_STATS_COUNTER(outpkts);
763         IP_VS_SHOW_STATS_COUNTER(inbytes);
764         IP_VS_SHOW_STATS_COUNTER(outbytes);
765
766         ip_vs_read_estimator(dst, src);
767
768         spin_unlock_bh(&src->lock);
769 }
770
771 static void
772 ip_vs_export_stats_user(struct ip_vs_stats_user *dst, struct ip_vs_kstats *src)
773 {
774         dst->conns = (u32)src->conns;
775         dst->inpkts = (u32)src->inpkts;
776         dst->outpkts = (u32)src->outpkts;
777         dst->inbytes = src->inbytes;
778         dst->outbytes = src->outbytes;
779         dst->cps = (u32)src->cps;
780         dst->inpps = (u32)src->inpps;
781         dst->outpps = (u32)src->outpps;
782         dst->inbps = (u32)src->inbps;
783         dst->outbps = (u32)src->outbps;
784 }
785
786 static void
787 ip_vs_zero_stats(struct ip_vs_stats *stats)
788 {
789         spin_lock_bh(&stats->lock);
790
791         /* get current counters as zero point, rates are zeroed */
792
793 #define IP_VS_ZERO_STATS_COUNTER(c) stats->kstats0.c = stats->kstats.c
794
795         IP_VS_ZERO_STATS_COUNTER(conns);
796         IP_VS_ZERO_STATS_COUNTER(inpkts);
797         IP_VS_ZERO_STATS_COUNTER(outpkts);
798         IP_VS_ZERO_STATS_COUNTER(inbytes);
799         IP_VS_ZERO_STATS_COUNTER(outbytes);
800
801         ip_vs_zero_estimator(stats);
802
803         spin_unlock_bh(&stats->lock);
804 }
805
806 /*
807  *      Update a destination in the given service
808  */
809 static void
810 __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest,
811                     struct ip_vs_dest_user_kern *udest, int add)
812 {
813         struct netns_ipvs *ipvs = svc->ipvs;
814         struct ip_vs_service *old_svc;
815         struct ip_vs_scheduler *sched;
816         int conn_flags;
817
818         /* We cannot modify an address and change the address family */
819         BUG_ON(!add && udest->af != dest->af);
820
821         if (add && udest->af != svc->af)
822                 ipvs->mixed_address_family_dests++;
823
824         /* keep the last_weight with latest non-0 weight */
825         if (add || udest->weight != 0)
826                 atomic_set(&dest->last_weight, udest->weight);
827
828         /* set the weight and the flags */
829         atomic_set(&dest->weight, udest->weight);
830         conn_flags = udest->conn_flags & IP_VS_CONN_F_DEST_MASK;
831         conn_flags |= IP_VS_CONN_F_INACTIVE;
832
833         /* set the IP_VS_CONN_F_NOOUTPUT flag if not masquerading/NAT */
834         if ((conn_flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ) {
835                 conn_flags |= IP_VS_CONN_F_NOOUTPUT;
836         } else {
837                 /*
838                  *    Put the real service in rs_table if not present.
839                  *    For now only for NAT!
840                  */
841                 ip_vs_rs_hash(ipvs, dest);
842                 /* FTP-NAT requires conntrack for mangling */
843                 if (svc->port == FTPPORT)
844                         ip_vs_register_conntrack(svc);
845         }
846         atomic_set(&dest->conn_flags, conn_flags);
847
848         /* bind the service */
849         old_svc = rcu_dereference_protected(dest->svc, 1);
850         if (!old_svc) {
851                 __ip_vs_bind_svc(dest, svc);
852         } else {
853                 if (old_svc != svc) {
854                         ip_vs_zero_stats(&dest->stats);
855                         __ip_vs_bind_svc(dest, svc);
856                         __ip_vs_svc_put(old_svc, true);
857                 }
858         }
859
860         /* set the dest status flags */
861         dest->flags |= IP_VS_DEST_F_AVAILABLE;
862
863         if (udest->u_threshold == 0 || udest->u_threshold > dest->u_threshold)
864                 dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
865         dest->u_threshold = udest->u_threshold;
866         dest->l_threshold = udest->l_threshold;
867
868         dest->af = udest->af;
869
870         spin_lock_bh(&dest->dst_lock);
871         __ip_vs_dst_cache_reset(dest);
872         spin_unlock_bh(&dest->dst_lock);
873
874         if (add) {
875                 ip_vs_start_estimator(svc->ipvs, &dest->stats);
876                 list_add_rcu(&dest->n_list, &svc->destinations);
877                 svc->num_dests++;
878                 sched = rcu_dereference_protected(svc->scheduler, 1);
879                 if (sched && sched->add_dest)
880                         sched->add_dest(svc, dest);
881         } else {
882                 sched = rcu_dereference_protected(svc->scheduler, 1);
883                 if (sched && sched->upd_dest)
884                         sched->upd_dest(svc, dest);
885         }
886 }
887
888
889 /*
890  *      Create a destination for the given service
891  */
892 static int
893 ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest,
894                struct ip_vs_dest **dest_p)
895 {
896         struct ip_vs_dest *dest;
897         unsigned int atype, i;
898
899         EnterFunction(2);
900
901 #ifdef CONFIG_IP_VS_IPV6
902         if (udest->af == AF_INET6) {
903                 int ret;
904
905                 atype = ipv6_addr_type(&udest->addr.in6);
906                 if ((!(atype & IPV6_ADDR_UNICAST) ||
907                         atype & IPV6_ADDR_LINKLOCAL) &&
908                         !__ip_vs_addr_is_local_v6(svc->ipvs->net, &udest->addr.in6))
909                         return -EINVAL;
910
911                 ret = nf_defrag_ipv6_enable(svc->ipvs->net);
912                 if (ret)
913                         return ret;
914         } else
915 #endif
916         {
917                 atype = inet_addr_type(svc->ipvs->net, udest->addr.ip);
918                 if (atype != RTN_LOCAL && atype != RTN_UNICAST)
919                         return -EINVAL;
920         }
921
922         dest = kzalloc(sizeof(struct ip_vs_dest), GFP_KERNEL);
923         if (dest == NULL)
924                 return -ENOMEM;
925
926         dest->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
927         if (!dest->stats.cpustats)
928                 goto err_alloc;
929
930         for_each_possible_cpu(i) {
931                 struct ip_vs_cpu_stats *ip_vs_dest_stats;
932                 ip_vs_dest_stats = per_cpu_ptr(dest->stats.cpustats, i);
933                 u64_stats_init(&ip_vs_dest_stats->syncp);
934         }
935
936         dest->af = udest->af;
937         dest->protocol = svc->protocol;
938         dest->vaddr = svc->addr;
939         dest->vport = svc->port;
940         dest->vfwmark = svc->fwmark;
941         ip_vs_addr_copy(udest->af, &dest->addr, &udest->addr);
942         dest->port = udest->port;
943
944         atomic_set(&dest->activeconns, 0);
945         atomic_set(&dest->inactconns, 0);
946         atomic_set(&dest->persistconns, 0);
947         refcount_set(&dest->refcnt, 1);
948
949         INIT_HLIST_NODE(&dest->d_list);
950         spin_lock_init(&dest->dst_lock);
951         spin_lock_init(&dest->stats.lock);
952         __ip_vs_update_dest(svc, dest, udest, 1);
953
954         *dest_p = dest;
955
956         LeaveFunction(2);
957         return 0;
958
959 err_alloc:
960         kfree(dest);
961         return -ENOMEM;
962 }
963
964
965 /*
966  *      Add a destination into an existing service
967  */
968 static int
969 ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
970 {
971         struct ip_vs_dest *dest;
972         union nf_inet_addr daddr;
973         __be16 dport = udest->port;
974         int ret;
975
976         EnterFunction(2);
977
978         if (udest->weight < 0) {
979                 pr_err("%s(): server weight less than zero\n", __func__);
980                 return -ERANGE;
981         }
982
983         if (udest->l_threshold > udest->u_threshold) {
984                 pr_err("%s(): lower threshold is higher than upper threshold\n",
985                         __func__);
986                 return -ERANGE;
987         }
988
989         ip_vs_addr_copy(udest->af, &daddr, &udest->addr);
990
991         /* We use function that requires RCU lock */
992         rcu_read_lock();
993         dest = ip_vs_lookup_dest(svc, udest->af, &daddr, dport);
994         rcu_read_unlock();
995
996         if (dest != NULL) {
997                 IP_VS_DBG(1, "%s(): dest already exists\n", __func__);
998                 return -EEXIST;
999         }
1000
1001         /*
1002          * Check if the dest already exists in the trash and
1003          * is from the same service
1004          */
1005         dest = ip_vs_trash_get_dest(svc, udest->af, &daddr, dport);
1006
1007         if (dest != NULL) {
1008                 IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, "
1009                               "dest->refcnt=%d, service %u/%s:%u\n",
1010                               IP_VS_DBG_ADDR(udest->af, &daddr), ntohs(dport),
1011                               refcount_read(&dest->refcnt),
1012                               dest->vfwmark,
1013                               IP_VS_DBG_ADDR(svc->af, &dest->vaddr),
1014                               ntohs(dest->vport));
1015
1016                 __ip_vs_update_dest(svc, dest, udest, 1);
1017                 ret = 0;
1018         } else {
1019                 /*
1020                  * Allocate and initialize the dest structure
1021                  */
1022                 ret = ip_vs_new_dest(svc, udest, &dest);
1023         }
1024         LeaveFunction(2);
1025
1026         return ret;
1027 }
1028
1029
1030 /*
1031  *      Edit a destination in the given service
1032  */
1033 static int
1034 ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
1035 {
1036         struct ip_vs_dest *dest;
1037         union nf_inet_addr daddr;
1038         __be16 dport = udest->port;
1039
1040         EnterFunction(2);
1041
1042         if (udest->weight < 0) {
1043                 pr_err("%s(): server weight less than zero\n", __func__);
1044                 return -ERANGE;
1045         }
1046
1047         if (udest->l_threshold > udest->u_threshold) {
1048                 pr_err("%s(): lower threshold is higher than upper threshold\n",
1049                         __func__);
1050                 return -ERANGE;
1051         }
1052
1053         ip_vs_addr_copy(udest->af, &daddr, &udest->addr);
1054
1055         /* We use function that requires RCU lock */
1056         rcu_read_lock();
1057         dest = ip_vs_lookup_dest(svc, udest->af, &daddr, dport);
1058         rcu_read_unlock();
1059
1060         if (dest == NULL) {
1061                 IP_VS_DBG(1, "%s(): dest doesn't exist\n", __func__);
1062                 return -ENOENT;
1063         }
1064
1065         __ip_vs_update_dest(svc, dest, udest, 0);
1066         LeaveFunction(2);
1067
1068         return 0;
1069 }
1070
1071 /*
1072  *      Delete a destination (must be already unlinked from the service)
1073  */
1074 static void __ip_vs_del_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest,
1075                              bool cleanup)
1076 {
1077         ip_vs_stop_estimator(ipvs, &dest->stats);
1078
1079         /*
1080          *  Remove it from the d-linked list with the real services.
1081          */
1082         ip_vs_rs_unhash(dest);
1083
1084         spin_lock_bh(&ipvs->dest_trash_lock);
1085         IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, dest->refcnt=%d\n",
1086                       IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port),
1087                       refcount_read(&dest->refcnt));
1088         if (list_empty(&ipvs->dest_trash) && !cleanup)
1089                 mod_timer(&ipvs->dest_trash_timer,
1090                           jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1));
1091         /* dest lives in trash with reference */
1092         list_add(&dest->t_list, &ipvs->dest_trash);
1093         dest->idle_start = 0;
1094         spin_unlock_bh(&ipvs->dest_trash_lock);
1095 }
1096
1097
1098 /*
1099  *      Unlink a destination from the given service
1100  */
1101 static void __ip_vs_unlink_dest(struct ip_vs_service *svc,
1102                                 struct ip_vs_dest *dest,
1103                                 int svcupd)
1104 {
1105         dest->flags &= ~IP_VS_DEST_F_AVAILABLE;
1106
1107         /*
1108          *  Remove it from the d-linked destination list.
1109          */
1110         list_del_rcu(&dest->n_list);
1111         svc->num_dests--;
1112
1113         if (dest->af != svc->af)
1114                 svc->ipvs->mixed_address_family_dests--;
1115
1116         if (svcupd) {
1117                 struct ip_vs_scheduler *sched;
1118
1119                 sched = rcu_dereference_protected(svc->scheduler, 1);
1120                 if (sched && sched->del_dest)
1121                         sched->del_dest(svc, dest);
1122         }
1123 }
1124
1125
1126 /*
1127  *      Delete a destination server in the given service
1128  */
1129 static int
1130 ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
1131 {
1132         struct ip_vs_dest *dest;
1133         __be16 dport = udest->port;
1134
1135         EnterFunction(2);
1136
1137         /* We use function that requires RCU lock */
1138         rcu_read_lock();
1139         dest = ip_vs_lookup_dest(svc, udest->af, &udest->addr, dport);
1140         rcu_read_unlock();
1141
1142         if (dest == NULL) {
1143                 IP_VS_DBG(1, "%s(): destination not found!\n", __func__);
1144                 return -ENOENT;
1145         }
1146
1147         /*
1148          *      Unlink dest from the service
1149          */
1150         __ip_vs_unlink_dest(svc, dest, 1);
1151
1152         /*
1153          *      Delete the destination
1154          */
1155         __ip_vs_del_dest(svc->ipvs, dest, false);
1156
1157         LeaveFunction(2);
1158
1159         return 0;
1160 }
1161
1162 static void ip_vs_dest_trash_expire(struct timer_list *t)
1163 {
1164         struct netns_ipvs *ipvs = from_timer(ipvs, t, dest_trash_timer);
1165         struct ip_vs_dest *dest, *next;
1166         unsigned long now = jiffies;
1167
1168         spin_lock(&ipvs->dest_trash_lock);
1169         list_for_each_entry_safe(dest, next, &ipvs->dest_trash, t_list) {
1170                 if (refcount_read(&dest->refcnt) > 1)
1171                         continue;
1172                 if (dest->idle_start) {
1173                         if (time_before(now, dest->idle_start +
1174                                              IP_VS_DEST_TRASH_PERIOD))
1175                                 continue;
1176                 } else {
1177                         dest->idle_start = max(1UL, now);
1178                         continue;
1179                 }
1180                 IP_VS_DBG_BUF(3, "Removing destination %u/%s:%u from trash\n",
1181                               dest->vfwmark,
1182                               IP_VS_DBG_ADDR(dest->af, &dest->addr),
1183                               ntohs(dest->port));
1184                 list_del(&dest->t_list);
1185                 ip_vs_dest_free(dest);
1186         }
1187         if (!list_empty(&ipvs->dest_trash))
1188                 mod_timer(&ipvs->dest_trash_timer,
1189                           jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1));
1190         spin_unlock(&ipvs->dest_trash_lock);
1191 }
1192
1193 /*
1194  *      Add a service into the service hash table
1195  */
1196 static int
1197 ip_vs_add_service(struct netns_ipvs *ipvs, struct ip_vs_service_user_kern *u,
1198                   struct ip_vs_service **svc_p)
1199 {
1200         int ret = 0, i;
1201         struct ip_vs_scheduler *sched = NULL;
1202         struct ip_vs_pe *pe = NULL;
1203         struct ip_vs_service *svc = NULL;
1204
1205         /* increase the module use count */
1206         if (!ip_vs_use_count_inc())
1207                 return -ENOPROTOOPT;
1208
1209         /* Lookup the scheduler by 'u->sched_name' */
1210         if (strcmp(u->sched_name, "none")) {
1211                 sched = ip_vs_scheduler_get(u->sched_name);
1212                 if (!sched) {
1213                         pr_info("Scheduler module ip_vs_%s not found\n",
1214                                 u->sched_name);
1215                         ret = -ENOENT;
1216                         goto out_err;
1217                 }
1218         }
1219
1220         if (u->pe_name && *u->pe_name) {
1221                 pe = ip_vs_pe_getbyname(u->pe_name);
1222                 if (pe == NULL) {
1223                         pr_info("persistence engine module ip_vs_pe_%s "
1224                                 "not found\n", u->pe_name);
1225                         ret = -ENOENT;
1226                         goto out_err;
1227                 }
1228         }
1229
1230 #ifdef CONFIG_IP_VS_IPV6
1231         if (u->af == AF_INET6) {
1232                 __u32 plen = (__force __u32) u->netmask;
1233
1234                 if (plen < 1 || plen > 128) {
1235                         ret = -EINVAL;
1236                         goto out_err;
1237                 }
1238
1239                 ret = nf_defrag_ipv6_enable(ipvs->net);
1240                 if (ret)
1241                         goto out_err;
1242         }
1243 #endif
1244
1245         svc = kzalloc(sizeof(struct ip_vs_service), GFP_KERNEL);
1246         if (svc == NULL) {
1247                 IP_VS_DBG(1, "%s(): no memory\n", __func__);
1248                 ret = -ENOMEM;
1249                 goto out_err;
1250         }
1251         svc->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
1252         if (!svc->stats.cpustats) {
1253                 ret = -ENOMEM;
1254                 goto out_err;
1255         }
1256
1257         for_each_possible_cpu(i) {
1258                 struct ip_vs_cpu_stats *ip_vs_stats;
1259                 ip_vs_stats = per_cpu_ptr(svc->stats.cpustats, i);
1260                 u64_stats_init(&ip_vs_stats->syncp);
1261         }
1262
1263
1264         /* I'm the first user of the service */
1265         atomic_set(&svc->refcnt, 0);
1266
1267         svc->af = u->af;
1268         svc->protocol = u->protocol;
1269         ip_vs_addr_copy(svc->af, &svc->addr, &u->addr);
1270         svc->port = u->port;
1271         svc->fwmark = u->fwmark;
1272         svc->flags = u->flags & ~IP_VS_SVC_F_HASHED;
1273         svc->timeout = u->timeout * HZ;
1274         svc->netmask = u->netmask;
1275         svc->ipvs = ipvs;
1276
1277         INIT_LIST_HEAD(&svc->destinations);
1278         spin_lock_init(&svc->sched_lock);
1279         spin_lock_init(&svc->stats.lock);
1280
1281         /* Bind the scheduler */
1282         if (sched) {
1283                 ret = ip_vs_bind_scheduler(svc, sched);
1284                 if (ret)
1285                         goto out_err;
1286                 sched = NULL;
1287         }
1288
1289         /* Bind the ct retriever */
1290         RCU_INIT_POINTER(svc->pe, pe);
1291         pe = NULL;
1292
1293         /* Update the virtual service counters */
1294         if (svc->port == FTPPORT)
1295                 atomic_inc(&ipvs->ftpsvc_counter);
1296         else if (svc->port == 0)
1297                 atomic_inc(&ipvs->nullsvc_counter);
1298         if (svc->pe && svc->pe->conn_out)
1299                 atomic_inc(&ipvs->conn_out_counter);
1300
1301         ip_vs_start_estimator(ipvs, &svc->stats);
1302
1303         /* Count only IPv4 services for old get/setsockopt interface */
1304         if (svc->af == AF_INET)
1305                 ipvs->num_services++;
1306
1307         /* Hash the service into the service table */
1308         ip_vs_svc_hash(svc);
1309
1310         *svc_p = svc;
1311         /* Now there is a service - full throttle */
1312         ipvs->enable = 1;
1313         return 0;
1314
1315
1316  out_err:
1317         if (svc != NULL) {
1318                 ip_vs_unbind_scheduler(svc, sched);
1319                 ip_vs_service_free(svc);
1320         }
1321         ip_vs_scheduler_put(sched);
1322         ip_vs_pe_put(pe);
1323
1324         /* decrease the module use count */
1325         ip_vs_use_count_dec();
1326
1327         return ret;
1328 }
1329
1330
1331 /*
1332  *      Edit a service and bind it with a new scheduler
1333  */
1334 static int
1335 ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u)
1336 {
1337         struct ip_vs_scheduler *sched = NULL, *old_sched;
1338         struct ip_vs_pe *pe = NULL, *old_pe = NULL;
1339         int ret = 0;
1340         bool new_pe_conn_out, old_pe_conn_out;
1341
1342         /*
1343          * Lookup the scheduler, by 'u->sched_name'
1344          */
1345         if (strcmp(u->sched_name, "none")) {
1346                 sched = ip_vs_scheduler_get(u->sched_name);
1347                 if (!sched) {
1348                         pr_info("Scheduler module ip_vs_%s not found\n",
1349                                 u->sched_name);
1350                         return -ENOENT;
1351                 }
1352         }
1353         old_sched = sched;
1354
1355         if (u->pe_name && *u->pe_name) {
1356                 pe = ip_vs_pe_getbyname(u->pe_name);
1357                 if (pe == NULL) {
1358                         pr_info("persistence engine module ip_vs_pe_%s "
1359                                 "not found\n", u->pe_name);
1360                         ret = -ENOENT;
1361                         goto out;
1362                 }
1363                 old_pe = pe;
1364         }
1365
1366 #ifdef CONFIG_IP_VS_IPV6
1367         if (u->af == AF_INET6) {
1368                 __u32 plen = (__force __u32) u->netmask;
1369
1370                 if (plen < 1 || plen > 128) {
1371                         ret = -EINVAL;
1372                         goto out;
1373                 }
1374         }
1375 #endif
1376
1377         old_sched = rcu_dereference_protected(svc->scheduler, 1);
1378         if (sched != old_sched) {
1379                 if (old_sched) {
1380                         ip_vs_unbind_scheduler(svc, old_sched);
1381                         RCU_INIT_POINTER(svc->scheduler, NULL);
1382                         /* Wait all svc->sched_data users */
1383                         synchronize_rcu();
1384                 }
1385                 /* Bind the new scheduler */
1386                 if (sched) {
1387                         ret = ip_vs_bind_scheduler(svc, sched);
1388                         if (ret) {
1389                                 ip_vs_scheduler_put(sched);
1390                                 goto out;
1391                         }
1392                 }
1393         }
1394
1395         /*
1396          * Set the flags and timeout value
1397          */
1398         svc->flags = u->flags | IP_VS_SVC_F_HASHED;
1399         svc->timeout = u->timeout * HZ;
1400         svc->netmask = u->netmask;
1401
1402         old_pe = rcu_dereference_protected(svc->pe, 1);
1403         if (pe != old_pe) {
1404                 rcu_assign_pointer(svc->pe, pe);
1405                 /* check for optional methods in new pe */
1406                 new_pe_conn_out = (pe && pe->conn_out) ? true : false;
1407                 old_pe_conn_out = (old_pe && old_pe->conn_out) ? true : false;
1408                 if (new_pe_conn_out && !old_pe_conn_out)
1409                         atomic_inc(&svc->ipvs->conn_out_counter);
1410                 if (old_pe_conn_out && !new_pe_conn_out)
1411                         atomic_dec(&svc->ipvs->conn_out_counter);
1412         }
1413
1414 out:
1415         ip_vs_scheduler_put(old_sched);
1416         ip_vs_pe_put(old_pe);
1417         return ret;
1418 }
1419
1420 /*
1421  *      Delete a service from the service list
1422  *      - The service must be unlinked, unlocked and not referenced!
1423  *      - We are called under _bh lock
1424  */
1425 static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup)
1426 {
1427         struct ip_vs_dest *dest, *nxt;
1428         struct ip_vs_scheduler *old_sched;
1429         struct ip_vs_pe *old_pe;
1430         struct netns_ipvs *ipvs = svc->ipvs;
1431
1432         /* Count only IPv4 services for old get/setsockopt interface */
1433         if (svc->af == AF_INET)
1434                 ipvs->num_services--;
1435
1436         ip_vs_stop_estimator(svc->ipvs, &svc->stats);
1437
1438         /* Unbind scheduler */
1439         old_sched = rcu_dereference_protected(svc->scheduler, 1);
1440         ip_vs_unbind_scheduler(svc, old_sched);
1441         ip_vs_scheduler_put(old_sched);
1442
1443         /* Unbind persistence engine, keep svc->pe */
1444         old_pe = rcu_dereference_protected(svc->pe, 1);
1445         if (old_pe && old_pe->conn_out)
1446                 atomic_dec(&ipvs->conn_out_counter);
1447         ip_vs_pe_put(old_pe);
1448
1449         /*
1450          *    Unlink the whole destination list
1451          */
1452         list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) {
1453                 __ip_vs_unlink_dest(svc, dest, 0);
1454                 __ip_vs_del_dest(svc->ipvs, dest, cleanup);
1455         }
1456
1457         /*
1458          *    Update the virtual service counters
1459          */
1460         if (svc->port == FTPPORT)
1461                 atomic_dec(&ipvs->ftpsvc_counter);
1462         else if (svc->port == 0)
1463                 atomic_dec(&ipvs->nullsvc_counter);
1464
1465         /*
1466          *    Free the service if nobody refers to it
1467          */
1468         __ip_vs_svc_put(svc, true);
1469
1470         /* decrease the module use count */
1471         ip_vs_use_count_dec();
1472 }
1473
1474 /*
1475  * Unlink a service from list and try to delete it if its refcnt reached 0
1476  */
1477 static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup)
1478 {
1479         ip_vs_unregister_conntrack(svc);
1480         /* Hold svc to avoid double release from dest_trash */
1481         atomic_inc(&svc->refcnt);
1482         /*
1483          * Unhash it from the service table
1484          */
1485         ip_vs_svc_unhash(svc);
1486
1487         __ip_vs_del_service(svc, cleanup);
1488 }
1489
1490 /*
1491  *      Delete a service from the service list
1492  */
1493 static int ip_vs_del_service(struct ip_vs_service *svc)
1494 {
1495         if (svc == NULL)
1496                 return -EEXIST;
1497         ip_vs_unlink_service(svc, false);
1498
1499         return 0;
1500 }
1501
1502
1503 /*
1504  *      Flush all the virtual services
1505  */
1506 static int ip_vs_flush(struct netns_ipvs *ipvs, bool cleanup)
1507 {
1508         int idx;
1509         struct ip_vs_service *svc;
1510         struct hlist_node *n;
1511
1512         /*
1513          * Flush the service table hashed by <netns,protocol,addr,port>
1514          */
1515         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1516                 hlist_for_each_entry_safe(svc, n, &ip_vs_svc_table[idx],
1517                                           s_list) {
1518                         if (svc->ipvs == ipvs)
1519                                 ip_vs_unlink_service(svc, cleanup);
1520                 }
1521         }
1522
1523         /*
1524          * Flush the service table hashed by fwmark
1525          */
1526         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1527                 hlist_for_each_entry_safe(svc, n, &ip_vs_svc_fwm_table[idx],
1528                                           f_list) {
1529                         if (svc->ipvs == ipvs)
1530                                 ip_vs_unlink_service(svc, cleanup);
1531                 }
1532         }
1533
1534         return 0;
1535 }
1536
1537 /*
1538  *      Delete service by {netns} in the service table.
1539  *      Called by __ip_vs_cleanup()
1540  */
1541 void ip_vs_service_net_cleanup(struct netns_ipvs *ipvs)
1542 {
1543         EnterFunction(2);
1544         /* Check for "full" addressed entries */
1545         mutex_lock(&__ip_vs_mutex);
1546         ip_vs_flush(ipvs, true);
1547         mutex_unlock(&__ip_vs_mutex);
1548         LeaveFunction(2);
1549 }
1550
1551 /* Put all references for device (dst_cache) */
1552 static inline void
1553 ip_vs_forget_dev(struct ip_vs_dest *dest, struct net_device *dev)
1554 {
1555         struct ip_vs_dest_dst *dest_dst;
1556
1557         spin_lock_bh(&dest->dst_lock);
1558         dest_dst = rcu_dereference_protected(dest->dest_dst, 1);
1559         if (dest_dst && dest_dst->dst_cache->dev == dev) {
1560                 IP_VS_DBG_BUF(3, "Reset dev:%s dest %s:%u ,dest->refcnt=%d\n",
1561                               dev->name,
1562                               IP_VS_DBG_ADDR(dest->af, &dest->addr),
1563                               ntohs(dest->port),
1564                               refcount_read(&dest->refcnt));
1565                 __ip_vs_dst_cache_reset(dest);
1566         }
1567         spin_unlock_bh(&dest->dst_lock);
1568
1569 }
1570 /* Netdev event receiver
1571  * Currently only NETDEV_DOWN is handled to release refs to cached dsts
1572  */
1573 static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,
1574                            void *ptr)
1575 {
1576         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1577         struct net *net = dev_net(dev);
1578         struct netns_ipvs *ipvs = net_ipvs(net);
1579         struct ip_vs_service *svc;
1580         struct ip_vs_dest *dest;
1581         unsigned int idx;
1582
1583         if (event != NETDEV_DOWN || !ipvs)
1584                 return NOTIFY_DONE;
1585         IP_VS_DBG(3, "%s() dev=%s\n", __func__, dev->name);
1586         EnterFunction(2);
1587         mutex_lock(&__ip_vs_mutex);
1588         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1589                 hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1590                         if (svc->ipvs == ipvs) {
1591                                 list_for_each_entry(dest, &svc->destinations,
1592                                                     n_list) {
1593                                         ip_vs_forget_dev(dest, dev);
1594                                 }
1595                         }
1596                 }
1597
1598                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1599                         if (svc->ipvs == ipvs) {
1600                                 list_for_each_entry(dest, &svc->destinations,
1601                                                     n_list) {
1602                                         ip_vs_forget_dev(dest, dev);
1603                                 }
1604                         }
1605
1606                 }
1607         }
1608
1609         spin_lock_bh(&ipvs->dest_trash_lock);
1610         list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
1611                 ip_vs_forget_dev(dest, dev);
1612         }
1613         spin_unlock_bh(&ipvs->dest_trash_lock);
1614         mutex_unlock(&__ip_vs_mutex);
1615         LeaveFunction(2);
1616         return NOTIFY_DONE;
1617 }
1618
1619 /*
1620  *      Zero counters in a service or all services
1621  */
1622 static int ip_vs_zero_service(struct ip_vs_service *svc)
1623 {
1624         struct ip_vs_dest *dest;
1625
1626         list_for_each_entry(dest, &svc->destinations, n_list) {
1627                 ip_vs_zero_stats(&dest->stats);
1628         }
1629         ip_vs_zero_stats(&svc->stats);
1630         return 0;
1631 }
1632
1633 static int ip_vs_zero_all(struct netns_ipvs *ipvs)
1634 {
1635         int idx;
1636         struct ip_vs_service *svc;
1637
1638         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1639                 hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1640                         if (svc->ipvs == ipvs)
1641                                 ip_vs_zero_service(svc);
1642                 }
1643         }
1644
1645         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1646                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1647                         if (svc->ipvs == ipvs)
1648                                 ip_vs_zero_service(svc);
1649                 }
1650         }
1651
1652         ip_vs_zero_stats(&ipvs->tot_stats);
1653         return 0;
1654 }
1655
1656 #ifdef CONFIG_SYSCTL
1657
1658 static int zero;
1659 static int one = 1;
1660 static int three = 3;
1661
1662 static int
1663 proc_do_defense_mode(struct ctl_table *table, int write,
1664                      void __user *buffer, size_t *lenp, loff_t *ppos)
1665 {
1666         struct netns_ipvs *ipvs = table->extra2;
1667         int *valp = table->data;
1668         int val = *valp;
1669         int rc;
1670
1671         struct ctl_table tmp = {
1672                 .data = &val,
1673                 .maxlen = sizeof(int),
1674                 .mode = table->mode,
1675         };
1676
1677         rc = proc_dointvec(&tmp, write, buffer, lenp, ppos);
1678         if (write && (*valp != val)) {
1679                 if (val < 0 || val > 3) {
1680                         rc = -EINVAL;
1681                 } else {
1682                         *valp = val;
1683                         update_defense_level(ipvs);
1684                 }
1685         }
1686         return rc;
1687 }
1688
1689 static int
1690 proc_do_sync_threshold(struct ctl_table *table, int write,
1691                        void __user *buffer, size_t *lenp, loff_t *ppos)
1692 {
1693         struct netns_ipvs *ipvs = table->extra2;
1694         int *valp = table->data;
1695         int val[2];
1696         int rc;
1697         struct ctl_table tmp = {
1698                 .data = &val,
1699                 .maxlen = table->maxlen,
1700                 .mode = table->mode,
1701         };
1702
1703         mutex_lock(&ipvs->sync_mutex);
1704         memcpy(val, valp, sizeof(val));
1705         rc = proc_dointvec(&tmp, write, buffer, lenp, ppos);
1706         if (write) {
1707                 if (val[0] < 0 || val[1] < 0 ||
1708                     (val[0] >= val[1] && val[1]))
1709                         rc = -EINVAL;
1710                 else
1711                         memcpy(valp, val, sizeof(val));
1712         }
1713         mutex_unlock(&ipvs->sync_mutex);
1714         return rc;
1715 }
1716
1717 static int
1718 proc_do_sync_ports(struct ctl_table *table, int write,
1719                    void __user *buffer, size_t *lenp, loff_t *ppos)
1720 {
1721         int *valp = table->data;
1722         int val = *valp;
1723         int rc;
1724
1725         struct ctl_table tmp = {
1726                 .data = &val,
1727                 .maxlen = sizeof(int),
1728                 .mode = table->mode,
1729         };
1730
1731         rc = proc_dointvec(&tmp, write, buffer, lenp, ppos);
1732         if (write && (*valp != val)) {
1733                 if (val < 1 || !is_power_of_2(val))
1734                         rc = -EINVAL;
1735                 else
1736                         *valp = val;
1737         }
1738         return rc;
1739 }
1740
1741 /*
1742  *      IPVS sysctl table (under the /proc/sys/net/ipv4/vs/)
1743  *      Do not change order or insert new entries without
1744  *      align with netns init in ip_vs_control_net_init()
1745  */
1746
1747 static struct ctl_table vs_vars[] = {
1748         {
1749                 .procname       = "amemthresh",
1750                 .maxlen         = sizeof(int),
1751                 .mode           = 0644,
1752                 .proc_handler   = proc_dointvec,
1753         },
1754         {
1755                 .procname       = "am_droprate",
1756                 .maxlen         = sizeof(int),
1757                 .mode           = 0644,
1758                 .proc_handler   = proc_dointvec,
1759         },
1760         {
1761                 .procname       = "drop_entry",
1762                 .maxlen         = sizeof(int),
1763                 .mode           = 0644,
1764                 .proc_handler   = proc_do_defense_mode,
1765         },
1766         {
1767                 .procname       = "drop_packet",
1768                 .maxlen         = sizeof(int),
1769                 .mode           = 0644,
1770                 .proc_handler   = proc_do_defense_mode,
1771         },
1772 #ifdef CONFIG_IP_VS_NFCT
1773         {
1774                 .procname       = "conntrack",
1775                 .maxlen         = sizeof(int),
1776                 .mode           = 0644,
1777                 .proc_handler   = &proc_dointvec,
1778         },
1779 #endif
1780         {
1781                 .procname       = "secure_tcp",
1782                 .maxlen         = sizeof(int),
1783                 .mode           = 0644,
1784                 .proc_handler   = proc_do_defense_mode,
1785         },
1786         {
1787                 .procname       = "snat_reroute",
1788                 .maxlen         = sizeof(int),
1789                 .mode           = 0644,
1790                 .proc_handler   = &proc_dointvec,
1791         },
1792         {
1793                 .procname       = "sync_version",
1794                 .maxlen         = sizeof(int),
1795                 .mode           = 0644,
1796                 .proc_handler   = proc_dointvec_minmax,
1797                 .extra1         = &zero,
1798                 .extra2         = &one,
1799         },
1800         {
1801                 .procname       = "sync_ports",
1802                 .maxlen         = sizeof(int),
1803                 .mode           = 0644,
1804                 .proc_handler   = proc_do_sync_ports,
1805         },
1806         {
1807                 .procname       = "sync_persist_mode",
1808                 .maxlen         = sizeof(int),
1809                 .mode           = 0644,
1810                 .proc_handler   = proc_dointvec,
1811         },
1812         {
1813                 .procname       = "sync_qlen_max",
1814                 .maxlen         = sizeof(unsigned long),
1815                 .mode           = 0644,
1816                 .proc_handler   = proc_doulongvec_minmax,
1817         },
1818         {
1819                 .procname       = "sync_sock_size",
1820                 .maxlen         = sizeof(int),
1821                 .mode           = 0644,
1822                 .proc_handler   = proc_dointvec,
1823         },
1824         {
1825                 .procname       = "cache_bypass",
1826                 .maxlen         = sizeof(int),
1827                 .mode           = 0644,
1828                 .proc_handler   = proc_dointvec,
1829         },
1830         {
1831                 .procname       = "expire_nodest_conn",
1832                 .maxlen         = sizeof(int),
1833                 .mode           = 0644,
1834                 .proc_handler   = proc_dointvec,
1835         },
1836         {
1837                 .procname       = "sloppy_tcp",
1838                 .maxlen         = sizeof(int),
1839                 .mode           = 0644,
1840                 .proc_handler   = proc_dointvec,
1841         },
1842         {
1843                 .procname       = "sloppy_sctp",
1844                 .maxlen         = sizeof(int),
1845                 .mode           = 0644,
1846                 .proc_handler   = proc_dointvec,
1847         },
1848         {
1849                 .procname       = "expire_quiescent_template",
1850                 .maxlen         = sizeof(int),
1851                 .mode           = 0644,
1852                 .proc_handler   = proc_dointvec,
1853         },
1854         {
1855                 .procname       = "sync_threshold",
1856                 .maxlen         =
1857                         sizeof(((struct netns_ipvs *)0)->sysctl_sync_threshold),
1858                 .mode           = 0644,
1859                 .proc_handler   = proc_do_sync_threshold,
1860         },
1861         {
1862                 .procname       = "sync_refresh_period",
1863                 .maxlen         = sizeof(int),
1864                 .mode           = 0644,
1865                 .proc_handler   = proc_dointvec_jiffies,
1866         },
1867         {
1868                 .procname       = "sync_retries",
1869                 .maxlen         = sizeof(int),
1870                 .mode           = 0644,
1871                 .proc_handler   = proc_dointvec_minmax,
1872                 .extra1         = &zero,
1873                 .extra2         = &three,
1874         },
1875         {
1876                 .procname       = "nat_icmp_send",
1877                 .maxlen         = sizeof(int),
1878                 .mode           = 0644,
1879                 .proc_handler   = proc_dointvec,
1880         },
1881         {
1882                 .procname       = "pmtu_disc",
1883                 .maxlen         = sizeof(int),
1884                 .mode           = 0644,
1885                 .proc_handler   = proc_dointvec,
1886         },
1887         {
1888                 .procname       = "backup_only",
1889                 .maxlen         = sizeof(int),
1890                 .mode           = 0644,
1891                 .proc_handler   = proc_dointvec,
1892         },
1893         {
1894                 .procname       = "conn_reuse_mode",
1895                 .maxlen         = sizeof(int),
1896                 .mode           = 0644,
1897                 .proc_handler   = proc_dointvec,
1898         },
1899         {
1900                 .procname       = "schedule_icmp",
1901                 .maxlen         = sizeof(int),
1902                 .mode           = 0644,
1903                 .proc_handler   = proc_dointvec,
1904         },
1905         {
1906                 .procname       = "ignore_tunneled",
1907                 .maxlen         = sizeof(int),
1908                 .mode           = 0644,
1909                 .proc_handler   = proc_dointvec,
1910         },
1911 #ifdef CONFIG_IP_VS_DEBUG
1912         {
1913                 .procname       = "debug_level",
1914                 .data           = &sysctl_ip_vs_debug_level,
1915                 .maxlen         = sizeof(int),
1916                 .mode           = 0644,
1917                 .proc_handler   = proc_dointvec,
1918         },
1919 #endif
1920         { }
1921 };
1922
1923 #endif
1924
1925 #ifdef CONFIG_PROC_FS
1926
1927 struct ip_vs_iter {
1928         struct seq_net_private p;  /* Do not move this, netns depends upon it*/
1929         struct hlist_head *table;
1930         int bucket;
1931 };
1932
1933 /*
1934  *      Write the contents of the VS rule table to a PROCfs file.
1935  *      (It is kept just for backward compatibility)
1936  */
1937 static inline const char *ip_vs_fwd_name(unsigned int flags)
1938 {
1939         switch (flags & IP_VS_CONN_F_FWD_MASK) {
1940         case IP_VS_CONN_F_LOCALNODE:
1941                 return "Local";
1942         case IP_VS_CONN_F_TUNNEL:
1943                 return "Tunnel";
1944         case IP_VS_CONN_F_DROUTE:
1945                 return "Route";
1946         default:
1947                 return "Masq";
1948         }
1949 }
1950
1951
1952 /* Get the Nth entry in the two lists */
1953 static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos)
1954 {
1955         struct net *net = seq_file_net(seq);
1956         struct netns_ipvs *ipvs = net_ipvs(net);
1957         struct ip_vs_iter *iter = seq->private;
1958         int idx;
1959         struct ip_vs_service *svc;
1960
1961         /* look in hash by protocol */
1962         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1963                 hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[idx], s_list) {
1964                         if ((svc->ipvs == ipvs) && pos-- == 0) {
1965                                 iter->table = ip_vs_svc_table;
1966                                 iter->bucket = idx;
1967                                 return svc;
1968                         }
1969                 }
1970         }
1971
1972         /* keep looking in fwmark */
1973         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1974                 hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[idx],
1975                                          f_list) {
1976                         if ((svc->ipvs == ipvs) && pos-- == 0) {
1977                                 iter->table = ip_vs_svc_fwm_table;
1978                                 iter->bucket = idx;
1979                                 return svc;
1980                         }
1981                 }
1982         }
1983
1984         return NULL;
1985 }
1986
1987 static void *ip_vs_info_seq_start(struct seq_file *seq, loff_t *pos)
1988         __acquires(RCU)
1989 {
1990         rcu_read_lock();
1991         return *pos ? ip_vs_info_array(seq, *pos - 1) : SEQ_START_TOKEN;
1992 }
1993
1994
1995 static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1996 {
1997         struct hlist_node *e;
1998         struct ip_vs_iter *iter;
1999         struct ip_vs_service *svc;
2000
2001         ++*pos;
2002         if (v == SEQ_START_TOKEN)
2003                 return ip_vs_info_array(seq,0);
2004
2005         svc = v;
2006         iter = seq->private;
2007
2008         if (iter->table == ip_vs_svc_table) {
2009                 /* next service in table hashed by protocol */
2010                 e = rcu_dereference(hlist_next_rcu(&svc->s_list));
2011                 if (e)
2012                         return hlist_entry(e, struct ip_vs_service, s_list);
2013
2014                 while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
2015                         hlist_for_each_entry_rcu(svc,
2016                                                  &ip_vs_svc_table[iter->bucket],
2017                                                  s_list) {
2018                                 return svc;
2019                         }
2020                 }
2021
2022                 iter->table = ip_vs_svc_fwm_table;
2023                 iter->bucket = -1;
2024                 goto scan_fwmark;
2025         }
2026
2027         /* next service in hashed by fwmark */
2028         e = rcu_dereference(hlist_next_rcu(&svc->f_list));
2029         if (e)
2030                 return hlist_entry(e, struct ip_vs_service, f_list);
2031
2032  scan_fwmark:
2033         while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
2034                 hlist_for_each_entry_rcu(svc,
2035                                          &ip_vs_svc_fwm_table[iter->bucket],
2036                                          f_list)
2037                         return svc;
2038         }
2039
2040         return NULL;
2041 }
2042
2043 static void ip_vs_info_seq_stop(struct seq_file *seq, void *v)
2044         __releases(RCU)
2045 {
2046         rcu_read_unlock();
2047 }
2048
2049
2050 static int ip_vs_info_seq_show(struct seq_file *seq, void *v)
2051 {
2052         if (v == SEQ_START_TOKEN) {
2053                 seq_printf(seq,
2054                         "IP Virtual Server version %d.%d.%d (size=%d)\n",
2055                         NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2056                 seq_puts(seq,
2057                          "Prot LocalAddress:Port Scheduler Flags\n");
2058                 seq_puts(seq,
2059                          "  -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n");
2060         } else {
2061                 struct net *net = seq_file_net(seq);
2062                 struct netns_ipvs *ipvs = net_ipvs(net);
2063                 const struct ip_vs_service *svc = v;
2064                 const struct ip_vs_iter *iter = seq->private;
2065                 const struct ip_vs_dest *dest;
2066                 struct ip_vs_scheduler *sched = rcu_dereference(svc->scheduler);
2067                 char *sched_name = sched ? sched->name : "none";
2068
2069                 if (svc->ipvs != ipvs)
2070                         return 0;
2071                 if (iter->table == ip_vs_svc_table) {
2072 #ifdef CONFIG_IP_VS_IPV6
2073                         if (svc->af == AF_INET6)
2074                                 seq_printf(seq, "%s  [%pI6]:%04X %s ",
2075                                            ip_vs_proto_name(svc->protocol),
2076                                            &svc->addr.in6,
2077                                            ntohs(svc->port),
2078                                            sched_name);
2079                         else
2080 #endif
2081                                 seq_printf(seq, "%s  %08X:%04X %s %s ",
2082                                            ip_vs_proto_name(svc->protocol),
2083                                            ntohl(svc->addr.ip),
2084                                            ntohs(svc->port),
2085                                            sched_name,
2086                                            (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2087                 } else {
2088                         seq_printf(seq, "FWM  %08X %s %s",
2089                                    svc->fwmark, sched_name,
2090                                    (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2091                 }
2092
2093                 if (svc->flags & IP_VS_SVC_F_PERSISTENT)
2094                         seq_printf(seq, "persistent %d %08X\n",
2095                                 svc->timeout,
2096                                 ntohl(svc->netmask));
2097                 else
2098                         seq_putc(seq, '\n');
2099
2100                 list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
2101 #ifdef CONFIG_IP_VS_IPV6
2102                         if (dest->af == AF_INET6)
2103                                 seq_printf(seq,
2104                                            "  -> [%pI6]:%04X"
2105                                            "      %-7s %-6d %-10d %-10d\n",
2106                                            &dest->addr.in6,
2107                                            ntohs(dest->port),
2108                                            ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2109                                            atomic_read(&dest->weight),
2110                                            atomic_read(&dest->activeconns),
2111                                            atomic_read(&dest->inactconns));
2112                         else
2113 #endif
2114                                 seq_printf(seq,
2115                                            "  -> %08X:%04X      "
2116                                            "%-7s %-6d %-10d %-10d\n",
2117                                            ntohl(dest->addr.ip),
2118                                            ntohs(dest->port),
2119                                            ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2120                                            atomic_read(&dest->weight),
2121                                            atomic_read(&dest->activeconns),
2122                                            atomic_read(&dest->inactconns));
2123
2124                 }
2125         }
2126         return 0;
2127 }
2128
2129 static const struct seq_operations ip_vs_info_seq_ops = {
2130         .start = ip_vs_info_seq_start,
2131         .next  = ip_vs_info_seq_next,
2132         .stop  = ip_vs_info_seq_stop,
2133         .show  = ip_vs_info_seq_show,
2134 };
2135
2136 static int ip_vs_stats_show(struct seq_file *seq, void *v)
2137 {
2138         struct net *net = seq_file_single_net(seq);
2139         struct ip_vs_kstats show;
2140
2141 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2142         seq_puts(seq,
2143                  "   Total Incoming Outgoing         Incoming         Outgoing\n");
2144         seq_puts(seq,
2145                  "   Conns  Packets  Packets            Bytes            Bytes\n");
2146
2147         ip_vs_copy_stats(&show, &net_ipvs(net)->tot_stats);
2148         seq_printf(seq, "%8LX %8LX %8LX %16LX %16LX\n\n",
2149                    (unsigned long long)show.conns,
2150                    (unsigned long long)show.inpkts,
2151                    (unsigned long long)show.outpkts,
2152                    (unsigned long long)show.inbytes,
2153                    (unsigned long long)show.outbytes);
2154
2155 /*                01234567 01234567 01234567 0123456701234567 0123456701234567*/
2156         seq_puts(seq,
2157                  " Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2158         seq_printf(seq, "%8LX %8LX %8LX %16LX %16LX\n",
2159                    (unsigned long long)show.cps,
2160                    (unsigned long long)show.inpps,
2161                    (unsigned long long)show.outpps,
2162                    (unsigned long long)show.inbps,
2163                    (unsigned long long)show.outbps);
2164
2165         return 0;
2166 }
2167
2168 static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v)
2169 {
2170         struct net *net = seq_file_single_net(seq);
2171         struct ip_vs_stats *tot_stats = &net_ipvs(net)->tot_stats;
2172         struct ip_vs_cpu_stats __percpu *cpustats = tot_stats->cpustats;
2173         struct ip_vs_kstats kstats;
2174         int i;
2175
2176 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2177         seq_puts(seq,
2178                  "       Total Incoming Outgoing         Incoming         Outgoing\n");
2179         seq_puts(seq,
2180                  "CPU    Conns  Packets  Packets            Bytes            Bytes\n");
2181
2182         for_each_possible_cpu(i) {
2183                 struct ip_vs_cpu_stats *u = per_cpu_ptr(cpustats, i);
2184                 unsigned int start;
2185                 u64 conns, inpkts, outpkts, inbytes, outbytes;
2186
2187                 do {
2188                         start = u64_stats_fetch_begin_irq(&u->syncp);
2189                         conns = u->cnt.conns;
2190                         inpkts = u->cnt.inpkts;
2191                         outpkts = u->cnt.outpkts;
2192                         inbytes = u->cnt.inbytes;
2193                         outbytes = u->cnt.outbytes;
2194                 } while (u64_stats_fetch_retry_irq(&u->syncp, start));
2195
2196                 seq_printf(seq, "%3X %8LX %8LX %8LX %16LX %16LX\n",
2197                            i, (u64)conns, (u64)inpkts,
2198                            (u64)outpkts, (u64)inbytes,
2199                            (u64)outbytes);
2200         }
2201
2202         ip_vs_copy_stats(&kstats, tot_stats);
2203
2204         seq_printf(seq, "  ~ %8LX %8LX %8LX %16LX %16LX\n\n",
2205                    (unsigned long long)kstats.conns,
2206                    (unsigned long long)kstats.inpkts,
2207                    (unsigned long long)kstats.outpkts,
2208                    (unsigned long long)kstats.inbytes,
2209                    (unsigned long long)kstats.outbytes);
2210
2211 /*                ... 01234567 01234567 01234567 0123456701234567 0123456701234567 */
2212         seq_puts(seq,
2213                  "     Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2214         seq_printf(seq, "    %8LX %8LX %8LX %16LX %16LX\n",
2215                    kstats.cps,
2216                    kstats.inpps,
2217                    kstats.outpps,
2218                    kstats.inbps,
2219                    kstats.outbps);
2220
2221         return 0;
2222 }
2223 #endif
2224
2225 /*
2226  *      Set timeout values for tcp tcpfin udp in the timeout_table.
2227  */
2228 static int ip_vs_set_timeout(struct netns_ipvs *ipvs, struct ip_vs_timeout_user *u)
2229 {
2230 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2231         struct ip_vs_proto_data *pd;
2232 #endif
2233
2234         IP_VS_DBG(2, "Setting timeout tcp:%d tcpfin:%d udp:%d\n",
2235                   u->tcp_timeout,
2236                   u->tcp_fin_timeout,
2237                   u->udp_timeout);
2238
2239 #ifdef CONFIG_IP_VS_PROTO_TCP
2240         if (u->tcp_timeout < 0 || u->tcp_timeout > (INT_MAX / HZ) ||
2241             u->tcp_fin_timeout < 0 || u->tcp_fin_timeout > (INT_MAX / HZ)) {
2242                 return -EINVAL;
2243         }
2244 #endif
2245
2246 #ifdef CONFIG_IP_VS_PROTO_UDP
2247         if (u->udp_timeout < 0 || u->udp_timeout > (INT_MAX / HZ))
2248                 return -EINVAL;
2249 #endif
2250
2251 #ifdef CONFIG_IP_VS_PROTO_TCP
2252         if (u->tcp_timeout) {
2253                 pd = ip_vs_proto_data_get(ipvs, IPPROTO_TCP);
2254                 pd->timeout_table[IP_VS_TCP_S_ESTABLISHED]
2255                         = u->tcp_timeout * HZ;
2256         }
2257
2258         if (u->tcp_fin_timeout) {
2259                 pd = ip_vs_proto_data_get(ipvs, IPPROTO_TCP);
2260                 pd->timeout_table[IP_VS_TCP_S_FIN_WAIT]
2261                         = u->tcp_fin_timeout * HZ;
2262         }
2263 #endif
2264
2265 #ifdef CONFIG_IP_VS_PROTO_UDP
2266         if (u->udp_timeout) {
2267                 pd = ip_vs_proto_data_get(ipvs, IPPROTO_UDP);
2268                 pd->timeout_table[IP_VS_UDP_S_NORMAL]
2269                         = u->udp_timeout * HZ;
2270         }
2271 #endif
2272         return 0;
2273 }
2274
2275 #define CMDID(cmd)              (cmd - IP_VS_BASE_CTL)
2276
2277 struct ip_vs_svcdest_user {
2278         struct ip_vs_service_user       s;
2279         struct ip_vs_dest_user          d;
2280 };
2281
2282 static const unsigned char set_arglen[CMDID(IP_VS_SO_SET_MAX) + 1] = {
2283         [CMDID(IP_VS_SO_SET_ADD)]         = sizeof(struct ip_vs_service_user),
2284         [CMDID(IP_VS_SO_SET_EDIT)]        = sizeof(struct ip_vs_service_user),
2285         [CMDID(IP_VS_SO_SET_DEL)]         = sizeof(struct ip_vs_service_user),
2286         [CMDID(IP_VS_SO_SET_ADDDEST)]     = sizeof(struct ip_vs_svcdest_user),
2287         [CMDID(IP_VS_SO_SET_DELDEST)]     = sizeof(struct ip_vs_svcdest_user),
2288         [CMDID(IP_VS_SO_SET_EDITDEST)]    = sizeof(struct ip_vs_svcdest_user),
2289         [CMDID(IP_VS_SO_SET_TIMEOUT)]     = sizeof(struct ip_vs_timeout_user),
2290         [CMDID(IP_VS_SO_SET_STARTDAEMON)] = sizeof(struct ip_vs_daemon_user),
2291         [CMDID(IP_VS_SO_SET_STOPDAEMON)]  = sizeof(struct ip_vs_daemon_user),
2292         [CMDID(IP_VS_SO_SET_ZERO)]        = sizeof(struct ip_vs_service_user),
2293 };
2294
2295 union ip_vs_set_arglen {
2296         struct ip_vs_service_user       field_IP_VS_SO_SET_ADD;
2297         struct ip_vs_service_user       field_IP_VS_SO_SET_EDIT;
2298         struct ip_vs_service_user       field_IP_VS_SO_SET_DEL;
2299         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_ADDDEST;
2300         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_DELDEST;
2301         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_EDITDEST;
2302         struct ip_vs_timeout_user       field_IP_VS_SO_SET_TIMEOUT;
2303         struct ip_vs_daemon_user        field_IP_VS_SO_SET_STARTDAEMON;
2304         struct ip_vs_daemon_user        field_IP_VS_SO_SET_STOPDAEMON;
2305         struct ip_vs_service_user       field_IP_VS_SO_SET_ZERO;
2306 };
2307
2308 #define MAX_SET_ARGLEN  sizeof(union ip_vs_set_arglen)
2309
2310 static void ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern *usvc,
2311                                   struct ip_vs_service_user *usvc_compat)
2312 {
2313         memset(usvc, 0, sizeof(*usvc));
2314
2315         usvc->af                = AF_INET;
2316         usvc->protocol          = usvc_compat->protocol;
2317         usvc->addr.ip           = usvc_compat->addr;
2318         usvc->port              = usvc_compat->port;
2319         usvc->fwmark            = usvc_compat->fwmark;
2320
2321         /* Deep copy of sched_name is not needed here */
2322         usvc->sched_name        = usvc_compat->sched_name;
2323
2324         usvc->flags             = usvc_compat->flags;
2325         usvc->timeout           = usvc_compat->timeout;
2326         usvc->netmask           = usvc_compat->netmask;
2327 }
2328
2329 static void ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern *udest,
2330                                    struct ip_vs_dest_user *udest_compat)
2331 {
2332         memset(udest, 0, sizeof(*udest));
2333
2334         udest->addr.ip          = udest_compat->addr;
2335         udest->port             = udest_compat->port;
2336         udest->conn_flags       = udest_compat->conn_flags;
2337         udest->weight           = udest_compat->weight;
2338         udest->u_threshold      = udest_compat->u_threshold;
2339         udest->l_threshold      = udest_compat->l_threshold;
2340         udest->af               = AF_INET;
2341 }
2342
2343 static int
2344 do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
2345 {
2346         struct net *net = sock_net(sk);
2347         int ret;
2348         unsigned char arg[MAX_SET_ARGLEN];
2349         struct ip_vs_service_user *usvc_compat;
2350         struct ip_vs_service_user_kern usvc;
2351         struct ip_vs_service *svc;
2352         struct ip_vs_dest_user *udest_compat;
2353         struct ip_vs_dest_user_kern udest;
2354         struct netns_ipvs *ipvs = net_ipvs(net);
2355
2356         BUILD_BUG_ON(sizeof(arg) > 255);
2357         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2358                 return -EPERM;
2359
2360         if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)
2361                 return -EINVAL;
2362         if (len != set_arglen[CMDID(cmd)]) {
2363                 IP_VS_DBG(1, "set_ctl: len %u != %u\n",
2364                           len, set_arglen[CMDID(cmd)]);
2365                 return -EINVAL;
2366         }
2367
2368         if (copy_from_user(arg, user, len) != 0)
2369                 return -EFAULT;
2370
2371         /* Handle daemons since they have another lock */
2372         if (cmd == IP_VS_SO_SET_STARTDAEMON ||
2373             cmd == IP_VS_SO_SET_STOPDAEMON) {
2374                 struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
2375
2376                 if (cmd == IP_VS_SO_SET_STARTDAEMON) {
2377                         struct ipvs_sync_daemon_cfg cfg;
2378
2379                         memset(&cfg, 0, sizeof(cfg));
2380                         ret = -EINVAL;
2381                         if (strscpy(cfg.mcast_ifn, dm->mcast_ifn,
2382                                     sizeof(cfg.mcast_ifn)) <= 0)
2383                                 return ret;
2384                         cfg.syncid = dm->syncid;
2385                         ret = start_sync_thread(ipvs, &cfg, dm->state);
2386                 } else {
2387                         ret = stop_sync_thread(ipvs, dm->state);
2388                 }
2389                 return ret;
2390         }
2391
2392         mutex_lock(&__ip_vs_mutex);
2393         if (cmd == IP_VS_SO_SET_FLUSH) {
2394                 /* Flush the virtual service */
2395                 ret = ip_vs_flush(ipvs, false);
2396                 goto out_unlock;
2397         } else if (cmd == IP_VS_SO_SET_TIMEOUT) {
2398                 /* Set timeout values for (tcp tcpfin udp) */
2399                 ret = ip_vs_set_timeout(ipvs, (struct ip_vs_timeout_user *)arg);
2400                 goto out_unlock;
2401         } else if (!len) {
2402                 /* No more commands with len == 0 below */
2403                 ret = -EINVAL;
2404                 goto out_unlock;
2405         }
2406
2407         usvc_compat = (struct ip_vs_service_user *)arg;
2408         udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
2409
2410         /* We only use the new structs internally, so copy userspace compat
2411          * structs to extended internal versions */
2412         ip_vs_copy_usvc_compat(&usvc, usvc_compat);
2413         ip_vs_copy_udest_compat(&udest, udest_compat);
2414
2415         if (cmd == IP_VS_SO_SET_ZERO) {
2416                 /* if no service address is set, zero counters in all */
2417                 if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
2418                         ret = ip_vs_zero_all(ipvs);
2419                         goto out_unlock;
2420                 }
2421         }
2422
2423         if ((cmd == IP_VS_SO_SET_ADD || cmd == IP_VS_SO_SET_EDIT) &&
2424             strnlen(usvc.sched_name, IP_VS_SCHEDNAME_MAXLEN) ==
2425             IP_VS_SCHEDNAME_MAXLEN) {
2426                 ret = -EINVAL;
2427                 goto out_unlock;
2428         }
2429
2430         /* Check for valid protocol: TCP or UDP or SCTP, even for fwmark!=0 */
2431         if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP &&
2432             usvc.protocol != IPPROTO_SCTP) {
2433                 pr_err("set_ctl: invalid protocol: %d %pI4:%d\n",
2434                        usvc.protocol, &usvc.addr.ip,
2435                        ntohs(usvc.port));
2436                 ret = -EFAULT;
2437                 goto out_unlock;
2438         }
2439
2440         /* Lookup the exact service by <protocol, addr, port> or fwmark */
2441         rcu_read_lock();
2442         if (usvc.fwmark == 0)
2443                 svc = __ip_vs_service_find(ipvs, usvc.af, usvc.protocol,
2444                                            &usvc.addr, usvc.port);
2445         else
2446                 svc = __ip_vs_svc_fwm_find(ipvs, usvc.af, usvc.fwmark);
2447         rcu_read_unlock();
2448
2449         if (cmd != IP_VS_SO_SET_ADD
2450             && (svc == NULL || svc->protocol != usvc.protocol)) {
2451                 ret = -ESRCH;
2452                 goto out_unlock;
2453         }
2454
2455         switch (cmd) {
2456         case IP_VS_SO_SET_ADD:
2457                 if (svc != NULL)
2458                         ret = -EEXIST;
2459                 else
2460                         ret = ip_vs_add_service(ipvs, &usvc, &svc);
2461                 break;
2462         case IP_VS_SO_SET_EDIT:
2463                 ret = ip_vs_edit_service(svc, &usvc);
2464                 break;
2465         case IP_VS_SO_SET_DEL:
2466                 ret = ip_vs_del_service(svc);
2467                 if (!ret)
2468                         goto out_unlock;
2469                 break;
2470         case IP_VS_SO_SET_ZERO:
2471                 ret = ip_vs_zero_service(svc);
2472                 break;
2473         case IP_VS_SO_SET_ADDDEST:
2474                 ret = ip_vs_add_dest(svc, &udest);
2475                 break;
2476         case IP_VS_SO_SET_EDITDEST:
2477                 ret = ip_vs_edit_dest(svc, &udest);
2478                 break;
2479         case IP_VS_SO_SET_DELDEST:
2480                 ret = ip_vs_del_dest(svc, &udest);
2481         }
2482
2483   out_unlock:
2484         mutex_unlock(&__ip_vs_mutex);
2485         return ret;
2486 }
2487
2488
2489 static void
2490 ip_vs_copy_service(struct ip_vs_service_entry *dst, struct ip_vs_service *src)
2491 {
2492         struct ip_vs_scheduler *sched;
2493         struct ip_vs_kstats kstats;
2494         char *sched_name;
2495
2496         sched = rcu_dereference_protected(src->scheduler, 1);
2497         sched_name = sched ? sched->name : "none";
2498         dst->protocol = src->protocol;
2499         dst->addr = src->addr.ip;
2500         dst->port = src->port;
2501         dst->fwmark = src->fwmark;
2502         strlcpy(dst->sched_name, sched_name, sizeof(dst->sched_name));
2503         dst->flags = src->flags;
2504         dst->timeout = src->timeout / HZ;
2505         dst->netmask = src->netmask;
2506         dst->num_dests = src->num_dests;
2507         ip_vs_copy_stats(&kstats, &src->stats);
2508         ip_vs_export_stats_user(&dst->stats, &kstats);
2509 }
2510
2511 static inline int
2512 __ip_vs_get_service_entries(struct netns_ipvs *ipvs,
2513                             const struct ip_vs_get_services *get,
2514                             struct ip_vs_get_services __user *uptr)
2515 {
2516         int idx, count=0;
2517         struct ip_vs_service *svc;
2518         struct ip_vs_service_entry entry;
2519         int ret = 0;
2520
2521         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2522                 hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
2523                         /* Only expose IPv4 entries to old interface */
2524                         if (svc->af != AF_INET || (svc->ipvs != ipvs))
2525                                 continue;
2526
2527                         if (count >= get->num_services)
2528                                 goto out;
2529                         memset(&entry, 0, sizeof(entry));
2530                         ip_vs_copy_service(&entry, svc);
2531                         if (copy_to_user(&uptr->entrytable[count],
2532                                          &entry, sizeof(entry))) {
2533                                 ret = -EFAULT;
2534                                 goto out;
2535                         }
2536                         count++;
2537                 }
2538         }
2539
2540         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2541                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
2542                         /* Only expose IPv4 entries to old interface */
2543                         if (svc->af != AF_INET || (svc->ipvs != ipvs))
2544                                 continue;
2545
2546                         if (count >= get->num_services)
2547                                 goto out;
2548                         memset(&entry, 0, sizeof(entry));
2549                         ip_vs_copy_service(&entry, svc);
2550                         if (copy_to_user(&uptr->entrytable[count],
2551                                          &entry, sizeof(entry))) {
2552                                 ret = -EFAULT;
2553                                 goto out;
2554                         }
2555                         count++;
2556                 }
2557         }
2558 out:
2559         return ret;
2560 }
2561
2562 static inline int
2563 __ip_vs_get_dest_entries(struct netns_ipvs *ipvs, const struct ip_vs_get_dests *get,
2564                          struct ip_vs_get_dests __user *uptr)
2565 {
2566         struct ip_vs_service *svc;
2567         union nf_inet_addr addr = { .ip = get->addr };
2568         int ret = 0;
2569
2570         rcu_read_lock();
2571         if (get->fwmark)
2572                 svc = __ip_vs_svc_fwm_find(ipvs, AF_INET, get->fwmark);
2573         else
2574                 svc = __ip_vs_service_find(ipvs, AF_INET, get->protocol, &addr,
2575                                            get->port);
2576         rcu_read_unlock();
2577
2578         if (svc) {
2579                 int count = 0;
2580                 struct ip_vs_dest *dest;
2581                 struct ip_vs_dest_entry entry;
2582                 struct ip_vs_kstats kstats;
2583
2584                 memset(&entry, 0, sizeof(entry));
2585                 list_for_each_entry(dest, &svc->destinations, n_list) {
2586                         if (count >= get->num_dests)
2587                                 break;
2588
2589                         /* Cannot expose heterogeneous members via sockopt
2590                          * interface
2591                          */
2592                         if (dest->af != svc->af)
2593                                 continue;
2594
2595                         entry.addr = dest->addr.ip;
2596                         entry.port = dest->port;
2597                         entry.conn_flags = atomic_read(&dest->conn_flags);
2598                         entry.weight = atomic_read(&dest->weight);
2599                         entry.u_threshold = dest->u_threshold;
2600                         entry.l_threshold = dest->l_threshold;
2601                         entry.activeconns = atomic_read(&dest->activeconns);
2602                         entry.inactconns = atomic_read(&dest->inactconns);
2603                         entry.persistconns = atomic_read(&dest->persistconns);
2604                         ip_vs_copy_stats(&kstats, &dest->stats);
2605                         ip_vs_export_stats_user(&entry.stats, &kstats);
2606                         if (copy_to_user(&uptr->entrytable[count],
2607                                          &entry, sizeof(entry))) {
2608                                 ret = -EFAULT;
2609                                 break;
2610                         }
2611                         count++;
2612                 }
2613         } else
2614                 ret = -ESRCH;
2615         return ret;
2616 }
2617
2618 static inline void
2619 __ip_vs_get_timeouts(struct netns_ipvs *ipvs, struct ip_vs_timeout_user *u)
2620 {
2621 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2622         struct ip_vs_proto_data *pd;
2623 #endif
2624
2625         memset(u, 0, sizeof (*u));
2626
2627 #ifdef CONFIG_IP_VS_PROTO_TCP
2628         pd = ip_vs_proto_data_get(ipvs, IPPROTO_TCP);
2629         u->tcp_timeout = pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ;
2630         u->tcp_fin_timeout = pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ;
2631 #endif
2632 #ifdef CONFIG_IP_VS_PROTO_UDP
2633         pd = ip_vs_proto_data_get(ipvs, IPPROTO_UDP);
2634         u->udp_timeout =
2635                         pd->timeout_table[IP_VS_UDP_S_NORMAL] / HZ;
2636 #endif
2637 }
2638
2639 static const unsigned char get_arglen[CMDID(IP_VS_SO_GET_MAX) + 1] = {
2640         [CMDID(IP_VS_SO_GET_VERSION)]  = 64,
2641         [CMDID(IP_VS_SO_GET_INFO)]     = sizeof(struct ip_vs_getinfo),
2642         [CMDID(IP_VS_SO_GET_SERVICES)] = sizeof(struct ip_vs_get_services),
2643         [CMDID(IP_VS_SO_GET_SERVICE)]  = sizeof(struct ip_vs_service_entry),
2644         [CMDID(IP_VS_SO_GET_DESTS)]    = sizeof(struct ip_vs_get_dests),
2645         [CMDID(IP_VS_SO_GET_TIMEOUT)]  = sizeof(struct ip_vs_timeout_user),
2646         [CMDID(IP_VS_SO_GET_DAEMON)]   = 2 * sizeof(struct ip_vs_daemon_user),
2647 };
2648
2649 union ip_vs_get_arglen {
2650         char                            field_IP_VS_SO_GET_VERSION[64];
2651         struct ip_vs_getinfo            field_IP_VS_SO_GET_INFO;
2652         struct ip_vs_get_services       field_IP_VS_SO_GET_SERVICES;
2653         struct ip_vs_service_entry      field_IP_VS_SO_GET_SERVICE;
2654         struct ip_vs_get_dests          field_IP_VS_SO_GET_DESTS;
2655         struct ip_vs_timeout_user       field_IP_VS_SO_GET_TIMEOUT;
2656         struct ip_vs_daemon_user        field_IP_VS_SO_GET_DAEMON[2];
2657 };
2658
2659 #define MAX_GET_ARGLEN  sizeof(union ip_vs_get_arglen)
2660
2661 static int
2662 do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
2663 {
2664         unsigned char arg[MAX_GET_ARGLEN];
2665         int ret = 0;
2666         unsigned int copylen;
2667         struct net *net = sock_net(sk);
2668         struct netns_ipvs *ipvs = net_ipvs(net);
2669
2670         BUG_ON(!net);
2671         BUILD_BUG_ON(sizeof(arg) > 255);
2672         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2673                 return -EPERM;
2674
2675         if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
2676                 return -EINVAL;
2677
2678         copylen = get_arglen[CMDID(cmd)];
2679         if (*len < (int) copylen) {
2680                 IP_VS_DBG(1, "get_ctl: len %d < %u\n", *len, copylen);
2681                 return -EINVAL;
2682         }
2683
2684         if (copy_from_user(arg, user, copylen) != 0)
2685                 return -EFAULT;
2686         /*
2687          * Handle daemons first since it has its own locking
2688          */
2689         if (cmd == IP_VS_SO_GET_DAEMON) {
2690                 struct ip_vs_daemon_user d[2];
2691
2692                 memset(&d, 0, sizeof(d));
2693                 mutex_lock(&ipvs->sync_mutex);
2694                 if (ipvs->sync_state & IP_VS_STATE_MASTER) {
2695                         d[0].state = IP_VS_STATE_MASTER;
2696                         strlcpy(d[0].mcast_ifn, ipvs->mcfg.mcast_ifn,
2697                                 sizeof(d[0].mcast_ifn));
2698                         d[0].syncid = ipvs->mcfg.syncid;
2699                 }
2700                 if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
2701                         d[1].state = IP_VS_STATE_BACKUP;
2702                         strlcpy(d[1].mcast_ifn, ipvs->bcfg.mcast_ifn,
2703                                 sizeof(d[1].mcast_ifn));
2704                         d[1].syncid = ipvs->bcfg.syncid;
2705                 }
2706                 if (copy_to_user(user, &d, sizeof(d)) != 0)
2707                         ret = -EFAULT;
2708                 mutex_unlock(&ipvs->sync_mutex);
2709                 return ret;
2710         }
2711
2712         mutex_lock(&__ip_vs_mutex);
2713         switch (cmd) {
2714         case IP_VS_SO_GET_VERSION:
2715         {
2716                 char buf[64];
2717
2718                 sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
2719                         NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2720                 if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
2721                         ret = -EFAULT;
2722                         goto out;
2723                 }
2724                 *len = strlen(buf)+1;
2725         }
2726         break;
2727
2728         case IP_VS_SO_GET_INFO:
2729         {
2730                 struct ip_vs_getinfo info;
2731                 info.version = IP_VS_VERSION_CODE;
2732                 info.size = ip_vs_conn_tab_size;
2733                 info.num_services = ipvs->num_services;
2734                 if (copy_to_user(user, &info, sizeof(info)) != 0)
2735                         ret = -EFAULT;
2736         }
2737         break;
2738
2739         case IP_VS_SO_GET_SERVICES:
2740         {
2741                 struct ip_vs_get_services *get;
2742                 int size;
2743
2744                 get = (struct ip_vs_get_services *)arg;
2745                 size = sizeof(*get) +
2746                         sizeof(struct ip_vs_service_entry) * get->num_services;
2747                 if (*len != size) {
2748                         pr_err("length: %u != %u\n", *len, size);
2749                         ret = -EINVAL;
2750                         goto out;
2751                 }
2752                 ret = __ip_vs_get_service_entries(ipvs, get, user);
2753         }
2754         break;
2755
2756         case IP_VS_SO_GET_SERVICE:
2757         {
2758                 struct ip_vs_service_entry *entry;
2759                 struct ip_vs_service *svc;
2760                 union nf_inet_addr addr;
2761
2762                 entry = (struct ip_vs_service_entry *)arg;
2763                 addr.ip = entry->addr;
2764                 rcu_read_lock();
2765                 if (entry->fwmark)
2766                         svc = __ip_vs_svc_fwm_find(ipvs, AF_INET, entry->fwmark);
2767                 else
2768                         svc = __ip_vs_service_find(ipvs, AF_INET,
2769                                                    entry->protocol, &addr,
2770                                                    entry->port);
2771                 rcu_read_unlock();
2772                 if (svc) {
2773                         ip_vs_copy_service(entry, svc);
2774                         if (copy_to_user(user, entry, sizeof(*entry)) != 0)
2775                                 ret = -EFAULT;
2776                 } else
2777                         ret = -ESRCH;
2778         }
2779         break;
2780
2781         case IP_VS_SO_GET_DESTS:
2782         {
2783                 struct ip_vs_get_dests *get;
2784                 int size;
2785
2786                 get = (struct ip_vs_get_dests *)arg;
2787                 size = sizeof(*get) +
2788                         sizeof(struct ip_vs_dest_entry) * get->num_dests;
2789                 if (*len != size) {
2790                         pr_err("length: %u != %u\n", *len, size);
2791                         ret = -EINVAL;
2792                         goto out;
2793                 }
2794                 ret = __ip_vs_get_dest_entries(ipvs, get, user);
2795         }
2796         break;
2797
2798         case IP_VS_SO_GET_TIMEOUT:
2799         {
2800                 struct ip_vs_timeout_user t;
2801
2802                 __ip_vs_get_timeouts(ipvs, &t);
2803                 if (copy_to_user(user, &t, sizeof(t)) != 0)
2804                         ret = -EFAULT;
2805         }
2806         break;
2807
2808         default:
2809                 ret = -EINVAL;
2810         }
2811
2812 out:
2813         mutex_unlock(&__ip_vs_mutex);
2814         return ret;
2815 }
2816
2817
2818 static struct nf_sockopt_ops ip_vs_sockopts = {
2819         .pf             = PF_INET,
2820         .set_optmin     = IP_VS_BASE_CTL,
2821         .set_optmax     = IP_VS_SO_SET_MAX+1,
2822         .set            = do_ip_vs_set_ctl,
2823         .get_optmin     = IP_VS_BASE_CTL,
2824         .get_optmax     = IP_VS_SO_GET_MAX+1,
2825         .get            = do_ip_vs_get_ctl,
2826         .owner          = THIS_MODULE,
2827 };
2828
2829 /*
2830  * Generic Netlink interface
2831  */
2832
2833 /* IPVS genetlink family */
2834 static struct genl_family ip_vs_genl_family;
2835
2836 /* Policy used for first-level command attributes */
2837 static const struct nla_policy ip_vs_cmd_policy[IPVS_CMD_ATTR_MAX + 1] = {
2838         [IPVS_CMD_ATTR_SERVICE]         = { .type = NLA_NESTED },
2839         [IPVS_CMD_ATTR_DEST]            = { .type = NLA_NESTED },
2840         [IPVS_CMD_ATTR_DAEMON]          = { .type = NLA_NESTED },
2841         [IPVS_CMD_ATTR_TIMEOUT_TCP]     = { .type = NLA_U32 },
2842         [IPVS_CMD_ATTR_TIMEOUT_TCP_FIN] = { .type = NLA_U32 },
2843         [IPVS_CMD_ATTR_TIMEOUT_UDP]     = { .type = NLA_U32 },
2844 };
2845
2846 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DAEMON */
2847 static const struct nla_policy ip_vs_daemon_policy[IPVS_DAEMON_ATTR_MAX + 1] = {
2848         [IPVS_DAEMON_ATTR_STATE]        = { .type = NLA_U32 },
2849         [IPVS_DAEMON_ATTR_MCAST_IFN]    = { .type = NLA_NUL_STRING,
2850                                             .len = IP_VS_IFNAME_MAXLEN - 1 },
2851         [IPVS_DAEMON_ATTR_SYNC_ID]      = { .type = NLA_U32 },
2852         [IPVS_DAEMON_ATTR_SYNC_MAXLEN]  = { .type = NLA_U16 },
2853         [IPVS_DAEMON_ATTR_MCAST_GROUP]  = { .type = NLA_U32 },
2854         [IPVS_DAEMON_ATTR_MCAST_GROUP6] = { .len = sizeof(struct in6_addr) },
2855         [IPVS_DAEMON_ATTR_MCAST_PORT]   = { .type = NLA_U16 },
2856         [IPVS_DAEMON_ATTR_MCAST_TTL]    = { .type = NLA_U8 },
2857 };
2858
2859 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_SERVICE */
2860 static const struct nla_policy ip_vs_svc_policy[IPVS_SVC_ATTR_MAX + 1] = {
2861         [IPVS_SVC_ATTR_AF]              = { .type = NLA_U16 },
2862         [IPVS_SVC_ATTR_PROTOCOL]        = { .type = NLA_U16 },
2863         [IPVS_SVC_ATTR_ADDR]            = { .type = NLA_BINARY,
2864                                             .len = sizeof(union nf_inet_addr) },
2865         [IPVS_SVC_ATTR_PORT]            = { .type = NLA_U16 },
2866         [IPVS_SVC_ATTR_FWMARK]          = { .type = NLA_U32 },
2867         [IPVS_SVC_ATTR_SCHED_NAME]      = { .type = NLA_NUL_STRING,
2868                                             .len = IP_VS_SCHEDNAME_MAXLEN - 1 },
2869         [IPVS_SVC_ATTR_PE_NAME]         = { .type = NLA_NUL_STRING,
2870                                             .len = IP_VS_PENAME_MAXLEN },
2871         [IPVS_SVC_ATTR_FLAGS]           = { .type = NLA_BINARY,
2872                                             .len = sizeof(struct ip_vs_flags) },
2873         [IPVS_SVC_ATTR_TIMEOUT]         = { .type = NLA_U32 },
2874         [IPVS_SVC_ATTR_NETMASK]         = { .type = NLA_U32 },
2875         [IPVS_SVC_ATTR_STATS]           = { .type = NLA_NESTED },
2876 };
2877
2878 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DEST */
2879 static const struct nla_policy ip_vs_dest_policy[IPVS_DEST_ATTR_MAX + 1] = {
2880         [IPVS_DEST_ATTR_ADDR]           = { .type = NLA_BINARY,
2881                                             .len = sizeof(union nf_inet_addr) },
2882         [IPVS_DEST_ATTR_PORT]           = { .type = NLA_U16 },
2883         [IPVS_DEST_ATTR_FWD_METHOD]     = { .type = NLA_U32 },
2884         [IPVS_DEST_ATTR_WEIGHT]         = { .type = NLA_U32 },
2885         [IPVS_DEST_ATTR_U_THRESH]       = { .type = NLA_U32 },
2886         [IPVS_DEST_ATTR_L_THRESH]       = { .type = NLA_U32 },
2887         [IPVS_DEST_ATTR_ACTIVE_CONNS]   = { .type = NLA_U32 },
2888         [IPVS_DEST_ATTR_INACT_CONNS]    = { .type = NLA_U32 },
2889         [IPVS_DEST_ATTR_PERSIST_CONNS]  = { .type = NLA_U32 },
2890         [IPVS_DEST_ATTR_STATS]          = { .type = NLA_NESTED },
2891         [IPVS_DEST_ATTR_ADDR_FAMILY]    = { .type = NLA_U16 },
2892 };
2893
2894 static int ip_vs_genl_fill_stats(struct sk_buff *skb, int container_type,
2895                                  struct ip_vs_kstats *kstats)
2896 {
2897         struct nlattr *nl_stats = nla_nest_start(skb, container_type);
2898
2899         if (!nl_stats)
2900                 return -EMSGSIZE;
2901
2902         if (nla_put_u32(skb, IPVS_STATS_ATTR_CONNS, (u32)kstats->conns) ||
2903             nla_put_u32(skb, IPVS_STATS_ATTR_INPKTS, (u32)kstats->inpkts) ||
2904             nla_put_u32(skb, IPVS_STATS_ATTR_OUTPKTS, (u32)kstats->outpkts) ||
2905             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INBYTES, kstats->inbytes,
2906                               IPVS_STATS_ATTR_PAD) ||
2907             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTBYTES, kstats->outbytes,
2908                               IPVS_STATS_ATTR_PAD) ||
2909             nla_put_u32(skb, IPVS_STATS_ATTR_CPS, (u32)kstats->cps) ||
2910             nla_put_u32(skb, IPVS_STATS_ATTR_INPPS, (u32)kstats->inpps) ||
2911             nla_put_u32(skb, IPVS_STATS_ATTR_OUTPPS, (u32)kstats->outpps) ||
2912             nla_put_u32(skb, IPVS_STATS_ATTR_INBPS, (u32)kstats->inbps) ||
2913             nla_put_u32(skb, IPVS_STATS_ATTR_OUTBPS, (u32)kstats->outbps))
2914                 goto nla_put_failure;
2915         nla_nest_end(skb, nl_stats);
2916
2917         return 0;
2918
2919 nla_put_failure:
2920         nla_nest_cancel(skb, nl_stats);
2921         return -EMSGSIZE;
2922 }
2923
2924 static int ip_vs_genl_fill_stats64(struct sk_buff *skb, int container_type,
2925                                    struct ip_vs_kstats *kstats)
2926 {
2927         struct nlattr *nl_stats = nla_nest_start(skb, container_type);
2928
2929         if (!nl_stats)
2930                 return -EMSGSIZE;
2931
2932         if (nla_put_u64_64bit(skb, IPVS_STATS_ATTR_CONNS, kstats->conns,
2933                               IPVS_STATS_ATTR_PAD) ||
2934             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INPKTS, kstats->inpkts,
2935                               IPVS_STATS_ATTR_PAD) ||
2936             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTPKTS, kstats->outpkts,
2937                               IPVS_STATS_ATTR_PAD) ||
2938             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INBYTES, kstats->inbytes,
2939                               IPVS_STATS_ATTR_PAD) ||
2940             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTBYTES, kstats->outbytes,
2941                               IPVS_STATS_ATTR_PAD) ||
2942             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_CPS, kstats->cps,
2943                               IPVS_STATS_ATTR_PAD) ||
2944             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INPPS, kstats->inpps,
2945                               IPVS_STATS_ATTR_PAD) ||
2946             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTPPS, kstats->outpps,
2947                               IPVS_STATS_ATTR_PAD) ||
2948             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INBPS, kstats->inbps,
2949                               IPVS_STATS_ATTR_PAD) ||
2950             nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTBPS, kstats->outbps,
2951                               IPVS_STATS_ATTR_PAD))
2952                 goto nla_put_failure;
2953         nla_nest_end(skb, nl_stats);
2954
2955         return 0;
2956
2957 nla_put_failure:
2958         nla_nest_cancel(skb, nl_stats);
2959         return -EMSGSIZE;
2960 }
2961
2962 static int ip_vs_genl_fill_service(struct sk_buff *skb,
2963                                    struct ip_vs_service *svc)
2964 {
2965         struct ip_vs_scheduler *sched;
2966         struct ip_vs_pe *pe;
2967         struct nlattr *nl_service;
2968         struct ip_vs_flags flags = { .flags = svc->flags,
2969                                      .mask = ~0 };
2970         struct ip_vs_kstats kstats;
2971         char *sched_name;
2972
2973         nl_service = nla_nest_start(skb, IPVS_CMD_ATTR_SERVICE);
2974         if (!nl_service)
2975                 return -EMSGSIZE;
2976
2977         if (nla_put_u16(skb, IPVS_SVC_ATTR_AF, svc->af))
2978                 goto nla_put_failure;
2979         if (svc->fwmark) {
2980                 if (nla_put_u32(skb, IPVS_SVC_ATTR_FWMARK, svc->fwmark))
2981                         goto nla_put_failure;
2982         } else {
2983                 if (nla_put_u16(skb, IPVS_SVC_ATTR_PROTOCOL, svc->protocol) ||
2984                     nla_put(skb, IPVS_SVC_ATTR_ADDR, sizeof(svc->addr), &svc->addr) ||
2985                     nla_put_be16(skb, IPVS_SVC_ATTR_PORT, svc->port))
2986                         goto nla_put_failure;
2987         }
2988
2989         sched = rcu_dereference_protected(svc->scheduler, 1);
2990         sched_name = sched ? sched->name : "none";
2991         pe = rcu_dereference_protected(svc->pe, 1);
2992         if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched_name) ||
2993             (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) ||
2994             nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||
2995             nla_put_u32(skb, IPVS_SVC_ATTR_TIMEOUT, svc->timeout / HZ) ||
2996             nla_put_be32(skb, IPVS_SVC_ATTR_NETMASK, svc->netmask))
2997                 goto nla_put_failure;
2998         ip_vs_copy_stats(&kstats, &svc->stats);
2999         if (ip_vs_genl_fill_stats(skb, IPVS_SVC_ATTR_STATS, &kstats))
3000                 goto nla_put_failure;
3001         if (ip_vs_genl_fill_stats64(skb, IPVS_SVC_ATTR_STATS64, &kstats))
3002                 goto nla_put_failure;
3003
3004         nla_nest_end(skb, nl_service);
3005
3006         return 0;
3007
3008 nla_put_failure:
3009         nla_nest_cancel(skb, nl_service);
3010         return -EMSGSIZE;
3011 }
3012
3013 static int ip_vs_genl_dump_service(struct sk_buff *skb,
3014                                    struct ip_vs_service *svc,
3015                                    struct netlink_callback *cb)
3016 {
3017         void *hdr;
3018
3019         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3020                           &ip_vs_genl_family, NLM_F_MULTI,
3021                           IPVS_CMD_NEW_SERVICE);
3022         if (!hdr)
3023                 return -EMSGSIZE;
3024
3025         if (ip_vs_genl_fill_service(skb, svc) < 0)
3026                 goto nla_put_failure;
3027
3028         genlmsg_end(skb, hdr);
3029         return 0;
3030
3031 nla_put_failure:
3032         genlmsg_cancel(skb, hdr);
3033         return -EMSGSIZE;
3034 }
3035
3036 static int ip_vs_genl_dump_services(struct sk_buff *skb,
3037                                     struct netlink_callback *cb)
3038 {
3039         int idx = 0, i;
3040         int start = cb->args[0];
3041         struct ip_vs_service *svc;
3042         struct net *net = sock_net(skb->sk);
3043         struct netns_ipvs *ipvs = net_ipvs(net);
3044
3045         mutex_lock(&__ip_vs_mutex);
3046         for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
3047                 hlist_for_each_entry(svc, &ip_vs_svc_table[i], s_list) {
3048                         if (++idx <= start || (svc->ipvs != ipvs))
3049                                 continue;
3050                         if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
3051                                 idx--;
3052                                 goto nla_put_failure;
3053                         }
3054                 }
3055         }
3056
3057         for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
3058                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[i], f_list) {
3059                         if (++idx <= start || (svc->ipvs != ipvs))
3060                                 continue;
3061                         if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
3062                                 idx--;
3063                                 goto nla_put_failure;
3064                         }
3065                 }
3066         }
3067
3068 nla_put_failure:
3069         mutex_unlock(&__ip_vs_mutex);
3070         cb->args[0] = idx;
3071
3072         return skb->len;
3073 }
3074
3075 static bool ip_vs_is_af_valid(int af)
3076 {
3077         if (af == AF_INET)
3078                 return true;
3079 #ifdef CONFIG_IP_VS_IPV6
3080         if (af == AF_INET6 && ipv6_mod_enabled())
3081                 return true;
3082 #endif
3083         return false;
3084 }
3085
3086 static int ip_vs_genl_parse_service(struct netns_ipvs *ipvs,
3087                                     struct ip_vs_service_user_kern *usvc,
3088                                     struct nlattr *nla, int full_entry,
3089                                     struct ip_vs_service **ret_svc)
3090 {
3091         struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1];
3092         struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr;
3093         struct ip_vs_service *svc;
3094
3095         /* Parse mandatory identifying service fields first */
3096         if (nla == NULL ||
3097             nla_parse_nested(attrs, IPVS_SVC_ATTR_MAX, nla,
3098                              ip_vs_svc_policy, NULL))
3099                 return -EINVAL;
3100
3101         nla_af          = attrs[IPVS_SVC_ATTR_AF];
3102         nla_protocol    = attrs[IPVS_SVC_ATTR_PROTOCOL];
3103         nla_addr        = attrs[IPVS_SVC_ATTR_ADDR];
3104         nla_port        = attrs[IPVS_SVC_ATTR_PORT];
3105         nla_fwmark      = attrs[IPVS_SVC_ATTR_FWMARK];
3106
3107         if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr))))
3108                 return -EINVAL;
3109
3110         memset(usvc, 0, sizeof(*usvc));
3111
3112         usvc->af = nla_get_u16(nla_af);
3113         if (!ip_vs_is_af_valid(usvc->af))
3114                 return -EAFNOSUPPORT;
3115
3116         if (nla_fwmark) {
3117                 usvc->protocol = IPPROTO_TCP;
3118                 usvc->fwmark = nla_get_u32(nla_fwmark);
3119         } else {
3120                 usvc->protocol = nla_get_u16(nla_protocol);
3121                 nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr));
3122                 usvc->port = nla_get_be16(nla_port);
3123                 usvc->fwmark = 0;
3124         }
3125
3126         rcu_read_lock();
3127         if (usvc->fwmark)
3128                 svc = __ip_vs_svc_fwm_find(ipvs, usvc->af, usvc->fwmark);
3129         else
3130                 svc = __ip_vs_service_find(ipvs, usvc->af, usvc->protocol,
3131                                            &usvc->addr, usvc->port);
3132         rcu_read_unlock();
3133         *ret_svc = svc;
3134
3135         /* If a full entry was requested, check for the additional fields */
3136         if (full_entry) {
3137                 struct nlattr *nla_sched, *nla_flags, *nla_pe, *nla_timeout,
3138                               *nla_netmask;
3139                 struct ip_vs_flags flags;
3140
3141                 nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME];
3142                 nla_pe = attrs[IPVS_SVC_ATTR_PE_NAME];
3143                 nla_flags = attrs[IPVS_SVC_ATTR_FLAGS];
3144                 nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT];
3145                 nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK];
3146
3147                 if (!(nla_sched && nla_flags && nla_timeout && nla_netmask))
3148                         return -EINVAL;
3149
3150                 nla_memcpy(&flags, nla_flags, sizeof(flags));
3151
3152                 /* prefill flags from service if it already exists */
3153                 if (svc)
3154                         usvc->flags = svc->flags;
3155
3156                 /* set new flags from userland */
3157                 usvc->flags = (usvc->flags & ~flags.mask) |
3158                               (flags.flags & flags.mask);
3159                 usvc->sched_name = nla_data(nla_sched);
3160                 usvc->pe_name = nla_pe ? nla_data(nla_pe) : NULL;
3161                 usvc->timeout = nla_get_u32(nla_timeout);
3162                 usvc->netmask = nla_get_be32(nla_netmask);
3163         }
3164
3165         return 0;
3166 }
3167
3168 static struct ip_vs_service *ip_vs_genl_find_service(struct netns_ipvs *ipvs,
3169                                                      struct nlattr *nla)
3170 {
3171         struct ip_vs_service_user_kern usvc;
3172         struct ip_vs_service *svc;
3173         int ret;
3174
3175         ret = ip_vs_genl_parse_service(ipvs, &usvc, nla, 0, &svc);
3176         return ret ? ERR_PTR(ret) : svc;
3177 }
3178
3179 static int ip_vs_genl_fill_dest(struct sk_buff *skb, struct ip_vs_dest *dest)
3180 {
3181         struct nlattr *nl_dest;
3182         struct ip_vs_kstats kstats;
3183
3184         nl_dest = nla_nest_start(skb, IPVS_CMD_ATTR_DEST);
3185         if (!nl_dest)
3186                 return -EMSGSIZE;
3187
3188         if (nla_put(skb, IPVS_DEST_ATTR_ADDR, sizeof(dest->addr), &dest->addr) ||
3189             nla_put_be16(skb, IPVS_DEST_ATTR_PORT, dest->port) ||
3190             nla_put_u32(skb, IPVS_DEST_ATTR_FWD_METHOD,
3191                         (atomic_read(&dest->conn_flags) &
3192                          IP_VS_CONN_F_FWD_MASK)) ||
3193             nla_put_u32(skb, IPVS_DEST_ATTR_WEIGHT,
3194                         atomic_read(&dest->weight)) ||
3195             nla_put_u32(skb, IPVS_DEST_ATTR_U_THRESH, dest->u_threshold) ||
3196             nla_put_u32(skb, IPVS_DEST_ATTR_L_THRESH, dest->l_threshold) ||
3197             nla_put_u32(skb, IPVS_DEST_ATTR_ACTIVE_CONNS,
3198                         atomic_read(&dest->activeconns)) ||
3199             nla_put_u32(skb, IPVS_DEST_ATTR_INACT_CONNS,
3200                         atomic_read(&dest->inactconns)) ||
3201             nla_put_u32(skb, IPVS_DEST_ATTR_PERSIST_CONNS,
3202                         atomic_read(&dest->persistconns)) ||
3203             nla_put_u16(skb, IPVS_DEST_ATTR_ADDR_FAMILY, dest->af))
3204                 goto nla_put_failure;
3205         ip_vs_copy_stats(&kstats, &dest->stats);
3206         if (ip_vs_genl_fill_stats(skb, IPVS_DEST_ATTR_STATS, &kstats))
3207                 goto nla_put_failure;
3208         if (ip_vs_genl_fill_stats64(skb, IPVS_DEST_ATTR_STATS64, &kstats))
3209                 goto nla_put_failure;
3210
3211         nla_nest_end(skb, nl_dest);
3212
3213         return 0;
3214
3215 nla_put_failure:
3216         nla_nest_cancel(skb, nl_dest);
3217         return -EMSGSIZE;
3218 }
3219
3220 static int ip_vs_genl_dump_dest(struct sk_buff *skb, struct ip_vs_dest *dest,
3221                                 struct netlink_callback *cb)
3222 {
3223         void *hdr;
3224
3225         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3226                           &ip_vs_genl_family, NLM_F_MULTI,
3227                           IPVS_CMD_NEW_DEST);
3228         if (!hdr)
3229                 return -EMSGSIZE;
3230
3231         if (ip_vs_genl_fill_dest(skb, dest) < 0)
3232                 goto nla_put_failure;
3233
3234         genlmsg_end(skb, hdr);
3235         return 0;
3236
3237 nla_put_failure:
3238         genlmsg_cancel(skb, hdr);
3239         return -EMSGSIZE;
3240 }
3241
3242 static int ip_vs_genl_dump_dests(struct sk_buff *skb,
3243                                  struct netlink_callback *cb)
3244 {
3245         int idx = 0;
3246         int start = cb->args[0];
3247         struct ip_vs_service *svc;
3248         struct ip_vs_dest *dest;
3249         struct nlattr *attrs[IPVS_CMD_ATTR_MAX + 1];
3250         struct net *net = sock_net(skb->sk);
3251         struct netns_ipvs *ipvs = net_ipvs(net);
3252
3253         mutex_lock(&__ip_vs_mutex);
3254
3255         /* Try to find the service for which to dump destinations */
3256         if (nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, IPVS_CMD_ATTR_MAX,
3257                         ip_vs_cmd_policy, NULL))
3258                 goto out_err;
3259
3260
3261         svc = ip_vs_genl_find_service(ipvs, attrs[IPVS_CMD_ATTR_SERVICE]);
3262         if (IS_ERR_OR_NULL(svc))
3263                 goto out_err;
3264
3265         /* Dump the destinations */
3266         list_for_each_entry(dest, &svc->destinations, n_list) {
3267                 if (++idx <= start)
3268                         continue;
3269                 if (ip_vs_genl_dump_dest(skb, dest, cb) < 0) {
3270                         idx--;
3271                         goto nla_put_failure;
3272                 }
3273         }
3274
3275 nla_put_failure:
3276         cb->args[0] = idx;
3277
3278 out_err:
3279         mutex_unlock(&__ip_vs_mutex);
3280
3281         return skb->len;
3282 }
3283
3284 static int ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern *udest,
3285                                  struct nlattr *nla, int full_entry)
3286 {
3287         struct nlattr *attrs[IPVS_DEST_ATTR_MAX + 1];
3288         struct nlattr *nla_addr, *nla_port;
3289         struct nlattr *nla_addr_family;
3290
3291         /* Parse mandatory identifying destination fields first */
3292         if (nla == NULL ||
3293             nla_parse_nested(attrs, IPVS_DEST_ATTR_MAX, nla,
3294                              ip_vs_dest_policy, NULL))
3295                 return -EINVAL;
3296
3297         nla_addr        = attrs[IPVS_DEST_ATTR_ADDR];
3298         nla_port        = attrs[IPVS_DEST_ATTR_PORT];
3299         nla_addr_family = attrs[IPVS_DEST_ATTR_ADDR_FAMILY];
3300
3301         if (!(nla_addr && nla_port))
3302                 return -EINVAL;
3303
3304         memset(udest, 0, sizeof(*udest));
3305
3306         nla_memcpy(&udest->addr, nla_addr, sizeof(udest->addr));
3307         udest->port = nla_get_be16(nla_port);
3308
3309         if (nla_addr_family)
3310                 udest->af = nla_get_u16(nla_addr_family);
3311         else
3312                 udest->af = 0;
3313
3314         /* If a full entry was requested, check for the additional fields */
3315         if (full_entry) {
3316                 struct nlattr *nla_fwd, *nla_weight, *nla_u_thresh,
3317                               *nla_l_thresh;
3318
3319                 nla_fwd         = attrs[IPVS_DEST_ATTR_FWD_METHOD];
3320                 nla_weight      = attrs[IPVS_DEST_ATTR_WEIGHT];
3321                 nla_u_thresh    = attrs[IPVS_DEST_ATTR_U_THRESH];
3322                 nla_l_thresh    = attrs[IPVS_DEST_ATTR_L_THRESH];
3323
3324                 if (!(nla_fwd && nla_weight && nla_u_thresh && nla_l_thresh))
3325                         return -EINVAL;
3326
3327                 udest->conn_flags = nla_get_u32(nla_fwd)
3328                                     & IP_VS_CONN_F_FWD_MASK;
3329                 udest->weight = nla_get_u32(nla_weight);
3330                 udest->u_threshold = nla_get_u32(nla_u_thresh);
3331                 udest->l_threshold = nla_get_u32(nla_l_thresh);
3332         }
3333
3334         return 0;
3335 }
3336
3337 static int ip_vs_genl_fill_daemon(struct sk_buff *skb, __u32 state,
3338                                   struct ipvs_sync_daemon_cfg *c)
3339 {
3340         struct nlattr *nl_daemon;
3341
3342         nl_daemon = nla_nest_start(skb, IPVS_CMD_ATTR_DAEMON);
3343         if (!nl_daemon)
3344                 return -EMSGSIZE;
3345
3346         if (nla_put_u32(skb, IPVS_DAEMON_ATTR_STATE, state) ||
3347             nla_put_string(skb, IPVS_DAEMON_ATTR_MCAST_IFN, c->mcast_ifn) ||
3348             nla_put_u32(skb, IPVS_DAEMON_ATTR_SYNC_ID, c->syncid) ||
3349             nla_put_u16(skb, IPVS_DAEMON_ATTR_SYNC_MAXLEN, c->sync_maxlen) ||
3350             nla_put_u16(skb, IPVS_DAEMON_ATTR_MCAST_PORT, c->mcast_port) ||
3351             nla_put_u8(skb, IPVS_DAEMON_ATTR_MCAST_TTL, c->mcast_ttl))
3352                 goto nla_put_failure;
3353 #ifdef CONFIG_IP_VS_IPV6
3354         if (c->mcast_af == AF_INET6) {
3355                 if (nla_put_in6_addr(skb, IPVS_DAEMON_ATTR_MCAST_GROUP6,
3356                                      &c->mcast_group.in6))
3357                         goto nla_put_failure;
3358         } else
3359 #endif
3360                 if (c->mcast_af == AF_INET &&
3361                     nla_put_in_addr(skb, IPVS_DAEMON_ATTR_MCAST_GROUP,
3362                                     c->mcast_group.ip))
3363                         goto nla_put_failure;
3364         nla_nest_end(skb, nl_daemon);
3365
3366         return 0;
3367
3368 nla_put_failure:
3369         nla_nest_cancel(skb, nl_daemon);
3370         return -EMSGSIZE;
3371 }
3372
3373 static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __u32 state,
3374                                   struct ipvs_sync_daemon_cfg *c,
3375                                   struct netlink_callback *cb)
3376 {
3377         void *hdr;
3378         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3379                           &ip_vs_genl_family, NLM_F_MULTI,
3380                           IPVS_CMD_NEW_DAEMON);
3381         if (!hdr)
3382                 return -EMSGSIZE;
3383
3384         if (ip_vs_genl_fill_daemon(skb, state, c))
3385                 goto nla_put_failure;
3386
3387         genlmsg_end(skb, hdr);
3388         return 0;
3389
3390 nla_put_failure:
3391         genlmsg_cancel(skb, hdr);
3392         return -EMSGSIZE;
3393 }
3394
3395 static int ip_vs_genl_dump_daemons(struct sk_buff *skb,
3396                                    struct netlink_callback *cb)
3397 {
3398         struct net *net = sock_net(skb->sk);
3399         struct netns_ipvs *ipvs = net_ipvs(net);
3400
3401         mutex_lock(&ipvs->sync_mutex);
3402         if ((ipvs->sync_state & IP_VS_STATE_MASTER) && !cb->args[0]) {
3403                 if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_MASTER,
3404                                            &ipvs->mcfg, cb) < 0)
3405                         goto nla_put_failure;
3406
3407                 cb->args[0] = 1;
3408         }
3409
3410         if ((ipvs->sync_state & IP_VS_STATE_BACKUP) && !cb->args[1]) {
3411                 if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_BACKUP,
3412                                            &ipvs->bcfg, cb) < 0)
3413                         goto nla_put_failure;
3414
3415                 cb->args[1] = 1;
3416         }
3417
3418 nla_put_failure:
3419         mutex_unlock(&ipvs->sync_mutex);
3420
3421         return skb->len;
3422 }
3423
3424 static int ip_vs_genl_new_daemon(struct netns_ipvs *ipvs, struct nlattr **attrs)
3425 {
3426         struct ipvs_sync_daemon_cfg c;
3427         struct nlattr *a;
3428         int ret;
3429
3430         memset(&c, 0, sizeof(c));
3431         if (!(attrs[IPVS_DAEMON_ATTR_STATE] &&
3432               attrs[IPVS_DAEMON_ATTR_MCAST_IFN] &&
3433               attrs[IPVS_DAEMON_ATTR_SYNC_ID]))
3434                 return -EINVAL;
3435         strlcpy(c.mcast_ifn, nla_data(attrs[IPVS_DAEMON_ATTR_MCAST_IFN]),
3436                 sizeof(c.mcast_ifn));
3437         c.syncid = nla_get_u32(attrs[IPVS_DAEMON_ATTR_SYNC_ID]);
3438
3439         a = attrs[IPVS_DAEMON_ATTR_SYNC_MAXLEN];
3440         if (a)
3441                 c.sync_maxlen = nla_get_u16(a);
3442
3443         a = attrs[IPVS_DAEMON_ATTR_MCAST_GROUP];
3444         if (a) {
3445                 c.mcast_af = AF_INET;
3446                 c.mcast_group.ip = nla_get_in_addr(a);
3447                 if (!ipv4_is_multicast(c.mcast_group.ip))
3448                         return -EINVAL;
3449         } else {
3450                 a = attrs[IPVS_DAEMON_ATTR_MCAST_GROUP6];
3451                 if (a) {
3452 #ifdef CONFIG_IP_VS_IPV6
3453                         int addr_type;
3454
3455                         c.mcast_af = AF_INET6;
3456                         c.mcast_group.in6 = nla_get_in6_addr(a);
3457                         addr_type = ipv6_addr_type(&c.mcast_group.in6);
3458                         if (!(addr_type & IPV6_ADDR_MULTICAST))
3459                                 return -EINVAL;
3460 #else
3461                         return -EAFNOSUPPORT;
3462 #endif
3463                 }
3464         }
3465
3466         a = attrs[IPVS_DAEMON_ATTR_MCAST_PORT];
3467         if (a)
3468                 c.mcast_port = nla_get_u16(a);
3469
3470         a = attrs[IPVS_DAEMON_ATTR_MCAST_TTL];
3471         if (a)
3472                 c.mcast_ttl = nla_get_u8(a);
3473
3474         /* The synchronization protocol is incompatible with mixed family
3475          * services
3476          */
3477         if (ipvs->mixed_address_family_dests > 0)
3478                 return -EINVAL;
3479
3480         ret = start_sync_thread(ipvs, &c,
3481                                 nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3482         return ret;
3483 }
3484
3485 static int ip_vs_genl_del_daemon(struct netns_ipvs *ipvs, struct nlattr **attrs)
3486 {
3487         int ret;
3488
3489         if (!attrs[IPVS_DAEMON_ATTR_STATE])
3490                 return -EINVAL;
3491
3492         ret = stop_sync_thread(ipvs,
3493                                nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3494         return ret;
3495 }
3496
3497 static int ip_vs_genl_set_config(struct netns_ipvs *ipvs, struct nlattr **attrs)
3498 {
3499         struct ip_vs_timeout_user t;
3500
3501         __ip_vs_get_timeouts(ipvs, &t);
3502
3503         if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP])
3504                 t.tcp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]);
3505
3506         if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN])
3507                 t.tcp_fin_timeout =
3508                         nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]);
3509
3510         if (attrs[IPVS_CMD_ATTR_TIMEOUT_UDP])
3511                 t.udp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]);
3512
3513         return ip_vs_set_timeout(ipvs, &t);
3514 }
3515
3516 static int ip_vs_genl_set_daemon(struct sk_buff *skb, struct genl_info *info)
3517 {
3518         int ret = -EINVAL, cmd;
3519         struct net *net = sock_net(skb->sk);
3520         struct netns_ipvs *ipvs = net_ipvs(net);
3521
3522         cmd = info->genlhdr->cmd;
3523
3524         if (cmd == IPVS_CMD_NEW_DAEMON || cmd == IPVS_CMD_DEL_DAEMON) {
3525                 struct nlattr *daemon_attrs[IPVS_DAEMON_ATTR_MAX + 1];
3526
3527                 if (!info->attrs[IPVS_CMD_ATTR_DAEMON] ||
3528                     nla_parse_nested(daemon_attrs, IPVS_DAEMON_ATTR_MAX,
3529                                      info->attrs[IPVS_CMD_ATTR_DAEMON],
3530                                      ip_vs_daemon_policy, info->extack))
3531                         goto out;
3532
3533                 if (cmd == IPVS_CMD_NEW_DAEMON)
3534                         ret = ip_vs_genl_new_daemon(ipvs, daemon_attrs);
3535                 else
3536                         ret = ip_vs_genl_del_daemon(ipvs, daemon_attrs);
3537         }
3538
3539 out:
3540         return ret;
3541 }
3542
3543 static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)
3544 {
3545         struct ip_vs_service *svc = NULL;
3546         struct ip_vs_service_user_kern usvc;
3547         struct ip_vs_dest_user_kern udest;
3548         int ret = 0, cmd;
3549         int need_full_svc = 0, need_full_dest = 0;
3550         struct net *net = sock_net(skb->sk);
3551         struct netns_ipvs *ipvs = net_ipvs(net);
3552
3553         cmd = info->genlhdr->cmd;
3554
3555         mutex_lock(&__ip_vs_mutex);
3556
3557         if (cmd == IPVS_CMD_FLUSH) {
3558                 ret = ip_vs_flush(ipvs, false);
3559                 goto out;
3560         } else if (cmd == IPVS_CMD_SET_CONFIG) {
3561                 ret = ip_vs_genl_set_config(ipvs, info->attrs);
3562                 goto out;
3563         } else if (cmd == IPVS_CMD_ZERO &&
3564                    !info->attrs[IPVS_CMD_ATTR_SERVICE]) {
3565                 ret = ip_vs_zero_all(ipvs);
3566                 goto out;
3567         }
3568
3569         /* All following commands require a service argument, so check if we
3570          * received a valid one. We need a full service specification when
3571          * adding / editing a service. Only identifying members otherwise. */
3572         if (cmd == IPVS_CMD_NEW_SERVICE || cmd == IPVS_CMD_SET_SERVICE)
3573                 need_full_svc = 1;
3574
3575         ret = ip_vs_genl_parse_service(ipvs, &usvc,
3576                                        info->attrs[IPVS_CMD_ATTR_SERVICE],
3577                                        need_full_svc, &svc);
3578         if (ret)
3579                 goto out;
3580
3581         /* Unless we're adding a new service, the service must already exist */
3582         if ((cmd != IPVS_CMD_NEW_SERVICE) && (svc == NULL)) {
3583                 ret = -ESRCH;
3584                 goto out;
3585         }
3586
3587         /* Destination commands require a valid destination argument. For
3588          * adding / editing a destination, we need a full destination
3589          * specification. */
3590         if (cmd == IPVS_CMD_NEW_DEST || cmd == IPVS_CMD_SET_DEST ||
3591             cmd == IPVS_CMD_DEL_DEST) {
3592                 if (cmd != IPVS_CMD_DEL_DEST)
3593                         need_full_dest = 1;
3594
3595                 ret = ip_vs_genl_parse_dest(&udest,
3596                                             info->attrs[IPVS_CMD_ATTR_DEST],
3597                                             need_full_dest);
3598                 if (ret)
3599                         goto out;
3600
3601                 /* Old protocols did not allow the user to specify address
3602                  * family, so we set it to zero instead.  We also didn't
3603                  * allow heterogeneous pools in the old code, so it's safe
3604                  * to assume that this will have the same address family as
3605                  * the service.
3606                  */
3607                 if (udest.af == 0)
3608                         udest.af = svc->af;
3609
3610                 if (!ip_vs_is_af_valid(udest.af)) {
3611                         ret = -EAFNOSUPPORT;
3612                         goto out;
3613                 }
3614
3615                 if (udest.af != svc->af && cmd != IPVS_CMD_DEL_DEST) {
3616                         /* The synchronization protocol is incompatible
3617                          * with mixed family services
3618                          */
3619                         if (ipvs->sync_state) {
3620                                 ret = -EINVAL;
3621                                 goto out;
3622                         }
3623
3624                         /* Which connection types do we support? */
3625                         switch (udest.conn_flags) {
3626                         case IP_VS_CONN_F_TUNNEL:
3627                                 /* We are able to forward this */
3628                                 break;
3629                         default:
3630                                 ret = -EINVAL;
3631                                 goto out;
3632                         }
3633                 }
3634         }
3635
3636         switch (cmd) {
3637         case IPVS_CMD_NEW_SERVICE:
3638                 if (svc == NULL)
3639                         ret = ip_vs_add_service(ipvs, &usvc, &svc);
3640                 else
3641                         ret = -EEXIST;
3642                 break;
3643         case IPVS_CMD_SET_SERVICE:
3644                 ret = ip_vs_edit_service(svc, &usvc);
3645                 break;
3646         case IPVS_CMD_DEL_SERVICE:
3647                 ret = ip_vs_del_service(svc);
3648                 /* do not use svc, it can be freed */
3649                 break;
3650         case IPVS_CMD_NEW_DEST:
3651                 ret = ip_vs_add_dest(svc, &udest);
3652                 break;
3653         case IPVS_CMD_SET_DEST:
3654                 ret = ip_vs_edit_dest(svc, &udest);
3655                 break;
3656         case IPVS_CMD_DEL_DEST:
3657                 ret = ip_vs_del_dest(svc, &udest);
3658                 break;
3659         case IPVS_CMD_ZERO:
3660                 ret = ip_vs_zero_service(svc);
3661                 break;
3662         default:
3663                 ret = -EINVAL;
3664         }
3665
3666 out:
3667         mutex_unlock(&__ip_vs_mutex);
3668
3669         return ret;
3670 }
3671
3672 static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)
3673 {
3674         struct sk_buff *msg;
3675         void *reply;
3676         int ret, cmd, reply_cmd;
3677         struct net *net = sock_net(skb->sk);
3678         struct netns_ipvs *ipvs = net_ipvs(net);
3679
3680         cmd = info->genlhdr->cmd;
3681
3682         if (cmd == IPVS_CMD_GET_SERVICE)
3683                 reply_cmd = IPVS_CMD_NEW_SERVICE;
3684         else if (cmd == IPVS_CMD_GET_INFO)
3685                 reply_cmd = IPVS_CMD_SET_INFO;
3686         else if (cmd == IPVS_CMD_GET_CONFIG)
3687                 reply_cmd = IPVS_CMD_SET_CONFIG;
3688         else {
3689                 pr_err("unknown Generic Netlink command\n");
3690                 return -EINVAL;
3691         }
3692
3693         msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
3694         if (!msg)
3695                 return -ENOMEM;
3696
3697         mutex_lock(&__ip_vs_mutex);
3698
3699         reply = genlmsg_put_reply(msg, info, &ip_vs_genl_family, 0, reply_cmd);
3700         if (reply == NULL)
3701                 goto nla_put_failure;
3702
3703         switch (cmd) {
3704         case IPVS_CMD_GET_SERVICE:
3705         {
3706                 struct ip_vs_service *svc;
3707
3708                 svc = ip_vs_genl_find_service(ipvs,
3709                                               info->attrs[IPVS_CMD_ATTR_SERVICE]);
3710                 if (IS_ERR(svc)) {
3711                         ret = PTR_ERR(svc);
3712                         goto out_err;
3713                 } else if (svc) {
3714                         ret = ip_vs_genl_fill_service(msg, svc);
3715                         if (ret)
3716                                 goto nla_put_failure;
3717                 } else {
3718                         ret = -ESRCH;
3719                         goto out_err;
3720                 }
3721
3722                 break;
3723         }
3724
3725         case IPVS_CMD_GET_CONFIG:
3726         {
3727                 struct ip_vs_timeout_user t;
3728
3729                 __ip_vs_get_timeouts(ipvs, &t);
3730 #ifdef CONFIG_IP_VS_PROTO_TCP
3731                 if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP,
3732                                 t.tcp_timeout) ||
3733                     nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP_FIN,
3734                                 t.tcp_fin_timeout))
3735                         goto nla_put_failure;
3736 #endif
3737 #ifdef CONFIG_IP_VS_PROTO_UDP
3738                 if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_UDP, t.udp_timeout))
3739                         goto nla_put_failure;
3740 #endif
3741
3742                 break;
3743         }
3744
3745         case IPVS_CMD_GET_INFO:
3746                 if (nla_put_u32(msg, IPVS_INFO_ATTR_VERSION,
3747                                 IP_VS_VERSION_CODE) ||
3748                     nla_put_u32(msg, IPVS_INFO_ATTR_CONN_TAB_SIZE,
3749                                 ip_vs_conn_tab_size))
3750                         goto nla_put_failure;
3751                 break;
3752         }
3753
3754         genlmsg_end(msg, reply);
3755         ret = genlmsg_reply(msg, info);
3756         goto out;
3757
3758 nla_put_failure:
3759         pr_err("not enough space in Netlink message\n");
3760         ret = -EMSGSIZE;
3761
3762 out_err:
3763         nlmsg_free(msg);
3764 out:
3765         mutex_unlock(&__ip_vs_mutex);
3766
3767         return ret;
3768 }
3769
3770
3771 static const struct genl_ops ip_vs_genl_ops[] = {
3772         {
3773                 .cmd    = IPVS_CMD_NEW_SERVICE,
3774                 .flags  = GENL_ADMIN_PERM,
3775                 .policy = ip_vs_cmd_policy,
3776                 .doit   = ip_vs_genl_set_cmd,
3777         },
3778         {
3779                 .cmd    = IPVS_CMD_SET_SERVICE,
3780                 .flags  = GENL_ADMIN_PERM,
3781                 .policy = ip_vs_cmd_policy,
3782                 .doit   = ip_vs_genl_set_cmd,
3783         },
3784         {
3785                 .cmd    = IPVS_CMD_DEL_SERVICE,
3786                 .flags  = GENL_ADMIN_PERM,
3787                 .policy = ip_vs_cmd_policy,
3788                 .doit   = ip_vs_genl_set_cmd,
3789         },
3790         {
3791                 .cmd    = IPVS_CMD_GET_SERVICE,
3792                 .flags  = GENL_ADMIN_PERM,
3793                 .doit   = ip_vs_genl_get_cmd,
3794                 .dumpit = ip_vs_genl_dump_services,
3795                 .policy = ip_vs_cmd_policy,
3796         },
3797         {
3798                 .cmd    = IPVS_CMD_NEW_DEST,
3799                 .flags  = GENL_ADMIN_PERM,
3800                 .policy = ip_vs_cmd_policy,
3801                 .doit   = ip_vs_genl_set_cmd,
3802         },
3803         {
3804                 .cmd    = IPVS_CMD_SET_DEST,
3805                 .flags  = GENL_ADMIN_PERM,
3806                 .policy = ip_vs_cmd_policy,
3807                 .doit   = ip_vs_genl_set_cmd,
3808         },
3809         {
3810                 .cmd    = IPVS_CMD_DEL_DEST,
3811                 .flags  = GENL_ADMIN_PERM,
3812                 .policy = ip_vs_cmd_policy,
3813                 .doit   = ip_vs_genl_set_cmd,
3814         },
3815         {
3816                 .cmd    = IPVS_CMD_GET_DEST,
3817                 .flags  = GENL_ADMIN_PERM,
3818                 .policy = ip_vs_cmd_policy,
3819                 .dumpit = ip_vs_genl_dump_dests,
3820         },
3821         {
3822                 .cmd    = IPVS_CMD_NEW_DAEMON,
3823                 .flags  = GENL_ADMIN_PERM,
3824                 .policy = ip_vs_cmd_policy,
3825                 .doit   = ip_vs_genl_set_daemon,
3826         },
3827         {
3828                 .cmd    = IPVS_CMD_DEL_DAEMON,
3829                 .flags  = GENL_ADMIN_PERM,
3830                 .policy = ip_vs_cmd_policy,
3831                 .doit   = ip_vs_genl_set_daemon,
3832         },
3833         {
3834                 .cmd    = IPVS_CMD_GET_DAEMON,
3835                 .flags  = GENL_ADMIN_PERM,
3836                 .dumpit = ip_vs_genl_dump_daemons,
3837         },
3838         {
3839                 .cmd    = IPVS_CMD_SET_CONFIG,
3840                 .flags  = GENL_ADMIN_PERM,
3841                 .policy = ip_vs_cmd_policy,
3842                 .doit   = ip_vs_genl_set_cmd,
3843         },
3844         {
3845                 .cmd    = IPVS_CMD_GET_CONFIG,
3846                 .flags  = GENL_ADMIN_PERM,
3847                 .doit   = ip_vs_genl_get_cmd,
3848         },
3849         {
3850                 .cmd    = IPVS_CMD_GET_INFO,
3851                 .flags  = GENL_ADMIN_PERM,
3852                 .doit   = ip_vs_genl_get_cmd,
3853         },
3854         {
3855                 .cmd    = IPVS_CMD_ZERO,
3856                 .flags  = GENL_ADMIN_PERM,
3857                 .policy = ip_vs_cmd_policy,
3858                 .doit   = ip_vs_genl_set_cmd,
3859         },
3860         {
3861                 .cmd    = IPVS_CMD_FLUSH,
3862                 .flags  = GENL_ADMIN_PERM,
3863                 .doit   = ip_vs_genl_set_cmd,
3864         },
3865 };
3866
3867 static struct genl_family ip_vs_genl_family __ro_after_init = {
3868         .hdrsize        = 0,
3869         .name           = IPVS_GENL_NAME,
3870         .version        = IPVS_GENL_VERSION,
3871         .maxattr        = IPVS_CMD_ATTR_MAX,
3872         .netnsok        = true,         /* Make ipvsadm to work on netns */
3873         .module         = THIS_MODULE,
3874         .ops            = ip_vs_genl_ops,
3875         .n_ops          = ARRAY_SIZE(ip_vs_genl_ops),
3876 };
3877
3878 static int __init ip_vs_genl_register(void)
3879 {
3880         return genl_register_family(&ip_vs_genl_family);
3881 }
3882
3883 static void ip_vs_genl_unregister(void)
3884 {
3885         genl_unregister_family(&ip_vs_genl_family);
3886 }
3887
3888 /* End of Generic Netlink interface definitions */
3889
3890 /*
3891  * per netns intit/exit func.
3892  */
3893 #ifdef CONFIG_SYSCTL
3894 static int __net_init ip_vs_control_net_init_sysctl(struct netns_ipvs *ipvs)
3895 {
3896         struct net *net = ipvs->net;
3897         int idx;
3898         struct ctl_table *tbl;
3899
3900         atomic_set(&ipvs->dropentry, 0);
3901         spin_lock_init(&ipvs->dropentry_lock);
3902         spin_lock_init(&ipvs->droppacket_lock);
3903         spin_lock_init(&ipvs->securetcp_lock);
3904
3905         if (!net_eq(net, &init_net)) {
3906                 tbl = kmemdup(vs_vars, sizeof(vs_vars), GFP_KERNEL);
3907                 if (tbl == NULL)
3908                         return -ENOMEM;
3909
3910                 /* Don't export sysctls to unprivileged users */
3911                 if (net->user_ns != &init_user_ns)
3912                         tbl[0].procname = NULL;
3913         } else
3914                 tbl = vs_vars;
3915         /* Initialize sysctl defaults */
3916         for (idx = 0; idx < ARRAY_SIZE(vs_vars); idx++) {
3917                 if (tbl[idx].proc_handler == proc_do_defense_mode)
3918                         tbl[idx].extra2 = ipvs;
3919         }
3920         idx = 0;
3921         ipvs->sysctl_amemthresh = 1024;
3922         tbl[idx++].data = &ipvs->sysctl_amemthresh;
3923         ipvs->sysctl_am_droprate = 10;
3924         tbl[idx++].data = &ipvs->sysctl_am_droprate;
3925         tbl[idx++].data = &ipvs->sysctl_drop_entry;
3926         tbl[idx++].data = &ipvs->sysctl_drop_packet;
3927 #ifdef CONFIG_IP_VS_NFCT
3928         tbl[idx++].data = &ipvs->sysctl_conntrack;
3929 #endif
3930         tbl[idx++].data = &ipvs->sysctl_secure_tcp;
3931         ipvs->sysctl_snat_reroute = 1;
3932         tbl[idx++].data = &ipvs->sysctl_snat_reroute;
3933         ipvs->sysctl_sync_ver = 1;
3934         tbl[idx++].data = &ipvs->sysctl_sync_ver;
3935         ipvs->sysctl_sync_ports = 1;
3936         tbl[idx++].data = &ipvs->sysctl_sync_ports;
3937         tbl[idx++].data = &ipvs->sysctl_sync_persist_mode;
3938         ipvs->sysctl_sync_qlen_max = nr_free_buffer_pages() / 32;
3939         tbl[idx++].data = &ipvs->sysctl_sync_qlen_max;
3940         ipvs->sysctl_sync_sock_size = 0;
3941         tbl[idx++].data = &ipvs->sysctl_sync_sock_size;
3942         tbl[idx++].data = &ipvs->sysctl_cache_bypass;
3943         tbl[idx++].data = &ipvs->sysctl_expire_nodest_conn;
3944         tbl[idx++].data = &ipvs->sysctl_sloppy_tcp;
3945         tbl[idx++].data = &ipvs->sysctl_sloppy_sctp;
3946         tbl[idx++].data = &ipvs->sysctl_expire_quiescent_template;
3947         ipvs->sysctl_sync_threshold[0] = DEFAULT_SYNC_THRESHOLD;
3948         ipvs->sysctl_sync_threshold[1] = DEFAULT_SYNC_PERIOD;
3949         tbl[idx].data = &ipvs->sysctl_sync_threshold;
3950         tbl[idx].extra2 = ipvs;
3951         tbl[idx++].maxlen = sizeof(ipvs->sysctl_sync_threshold);
3952         ipvs->sysctl_sync_refresh_period = DEFAULT_SYNC_REFRESH_PERIOD;
3953         tbl[idx++].data = &ipvs->sysctl_sync_refresh_period;
3954         ipvs->sysctl_sync_retries = clamp_t(int, DEFAULT_SYNC_RETRIES, 0, 3);
3955         tbl[idx++].data = &ipvs->sysctl_sync_retries;
3956         tbl[idx++].data = &ipvs->sysctl_nat_icmp_send;
3957         ipvs->sysctl_pmtu_disc = 1;
3958         tbl[idx++].data = &ipvs->sysctl_pmtu_disc;
3959         tbl[idx++].data = &ipvs->sysctl_backup_only;
3960         ipvs->sysctl_conn_reuse_mode = 1;
3961         tbl[idx++].data = &ipvs->sysctl_conn_reuse_mode;
3962         tbl[idx++].data = &ipvs->sysctl_schedule_icmp;
3963         tbl[idx++].data = &ipvs->sysctl_ignore_tunneled;
3964 #ifdef CONFIG_IP_VS_DEBUG
3965         /* Global sysctls must be ro in non-init netns */
3966         if (!net_eq(net, &init_net))
3967                 tbl[idx++].mode = 0444;
3968 #endif
3969
3970         ipvs->sysctl_hdr = register_net_sysctl(net, "net/ipv4/vs", tbl);
3971         if (ipvs->sysctl_hdr == NULL) {
3972                 if (!net_eq(net, &init_net))
3973                         kfree(tbl);
3974                 return -ENOMEM;
3975         }
3976         ip_vs_start_estimator(ipvs, &ipvs->tot_stats);
3977         ipvs->sysctl_tbl = tbl;
3978         /* Schedule defense work */
3979         INIT_DELAYED_WORK(&ipvs->defense_work, defense_work_handler);
3980         schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD);
3981
3982         return 0;
3983 }
3984
3985 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct netns_ipvs *ipvs)
3986 {
3987         struct net *net = ipvs->net;
3988
3989         cancel_delayed_work_sync(&ipvs->defense_work);
3990         cancel_work_sync(&ipvs->defense_work.work);
3991         unregister_net_sysctl_table(ipvs->sysctl_hdr);
3992         ip_vs_stop_estimator(ipvs, &ipvs->tot_stats);
3993
3994         if (!net_eq(net, &init_net))
3995                 kfree(ipvs->sysctl_tbl);
3996 }
3997
3998 #else
3999
4000 static int __net_init ip_vs_control_net_init_sysctl(struct netns_ipvs *ipvs) { return 0; }
4001 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct netns_ipvs *ipvs) { }
4002
4003 #endif
4004
4005 static struct notifier_block ip_vs_dst_notifier = {
4006         .notifier_call = ip_vs_dst_event,
4007 #ifdef CONFIG_IP_VS_IPV6
4008         .priority = ADDRCONF_NOTIFY_PRIORITY + 5,
4009 #endif
4010 };
4011
4012 int __net_init ip_vs_control_net_init(struct netns_ipvs *ipvs)
4013 {
4014         int i, idx;
4015
4016         /* Initialize rs_table */
4017         for (idx = 0; idx < IP_VS_RTAB_SIZE; idx++)
4018                 INIT_HLIST_HEAD(&ipvs->rs_table[idx]);
4019
4020         INIT_LIST_HEAD(&ipvs->dest_trash);
4021         spin_lock_init(&ipvs->dest_trash_lock);
4022         timer_setup(&ipvs->dest_trash_timer, ip_vs_dest_trash_expire, 0);
4023         atomic_set(&ipvs->ftpsvc_counter, 0);
4024         atomic_set(&ipvs->nullsvc_counter, 0);
4025         atomic_set(&ipvs->conn_out_counter, 0);
4026
4027         /* procfs stats */
4028         ipvs->tot_stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
4029         if (!ipvs->tot_stats.cpustats)
4030                 return -ENOMEM;
4031
4032         for_each_possible_cpu(i) {
4033                 struct ip_vs_cpu_stats *ipvs_tot_stats;
4034                 ipvs_tot_stats = per_cpu_ptr(ipvs->tot_stats.cpustats, i);
4035                 u64_stats_init(&ipvs_tot_stats->syncp);
4036         }
4037
4038         spin_lock_init(&ipvs->tot_stats.lock);
4039
4040         proc_create_net("ip_vs", 0, ipvs->net->proc_net, &ip_vs_info_seq_ops,
4041                         sizeof(struct ip_vs_iter));
4042         proc_create_net_single("ip_vs_stats", 0, ipvs->net->proc_net,
4043                         ip_vs_stats_show, NULL);
4044         proc_create_net_single("ip_vs_stats_percpu", 0, ipvs->net->proc_net,
4045                         ip_vs_stats_percpu_show, NULL);
4046
4047         if (ip_vs_control_net_init_sysctl(ipvs))
4048                 goto err;
4049
4050         return 0;
4051
4052 err:
4053         free_percpu(ipvs->tot_stats.cpustats);
4054         return -ENOMEM;
4055 }
4056
4057 void __net_exit ip_vs_control_net_cleanup(struct netns_ipvs *ipvs)
4058 {
4059         ip_vs_trash_cleanup(ipvs);
4060         ip_vs_control_net_cleanup_sysctl(ipvs);
4061         remove_proc_entry("ip_vs_stats_percpu", ipvs->net->proc_net);
4062         remove_proc_entry("ip_vs_stats", ipvs->net->proc_net);
4063         remove_proc_entry("ip_vs", ipvs->net->proc_net);
4064         free_percpu(ipvs->tot_stats.cpustats);
4065 }
4066
4067 int __init ip_vs_register_nl_ioctl(void)
4068 {
4069         int ret;
4070
4071         ret = nf_register_sockopt(&ip_vs_sockopts);
4072         if (ret) {
4073                 pr_err("cannot register sockopt.\n");
4074                 goto err_sock;
4075         }
4076
4077         ret = ip_vs_genl_register();
4078         if (ret) {
4079                 pr_err("cannot register Generic Netlink interface.\n");
4080                 goto err_genl;
4081         }
4082         return 0;
4083
4084 err_genl:
4085         nf_unregister_sockopt(&ip_vs_sockopts);
4086 err_sock:
4087         return ret;
4088 }
4089
4090 void ip_vs_unregister_nl_ioctl(void)
4091 {
4092         ip_vs_genl_unregister();
4093         nf_unregister_sockopt(&ip_vs_sockopts);
4094 }
4095
4096 int __init ip_vs_control_init(void)
4097 {
4098         int idx;
4099         int ret;
4100
4101         EnterFunction(2);
4102
4103         /* Initialize svc_table, ip_vs_svc_fwm_table */
4104         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
4105                 INIT_HLIST_HEAD(&ip_vs_svc_table[idx]);
4106                 INIT_HLIST_HEAD(&ip_vs_svc_fwm_table[idx]);
4107         }
4108
4109         smp_wmb();      /* Do we really need it now ? */
4110
4111         ret = register_netdevice_notifier(&ip_vs_dst_notifier);
4112         if (ret < 0)
4113                 return ret;
4114
4115         LeaveFunction(2);
4116         return 0;
4117 }
4118
4119
4120 void ip_vs_control_cleanup(void)
4121 {
4122         EnterFunction(2);
4123         unregister_netdevice_notifier(&ip_vs_dst_notifier);
4124         LeaveFunction(2);
4125 }