]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/lsns.c
lsns: make --tree default, update man-page
[thirdparty/util-linux.git] / sys-utils / lsns.c
1 /*
2 * lsns(8) - list system namespaces
3 *
4 * Copyright (C) 2015 Karel Zak <kzak@redhat.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it would be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20 #include <stdio.h>
21 #include <string.h>
22 #include <getopt.h>
23 #include <stdlib.h>
24 #include <assert.h>
25 #include <dirent.h>
26 #include <unistd.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <wchar.h>
30 #include <libsmartcols.h>
31 #include <libmount.h>
32
33 #ifdef HAVE_LINUX_NET_NAMESPACE_H
34 #include <stdbool.h>
35 #include <sys/socket.h>
36 #include <linux/netlink.h>
37 #include <linux/rtnetlink.h>
38 #include <linux/net_namespace.h>
39 #endif
40
41 #ifdef HAVE_LINUX_NSFS_H
42 #include <linux/nsfs.h>
43 #endif
44
45 #include "pathnames.h"
46 #include "nls.h"
47 #include "xalloc.h"
48 #include "c.h"
49 #include "list.h"
50 #include "closestream.h"
51 #include "optutils.h"
52 #include "procutils.h"
53 #include "strutils.h"
54 #include "namespace.h"
55 #include "idcache.h"
56
57 #include "debug.h"
58
59 static UL_DEBUG_DEFINE_MASK(lsns);
60 UL_DEBUG_DEFINE_MASKNAMES(lsns) = UL_DEBUG_EMPTY_MASKNAMES;
61
62 #define LSNS_DEBUG_INIT (1 << 1)
63 #define LSNS_DEBUG_PROC (1 << 2)
64 #define LSNS_DEBUG_NS (1 << 3)
65 #define LSNS_DEBUG_ALL 0xFFFF
66
67 #define LSNS_NETNS_UNUSABLE -2
68
69 #define DBG(m, x) __UL_DBG(lsns, LSNS_DEBUG_, m, x)
70 #define ON_DBG(m, x) __UL_DBG_CALL(lsns, LSNS_DEBUG_, m, x)
71
72 #define UL_DEBUG_CURRENT_MASK UL_DEBUG_MASK(lsns)
73 #include "debugobj.h"
74
75 static struct idcache *uid_cache = NULL;
76
77 /* column IDs */
78 enum {
79 COL_NS = 0,
80 COL_TYPE,
81 COL_PATH,
82 COL_NPROCS,
83 COL_PID,
84 COL_PPID,
85 COL_COMMAND,
86 COL_UID,
87 COL_USER,
88 COL_NETNSID,
89 COL_NSFS,
90 COL_PNS, /* parent namespace */
91 COL_ONS, /* owner namespace */
92 };
93
94 /* column names */
95 struct colinfo {
96 const char *name; /* header */
97 double whint; /* width hint (N < 1 is in percent of termwidth) */
98 int flags; /* SCOLS_FL_* */
99 const char *help;
100 int json_type;
101 };
102
103 /* columns descriptions */
104 static const struct colinfo infos[] = {
105 [COL_NS] = { "NS", 10, SCOLS_FL_RIGHT, N_("namespace identifier (inode number)"), SCOLS_JSON_NUMBER },
106 [COL_TYPE] = { "TYPE", 5, 0, N_("kind of namespace") },
107 [COL_PATH] = { "PATH", 0, 0, N_("path to the namespace")},
108 [COL_NPROCS] = { "NPROCS", 5, SCOLS_FL_RIGHT, N_("number of processes in the namespace"), SCOLS_JSON_NUMBER },
109 [COL_PID] = { "PID", 5, SCOLS_FL_RIGHT, N_("lowest PID in the namespace"), SCOLS_JSON_NUMBER },
110 [COL_PPID] = { "PPID", 5, SCOLS_FL_RIGHT, N_("PPID of the PID"), SCOLS_JSON_NUMBER },
111 [COL_COMMAND] = { "COMMAND", 0, SCOLS_FL_TRUNC, N_("command line of the PID")},
112 [COL_UID] = { "UID", 0, SCOLS_FL_RIGHT, N_("UID of the PID"), SCOLS_JSON_NUMBER},
113 [COL_USER] = { "USER", 0, 0, N_("username of the PID")},
114 [COL_NETNSID] = { "NETNSID", 0, SCOLS_FL_RIGHT, N_("namespace ID as used by network subsystem")},
115 [COL_NSFS] = { "NSFS", 0, SCOLS_FL_WRAP, N_("nsfs mountpoint (usually used network subsystem)")},
116 [COL_PNS] = { "PNS", 10, SCOLS_FL_RIGHT, N_("parent namespace identifier (inode number)"), SCOLS_JSON_NUMBER },
117 [COL_ONS] = { "ONS", 10, SCOLS_FL_RIGHT, N_("owner namespace identifier (inode number)"), SCOLS_JSON_NUMBER },
118 };
119
120 static int columns[ARRAY_SIZE(infos) * 2];
121 static size_t ncolumns;
122
123 enum {
124 LSNS_ID_MNT = 0,
125 LSNS_ID_NET,
126 LSNS_ID_PID,
127 LSNS_ID_UTS,
128 LSNS_ID_IPC,
129 LSNS_ID_USER,
130 LSNS_ID_CGROUP,
131 LSNS_ID_TIME
132 };
133
134 static char *ns_names[] = {
135 [LSNS_ID_MNT] = "mnt",
136 [LSNS_ID_NET] = "net",
137 [LSNS_ID_PID] = "pid",
138 [LSNS_ID_UTS] = "uts",
139 [LSNS_ID_IPC] = "ipc",
140 [LSNS_ID_USER] = "user",
141 [LSNS_ID_CGROUP] = "cgroup",
142 [LSNS_ID_TIME] = "time"
143 };
144
145 struct lsns_namespace {
146 ino_t id;
147 int type; /* LSNS_* */
148 int nprocs;
149 int netnsid;
150 ino_t parentid;
151 ino_t ownerid;
152
153 struct lsns_process *proc;
154
155 struct lsns_namespace *parentns;
156 struct lsns_namespace *ownerns;
157 struct libscols_line *ns_outline;
158
159 struct list_head namespaces; /* lsns->processes member */
160 struct list_head processes; /* head of lsns_process *siblings */
161 };
162
163 struct lsns_process {
164 pid_t pid; /* process PID */
165 pid_t ppid; /* parent's PID */
166 pid_t tpid; /* thread group */
167 char state;
168 uid_t uid;
169
170 ino_t ns_ids[ARRAY_SIZE(ns_names)];
171 ino_t ns_pids[ARRAY_SIZE(ns_names)];
172 ino_t ns_oids[ARRAY_SIZE(ns_names)];
173
174 struct list_head ns_siblings[ARRAY_SIZE(ns_names)];
175
176 struct list_head processes; /* list of processes */
177
178 struct libscols_line *outline;
179 struct lsns_process *parent;
180
181 int netnsid;
182 };
183
184
185 enum {
186 LSNS_TREE_NONE,
187 LSNS_TREE_PROCESS,
188 LSNS_TREE_OWNER,
189 LSNS_TREE_PARENT,
190 };
191
192 struct lsns {
193 struct list_head processes;
194 struct list_head namespaces;
195
196 pid_t fltr_pid; /* filter out by PID */
197 ino_t fltr_ns; /* filter out by namespace */
198 int fltr_types[ARRAY_SIZE(ns_names)];
199 int fltr_ntypes;
200
201 unsigned int raw : 1,
202 json : 1,
203 tree : 2,
204 no_trunc : 1,
205 no_headings: 1,
206 no_wrap : 1;
207
208
209 struct libmnt_table *tab;
210 };
211
212 struct netnsid_cache {
213 ino_t ino;
214 int id;
215 struct list_head netnsids;
216 };
217
218 static struct list_head netnsids_cache;
219
220 static int netlink_fd = -1;
221
222 static void lsns_init_debug(void)
223 {
224 __UL_INIT_DEBUG_FROM_ENV(lsns, LSNS_DEBUG_, 0, LSNS_DEBUG);
225 }
226
227 static int ns_name2type(const char *name)
228 {
229 size_t i;
230
231 for (i = 0; i < ARRAY_SIZE(ns_names); i++) {
232 if (strcmp(ns_names[i], name) == 0)
233 return i;
234 }
235 return -1;
236 }
237
238 static int column_name_to_id(const char *name, size_t namesz)
239 {
240 size_t i;
241
242 assert(name);
243
244 for (i = 0; i < ARRAY_SIZE(infos); i++) {
245 const char *cn = infos[i].name;
246
247 if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
248 return i;
249 }
250 warnx(_("unknown column: %s"), name);
251 return -1;
252 }
253
254 static int has_column(int id)
255 {
256 size_t i;
257
258 for (i = 0; i < ncolumns; i++) {
259 if (columns[i] == id)
260 return 1;
261 }
262 return 0;
263 }
264
265 static inline int get_column_id(int num)
266 {
267 assert(num >= 0);
268 assert((size_t) num < ncolumns);
269 assert(columns[num] < (int) ARRAY_SIZE(infos));
270
271 return columns[num];
272 }
273
274 static inline const struct colinfo *get_column_info(unsigned num)
275 {
276 return &infos[ get_column_id(num) ];
277 }
278
279 static int get_ns_ino(int dir, const char *nsname, ino_t *ino, ino_t *pino, ino_t *oino)
280 {
281 struct stat st;
282 char path[16];
283
284 snprintf(path, sizeof(path), "ns/%s", nsname);
285
286 if (fstatat(dir, path, &st, 0) != 0)
287 return -errno;
288 *ino = st.st_ino;
289
290 *pino = 0;
291 *oino = 0;
292
293 #ifdef HAVE_LINUX_NSFS_H
294 int fd, pfd, ofd;
295 fd = openat(dir, path, 0);
296 if (fd < 0)
297 return -errno;
298 if (strcmp(nsname, "pid") == 0 || strcmp(nsname, "user") == 0) {
299 if ((pfd = ioctl(fd, NS_GET_PARENT)) < 0) {
300 if (errno == EPERM)
301 goto user;
302 close(fd);
303 return -errno;
304 }
305 if (fstat(pfd, &st) < 0) {
306 close(pfd);
307 close(fd);
308 return -errno;
309 }
310 *pino = st.st_ino;
311 close(pfd);
312 }
313 user:
314 if ((ofd = ioctl(fd, NS_GET_USERNS)) < 0) {
315 if (errno == EPERM)
316 goto out;
317 close(fd);
318 return -errno;
319 }
320 if (fstat(ofd, &st) < 0) {
321 close(ofd);
322 close(fd);
323 return -errno;
324 }
325 *oino = st.st_ino;
326 close(ofd);
327 out:
328 close(fd);
329 #endif
330 return 0;
331 }
332
333 static int parse_proc_stat(FILE *fp, pid_t *pid, char *state, pid_t *ppid)
334 {
335 char *line = NULL, *p;
336 size_t len = 0;
337 int rc;
338
339 if (getline(&line, &len, fp) < 0) {
340 rc = -errno;
341 goto error;
342 }
343
344 p = strrchr(line, ')');
345 if (p == NULL ||
346 sscanf(line, "%d (", pid) != 1 ||
347 sscanf(p, ") %c %d*[^\n]", state, ppid) != 2) {
348 rc = -EINVAL;
349 goto error;
350 }
351 rc = 0;
352
353 error:
354 free(line);
355 return rc;
356 }
357
358 #ifdef HAVE_LINUX_NET_NAMESPACE_H
359 static int netnsid_cache_find(ino_t netino, int *netnsid)
360 {
361 struct list_head *p;
362
363 list_for_each(p, &netnsids_cache) {
364 struct netnsid_cache *e = list_entry(p,
365 struct netnsid_cache,
366 netnsids);
367 if (e->ino == netino) {
368 *netnsid = e->id;
369 return 1;
370 }
371 }
372
373 return 0;
374 }
375
376 static void netnsid_cache_add(ino_t netino, int netnsid)
377 {
378 struct netnsid_cache *e;
379
380 e = xcalloc(1, sizeof(*e));
381 e->ino = netino;
382 e->id = netnsid;
383 INIT_LIST_HEAD(&e->netnsids);
384 list_add(&e->netnsids, &netnsids_cache);
385 }
386
387 static int get_netnsid_via_netlink_send_request(int target_fd)
388 {
389 unsigned char req[NLMSG_SPACE(sizeof(struct rtgenmsg))
390 + RTA_SPACE(sizeof(int32_t))];
391
392 struct nlmsghdr *nlh = (struct nlmsghdr *)req;
393 struct rtgenmsg *rt = NLMSG_DATA(req);
394 struct rtattr *rta = (struct rtattr *)
395 (req + NLMSG_SPACE(sizeof(struct rtgenmsg)));
396 int32_t *fd = RTA_DATA(rta);
397
398 nlh->nlmsg_len = sizeof(req);
399 nlh->nlmsg_flags = NLM_F_REQUEST;
400 nlh->nlmsg_type = RTM_GETNSID;
401 rt->rtgen_family = AF_UNSPEC;
402 rta->rta_type = NETNSA_FD;
403 rta->rta_len = RTA_SPACE(sizeof(int32_t));
404 *fd = target_fd;
405
406 if (send(netlink_fd, req, sizeof(req), 0) < 0)
407 return -1;
408 return 0;
409 }
410
411 static int get_netnsid_via_netlink_recv_response(int *netnsid)
412 {
413 unsigned char res[NLMSG_SPACE(sizeof(struct rtgenmsg))
414 + ((RTA_SPACE(sizeof(int32_t))
415 < RTA_SPACE(sizeof(struct nlmsgerr)))
416 ? RTA_SPACE(sizeof(struct nlmsgerr))
417 : RTA_SPACE(sizeof(int32_t)))];
418 int rtalen;
419 ssize_t reslen;
420
421 struct nlmsghdr *nlh;
422 struct rtattr *rta;
423
424 reslen = recv(netlink_fd, res, sizeof(res), 0);
425 if (reslen < 0)
426 return -1;
427
428 nlh = (struct nlmsghdr *)res;
429 if (!(NLMSG_OK(nlh, (size_t)reslen)
430 && nlh->nlmsg_type == RTM_NEWNSID))
431 return -1;
432
433 rtalen = NLMSG_PAYLOAD(nlh, sizeof(struct rtgenmsg));
434 rta = (struct rtattr *)(res + NLMSG_SPACE(sizeof(struct rtgenmsg)));
435 if (!(RTA_OK(rta, rtalen)
436 && rta->rta_type == NETNSA_NSID))
437 return -1;
438
439 *netnsid = *(int *)RTA_DATA(rta);
440
441 return 0;
442 }
443
444 static int get_netnsid_via_netlink(int dir, const char *path)
445 {
446 int netnsid;
447 int target_fd;
448
449 if (netlink_fd < 0)
450 return LSNS_NETNS_UNUSABLE;
451
452 target_fd = openat(dir, path, O_RDONLY);
453 if (target_fd < 0)
454 return LSNS_NETNS_UNUSABLE;
455
456 if (get_netnsid_via_netlink_send_request(target_fd) < 0) {
457 netnsid = LSNS_NETNS_UNUSABLE;
458 goto out;
459 }
460
461 if (get_netnsid_via_netlink_recv_response(&netnsid) < 0) {
462 netnsid = LSNS_NETNS_UNUSABLE;
463 goto out;
464 }
465
466 out:
467 close(target_fd);
468 return netnsid;
469 }
470
471 static int get_netnsid(int dir, ino_t netino)
472 {
473 int netnsid;
474
475 if (!netnsid_cache_find(netino, &netnsid)) {
476 netnsid = get_netnsid_via_netlink(dir, "ns/net");
477 netnsid_cache_add(netino, netnsid);
478 }
479
480 return netnsid;
481 }
482 #else
483 static int get_netnsid(int dir __attribute__((__unused__)),
484 ino_t netino __attribute__((__unused__)))
485 {
486 return LSNS_NETNS_UNUSABLE;
487 }
488 #endif /* HAVE_LINUX_NET_NAMESPACE_H */
489
490 static int read_process(struct lsns *ls, pid_t pid)
491 {
492 struct lsns_process *p = NULL;
493 char buf[BUFSIZ];
494 DIR *dir;
495 int rc = 0, fd;
496 FILE *f = NULL;
497 size_t i;
498 struct stat st;
499
500 DBG(PROC, ul_debug("reading %d", (int) pid));
501
502 snprintf(buf, sizeof(buf), "/proc/%d", pid);
503 dir = opendir(buf);
504 if (!dir)
505 return -errno;
506
507 p = xcalloc(1, sizeof(*p));
508 p->netnsid = LSNS_NETNS_UNUSABLE;
509
510 if (fstat(dirfd(dir), &st) == 0) {
511 p->uid = st.st_uid;
512 add_uid(uid_cache, st.st_uid);
513 }
514
515 fd = openat(dirfd(dir), "stat", O_RDONLY);
516 if (fd < 0) {
517 rc = -errno;
518 goto done;
519 }
520 if (!(f = fdopen(fd, "r"))) {
521 rc = -errno;
522 goto done;
523 }
524 rc = parse_proc_stat(f, &p->pid, &p->state, &p->ppid);
525 if (rc < 0)
526 goto done;
527 rc = 0;
528
529 for (i = 0; i < ARRAY_SIZE(p->ns_ids); i++) {
530 INIT_LIST_HEAD(&p->ns_siblings[i]);
531
532 if (!ls->fltr_types[i])
533 continue;
534
535 rc = get_ns_ino(dirfd(dir), ns_names[i], &p->ns_ids[i],
536 &p->ns_pids[i], &p->ns_oids[i]);
537 if (rc && rc != -EACCES && rc != -ENOENT)
538 goto done;
539 if (i == LSNS_ID_NET)
540 p->netnsid = get_netnsid(dirfd(dir), p->ns_ids[i]);
541 rc = 0;
542 }
543
544 INIT_LIST_HEAD(&p->processes);
545
546 DBG(PROC, ul_debugobj(p, "new pid=%d", p->pid));
547 list_add_tail(&p->processes, &ls->processes);
548 done:
549 if (f)
550 fclose(f);
551 closedir(dir);
552 if (rc)
553 free(p);
554 return rc;
555 }
556
557 static int read_processes(struct lsns *ls)
558 {
559 struct proc_processes *proc = NULL;
560 pid_t pid;
561 int rc = 0;
562
563 DBG(PROC, ul_debug("opening /proc"));
564
565 if (!(proc = proc_open_processes())) {
566 rc = -errno;
567 goto done;
568 }
569
570 while (proc_next_pid(proc, &pid) == 0) {
571 rc = read_process(ls, pid);
572 if (rc && rc != -EACCES && rc != -ENOENT)
573 break;
574 rc = 0;
575 }
576 done:
577 DBG(PROC, ul_debug("closing /proc"));
578 proc_close_processes(proc);
579 return rc;
580 }
581
582 static struct lsns_namespace *get_namespace(struct lsns *ls, ino_t ino)
583 {
584 struct list_head *p;
585
586 list_for_each(p, &ls->namespaces) {
587 struct lsns_namespace *ns = list_entry(p, struct lsns_namespace, namespaces);
588
589 if (ns->id == ino)
590 return ns;
591 }
592 return NULL;
593 }
594
595 static int namespace_has_process(struct lsns_namespace *ns, pid_t pid)
596 {
597 struct list_head *p;
598
599 list_for_each(p, &ns->processes) {
600 struct lsns_process *proc = list_entry(p, struct lsns_process, ns_siblings[ns->type]);
601
602 if (proc->pid == pid)
603 return 1;
604 }
605 return 0;
606 }
607
608 static struct lsns_namespace *add_namespace(struct lsns *ls, int type, ino_t ino,
609 ino_t parent_ino, ino_t owner_ino)
610 {
611 struct lsns_namespace *ns = xcalloc(1, sizeof(*ns));
612
613 if (!ns)
614 return NULL;
615
616 DBG(NS, ul_debugobj(ns, "new %s[%ju]", ns_names[type], (uintmax_t)ino));
617
618 INIT_LIST_HEAD(&ns->processes);
619 INIT_LIST_HEAD(&ns->namespaces);
620
621 ns->type = type;
622 ns->id = ino;
623 ns->parentid = parent_ino;
624 ns->ownerid = owner_ino;
625
626 list_add_tail(&ns->namespaces, &ls->namespaces);
627 return ns;
628 }
629
630 static int add_process_to_namespace(struct lsns *ls, struct lsns_namespace *ns, struct lsns_process *proc)
631 {
632 struct list_head *p;
633
634 DBG(NS, ul_debugobj(ns, "add process [%p] pid=%d to %s[%ju]",
635 proc, proc->pid, ns_names[ns->type], (uintmax_t)ns->id));
636
637 list_for_each(p, &ls->processes) {
638 struct lsns_process *xproc = list_entry(p, struct lsns_process, processes);
639
640 if (xproc->pid == proc->ppid) /* my parent */
641 proc->parent = xproc;
642 else if (xproc->ppid == proc->pid) /* my child */
643 xproc->parent = proc;
644 }
645
646 list_add_tail(&proc->ns_siblings[ns->type], &ns->processes);
647 ns->nprocs++;
648
649 if (!ns->proc || ns->proc->pid > proc->pid)
650 ns->proc = proc;
651
652 return 0;
653 }
654
655 static int cmp_namespaces(struct list_head *a, struct list_head *b,
656 __attribute__((__unused__)) void *data)
657 {
658 struct lsns_namespace *xa = list_entry(a, struct lsns_namespace, namespaces),
659 *xb = list_entry(b, struct lsns_namespace, namespaces);
660
661 return cmp_numbers(xa->id, xb->id);
662 }
663
664 static int netnsid_xasputs(char **str, int netnsid)
665 {
666 if (netnsid >= 0)
667 return xasprintf(str, "%d", netnsid);
668 #ifdef NETNSA_NSID_NOT_ASSIGNED
669 if (netnsid == NETNSA_NSID_NOT_ASSIGNED)
670 return xasprintf(str, "%s", "unassigned");
671 #endif
672 return 0;
673 }
674
675 static int read_namespaces(struct lsns *ls)
676 {
677 struct list_head *p;
678
679 DBG(NS, ul_debug("reading namespace"));
680
681 list_for_each(p, &ls->processes) {
682 size_t i;
683 struct lsns_namespace *ns;
684 struct lsns_process *proc = list_entry(p, struct lsns_process, processes);
685
686 for (i = 0; i < ARRAY_SIZE(proc->ns_ids); i++) {
687 if (proc->ns_ids[i] == 0)
688 continue;
689 if (!(ns = get_namespace(ls, proc->ns_ids[i]))) {
690 ns = add_namespace(ls, i, proc->ns_ids[i],
691 proc->ns_pids[i], proc->ns_oids[i]);
692 if (!ns)
693 return -ENOMEM;
694 }
695 add_process_to_namespace(ls, ns, proc);
696 }
697 }
698
699 if (ls->tree == LSNS_TREE_OWNER || ls->tree == LSNS_TREE_PARENT) {
700 list_for_each(p, &ls->namespaces) {
701 struct lsns_namespace *ns = list_entry(p, struct lsns_namespace, namespaces);
702 struct list_head *pp;
703 list_for_each(pp, &ls->namespaces) {
704 struct lsns_namespace *pns = list_entry(pp, struct lsns_namespace, namespaces);
705 if (ns->type == LSNS_ID_USER
706 || ns->type == LSNS_ID_PID) {
707 if (ns->parentid == pns->id)
708 ns->parentns = pns;
709 if (ns->ownerid == pns->id)
710 ns->ownerns = pns;
711 if (ns->parentns && ns->ownerns)
712 break;
713 } else {
714 if (ns->ownerid == pns->id) {
715 ns->ownerns = pns;
716 break;
717 }
718 }
719 }
720 }
721 }
722
723 list_sort(&ls->namespaces, cmp_namespaces, NULL);
724
725 return 0;
726 }
727
728 static int is_nsfs_root(struct libmnt_fs *fs, void *data)
729 {
730 if (!mnt_fs_match_fstype(fs, "nsfs") || !mnt_fs_get_root(fs))
731 return 0;
732
733 return (strcmp(mnt_fs_get_root(fs), (char *)data) == 0);
734 }
735
736 static int is_path_included(const char *path_set, const char *elt,
737 const char sep)
738 {
739 size_t elt_len;
740 size_t path_set_len;
741 char *tmp;
742
743
744 tmp = strstr(path_set, elt);
745 if (!tmp)
746 return 0;
747
748 elt_len = strlen(elt);
749 path_set_len = strlen(path_set);
750
751 /* path_set includes only elt or
752 * path_set includes elt as the first element.
753 */
754 if (tmp == path_set
755 && ((path_set_len == elt_len)
756 || (path_set[elt_len] == sep)))
757 return 1;
758
759 /* path_set includes elt at the middle
760 * or as the last element.
761 */
762 if ((*(tmp - 1) == sep)
763 && ((*(tmp + elt_len) == sep)
764 || (*(tmp + elt_len) == '\0')))
765 return 1;
766
767 return 0;
768 }
769
770 static int nsfs_xasputs(char **str,
771 struct lsns_namespace *ns,
772 struct libmnt_table *tab,
773 char sep)
774 {
775 struct libmnt_iter *itr = mnt_new_iter(MNT_ITER_FORWARD);
776 char *expected_root;
777 struct libmnt_fs *fs = NULL;
778
779 xasprintf(&expected_root, "%s:[%ju]", ns_names[ns->type], (uintmax_t)ns->id);
780 *str = NULL;
781
782 while (mnt_table_find_next_fs(tab, itr, is_nsfs_root,
783 expected_root, &fs) == 0) {
784
785 const char *tgt = mnt_fs_get_target(fs);
786
787 if (!*str)
788 xasprintf(str, "%s", tgt);
789
790 else if (!is_path_included(*str, tgt, sep)) {
791 char *tmp = NULL;
792
793 xasprintf(&tmp, "%s%c%s", *str, sep, tgt);
794 free(*str);
795 *str = tmp;
796 }
797 }
798 free(expected_root);
799 mnt_free_iter(itr);
800
801 return 1;
802 }
803 static void add_scols_line(struct lsns *ls, struct libscols_table *table,
804 struct lsns_namespace *ns, struct lsns_process *proc)
805 {
806 size_t i;
807 struct libscols_line *line;
808
809 assert(ns);
810 assert(table);
811
812 line = scols_table_new_line(table,
813 (ls->tree == LSNS_TREE_PROCESS) && proc->parent ? proc->parent->outline:
814 (ls->tree == LSNS_TREE_PARENT) && ns->parentns ? ns->parentns->ns_outline:
815 (ls->tree == LSNS_TREE_OWNER) && ns->ownerns ? ns->ownerns->ns_outline:
816 NULL);
817 if (!line) {
818 warn(_("failed to add line to output"));
819 return;
820 }
821
822 for (i = 0; i < ncolumns; i++) {
823 char *str = NULL;
824
825 switch (get_column_id(i)) {
826 case COL_NS:
827 xasprintf(&str, "%ju", (uintmax_t)ns->id);
828 break;
829 case COL_PID:
830 xasprintf(&str, "%d", (int) proc->pid);
831 break;
832 case COL_PPID:
833 xasprintf(&str, "%d", (int) proc->ppid);
834 break;
835 case COL_TYPE:
836 xasprintf(&str, "%s", ns_names[ns->type]);
837 break;
838 case COL_NPROCS:
839 xasprintf(&str, "%d", ns->nprocs);
840 break;
841 case COL_COMMAND:
842 str = proc_get_command(proc->pid);
843 if (!str)
844 str = proc_get_command_name(proc->pid);
845 break;
846 case COL_PATH:
847 xasprintf(&str, "/proc/%d/ns/%s", (int) proc->pid, ns_names[ns->type]);
848 break;
849 case COL_UID:
850 xasprintf(&str, "%d", (int) proc->uid);
851 break;
852 case COL_USER:
853 xasprintf(&str, "%s", get_id(uid_cache, proc->uid)->name);
854 break;
855 case COL_NETNSID:
856 if (ns->type == LSNS_ID_NET)
857 netnsid_xasputs(&str, proc->netnsid);
858 break;
859 case COL_NSFS:
860 nsfs_xasputs(&str, ns, ls->tab, ls->no_wrap ? ',' : '\n');
861 break;
862 case COL_PNS:
863 xasprintf(&str, "%ju", (uintmax_t)ns->parentid);
864 break;
865 case COL_ONS:
866 xasprintf(&str, "%ju", (uintmax_t)ns->ownerid);
867 break;
868 default:
869 break;
870 }
871
872 if (str && scols_line_refer_data(line, i, str) != 0)
873 err_oom();
874 }
875
876 if (ls->tree == LSNS_TREE_OWNER || ls->tree == LSNS_TREE_PARENT)
877 ns->ns_outline = line;
878 else
879 proc->outline = line;
880 }
881
882 static struct libscols_table *init_scols_table(struct lsns *ls)
883 {
884 struct libscols_table *tab;
885 size_t i;
886
887 tab = scols_new_table();
888 if (!tab) {
889 warn(_("failed to initialize output table"));
890 return NULL;
891 }
892
893 scols_table_enable_raw(tab, ls->raw);
894 scols_table_enable_json(tab, ls->json);
895 scols_table_enable_noheadings(tab, ls->no_headings);
896
897 if (ls->json)
898 scols_table_set_name(tab, "namespaces");
899
900 for (i = 0; i < ncolumns; i++) {
901 const struct colinfo *col = get_column_info(i);
902 int flags = col->flags;
903 struct libscols_column *cl;
904
905 if (ls->no_trunc)
906 flags &= ~SCOLS_FL_TRUNC;
907 if (ls->tree == LSNS_TREE_PROCESS && get_column_id(i) == COL_COMMAND)
908 flags |= SCOLS_FL_TREE;
909 if (ls->no_wrap)
910 flags &= ~SCOLS_FL_WRAP;
911 if ((ls->tree == LSNS_TREE_OWNER || ls->tree == LSNS_TREE_PARENT)
912 && get_column_id(i) == COL_NS) {
913 flags |= SCOLS_FL_TREE;
914 flags &= ~SCOLS_FL_RIGHT;
915 }
916
917 cl = scols_table_new_column(tab, col->name, col->whint, flags);
918 if (cl == NULL) {
919 warnx(_("failed to initialize output column"));
920 goto err;
921 }
922 if (ls->json)
923 scols_column_set_json_type(cl, col->json_type);
924
925 if (!ls->no_wrap && get_column_id(i) == COL_NSFS) {
926 scols_column_set_wrapfunc(cl,
927 scols_wrapnl_chunksize,
928 scols_wrapnl_nextchunk,
929 NULL);
930 scols_column_set_safechars(cl, "\n");
931 }
932 }
933
934 return tab;
935 err:
936 scols_unref_table(tab);
937 return NULL;
938 }
939
940 static void show_namespace(struct lsns *ls, struct libscols_table *tab,
941 struct lsns_namespace *ns, struct lsns_process *proc)
942 {
943 /*
944 * create a tree from owner->owned and/or parent->child relation
945 */
946 if (ls->tree == LSNS_TREE_OWNER
947 && ns->ownerns
948 && !ns->ownerns->ns_outline)
949 show_namespace(ls, tab, ns->ownerns, ns->ownerns->proc);
950 else if (ls->tree == LSNS_TREE_PARENT) {
951 if (ns->parentns) {
952 if (!ns->parentns->ns_outline)
953 show_namespace(ls, tab, ns->parentns, ns->parentns->proc);
954 }
955 else if (ns->ownerns && !ns->ownerns->ns_outline)
956 show_namespace(ls, tab, ns->ownerns, ns->ownerns->proc);
957 }
958
959 add_scols_line(ls, tab, ns, proc);
960 }
961
962 static int show_namespaces(struct lsns *ls)
963 {
964 struct libscols_table *tab;
965 struct list_head *p;
966 int rc = 0;
967
968 tab = init_scols_table(ls);
969 if (!tab)
970 return -ENOMEM;
971
972 list_for_each(p, &ls->namespaces) {
973 struct lsns_namespace *ns = list_entry(p, struct lsns_namespace, namespaces);
974
975 if (ls->fltr_pid != 0 && !namespace_has_process(ns, ls->fltr_pid))
976 continue;
977
978 if (!ns->ns_outline)
979 show_namespace(ls, tab, ns, ns->proc);
980 }
981
982 scols_print_table(tab);
983 scols_unref_table(tab);
984 return rc;
985 }
986
987 static void show_process(struct lsns *ls, struct libscols_table *tab,
988 struct lsns_process *proc, struct lsns_namespace *ns)
989 {
990 /*
991 * create a tree from parent->child relation, but only if the parent is
992 * within the same namespace
993 */
994 if (ls->tree == LSNS_TREE_PROCESS
995 && proc->parent
996 && !proc->parent->outline
997 && proc->parent->ns_ids[ns->type] == proc->ns_ids[ns->type])
998 show_process(ls, tab, proc->parent, ns);
999
1000 add_scols_line(ls, tab, ns, proc);
1001 }
1002
1003
1004 static int show_namespace_processes(struct lsns *ls, struct lsns_namespace *ns)
1005 {
1006 struct libscols_table *tab;
1007 struct list_head *p;
1008
1009 tab = init_scols_table(ls);
1010 if (!tab)
1011 return -ENOMEM;
1012
1013 list_for_each(p, &ns->processes) {
1014 struct lsns_process *proc = list_entry(p, struct lsns_process, ns_siblings[ns->type]);
1015
1016 if (!proc->outline)
1017 show_process(ls, tab, proc, ns);
1018 }
1019
1020
1021 scols_print_table(tab);
1022 scols_unref_table(tab);
1023 return 0;
1024 }
1025
1026 static void __attribute__((__noreturn__)) usage(void)
1027 {
1028 FILE *out = stdout;
1029 size_t i;
1030
1031 fputs(USAGE_HEADER, out);
1032
1033 fprintf(out,
1034 _(" %s [options] [<namespace>]\n"), program_invocation_short_name);
1035
1036 fputs(USAGE_SEPARATOR, out);
1037 fputs(_("List system namespaces.\n"), out);
1038
1039 fputs(USAGE_OPTIONS, out);
1040 fputs(_(" -J, --json use JSON output format\n"), out);
1041 fputs(_(" -l, --list use list format output\n"), out);
1042 fputs(_(" -n, --noheadings don't print headings\n"), out);
1043 fputs(_(" -o, --output <list> define which output columns to use\n"), out);
1044 fputs(_(" --output-all output all columns\n"), out);
1045 fputs(_(" -p, --task <pid> print process namespaces\n"), out);
1046 fputs(_(" -r, --raw use the raw output format\n"), out);
1047 fputs(_(" -u, --notruncate don't truncate text in columns\n"), out);
1048 fputs(_(" -W, --nowrap don't use multi-line representation\n"), out);
1049 fputs(_(" -t, --type <name> namespace type (mnt, net, ipc, user, pid, uts, cgroup, time)\n"), out);
1050 fputs(_(" -T, --tree <rel> use tree format (parent, owner, or process)\n"), out);
1051
1052 fputs(USAGE_SEPARATOR, out);
1053 printf(USAGE_HELP_OPTIONS(24));
1054
1055 fputs(USAGE_COLUMNS, out);
1056 for (i = 0; i < ARRAY_SIZE(infos); i++)
1057 fprintf(out, " %11s %s\n", infos[i].name, _(infos[i].help));
1058
1059 printf(USAGE_MAN_TAIL("lsns(8)"));
1060
1061 exit(EXIT_SUCCESS);
1062 }
1063
1064
1065 int main(int argc, char *argv[])
1066 {
1067 struct lsns ls;
1068 int c, force_list = 0;
1069 int r = 0;
1070 char *outarg = NULL;
1071 enum {
1072 OPT_OUTPUT_ALL = CHAR_MAX + 1
1073 };
1074 static const struct option long_opts[] = {
1075 { "json", no_argument, NULL, 'J' },
1076 { "task", required_argument, NULL, 'p' },
1077 { "help", no_argument, NULL, 'h' },
1078 { "output", required_argument, NULL, 'o' },
1079 { "output-all", no_argument, NULL, OPT_OUTPUT_ALL },
1080 { "notruncate", no_argument, NULL, 'u' },
1081 { "version", no_argument, NULL, 'V' },
1082 { "noheadings", no_argument, NULL, 'n' },
1083 { "nowrap", no_argument, NULL, 'W' },
1084 { "list", no_argument, NULL, 'l' },
1085 { "raw", no_argument, NULL, 'r' },
1086 { "type", required_argument, NULL, 't' },
1087 { "tree", optional_argument, NULL, 'T' },
1088 { NULL, 0, NULL, 0 }
1089 };
1090
1091 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
1092 { 'J','r' },
1093 { 'l','T' },
1094 { 0 }
1095 };
1096 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1097 int is_net = 0;
1098
1099 setlocale(LC_ALL, "");
1100 bindtextdomain(PACKAGE, LOCALEDIR);
1101 textdomain(PACKAGE);
1102 close_stdout_atexit();
1103
1104 lsns_init_debug();
1105 memset(&ls, 0, sizeof(ls));
1106
1107 INIT_LIST_HEAD(&ls.processes);
1108 INIT_LIST_HEAD(&ls.namespaces);
1109 INIT_LIST_HEAD(&netnsids_cache);
1110
1111 while ((c = getopt_long(argc, argv,
1112 "Jlp:o:nruhVt:T::W", long_opts, NULL)) != -1) {
1113
1114 err_exclusive_options(c, long_opts, excl, excl_st);
1115
1116 switch(c) {
1117 case 'J':
1118 ls.json = 1;
1119 break;
1120 case 'l':
1121 force_list = 1;
1122 break;
1123 case 'o':
1124 outarg = optarg;
1125 break;
1126 case OPT_OUTPUT_ALL:
1127 for (ncolumns = 0; ncolumns < ARRAY_SIZE(infos); ncolumns++)
1128 columns[ncolumns] = ncolumns;
1129 break;
1130 case 'p':
1131 ls.fltr_pid = strtos32_or_err(optarg, _("invalid PID argument"));
1132 break;
1133 case 'n':
1134 ls.no_headings = 1;
1135 break;
1136 case 'r':
1137 ls.no_wrap = ls.raw = 1;
1138 break;
1139 case 'u':
1140 ls.no_trunc = 1;
1141 break;
1142 case 't':
1143 {
1144 int type = ns_name2type(optarg);
1145 if (type < 0)
1146 errx(EXIT_FAILURE, _("unknown namespace type: %s"), optarg);
1147 ls.fltr_types[type] = 1;
1148 ls.fltr_ntypes++;
1149 if (type == LSNS_ID_NET)
1150 is_net = 1;
1151 break;
1152 }
1153 case 'W':
1154 ls.no_wrap = 1;
1155 break;
1156 case 'T':
1157 ls.tree = LSNS_TREE_OWNER;
1158 if (optarg) {
1159 if (*optarg == '=')
1160 optarg++;
1161 if (strcmp (optarg, "parent") == 0)
1162 ls.tree = LSNS_TREE_PARENT;
1163 else if (strcmp (optarg, "process") == 0)
1164 ls.tree = LSNS_TREE_PROCESS;
1165 else if (strcmp (optarg, "owner") != 0)
1166 errx(EXIT_FAILURE, _("unknown nstree type: %s"), optarg);
1167 }
1168 break;
1169
1170 case 'h':
1171 usage();
1172 case 'V':
1173 print_version(EXIT_SUCCESS);
1174 default:
1175 errtryhelp(EXIT_FAILURE);
1176 }
1177 }
1178
1179 if (!ls.fltr_ntypes) {
1180 size_t i;
1181
1182 for (i = 0; i < ARRAY_SIZE(ns_names); i++)
1183 ls.fltr_types[i] = 1;
1184 }
1185
1186 if (optind < argc) {
1187 if (ls.fltr_pid)
1188 errx(EXIT_FAILURE, _("--task is mutually exclusive with <namespace>"));
1189 ls.fltr_ns = strtou64_or_err(argv[optind], _("invalid namespace argument"));
1190 if (!ls.tree && !force_list)
1191 ls.tree = LSNS_TREE_PROCESS;
1192
1193 if (!ncolumns) {
1194 columns[ncolumns++] = COL_PID;
1195 columns[ncolumns++] = COL_PPID;
1196 columns[ncolumns++] = COL_USER;
1197 columns[ncolumns++] = COL_COMMAND;
1198 }
1199 }
1200
1201 if (!ncolumns) {
1202 columns[ncolumns++] = COL_NS;
1203 columns[ncolumns++] = COL_TYPE;
1204 columns[ncolumns++] = COL_NPROCS;
1205 columns[ncolumns++] = COL_PID;
1206 columns[ncolumns++] = COL_USER;
1207 if (is_net) {
1208 columns[ncolumns++] = COL_NETNSID;
1209 columns[ncolumns++] = COL_NSFS;
1210 }
1211 columns[ncolumns++] = COL_COMMAND;
1212
1213 if (!ls.tree && !force_list)
1214 ls.tree = LSNS_TREE_PROCESS;
1215 }
1216
1217 if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
1218 &ncolumns, column_name_to_id) < 0)
1219 return EXIT_FAILURE;
1220
1221 scols_init_debug(0);
1222
1223 uid_cache = new_idcache();
1224 if (!uid_cache)
1225 err(EXIT_FAILURE, _("failed to allocate UID cache"));
1226
1227 #ifdef HAVE_LINUX_NET_NAMESPACE_H
1228 if (has_column(COL_NETNSID))
1229 netlink_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1230 #endif
1231 if (has_column(COL_NSFS)) {
1232 ls.tab = mnt_new_table_from_file(_PATH_PROC_MOUNTINFO);
1233 if (!ls.tab)
1234 err(MNT_EX_FAIL, _("failed to parse %s"), _PATH_PROC_MOUNTINFO);
1235 }
1236
1237 r = read_processes(&ls);
1238 if (!r)
1239 r = read_namespaces(&ls);
1240 if (!r) {
1241 if (ls.fltr_ns) {
1242 struct lsns_namespace *ns = get_namespace(&ls, ls.fltr_ns);
1243
1244 if (!ns)
1245 errx(EXIT_FAILURE, _("not found namespace: %ju"), (uintmax_t) ls.fltr_ns);
1246 r = show_namespace_processes(&ls, ns);
1247 } else
1248 r = show_namespaces(&ls);
1249 }
1250
1251 mnt_free_table(ls.tab);
1252 if (netlink_fd >= 0)
1253 close(netlink_fd);
1254 free_idcache(uid_cache);
1255 return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1256 }