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