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