chiark / gitweb /
4d3877f76ac5d72f0408553a42ff7aa8d3ca94c2
[chiark-utils.git] / cprogs / acctdump.c
1 /*
2  * acctdump.c - accounting data dump utility
3  *
4  * Copyright (C) 1998 Ian Jackson <ian@chiark.greenend.org.uk>
5  *
6  * This is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2,
9  * or (at your option) any later version.
10  *
11  * This is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this file; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <time.h>
24 #include <stdarg.h>
25 #include <wait.h>
26 #include <string.h>
27 #include <pwd.h>
28 #include <grp.h>
29 #include <dirent.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <sys/stat.h>
33
34 typedef unsigned long long u64;
35 #include <sys/acct.h>
36 typedef struct acct_v3 struct_acct;
37
38 #include "myopt.h"
39
40 static int forwards, nobanner, usestdin, raw, usages;
41
42 static int de_used, de_allocd;
43 static struct deventry {
44   const char *fn;
45   dev_t dev;
46 } *deventries;
47
48 static const struct cmdinfo cmdinfos[]= {
49   { "--forwards",  'f',  0, &forwards, 0, 0, 1, 0, 0 },
50   { "--no-banner", 'q',  0, &nobanner, 0, 0, 1, 0, 0 },
51   { "--stdin",     'p',  0, &usestdin, 0, 0, 1, 0, 0 },
52   { "--raw",       'r',  0, &raw,      0, 0, 1, 0, 0 },
53   { "--resource",  'u',  0, &usages,   0, 0, 1, 0, 0 },
54   {  0                                                 }
55 };
56
57 static const char *sigabbrev[]= {
58   "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE",
59   "KILL", "USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT",
60   "CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU",
61   "XFSZ", "VTALRM", "PROF", "WINCH", "IO"
62 };
63
64 static void usage(FILE *file) {
65   fputs("usage: acctdump [<options>] [<file> ...]\n"
66         "options: -f|--forwards -q|--no-banner -p|--stdin -r|--raw -u|--resource\n",
67         file);
68   if (ferror(file)) { perror("print usage"); exit(8); }
69 }
70
71 void badusage(const char *fmt, ...) {
72   va_list al;
73
74   fputs("usage error: ",stderr);
75   va_start(al,fmt);
76   vfprintf(stderr,fmt,al);
77   va_end(al);
78   fputs("\n",stderr);
79   usage(stderr);
80   exit(12);
81 }
82
83 static void checkstdout(void) {
84   if (ferror(stdout)) { perror("stdout"); exit(8); }
85 }
86
87 static void scandev(const char *basename, int levelsleft) {
88   /* We deliberately ignore most errors */
89   DIR *dir;
90   struct dirent *de;
91   struct stat stab;
92   int fnbufalloc, fnbufreq, r, basel, nallocd;
93   char *fnbuf, *nfnbuf;
94   struct deventry *ndeventries;
95   
96   if (levelsleft==0) return;
97
98   dir= opendir(basename); 
99   if (!dir) {
100     fprintf(stderr, "%s: opendir: %s\n", basename, strerror(errno));
101     return;
102   }
103   fnbufalloc= 0;
104   fnbuf= 0;
105   basel= strlen(basename);
106
107   while ((errno=0, de= readdir(dir))) {
108     fnbufreq= basel+1+strlen(de->d_name)+1;
109     if (fnbufalloc<fnbufreq) {
110       fnbufalloc= fnbufreq+10;
111       nfnbuf= realloc(fnbuf,fnbufalloc);
112       if (!nfnbuf) { free(fnbuf); fnbufalloc=0; continue; }
113       fnbuf= nfnbuf;
114     }
115     sprintf(fnbuf,"%s/%s",basename,de->d_name);
116     r= lstat(fnbuf,&stab);
117     if (r) {
118       fprintf(stderr, "%s: %s\n", fnbuf, strerror(errno));
119       continue;
120     }
121     if (S_ISCHR(stab.st_mode)) {
122       if (de_used >= de_allocd) {
123         nallocd= (de_allocd+10)<<1;
124         ndeventries= realloc(deventries,nallocd*sizeof(*deventries));
125         if (!ndeventries) continue;
126         de_allocd= nallocd;
127         deventries= ndeventries;
128       }
129       deventries[de_used].fn= strdup(fnbuf+5); /* remove /dev */
130       if (!deventries[de_used].fn) continue;
131       deventries[de_used].dev= stab.st_rdev;
132       de_used++;
133     } else if (S_ISDIR(stab.st_mode) && de->d_name[0] != '.') {
134       scandev(fnbuf,levelsleft-1);
135     }
136   }
137   if (errno)
138       fprintf(stderr, "%s: readdir: %s\n", basename, strerror(errno));
139   closedir(dir);
140   free(fnbuf);
141 }
142
143 static int walkdev_cptr(const void *av, const void *bv) {
144   const struct deventry *a= av;
145   const struct deventry *b= bv;
146   return a->dev - b->dev;
147 }
148   
149 static void printbanner(void) {
150   if (raw) {
151     fputs("begin date command          "
152           "uid      gid      tty dev  FSDX exit",
153           stdout);
154   } else {
155     fputs("begin date and time command          "
156           "user     group    tty dev    FSDX sigexit",
157           stdout);
158   }
159   if (usages) {
160     fputs("  user time   sys time  elap time   minflt   maxflt",
161           stdout);
162   }
163   putchar('\n');
164   checkstdout();
165 }
166
167 static void printrecord(const struct_acct *as, const char *filename) {
168   static int walkeddev;
169
170   int i, dc, r;
171   const char *fp;
172   char buf[100];
173   struct tm *tm;
174   struct deventry *deve, devlookfor;
175   struct passwd *pw;
176   struct group *gr;
177   time_t btime;
178
179   if (raw) {
180     printf("%10lu ",(unsigned long)as->ac_btime);
181   } else {
182     btime= as->ac_btime;
183     tm= localtime(&btime);
184     strftime(buf,sizeof(buf),"%Y-%m-%d %H:%M:%S",tm); buf[sizeof(buf)-1]= 0;
185     printf("%19s ",buf);
186   }
187   
188   printf("%-16.16s ", as->ac_comm);
189   
190   pw= raw ? 0 : getpwuid(as->ac_uid);
191   if (pw) printf("%-8s ",pw->pw_name);
192   else printf("%-8ld ",(long)as->ac_uid);
193   
194   gr= raw ? 0 : getgrgid(as->ac_gid);
195   if (gr) printf("%-8s ",gr->gr_name);
196   else printf("%-8ld ",(long)as->ac_gid);
197
198   if (raw) {
199     if (!(as->ac_tty + 1) /* check for -1 without knowing type */) {
200       printf("-        ");
201     } else {
202       printf("%08lx ",(unsigned long)as->ac_tty);
203     }
204   } else {
205     if (!(as->ac_tty + 1)) {
206       printf("-          ");
207     } else {
208       if (!walkeddev) {
209         scandev("/dev",4);
210         qsort(deventries,de_used,sizeof(*deventries),walkdev_cptr);
211         walkeddev= 1;
212       }
213       devlookfor.fn= 0;
214       devlookfor.dev= as->ac_tty;
215       deve= bsearch(&devlookfor,deventries,de_used,sizeof(*deventries),walkdev_cptr);
216       if (deve) {
217         printf("%-10s ",deve->fn);
218       } else {
219         printf("%08lx   ",(unsigned long)as->ac_tty);
220       }
221     }
222   }
223
224   r= as->ac_flag;
225   for (i=1, fp= "FS4DX"; *fp; fp++, i<<=1) {
226     if (r&i) {
227       putchar(*fp);
228       r &= ~i;
229     } else if (!isdigit(*fp)) {
230       putchar(' ');
231     }
232   }
233   if (r) {
234     printf("#%x",r);
235   }
236   putchar(' ');
237   
238   dc= WCOREDUMP(as->ac_exitcode) ? 'd' : 'k';
239   if (raw) {
240     if (WIFEXITED(as->ac_exitcode)) {
241       printf(" %3d",WEXITSTATUS(as->ac_exitcode));
242     } else if (WIFSIGNALED(as->ac_exitcode)) {
243       printf("%c%3d",
244              dc,
245              WTERMSIG(as->ac_exitcode));
246     } else {
247       printf("%04lx",(unsigned long)as->ac_exitcode);
248     }
249   } else {
250     if (WIFEXITED(as->ac_exitcode)) {
251       printf(" %6d",WEXITSTATUS(as->ac_exitcode));
252     } else if (WIFSIGNALED(as->ac_exitcode)) {
253       r= WTERMSIG(as->ac_exitcode);
254       if (r>0 && r<=sizeof(sigabbrev)/sizeof(*sigabbrev)) {
255         printf("%c%6s",
256                dc,
257                sigabbrev[r-1]);
258       } else {
259         printf("%cSIG%-3d",
260                dc,
261                r);
262       }
263     } else {
264       printf("#%04lx",(unsigned long)as->ac_exitcode);
265     }
266   }
267
268   if (usages) {
269     printf(" %10lu %10lu %10lu %8ld %8ld",
270            (unsigned long)as->ac_utime,
271            (unsigned long)as->ac_stime,
272            (unsigned long)as->ac_etime,
273            (unsigned long)as->ac_minflt,
274            (unsigned long)as->ac_majflt);
275   }
276   putchar('\n');
277
278   checkstdout();
279 }
280
281 static void processfile(FILE *file, const char *filename) {
282   struct_acct as;
283   long pos;
284   int r;
285   
286   if (forwards) {
287     while ((r= fread(&as,1,sizeof(as),file)) == sizeof(as)) {
288       printrecord(&as,filename);
289     }
290   } else {
291     r= fseek(file,0,SEEK_END); if (r) { perror(filename); exit(8); }
292     pos= ftell(file); if (pos==-1) { perror(filename); exit(8); }
293     if (pos % sizeof(as)) { 
294       fprintf(stderr, "%s: File size is not an integral number "
295               "of accounting records\n", filename);
296       exit(8);
297     }
298     for (;;) {
299       if (pos<sizeof(as)) break;
300       pos -= sizeof(as);
301       r= fseek(file,pos,SEEK_SET); if (r==-1) { perror(filename); exit(8); }
302       r= fread(&as,1,sizeof(as),file); if (r!=sizeof(as)) { perror(filename); exit(8); }
303       printrecord(&as,filename);
304     }
305   }
306   if (ferror(file) || fclose(file)) { perror(filename); exit(8); }
307 }
308
309 static void processnamedfile(const char *filename) {
310   FILE *file;
311
312   file= fopen(filename,"rb"); if (!file) { perror(filename); exit(8); }
313   processfile(file,filename);
314 }
315
316 int main(int argc, const char *const *argv) {
317   myopt(&argv,cmdinfos);
318   if (!nobanner) printbanner();
319   if (usestdin) {
320     processfile(stdin,"<standard input>");
321   } else if (!*argv) {
322     processnamedfile("/var/log/account/pacct");
323   } else {
324     while (*argv) {
325       processnamedfile(*argv);
326       argv++;
327     }
328   }
329   checkstdout();
330   if (fflush(stdout)) { perror("flush stdout"); exit(8); }
331   return 0;
332 }