]> mj.ucw.cz Git - ywho.git/blob - ywho.c
192c308a10f04e05e41b17bd9cea6fff5fd59b39
[ywho.git] / ywho.c
1 /*
2  *      Extended `who' command, version 1.11.
3  *
4  *      (c) 1996--2003 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU General Public License. See file COPYING in any of the GNU packages.
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <utmp.h>
16 #include <time.h>
17 #include <dirent.h>
18 #include <pwd.h>
19 #include <sys/stat.h>
20 #include <asm/param.h>
21 #include <sys/ioctl.h>
22 #include <ctype.h>
23
24 #undef DEBUG
25 #define MAXHOSTSIZE 24
26
27 #ifdef DEBUG
28 #define DBG(x,y...) printf(x,##y)
29 #else
30 #define DBG(x,y...) do { } while(0)
31 #endif
32
33 struct procrec {
34   struct procrec *next;
35   int pid, ppid, pgrp, sess;
36   int uid, state, distance;
37   time_t ctim, tim;
38   struct utrec *user;
39   char cmd_line[1];
40 };
41
42 static struct procrec *first_procrec;
43
44 struct utrec {
45   struct utrec *next;
46   pid_t login_pid;
47   char line[UT_LINESIZE];
48   time_t login_time, click_time, total_time;
49   char user_name[UT_NAMESIZE+1];
50   int uid;
51   char host_name[MAXHOSTSIZE+1];
52   int mesg, detach;
53   struct procrec *proc;
54 };
55
56 static struct utrec *first_utrec;
57 static int usercnt, zombies, maxhost = 10;
58 static time_t now;
59
60 static void *
61 xmalloc(int i)
62 {
63   void *z;
64   z = malloc(i);
65   if (!z)
66     {
67       fprintf(stderr, "ywho: out of memory!\n");
68       exit(1);
69     }
70   return z;
71 }
72
73 static void
74 strcpy_padded(char *to, char *from, int size)
75 {
76   memcpy(to, from, size);
77   to[size] = 0;
78 }
79
80 static void
81 readutmp(void)
82 {
83   static struct utmp *ut;
84   static struct passwd *pw;
85   char *z;
86   utmpname(UTMP_FILE);
87   while (ut = getutent())
88     if (ut->ut_type == USER_PROCESS && ut->ut_user[0])
89       {
90         struct utrec *u = xmalloc(sizeof(struct utrec));
91         struct stat st;
92         char device[32];
93         size_t hlen;
94         bzero(u, sizeof(*u));
95         u->next = first_utrec;
96         first_utrec = u;
97         u->login_pid = ut->ut_pid;
98         z = ut->ut_line;
99         if (!strncmp(z, "tty", 3))
100           {
101             if (z[3] >= '0' && z[3] <= '9')
102               sprintf(u->line, "c%s", z+3);
103             else
104               strcpy(u->line, z+3);
105           }
106         else if (!strncmp(z, "pts/", 4))
107           strcpy(u->line, z+4);
108         u->login_time = ut->ut_time;
109         strcpy_padded(u->user_name, ut->ut_user, UT_NAMESIZE);
110         pw = getpwnam(u->user_name);
111         if (pw)
112           u->uid = pw->pw_uid;
113         else
114           u->uid = -1;
115         strcpy_padded(u->host_name, ut->ut_host,
116           (MAXHOSTSIZE > UT_HOSTSIZE ? UT_HOSTSIZE : MAXHOSTSIZE));
117         if ((hlen = strlen(u->host_name)) > maxhost)
118           maxhost = hlen;
119         strcpy(u->line, ut->ut_line);
120         if (*u->line)
121           {
122             char *z = u->line;
123             if (!strncmp(z, "tty", 3))
124               {
125                 if (isdigit(z[3]))
126                   sprintf(u->line, "c%s", z+3);
127                 else
128                   strcpy(u->line, z+3);
129               }
130             else if (!strncmp(z, "pts/", 4))
131               strcpy(u->line, z+4);
132             else
133               strcpy(u->line, z);
134           }
135         strcpy(device, "/dev/");
136         strcat(device, ut->ut_line);
137         if (stat(device, &st))
138           u->mesg = 2;
139         else
140           {
141             u->mesg = !!(S_IWGRP & st.st_mode);
142             u->click_time = st.st_atime;
143 #if 0
144             if (u->click_time < st.st_mtime)
145               u->click_time = st.st_mtime;
146             if (u->click_time < st.st_ctime)
147               u->click_time = st.st_ctime;
148 #endif
149           }
150         u->detach = 0;
151         usercnt++;
152         DBG("UTMP: %s %s %d %d\n", u->user_name, u->host_name,
153             u->uid, u->login_pid);
154       }
155   endutent();
156 }
157
158 static void
159 puttime(int s)
160 {
161   int d, h, m;
162   if (s < 100)
163     printf("%4ds", s);
164   else
165     {
166       m = s/60;
167       s %= 60;
168       h = m/60;
169       m %= 60;
170       if (h < 100)
171         printf("%02d.%02d", h, m);
172       else
173         {
174           d = h/24;
175           h %= 24;
176           if (d < 100)
177             printf("%2dd%02d", d, h);
178           else
179             printf("%4dd", d);
180         }
181     }
182 }
183
184 static void
185 memory(unsigned int i)
186 {
187   if (i < 10240)
188     printf("%dB", i);
189   else
190     {
191       i = (i+511U)/1024U;
192       if (i < 2048)
193         printf("%dK", i);
194       else
195         {
196           i = (i+511)/1024;
197           if (i < 2048)
198             printf("%dM", i);
199           else
200             printf("%dG", (i+511U)/1024U);
201         }
202     }
203 }
204
205 static void
206 line1(void)
207 {
208   FILE *f;
209   char line[256];
210   char *z;
211   int num_cpus = 0;
212
213   if (f = fopen("/proc/version", "r"))
214     {
215       fgets(line, 256, f);
216       z = strchr(line, '(');
217       if (z)
218         {
219           while (z != line && z[-1] == ' ')
220             z--;
221         }
222       else
223         z = line + strlen(line) - 1;
224       *z = 0;
225       z = strstr(line, " version");
226       if (z)
227         memmove(z, z+8, strlen(z+8)+1);
228       printf(line);
229       fclose(f);
230     }
231
232   if (gethostname(line, sizeof(line)) >= 0)
233     printf(" (%s)", line);
234
235   if (f = fopen("/proc/cpuinfo", "r"))
236     {
237       while (fgets(line, 256, f))
238         {
239           if (!strncmp(line, "processor\t", 9))
240             num_cpus++;
241         }
242       printf(" [%d CPU%s]", num_cpus, (num_cpus != 1 ? "s" : ""));
243       fclose(f);
244     }
245
246   if (f = fopen("/proc/uptime", "r"))
247     {
248       int p,q,p1,q1;
249       fgets(line, 256, f);
250       sscanf(line, "%d.%d%d.%d", &p, &p1, &q, &q1);
251       printf(" up ");
252       puttime(p);
253       printf(" run ");
254       puttime(num_cpus*p - q);
255       fclose(f);
256     }
257
258   {
259     now = time(NULL);
260     struct tm *tm = localtime(&now);
261     strftime(line, sizeof(line), "%a %Y-%m-%d %H.%M:%S", tm);
262     printf(" on %s\n", line);
263   }
264 }
265
266 static void
267 line2(void)
268 {
269   FILE *f;
270   char line[256];
271   char *z;
272
273   if (f = fopen("/proc/loadavg", "r"))
274     {
275       int i = 3;
276       fgets(line, 256, f);
277       *strchr(line, '\n') = 0;
278       z = line-1;
279       while (i-- && z)
280         {
281           *z = '/';
282           z = strchr(z, ' ');
283         }
284       if (z)
285         {
286           char *k;
287           *z++ = 0;
288           k = strchr(z, ' ');
289           if (k)
290             *k = 0;
291           printf("R/T=%s, ", z);
292         }
293       else
294         z = line;
295       printf("LAV=%s", line);
296       fclose(f);
297     }
298
299   if (f = fopen("/proc/meminfo", "r"))
300     {
301       int free, buffers, cached, stotal, sfree;
302       free = buffers = stotal = sfree = 0;
303       while (fgets(line, 256, f))
304         {
305           if (!strncmp(line, "MemFree:", 8))
306             sscanf(line+8, "%d", &free);
307           else if (!strncmp(line, "Buffers:", 8))
308             sscanf(line+8, "%d", &buffers);
309           else if (!strncmp(line, "Cached:", 7))
310             sscanf(line+7, "%d", &cached);
311           else if (!strncmp(line, "SwapTotal:", 10))
312             sscanf(line+10, "%d", &stotal);
313           else if (!strncmp(line, "SwapFree:", 9))
314             sscanf(line+9, "%d", &sfree);
315         }
316       printf(", free ");
317       memory(1024*(free+buffers+cached));
318       printf(" of RAM");
319       if (stotal != sfree)
320         {
321           printf(", used ");
322           memory(1024*(stotal - sfree));
323           printf(" of swap");
324         }
325     }
326   printf(", %d user%s\n", usercnt, usercnt == 1 ? "" : "s");
327 }
328
329 static void
330 readproc(void)
331 {
332   DIR *d;
333   struct dirent *e;
334   struct winsize win;
335   unsigned cmdcols;
336 #define LEFTSIZE 35
337   
338   if (!ioctl(1, TIOCGWINSZ, &win) && win.ws_col >= LEFTSIZE + maxhost + 10 && win.ws_col < 1024)
339     cmdcols = win.ws_col;
340   else
341     cmdcols = 80;
342   cmdcols -= LEFTSIZE + maxhost;
343   if (d = opendir("/proc"))
344     {
345       while (e = readdir(d))
346         {
347           int i;
348           if (sscanf(e->d_name, "%d", &i)==1)
349             {
350               struct procrec *p = xmalloc(sizeof(struct procrec) + cmdcols);
351               struct stat st;
352               char name[256], eman[1024];
353               int fil;
354               bzero(p, sizeof(*p));
355               p->pid = i;
356               strcpy(name, "/proc/");
357               strcat(name, e->d_name);
358               if (!stat(name, &st))
359                 {
360                   p->uid = st.st_uid;
361                   strcpy(eman, name);
362                   strcat(eman, "/cmdline");
363                   if ((fil = open(eman, O_RDONLY)) >= 0)
364                     {
365                       int y, z = read(fil, p->cmd_line, cmdcols);
366                       if (z < 0)
367                         z = 0;
368                       for (y=0; y<z; y++)
369                         if (!p->cmd_line[y])
370                           p->cmd_line[y] = ' ';
371                       p->cmd_line[z] = 0;
372                       close(fil);
373                     }
374                   strcpy(eman, name);
375                   strcat(eman, "/stat");
376                   if ((fil = open(eman, O_RDONLY)) >= 0)
377                     {
378                       int z = read(fil, eman, 1023);
379                       char *j, *k;
380                       int trash, utim, stim, cutim, cstim;
381                       if (z < 0)
382                         z = 0;
383                       eman[z] = 0;
384                       if ((j = strchr(eman, '(')) && (k = strchr(j+1, ')')))
385                         {
386                           *k = 0;
387                           if (!p->cmd_line[0])
388                             {
389                               strncpy(p->cmd_line, j+1, cmdcols);
390                               p->cmd_line[cmdcols] = 0;
391                             }
392                           p->state = k[2];
393                           if (p->state == 'Z')
394                             zombies++;
395                           sscanf(k+4, "%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
396                                  &p->ppid, &p->pgrp, &p->sess, &trash, &trash,
397                                  &trash, &trash, &trash, &trash, &trash, &utim,
398                                  &stim, &cutim, &cstim);
399                           DBG("PROC: pid=%d ppid=%d pgrp=%d sess=%d uid=%d\n", p->pid, p->ppid, p->pgrp, p->sess, p->uid);
400                           p->next = first_procrec;
401                           first_procrec = p;
402                         }
403                       p->tim = utim + stim;
404                       p->ctim = cutim + cstim;
405                       close(fil);
406                     }
407                 }
408             }
409         }
410       closedir(d);
411     }
412   else
413     {
414       perror("unable to scan /proc");
415       exit(1);
416     }
417 }
418
419 static void
420 solve(void)
421 {
422   struct utrec *u;
423   struct procrec *m, *n;
424   struct passwd *pw;
425   int cnt;
426
427   /* Recognize login session process trees and find leaves of these trees */
428   for (u=first_utrec; u; u=u->next)
429     {
430       for (m=first_procrec; m; m=m->next)
431         if (m->pid == u->login_pid)
432           {
433             m->user = u;
434             u->total_time = m->ctim;
435             u->proc = m;
436             DBG("** %d is login process for %s@%s\n", m->pid, u->user_name, u->line);
437           }
438     }
439   do
440     {
441       cnt = 0;
442       for (m=first_procrec; m; m=m->next)
443         if (!m->user)
444           for (n=first_procrec; n; n=n->next)
445             if (n->pid == m->ppid && n->user)
446               {
447                 u = m->user = n->user;
448                 m->distance = n->distance + 1;
449                 if (!u->proc || u->proc->distance < m->distance)
450                   u->proc = m;
451                 cnt++;
452                 DBG("** %d at distance %d for %s@%s\n", m->pid, m->distance, u->user_name, u->line);
453                 break;
454               }
455     }
456   while (cnt);
457
458   /* Process the remaining processes */
459   for(m=first_procrec; m; m=m->next)
460     {
461       if (m->user)
462         continue;
463       for(u=first_utrec; u; u=u->next)
464         if (u->uid == m->uid)
465           break;
466       if (!u)
467         {
468           if (m->uid < 2 || m->ppid != 1)
469             continue;
470           u = xmalloc(sizeof(struct utrec));
471           bzero(u, sizeof(*u));
472           u->next = first_utrec;
473           first_utrec = u;
474           pw = getpwuid(u->uid = m->uid);
475           if (pw)
476             strcpy(u->user_name, pw->pw_name);
477           else
478             sprintf(u->user_name, "<%d>", m->uid);
479           u->mesg = 3;
480         }
481       if (!u->proc)
482         u->proc = m;
483       u->total_time += m->ctim;
484       u->detach++;
485       DBG("** daemon %s (%s)\n", m->cmd_line, u->user_name);
486     }
487 }
488
489 static inline int
490 comp(struct utrec *a, struct utrec *b)
491 {
492   int k;
493   if (b->mesg == 3)
494     return -1;
495   k = strcmp(a->user_name, b->user_name);
496   if (k)
497     return k;
498   if (!a->host_name[0] && b->host_name[0])
499     return -1;
500   return strcmp(a->line, b->line);
501 }
502
503 static void
504 sort(void)
505 {
506   struct utrec *fi = NULL;
507   struct utrec *z, **y, **m, **l;
508   l = &fi;
509   while (first_utrec)
510     {
511       y = &first_utrec;
512       m = y;
513       while (z = *y)
514         {
515           if (comp(z, *m) < 0)
516             m = y;
517           y = &z->next;
518         }
519       z = *m;
520       *m = z->next;
521       *l = z;
522       z->next = NULL;
523       l = &z->next;
524     }
525   first_utrec = fi;
526 }
527
528 static void
529 show(void)
530 {
531   struct utrec *u;
532   unsigned char *c;
533   printf("Name     Li  MD %-*s LogT  IdleT RunT  Command\n", maxhost, "From");
534   for(u=first_utrec; u; u=u->next)
535     {
536       if (!u->line[0])
537         strcpy(u->line, "--");
538       printf("%-8.8s %-3s %c%c %-*.*s ",
539              u->user_name,
540              u->line,
541              u->mesg ? ' ' : '-',
542              u->detach ? 'D' : ' ',
543              maxhost,
544              maxhost,
545              u->host_name);
546       if (u->mesg <= 1)
547         {
548           if (u->login_time > now)
549             u->login_time = now;
550           puttime(now - u->login_time);
551           putchar(' ');
552           if (u->click_time > now)
553             u->click_time = now;
554           if (now - u->click_time >= 60)
555             puttime(now - u->click_time);
556           else
557             printf("     ");
558         }
559       else
560         printf("?????      ");
561       if (u->proc)
562         {
563           putchar(' ');
564           puttime((unsigned)u->total_time/(unsigned)HZ);
565           putchar(' ');
566           for (c = u->proc->cmd_line; *c; c++)
567             {
568               if (*c < 0x20 || (*c >= 0x7f && *c < 0xa0))
569                 putchar(' ');
570               else
571                 putchar(*c);
572             }
573         }
574       else
575         printf(" <nothing>");
576       putchar('\n');
577     }
578 }
579
580 int main(void)
581 {
582   readutmp();
583   line1();
584   line2();
585   readproc();
586   solve();
587   sort();
588   show();
589   if (zombies)
590     {
591       printf("!!! There %s %d zombie%s walking around.\n",
592              zombies == 1 ? "is" : "are",
593              zombies,
594              zombies == 1 ? "" : "s" );
595     }
596   return 0;
597 }