]> git.proxmox.com Git - mirror_iproute2.git/blame - ip/ipnetns.c
ipnetns: fix misleading comment about 'ip monitor nsid'
[mirror_iproute2.git] / ip / ipnetns.c
CommitLineData
6054c1eb 1/* SPDX-License-Identifier: GPL-2.0 */
0dc34c77
EB
2#define _ATFILE_SOURCE
3#include <sys/types.h>
4#include <sys/stat.h>
5#include <sys/wait.h>
6#include <sys/inotify.h>
7#include <sys/mount.h>
0dc34c77
EB
8#include <sys/syscall.h>
9#include <stdio.h>
10#include <string.h>
11#include <sched.h>
12#include <fcntl.h>
13#include <dirent.h>
14#include <errno.h>
15#include <unistd.h>
9a7b3d91 16#include <ctype.h>
d652ccbf 17#include <linux/limits.h>
0dc34c77 18
d182ee13
ND
19#include <linux/net_namespace.h>
20
0dc34c77 21#include "utils.h"
4952b459 22#include "list.h"
0dc34c77 23#include "ip_common.h"
eb67e449 24#include "namespace.h"
e93d9221 25#include "json_print.h"
0dc34c77 26
8e2d47dc 27static int usage(void)
0dc34c77 28{
8589eb4e
MC
29 fprintf(stderr,
30 "Usage: ip netns list\n"
31 " ip netns add NAME\n"
32 " ip netns attach NAME PID\n"
33 " ip netns set NAME NETNSID\n"
34 " ip [-all] netns delete [NAME]\n"
35 " ip netns identify [PID]\n"
36 " ip netns pids NAME\n"
37 " ip [-all] netns exec [NAME] cmd ...\n"
38 " ip netns monitor\n"
eaefb078 39 " ip netns list-id [target-nsid POSITIVE-INT] [nsid POSITIVE-INT]\n"
8589eb4e 40 "NETNSID := auto | POSITIVE-INT\n");
a05f6511 41 exit(-1);
0dc34c77
EB
42}
43
d652ccbf
ND
44/* This socket is used to get nsid */
45static struct rtnl_handle rtnsh = { .fd = -1 };
46
4c7d9a58 47static int have_rtnl_getnsid = -1;
b2e29223 48static int saved_netns = -1;
eaefb078 49static struct link_filter filter;
4c7d9a58 50
cd554f2c 51static int ipnetns_accept_msg(struct rtnl_ctrl_data *ctrl,
4c7d9a58
ND
52 struct nlmsghdr *n, void *arg)
53{
54 struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(n);
55
56 if (n->nlmsg_type == NLMSG_ERROR &&
57 (err->error == -EOPNOTSUPP || err->error == -EINVAL))
58 have_rtnl_getnsid = 0;
59 else
60 have_rtnl_getnsid = 1;
61 return -1;
62}
63
64static int ipnetns_have_nsid(void)
65{
66 struct {
67 struct nlmsghdr n;
68 struct rtgenmsg g;
69 char buf[1024];
d17b136f
PS
70 } req = {
71 .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
72 .n.nlmsg_flags = NLM_F_REQUEST,
73 .n.nlmsg_type = RTM_GETNSID,
74 .g.rtgen_family = AF_UNSPEC,
75 };
4c7d9a58
ND
76 int fd;
77
78 if (have_rtnl_getnsid < 0) {
4c7d9a58
ND
79 fd = open("/proc/self/ns/net", O_RDONLY);
80 if (fd < 0) {
c44003f7
LZ
81 have_rtnl_getnsid = 0;
82 return 0;
4c7d9a58
ND
83 }
84
85 addattr32(&req.n, 1024, NETNSA_FD, fd);
86
87 if (rtnl_send(&rth, &req.n, req.n.nlmsg_len) < 0) {
88 perror("request send failed");
89 exit(1);
90 }
91 rtnl_listen(&rth, ipnetns_accept_msg, NULL);
92 close(fd);
93 }
94
95 return have_rtnl_getnsid;
96}
97
974ef93b 98int get_netnsid_from_name(const char *name)
d182ee13
ND
99{
100 struct {
101 struct nlmsghdr n;
102 struct rtgenmsg g;
103 char buf[1024];
86bf43c7 104 } req = {
d17b136f
PS
105 .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
106 .n.nlmsg_flags = NLM_F_REQUEST,
107 .n.nlmsg_type = RTM_GETNSID,
108 .g.rtgen_family = AF_UNSPEC,
109 };
86bf43c7 110 struct nlmsghdr *answer;
d182ee13
ND
111 struct rtattr *tb[NETNSA_MAX + 1];
112 struct rtgenmsg *rthdr;
9bf2c538 113 int len, fd, ret = -1;
d182ee13 114
974ef93b
ND
115 netns_nsid_socket_init();
116
d182ee13
ND
117 fd = netns_get_fd(name);
118 if (fd < 0)
119 return fd;
120
121 addattr32(&req.n, 1024, NETNSA_FD, fd);
86bf43c7 122 if (rtnl_talk(&rtnsh, &req.n, &answer) < 0) {
d182ee13
ND
123 close(fd);
124 return -2;
125 }
126 close(fd);
127
128 /* Validate message and parse attributes */
86bf43c7 129 if (answer->nlmsg_type == NLMSG_ERROR)
9bf2c538 130 goto out;
d182ee13 131
86bf43c7
HL
132 rthdr = NLMSG_DATA(answer);
133 len = answer->nlmsg_len - NLMSG_SPACE(sizeof(*rthdr));
d182ee13 134 if (len < 0)
9bf2c538 135 goto out;
d182ee13
ND
136
137 parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);
138
86bf43c7 139 if (tb[NETNSA_NSID]) {
f19966ef 140 ret = rta_getattr_s32(tb[NETNSA_NSID]);
86bf43c7 141 }
d182ee13 142
9bf2c538 143out:
86bf43c7 144 free(answer);
9bf2c538 145 return ret;
d182ee13
ND
146}
147
d652ccbf
ND
148struct nsid_cache {
149 struct hlist_node nsid_hash;
150 struct hlist_node name_hash;
151 int nsid;
2f29d6bb 152 char name[0];
d652ccbf
ND
153};
154
155#define NSIDMAP_SIZE 128
156#define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
157#define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
158
159static struct hlist_head nsid_head[NSIDMAP_SIZE];
160static struct hlist_head name_head[NSIDMAP_SIZE];
161
162static struct nsid_cache *netns_map_get_by_nsid(int nsid)
163{
164 uint32_t h = NSID_HASH_NSID(nsid);
165 struct hlist_node *n;
166
167 hlist_for_each(n, &nsid_head[h]) {
168 struct nsid_cache *c = container_of(n, struct nsid_cache,
169 nsid_hash);
170 if (c->nsid == nsid)
171 return c;
172 }
173
174 return NULL;
175}
176
9580bad7
ND
177char *get_name_from_nsid(int nsid)
178{
179 struct nsid_cache *c;
180
181 netns_nsid_socket_init();
182 netns_map_init();
183
184 c = netns_map_get_by_nsid(nsid);
185 if (c)
186 return c->name;
187
188 return NULL;
189}
190
2f29d6bb 191static int netns_map_add(int nsid, const char *name)
d652ccbf
ND
192{
193 struct nsid_cache *c;
194 uint32_t h;
195
196 if (netns_map_get_by_nsid(nsid) != NULL)
197 return -EEXIST;
198
a1b4a274 199 c = malloc(sizeof(*c) + strlen(name) + 1);
d652ccbf
ND
200 if (c == NULL) {
201 perror("malloc");
202 return -ENOMEM;
203 }
204 c->nsid = nsid;
205 strcpy(c->name, name);
206
207 h = NSID_HASH_NSID(nsid);
208 hlist_add_head(&c->nsid_hash, &nsid_head[h]);
209
210 h = NSID_HASH_NAME(name);
211 hlist_add_head(&c->name_hash, &name_head[h]);
212
213 return 0;
214}
215
216static void netns_map_del(struct nsid_cache *c)
217{
218 hlist_del(&c->name_hash);
219 hlist_del(&c->nsid_hash);
220 free(c);
221}
222
e29a8e05
AA
223void netns_nsid_socket_init(void)
224{
225 if (rtnsh.fd > -1 || !ipnetns_have_nsid())
226 return;
227
228 if (rtnl_open(&rtnsh, 0) < 0) {
229 fprintf(stderr, "Cannot open rtnetlink\n");
230 exit(1);
231 }
232
233}
234
d652ccbf
ND
235void netns_map_init(void)
236{
237 static int initialized;
238 struct dirent *entry;
239 DIR *dir;
240 int nsid;
241
242 if (initialized || !ipnetns_have_nsid())
243 return;
244
d652ccbf
ND
245 dir = opendir(NETNS_RUN_DIR);
246 if (!dir)
247 return;
248
249 while ((entry = readdir(dir)) != NULL) {
250 if (strcmp(entry->d_name, ".") == 0)
251 continue;
252 if (strcmp(entry->d_name, "..") == 0)
253 continue;
254 nsid = get_netnsid_from_name(entry->d_name);
255
256 if (nsid >= 0)
257 netns_map_add(nsid, entry->d_name);
258 }
259 closedir(dir);
260 initialized = 1;
261}
262
263static int netns_get_name(int nsid, char *name)
264{
265 struct dirent *entry;
266 DIR *dir;
267 int id;
268
269 dir = opendir(NETNS_RUN_DIR);
270 if (!dir)
271 return -ENOENT;
272
273 while ((entry = readdir(dir)) != NULL) {
274 if (strcmp(entry->d_name, ".") == 0)
275 continue;
276 if (strcmp(entry->d_name, "..") == 0)
277 continue;
278 id = get_netnsid_from_name(entry->d_name);
279
280 if (nsid == id) {
281 strcpy(name, entry->d_name);
282 closedir(dir);
283 return 0;
284 }
285 }
286 closedir(dir);
287 return -ENOENT;
288}
289
cd554f2c 290int print_nsid(struct nlmsghdr *n, void *arg)
d652ccbf
ND
291{
292 struct rtgenmsg *rthdr = NLMSG_DATA(n);
293 struct rtattr *tb[NETNSA_MAX+1];
294 int len = n->nlmsg_len;
295 FILE *fp = (FILE *)arg;
296 struct nsid_cache *c;
297 char name[NAME_MAX];
eaefb078 298 int nsid, current;
d652ccbf
ND
299
300 if (n->nlmsg_type != RTM_NEWNSID && n->nlmsg_type != RTM_DELNSID)
301 return 0;
302
303 len -= NLMSG_SPACE(sizeof(*rthdr));
304 if (len < 0) {
305 fprintf(stderr, "BUG: wrong nlmsg len %d in %s\n", len,
306 __func__);
307 return -1;
308 }
309
310 parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);
311 if (tb[NETNSA_NSID] == NULL) {
312 fprintf(stderr, "BUG: NETNSA_NSID is missing %s\n", __func__);
313 return -1;
314 }
315
e93d9221 316 open_json_object(NULL);
d652ccbf 317 if (n->nlmsg_type == RTM_DELNSID)
e93d9221 318 print_bool(PRINT_ANY, "deleted", "Deleted ", true);
d652ccbf 319
f19966ef 320 nsid = rta_getattr_s32(tb[NETNSA_NSID]);
eaefb078
ND
321 if (nsid < 0)
322 print_string(PRINT_ANY, "nsid", "nsid %s ", "not-assigned");
323 else
f19966ef 324 print_int(PRINT_ANY, "nsid", "nsid %d ", nsid);
eaefb078
ND
325
326 if (tb[NETNSA_CURRENT_NSID]) {
f19966ef 327 current = rta_getattr_s32(tb[NETNSA_CURRENT_NSID]);
eaefb078
ND
328 if (current < 0)
329 print_string(PRINT_ANY, "current-nsid",
330 "current-nsid %s ", "not-assigned");
331 else
f19966ef
GN
332 print_int(PRINT_ANY, "current-nsid",
333 "current-nsid %d ", current);
eaefb078 334 }
d652ccbf 335
eaefb078 336 c = netns_map_get_by_nsid(tb[NETNSA_CURRENT_NSID] ? current : nsid);
d652ccbf 337 if (c != NULL) {
e93d9221
SH
338 print_string(PRINT_ANY, "name",
339 "(iproute2 netns name: %s)", c->name);
d652ccbf
ND
340 netns_map_del(c);
341 }
342
df6da60b 343 /* nsid might not be in cache */
d652ccbf
ND
344 if (c == NULL && n->nlmsg_type == RTM_NEWNSID)
345 if (netns_get_name(nsid, name) == 0) {
e93d9221
SH
346 print_string(PRINT_ANY, "name",
347 "(iproute2 netns name: %s)", name);
d652ccbf
ND
348 netns_map_add(nsid, name);
349 }
350
e93d9221
SH
351 print_string(PRINT_FP, NULL, "\n", NULL);
352 close_json_object();
d652ccbf
ND
353 fflush(fp);
354 return 0;
355}
356
eaefb078
ND
357static int get_netnsid_from_netnsid(int nsid)
358{
359 struct {
360 struct nlmsghdr n;
361 struct rtgenmsg g;
362 char buf[1024];
363 } req = {
364 .n.nlmsg_len = NLMSG_LENGTH(NLMSG_ALIGN(sizeof(struct rtgenmsg))),
365 .n.nlmsg_flags = NLM_F_REQUEST,
366 .n.nlmsg_type = RTM_GETNSID,
367 .g.rtgen_family = AF_UNSPEC,
368 };
369 struct nlmsghdr *answer;
370 int err;
371
372 netns_nsid_socket_init();
373
374 err = addattr32(&req.n, sizeof(req), NETNSA_NSID, nsid);
375 if (err)
376 return err;
377
378 if (filter.target_nsid >= 0) {
379 err = addattr32(&req.n, sizeof(req), NETNSA_TARGET_NSID,
380 filter.target_nsid);
381 if (err)
382 return err;
383 }
384
385 if (rtnl_talk(&rtnsh, &req.n, &answer) < 0)
386 return -2;
387
388 /* Validate message and parse attributes */
389 if (answer->nlmsg_type == NLMSG_ERROR)
390 goto err_out;
391
392 new_json_obj(json);
393 err = print_nsid(answer, stdout);
394 delete_json_obj();
395err_out:
396 free(answer);
397 return err;
398}
399
400static int netns_filter_req(struct nlmsghdr *nlh, int reqlen)
401{
402 int err;
403
404 if (filter.target_nsid >= 0) {
405 err = addattr32(nlh, reqlen, NETNSA_TARGET_NSID,
406 filter.target_nsid);
407 if (err)
408 return err;
409 }
410
411 return 0;
412}
413
d652ccbf
ND
414static int netns_list_id(int argc, char **argv)
415{
eaefb078
ND
416 int nsid = -1;
417
d652ccbf
ND
418 if (!ipnetns_have_nsid()) {
419 fprintf(stderr,
420 "RTM_GETNSID is not supported by the kernel.\n");
421 return -ENOTSUP;
422 }
423
eaefb078
ND
424 filter.target_nsid = -1;
425 while (argc > 0) {
426 if (strcmp(*argv, "target-nsid") == 0) {
427 if (filter.target_nsid >= 0)
428 duparg("target-nsid", *argv);
429 NEXT_ARG();
430
431 if (get_integer(&filter.target_nsid, *argv, 0))
432 invarg("\"target-nsid\" value is invalid\n",
433 *argv);
434 else if (filter.target_nsid < 0)
435 invarg("\"target-nsid\" value should be >= 0\n",
436 argv[1]);
437 } else if (strcmp(*argv, "nsid") == 0) {
438 if (nsid >= 0)
439 duparg("nsid", *argv);
440 NEXT_ARG();
441
442 if (get_integer(&nsid, *argv, 0))
443 invarg("\"nsid\" value is invalid\n", *argv);
444 else if (nsid < 0)
445 invarg("\"nsid\" value should be >= 0\n",
446 argv[1]);
447 } else
448 usage();
449 argc--; argv++;
450 }
451
452 if (nsid >= 0)
453 return get_netnsid_from_netnsid(nsid);
454
455 if (rtnl_nsiddump_req_filter_fn(&rth, AF_UNSPEC,
456 netns_filter_req) < 0) {
d652ccbf
ND
457 perror("Cannot send dump request");
458 exit(1);
459 }
e93d9221
SH
460
461 new_json_obj(json);
d652ccbf 462 if (rtnl_dump_filter(&rth, print_nsid, stdout) < 0) {
e93d9221 463 delete_json_obj();
d652ccbf
ND
464 fprintf(stderr, "Dump terminated\n");
465 exit(1);
466 }
e93d9221 467 delete_json_obj();
d652ccbf
ND
468 return 0;
469}
470
0dc34c77
EB
471static int netns_list(int argc, char **argv)
472{
473 struct dirent *entry;
474 DIR *dir;
d182ee13 475 int id;
0dc34c77
EB
476
477 dir = opendir(NETNS_RUN_DIR);
478 if (!dir)
a05f6511 479 return 0;
0dc34c77 480
e93d9221 481 new_json_obj(json);
0dc34c77
EB
482 while ((entry = readdir(dir)) != NULL) {
483 if (strcmp(entry->d_name, ".") == 0)
484 continue;
485 if (strcmp(entry->d_name, "..") == 0)
486 continue;
e93d9221
SH
487
488 open_json_object(NULL);
489 print_string(PRINT_ANY, "name",
490 "%s", entry->d_name);
4c7d9a58
ND
491 if (ipnetns_have_nsid()) {
492 id = get_netnsid_from_name(entry->d_name);
493 if (id >= 0)
f19966ef 494 print_int(PRINT_ANY, "id", " (id: %d)", id);
4c7d9a58 495 }
e93d9221
SH
496 print_string(PRINT_FP, NULL, "\n", NULL);
497 close_json_object();
0dc34c77
EB
498 }
499 closedir(dir);
e93d9221 500 delete_json_obj();
a05f6511 501 return 0;
0dc34c77
EB
502}
503
903818fb
MC
504static int do_switch(void *arg)
505{
506 char *netns = arg;
507
508 /* we just changed namespaces. clear any vrf association
509 * with prior namespace before exec'ing command
510 */
511 vrf_reset();
512
513 return netns_switch(netns);
514}
515
b13ba03f
VK
516static int on_netns_exec(char *nsname, void *arg)
517{
518 char **argv = arg;
56f5daac 519
903818fb
MC
520 printf("\nnetns: %s\n", nsname);
521 cmd_exec(argv[0], argv, true, do_switch, nsname);
b13ba03f
VK
522 return 0;
523}
524
525static int netns_exec(int argc, char **argv)
526{
527 /* Setup the proper environment for apps that are not netns
528 * aware, and execute a program in that environment.
529 */
b13ba03f
VK
530 if (argc < 1 && !do_all) {
531 fprintf(stderr, "No netns name specified\n");
532 return -1;
533 }
534 if ((argc < 2 && !do_all) || (argc < 1 && do_all)) {
535 fprintf(stderr, "No command specified\n");
536 return -1;
537 }
538
539 if (do_all)
903818fb 540 return netns_foreach(on_netns_exec, argv);
ee9369a0 541
b13ba03f
VK
542 /* ip must return the status of the child,
543 * but do_cmd() will add a minus to this,
544 * so let's add another one here to cancel it.
545 */
903818fb 546 return -cmd_exec(argv[1], argv + 1, !!batch_mode, do_switch, argv[0]);
b13ba03f
VK
547}
548
9a7b3d91
EB
549static int is_pid(const char *str)
550{
551 int ch;
56f5daac 552
9a7b3d91
EB
553 for (; (ch = *str); str++) {
554 if (!isdigit(ch))
555 return 0;
556 }
557 return 1;
558}
559
560static int netns_pids(int argc, char **argv)
561{
562 const char *name;
ea343669 563 char net_path[PATH_MAX];
9a7b3d91
EB
564 int netns;
565 struct stat netst;
566 DIR *dir;
567 struct dirent *entry;
568
569 if (argc < 1) {
570 fprintf(stderr, "No netns name specified\n");
a05f6511 571 return -1;
9a7b3d91
EB
572 }
573 if (argc > 1) {
574 fprintf(stderr, "extra arguments specified\n");
a05f6511 575 return -1;
9a7b3d91
EB
576 }
577
578 name = argv[0];
579 snprintf(net_path, sizeof(net_path), "%s/%s", NETNS_RUN_DIR, name);
580 netns = open(net_path, O_RDONLY);
581 if (netns < 0) {
582 fprintf(stderr, "Cannot open network namespace: %s\n",
583 strerror(errno));
a05f6511 584 return -1;
9a7b3d91
EB
585 }
586 if (fstat(netns, &netst) < 0) {
587 fprintf(stderr, "Stat of netns failed: %s\n",
588 strerror(errno));
a05f6511 589 return -1;
9a7b3d91
EB
590 }
591 dir = opendir("/proc/");
592 if (!dir) {
593 fprintf(stderr, "Open of /proc failed: %s\n",
594 strerror(errno));
a05f6511 595 return -1;
9a7b3d91 596 }
56f5daac 597 while ((entry = readdir(dir))) {
ea343669 598 char pid_net_path[PATH_MAX];
9a7b3d91 599 struct stat st;
56f5daac 600
9a7b3d91
EB
601 if (!is_pid(entry->d_name))
602 continue;
603 snprintf(pid_net_path, sizeof(pid_net_path), "/proc/%s/ns/net",
604 entry->d_name);
605 if (stat(pid_net_path, &st) != 0)
606 continue;
607 if ((st.st_dev == netst.st_dev) &&
608 (st.st_ino == netst.st_ino)) {
609 printf("%s\n", entry->d_name);
610 }
611 }
612 closedir(dir);
a05f6511 613 return 0;
0612519e 614
9a7b3d91
EB
615}
616
9c49438a 617int netns_identify_pid(const char *pidstr, char *name, int len)
9a7b3d91 618{
ea343669 619 char net_path[PATH_MAX];
9a7b3d91
EB
620 int netns;
621 struct stat netst;
622 DIR *dir;
623 struct dirent *entry;
624
9c49438a 625 name[0] = '\0';
9a7b3d91
EB
626
627 snprintf(net_path, sizeof(net_path), "/proc/%s/ns/net", pidstr);
628 netns = open(net_path, O_RDONLY);
629 if (netns < 0) {
630 fprintf(stderr, "Cannot open network namespace: %s\n",
631 strerror(errno));
a05f6511 632 return -1;
9a7b3d91
EB
633 }
634 if (fstat(netns, &netst) < 0) {
635 fprintf(stderr, "Stat of netns failed: %s\n",
636 strerror(errno));
a05f6511 637 return -1;
9a7b3d91
EB
638 }
639 dir = opendir(NETNS_RUN_DIR);
640 if (!dir) {
641 /* Succeed treat a missing directory as an empty directory */
642 if (errno == ENOENT)
a05f6511 643 return 0;
9a7b3d91
EB
644
645 fprintf(stderr, "Failed to open directory %s:%s\n",
646 NETNS_RUN_DIR, strerror(errno));
a05f6511 647 return -1;
9a7b3d91
EB
648 }
649
56f5daac 650 while ((entry = readdir(dir))) {
ea343669 651 char name_path[PATH_MAX];
9a7b3d91
EB
652 struct stat st;
653
654 if (strcmp(entry->d_name, ".") == 0)
655 continue;
656 if (strcmp(entry->d_name, "..") == 0)
657 continue;
658
659 snprintf(name_path, sizeof(name_path), "%s/%s", NETNS_RUN_DIR,
660 entry->d_name);
661
662 if (stat(name_path, &st) != 0)
663 continue;
664
665 if ((st.st_dev == netst.st_dev) &&
666 (st.st_ino == netst.st_ino)) {
18f156bf 667 strlcpy(name, entry->d_name, len);
9a7b3d91
EB
668 }
669 }
670 closedir(dir);
a05f6511 671 return 0;
0612519e 672
9a7b3d91
EB
673}
674
9c49438a
DA
675static int netns_identify(int argc, char **argv)
676{
677 const char *pidstr;
678 char name[256];
679 int rc;
680
681 if (argc < 1) {
682 pidstr = "self";
683 } else if (argc > 1) {
684 fprintf(stderr, "extra arguments specified\n");
685 return -1;
686 } else {
687 pidstr = argv[0];
688 if (!is_pid(pidstr)) {
689 fprintf(stderr, "Specified string '%s' is not a pid\n",
690 pidstr);
691 return -1;
692 }
693 }
694
695 rc = netns_identify_pid(pidstr, name, sizeof(name));
696 if (!rc)
697 printf("%s\n", name);
698
699 return rc;
700}
701
33724939 702static int on_netns_del(char *nsname, void *arg)
0dc34c77 703{
ea343669 704 char netns_path[PATH_MAX];
0dc34c77 705
33724939 706 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, nsname);
0dc34c77
EB
707 umount2(netns_path, MNT_DETACH);
708 if (unlink(netns_path) < 0) {
14645ec2 709 fprintf(stderr, "Cannot remove namespace file \"%s\": %s\n",
0dc34c77 710 netns_path, strerror(errno));
a05f6511 711 return -1;
0dc34c77 712 }
a05f6511 713 return 0;
0dc34c77
EB
714}
715
33724939
VK
716static int netns_delete(int argc, char **argv)
717{
718 if (argc < 1 && !do_all) {
719 fprintf(stderr, "No netns name specified\n");
720 return -1;
721 }
722
723 if (do_all)
724 return netns_foreach(on_netns_del, NULL);
725
726 return on_netns_del(argv[0], NULL);
727}
728
c1cbb18a 729static int create_netns_dir(void)
730{
731 /* Create the base netns directory if it doesn't exist */
732 if (mkdir(NETNS_RUN_DIR, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)) {
733 if (errno != EEXIST) {
734 fprintf(stderr, "mkdir %s failed: %s\n",
735 NETNS_RUN_DIR, strerror(errno));
736 return -1;
737 }
738 }
739
740 return 0;
741}
742
b2e29223
MC
743/* Obtain a FD for the current namespace, so we can reenter it later */
744static void netns_save(void)
745{
746 if (saved_netns != -1)
747 return;
748
749 saved_netns = open("/proc/self/ns/net", O_RDONLY | O_CLOEXEC);
750 if (saved_netns == -1) {
751 perror("Cannot open init namespace");
752 exit(1);
753 }
754}
755
756static void netns_restore(void)
757{
758 if (saved_netns == -1)
759 return;
760
761 if (setns(saved_netns, CLONE_NEWNET)) {
762 perror("setns");
763 exit(1);
764 }
765
766 close(saved_netns);
767 saved_netns = -1;
768}
769
e3dbcb2a 770static int netns_add(int argc, char **argv, bool create)
0dc34c77
EB
771{
772 /* This function creates a new network namespace and
773 * a new mount namespace and bind them into a well known
774 * location in the filesystem based on the name provided.
775 *
e3dbcb2a
MC
776 * If create is true, a new namespace will be created,
777 * otherwise an existing one will be attached to the file.
778 *
0dc34c77
EB
779 * The mount namespace is created so that any necessary
780 * userspace tweaks like remounting /sys, or bind mounting
e3dbcb2a 781 * a new /etc/resolv.conf can be shared between users.
0dc34c77 782 */
e3dbcb2a 783 char netns_path[PATH_MAX], proc_path[PATH_MAX];
0dc34c77 784 const char *name;
e3dbcb2a 785 pid_t pid;
223f4d8e 786 int fd;
58a3e827 787 int made_netns_run_dir_mount = 0;
0dc34c77 788
e3dbcb2a
MC
789 if (create) {
790 if (argc < 1) {
791 fprintf(stderr, "No netns name specified\n");
792 return -1;
793 }
794 } else {
795 if (argc < 2) {
796 fprintf(stderr, "No netns name and PID specified\n");
797 return -1;
798 }
799
800 if (get_s32(&pid, argv[1], 0) || !pid) {
801 fprintf(stderr, "Invalid PID: %s\n", argv[1]);
802 return -1;
803 }
0dc34c77
EB
804 }
805 name = argv[0];
806
807 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, name);
808
c1cbb18a 809 if (create_netns_dir())
810 return -1;
0dc34c77 811
d259f030 812 /* Make it possible for network namespace mounts to propagate between
58a3e827
EB
813 * mount namespaces. This makes it likely that a unmounting a network
814 * namespace file in one namespace will unmount the network namespace
815 * file in all namespaces allowing the network namespace to be freed
816 * sooner.
817 */
818 while (mount("", NETNS_RUN_DIR, "none", MS_SHARED | MS_REC, NULL)) {
819 /* Fail unless we need to make the mount point */
820 if (errno != EINVAL || made_netns_run_dir_mount) {
821 fprintf(stderr, "mount --make-shared %s failed: %s\n",
822 NETNS_RUN_DIR, strerror(errno));
a05f6511 823 return -1;
58a3e827
EB
824 }
825
826 /* Upgrade NETNS_RUN_DIR to a mount point */
d6a4076b 827 if (mount(NETNS_RUN_DIR, NETNS_RUN_DIR, "none", MS_BIND | MS_REC, NULL)) {
58a3e827
EB
828 fprintf(stderr, "mount --bind %s %s failed: %s\n",
829 NETNS_RUN_DIR, NETNS_RUN_DIR, strerror(errno));
a05f6511 830 return -1;
58a3e827
EB
831 }
832 made_netns_run_dir_mount = 1;
833 }
834
0dc34c77 835 /* Create the filesystem state */
223f4d8e
EB
836 fd = open(netns_path, O_RDONLY|O_CREAT|O_EXCL, 0);
837 if (fd < 0) {
55713c8c 838 fprintf(stderr, "Cannot create namespace file \"%s\": %s\n",
0dc34c77 839 netns_path, strerror(errno));
a05f6511 840 return -1;
0dc34c77 841 }
223f4d8e 842 close(fd);
e3dbcb2a
MC
843
844 if (create) {
80a931d4 845 netns_save();
e3dbcb2a
MC
846 if (unshare(CLONE_NEWNET) < 0) {
847 fprintf(stderr, "Failed to create a new network namespace \"%s\": %s\n",
848 name, strerror(errno));
849 goto out_delete;
850 }
851
852 strcpy(proc_path, "/proc/self/ns/net");
853 } else {
854 snprintf(proc_path, sizeof(proc_path), "/proc/%d/ns/net", pid);
0dc34c77
EB
855 }
856
857 /* Bind the netns last so I can watch for it */
e3dbcb2a
MC
858 if (mount(proc_path, netns_path, "none", MS_BIND, NULL) < 0) {
859 fprintf(stderr, "Bind %s -> %s failed: %s\n",
860 proc_path, netns_path, strerror(errno));
0dc34c77
EB
861 goto out_delete;
862 }
b2e29223
MC
863 netns_restore();
864
a05f6511 865 return 0;
0dc34c77 866out_delete:
e3dbcb2a 867 if (create) {
b2e29223 868 netns_restore();
e3dbcb2a
MC
869 netns_delete(argc, argv);
870 } else if (unlink(netns_path) < 0) {
871 fprintf(stderr, "Cannot remove namespace file \"%s\": %s\n",
872 netns_path, strerror(errno));
873 }
a05f6511 874 return -1;
0dc34c77
EB
875}
876
974ef93b 877int set_netnsid_from_name(const char *name, int nsid)
d182ee13
ND
878{
879 struct {
880 struct nlmsghdr n;
881 struct rtgenmsg g;
882 char buf[1024];
d17b136f
PS
883 } req = {
884 .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
885 .n.nlmsg_flags = NLM_F_REQUEST,
886 .n.nlmsg_type = RTM_NEWNSID,
887 .g.rtgen_family = AF_UNSPEC,
888 };
d182ee13
ND
889 int fd, err = 0;
890
974ef93b
ND
891 netns_nsid_socket_init();
892
d182ee13
ND
893 fd = netns_get_fd(name);
894 if (fd < 0)
895 return fd;
896
897 addattr32(&req.n, 1024, NETNSA_FD, fd);
898 addattr32(&req.n, 1024, NETNSA_NSID, nsid);
86bf43c7 899 if (rtnl_talk(&rth, &req.n, NULL) < 0)
d182ee13
ND
900 err = -2;
901
902 close(fd);
903 return err;
904}
905
906static int netns_set(int argc, char **argv)
907{
ea343669 908 char netns_path[PATH_MAX];
d182ee13 909 const char *name;
ebe3ce2f 910 int netns, nsid;
d182ee13
ND
911
912 if (argc < 1) {
913 fprintf(stderr, "No netns name specified\n");
914 return -1;
915 }
916 if (argc < 2) {
917 fprintf(stderr, "No nsid specified\n");
918 return -1;
919 }
920 name = argv[0];
375d51ca
CB
921 /* If a negative nsid is specified the kernel will select the nsid. */
922 if (strcmp(argv[1], "auto") == 0)
923 nsid = -1;
ebe3ce2f 924 else if (get_integer(&nsid, argv[1], 0))
acbe9118 925 invarg("Invalid \"netnsid\" value\n", argv[1]);
ebe3ce2f
ND
926 else if (nsid < 0)
927 invarg("\"netnsid\" value should be >= 0\n", argv[1]);
d182ee13
ND
928
929 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, name);
930 netns = open(netns_path, O_RDONLY | O_CLOEXEC);
931 if (netns < 0) {
932 fprintf(stderr, "Cannot open network namespace \"%s\": %s\n",
933 name, strerror(errno));
934 return -1;
935 }
936
937 return set_netnsid_from_name(name, nsid);
938}
0dc34c77
EB
939
940static int netns_monitor(int argc, char **argv)
941{
942 char buf[4096];
943 struct inotify_event *event;
944 int fd;
56f5daac 945
0dc34c77
EB
946 fd = inotify_init();
947 if (fd < 0) {
948 fprintf(stderr, "inotify_init failed: %s\n",
949 strerror(errno));
a05f6511 950 return -1;
0dc34c77 951 }
c1cbb18a 952
953 if (create_netns_dir())
954 return -1;
955
0dc34c77
EB
956 if (inotify_add_watch(fd, NETNS_RUN_DIR, IN_CREATE | IN_DELETE) < 0) {
957 fprintf(stderr, "inotify_add_watch failed: %s\n",
958 strerror(errno));
a05f6511 959 return -1;
0dc34c77 960 }
56f5daac 961 for (;;) {
0dc34c77 962 ssize_t len = read(fd, buf, sizeof(buf));
56f5daac 963
0dc34c77
EB
964 if (len < 0) {
965 fprintf(stderr, "read failed: %s\n",
966 strerror(errno));
a05f6511 967 return -1;
0dc34c77
EB
968 }
969 for (event = (struct inotify_event *)buf;
970 (char *)event < &buf[len];
971 event = (struct inotify_event *)((char *)event + sizeof(*event) + event->len)) {
972 if (event->mask & IN_CREATE)
973 printf("add %s\n", event->name);
974 if (event->mask & IN_DELETE)
975 printf("delete %s\n", event->name);
976 }
977 }
a05f6511 978 return 0;
0dc34c77
EB
979}
980
79928fd0
MC
981static int invalid_name(const char *name)
982{
d3f0b091
MC
983 return !*name || strlen(name) > NAME_MAX ||
984 strchr(name, '/') || !strcmp(name, ".") || !strcmp(name, "..");
79928fd0
MC
985}
986
0dc34c77
EB
987int do_netns(int argc, char **argv)
988{
e29a8e05 989 netns_nsid_socket_init();
d652ccbf 990
e29a8e05
AA
991 if (argc < 1) {
992 netns_map_init();
0dc34c77 993 return netns_list(0, NULL);
e29a8e05 994 }
0dc34c77 995
b7f28e0b 996 if (!do_all && argc > 1 && invalid_name(argv[1])) {
79928fd0
MC
997 fprintf(stderr, "Invalid netns name \"%s\"\n", argv[1]);
998 exit(-1);
999 }
1000
0dc34c77 1001 if ((matches(*argv, "list") == 0) || (matches(*argv, "show") == 0) ||
e29a8e05
AA
1002 (matches(*argv, "lst") == 0)) {
1003 netns_map_init();
0dc34c77 1004 return netns_list(argc-1, argv+1);
e29a8e05 1005 }
0dc34c77 1006
e29a8e05
AA
1007 if ((matches(*argv, "list-id") == 0)) {
1008 netns_map_init();
d652ccbf 1009 return netns_list_id(argc-1, argv+1);
e29a8e05 1010 }
d652ccbf 1011
0dc34c77 1012 if (matches(*argv, "help") == 0)
8e2d47dc 1013 return usage();
0dc34c77
EB
1014
1015 if (matches(*argv, "add") == 0)
e3dbcb2a 1016 return netns_add(argc-1, argv+1, true);
0dc34c77 1017
d182ee13
ND
1018 if (matches(*argv, "set") == 0)
1019 return netns_set(argc-1, argv+1);
1020
0dc34c77
EB
1021 if (matches(*argv, "delete") == 0)
1022 return netns_delete(argc-1, argv+1);
1023
9a7b3d91
EB
1024 if (matches(*argv, "identify") == 0)
1025 return netns_identify(argc-1, argv+1);
1026
1027 if (matches(*argv, "pids") == 0)
1028 return netns_pids(argc-1, argv+1);
1029
0dc34c77
EB
1030 if (matches(*argv, "exec") == 0)
1031 return netns_exec(argc-1, argv+1);
1032
1033 if (matches(*argv, "monitor") == 0)
1034 return netns_monitor(argc-1, argv+1);
1035
e3dbcb2a
MC
1036 if (matches(*argv, "attach") == 0)
1037 return netns_add(argc-1, argv+1, false);
1038
0dc34c77 1039 fprintf(stderr, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv);
a05f6511 1040 exit(-1);
0dc34c77 1041}