chiark / gitweb /
0cd7a4e566b6acabf37c809d3cc5651f0bcaaa14
[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
36
37 /* Sadly this thing is not very portable */
38
39 #if defined(__linux__)
40
41 #include <sys/types.h>
42 #include <sys/acct.h>
43
44 typedef struct acct_v3 struct_acct;
45 #define HAVE_AC_EXITCODE
46 #define HAVE_AC_FLT
47 #define FIELD_AC_FLAG(as) ((as)->ac_flag)
48
49 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
50
51 #include <sys/param.h>
52 #include <sys/types.h>
53 #include <sys/acct.h>
54
55 typedef struct acctv2 struct_acct;
56 #define HAVE_AC_IO_MEM
57 #define FIELD_AC_FLAG(as) ((as)->ac_flagx & ~ANVER)
58
59 #else
60
61 #error Do not know what struct_acct to use on this platform
62
63 #endif
64
65
66 #include "myopt.h"
67
68 static int forwards, nobanner, usestdin, raw, usages;
69
70 static int de_used, de_allocd;
71 static struct deventry {
72   const char *fn;
73   dev_t dev;
74 } *deventries;
75
76 static const struct cmdinfo cmdinfos[]= {
77   { "--forwards",  'f',  0, &forwards, 0, 0, 1, 0, 0 },
78   { "--no-banner", 'q',  0, &nobanner, 0, 0, 1, 0, 0 },
79   { "--stdin",     'p',  0, &usestdin, 0, 0, 1, 0, 0 },
80   { "--raw",       'r',  0, &raw,      0, 0, 1, 0, 0 },
81   { "--resource",  'u',  0, &usages,   0, 0, 1, 0, 0 },
82   {  0                                                 }
83 };
84
85 #ifdef HAVE_AC_EXITCODE
86 static const char *sigabbrev[]= {
87   "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE",
88   "KILL", "USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT",
89   "CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU",
90   "XFSZ", "VTALRM", "PROF", "WINCH", "IO"
91 };
92 #endif
93
94 void usagemessage(void) {
95   fputs("usage: acctdump [<options>] [<file> ...]\n"
96         "options: -f|--forwards -q|--no-banner -p|--stdin -r|--raw -u|--resource\n",
97         stderr);
98   if (ferror(stderr)) { perror("print usage"); exit(8); }
99 }
100
101 static void checkstdout(void) {
102   if (ferror(stdout)) { perror("stdout"); exit(8); }
103 }
104
105 static void scandev(const char *basename, int levelsleft) {
106   /* We deliberately ignore most errors */
107   DIR *dir;
108   struct dirent *de;
109   struct stat stab;
110   int fnbufalloc, fnbufreq, r, basel, nallocd;
111   char *fnbuf, *nfnbuf;
112   struct deventry *ndeventries;
113   
114   if (levelsleft==0) return;
115
116   dir= opendir(basename); 
117   if (!dir) {
118     fprintf(stderr, "%s: opendir: %s\n", basename, strerror(errno));
119     return;
120   }
121   fnbufalloc= 0;
122   fnbuf= 0;
123   basel= strlen(basename);
124
125   while ((errno=0, de= readdir(dir))) {
126     fnbufreq= basel+1+strlen(de->d_name)+1;
127     if (fnbufalloc<fnbufreq) {
128       fnbufalloc= fnbufreq+10;
129       nfnbuf= realloc(fnbuf,fnbufalloc);
130       if (!nfnbuf) { free(fnbuf); fnbufalloc=0; continue; }
131       fnbuf= nfnbuf;
132     }
133     sprintf(fnbuf,"%s/%s",basename,de->d_name);
134     r= lstat(fnbuf,&stab);
135     if (r) {
136       fprintf(stderr, "%s: %s\n", fnbuf, strerror(errno));
137       continue;
138     }
139     if (S_ISCHR(stab.st_mode)) {
140       if (de_used >= de_allocd) {
141         nallocd= (de_allocd+10)<<1;
142         ndeventries= realloc(deventries,nallocd*sizeof(*deventries));
143         if (!ndeventries) continue;
144         de_allocd= nallocd;
145         deventries= ndeventries;
146       }
147       deventries[de_used].fn= strdup(fnbuf+5); /* remove /dev */
148       if (!deventries[de_used].fn) continue;
149       deventries[de_used].dev= stab.st_rdev;
150       de_used++;
151     } else if (S_ISDIR(stab.st_mode) && de->d_name[0] != '.') {
152       scandev(fnbuf,levelsleft-1);
153     }
154   }
155   if (errno)
156       fprintf(stderr, "%s: readdir: %s\n", basename, strerror(errno));
157   closedir(dir);
158   free(fnbuf);
159 }
160
161 static int walkdev_cptr(const void *av, const void *bv) {
162   const struct deventry *a= av;
163   const struct deventry *b= bv;
164   return a->dev - b->dev;
165 }
166   
167 static void printbanner(void) {
168   if (raw) {
169     fputs("begin date command          "
170           "uid      gid      tty dev  FSDX "
171 #ifdef HAVE_AC_EXITCODE
172           "exit"
173 #endif
174           , stdout);
175   } else {
176     fputs("begin date and time command          "
177           "user     group    tty dev    FSDX "
178 #ifdef HAVE_AC_EXITCODE
179           "sigexit"
180 #endif
181           , stdout);
182   }
183   if (usages) {
184     fputs("  user time   sys time  elap time "
185 #ifdef HAVE_AC_FLT
186           "  minflt   maxflt"
187 #endif
188 #ifdef HAVE_AC_IO_MEM
189           "  avg.mem      io"
190 #endif
191           , stdout);
192   }
193   putchar('\n');
194   checkstdout();
195 }
196
197 static void printrecord(const struct_acct *as, const char *filename) {
198   static int walkeddev;
199
200   int i, r;
201   const char *fp;
202   char buf[100];
203   struct tm *tm;
204   struct deventry *deve, devlookfor;
205   struct passwd *pw;
206   struct group *gr;
207   time_t btime;
208
209   if (raw) {
210     printf("%10lu ",(unsigned long)as->ac_btime);
211   } else {
212     btime= as->ac_btime;
213     tm= localtime(&btime);
214     strftime(buf,sizeof(buf),"%Y-%m-%d %H:%M:%S",tm); buf[sizeof(buf)-1]= 0;
215     printf("%19s ",buf);
216   }
217   
218   printf("%-16.16s ", as->ac_comm);
219   
220   pw= raw ? 0 : getpwuid(as->ac_uid);
221   if (pw) printf("%-8s ",pw->pw_name);
222   else printf("%-8ld ",(long)as->ac_uid);
223   
224   gr= raw ? 0 : getgrgid(as->ac_gid);
225   if (gr) printf("%-8s ",gr->gr_name);
226   else printf("%-8ld ",(long)as->ac_gid);
227
228   if (raw) {
229     if (!(as->ac_tty + 1) /* check for -1 without knowing type */) {
230       printf("-        ");
231     } else {
232       printf("%08lx ",(unsigned long)as->ac_tty);
233     }
234   } else {
235     if (!(as->ac_tty + 1)) {
236       printf("-          ");
237     } else {
238       if (!walkeddev) {
239         scandev("/dev",4);
240         qsort(deventries,de_used,sizeof(*deventries),walkdev_cptr);
241         walkeddev= 1;
242       }
243       devlookfor.fn= 0;
244       devlookfor.dev= as->ac_tty;
245       deve= bsearch(&devlookfor,deventries,de_used,sizeof(*deventries),walkdev_cptr);
246       if (deve) {
247         printf("%-10s ",deve->fn);
248       } else {
249         printf("%08lx   ",(unsigned long)as->ac_tty);
250       }
251     }
252   }
253
254   r= FIELD_AC_FLAG(as);
255   for (i=1, fp= "FS4DX"; *fp; fp++, i<<=1) {
256     if (r&i) {
257       putchar(*fp);
258       r &= ~i;
259     } else if (!isdigit(*fp)) {
260       putchar(' ');
261     }
262   }
263   if (r) {
264     printf("#%x",r);
265   }
266   putchar(' ');
267
268 #ifdef HAVE_AC_EXITCODE
269   int dc;
270   dc= WCOREDUMP(as->ac_exitcode) ? 'd' : 'k';
271   if (raw) {
272     if (WIFEXITED(as->ac_exitcode)) {
273       printf(" %3d",WEXITSTATUS(as->ac_exitcode));
274     } else if (WIFSIGNALED(as->ac_exitcode)) {
275       printf("%c%3d",
276              dc,
277              WTERMSIG(as->ac_exitcode));
278     } else {
279       printf("%04lx",(unsigned long)as->ac_exitcode);
280     }
281   } else {
282     if (WIFEXITED(as->ac_exitcode)) {
283       printf(" %6d",WEXITSTATUS(as->ac_exitcode));
284     } else if (WIFSIGNALED(as->ac_exitcode)) {
285       r= WTERMSIG(as->ac_exitcode);
286       if (r>0 && r<=sizeof(sigabbrev)/sizeof(*sigabbrev)) {
287         printf("%c%6s",
288                dc,
289                sigabbrev[r-1]);
290       } else {
291         printf("%cSIG%-3d",
292                dc,
293                r);
294       }
295     } else {
296       printf("#%04lx",(unsigned long)as->ac_exitcode);
297     }
298   }
299 #endif /*HAVE_AC_EXITCODE*/
300
301   if (usages) {
302     printf(" %10lu %10lu %10lu",
303            (unsigned long)as->ac_utime,
304            (unsigned long)as->ac_stime,
305            (unsigned long)as->ac_etime);
306 #ifdef HAVE_AC_FLT
307     printf(" %8lu %8lu",
308            (unsigned long)as->ac_minflt,
309            (unsigned long)as->ac_majflt);
310 #endif
311 #ifdef HAVE_AC_IO_MEM
312     printf(" %4e %4e",
313            as->ac_mem,
314            as->ac_io);
315 #endif
316   }
317   putchar('\n');
318
319   checkstdout();
320 }
321
322 static void processfile(FILE *file, const char *filename) {
323   struct_acct as;
324   long pos;
325   int r;
326   
327   if (forwards) {
328     while ((r= fread(&as,1,sizeof(as),file)) == sizeof(as)) {
329       printrecord(&as,filename);
330     }
331   } else {
332     r= fseek(file,0,SEEK_END); if (r) { perror(filename); exit(8); }
333     pos= ftell(file); if (pos==-1) { perror(filename); exit(8); }
334     if (pos % sizeof(as)) { 
335       fprintf(stderr, "%s: File size is not an integral number "
336               "of accounting records\n", filename);
337       exit(8);
338     }
339     for (;;) {
340       if (pos<sizeof(as)) break;
341       pos -= sizeof(as);
342       r= fseek(file,pos,SEEK_SET); if (r==-1) { perror(filename); exit(8); }
343       r= fread(&as,1,sizeof(as),file); if (r!=sizeof(as)) { perror(filename); exit(8); }
344       printrecord(&as,filename);
345     }
346   }
347   if (ferror(file) || fclose(file)) { perror(filename); exit(8); }
348 }
349
350 static void processnamedfile(const char *filename) {
351   FILE *file;
352
353   file= fopen(filename,"rb"); if (!file) { perror(filename); exit(8); }
354   processfile(file,filename);
355 }
356
357 int main(int argc, const char *const *argv) {
358   myopt(&argv,cmdinfos);
359   if (!nobanner) printbanner();
360   if (usestdin) {
361     processfile(stdin,"<standard input>");
362   } else if (!*argv) {
363     processnamedfile("/var/log/account/pacct");
364   } else {
365     while (*argv) {
366       processnamedfile(*argv);
367       argv++;
368     }
369   }
370   checkstdout();
371   if (fflush(stdout)) { perror("flush stdout"); exit(8); }
372   return 0;
373 }