Merge branch 'vendor/OPENSSL'
[dragonfly.git] / contrib / top / commands.c
1 /*
2  *  Top users/processes display for Unix
3  *  Version 3
4  *
5  *  This program may be freely redistributed,
6  *  but this entire comment MUST remain intact.
7  *
8  *  Copyright (c) 1984, 1989, William LeFebvre, Rice University
9  *  Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
10  *
11  * $FreeBSD: src/contrib/top/commands.c,v 1.4.6.1 2002/08/11 17:09:25 dwmalone Exp $
12  * $DragonFly: src/contrib/top/commands.c,v 1.3 2006/02/15 12:54:36 corecode Exp $
13  */
14
15 /*
16  *  This file contains the routines that implement some of the interactive
17  *  mode commands.  Note that some of the commands are implemented in-line
18  *  in "main".  This is necessary because they change the global state of
19  *  "top" (i.e.:  changing the number of processes to display).
20  */
21
22 #include "os.h"
23 #include <ctype.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <sys/time.h>
28 #include <sys/resource.h>
29
30 #include "sigdesc.h"            /* generated automatically */
31 #include "top.h"
32 #include "boolean.h"
33 #include "utils.h"
34 #include "commands.h"
35
36 struct errs;
37
38 extern const char *copyright;
39
40 /* imported from screen.c */
41 extern int overstrike;
42
43 static int err_compar(const void *, const void *);
44 static const char *err_string(void);
45 static int str_adderr(char *str, int len, int err);
46 static int str_addarg(char *str, int len, char *arg, int first);
47
48 /*
49  *  show_help() - display the help screen; invoked in response to
50  *              either 'h' or '?'.
51  */
52
53 void
54 show_help(void)
55 {
56     printf("Top version %s, %s\n", version_string(), copyright);
57     fputs("\n\n\
58 A top users display for Unix\n\
59 \n\
60 These single-character commands are available:\n\
61 \n\
62 ^L      - redraw screen\n\
63 q       - quit\n\
64 h or ?  - help; show this text\n", stdout);
65
66     /* not all commands are availalbe with overstrike terminals */
67     if (overstrike)
68     {
69         fputs("\n\
70 Other commands are also available, but this terminal is not\n\
71 sophisticated enough to handle those commands gracefully.\n\n", stdout);
72     }
73     else
74     {
75         fputs("\
76 d       - change number of displays to show\n\
77 e       - list errors generated by last \"kill\" or \"renice\" command\n\
78 i       - toggle the displaying of idle processes\n\
79 I       - same as 'i'\n\
80 O       - only display threads\n\
81 T       - toggle the displaying of threads\n\
82 S       - toggle the displaying of system processes\n\
83 k       - kill processes; send a signal to a list of processes\n\
84 n or #  - change number of processes to display\n", stdout);
85 #ifdef ORDER
86         fputs("\
87 o       - specify sort order (pri, size, res, cpu, time, thr)\n", stdout);
88 #endif
89         fputs("\
90 r       - renice a process\n\
91 s       - change number of seconds to delay between updates\n\
92 u       - display processes for only one user (+ selects all users)\n\
93 \n\
94 \n", stdout);
95     }
96 }
97
98 /*
99  *  Utility routines that help with some of the commands.
100  */
101
102 char *
103 next_field(char *str)
104 {
105     if ((str = strchr(str, ' ')) == NULL)
106     {
107         return(NULL);
108     }
109     *str = '\0';
110     while (*++str == ' ') /* loop */;
111
112     /* if there is nothing left of the string, return NULL */
113     /* This fix is dedicated to Greg Earle */
114     return(*str == '\0' ? NULL : str);
115 }
116
117 int
118 scanint(char *str, int *intp)
119 {
120     register int val = 0;
121     register char ch;
122
123     /* if there is nothing left of the string, flag it as an error */
124     /* This fix is dedicated to Greg Earle */
125     if (*str == '\0')
126     {
127         return(-1);
128     }
129
130     while ((ch = *str++) != '\0')
131     {
132         if (isdigit(ch))
133         {
134             val = val * 10 + (ch - '0');
135         }
136         else if (isspace(ch))
137         {
138             break;
139         }
140         else
141         {
142             return(-1);
143         }
144     }
145     *intp = val;
146     return(0);
147 }
148
149 /*
150  *  Some of the commands make system calls that could generate errors.
151  *  These errors are collected up in an array of structures for later
152  *  contemplation and display.  Such routines return a string containing an
153  *  error message, or NULL if no errors occurred.  The next few routines are
154  *  for manipulating and displaying these errors.  We need an upper limit on
155  *  the number of errors, so we arbitrarily choose 20.
156  */
157
158 #define ERRMAX 20
159
160 struct errs             /* structure for a system-call error */
161 {
162     int  errnum;        /* value of errno (that is, the actual error) */
163     char *arg;          /* argument that caused the error */
164 };
165
166 static struct errs errs[ERRMAX];
167 static int errcnt;
168 static const char *err_toomany = " too many errors occurred";
169 static const char *err_listem =
170         " Many errors occurred.  Press `e' to display the list of errors.";
171
172 /* These macros get used to reset and log the errors */
173 #define ERR_RESET   errcnt = 0
174 #define ERROR(p, e) if (errcnt >= ERRMAX) \
175                     { \
176                         return(err_toomany); \
177                     } \
178                     else \
179                     { \
180                         errs[errcnt].arg = (p); \
181                         errs[errcnt++].errnum = (e); \
182                     }
183
184 /*
185  *  err_string() - return an appropriate error string.  This is what the
186  *      command will return for displaying.  If no errors were logged, then
187  *      return NULL.  The maximum length of the error string is defined by
188  *      "STRMAX".
189  */
190
191 #define STRMAX 80
192
193 static const char *
194 err_string(void)
195 {
196     struct errs *errp;
197     int  cnt = 0;
198     int  first = Yes;
199     int  currerr = -1;
200     int stringlen;              /* characters still available in "string" */
201     static char string[STRMAX];
202
203     /* if there are no errors, return NULL */
204     if (errcnt == 0)
205     {
206         return(NULL);
207     }
208
209     /* sort the errors */
210     qsort((char *)errs, errcnt, sizeof(struct errs), err_compar);
211
212     /* need a space at the front of the error string */
213     string[0] = ' ';
214     string[1] = '\0';
215     stringlen = STRMAX - 2;
216
217     /* loop thru the sorted list, building an error string */
218     while (cnt < errcnt)
219     {
220         errp = &(errs[cnt++]);
221         if (errp->errnum != currerr)
222         {
223             if (currerr != -1)
224             {
225                 if ((stringlen = str_adderr(string, stringlen, currerr)) < 2)
226                 {
227                     return(err_listem);
228                 }
229                 (void) strcat(string, "; ");      /* we know there's more */
230             }
231             currerr = errp->errnum;
232             first = Yes;
233         }
234         if ((stringlen = str_addarg(string, stringlen, errp->arg, first)) ==0)
235         {
236             return(err_listem);
237         }
238         first = No;
239     }
240
241     /* add final message */
242     stringlen = str_adderr(string, stringlen, currerr);
243
244     /* return the error string */
245     return(stringlen == 0 ? err_listem : string);
246 }
247
248 /*
249  *  str_adderr(str, len, err) - add an explanation of error "err" to
250  *      the string "str".
251  */
252
253 static int
254 str_adderr(char *str, int len, int err)
255 {
256     const char *msg;
257     int  msglen;
258
259     msg = err == 0 ? "Not a number" : errmsg(err);
260     msglen = strlen(msg) + 2;
261     if (len <= msglen)
262     {
263         return(0);
264     }
265     (void) strcat(str, ": ");
266     (void) strcat(str, msg);
267     return(len - msglen);
268 }
269
270 /*
271  *  str_addarg(str, len, arg, first) - add the string argument "arg" to
272  *      the string "str".  This is the first in the group when "first"
273  *      is set (indicating that a comma should NOT be added to the front).
274  */
275 static int
276 str_addarg(char *str, int len, char *arg, int first)
277 {
278     register int arglen;
279
280     arglen = strlen(arg);
281     if (!first)
282     {
283         arglen += 2;
284     }
285     if (len <= arglen)
286     {
287         return(0);
288     }
289     if (!first)
290     {
291         (void) strcat(str, ", ");
292     }
293     (void) strcat(str, arg);
294     return(len - arglen);
295 }
296
297 /*
298  *  err_compar(p1, p2) - comparison routine used by "qsort"
299  *      for sorting errors.
300  */
301 static int
302 err_compar(const void *arg1, const void *arg2)
303 {
304     const struct errs *p1 = arg1;
305     const struct errs *p2 = arg2;
306     int result;
307
308     if ((result = p1->errnum - p2->errnum) == 0)
309     {
310         return(strcmp(p1->arg, p2->arg));
311     }
312     return(result);
313 }
314
315 /*
316  *  error_count() - return the number of errors currently logged.
317  */
318
319 int
320 error_count(void)
321 {
322     return(errcnt);
323 }
324
325 /*
326  *  show_errors() - display on stdout the current log of errors.
327  */
328
329 void
330 show_errors(void)
331 {
332     register int cnt = 0;
333     register struct errs *errp = errs;
334
335     printf("%d error%s:\n\n", errcnt, errcnt == 1 ? "" : "s");
336     while (cnt++ < errcnt)
337     {
338         printf("%5s: %s\n", errp->arg,
339             errp->errnum == 0 ? "Not a number" : errmsg(errp->errnum));
340         errp++;
341     }
342 }
343
344 /*
345  *  kill_procs(str) - send signals to processes, much like the "kill"
346  *              command does; invoked in response to 'k'.
347  */
348
349 const char *
350 kill_procs(char *str)
351 {
352     register char *nptr;
353     int signum = SIGTERM;       /* default */
354     int procnum;
355     struct sigdesc *sigp;
356     int uid;
357
358     /* reset error array */
359     ERR_RESET;
360
361     /* remember our uid */
362     uid = getuid();
363
364     /* skip over leading white space */
365     while (isspace(*str)) str++;
366
367     if (str[0] == '-')
368     {
369         /* explicit signal specified */
370         if ((nptr = next_field(str)) == NULL)
371         {
372             return(" kill: no processes specified");
373         }
374
375         if (isdigit(str[1]))
376         {
377             (void) scanint(str + 1, &signum);
378             if (signum <= 0 || signum >= NSIG)
379             {
380                 return(" invalid signal number");
381             }
382         }
383         else 
384         {
385             /* translate the name into a number */
386             for (sigp = sigdesc; sigp->name != NULL; sigp++)
387             {
388                 if (strcmp(sigp->name, str + 1) == 0)
389                 {
390                     signum = sigp->number;
391                     break;
392                 }
393             }
394
395             /* was it ever found */
396             if (sigp->name == NULL)
397             {
398                 return(" bad signal name");
399             }
400         }
401         /* put the new pointer in place */
402         str = nptr;
403     }
404
405     /* loop thru the string, killing processes */
406     do
407     {
408         if (scanint(str, &procnum) == -1)
409         {
410             ERROR(str, 0);
411         }
412         else
413         {
414             /* check process owner if we're not root */
415             if (uid && (uid != proc_owner(procnum)))
416             {
417                 ERROR(str, EACCES);
418             }
419             /* go in for the kill */
420             else if (kill(procnum, signum) == -1)
421             {
422                 /* chalk up an error */
423                 ERROR(str, errno);
424             }
425         }
426     } while ((str = next_field(str)) != NULL);
427
428     /* return appropriate error string */
429     return(err_string());
430 }
431
432 /*
433  *  renice_procs(str) - change the "nice" of processes, much like the
434  *              "renice" command does; invoked in response to 'r'.
435  */
436
437 const char *
438 renice_procs(char *str)
439 {
440     register char negate;
441     int prio;
442     int procnum;
443     int uid;
444
445     ERR_RESET;
446     uid = getuid();
447
448     /* allow for negative priority values */
449     if ((negate = (*str == '-')) != 0)
450     {
451         /* move past the minus sign */
452         str++;
453     }
454
455     /* use procnum as a temporary holding place and get the number */
456     procnum = scanint(str, &prio);
457
458     /* negate if necessary */
459     if (negate)
460     {
461         prio = -prio;
462     }
463
464 #if defined(PRIO_MIN) && defined(PRIO_MAX)
465     /* check for validity */
466     if (procnum == -1 || prio < PRIO_MIN || prio > PRIO_MAX)
467     {
468         return(" bad priority value");
469     }
470 #endif
471
472     /* move to the first process number */
473     if ((str = next_field(str)) == NULL)
474     {
475         return(" no processes specified");
476     }
477
478     /* loop thru the process numbers, renicing each one */
479     do
480     {
481         if (scanint(str, &procnum) == -1)
482         {
483             ERROR(str, 0);
484         }
485
486         /* check process owner if we're not root */
487         else if (uid && (uid != proc_owner(procnum)))
488         {
489             ERROR(str, EACCES);
490         }
491         else if (setpriority(PRIO_PROCESS, procnum, prio) == -1)
492         {
493             ERROR(str, errno);
494         }
495     } while ((str = next_field(str)) != NULL);
496
497     /* return appropriate error string */
498     return(err_string());
499 }
500