]> mj.ucw.cz Git - ywho.git/blob - ywho.c
make release: Reorganized my directory structure
[ywho.git] / ywho.c
1 /*
2  *      Extended `who' command, version 1.12.
3  *
4  *      (c) 1996--2010 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       z = strchr(line, '\n');
278       if (z)
279         *z = 0;
280       z = line;
281       while (i-- && z)
282         {
283           if (z > line)
284             *z = '/';
285           z = strchr(z, ' ');
286         }
287       if (z)
288         {
289           char *k;
290           *z++ = 0;
291           k = strchr(z, ' ');
292           if (k)
293             *k = 0;
294           printf("R/T=%s, ", z);
295         }
296       else
297         z = line;
298       printf("LAV=%s", line);
299       fclose(f);
300     }
301
302   if (f = fopen("/proc/meminfo", "r"))
303     {
304       int free, buffers, cached, stotal, sfree;
305       free = buffers = stotal = sfree = 0;
306       while (fgets(line, 256, f))
307         {
308           if (!strncmp(line, "MemFree:", 8))
309             sscanf(line+8, "%d", &free);
310           else if (!strncmp(line, "Buffers:", 8))
311             sscanf(line+8, "%d", &buffers);
312           else if (!strncmp(line, "Cached:", 7))
313             sscanf(line+7, "%d", &cached);
314           else if (!strncmp(line, "SwapTotal:", 10))
315             sscanf(line+10, "%d", &stotal);
316           else if (!strncmp(line, "SwapFree:", 9))
317             sscanf(line+9, "%d", &sfree);
318         }
319       printf(", free ");
320       memory(1024*(free+buffers+cached));
321       printf(" of RAM");
322       if (stotal != sfree)
323         {
324           printf(", used ");
325           memory(1024*(stotal - sfree));
326           printf(" of swap");
327         }
328     }
329   printf(", %d user%s\n", usercnt, usercnt == 1 ? "" : "s");
330 }
331
332 static void
333 readproc(void)
334 {
335   DIR *d;
336   struct dirent *e;
337   struct winsize win;
338   unsigned cmdcols;
339 #define LEFTSIZE 35
340   
341   if (!ioctl(1, TIOCGWINSZ, &win) && win.ws_col >= LEFTSIZE + maxhost + 10 && win.ws_col < 1024)
342     cmdcols = win.ws_col;
343   else
344     cmdcols = 80;
345   cmdcols -= LEFTSIZE + maxhost;
346   if (d = opendir("/proc"))
347     {
348       while (e = readdir(d))
349         {
350           int i;
351           if (sscanf(e->d_name, "%d", &i)==1)
352             {
353               struct procrec *p = xmalloc(sizeof(struct procrec) + cmdcols);
354               struct stat st;
355               char name[256], eman[1024];
356               int fil;
357               bzero(p, sizeof(*p));
358               p->pid = i;
359               strcpy(name, "/proc/");
360               strcat(name, e->d_name);
361               if (!stat(name, &st))
362                 {
363                   p->uid = st.st_uid;
364                   strcpy(eman, name);
365                   strcat(eman, "/cmdline");
366                   if ((fil = open(eman, O_RDONLY)) >= 0)
367                     {
368                       int y, z = read(fil, p->cmd_line, cmdcols);
369                       if (z < 0)
370                         z = 0;
371                       for (y=0; y<z; y++)
372                         if (!p->cmd_line[y])
373                           p->cmd_line[y] = ' ';
374                       p->cmd_line[z] = 0;
375                       close(fil);
376                     }
377                   strcpy(eman, name);
378                   strcat(eman, "/stat");
379                   if ((fil = open(eman, O_RDONLY)) >= 0)
380                     {
381                       int z = read(fil, eman, 1023);
382                       char *j, *k;
383                       int trash, utim, stim, cutim, cstim;
384                       if (z < 0)
385                         z = 0;
386                       eman[z] = 0;
387                       if ((j = strchr(eman, '(')) && (k = strchr(j+1, ')')))
388                         {
389                           *k = 0;
390                           if (!p->cmd_line[0])
391                             {
392                               strncpy(p->cmd_line, j+1, cmdcols);
393                               p->cmd_line[cmdcols] = 0;
394                             }
395                           p->state = k[2];
396                           if (p->state == 'Z')
397                             zombies++;
398                           sscanf(k+4, "%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
399                                  &p->ppid, &p->pgrp, &p->sess, &trash, &trash,
400                                  &trash, &trash, &trash, &trash, &trash, &utim,
401                                  &stim, &cutim, &cstim);
402                           DBG("PROC: pid=%d ppid=%d pgrp=%d sess=%d uid=%d\n", p->pid, p->ppid, p->pgrp, p->sess, p->uid);
403                           p->next = first_procrec;
404                           first_procrec = p;
405                         }
406                       p->tim = utim + stim;
407                       p->ctim = cutim + cstim;
408                       close(fil);
409                     }
410                 }
411             }
412         }
413       closedir(d);
414     }
415   else
416     {
417       perror("unable to scan /proc");
418       exit(1);
419     }
420 }
421
422 static void
423 solve(void)
424 {
425   struct utrec *u;
426   struct procrec *m, *n;
427   struct passwd *pw;
428   int cnt;
429
430   /* Recognize login session process trees and find leaves of these trees */
431   for (u=first_utrec; u; u=u->next)
432     {
433       for (m=first_procrec; m; m=m->next)
434         if (m->pid == u->login_pid)
435           {
436             m->user = u;
437             u->total_time = m->ctim;
438             u->proc = m;
439             DBG("** %d is login process for %s@%s\n", m->pid, u->user_name, u->line);
440           }
441     }
442   do
443     {
444       cnt = 0;
445       for (m=first_procrec; m; m=m->next)
446         if (!m->user)
447           for (n=first_procrec; n; n=n->next)
448             if (n->pid == m->ppid && n->user)
449               {
450                 u = m->user = n->user;
451                 m->distance = n->distance + 1;
452                 if (!u->proc || u->proc->distance < m->distance)
453                   u->proc = m;
454                 cnt++;
455                 DBG("** %d at distance %d for %s@%s\n", m->pid, m->distance, u->user_name, u->line);
456                 break;
457               }
458     }
459   while (cnt);
460
461   /* Process the remaining processes */
462   for(m=first_procrec; m; m=m->next)
463     {
464       if (m->user)
465         continue;
466       for(u=first_utrec; u; u=u->next)
467         if (u->uid == m->uid)
468           break;
469       if (!u)
470         {
471           if (m->uid < 2 || m->ppid != 1)
472             continue;
473           u = xmalloc(sizeof(struct utrec));
474           bzero(u, sizeof(*u));
475           u->next = first_utrec;
476           first_utrec = u;
477           pw = getpwuid(u->uid = m->uid);
478           if (pw)
479             strcpy(u->user_name, pw->pw_name);
480           else
481             sprintf(u->user_name, "<%d>", m->uid);
482           u->mesg = 3;
483         }
484       if (!u->proc)
485         u->proc = m;
486       u->total_time += m->ctim;
487       u->detach++;
488       DBG("** daemon %s (%s)\n", m->cmd_line, u->user_name);
489     }
490 }
491
492 static inline int
493 comp(struct utrec *a, struct utrec *b)
494 {
495   int k;
496   if (b->mesg == 3)
497     return -1;
498   k = strcmp(a->user_name, b->user_name);
499   if (k)
500     return k;
501   if (!a->host_name[0] && b->host_name[0])
502     return -1;
503   return strcmp(a->line, b->line);
504 }
505
506 static void
507 sort(void)
508 {
509   struct utrec *fi = NULL;
510   struct utrec *z, **y, **m, **l;
511   l = &fi;
512   while (first_utrec)
513     {
514       y = &first_utrec;
515       m = y;
516       while (z = *y)
517         {
518           if (comp(z, *m) < 0)
519             m = y;
520           y = &z->next;
521         }
522       z = *m;
523       *m = z->next;
524       *l = z;
525       z->next = NULL;
526       l = &z->next;
527     }
528   first_utrec = fi;
529 }
530
531 static void
532 show(void)
533 {
534   struct utrec *u;
535   unsigned char *c;
536   printf("Name     Li  MD %-*s LogT  IdleT RunT  Command\n", maxhost, "From");
537   for(u=first_utrec; u; u=u->next)
538     {
539       if (!u->line[0])
540         strcpy(u->line, "--");
541       printf("%-8.8s %-3s %c%c %-*.*s ",
542              u->user_name,
543              u->line,
544              u->mesg ? ' ' : '-',
545              u->detach ? 'D' : ' ',
546              maxhost,
547              maxhost,
548              u->host_name);
549       if (u->mesg <= 1)
550         {
551           if (u->login_time > now)
552             u->login_time = now;
553           puttime(now - u->login_time);
554           putchar(' ');
555           if (u->click_time > now)
556             u->click_time = now;
557           if (now - u->click_time >= 60)
558             puttime(now - u->click_time);
559           else
560             printf("     ");
561         }
562       else
563         printf("?????      ");
564       if (u->proc)
565         {
566           putchar(' ');
567           puttime((unsigned)u->total_time/(unsigned)HZ);
568           putchar(' ');
569           for (c = (unsigned char *) u->proc->cmd_line; *c; c++)
570             {
571               if (*c < 0x20 || (*c >= 0x7f && *c < 0xa0))
572                 putchar(' ');
573               else
574                 putchar(*c);
575             }
576         }
577       else
578         printf(" <nothing>");
579       putchar('\n');
580     }
581 }
582
583 int main(void)
584 {
585   readutmp();
586   line1();
587   line2();
588   readproc();
589   solve();
590   sort();
591   show();
592   if (zombies)
593     {
594       printf("!!! There %s %d zombie%s walking around.\n",
595              zombies == 1 ? "is" : "are",
596              zombies,
597              zombies == 1 ? "" : "s" );
598     }
599   return 0;
600 }