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