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