]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/lsns.c
lsns: show namespaces only kept alive by open file descriptors
[thirdparty/util-linux.git] / sys-utils / lsns.c
1 /*
2 * SPDX-License-Identifier: GPL-2.0-or-later
3 *
4 * lsns(8) - list system namespaces
5 *
6 * Copyright (C) 2015 Karel Zak <kzak@redhat.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 */
13 #include <stdio.h>
14 #include <string.h>
15 #include <getopt.h>
16 #include <stdlib.h>
17 #include <assert.h>
18 #include <dirent.h>
19 #include <unistd.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <wchar.h>
23 #include <libsmartcols.h>
24 #include <libmount.h>
25 # include <stdbool.h>
26
27 #ifdef HAVE_LINUX_NET_NAMESPACE_H
28 # include <sys/socket.h>
29 # include <linux/netlink.h>
30 # include <linux/rtnetlink.h>
31 # include <linux/net_namespace.h>
32 #endif
33
34 #ifdef HAVE_LINUX_NSFS_H
35 # include <linux/nsfs.h>
36 # if defined(NS_GET_NSTYPE) && defined(NS_GET_OWNER_UID)
37 # define USE_NS_GET_API 1
38 # endif
39 #endif
40
41 #include "pathnames.h"
42 #include "nls.h"
43 #include "xalloc.h"
44 #include "c.h"
45 #include "list.h"
46 #include "closestream.h"
47 #include "optutils.h"
48 #include "procfs.h"
49 #include "strutils.h"
50 #include "namespace.h"
51 #include "idcache.h"
52 #include "fileutils.h"
53 #include "column-list-table.h"
54
55 #include "debug.h"
56
57 static UL_DEBUG_DEFINE_MASK(lsns);
58 UL_DEBUG_DEFINE_MASKNAMES(lsns) = UL_DEBUG_EMPTY_MASKNAMES;
59
60 #define LSNS_DEBUG_INIT (1 << 1)
61 #define LSNS_DEBUG_PROC (1 << 2)
62 #define LSNS_DEBUG_NS (1 << 3)
63 #define LSNS_DEBUG_FILTER (1 << 4)
64 #define LSNS_DEBUG_ALL 0xFFFF
65
66 #define LSNS_NETNS_UNUSABLE -2
67
68 #define DBG(m, x) __UL_DBG(lsns, LSNS_DEBUG_, m, x)
69 #define ON_DBG(m, x) __UL_DBG_CALL(lsns, LSNS_DEBUG_, m, x)
70
71 #define lsns_ioctl(fildes, request, ...) __extension__ ({ \
72 int ret = ioctl(fildes, request, ##__VA_ARGS__); \
73 if (ret == -1 && errno == ENOTTY) \
74 warnx("Unsupported ioctl %s", #request); \
75 ret; })
76
77 #define UL_DEBUG_CURRENT_MASK UL_DEBUG_MASK(lsns)
78 #include "debugobj.h"
79
80 #define EXIT_UNSUPPORTED_IOCTL 2
81
82 static struct idcache *uid_cache = NULL;
83
84 /* column IDs */
85 enum {
86 COL_NS = 0,
87 COL_TYPE,
88 COL_PATH,
89 COL_NPROCS,
90 COL_PID,
91 COL_PPID,
92 COL_COMMAND,
93 COL_UID,
94 COL_USER,
95 COL_NETNSID,
96 COL_NSFS,
97 COL_PNS, /* parent namespace */
98 COL_ONS, /* owner namespace */
99 };
100
101 /* column names */
102 struct colinfo {
103 const char *name; /* header */
104 double whint; /* width hint (N < 1 is in percent of termwidth) */
105 int flags; /* SCOLS_FL_* */
106 const char *help;
107 int json_type;
108 };
109
110 /* columns descriptions */
111 static const struct colinfo infos[] = {
112 [COL_NS] = { "NS", 10, SCOLS_FL_RIGHT, N_("namespace identifier (inode number)"), SCOLS_JSON_NUMBER },
113 [COL_TYPE] = { "TYPE", 5, 0, N_("kind of namespace") },
114 [COL_PATH] = { "PATH", 0, 0, N_("path to the namespace")},
115 [COL_NPROCS] = { "NPROCS", 5, SCOLS_FL_RIGHT, N_("number of processes in the namespace"), SCOLS_JSON_NUMBER },
116 [COL_PID] = { "PID", 5, SCOLS_FL_RIGHT, N_("lowest PID in the namespace"), SCOLS_JSON_NUMBER },
117 [COL_PPID] = { "PPID", 5, SCOLS_FL_RIGHT, N_("PPID of the PID"), SCOLS_JSON_NUMBER },
118 [COL_COMMAND] = { "COMMAND", 0, SCOLS_FL_TRUNC, N_("command line of the PID")},
119 [COL_UID] = { "UID", 0, SCOLS_FL_RIGHT, N_("UID of the PID"), SCOLS_JSON_NUMBER},
120 [COL_USER] = { "USER", 0, 0, N_("username of the PID")},
121 [COL_NETNSID] = { "NETNSID", 0, SCOLS_FL_RIGHT, N_("namespace ID as used by network subsystem")},
122 [COL_NSFS] = { "NSFS", 0, SCOLS_FL_WRAP, N_("nsfs mountpoint (usually used network subsystem)")},
123 [COL_PNS] = { "PNS", 10, SCOLS_FL_RIGHT, N_("parent namespace identifier (inode number)"), SCOLS_JSON_NUMBER },
124 [COL_ONS] = { "ONS", 10, SCOLS_FL_RIGHT, N_("owner namespace identifier (inode number)"), SCOLS_JSON_NUMBER },
125 };
126
127 static int columns[ARRAY_SIZE(infos) * 2];
128 static size_t ncolumns;
129
130 enum {
131 LSNS_ID_MNT = 0,
132 LSNS_ID_NET,
133 LSNS_ID_PID,
134 LSNS_ID_UTS,
135 LSNS_ID_IPC,
136 LSNS_ID_USER,
137 LSNS_ID_CGROUP,
138 LSNS_ID_TIME
139 };
140
141 static char *ns_names[] = {
142 [LSNS_ID_MNT] = "mnt",
143 [LSNS_ID_NET] = "net",
144 [LSNS_ID_PID] = "pid",
145 [LSNS_ID_UTS] = "uts",
146 [LSNS_ID_IPC] = "ipc",
147 [LSNS_ID_USER] = "user",
148 [LSNS_ID_CGROUP] = "cgroup",
149 [LSNS_ID_TIME] = "time"
150 };
151
152 enum {
153 RELA_PARENT,
154 RELA_OWNER,
155 MAX_RELA
156 };
157
158 struct lsns_namespace {
159 ino_t id;
160 int type; /* LSNS_* */
161 int nprocs;
162 int netnsid;
163 ino_t related_id[MAX_RELA];
164
165 struct lsns_process *proc;
166
167 struct lsns_namespace *related_ns[MAX_RELA];
168 struct libscols_line *ns_outline;
169 uid_t uid_fallback; /* refer this member if `proc' is NULL. */
170
171 struct list_head namespaces; /* lsns->processes member */
172 struct list_head processes; /* head of lsns_process *siblings */
173 };
174
175 struct lsns_process {
176 pid_t pid; /* process PID */
177 pid_t ppid; /* parent's PID */
178 pid_t tpid; /* thread group */
179 char state;
180 uid_t uid;
181
182 ino_t ns_ids[ARRAY_SIZE(ns_names)];
183 ino_t ns_pids[ARRAY_SIZE(ns_names)];
184 ino_t ns_oids[ARRAY_SIZE(ns_names)];
185
186 struct list_head ns_siblings[ARRAY_SIZE(ns_names)];
187
188 struct list_head processes; /* list of processes */
189
190 struct libscols_line *outline;
191 struct lsns_process *parent;
192
193 int netnsid;
194 };
195
196
197 enum {
198 LSNS_TREE_NONE,
199 LSNS_TREE_PROCESS,
200 LSNS_TREE_OWNER,
201 LSNS_TREE_PARENT,
202 };
203
204 struct lsns {
205 struct list_head processes;
206 struct list_head namespaces;
207
208 pid_t fltr_pid; /* filter out by PID */
209 ino_t fltr_ns; /* filter out by namespace */
210 int fltr_types[ARRAY_SIZE(ns_names)];
211 int fltr_ntypes;
212
213 unsigned int raw : 1,
214 json : 1,
215 tree : 2,
216 persist : 1,
217 no_trunc : 1,
218 no_headings: 1,
219 no_wrap : 1;
220
221 dev_t nsfs_dev;
222
223 struct libmnt_table *tab;
224 struct libscols_filter *filter;
225 };
226
227 struct netnsid_cache {
228 ino_t ino;
229 int id;
230 struct list_head netnsids;
231 };
232
233 /* "userdata" used by callback for libsmartcols filter */
234 struct filler_data {
235 struct lsns *ls;
236 struct lsns_namespace *ns;
237 struct lsns_process *proc;
238 };
239
240 static struct list_head netnsids_cache;
241
242 static int netlink_fd = -1;
243
244 static void lsns_init_debug(void)
245 {
246 __UL_INIT_DEBUG_FROM_ENV(lsns, LSNS_DEBUG_, 0, LSNS_DEBUG);
247 }
248
249 static int ns_name2type(const char *name)
250 {
251 size_t i;
252
253 for (i = 0; i < ARRAY_SIZE(ns_names); i++) {
254 if (strcmp(ns_names[i], name) == 0)
255 return i;
256 }
257 return -1;
258 }
259
260 static int column_name_to_id(const char *name, size_t namesz)
261 {
262 size_t i;
263
264 assert(name);
265
266 for (i = 0; i < ARRAY_SIZE(infos); i++) {
267 const char *cn = infos[i].name;
268
269 if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
270 return i;
271 }
272 warnx(_("unknown column: %s"), name);
273 return -1;
274 }
275
276 static int has_column(int id)
277 {
278 size_t i;
279
280 for (i = 0; i < ncolumns; i++) {
281 if (columns[i] == id)
282 return 1;
283 }
284 return 0;
285 }
286
287 static inline int get_column_id(int num)
288 {
289 assert(num >= 0);
290 assert((size_t) num < ncolumns);
291 assert(columns[num] < (int) ARRAY_SIZE(infos));
292
293 return columns[num];
294 }
295
296 static inline const struct colinfo *get_column_info(unsigned num)
297 {
298 return &infos[ get_column_id(num) ];
299 }
300
301 static int get_ns_ino(struct path_cxt *pc, const char *nsname, ino_t *ino, ino_t *pino, ino_t *oino)
302 {
303 struct stat st;
304 char path[16];
305
306 snprintf(path, sizeof(path), "ns/%s", nsname);
307
308 if (ul_path_stat(pc, &st, 0, path) != 0)
309 return -errno;
310 *ino = st.st_ino;
311
312 *pino = 0;
313 *oino = 0;
314
315 #ifdef USE_NS_GET_API
316 int fd, pfd, ofd;
317 fd = ul_path_open(pc, 0, path);
318 if (fd < 0)
319 return -errno;
320 if (strcmp(nsname, "pid") == 0 || strcmp(nsname, "user") == 0) {
321 if ((pfd = lsns_ioctl(fd, NS_GET_PARENT)) < 0) {
322 if (errno == EPERM)
323 goto user;
324 close(fd);
325 return -errno;
326 }
327 if (fstat(pfd, &st) < 0) {
328 close(pfd);
329 close(fd);
330 return -errno;
331 }
332 *pino = st.st_ino;
333 close(pfd);
334 }
335 user:
336 if ((ofd = lsns_ioctl(fd, NS_GET_USERNS)) < 0) {
337 if (errno == EPERM)
338 goto out;
339 close(fd);
340 return -errno;
341 }
342 if (fstat(ofd, &st) < 0) {
343 close(ofd);
344 close(fd);
345 return -errno;
346 }
347 *oino = st.st_ino;
348 close(ofd);
349 out:
350 close(fd);
351 #endif
352 return 0;
353 }
354
355 static int parse_proc_stat(char *line, pid_t *pid, char *state, pid_t *ppid)
356 {
357 char *p;
358 int rc;
359
360 p = strrchr(line, ')');
361 if (p == NULL ||
362 sscanf(line, "%d (", pid) != 1 ||
363 sscanf(p, ") %c %d*[^\n]", state, ppid) != 2) {
364 rc = -EINVAL;
365 goto error;
366 }
367 rc = 0;
368
369 error:
370 return rc;
371 }
372
373 #ifdef HAVE_LINUX_NET_NAMESPACE_H
374 static int netnsid_cache_find(ino_t netino, int *netnsid)
375 {
376 struct list_head *p;
377
378 list_for_each(p, &netnsids_cache) {
379 struct netnsid_cache *e = list_entry(p,
380 struct netnsid_cache,
381 netnsids);
382 if (e->ino == netino) {
383 *netnsid = e->id;
384 return 1;
385 }
386 }
387
388 return 0;
389 }
390
391 static void netnsid_cache_add(ino_t netino, int netnsid)
392 {
393 struct netnsid_cache *e;
394
395 e = xcalloc(1, sizeof(*e));
396 e->ino = netino;
397 e->id = netnsid;
398 INIT_LIST_HEAD(&e->netnsids);
399 list_add(&e->netnsids, &netnsids_cache);
400 }
401
402 static int get_netnsid_via_netlink_send_request(int target_fd)
403 {
404 unsigned char req[NLMSG_SPACE(sizeof(struct rtgenmsg))
405 + RTA_SPACE(sizeof(int32_t))];
406
407 struct nlmsghdr *nlh = (struct nlmsghdr *)req;
408 struct rtgenmsg *rt = NLMSG_DATA(req);
409 struct rtattr *rta = (struct rtattr *)
410 (req + NLMSG_SPACE(sizeof(struct rtgenmsg)));
411 int32_t *fd = RTA_DATA(rta);
412
413 nlh->nlmsg_len = sizeof(req);
414 nlh->nlmsg_flags = NLM_F_REQUEST;
415 nlh->nlmsg_type = RTM_GETNSID;
416 rt->rtgen_family = AF_UNSPEC;
417 rta->rta_type = NETNSA_FD;
418 rta->rta_len = RTA_SPACE(sizeof(int32_t));
419 *fd = target_fd;
420
421 if (send(netlink_fd, req, sizeof(req), 0) < 0)
422 return -1;
423 return 0;
424 }
425
426 static int get_netnsid_via_netlink_recv_response(int *netnsid)
427 {
428 unsigned char res[NLMSG_SPACE(sizeof(struct rtgenmsg))
429 + ((RTA_SPACE(sizeof(int32_t))
430 < RTA_SPACE(sizeof(struct nlmsgerr)))
431 ? RTA_SPACE(sizeof(struct nlmsgerr))
432 : RTA_SPACE(sizeof(int32_t)))];
433 int rtalen;
434 ssize_t reslen;
435
436 struct nlmsghdr *nlh;
437 struct rtattr *rta;
438
439 reslen = recv(netlink_fd, res, sizeof(res), 0);
440 if (reslen < 0)
441 return -1;
442
443 nlh = (struct nlmsghdr *)res;
444 if (!(NLMSG_OK(nlh, (size_t)reslen)
445 && nlh->nlmsg_type == RTM_NEWNSID))
446 return -1;
447
448 rtalen = NLMSG_PAYLOAD(nlh, sizeof(struct rtgenmsg));
449 rta = (struct rtattr *)(res + NLMSG_SPACE(sizeof(struct rtgenmsg)));
450 if (!(RTA_OK(rta, rtalen)
451 && rta->rta_type == NETNSA_NSID))
452 return -1;
453
454 *netnsid = *(int *)RTA_DATA(rta);
455
456 return 0;
457 }
458
459 static int get_netnsid_via_netlink(struct path_cxt *pc, const char *path)
460 {
461 int netnsid;
462 int target_fd;
463
464 if (netlink_fd < 0)
465 return LSNS_NETNS_UNUSABLE;
466
467 target_fd = ul_path_open(pc, O_RDONLY, path);
468 if (target_fd < 0)
469 return LSNS_NETNS_UNUSABLE;
470
471 if (get_netnsid_via_netlink_send_request(target_fd) < 0) {
472 netnsid = LSNS_NETNS_UNUSABLE;
473 goto out;
474 }
475
476 if (get_netnsid_via_netlink_recv_response(&netnsid) < 0) {
477 netnsid = LSNS_NETNS_UNUSABLE;
478 goto out;
479 }
480
481 out:
482 close(target_fd);
483 return netnsid;
484 }
485
486 static int get_netnsid(struct path_cxt *pc, ino_t netino)
487 {
488 int netnsid;
489
490 if (!netnsid_cache_find(netino, &netnsid)) {
491 netnsid = get_netnsid_via_netlink(pc, "ns/net");
492 netnsid_cache_add(netino, netnsid);
493 }
494
495 return netnsid;
496 }
497 #else
498 static int get_netnsid(struct path_cxt *pc __attribute__((__unused__)),
499 ino_t netino __attribute__((__unused__)))
500 {
501 return LSNS_NETNS_UNUSABLE;
502 }
503 #endif /* HAVE_LINUX_NET_NAMESPACE_H */
504
505 static struct lsns_namespace *add_namespace_for_nsfd(struct lsns *ls, int fd, ino_t ino);
506
507 static void read_open_ns_inos(struct lsns *ls, struct path_cxt *pc)
508 {
509 DIR *sub = NULL;
510 struct dirent *d = NULL;
511 char path[sizeof("fd/") + sizeof(stringify_value(UINT64_MAX))];
512
513 while (ul_path_next_dirent(pc, &sub, "fd", &d) == 0) {
514 uint64_t num;
515 struct stat st;
516
517 if (ul_strtou64(d->d_name, &num, 10) != 0) /* only numbers */
518 continue;
519
520 snprintf(path, sizeof(path), "fd/%ju", (uintmax_t) num);
521 ul_path_stat(pc, &st, 0, path);
522 if (st.st_dev == ls->nsfs_dev) {
523 int fd = ul_path_open(pc, O_RDONLY, path);
524 if (fd >= 0) {
525 add_namespace_for_nsfd(ls, fd, st.st_ino);
526 close(fd);
527 }
528 }
529 }
530 }
531
532 static int read_process(struct lsns *ls, struct path_cxt *pc)
533 {
534 struct lsns_process *p = NULL;
535 int rc = 0;
536 char buf[BUFSIZ];
537 size_t i;
538
539 p = xcalloc(1, sizeof(*p));
540 p->netnsid = LSNS_NETNS_UNUSABLE;
541
542 if (procfs_process_get_uid(pc, &p->uid) == 0)
543 add_uid(uid_cache, p->uid);
544
545 if ((rc = procfs_process_get_stat(pc, buf, sizeof(buf))) < 0)
546 goto done;
547 if ((rc = parse_proc_stat(buf, &p->pid, &p->state, &p->ppid)) < 0)
548 goto done;
549 rc = 0;
550
551 for (i = 0; i < ARRAY_SIZE(p->ns_ids); i++) {
552 INIT_LIST_HEAD(&p->ns_siblings[i]);
553
554 if (!ls->fltr_types[i])
555 continue;
556
557 rc = get_ns_ino(pc, ns_names[i], &p->ns_ids[i],
558 &p->ns_pids[i], &p->ns_oids[i]);
559 if (rc && rc != -EACCES && rc != -ENOENT)
560 goto done;
561 if (i == LSNS_ID_NET)
562 p->netnsid = get_netnsid(pc, p->ns_ids[i]);
563 rc = 0;
564 }
565
566 INIT_LIST_HEAD(&p->processes);
567
568 DBG(PROC, ul_debugobj(p, "new pid=%d", p->pid));
569 list_add_tail(&p->processes, &ls->processes);
570
571 read_open_ns_inos(ls, pc);
572 done:
573 if (rc)
574 free(p);
575 return rc;
576 }
577
578 static int read_processes(struct lsns *ls)
579 {
580 DIR *dir;
581 struct dirent *d;
582 int rc = 0;
583 struct path_cxt *pc;
584
585 DBG(PROC, ul_debug("opening /proc"));
586
587 dir = opendir(_PATH_PROC);
588 if (!dir)
589 return -errno;
590
591 pc = ul_new_path(NULL);
592 if (!pc)
593 err(EXIT_FAILURE, _("failed to alloc procfs handler"));
594
595 while ((d = xreaddir(dir))) {
596 pid_t pid = 0;
597
598 if (procfs_dirent_get_pid(d, &pid) != 0)
599 continue;
600
601 DBG(PROC, ul_debug("reading %d", (int) pid));
602 rc = procfs_process_init_path(pc, pid);
603 if (rc < 0) {
604 DBG(PROC, ul_debug("failed in reading /proc/%d", (int) pid));
605 continue;
606 }
607
608 rc = read_process(ls, pc);
609 if (rc && rc != -EACCES && rc != -ENOENT)
610 break;
611 rc = 0;
612 }
613
614 ul_unref_path(pc);
615
616 DBG(PROC, ul_debug("closing /proc"));
617 closedir(dir);
618 return rc;
619 }
620
621 static struct lsns_namespace *get_namespace(struct lsns *ls, ino_t ino)
622 {
623 struct list_head *p;
624
625 list_for_each(p, &ls->namespaces) {
626 struct lsns_namespace *ns = list_entry(p, struct lsns_namespace, namespaces);
627
628 if (ns->id == ino)
629 return ns;
630 }
631 return NULL;
632 }
633
634 static int namespace_has_process(struct lsns_namespace *ns, pid_t pid)
635 {
636 struct list_head *p;
637
638 list_for_each(p, &ns->processes) {
639 struct lsns_process *proc = list_entry(p, struct lsns_process, ns_siblings[ns->type]);
640
641 if (proc->pid == pid)
642 return 1;
643 }
644 return 0;
645 }
646
647 static struct lsns_namespace *add_namespace(struct lsns *ls, int type, ino_t ino,
648 ino_t parent_ino, ino_t owner_ino)
649 {
650 struct lsns_namespace *ns = xcalloc(1, sizeof(*ns));
651
652 if (!ns)
653 return NULL;
654
655 DBG(NS, ul_debugobj(ns, "new %s[%ju]", ns_names[type], (uintmax_t)ino));
656
657 INIT_LIST_HEAD(&ns->processes);
658 INIT_LIST_HEAD(&ns->namespaces);
659
660 ns->type = type;
661 ns->id = ino;
662 ns->related_id[RELA_PARENT] = parent_ino;
663 ns->related_id[RELA_OWNER] = owner_ino;
664
665 list_add_tail(&ns->namespaces, &ls->namespaces);
666 return ns;
667 }
668
669 static int add_process_to_namespace(struct lsns *ls, struct lsns_namespace *ns, struct lsns_process *proc)
670 {
671 struct list_head *p;
672
673 DBG(NS, ul_debugobj(ns, "add process [%p] pid=%d to %s[%ju]",
674 proc, proc->pid, ns_names[ns->type], (uintmax_t)ns->id));
675
676 list_for_each(p, &ls->processes) {
677 struct lsns_process *xproc = list_entry(p, struct lsns_process, processes);
678
679 if (xproc->pid == proc->ppid) /* my parent */
680 proc->parent = xproc;
681 else if (xproc->ppid == proc->pid) /* my child */
682 xproc->parent = proc;
683 }
684
685 list_add_tail(&proc->ns_siblings[ns->type], &ns->processes);
686 ns->nprocs++;
687
688 if (!ns->proc || ns->proc->pid > proc->pid)
689 ns->proc = proc;
690
691 return 0;
692 }
693
694 static int cmp_namespaces(struct list_head *a, struct list_head *b,
695 __attribute__((__unused__)) void *data)
696 {
697 struct lsns_namespace *xa = list_entry(a, struct lsns_namespace, namespaces),
698 *xb = list_entry(b, struct lsns_namespace, namespaces);
699
700 return cmp_numbers(xa->id, xb->id);
701 }
702
703 static int netnsid_xasputs(char **str, int netnsid)
704 {
705 if (netnsid >= 0)
706 return xasprintf(str, "%d", netnsid);
707 #ifdef NETNSA_NSID_NOT_ASSIGNED
708 if (netnsid == NETNSA_NSID_NOT_ASSIGNED)
709 return xasprintf(str, "%s", "unassigned");
710 #endif
711 return 0;
712 }
713
714 #ifdef USE_NS_GET_API
715 static int clone_type_to_lsns_type(int clone_type)
716 {
717 switch (clone_type) {
718 case CLONE_NEWNS:
719 return LSNS_ID_MNT;
720 case CLONE_NEWCGROUP:
721 return LSNS_ID_CGROUP;
722 case CLONE_NEWUTS:
723 return LSNS_ID_UTS;
724 case CLONE_NEWIPC:
725 return LSNS_ID_IPC;
726 case CLONE_NEWUSER:
727 return LSNS_ID_USER;
728 case CLONE_NEWPID:
729 return LSNS_ID_PID;
730 case CLONE_NEWNET:
731 return LSNS_ID_NET;
732 #ifdef CLONE_NEWTIME
733 case CLONE_NEWTIME:
734 return LSNS_ID_TIME;
735 #endif
736 default:
737 return -1;
738 }
739 }
740
741 static struct lsns_namespace *add_namespace_for_nsfd(struct lsns *ls, int fd, ino_t ino)
742 {
743 int fd_owner = -1, fd_parent = -1;
744 struct stat st_owner, st_parent;
745 ino_t ino_owner = 0, ino_parent = 0;
746 struct lsns_namespace *ns;
747 int clone_type, lsns_type;
748
749 clone_type = lsns_ioctl(fd, NS_GET_NSTYPE);
750 if (clone_type < 0)
751 return NULL;
752 lsns_type = clone_type_to_lsns_type(clone_type);
753 if (lsns_type < 0 || ls->fltr_types[lsns_type] == 0)
754 return NULL;
755
756 fd_owner = lsns_ioctl(fd, NS_GET_USERNS);
757 if (fd_owner < 0)
758 goto parent;
759 if (fstat(fd_owner, &st_owner) < 0)
760 goto parent;
761 ino_owner = st_owner.st_ino;
762
763 parent:
764 fd_parent = lsns_ioctl(fd, NS_GET_PARENT);
765 if (fd_parent < 0)
766 goto add_ns;
767 if (fstat(fd_parent, &st_parent) < 0)
768 goto add_ns;
769 ino_parent = st_parent.st_ino;
770
771 add_ns:
772 ns = add_namespace(ls, lsns_type, ino, ino_parent, ino_owner);
773 lsns_ioctl(fd, NS_GET_OWNER_UID, &ns->uid_fallback);
774 add_uid(uid_cache, ns->uid_fallback);
775
776 if ((lsns_type == LSNS_ID_USER || lsns_type == LSNS_ID_PID)
777 && ino_parent != ino && ino_parent != 0) {
778 ns->related_ns[RELA_PARENT] = get_namespace(ls, ino_parent);
779 if (!ns->related_ns[RELA_PARENT]) {
780 ns->related_ns[RELA_PARENT] = add_namespace_for_nsfd(ls, fd_parent, ino_parent);
781 if (ino_parent == ino_owner)
782 ns->related_ns[RELA_OWNER] = ns->related_ns[RELA_PARENT];
783 }
784 }
785
786 if (ns->related_ns[RELA_OWNER] == NULL && ino_owner != 0) {
787 ns->related_ns[RELA_OWNER] = get_namespace(ls, ino_owner);
788 if (!ns->related_ns[RELA_OWNER])
789 ns->related_ns[RELA_OWNER] = add_namespace_for_nsfd(ls, fd_owner, ino_owner);
790 }
791
792 if (fd_owner >= 0)
793 close(fd_owner);
794 if (fd_parent >= 0)
795 close(fd_parent);
796
797 return ns;
798 }
799
800 static void interpolate_missing_namespaces(struct lsns *ls, struct lsns_namespace *orphan, int rela)
801 {
802 const int cmd[MAX_RELA] = {
803 [RELA_PARENT] = NS_GET_PARENT,
804 [RELA_OWNER] = NS_GET_USERNS
805 };
806 char buf[BUFSIZ];
807 int fd_orphan, fd_missing;
808 struct stat st;
809
810 orphan->related_ns[rela] = get_namespace(ls, orphan->related_id[rela]);
811 if (orphan->related_ns[rela])
812 return;
813
814 snprintf(buf, sizeof(buf), "/proc/%d/ns/%s", orphan->proc->pid, ns_names[orphan->type]);
815 fd_orphan = open(buf, O_RDONLY);
816 if (fd_orphan < 0)
817 return;
818
819 fd_missing = lsns_ioctl(fd_orphan, cmd[rela]);
820 close(fd_orphan);
821 if (fd_missing < 0)
822 return;
823
824 if (fstat(fd_missing, &st) < 0
825 || st.st_ino != orphan->related_id[rela]) {
826 close(fd_missing);
827 return;
828 }
829
830 orphan->related_ns[rela] = add_namespace_for_nsfd(ls, fd_missing, orphan->related_id[rela]);
831 close(fd_missing);
832 }
833
834 static void read_related_namespaces(struct lsns *ls)
835 {
836 struct list_head *p;
837 struct lsns_namespace *orphan[2] = {NULL, NULL};
838 int rela;
839
840 list_for_each(p, &ls->namespaces) {
841 struct lsns_namespace *ns = list_entry(p, struct lsns_namespace, namespaces);
842 struct list_head *pp;
843 list_for_each(pp, &ls->namespaces) {
844 struct lsns_namespace *pns = list_entry(pp, struct lsns_namespace, namespaces);
845 if (ns->type == LSNS_ID_USER
846 || ns->type == LSNS_ID_PID) {
847 if (ns->related_id[RELA_PARENT] == pns->id)
848 ns->related_ns[RELA_PARENT] = pns;
849 if (ns->related_id[RELA_OWNER] == pns->id)
850 ns->related_ns[RELA_OWNER] = pns;
851 if (ns->related_ns[RELA_PARENT] && ns->related_ns[RELA_OWNER])
852 break;
853 } else {
854 if (ns->related_id[RELA_OWNER] == pns->id) {
855 ns->related_ns[RELA_OWNER] = pns;
856 break;
857 }
858 }
859 }
860
861 /* lsns scans /proc/[0-9]+ for finding namespaces.
862 * So if a namespace has no process, lsns cannot
863 * find it. Here we call it a missing namespace.
864 *
865 * If the id for a related namesspce is known but
866 * namespace for the id is not found, there must
867 * be orphan namespaces. A missing namespace is an
868 * owner or a parent of the orphan namespace.
869 */
870 for (rela = 0; rela < MAX_RELA; rela++) {
871 if (ns->related_id[rela] != 0
872 && ns->related_ns[rela] == NULL) {
873 ns->related_ns[rela] = orphan[rela];
874 orphan[rela] = ns;
875 }
876 }
877 }
878
879 for (rela = 0; rela < MAX_RELA; rela++) {
880 while (orphan[rela]) {
881 struct lsns_namespace *current = orphan[rela];
882 orphan[rela] = orphan[rela]->related_ns[rela];
883 current->related_ns[rela] = NULL;
884 interpolate_missing_namespaces(ls, current, rela);
885 }
886 }
887 }
888
889 static int read_persistent_namespaces(struct lsns *ls)
890 {
891 struct libmnt_iter *itr = mnt_new_iter(MNT_ITER_FORWARD);
892 struct libmnt_fs *fs = NULL;
893
894 while (mnt_table_next_fs(ls->tab, itr, &fs) == 0) {
895 const char *root;
896 char *p, *end = NULL;
897 ino_t ino;
898 int fd;
899
900 if (!mnt_fs_match_fstype(fs, "nsfs"))
901 continue;
902 root = mnt_fs_get_root(fs);
903 if (!root || !(p = strchr(root, '[')))
904 continue;
905
906 errno = 0;
907 ino = strtoumax(++p, &end, 10);
908 if (!end || *end != ']' || errno != 0)
909 continue;
910 if (get_namespace(ls, ino))
911 continue;
912
913 fd = open(mnt_fs_get_target(fs), O_RDONLY);
914 if (fd < 0)
915 continue;
916
917 add_namespace_for_nsfd(ls, fd, ino);
918 close(fd);
919 }
920
921 mnt_free_iter(itr);
922 return 0;
923 }
924
925 #endif /* USE_NS_GET_API */
926
927 static int read_namespaces(struct lsns *ls)
928 {
929 struct list_head *p;
930
931 DBG(NS, ul_debug("reading namespace"));
932
933 list_for_each(p, &ls->processes) {
934 size_t i;
935 struct lsns_namespace *ns;
936 struct lsns_process *proc = list_entry(p, struct lsns_process, processes);
937
938 for (i = 0; i < ARRAY_SIZE(proc->ns_ids); i++) {
939 if (proc->ns_ids[i] == 0)
940 continue;
941 if (!(ns = get_namespace(ls, proc->ns_ids[i]))) {
942 ns = add_namespace(ls, i, proc->ns_ids[i],
943 proc->ns_pids[i], proc->ns_oids[i]);
944 if (!ns)
945 return -ENOMEM;
946 }
947 add_process_to_namespace(ls, ns, proc);
948 }
949 }
950
951 #ifdef USE_NS_GET_API
952 read_persistent_namespaces(ls);
953
954 if (ls->tree == LSNS_TREE_OWNER || ls->tree == LSNS_TREE_PARENT)
955 read_related_namespaces(ls);
956 #endif
957 list_sort(&ls->namespaces, cmp_namespaces, NULL);
958
959 return 0;
960 }
961
962 static int is_nsfs_root(struct libmnt_fs *fs, void *data)
963 {
964 if (!mnt_fs_match_fstype(fs, "nsfs") || !mnt_fs_get_root(fs))
965 return 0;
966
967 return (strcmp(mnt_fs_get_root(fs), (char *)data) == 0);
968 }
969
970 static int is_path_included(const char *path_set, const char *elt,
971 const char sep)
972 {
973 size_t elt_len;
974 size_t path_set_len;
975 char *tmp;
976
977
978 tmp = strstr(path_set, elt);
979 if (!tmp)
980 return 0;
981
982 elt_len = strlen(elt);
983 path_set_len = strlen(path_set);
984
985 /* path_set includes only elt or
986 * path_set includes elt as the first element.
987 */
988 if (tmp == path_set
989 && ((path_set_len == elt_len)
990 || (path_set[elt_len] == sep)))
991 return 1;
992
993 /* path_set includes elt at the middle
994 * or as the last element.
995 */
996 if ((*(tmp - 1) == sep)
997 && ((*(tmp + elt_len) == sep)
998 || (*(tmp + elt_len) == '\0')))
999 return 1;
1000
1001 return 0;
1002 }
1003
1004 static int nsfs_xasputs(char **str,
1005 struct lsns_namespace *ns,
1006 struct libmnt_table *tab,
1007 char sep)
1008 {
1009 struct libmnt_iter *itr = mnt_new_iter(MNT_ITER_FORWARD);
1010 char *expected_root;
1011 struct libmnt_fs *fs = NULL;
1012
1013 xasprintf(&expected_root, "%s:[%ju]", ns_names[ns->type], (uintmax_t)ns->id);
1014 *str = NULL;
1015
1016 while (mnt_table_find_next_fs(tab, itr, is_nsfs_root,
1017 expected_root, &fs) == 0) {
1018
1019 const char *tgt = mnt_fs_get_target(fs);
1020
1021 if (!*str)
1022 xasprintf(str, "%s", tgt);
1023
1024 else if (!is_path_included(*str, tgt, sep)) {
1025 char *tmp = NULL;
1026
1027 xasprintf(&tmp, "%s%c%s", *str, sep, tgt);
1028 free(*str);
1029 *str = tmp;
1030 }
1031 }
1032 free(expected_root);
1033 mnt_free_iter(itr);
1034
1035 return 1;
1036 }
1037
1038 static void fill_column(struct lsns *ls,
1039 struct lsns_namespace *ns,
1040 struct lsns_process *proc,
1041 struct libscols_line *line,
1042 size_t column_index)
1043 {
1044 char *str = NULL;
1045
1046 switch (get_column_id(column_index)) {
1047 case COL_NS:
1048 xasprintf(&str, "%ju", (uintmax_t)ns->id);
1049 break;
1050 case COL_PID:
1051 if (proc)
1052 xasprintf(&str, "%d", (int) proc->pid);
1053 break;
1054 case COL_PPID:
1055 if (proc)
1056 xasprintf(&str, "%d", (int) proc->ppid);
1057 break;
1058 case COL_TYPE:
1059 xasprintf(&str, "%s", ns_names[ns->type]);
1060 break;
1061 case COL_NPROCS:
1062 xasprintf(&str, "%d", ns->nprocs);
1063 break;
1064 case COL_COMMAND:
1065 if (!proc)
1066 break;
1067 str = pid_get_cmdline(proc->pid);
1068 if (!str)
1069 str = pid_get_cmdname(proc->pid);
1070 break;
1071 case COL_PATH:
1072 if (!proc)
1073 break;
1074 xasprintf(&str, "/proc/%d/ns/%s", (int) proc->pid, ns_names[ns->type]);
1075 break;
1076 case COL_UID:
1077 xasprintf(&str, "%d", proc? (int) proc->uid: (int) ns->uid_fallback);
1078 break;
1079 case COL_USER:
1080 xasprintf(&str, "%s", get_id(uid_cache, proc? proc->uid: ns->uid_fallback)->name);
1081 break;
1082 case COL_NETNSID:
1083 if (!proc)
1084 break;
1085 if (ns->type == LSNS_ID_NET)
1086 netnsid_xasputs(&str, proc->netnsid);
1087 break;
1088 case COL_NSFS:
1089 nsfs_xasputs(&str, ns, ls->tab, ls->no_wrap ? ',' : '\n');
1090 break;
1091 case COL_PNS:
1092 xasprintf(&str, "%ju", (uintmax_t)ns->related_id[RELA_PARENT]);
1093 break;
1094 case COL_ONS:
1095 xasprintf(&str, "%ju", (uintmax_t)ns->related_id[RELA_OWNER]);
1096 break;
1097 default:
1098 break;
1099 }
1100
1101 if (str && scols_line_refer_data(line, column_index, str) != 0)
1102 err_oom();
1103 }
1104
1105
1106 static int filter_filler_cb(
1107 struct libscols_filter *filter __attribute__((__unused__)),
1108 struct libscols_line *line,
1109 size_t column_index,
1110 void *userdata)
1111 {
1112 struct filler_data *fid = (struct filler_data *) userdata;
1113
1114 fill_column(fid->ls, fid->ns, fid->proc, line, column_index);
1115 return 0;
1116 }
1117
1118 static void add_scols_line(struct lsns *ls, struct libscols_table *table,
1119 struct lsns_namespace *ns, struct lsns_process *proc)
1120 {
1121 size_t i;
1122 struct libscols_line *line;
1123
1124 assert(ns);
1125 assert(table);
1126
1127 line = scols_table_new_line(table,
1128 (ls->tree == LSNS_TREE_PROCESS && proc) && proc->parent ? proc->parent->outline:
1129 (ls->tree == LSNS_TREE_PARENT) && ns->related_ns[RELA_PARENT] ? ns->related_ns[RELA_PARENT]->ns_outline:
1130 (ls->tree == LSNS_TREE_OWNER) && ns->related_ns[RELA_OWNER] ? ns->related_ns[RELA_OWNER]->ns_outline:
1131 NULL);
1132 if (!line) {
1133 warn(_("failed to add line to output"));
1134 return;
1135 }
1136
1137 if (ls->filter) {
1138 int status = 0;
1139 struct filler_data fid = {
1140 .ls = ls,
1141 .ns = ns,
1142 .proc = proc,
1143 };
1144
1145 scols_filter_set_filler_cb(ls->filter,
1146 filter_filler_cb, (void *) &fid);
1147
1148 if (scols_line_apply_filter(line, ls->filter, &status))
1149 err(EXIT_FAILURE, _("failed to apply filter"));
1150 if (status == 0) {
1151 struct libscols_line *x = scols_line_get_parent(line);
1152
1153 if (x)
1154 scols_line_remove_child(x, line);
1155
1156 scols_table_remove_line(table, line);
1157 return;
1158 }
1159 }
1160
1161 for (i = 0; i < ncolumns; i++) {
1162 if (scols_line_is_filled(line, i))
1163 continue;
1164 fill_column(ls, ns, proc, line, i);
1165 }
1166
1167 if (ls->tree == LSNS_TREE_OWNER || ls->tree == LSNS_TREE_PARENT)
1168 ns->ns_outline = line;
1169 else if (proc)
1170 proc->outline = line;
1171 }
1172
1173 static struct libscols_table *init_scols_table(struct lsns *ls)
1174 {
1175 struct libscols_table *tab;
1176 size_t i;
1177
1178 tab = scols_new_table();
1179 if (!tab) {
1180 warn(_("failed to initialize output table"));
1181 return NULL;
1182 }
1183
1184 scols_table_enable_raw(tab, ls->raw);
1185 scols_table_enable_json(tab, ls->json);
1186 scols_table_enable_noheadings(tab, ls->no_headings);
1187
1188 if (ls->json)
1189 scols_table_set_name(tab, "namespaces");
1190
1191 for (i = 0; i < ncolumns; i++) {
1192 const struct colinfo *col = get_column_info(i);
1193 int flags = col->flags;
1194 struct libscols_column *cl;
1195
1196 if (ls->no_trunc)
1197 flags &= ~SCOLS_FL_TRUNC;
1198 if (ls->tree == LSNS_TREE_PROCESS && get_column_id(i) == COL_COMMAND)
1199 flags |= SCOLS_FL_TREE;
1200 if (ls->no_wrap)
1201 flags &= ~SCOLS_FL_WRAP;
1202 if ((ls->tree == LSNS_TREE_OWNER || ls->tree == LSNS_TREE_PARENT)
1203 && get_column_id(i) == COL_NS) {
1204 flags |= SCOLS_FL_TREE;
1205 flags &= ~SCOLS_FL_RIGHT;
1206 }
1207
1208 cl = scols_table_new_column(tab, col->name, col->whint, flags);
1209 if (cl == NULL) {
1210 warnx(_("failed to initialize output column"));
1211 goto err;
1212 }
1213 if (ls->json || ls->filter)
1214 scols_column_set_json_type(cl, col->json_type);
1215
1216 if (!ls->no_wrap && get_column_id(i) == COL_NSFS) {
1217 scols_column_set_wrapfunc(cl,
1218 scols_wrapnl_chunksize,
1219 scols_wrapnl_nextchunk,
1220 NULL);
1221 scols_column_set_safechars(cl, "\n");
1222 }
1223 }
1224
1225 return tab;
1226 err:
1227 scols_unref_table(tab);
1228 return NULL;
1229 }
1230
1231 static void show_namespace(struct lsns *ls, struct libscols_table *tab,
1232 struct lsns_namespace *ns, struct lsns_process *proc)
1233 {
1234 /*
1235 * create a tree from owner->owned and/or parent->child relation
1236 */
1237 if (ls->tree == LSNS_TREE_OWNER
1238 && ns->related_ns[RELA_OWNER]
1239 && !ns->related_ns[RELA_OWNER]->ns_outline)
1240 show_namespace(ls, tab, ns->related_ns[RELA_OWNER], ns->related_ns[RELA_OWNER]->proc);
1241 else if (ls->tree == LSNS_TREE_PARENT) {
1242 if (ns->related_ns[RELA_PARENT]) {
1243 if (!ns->related_ns[RELA_PARENT]->ns_outline)
1244 show_namespace(ls, tab, ns->related_ns[RELA_PARENT], ns->related_ns[RELA_PARENT]->proc);
1245 }
1246 else if (ns->related_ns[RELA_OWNER] && !ns->related_ns[RELA_OWNER]->ns_outline)
1247 show_namespace(ls, tab, ns->related_ns[RELA_OWNER], ns->related_ns[RELA_OWNER]->proc);
1248 }
1249
1250 add_scols_line(ls, tab, ns, proc);
1251 }
1252
1253 static inline void add_column(int id)
1254 {
1255 if (ncolumns >= ARRAY_SIZE(columns))
1256 errx(EXIT_FAILURE, _("too many columns specified, "
1257 "the limit is %zu columns"),
1258 ARRAY_SIZE(columns) - 1);
1259 columns[ ncolumns++ ] = id;
1260 }
1261
1262 static void init_scols_filter(struct libscols_table *tb, struct libscols_filter *f)
1263 {
1264 struct libscols_iter *itr;
1265 const char *name = NULL;
1266 int nerrs = 0;
1267
1268 itr = scols_new_iter(SCOLS_ITER_FORWARD);
1269 if (!itr)
1270 err(EXIT_FAILURE, _("failed to allocate iterator"));
1271
1272 while (scols_filter_next_holder(f, itr, &name, 0) == 0) {
1273 struct libscols_column *col = scols_table_get_column_by_name(tb, name);
1274 int id = column_name_to_id(name, strlen(name));
1275 const struct colinfo *ci = id >= 0 ? &infos[id] : NULL;
1276
1277 if (!ci) {
1278 nerrs++;
1279 continue; /* report all unknown columns */
1280 }
1281 if (!col) {
1282 add_column(id);
1283 col = scols_table_new_column(tb, ci->name,
1284 ci->whint, SCOLS_FL_HIDDEN);
1285 if (!col)
1286 err(EXIT_FAILURE,_("failed to allocate output column"));
1287
1288 scols_column_set_json_type(col, ci->json_type);
1289 }
1290
1291 scols_filter_assign_column(f, itr, name, col);
1292 }
1293
1294 scols_free_iter(itr);
1295
1296 if (!nerrs)
1297 return;
1298
1299 errx(EXIT_FAILURE, _("failed to initialize filter"));
1300 }
1301
1302 static int show_namespaces(struct lsns *ls)
1303 {
1304 struct libscols_table *tab;
1305 struct list_head *p;
1306 int rc = 0;
1307
1308 tab = init_scols_table(ls);
1309 if (!tab)
1310 return -ENOMEM;
1311
1312 init_scols_filter(tab, ls->filter);
1313
1314 list_for_each(p, &ls->namespaces) {
1315 struct lsns_namespace *ns = list_entry(p, struct lsns_namespace, namespaces);
1316
1317 if (ls->fltr_pid != 0 && !namespace_has_process(ns, ls->fltr_pid))
1318 continue;
1319 if (ls->persist && ns->nprocs != 0)
1320 continue;
1321
1322 if (!ns->ns_outline)
1323 show_namespace(ls, tab, ns, ns->proc);
1324 }
1325
1326 scols_print_table(tab);
1327 scols_unref_table(tab);
1328 return rc;
1329 }
1330
1331 static void show_process(struct lsns *ls, struct libscols_table *tab,
1332 struct lsns_process *proc, struct lsns_namespace *ns)
1333 {
1334 /*
1335 * create a tree from parent->child relation, but only if the parent is
1336 * within the same namespace
1337 */
1338 if (ls->tree == LSNS_TREE_PROCESS
1339 && proc->parent
1340 && !proc->parent->outline
1341 && proc->parent->ns_ids[ns->type] == proc->ns_ids[ns->type])
1342 show_process(ls, tab, proc->parent, ns);
1343
1344 add_scols_line(ls, tab, ns, proc);
1345 }
1346
1347
1348 static int show_namespace_processes(struct lsns *ls, struct lsns_namespace *ns)
1349 {
1350 struct libscols_table *tab;
1351 struct list_head *p;
1352
1353 tab = init_scols_table(ls);
1354 if (!tab)
1355 return -ENOMEM;
1356
1357 list_for_each(p, &ns->processes) {
1358 struct lsns_process *proc = list_entry(p, struct lsns_process, ns_siblings[ns->type]);
1359
1360 if (!proc->outline)
1361 show_process(ls, tab, proc, ns);
1362 }
1363
1364
1365 scols_print_table(tab);
1366 scols_unref_table(tab);
1367 return 0;
1368 }
1369
1370 static void free_lsns_process(struct lsns_process *lsns_p)
1371 {
1372 free(lsns_p);
1373 }
1374
1375 static void free_netnsid_caches(struct netnsid_cache *cache)
1376 {
1377 free(cache);
1378 }
1379
1380 static void free_lsns_namespace(struct lsns_namespace *lsns_n)
1381 {
1382 free(lsns_n);
1383 }
1384
1385 static void free_all(struct lsns *ls)
1386 {
1387 list_free(&ls->processes, struct lsns_process, processes, free_lsns_process);
1388 list_free(&netnsids_cache, struct netnsid_cache, netnsids, free_netnsid_caches);
1389 list_free(&ls->namespaces, struct lsns_namespace, namespaces, free_lsns_namespace);
1390 }
1391
1392 static struct libscols_filter *new_filter(const char *query)
1393 {
1394 struct libscols_filter *f;
1395
1396 f = scols_new_filter(NULL);
1397 if (!f)
1398 err(EXIT_FAILURE, _("failed to allocate filter"));
1399 if (query && scols_filter_parse_string(f, query) != 0)
1400 errx(EXIT_FAILURE, _("failed to parse \"%s\": %s"), query,
1401 scols_filter_get_errmsg(f));
1402 return f;
1403 }
1404
1405 static void __attribute__((__noreturn__)) usage(void)
1406 {
1407 FILE *out = stdout;
1408
1409 fputs(USAGE_HEADER, out);
1410
1411 fprintf(out,
1412 _(" %s [options] [<namespace>]\n"), program_invocation_short_name);
1413
1414 fputs(USAGE_SEPARATOR, out);
1415 fputs(_("List system namespaces.\n"), out);
1416
1417 fputs(USAGE_OPTIONS, out);
1418 fputs(_(" -J, --json use JSON output format\n"), out);
1419 fputs(_(" -l, --list use list format output\n"), out);
1420 fputs(_(" -n, --noheadings don't print headings\n"), out);
1421 fputs(_(" -o, --output <list> define which output columns to use\n"), out);
1422 fputs(_(" --output-all output all columns\n"), out);
1423 fputs(_(" -P, --persistent namespaces without processes\n"), out);
1424 fputs(_(" -p, --task <pid> print process namespaces\n"), out);
1425 fputs(_(" -r, --raw use the raw output format\n"), out);
1426 fputs(_(" -u, --notruncate don't truncate text in columns\n"), out);
1427 fputs(_(" -W, --nowrap don't use multi-line representation\n"), out);
1428 fputs(_(" -t, --type <name> namespace type (mnt, net, ipc, user, pid, uts, cgroup, time)\n"), out);
1429 fputs(_(" -T, --tree[=<rel>] use tree format (parent, owner, or process)\n"), out);
1430
1431 fputs(USAGE_SEPARATOR, out);
1432 fputs(_(" -H, --list-columns list the available columns\n"), out);
1433 fprintf(out, USAGE_HELP_OPTIONS(24));
1434 fprintf(out, USAGE_MAN_TAIL("lsns(8)"));
1435
1436 exit(EXIT_SUCCESS);
1437 }
1438
1439 static void __attribute__((__noreturn__)) list_colunms(bool raw, bool json)
1440 {
1441 struct libscols_table *col_tb = xcolumn_list_table_new("lsns-columns", stdout, raw, json);
1442
1443 for (size_t i = 0; i < ARRAY_SIZE(infos); i++)
1444 xcolumn_list_table_append_line(col_tb, infos[i].name,
1445 infos[i].json_type, NULL,
1446 _(infos[i].help));
1447
1448 scols_print_table(col_tb);
1449 scols_unref_table(col_tb);
1450
1451 exit(EXIT_SUCCESS);
1452 }
1453
1454 static dev_t read_nsfs_dev(void)
1455 {
1456 struct stat st;
1457
1458 if (stat("/proc/self/ns/user", &st) < 0)
1459 err(EXIT_FAILURE, _("failed to do stat /proc/self/ns/user"));
1460
1461 return st.st_dev;
1462 }
1463
1464 int main(int argc, char *argv[])
1465 {
1466 struct lsns ls;
1467 int c, force_list = 0;
1468 int r = 0;
1469 char *outarg = NULL;
1470 enum {
1471 OPT_OUTPUT_ALL = CHAR_MAX + 1
1472 };
1473 static const struct option long_opts[] = {
1474 { "json", no_argument, NULL, 'J' },
1475 { "task", required_argument, NULL, 'p' },
1476 { "help", no_argument, NULL, 'h' },
1477 { "output", required_argument, NULL, 'o' },
1478 { "output-all", no_argument, NULL, OPT_OUTPUT_ALL },
1479 { "persistent", no_argument, NULL, 'P' },
1480 { "filter", required_argument, NULL, 'Q' },
1481 { "notruncate", no_argument, NULL, 'u' },
1482 { "version", no_argument, NULL, 'V' },
1483 { "noheadings", no_argument, NULL, 'n' },
1484 { "nowrap", no_argument, NULL, 'W' },
1485 { "list", no_argument, NULL, 'l' },
1486 { "raw", no_argument, NULL, 'r' },
1487 { "type", required_argument, NULL, 't' },
1488 { "tree", optional_argument, NULL, 'T' },
1489 { "list-columns", no_argument, NULL, 'H' },
1490 { NULL, 0, NULL, 0 }
1491 };
1492
1493 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
1494 { 'J','r' },
1495 { 'P','p' },
1496 { 'l','T' },
1497 { 0 }
1498 };
1499 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1500 int is_net = 0;
1501
1502 setlocale(LC_ALL, "");
1503 bindtextdomain(PACKAGE, LOCALEDIR);
1504 textdomain(PACKAGE);
1505 close_stdout_atexit();
1506
1507 lsns_init_debug();
1508 memset(&ls, 0, sizeof(ls));
1509
1510 INIT_LIST_HEAD(&ls.processes);
1511 INIT_LIST_HEAD(&ls.namespaces);
1512 INIT_LIST_HEAD(&netnsids_cache);
1513
1514 while ((c = getopt_long(argc, argv,
1515 "JlPp:o:nruhVt:T::WQ:H", long_opts, NULL)) != -1) {
1516
1517 err_exclusive_options(c, long_opts, excl, excl_st);
1518
1519 switch(c) {
1520 case 'J':
1521 ls.json = 1;
1522 break;
1523 case 'l':
1524 force_list = 1;
1525 break;
1526 case 'o':
1527 outarg = optarg;
1528 break;
1529 case OPT_OUTPUT_ALL:
1530 for (ncolumns = 0; ncolumns < ARRAY_SIZE(infos); ncolumns++)
1531 columns[ncolumns] = ncolumns;
1532 break;
1533 case 'P':
1534 ls.persist = 1;
1535 break;
1536 case 'p':
1537 ls.fltr_pid = strtos32_or_err(optarg, _("invalid PID argument"));
1538 break;
1539 case 'n':
1540 ls.no_headings = 1;
1541 break;
1542 case 'r':
1543 ls.no_wrap = ls.raw = 1;
1544 break;
1545 case 'u':
1546 ls.no_trunc = 1;
1547 break;
1548 case 't':
1549 {
1550 int type = ns_name2type(optarg);
1551 if (type < 0)
1552 errx(EXIT_FAILURE, _("unknown namespace type: %s"), optarg);
1553 ls.fltr_types[type] = 1;
1554 ls.fltr_ntypes++;
1555 if (type == LSNS_ID_NET)
1556 is_net = 1;
1557 break;
1558 }
1559 case 'W':
1560 ls.no_wrap = 1;
1561 break;
1562 case 'T':
1563 ls.tree = LSNS_TREE_OWNER;
1564 if (optarg) {
1565 if (*optarg == '=')
1566 optarg++;
1567 if (strcmp (optarg, "parent") == 0)
1568 ls.tree = LSNS_TREE_PARENT;
1569 else if (strcmp (optarg, "process") == 0)
1570 ls.tree = LSNS_TREE_PROCESS;
1571 else if (strcmp (optarg, "owner") != 0)
1572 errx(EXIT_FAILURE, _("unknown tree type: %s"), optarg);
1573 }
1574 break;
1575 case 'Q':
1576 ls.filter = new_filter(optarg);
1577 break;
1578 case 'H':
1579 list_colunms(ls.raw, ls.json);
1580
1581 case 'h':
1582 usage();
1583 case 'V':
1584 print_version(EXIT_SUCCESS);
1585 default:
1586 errtryhelp(EXIT_FAILURE);
1587 }
1588 }
1589
1590 if (!ls.fltr_ntypes) {
1591 size_t i;
1592
1593 for (i = 0; i < ARRAY_SIZE(ns_names); i++)
1594 ls.fltr_types[i] = 1;
1595 }
1596
1597 if (optind < argc) {
1598 if (ls.fltr_pid)
1599 errx(EXIT_FAILURE, _("--task is mutually exclusive with <namespace>"));
1600 ls.fltr_ns = strtou64_or_err(argv[optind], _("invalid namespace argument"));
1601 if (!ls.tree && !force_list)
1602 ls.tree = LSNS_TREE_PROCESS;
1603
1604 if (!ncolumns) {
1605 columns[ncolumns++] = COL_PID;
1606 columns[ncolumns++] = COL_PPID;
1607 columns[ncolumns++] = COL_USER;
1608 columns[ncolumns++] = COL_COMMAND;
1609 }
1610 }
1611
1612 if (!ncolumns) {
1613 columns[ncolumns++] = COL_NS;
1614 columns[ncolumns++] = COL_TYPE;
1615 columns[ncolumns++] = COL_NPROCS;
1616 columns[ncolumns++] = COL_PID;
1617 columns[ncolumns++] = COL_USER;
1618 if (is_net) {
1619 columns[ncolumns++] = COL_NETNSID;
1620 columns[ncolumns++] = COL_NSFS;
1621 }
1622 columns[ncolumns++] = COL_COMMAND;
1623
1624 if (!ls.tree && !force_list)
1625 ls.tree = LSNS_TREE_PROCESS;
1626 }
1627
1628 #ifndef USE_NS_GET_API
1629 if (ls.tree && ls.tree != LSNS_TREE_PROCESS)
1630 errx(EXIT_FAILURE, _("--tree={parent|owner} is unsupported for your system"));
1631 #endif
1632 if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
1633 &ncolumns, column_name_to_id) < 0)
1634 return EXIT_FAILURE;
1635
1636 scols_init_debug(0);
1637
1638 uid_cache = new_idcache();
1639 if (!uid_cache)
1640 err(EXIT_FAILURE, _("failed to allocate UID cache"));
1641
1642 #ifdef HAVE_LINUX_NET_NAMESPACE_H
1643 if (has_column(COL_NETNSID))
1644 netlink_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1645 #endif
1646 ls.tab = mnt_new_table_from_file(_PATH_PROC_MOUNTINFO);
1647 if (!ls.tab)
1648 err(MNT_EX_FAIL, _("failed to parse %s"), _PATH_PROC_MOUNTINFO);
1649
1650 ls.nsfs_dev = read_nsfs_dev();
1651
1652 r = read_processes(&ls);
1653 if (!r)
1654 r = read_namespaces(&ls);
1655 if (!r) {
1656 if (ls.fltr_ns) {
1657 struct lsns_namespace *ns = get_namespace(&ls, ls.fltr_ns);
1658
1659 if (!ns)
1660 errx(EXIT_FAILURE, _("not found namespace: %ju"), (uintmax_t) ls.fltr_ns);
1661 r = show_namespace_processes(&ls, ns);
1662 } else
1663 r = show_namespaces(&ls);
1664 }
1665
1666 scols_unref_filter(ls.filter);
1667 mnt_free_table(ls.tab);
1668 if (netlink_fd >= 0)
1669 close(netlink_fd);
1670 free_idcache(uid_cache);
1671
1672 free_all(&ls);
1673
1674 switch (r) {
1675 case 0: return EXIT_SUCCESS;
1676 case -ENOTTY: return EXIT_UNSUPPORTED_IOCTL;
1677 default: return EXIT_FAILURE;
1678 }
1679 }