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