c3023cf5e97ca70e97bbcd3235948e1d9fb24e3b
[oweals/busybox.git] / procps / ps.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini ps implementation(s) for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  * Fix for SELinux Support:(c)2007 Hiroshi Shinji <shiroshi@my.email.ne.jp>
7                            (c)2007 Yuichi Nakamura <ynakam@hitachisoft.jp>
8  *
9  * Licensed under the GPL version 2, see the file LICENSE in this tarball.
10  */
11
12 #include "libbb.h"
13
14 #if ENABLE_DESKTOP
15
16 /* Print value to buf, max size+1 chars (including trailing '\0') */
17
18 static void func_user(char *buf, int size, const procps_status_t *ps)
19 {
20         safe_strncpy(buf, get_cached_username(ps->uid), size+1);
21 }
22
23 static void func_comm(char *buf, int size, const procps_status_t *ps)
24 {
25         safe_strncpy(buf, ps->comm, size+1);
26 }
27
28 static void func_args(char *buf, int size, const procps_status_t *ps)
29 {
30         buf[0] = '\0';
31         if (ps->cmd)
32                 safe_strncpy(buf, ps->cmd, size+1);
33         else if (size >= 2)
34                 sprintf(buf, "[%.*s]", size-2, ps->comm);
35 }
36
37 static void func_pid(char *buf, int size, const procps_status_t *ps)
38 {
39         sprintf(buf, "%*u", size, ps->pid);
40 }
41
42 static void func_ppid(char *buf, int size, const procps_status_t *ps)
43 {
44         sprintf(buf, "%*u", size, ps->ppid);
45 }
46
47 static void func_pgid(char *buf, int size, const procps_status_t *ps)
48 {
49         sprintf(buf, "%*u", size, ps->pgid);
50 }
51
52 static void put_u(char *buf, int size, unsigned u)
53 {
54         char buf5[5];
55         smart_ulltoa5( ((unsigned long long)u) << 10, buf5);
56         sprintf(buf, "%.*s", size, buf5);
57 }
58
59 static void func_vsz(char *buf, int size, const procps_status_t *ps)
60 {
61         put_u(buf, size, ps->vsz);
62 }
63
64 static void func_rss(char *buf, int size, const procps_status_t *ps)
65 {
66         put_u(buf, size, ps->rss);
67 }
68
69 static void func_tty(char *buf, int size, const procps_status_t *ps)
70 {
71         safe_strncpy(buf, ps->tty_str, size+1);
72 }
73
74 #if ENABLE_SELINUX
75 static void func_label(char *buf, int size, const procps_status_t *ps)
76 {
77         safe_strncpy(buf, ps->context ? ps->context : "unknown", size+1);
78 }
79 #endif
80
81 /*
82 static void func_nice(char *buf, int size, const procps_status_t *ps)
83 {
84         ps->???
85 }
86
87 static void func_etime(char *buf, int size, const procps_status_t *ps)
88 {
89         elapled time [[dd-]hh:]mm:ss
90 }
91
92 static void func_time(char *buf, int size, const procps_status_t *ps)
93 {
94         cumulative time [[dd-]hh:]mm:ss
95 }
96
97 static void func_pcpu(char *buf, int size, const procps_status_t *ps)
98 {
99 }
100 */
101
102 typedef struct {
103         uint16_t width;
104         char name[6];
105         const char *header;
106         void (*f)(char *buf, int size, const procps_status_t *ps);
107         int ps_flags;
108 } ps_out_t;
109
110 static const ps_out_t out_spec[] = {
111 // Mandated by POSIX:
112         { 8                  , "user"  ,"USER"   ,func_user  ,PSSCAN_UIDGID          },
113         { 16                 , "comm"  ,"COMMAND",func_comm  ,PSSCAN_COMM            },
114         { 256                , "args"  ,"COMMAND",func_args  ,PSSCAN_CMD|PSSCAN_COMM },
115         { 5                  , "pid"   ,"PID"    ,func_pid   ,PSSCAN_PID             },
116         { 5                  , "ppid"  ,"PPID"   ,func_ppid  ,PSSCAN_PPID            },
117         { 5                  , "pgid"  ,"PGID"   ,func_pgid  ,PSSCAN_PGID            },
118 //      { sizeof("ELAPSED")-1, "etime" ,"ELAPSED",func_etime ,PSSCAN_                },
119 //      { sizeof("GROUP"  )-1, "group" ,"GROUP"  ,func_group ,PSSCAN_UIDGID          },
120 //      { sizeof("NI"     )-1, "nice"  ,"NI"     ,func_nice  ,PSSCAN_                },
121 //      { sizeof("%CPU"   )-1, "pcpu"  ,"%CPU"   ,func_pcpu  ,PSSCAN_                },
122 //      { sizeof("RGROUP" )-1, "rgroup","RGROUP" ,func_rgroup,PSSCAN_UIDGID          },
123 //      { sizeof("RUSER"  )-1, "ruser" ,"RUSER"  ,func_ruser ,PSSCAN_UIDGID          },
124 //      { sizeof("TIME"   )-1, "time"  ,"TIME"   ,func_time  ,PSSCAN_                },
125         { 6                  , "tty"   ,"TT"     ,func_tty   ,PSSCAN_TTY             },
126         { 4                  , "vsz"   ,"VSZ"    ,func_vsz   ,PSSCAN_VSZ             },
127 // Not mandated by POSIX, but useful:
128         { 4                  , "rss"   ,"RSS"    ,func_rss   ,PSSCAN_RSS             },
129 #if ENABLE_SELINUX
130         { 35                 , "label" ,"LABEL"  ,func_label ,PSSCAN_CONTEXT         },
131 #endif
132 };
133
134 #define VEC_SIZE(v) ( sizeof(v) / sizeof((v)[0]) )
135
136 #if ENABLE_SELINUX
137 #define SELINIX_O_PREFIX "label,"
138 #define DEFAULT_O_STR    SELINIX_O_PREFIX "pid,user" /* TODO: ,vsz,stat */ ",args"
139 #else
140 #define DEFAULT_O_STR    "pid,user" /* TODO: ,vsz,stat */ ",args"
141 #endif
142
143 struct globals {
144         ps_out_t* out;
145         int out_cnt;
146         int print_header;
147         int need_flags;
148         char *buffer;
149         unsigned terminal_width;
150         char default_o[sizeof(DEFAULT_O_STR)];
151 };
152 #define G (*(struct globals*)&bb_common_bufsiz1)
153 #define out            (G.out           )
154 #define out_cnt        (G.out_cnt       )
155 #define print_header   (G.print_header  )
156 #define need_flags     (G.need_flags    )
157 #define buffer         (G.buffer        )
158 #define terminal_width (G.terminal_width)
159 #define default_o      (G.default_o     )
160
161 static ps_out_t* new_out_t(void)
162 {
163         int i = out_cnt++;
164         out = xrealloc(out, out_cnt * sizeof(*out));
165         return &out[i];
166 }
167
168 static const ps_out_t* find_out_spec(const char *name)
169 {
170         int i;
171         for (i = 0; i < VEC_SIZE(out_spec); i++) {
172                 if (!strcmp(name, out_spec[i].name))
173                         return &out_spec[i];
174         }
175         bb_error_msg_and_die("bad -o argument '%s'", name);
176 }
177
178 static void parse_o(char* opt)
179 {
180         ps_out_t* new;
181         // POSIX: "-o is blank- or comma-separated list" (FIXME)
182         char *comma, *equal;
183         while (1) {
184                 comma = strchr(opt, ',');
185                 equal = strchr(opt, '=');
186                 if (comma && (!equal || equal > comma)) {
187                         *comma = '\0';
188                         *new_out_t() = *find_out_spec(opt);
189                         *comma = ',';
190                         opt = comma + 1;
191                         continue;
192                 }
193                 break;
194         }
195         // opt points to last spec in comma separated list.
196         // This one can have =HEADER part.
197         new = new_out_t();
198         if (equal)
199                 *equal = '\0';
200         *new = *find_out_spec(opt);
201         if (equal) {
202                 *equal = '=';
203                 new->header = equal + 1;
204                 // POSIX: the field widths shall be ... at least as wide as
205                 // the header text (default or overridden value).
206                 // If the header text is null, such as -o user=,
207                 // the field width shall be at least as wide as the
208                 // default header text
209                 if (new->header[0]) {
210                         new->width = strlen(new->header);
211                         print_header = 1;
212                 }
213         } else
214                 print_header = 1;
215 }
216
217 static void post_process(void)
218 {
219         int i;
220         int width = 0;
221         for (i = 0; i < out_cnt; i++) {
222                 need_flags |= out[i].ps_flags;
223                 if (out[i].header[0]) {
224                         print_header = 1;
225                 }
226                 width += out[i].width + 1; /* "FIELD " */
227         }
228 #if ENABLE_SELINUX
229         if (!is_selinux_enabled())
230                 need_flags &= ~PSSCAN_CONTEXT;
231 #endif
232         buffer = xmalloc(width + 1); /* for trailing \0 */
233 }
234
235 static void format_header(void)
236 {
237         int i;
238         ps_out_t* op;
239         char *p;
240
241         if (!print_header)
242                 return;
243         p = buffer;
244         i = 0;
245         if (out_cnt) {
246                 while (1) {
247                         op = &out[i];
248                         if (++i == out_cnt) /* do not pad last field */
249                                 break;
250                         p += sprintf(p, "%-*s ", op->width, op->header);
251                 }
252                 strcpy(p, op->header);
253         }
254         printf("%.*s\n", terminal_width, buffer);
255 }
256
257 static void format_process(const procps_status_t *ps)
258 {
259         int i, len;
260         char *p = buffer;
261         i = 0;
262         if (out_cnt) while (1) {
263                 out[i].f(p, out[i].width, ps);
264                 // POSIX: Any field need not be meaningful in all
265                 // implementations. In such a case a hyphen ( '-' )
266                 // should be output in place of the field value.
267                 if (!p[0]) {
268                         p[0] = '-';
269                         p[1] = '\0';
270                 }
271                 len = strlen(p);
272                 p += len;
273                 len = out[i].width - len + 1;
274                 if (++i == out_cnt) /* do not pad last field */
275                         break;
276                 p += sprintf(p, "%*s", len, "");
277         }
278         printf("%.*s\n", terminal_width, buffer);
279 }
280
281 int ps_main(int argc, char **argv);
282 int ps_main(int argc, char **argv)
283 {
284         procps_status_t *p;
285         llist_t* opt_o = NULL;
286         USE_SELINUX(int opt;)
287
288         // POSIX:
289         // -a  Write information for all processes associated with terminals
290         //     Implementations may omit session leaders from this list
291         // -A  Write information for all processes
292         // -d  Write information for all processes, except session leaders
293         // -e  Write information for all processes (equivalent to -A.)
294         // -f  Generate a full listing
295         // -l  Generate a long listing
296         // -o col1,col2,col3=header
297         //     Select which columns to display
298         /* We allow (and ignore) most of the above. FIXME */
299         opt_complementary = "o::";
300         USE_SELINUX(opt =) getopt32(argc, argv, "Zo:aAdefl", &opt_o);
301         if (opt_o) {
302                 do {
303                         parse_o(opt_o->data);
304                         opt_o = opt_o->link;
305                 } while (opt_o);
306         } else {
307                 /* Below: parse_o() needs char*, NOT const char*... */
308 #if ENABLE_SELINUX
309                 if (!(opt & 1) || !is_selinux_enabled()) {
310                         /* no -Z or no SELinux: do not show LABEL */
311                         strcpy(default_o, DEFAULT_O_STR + sizeof(SELINIX_O_PREFIX)-1);
312                 } else
313 #endif
314                 {
315                         strcpy(default_o, DEFAULT_O_STR);
316                 }
317                 parse_o(default_o);
318         }
319         post_process();
320
321         /* Was INT_MAX, but some libc's go belly up with printf("%.*s")
322          * and such large widths */
323         terminal_width = 30000;
324         if (isatty(1)) {
325                 get_terminal_width_height(1, &terminal_width, NULL);
326                 terminal_width--;
327         }
328         format_header();
329
330         p = NULL;
331         while ((p = procps_scan(p, need_flags))) {
332                 format_process(p);
333         }
334
335         return EXIT_SUCCESS;
336 }
337
338
339 #else /* !ENABLE_DESKTOP */
340
341
342 int ps_main(int argc, char **argv);
343 int ps_main(int argc, char **argv)
344 {
345         procps_status_t *p = NULL;
346         int i, len;
347         SKIP_SELINUX(const) int use_selinux = 0;
348 #if !ENABLE_FEATURE_PS_WIDE
349         enum { terminal_width = 79 };
350 #else
351         int terminal_width;
352         int w_count = 0;
353 #endif
354
355 #if ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX
356 #if ENABLE_FEATURE_PS_WIDE
357         opt_complementary = "-:ww";
358         USE_SELINUX(i =) getopt32(argc, argv, USE_SELINUX("Z") "w", &w_count);
359         /* if w is given once, GNU ps sets the width to 132,
360          * if w is given more than once, it is "unlimited"
361          */
362         if (w_count) {
363                 terminal_width = (w_count==1) ? 132 : INT_MAX;
364         } else {
365                 get_terminal_width_height(1, &terminal_width, NULL);
366                 /* Go one less... */
367                 terminal_width--;
368         }
369 #else /* only ENABLE_SELINUX */
370         i = getopt32(argc, argv, "Z");
371 #endif
372 #if ENABLE_SELINUX
373         if ((i & 1) && is_selinux_enabled())
374                 use_selinux = PSSCAN_CONTEXT;
375 #endif
376 #endif /* ENABLE_FEATURE_PS_WIDE || ENABLE_SELINUX */
377
378         if (use_selinux)
379                 puts("  PID Context                          Stat Command");
380         else
381                 puts("  PID  Uid        VSZ Stat Command");
382
383         while ((p = procps_scan(p, 0
384                         | PSSCAN_PID
385                         | PSSCAN_UIDGID
386                         | PSSCAN_STATE
387                         | PSSCAN_VSZ
388                         | PSSCAN_CMD
389                         | use_selinux
390         ))) {
391                 char *namecmd = p->cmd;
392 #if ENABLE_SELINUX
393                 if (use_selinux) {
394                         len = printf("%5u %-32s %s ",
395                                         p->pid,
396                                         p->context ? p->context : "unknown",
397                                         p->state);
398                 } else
399 #endif
400                 {
401                         const char *user = get_cached_username(p->uid);
402                         if (p->vsz == 0)
403                                 len = printf("%5u %-8s        %s ",
404                                         p->pid, user, p->state);
405                         else
406                                 len = printf("%5u %-8s %6u %s ",
407                                         p->pid, user, p->vsz, p->state);
408                 }
409
410                 i = terminal_width-len;
411
412                 if (namecmd && namecmd[0]) {
413                         if (i < 0)
414                                 i = 0;
415                         if (strlen(namecmd) > (size_t)i)
416                                 namecmd[i] = '\0';
417                         puts(namecmd);
418                 } else {
419                         namecmd = p->comm;
420                         if (i < 2)
421                                 i = 2;
422                         if (strlen(namecmd) > ((size_t)i-2))
423                                 namecmd[i-2] = '\0';
424                         printf("[%s]\n", namecmd);
425                 }
426         }
427         if (ENABLE_FEATURE_CLEAN_UP)
428                 clear_username_cache();
429         return EXIT_SUCCESS;
430 }
431
432 #endif /* ENABLE_DESKTOP */