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