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