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