xref: /linux/net/core/net_namespace.c (revision f7308991bfeea3f6a4c6281c64fc1ba9dc6e56b3)
1 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
2 
3 #include <linux/workqueue.h>
4 #include <linux/rtnetlink.h>
5 #include <linux/cache.h>
6 #include <linux/slab.h>
7 #include <linux/list.h>
8 #include <linux/delay.h>
9 #include <linux/sched.h>
10 #include <linux/idr.h>
11 #include <linux/rculist.h>
12 #include <linux/nsproxy.h>
13 #include <linux/fs.h>
14 #include <linux/proc_ns.h>
15 #include <linux/file.h>
16 #include <linux/export.h>
17 #include <linux/user_namespace.h>
18 #include <linux/net_namespace.h>
19 #include <linux/sched/task.h>
20 
21 #include <net/sock.h>
22 #include <net/netlink.h>
23 #include <net/net_namespace.h>
24 #include <net/netns/generic.h>
25 
26 /*
27  *	Our network namespace constructor/destructor lists
28  */
29 
30 static LIST_HEAD(pernet_list);
31 static struct list_head *first_device = &pernet_list;
32 
33 LIST_HEAD(net_namespace_list);
34 EXPORT_SYMBOL_GPL(net_namespace_list);
35 
36 struct net init_net = {
37 	.count		= REFCOUNT_INIT(1),
38 	.dev_base_head	= LIST_HEAD_INIT(init_net.dev_base_head),
39 };
40 EXPORT_SYMBOL(init_net);
41 
42 static bool init_net_initialized;
43 static unsigned nr_sync_pernet_ops;
44 /*
45  * net_sem: protects: pernet_list, net_generic_ids, nr_sync_pernet_ops,
46  * init_net_initialized and first_device pointer.
47  */
48 DECLARE_RWSEM(net_sem);
49 
50 #define MIN_PERNET_OPS_ID	\
51 	((sizeof(struct net_generic) + sizeof(void *) - 1) / sizeof(void *))
52 
53 #define INITIAL_NET_GEN_PTRS	13 /* +1 for len +2 for rcu_head */
54 
55 static unsigned int max_gen_ptrs = INITIAL_NET_GEN_PTRS;
56 
57 static struct net_generic *net_alloc_generic(void)
58 {
59 	struct net_generic *ng;
60 	unsigned int generic_size = offsetof(struct net_generic, ptr[max_gen_ptrs]);
61 
62 	ng = kzalloc(generic_size, GFP_KERNEL);
63 	if (ng)
64 		ng->s.len = max_gen_ptrs;
65 
66 	return ng;
67 }
68 
69 static int net_assign_generic(struct net *net, unsigned int id, void *data)
70 {
71 	struct net_generic *ng, *old_ng;
72 
73 	BUG_ON(id < MIN_PERNET_OPS_ID);
74 
75 	old_ng = rcu_dereference_protected(net->gen,
76 					   lockdep_is_held(&net_sem));
77 	if (old_ng->s.len > id) {
78 		old_ng->ptr[id] = data;
79 		return 0;
80 	}
81 
82 	ng = net_alloc_generic();
83 	if (ng == NULL)
84 		return -ENOMEM;
85 
86 	/*
87 	 * Some synchronisation notes:
88 	 *
89 	 * The net_generic explores the net->gen array inside rcu
90 	 * read section. Besides once set the net->gen->ptr[x]
91 	 * pointer never changes (see rules in netns/generic.h).
92 	 *
93 	 * That said, we simply duplicate this array and schedule
94 	 * the old copy for kfree after a grace period.
95 	 */
96 
97 	memcpy(&ng->ptr[MIN_PERNET_OPS_ID], &old_ng->ptr[MIN_PERNET_OPS_ID],
98 	       (old_ng->s.len - MIN_PERNET_OPS_ID) * sizeof(void *));
99 	ng->ptr[id] = data;
100 
101 	rcu_assign_pointer(net->gen, ng);
102 	kfree_rcu(old_ng, s.rcu);
103 	return 0;
104 }
105 
106 static int ops_init(const struct pernet_operations *ops, struct net *net)
107 {
108 	int err = -ENOMEM;
109 	void *data = NULL;
110 
111 	if (ops->id && ops->size) {
112 		data = kzalloc(ops->size, GFP_KERNEL);
113 		if (!data)
114 			goto out;
115 
116 		err = net_assign_generic(net, *ops->id, data);
117 		if (err)
118 			goto cleanup;
119 	}
120 	err = 0;
121 	if (ops->init)
122 		err = ops->init(net);
123 	if (!err)
124 		return 0;
125 
126 cleanup:
127 	kfree(data);
128 
129 out:
130 	return err;
131 }
132 
133 static void ops_free(const struct pernet_operations *ops, struct net *net)
134 {
135 	if (ops->id && ops->size) {
136 		kfree(net_generic(net, *ops->id));
137 	}
138 }
139 
140 static void ops_exit_list(const struct pernet_operations *ops,
141 			  struct list_head *net_exit_list)
142 {
143 	struct net *net;
144 	if (ops->exit) {
145 		list_for_each_entry(net, net_exit_list, exit_list)
146 			ops->exit(net);
147 	}
148 	if (ops->exit_batch)
149 		ops->exit_batch(net_exit_list);
150 }
151 
152 static void ops_free_list(const struct pernet_operations *ops,
153 			  struct list_head *net_exit_list)
154 {
155 	struct net *net;
156 	if (ops->size && ops->id) {
157 		list_for_each_entry(net, net_exit_list, exit_list)
158 			ops_free(ops, net);
159 	}
160 }
161 
162 /* should be called with nsid_lock held */
163 static int alloc_netid(struct net *net, struct net *peer, int reqid)
164 {
165 	int min = 0, max = 0;
166 
167 	if (reqid >= 0) {
168 		min = reqid;
169 		max = reqid + 1;
170 	}
171 
172 	return idr_alloc(&net->netns_ids, peer, min, max, GFP_ATOMIC);
173 }
174 
175 /* This function is used by idr_for_each(). If net is equal to peer, the
176  * function returns the id so that idr_for_each() stops. Because we cannot
177  * returns the id 0 (idr_for_each() will not stop), we return the magic value
178  * NET_ID_ZERO (-1) for it.
179  */
180 #define NET_ID_ZERO -1
181 static int net_eq_idr(int id, void *net, void *peer)
182 {
183 	if (net_eq(net, peer))
184 		return id ? : NET_ID_ZERO;
185 	return 0;
186 }
187 
188 /* Should be called with nsid_lock held. If a new id is assigned, the bool alloc
189  * is set to true, thus the caller knows that the new id must be notified via
190  * rtnl.
191  */
192 static int __peernet2id_alloc(struct net *net, struct net *peer, bool *alloc)
193 {
194 	int id = idr_for_each(&net->netns_ids, net_eq_idr, peer);
195 	bool alloc_it = *alloc;
196 
197 	*alloc = false;
198 
199 	/* Magic value for id 0. */
200 	if (id == NET_ID_ZERO)
201 		return 0;
202 	if (id > 0)
203 		return id;
204 
205 	if (alloc_it) {
206 		id = alloc_netid(net, peer, -1);
207 		*alloc = true;
208 		return id >= 0 ? id : NETNSA_NSID_NOT_ASSIGNED;
209 	}
210 
211 	return NETNSA_NSID_NOT_ASSIGNED;
212 }
213 
214 /* should be called with nsid_lock held */
215 static int __peernet2id(struct net *net, struct net *peer)
216 {
217 	bool no = false;
218 
219 	return __peernet2id_alloc(net, peer, &no);
220 }
221 
222 static void rtnl_net_notifyid(struct net *net, int cmd, int id);
223 /* This function returns the id of a peer netns. If no id is assigned, one will
224  * be allocated and returned.
225  */
226 int peernet2id_alloc(struct net *net, struct net *peer)
227 {
228 	bool alloc = false, alive = false;
229 	int id;
230 
231 	if (refcount_read(&net->count) == 0)
232 		return NETNSA_NSID_NOT_ASSIGNED;
233 	spin_lock_bh(&net->nsid_lock);
234 	/*
235 	 * When peer is obtained from RCU lists, we may race with
236 	 * its cleanup. Check whether it's alive, and this guarantees
237 	 * we never hash a peer back to net->netns_ids, after it has
238 	 * just been idr_remove()'d from there in cleanup_net().
239 	 */
240 	if (maybe_get_net(peer))
241 		alive = alloc = true;
242 	id = __peernet2id_alloc(net, peer, &alloc);
243 	spin_unlock_bh(&net->nsid_lock);
244 	if (alloc && id >= 0)
245 		rtnl_net_notifyid(net, RTM_NEWNSID, id);
246 	if (alive)
247 		put_net(peer);
248 	return id;
249 }
250 EXPORT_SYMBOL_GPL(peernet2id_alloc);
251 
252 /* This function returns, if assigned, the id of a peer netns. */
253 int peernet2id(struct net *net, struct net *peer)
254 {
255 	int id;
256 
257 	spin_lock_bh(&net->nsid_lock);
258 	id = __peernet2id(net, peer);
259 	spin_unlock_bh(&net->nsid_lock);
260 	return id;
261 }
262 EXPORT_SYMBOL(peernet2id);
263 
264 /* This function returns true is the peer netns has an id assigned into the
265  * current netns.
266  */
267 bool peernet_has_id(struct net *net, struct net *peer)
268 {
269 	return peernet2id(net, peer) >= 0;
270 }
271 
272 struct net *get_net_ns_by_id(struct net *net, int id)
273 {
274 	struct net *peer;
275 
276 	if (id < 0)
277 		return NULL;
278 
279 	rcu_read_lock();
280 	peer = idr_find(&net->netns_ids, id);
281 	if (peer)
282 		peer = maybe_get_net(peer);
283 	rcu_read_unlock();
284 
285 	return peer;
286 }
287 
288 /*
289  * setup_net runs the initializers for the network namespace object.
290  */
291 static __net_init int setup_net(struct net *net, struct user_namespace *user_ns)
292 {
293 	/* Must be called with net_sem held */
294 	const struct pernet_operations *ops, *saved_ops;
295 	int error = 0;
296 	LIST_HEAD(net_exit_list);
297 
298 	refcount_set(&net->count, 1);
299 	refcount_set(&net->passive, 1);
300 	net->dev_base_seq = 1;
301 	net->user_ns = user_ns;
302 	idr_init(&net->netns_ids);
303 	spin_lock_init(&net->nsid_lock);
304 
305 	list_for_each_entry(ops, &pernet_list, list) {
306 		error = ops_init(ops, net);
307 		if (error < 0)
308 			goto out_undo;
309 	}
310 	rtnl_lock();
311 	list_add_tail_rcu(&net->list, &net_namespace_list);
312 	rtnl_unlock();
313 out:
314 	return error;
315 
316 out_undo:
317 	/* Walk through the list backwards calling the exit functions
318 	 * for the pernet modules whose init functions did not fail.
319 	 */
320 	list_add(&net->exit_list, &net_exit_list);
321 	saved_ops = ops;
322 	list_for_each_entry_continue_reverse(ops, &pernet_list, list)
323 		ops_exit_list(ops, &net_exit_list);
324 
325 	ops = saved_ops;
326 	list_for_each_entry_continue_reverse(ops, &pernet_list, list)
327 		ops_free_list(ops, &net_exit_list);
328 
329 	rcu_barrier();
330 	goto out;
331 }
332 
333 static int __net_init net_defaults_init_net(struct net *net)
334 {
335 	net->core.sysctl_somaxconn = SOMAXCONN;
336 	return 0;
337 }
338 
339 static struct pernet_operations net_defaults_ops = {
340 	.init = net_defaults_init_net,
341 	.async = true,
342 };
343 
344 static __init int net_defaults_init(void)
345 {
346 	if (register_pernet_subsys(&net_defaults_ops))
347 		panic("Cannot initialize net default settings");
348 
349 	return 0;
350 }
351 
352 core_initcall(net_defaults_init);
353 
354 #ifdef CONFIG_NET_NS
355 static struct ucounts *inc_net_namespaces(struct user_namespace *ns)
356 {
357 	return inc_ucount(ns, current_euid(), UCOUNT_NET_NAMESPACES);
358 }
359 
360 static void dec_net_namespaces(struct ucounts *ucounts)
361 {
362 	dec_ucount(ucounts, UCOUNT_NET_NAMESPACES);
363 }
364 
365 static struct kmem_cache *net_cachep;
366 static struct workqueue_struct *netns_wq;
367 
368 static struct net *net_alloc(void)
369 {
370 	struct net *net = NULL;
371 	struct net_generic *ng;
372 
373 	ng = net_alloc_generic();
374 	if (!ng)
375 		goto out;
376 
377 	net = kmem_cache_zalloc(net_cachep, GFP_KERNEL);
378 	if (!net)
379 		goto out_free;
380 
381 	rcu_assign_pointer(net->gen, ng);
382 out:
383 	return net;
384 
385 out_free:
386 	kfree(ng);
387 	goto out;
388 }
389 
390 static void net_free(struct net *net)
391 {
392 	kfree(rcu_access_pointer(net->gen));
393 	kmem_cache_free(net_cachep, net);
394 }
395 
396 void net_drop_ns(void *p)
397 {
398 	struct net *ns = p;
399 	if (ns && refcount_dec_and_test(&ns->passive))
400 		net_free(ns);
401 }
402 
403 struct net *copy_net_ns(unsigned long flags,
404 			struct user_namespace *user_ns, struct net *old_net)
405 {
406 	struct ucounts *ucounts;
407 	struct net *net;
408 	unsigned write;
409 	int rv;
410 
411 	if (!(flags & CLONE_NEWNET))
412 		return get_net(old_net);
413 
414 	ucounts = inc_net_namespaces(user_ns);
415 	if (!ucounts)
416 		return ERR_PTR(-ENOSPC);
417 
418 	net = net_alloc();
419 	if (!net) {
420 		rv = -ENOMEM;
421 		goto dec_ucounts;
422 	}
423 	refcount_set(&net->passive, 1);
424 	net->ucounts = ucounts;
425 	get_user_ns(user_ns);
426 again:
427 	write = READ_ONCE(nr_sync_pernet_ops);
428 	if (write)
429 		rv = down_write_killable(&net_sem);
430 	else
431 		rv = down_read_killable(&net_sem);
432 	if (rv < 0)
433 		goto put_userns;
434 
435 	if (!write && unlikely(READ_ONCE(nr_sync_pernet_ops))) {
436 		up_read(&net_sem);
437 		goto again;
438 	}
439 	rv = setup_net(net, user_ns);
440 
441 	if (write)
442 		up_write(&net_sem);
443 	else
444 		up_read(&net_sem);
445 
446 	if (rv < 0) {
447 put_userns:
448 		put_user_ns(user_ns);
449 		net_drop_ns(net);
450 dec_ucounts:
451 		dec_net_namespaces(ucounts);
452 		return ERR_PTR(rv);
453 	}
454 	return net;
455 }
456 
457 static void unhash_nsid(struct net *net, struct net *last)
458 {
459 	struct net *tmp;
460 	/* This function is only called from cleanup_net() work,
461 	 * and this work is the only process, that may delete
462 	 * a net from net_namespace_list. So, when the below
463 	 * is executing, the list may only grow. Thus, we do not
464 	 * use for_each_net_rcu() or rtnl_lock().
465 	 */
466 	for_each_net(tmp) {
467 		int id;
468 
469 		spin_lock_bh(&tmp->nsid_lock);
470 		id = __peernet2id(tmp, net);
471 		if (id >= 0)
472 			idr_remove(&tmp->netns_ids, id);
473 		spin_unlock_bh(&tmp->nsid_lock);
474 		if (id >= 0)
475 			rtnl_net_notifyid(tmp, RTM_DELNSID, id);
476 		if (tmp == last)
477 			break;
478 	}
479 	spin_lock_bh(&net->nsid_lock);
480 	idr_destroy(&net->netns_ids);
481 	spin_unlock_bh(&net->nsid_lock);
482 }
483 
484 static LLIST_HEAD(cleanup_list);
485 
486 static void cleanup_net(struct work_struct *work)
487 {
488 	const struct pernet_operations *ops;
489 	struct net *net, *tmp, *last;
490 	struct llist_node *net_kill_list;
491 	LIST_HEAD(net_exit_list);
492 	unsigned write;
493 
494 	/* Atomically snapshot the list of namespaces to cleanup */
495 	net_kill_list = llist_del_all(&cleanup_list);
496 again:
497 	write = READ_ONCE(nr_sync_pernet_ops);
498 	if (write)
499 		down_write(&net_sem);
500 	else
501 		down_read(&net_sem);
502 
503 	if (!write && unlikely(READ_ONCE(nr_sync_pernet_ops))) {
504 		up_read(&net_sem);
505 		goto again;
506 	}
507 
508 	/* Don't let anyone else find us. */
509 	rtnl_lock();
510 	llist_for_each_entry(net, net_kill_list, cleanup_list)
511 		list_del_rcu(&net->list);
512 	/* Cache last net. After we unlock rtnl, no one new net
513 	 * added to net_namespace_list can assign nsid pointer
514 	 * to a net from net_kill_list (see peernet2id_alloc()).
515 	 * So, we skip them in unhash_nsid().
516 	 *
517 	 * Note, that unhash_nsid() does not delete nsid links
518 	 * between net_kill_list's nets, as they've already
519 	 * deleted from net_namespace_list. But, this would be
520 	 * useless anyway, as netns_ids are destroyed there.
521 	 */
522 	last = list_last_entry(&net_namespace_list, struct net, list);
523 	rtnl_unlock();
524 
525 	llist_for_each_entry(net, net_kill_list, cleanup_list) {
526 		unhash_nsid(net, last);
527 		list_add_tail(&net->exit_list, &net_exit_list);
528 	}
529 
530 	/*
531 	 * Another CPU might be rcu-iterating the list, wait for it.
532 	 * This needs to be before calling the exit() notifiers, so
533 	 * the rcu_barrier() below isn't sufficient alone.
534 	 */
535 	synchronize_rcu();
536 
537 	/* Run all of the network namespace exit methods */
538 	list_for_each_entry_reverse(ops, &pernet_list, list)
539 		ops_exit_list(ops, &net_exit_list);
540 
541 	/* Free the net generic variables */
542 	list_for_each_entry_reverse(ops, &pernet_list, list)
543 		ops_free_list(ops, &net_exit_list);
544 
545 	if (write)
546 		up_write(&net_sem);
547 	else
548 		up_read(&net_sem);
549 
550 	/* Ensure there are no outstanding rcu callbacks using this
551 	 * network namespace.
552 	 */
553 	rcu_barrier();
554 
555 	/* Finally it is safe to free my network namespace structure */
556 	list_for_each_entry_safe(net, tmp, &net_exit_list, exit_list) {
557 		list_del_init(&net->exit_list);
558 		dec_net_namespaces(net->ucounts);
559 		put_user_ns(net->user_ns);
560 		net_drop_ns(net);
561 	}
562 }
563 
564 /**
565  * net_ns_barrier - wait until concurrent net_cleanup_work is done
566  *
567  * cleanup_net runs from work queue and will first remove namespaces
568  * from the global list, then run net exit functions.
569  *
570  * Call this in module exit path to make sure that all netns
571  * ->exit ops have been invoked before the function is removed.
572  */
573 void net_ns_barrier(void)
574 {
575 	down_write(&net_sem);
576 	up_write(&net_sem);
577 }
578 EXPORT_SYMBOL(net_ns_barrier);
579 
580 static DECLARE_WORK(net_cleanup_work, cleanup_net);
581 
582 void __put_net(struct net *net)
583 {
584 	/* Cleanup the network namespace in process context */
585 	if (llist_add(&net->cleanup_list, &cleanup_list))
586 		queue_work(netns_wq, &net_cleanup_work);
587 }
588 EXPORT_SYMBOL_GPL(__put_net);
589 
590 struct net *get_net_ns_by_fd(int fd)
591 {
592 	struct file *file;
593 	struct ns_common *ns;
594 	struct net *net;
595 
596 	file = proc_ns_fget(fd);
597 	if (IS_ERR(file))
598 		return ERR_CAST(file);
599 
600 	ns = get_proc_ns(file_inode(file));
601 	if (ns->ops == &netns_operations)
602 		net = get_net(container_of(ns, struct net, ns));
603 	else
604 		net = ERR_PTR(-EINVAL);
605 
606 	fput(file);
607 	return net;
608 }
609 
610 #else
611 struct net *get_net_ns_by_fd(int fd)
612 {
613 	return ERR_PTR(-EINVAL);
614 }
615 #endif
616 EXPORT_SYMBOL_GPL(get_net_ns_by_fd);
617 
618 struct net *get_net_ns_by_pid(pid_t pid)
619 {
620 	struct task_struct *tsk;
621 	struct net *net;
622 
623 	/* Lookup the network namespace */
624 	net = ERR_PTR(-ESRCH);
625 	rcu_read_lock();
626 	tsk = find_task_by_vpid(pid);
627 	if (tsk) {
628 		struct nsproxy *nsproxy;
629 		task_lock(tsk);
630 		nsproxy = tsk->nsproxy;
631 		if (nsproxy)
632 			net = get_net(nsproxy->net_ns);
633 		task_unlock(tsk);
634 	}
635 	rcu_read_unlock();
636 	return net;
637 }
638 EXPORT_SYMBOL_GPL(get_net_ns_by_pid);
639 
640 static __net_init int net_ns_net_init(struct net *net)
641 {
642 #ifdef CONFIG_NET_NS
643 	net->ns.ops = &netns_operations;
644 #endif
645 	return ns_alloc_inum(&net->ns);
646 }
647 
648 static __net_exit void net_ns_net_exit(struct net *net)
649 {
650 	ns_free_inum(&net->ns);
651 }
652 
653 static struct pernet_operations __net_initdata net_ns_ops = {
654 	.init = net_ns_net_init,
655 	.exit = net_ns_net_exit,
656 	.async = true,
657 };
658 
659 static const struct nla_policy rtnl_net_policy[NETNSA_MAX + 1] = {
660 	[NETNSA_NONE]		= { .type = NLA_UNSPEC },
661 	[NETNSA_NSID]		= { .type = NLA_S32 },
662 	[NETNSA_PID]		= { .type = NLA_U32 },
663 	[NETNSA_FD]		= { .type = NLA_U32 },
664 };
665 
666 static int rtnl_net_newid(struct sk_buff *skb, struct nlmsghdr *nlh,
667 			  struct netlink_ext_ack *extack)
668 {
669 	struct net *net = sock_net(skb->sk);
670 	struct nlattr *tb[NETNSA_MAX + 1];
671 	struct nlattr *nla;
672 	struct net *peer;
673 	int nsid, err;
674 
675 	err = nlmsg_parse(nlh, sizeof(struct rtgenmsg), tb, NETNSA_MAX,
676 			  rtnl_net_policy, extack);
677 	if (err < 0)
678 		return err;
679 	if (!tb[NETNSA_NSID]) {
680 		NL_SET_ERR_MSG(extack, "nsid is missing");
681 		return -EINVAL;
682 	}
683 	nsid = nla_get_s32(tb[NETNSA_NSID]);
684 
685 	if (tb[NETNSA_PID]) {
686 		peer = get_net_ns_by_pid(nla_get_u32(tb[NETNSA_PID]));
687 		nla = tb[NETNSA_PID];
688 	} else if (tb[NETNSA_FD]) {
689 		peer = get_net_ns_by_fd(nla_get_u32(tb[NETNSA_FD]));
690 		nla = tb[NETNSA_FD];
691 	} else {
692 		NL_SET_ERR_MSG(extack, "Peer netns reference is missing");
693 		return -EINVAL;
694 	}
695 	if (IS_ERR(peer)) {
696 		NL_SET_BAD_ATTR(extack, nla);
697 		NL_SET_ERR_MSG(extack, "Peer netns reference is invalid");
698 		return PTR_ERR(peer);
699 	}
700 
701 	spin_lock_bh(&net->nsid_lock);
702 	if (__peernet2id(net, peer) >= 0) {
703 		spin_unlock_bh(&net->nsid_lock);
704 		err = -EEXIST;
705 		NL_SET_BAD_ATTR(extack, nla);
706 		NL_SET_ERR_MSG(extack,
707 			       "Peer netns already has a nsid assigned");
708 		goto out;
709 	}
710 
711 	err = alloc_netid(net, peer, nsid);
712 	spin_unlock_bh(&net->nsid_lock);
713 	if (err >= 0) {
714 		rtnl_net_notifyid(net, RTM_NEWNSID, err);
715 		err = 0;
716 	} else if (err == -ENOSPC && nsid >= 0) {
717 		err = -EEXIST;
718 		NL_SET_BAD_ATTR(extack, tb[NETNSA_NSID]);
719 		NL_SET_ERR_MSG(extack, "The specified nsid is already used");
720 	}
721 out:
722 	put_net(peer);
723 	return err;
724 }
725 
726 static int rtnl_net_get_size(void)
727 {
728 	return NLMSG_ALIGN(sizeof(struct rtgenmsg))
729 	       + nla_total_size(sizeof(s32)) /* NETNSA_NSID */
730 	       ;
731 }
732 
733 static int rtnl_net_fill(struct sk_buff *skb, u32 portid, u32 seq, int flags,
734 			 int cmd, struct net *net, int nsid)
735 {
736 	struct nlmsghdr *nlh;
737 	struct rtgenmsg *rth;
738 
739 	nlh = nlmsg_put(skb, portid, seq, cmd, sizeof(*rth), flags);
740 	if (!nlh)
741 		return -EMSGSIZE;
742 
743 	rth = nlmsg_data(nlh);
744 	rth->rtgen_family = AF_UNSPEC;
745 
746 	if (nla_put_s32(skb, NETNSA_NSID, nsid))
747 		goto nla_put_failure;
748 
749 	nlmsg_end(skb, nlh);
750 	return 0;
751 
752 nla_put_failure:
753 	nlmsg_cancel(skb, nlh);
754 	return -EMSGSIZE;
755 }
756 
757 static int rtnl_net_getid(struct sk_buff *skb, struct nlmsghdr *nlh,
758 			  struct netlink_ext_ack *extack)
759 {
760 	struct net *net = sock_net(skb->sk);
761 	struct nlattr *tb[NETNSA_MAX + 1];
762 	struct nlattr *nla;
763 	struct sk_buff *msg;
764 	struct net *peer;
765 	int err, id;
766 
767 	err = nlmsg_parse(nlh, sizeof(struct rtgenmsg), tb, NETNSA_MAX,
768 			  rtnl_net_policy, extack);
769 	if (err < 0)
770 		return err;
771 	if (tb[NETNSA_PID]) {
772 		peer = get_net_ns_by_pid(nla_get_u32(tb[NETNSA_PID]));
773 		nla = tb[NETNSA_PID];
774 	} else if (tb[NETNSA_FD]) {
775 		peer = get_net_ns_by_fd(nla_get_u32(tb[NETNSA_FD]));
776 		nla = tb[NETNSA_FD];
777 	} else {
778 		NL_SET_ERR_MSG(extack, "Peer netns reference is missing");
779 		return -EINVAL;
780 	}
781 
782 	if (IS_ERR(peer)) {
783 		NL_SET_BAD_ATTR(extack, nla);
784 		NL_SET_ERR_MSG(extack, "Peer netns reference is invalid");
785 		return PTR_ERR(peer);
786 	}
787 
788 	msg = nlmsg_new(rtnl_net_get_size(), GFP_KERNEL);
789 	if (!msg) {
790 		err = -ENOMEM;
791 		goto out;
792 	}
793 
794 	id = peernet2id(net, peer);
795 	err = rtnl_net_fill(msg, NETLINK_CB(skb).portid, nlh->nlmsg_seq, 0,
796 			    RTM_NEWNSID, net, id);
797 	if (err < 0)
798 		goto err_out;
799 
800 	err = rtnl_unicast(msg, net, NETLINK_CB(skb).portid);
801 	goto out;
802 
803 err_out:
804 	nlmsg_free(msg);
805 out:
806 	put_net(peer);
807 	return err;
808 }
809 
810 struct rtnl_net_dump_cb {
811 	struct net *net;
812 	struct sk_buff *skb;
813 	struct netlink_callback *cb;
814 	int idx;
815 	int s_idx;
816 };
817 
818 static int rtnl_net_dumpid_one(int id, void *peer, void *data)
819 {
820 	struct rtnl_net_dump_cb *net_cb = (struct rtnl_net_dump_cb *)data;
821 	int ret;
822 
823 	if (net_cb->idx < net_cb->s_idx)
824 		goto cont;
825 
826 	ret = rtnl_net_fill(net_cb->skb, NETLINK_CB(net_cb->cb->skb).portid,
827 			    net_cb->cb->nlh->nlmsg_seq, NLM_F_MULTI,
828 			    RTM_NEWNSID, net_cb->net, id);
829 	if (ret < 0)
830 		return ret;
831 
832 cont:
833 	net_cb->idx++;
834 	return 0;
835 }
836 
837 static int rtnl_net_dumpid(struct sk_buff *skb, struct netlink_callback *cb)
838 {
839 	struct net *net = sock_net(skb->sk);
840 	struct rtnl_net_dump_cb net_cb = {
841 		.net = net,
842 		.skb = skb,
843 		.cb = cb,
844 		.idx = 0,
845 		.s_idx = cb->args[0],
846 	};
847 
848 	spin_lock_bh(&net->nsid_lock);
849 	idr_for_each(&net->netns_ids, rtnl_net_dumpid_one, &net_cb);
850 	spin_unlock_bh(&net->nsid_lock);
851 
852 	cb->args[0] = net_cb.idx;
853 	return skb->len;
854 }
855 
856 static void rtnl_net_notifyid(struct net *net, int cmd, int id)
857 {
858 	struct sk_buff *msg;
859 	int err = -ENOMEM;
860 
861 	msg = nlmsg_new(rtnl_net_get_size(), GFP_KERNEL);
862 	if (!msg)
863 		goto out;
864 
865 	err = rtnl_net_fill(msg, 0, 0, 0, cmd, net, id);
866 	if (err < 0)
867 		goto err_out;
868 
869 	rtnl_notify(msg, net, 0, RTNLGRP_NSID, NULL, 0);
870 	return;
871 
872 err_out:
873 	nlmsg_free(msg);
874 out:
875 	rtnl_set_sk_err(net, RTNLGRP_NSID, err);
876 }
877 
878 static int __init net_ns_init(void)
879 {
880 	struct net_generic *ng;
881 
882 #ifdef CONFIG_NET_NS
883 	net_cachep = kmem_cache_create("net_namespace", sizeof(struct net),
884 					SMP_CACHE_BYTES,
885 					SLAB_PANIC, NULL);
886 
887 	/* Create workqueue for cleanup */
888 	netns_wq = create_singlethread_workqueue("netns");
889 	if (!netns_wq)
890 		panic("Could not create netns workq");
891 #endif
892 
893 	ng = net_alloc_generic();
894 	if (!ng)
895 		panic("Could not allocate generic netns");
896 
897 	rcu_assign_pointer(init_net.gen, ng);
898 
899 	down_write(&net_sem);
900 	if (setup_net(&init_net, &init_user_ns))
901 		panic("Could not setup the initial network namespace");
902 
903 	init_net_initialized = true;
904 	up_write(&net_sem);
905 
906 	register_pernet_subsys(&net_ns_ops);
907 
908 	rtnl_register(PF_UNSPEC, RTM_NEWNSID, rtnl_net_newid, NULL,
909 		      RTNL_FLAG_DOIT_UNLOCKED);
910 	rtnl_register(PF_UNSPEC, RTM_GETNSID, rtnl_net_getid, rtnl_net_dumpid,
911 		      RTNL_FLAG_DOIT_UNLOCKED);
912 
913 	return 0;
914 }
915 
916 pure_initcall(net_ns_init);
917 
918 #ifdef CONFIG_NET_NS
919 static int __register_pernet_operations(struct list_head *list,
920 					struct pernet_operations *ops)
921 {
922 	struct net *net;
923 	int error;
924 	LIST_HEAD(net_exit_list);
925 
926 	list_add_tail(&ops->list, list);
927 	if (ops->init || (ops->id && ops->size)) {
928 		for_each_net(net) {
929 			error = ops_init(ops, net);
930 			if (error)
931 				goto out_undo;
932 			list_add_tail(&net->exit_list, &net_exit_list);
933 		}
934 	}
935 	return 0;
936 
937 out_undo:
938 	/* If I have an error cleanup all namespaces I initialized */
939 	list_del(&ops->list);
940 	ops_exit_list(ops, &net_exit_list);
941 	ops_free_list(ops, &net_exit_list);
942 	return error;
943 }
944 
945 static void __unregister_pernet_operations(struct pernet_operations *ops)
946 {
947 	struct net *net;
948 	LIST_HEAD(net_exit_list);
949 
950 	list_del(&ops->list);
951 	for_each_net(net)
952 		list_add_tail(&net->exit_list, &net_exit_list);
953 	ops_exit_list(ops, &net_exit_list);
954 	ops_free_list(ops, &net_exit_list);
955 }
956 
957 #else
958 
959 static int __register_pernet_operations(struct list_head *list,
960 					struct pernet_operations *ops)
961 {
962 	if (!init_net_initialized) {
963 		list_add_tail(&ops->list, list);
964 		return 0;
965 	}
966 
967 	return ops_init(ops, &init_net);
968 }
969 
970 static void __unregister_pernet_operations(struct pernet_operations *ops)
971 {
972 	if (!init_net_initialized) {
973 		list_del(&ops->list);
974 	} else {
975 		LIST_HEAD(net_exit_list);
976 		list_add(&init_net.exit_list, &net_exit_list);
977 		ops_exit_list(ops, &net_exit_list);
978 		ops_free_list(ops, &net_exit_list);
979 	}
980 }
981 
982 #endif /* CONFIG_NET_NS */
983 
984 static DEFINE_IDA(net_generic_ids);
985 
986 static int register_pernet_operations(struct list_head *list,
987 				      struct pernet_operations *ops)
988 {
989 	int error;
990 
991 	if (ops->id) {
992 again:
993 		error = ida_get_new_above(&net_generic_ids, MIN_PERNET_OPS_ID, ops->id);
994 		if (error < 0) {
995 			if (error == -EAGAIN) {
996 				ida_pre_get(&net_generic_ids, GFP_KERNEL);
997 				goto again;
998 			}
999 			return error;
1000 		}
1001 		max_gen_ptrs = max(max_gen_ptrs, *ops->id + 1);
1002 	}
1003 	error = __register_pernet_operations(list, ops);
1004 	if (error) {
1005 		rcu_barrier();
1006 		if (ops->id)
1007 			ida_remove(&net_generic_ids, *ops->id);
1008 	} else if (!ops->async) {
1009 		pr_info_once("Pernet operations %ps are sync.\n", ops);
1010 		nr_sync_pernet_ops++;
1011 	}
1012 
1013 	return error;
1014 }
1015 
1016 static void unregister_pernet_operations(struct pernet_operations *ops)
1017 {
1018 	if (!ops->async)
1019 		BUG_ON(nr_sync_pernet_ops-- == 0);
1020 	__unregister_pernet_operations(ops);
1021 	rcu_barrier();
1022 	if (ops->id)
1023 		ida_remove(&net_generic_ids, *ops->id);
1024 }
1025 
1026 /**
1027  *      register_pernet_subsys - register a network namespace subsystem
1028  *	@ops:  pernet operations structure for the subsystem
1029  *
1030  *	Register a subsystem which has init and exit functions
1031  *	that are called when network namespaces are created and
1032  *	destroyed respectively.
1033  *
1034  *	When registered all network namespace init functions are
1035  *	called for every existing network namespace.  Allowing kernel
1036  *	modules to have a race free view of the set of network namespaces.
1037  *
1038  *	When a new network namespace is created all of the init
1039  *	methods are called in the order in which they were registered.
1040  *
1041  *	When a network namespace is destroyed all of the exit methods
1042  *	are called in the reverse of the order with which they were
1043  *	registered.
1044  */
1045 int register_pernet_subsys(struct pernet_operations *ops)
1046 {
1047 	int error;
1048 	down_write(&net_sem);
1049 	error =  register_pernet_operations(first_device, ops);
1050 	up_write(&net_sem);
1051 	return error;
1052 }
1053 EXPORT_SYMBOL_GPL(register_pernet_subsys);
1054 
1055 /**
1056  *      unregister_pernet_subsys - unregister a network namespace subsystem
1057  *	@ops: pernet operations structure to manipulate
1058  *
1059  *	Remove the pernet operations structure from the list to be
1060  *	used when network namespaces are created or destroyed.  In
1061  *	addition run the exit method for all existing network
1062  *	namespaces.
1063  */
1064 void unregister_pernet_subsys(struct pernet_operations *ops)
1065 {
1066 	down_write(&net_sem);
1067 	unregister_pernet_operations(ops);
1068 	up_write(&net_sem);
1069 }
1070 EXPORT_SYMBOL_GPL(unregister_pernet_subsys);
1071 
1072 /**
1073  *      register_pernet_device - register a network namespace device
1074  *	@ops:  pernet operations structure for the subsystem
1075  *
1076  *	Register a device which has init and exit functions
1077  *	that are called when network namespaces are created and
1078  *	destroyed respectively.
1079  *
1080  *	When registered all network namespace init functions are
1081  *	called for every existing network namespace.  Allowing kernel
1082  *	modules to have a race free view of the set of network namespaces.
1083  *
1084  *	When a new network namespace is created all of the init
1085  *	methods are called in the order in which they were registered.
1086  *
1087  *	When a network namespace is destroyed all of the exit methods
1088  *	are called in the reverse of the order with which they were
1089  *	registered.
1090  */
1091 int register_pernet_device(struct pernet_operations *ops)
1092 {
1093 	int error;
1094 	down_write(&net_sem);
1095 	error = register_pernet_operations(&pernet_list, ops);
1096 	if (!error && (first_device == &pernet_list))
1097 		first_device = &ops->list;
1098 	up_write(&net_sem);
1099 	return error;
1100 }
1101 EXPORT_SYMBOL_GPL(register_pernet_device);
1102 
1103 /**
1104  *      unregister_pernet_device - unregister a network namespace netdevice
1105  *	@ops: pernet operations structure to manipulate
1106  *
1107  *	Remove the pernet operations structure from the list to be
1108  *	used when network namespaces are created or destroyed.  In
1109  *	addition run the exit method for all existing network
1110  *	namespaces.
1111  */
1112 void unregister_pernet_device(struct pernet_operations *ops)
1113 {
1114 	down_write(&net_sem);
1115 	if (&ops->list == first_device)
1116 		first_device = first_device->next;
1117 	unregister_pernet_operations(ops);
1118 	up_write(&net_sem);
1119 }
1120 EXPORT_SYMBOL_GPL(unregister_pernet_device);
1121 
1122 #ifdef CONFIG_NET_NS
1123 static struct ns_common *netns_get(struct task_struct *task)
1124 {
1125 	struct net *net = NULL;
1126 	struct nsproxy *nsproxy;
1127 
1128 	task_lock(task);
1129 	nsproxy = task->nsproxy;
1130 	if (nsproxy)
1131 		net = get_net(nsproxy->net_ns);
1132 	task_unlock(task);
1133 
1134 	return net ? &net->ns : NULL;
1135 }
1136 
1137 static inline struct net *to_net_ns(struct ns_common *ns)
1138 {
1139 	return container_of(ns, struct net, ns);
1140 }
1141 
1142 static void netns_put(struct ns_common *ns)
1143 {
1144 	put_net(to_net_ns(ns));
1145 }
1146 
1147 static int netns_install(struct nsproxy *nsproxy, struct ns_common *ns)
1148 {
1149 	struct net *net = to_net_ns(ns);
1150 
1151 	if (!ns_capable(net->user_ns, CAP_SYS_ADMIN) ||
1152 	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
1153 		return -EPERM;
1154 
1155 	put_net(nsproxy->net_ns);
1156 	nsproxy->net_ns = get_net(net);
1157 	return 0;
1158 }
1159 
1160 static struct user_namespace *netns_owner(struct ns_common *ns)
1161 {
1162 	return to_net_ns(ns)->user_ns;
1163 }
1164 
1165 const struct proc_ns_operations netns_operations = {
1166 	.name		= "net",
1167 	.type		= CLONE_NEWNET,
1168 	.get		= netns_get,
1169 	.put		= netns_put,
1170 	.install	= netns_install,
1171 	.owner		= netns_owner,
1172 };
1173 #endif
1174