]> mj.ucw.cz Git - ywho.git/blob - ywho.c
Do not forget "Cached:" in /proc/meminfo when calculating free memory
[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 dispsys(void)
207 {
208   FILE *f;
209   char line[256];
210   char *z, *w;
211   w = NULL;
212   if (f = fopen("/proc/version", "r"))
213     {
214       fgets(line, 256, f);
215       z = strchr(line, '(');
216       if (z)
217         {
218           while (z != line && z[-1] == ' ')
219             z--;
220         }
221       else
222         z = line + strlen(line) - 1;
223       *z = 0;
224       z = strstr(line, " version");
225       if (z)
226         memmove(z, z+8, strlen(z+8)+1);
227       printf(line);
228       fclose(f);
229     }
230   if (f = fopen("/proc/cpuinfo", "r"))
231     {
232       char a[32], b[32], c[32];
233       strcpy(a, "???");
234       b[0] = 0;
235       c[0] = 0;
236       for(;;)
237         {
238           fgets(line, 256, f);
239           if (feof(f))
240             break;
241           if (!strncmp(line, "cpu\t\t: ", 7))
242             {
243               z = line+7;
244               w = a;
245             }
246           else if (!strncmp(line, "cpu family\t: ",13))
247             {
248               z = line+13; strcpy(z + 1, "86\n");
249               w = a;
250             }
251           else if (!strncmp(line, "model\t\t: ", 9))
252             {
253               z = line+9;
254               w = b;
255             }
256           else if (!strncmp(line, "model name\t: ", 13))
257             {
258               z = line+13;
259               if (!strncmp(z, "AMD-K6", 6))
260                 {
261                   z[3] = ' ';
262                   if ((w = strstr(z, "tm w/ multimedia")))
263                     strcpy(w, "-1\n");
264                   else if ((w = strstr(z, "(tm) 3D")))
265                     strcpy(w, "-2\n");
266                 }
267               w = b;
268             }
269           else if (!strncmp(line, "mask\t\t: ", 8))
270             {
271               z = line+8;
272               w = c;
273             }
274           else
275             z = NULL;
276           if (z)
277             {
278               line[strlen(line)-1] = 0;
279               strcpy(w, z);
280               if (!strcmp(w, "Unknown"))
281                 w[0] = 0;
282             }
283         }
284       printf(" on %s", *b ? b : a);
285       if (*c)
286         printf("/%s", c);
287       fclose(f);
288     }
289   if (f = fopen("/proc/uptime", "r"))
290     {
291       int p,q,p1,q1;
292       fgets(line, 256, f);
293       sscanf(line, "%d.%d%d.%d", &p, &p1, &q, &q1);
294       printf(" up ");
295       puttime(p);
296       printf(" run ");
297       puttime(p-q);
298       fclose(f);
299     }
300   {
301     struct tm *tm;
302     char *days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
303     now = time(NULL);
304     tm = localtime(&now);
305     printf(" on %s %02d-%02d-%02d %02d.%02d:%02d", days[tm->tm_wday], tm->tm_mday, tm->tm_mon+1,
306            tm->tm_year%100, tm->tm_hour, tm->tm_min, tm->tm_sec);
307     printf(" (%u UE)\n", (unsigned int) now);
308   }
309   if (f = fopen("/proc/loadavg", "r"))
310     {
311       int i = 3;
312       fgets(line, 256, f);
313       *strchr(line, '\n') = 0;
314       z = line-1;
315       while (i-- && z)
316         {
317           *z = '/';
318           z = strchr(z, ' ');
319         }
320       if (z)
321         {
322           char *k;
323           *z++ = 0;
324           k = strchr(z, ' ');
325           if (k)
326             *k = 0;
327           printf("R/T=%s, ", z);
328         }
329       else
330         z = line;
331       printf("LAV=%s", line);
332       fclose(f);
333     }
334   if (f = fopen("/proc/meminfo", "r"))
335     {
336       int free, buffers, cached, stotal, sfree;
337       free = buffers = stotal = sfree = 0;
338       while (fgets(line, 256, f))
339         {
340           if (!strncmp(line, "MemFree:", 8))
341             sscanf(line+8, "%d", &free);
342           else if (!strncmp(line, "Buffers:", 8))
343             sscanf(line+8, "%d", &buffers);
344           else if (!strncmp(line, "Cached:", 7))
345             sscanf(line+7, "%d", &cached);
346           else if (!strncmp(line, "SwapTotal:", 10))
347             sscanf(line+10, "%d", &stotal);
348           else if (!strncmp(line, "SwapFree:", 9))
349             sscanf(line+9, "%d", &sfree);
350         }
351       printf(", free ");
352       memory(1024*(free+buffers+cached));
353       printf(" of RAM");
354       if (stotal != sfree)
355         {
356           printf(", used ");
357           memory(1024*(stotal - sfree));
358           printf(" of swap");
359         }
360     }
361   printf(", %d user%s.\n", usercnt, usercnt == 1 ? "" : "s");
362 }
363
364 static void
365 readproc(void)
366 {
367   DIR *d;
368   struct dirent *e;
369   struct winsize win;
370   unsigned cmdcols;
371 #define LEFTSIZE 35
372   
373   if (!ioctl(1, TIOCGWINSZ, &win) && win.ws_col >= LEFTSIZE + maxhost + 10 && win.ws_col < 1024)
374     cmdcols = win.ws_col;
375   else
376     cmdcols = 80;
377   cmdcols -= LEFTSIZE + maxhost;
378   if (d = opendir("/proc"))
379     {
380       while (e = readdir(d))
381         {
382           int i;
383           if (sscanf(e->d_name, "%d", &i)==1)
384             {
385               struct procrec *p = xmalloc(sizeof(struct procrec) + cmdcols);
386               struct stat st;
387               char name[256], eman[1024];
388               int fil;
389               bzero(p, sizeof(*p));
390               p->pid = i;
391               strcpy(name, "/proc/");
392               strcat(name, e->d_name);
393               if (!stat(name, &st))
394                 {
395                   p->uid = st.st_uid;
396                   strcpy(eman, name);
397                   strcat(eman, "/cmdline");
398                   if ((fil = open(eman, O_RDONLY)) >= 0)
399                     {
400                       int y, z = read(fil, p->cmd_line, cmdcols);
401                       if (z < 0)
402                         z = 0;
403                       for (y=0; y<z; y++)
404                         if (!p->cmd_line[y])
405                           p->cmd_line[y] = ' ';
406                       p->cmd_line[z] = 0;
407                       close(fil);
408                     }
409                   strcpy(eman, name);
410                   strcat(eman, "/stat");
411                   if ((fil = open(eman, O_RDONLY)) >= 0)
412                     {
413                       int z = read(fil, eman, 1023);
414                       char *j, *k;
415                       int trash, utim, stim, cutim, cstim;
416                       if (z < 0)
417                         z = 0;
418                       eman[z] = 0;
419                       if ((j = strchr(eman, '(')) && (k = strchr(j+1, ')')))
420                         {
421                           *k = 0;
422                           if (!p->cmd_line[0])
423                             {
424                               strncpy(p->cmd_line, j+1, cmdcols);
425                               p->cmd_line[cmdcols] = 0;
426                             }
427                           p->state = k[2];
428                           if (p->state == 'Z')
429                             zombies++;
430                           sscanf(k+4, "%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
431                                  &p->ppid, &p->pgrp, &p->sess, &trash, &trash,
432                                  &trash, &trash, &trash, &trash, &trash, &utim,
433                                  &stim, &cutim, &cstim);
434                           DBG("PROC: pid=%d ppid=%d pgrp=%d sess=%d uid=%d\n", p->pid, p->ppid, p->pgrp, p->sess, p->uid);
435                           p->next = first_procrec;
436                           first_procrec = p;
437                         }
438                       p->tim = utim + stim;
439                       p->ctim = cutim + cstim;
440                       close(fil);
441                     }
442                 }
443             }
444         }
445       closedir(d);
446     }
447   else
448     {
449       perror("unable to scan /proc");
450       exit(1);
451     }
452 }
453
454 static void
455 solve(void)
456 {
457   struct utrec *u;
458   struct procrec *m, *n;
459   struct passwd *pw;
460   int cnt;
461
462   /* Recognize login session process trees and find leaves of these trees */
463   for (u=first_utrec; u; u=u->next)
464     {
465       for (m=first_procrec; m; m=m->next)
466         if (m->pid == u->login_pid)
467           {
468             m->user = u;
469             u->total_time = m->ctim;
470             u->proc = m;
471             DBG("** %d is login process for %s@%s\n", m->pid, u->user_name, u->line);
472           }
473     }
474   do
475     {
476       cnt = 0;
477       for (m=first_procrec; m; m=m->next)
478         if (!m->user)
479           for (n=first_procrec; n; n=n->next)
480             if (n->pid == m->ppid && n->user)
481               {
482                 u = m->user = n->user;
483                 m->distance = n->distance + 1;
484                 if (!u->proc || u->proc->distance < m->distance)
485                   u->proc = m;
486                 cnt++;
487                 DBG("** %d at distance %d for %s@%s\n", m->pid, m->distance, u->user_name, u->line);
488                 break;
489               }
490     }
491   while (cnt);
492
493   /* Process the remaining processes */
494   for(m=first_procrec; m; m=m->next)
495     {
496       if (m->user)
497         continue;
498       for(u=first_utrec; u; u=u->next)
499         if (u->uid == m->uid)
500           break;
501       if (!u)
502         {
503           if (m->uid < 2 || m->ppid != 1)
504             continue;
505           u = xmalloc(sizeof(struct utrec));
506           bzero(u, sizeof(*u));
507           u->next = first_utrec;
508           first_utrec = u;
509           pw = getpwuid(u->uid = m->uid);
510           if (pw)
511             strcpy(u->user_name, pw->pw_name);
512           else
513             sprintf(u->user_name, "<%d>", m->uid);
514           u->mesg = 3;
515         }
516       if (!u->proc)
517         u->proc = m;
518       u->total_time += m->ctim;
519       u->detach++;
520       DBG("** daemon %s (%s)\n", m->cmd_line, u->user_name);
521     }
522 }
523
524 static inline int
525 comp(struct utrec *a, struct utrec *b)
526 {
527   int k;
528   if (b->mesg == 3)
529     return -1;
530   k = strcmp(a->user_name, b->user_name);
531   if (k)
532     return k;
533   if (!a->host_name[0] && b->host_name[0])
534     return -1;
535   return strcmp(a->line, b->line);
536 }
537
538 static void
539 sort(void)
540 {
541   struct utrec *fi = NULL;
542   struct utrec *z, **y, **m, **l;
543   l = &fi;
544   while (first_utrec)
545     {
546       y = &first_utrec;
547       m = y;
548       while (z = *y)
549         {
550           if (comp(z, *m) < 0)
551             m = y;
552           y = &z->next;
553         }
554       z = *m;
555       *m = z->next;
556       *l = z;
557       z->next = NULL;
558       l = &z->next;
559     }
560   first_utrec = fi;
561 }
562
563 static void
564 show(void)
565 {
566   struct utrec *u;
567   unsigned char *c;
568   printf("Name     Li  MD %-*s LogT  IdleT RunT  Command\n", maxhost, "From");
569   for(u=first_utrec; u; u=u->next)
570     {
571       if (!u->line[0])
572         strcpy(u->line, "--");
573       printf("%-8.8s %-3s %c%c %-*.*s ",
574              u->user_name,
575              u->line,
576              u->mesg ? ' ' : '-',
577              u->detach ? 'D' : ' ',
578              maxhost,
579              maxhost,
580              u->host_name);
581       if (u->mesg <= 1)
582         {
583           if (u->login_time > now)
584             u->login_time = now;
585           puttime(now - u->login_time);
586           putchar(' ');
587           if (u->click_time > now)
588             u->click_time = now;
589           if (now - u->click_time >= 60)
590             puttime(now - u->click_time);
591           else
592             printf("     ");
593         }
594       else
595         printf("?????      ");
596       if (u->proc)
597         {
598           putchar(' ');
599           puttime((unsigned)u->total_time/(unsigned)HZ);
600           putchar(' ');
601           for (c = u->proc->cmd_line; *c; c++)
602             {
603               if (*c < 0x20 || (*c >= 0x7f && *c < 0xa0))
604                 putchar(' ');
605               else
606                 putchar(*c);
607             }
608         }
609       else
610         printf(" <nothing>");
611       putchar('\n');
612     }
613 }
614
615 int main(void)
616 {
617   readutmp();
618   dispsys();
619   readproc();
620   solve();
621   sort();
622   show();
623   if (zombies)
624     {
625       printf("!!! There %s %d zombie%s walking around.\n",
626              zombies == 1 ? "is" : "are",
627              zombies,
628              zombies == 1 ? "" : "s" );
629     }
630   return 0;
631 }