chiark / gitweb /
Fix printf field width types
[vbig.git] / vbig.cc
1 /*
2  * This file is part of vbig.
3  * Copyright (C) 2011 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 #include <config.h>
19 #include <cstdio>
20 #include <cstring>
21 #include <cstdlib>
22 #include <cerrno>
23 #include <cstdarg>
24 #include <getopt.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <assert.h>
29 #include <sys/stat.h>
30 #include "Arcfour.h"
31
32 #define DEFAULT_SEED_LENGTH 2048;
33
34 // Command line options
35 const struct option opts[] = {
36   { "seed", required_argument, 0, 's' },
37   { "seed-file", required_argument, 0, 'S' },
38   { "seed-length", required_argument, 0, 'L' },
39   { "both", no_argument, 0, 'b' },
40   { "verify", no_argument, 0, 'v' },
41   { "create", no_argument, 0, 'c' },
42   { "flush", no_argument, 0, 'f' },
43   { "entire", no_argument, 0, 'e' },
44   { "progress", no_argument, 0, 'p' },
45   { "help", no_argument, 0, 'h' },
46   { "version", no_argument, 0, 'V' },
47   { 0, 0, 0, 0 },
48 };
49
50 // Display help message
51 static void help(void) {
52   printf("vbig - create or verify a large but pseudo-random file\n"
53          "\n"
54          "Usage:\n"
55          "  vbig [OPTIONS] [--both|--verify|--create] PATH] [SIZE]\n"
56          "\n"
57          "Options:\n"
58          "  --seed, -s        Specify random seed as string\n"
59          "  --seed-file, -S   Read random seed from (start of) this file\n"
60          "  --seed-length, -L Set (maximum) seed length to read from file\n"
61          "  --verify, -v      Verify that PATH contains the expected contents\n"
62          "  --create, -c      Create PATH with psuedo-random contents\n"
63          "  --both, -b        Do both create and verify (default)\n"
64          "  --flush, -f       Flush cache\n"
65          "  --entire, -e      Write until full; read until EOF\n"
66          "  --progress, -p    Show progress as we go\n"
67          "  --help, -h        Display usage message\n"
68          "  --version, -V     Display version string\n");
69 }
70
71 // Possible modes of operation
72 enum mode_type {
73   VERIFY,
74   CREATE,
75   BOTH
76 };
77
78 static void clearprogress();
79
80 // Report an error and exit
81 static void fatal(int errno_value, const char *fmt, ...) {
82   va_list ap;
83   clearprogress();
84   fprintf(stderr, "ERROR: ");
85   va_start(ap, fmt);
86   vfprintf(stderr, fmt, ap);
87   va_end(ap);
88   if(errno_value)
89     fprintf(stderr, ": %s", strerror(errno_value));
90   fputc('\n', stderr);
91   exit(1);
92 }
93
94 // Evict whatever FP points to from RAM
95 static void flushCache(FILE *fp) {
96   // drop_caches only evicts clean pages, so first the target file is
97   // synced.
98   if(fsync(fileno(fp)) < 0)
99     fatal(errno, "fsync");
100 #if defined DROP_CACHE_FILE
101   int fd;
102   if((fd = open(DROP_CACHE_FILE, O_WRONLY, 0)) < 0)
103     fatal(errno, "%s", DROP_CACHE_FILE);
104   if(write(fd, "3\n", 2) < 0)
105     fatal(errno, "%s", DROP_CACHE_FILE);
106   close(fd);
107 #elif defined PURGE_COMMAND
108   int rc;
109   if((rc = system(PURGE_COMMAND)) < 0)
110     fatal(errno, "executing %s", PURGE_COMMAND);
111   else if(rc) {
112     if(WIFSIGNALED(rc)) {
113       fprintf(stderr, "%s%s\n", 
114               strsignal(WTERMSIG(rc)),
115               WCOREDUMP(rc) ? " (core dumped)" : "");
116       exit(WTERMSIG(rc) + 128);
117     } else
118       exit(WEXITSTATUS(rc));
119   }
120 #endif
121 }
122
123 static long long execute(mode_type mode, bool entire, const char *show);
124
125 static const char default_seed[] = "hexapodia as the key insight";
126 static void *seed;
127 static size_t seedlen;
128 static const char *seedpath;
129 static const char *path;
130 static bool entireopt = false;
131 static bool flush = false;
132 static bool progress = false;
133 static long long size;
134
135 int main(int argc, char **argv) {
136   mode_type mode = BOTH;
137   int n;
138   char *ep;
139   while((n = getopt_long(argc, argv, "+s:S:L:vcepfhV", opts, 0)) >= 0) {
140     switch(n) {
141     case 's': seed = optarg; seedlen = strlen(optarg); break;
142     case 'S': seedpath = optarg; break;
143     case 'L':
144       seedlen = strtoul(optarg,&ep,0);
145       if(ep==optarg || *ep) fatal(0, "bad number for -S");
146       break;
147     case 'b': mode = BOTH; break;
148     case 'v': mode = VERIFY; break;
149     case 'c': mode = CREATE; break;
150     case 'e': entireopt = true; break;
151     case 'p': progress = true; break;
152     case 'f': flush = true; break;
153     case 'h': help(); exit(0);
154     case 'V': puts(VERSION); exit(0);
155     default:
156       fatal(0, "unknown option");
157     }
158   }
159   argc -= optind;
160   argv += optind;
161   if(argc > 2)
162     fatal(0, "excess arguments");
163   if(argc == 1 && mode == BOTH)
164     entireopt = true;
165   if(entireopt) {
166     if(argc != 1)
167       fatal(0, "with --entire, size should not be specified");
168   } else {
169     if(argc < (mode == VERIFY ? 1 : 2))
170       fatal(0, "insufficient arguments");
171   }
172   if(seed && seedpath)
173     fatal(0, "both --seed and --seed-file specified");
174   if(mode == BOTH && !seed && !seedpath) {
175 #ifdef HAVE_RANDOM_DEVICE
176     seedpath = RANDOM_DEVICE;
177 #else
178     fatal(0, "no --seed or --seed-file specified in --both mode"
179           " and random device not supported on this system");
180 #endif
181   }
182   if(seedpath) {
183     if(!seedlen)
184       seedlen = DEFAULT_SEED_LENGTH;
185     FILE *seedfile = fopen(seedpath, "rb");
186     if(!seedfile)
187       fatal(errno, "%s", seedpath);
188     seed = malloc(seedlen);
189     if(!seed)
190       fatal(errno, "allocate seed");
191     seedlen = fread(seed, 1, seedlen, seedfile);
192     if(ferror(seedfile))
193       fatal(errno, "read %s", seedpath);
194     fclose(seedfile);
195   }
196   if (!seed) {
197     seed = (void*)default_seed;
198     seedlen = sizeof(default_seed)-1;
199   }
200   path = argv[0];
201   if(argc > 1) {
202     errno = 0;
203     char *end;
204     size = strtoll(argv[1], &end, 10);
205     if(errno)
206       fatal(errno, "invalid size");
207     if(end == argv[1])
208       fatal(0, "invalid size");
209     if(!strcmp(end, "K"))
210       size *= 1024;
211     else if(!strcmp(end, "M"))
212       size *= 1024 * 1024;
213     else if(!strcmp(end, "G"))
214       size *= 1024 * 1024 * 1024;
215     else if(*end)
216       fatal(0, "invalid size");
217   } else if(entireopt) {
218     size = LONG_LONG_MAX;
219   } else {
220     struct stat sb;
221     if(stat(path, &sb) < 0)
222       fatal(errno, "stat %s", path);
223     size = sb.st_size;
224   }
225   const char *show = entireopt ? (mode == CREATE ? "written" : "verified") : 0;
226   if(mode == BOTH) {
227     size = execute(CREATE, entireopt, 0);
228     execute(VERIFY, false, show);
229   } else {
230     execute(mode, entireopt, show);
231   }
232   return 0;
233 }
234
235 static void flushstdout() {
236   if(ferror(stdout) || fflush(stdout))
237     fatal(errno, "flush stdout");
238 }
239
240 static void clearprogress() {
241   if (!progress) return;
242   printf(" %-10s %*s   \r", "", (int)sizeof(long long)*4, "");
243   flushstdout();
244 }
245
246 static void showprogress(long long amount, const char *show) {
247   if (!progress) return;
248
249   static int counter;
250   if (counter++ < 1000) return;
251   counter = 0;
252
253   int triples = sizeof(amount);
254   char rawbuf[triples*3 + 1];
255   char outbuf[triples*4 + 1];
256   snprintf(rawbuf, sizeof(rawbuf), "% *lld", (int)sizeof(rawbuf)-1, amount);
257   for (int i=0; i<triples; i++) {
258     outbuf[i*4] = ' ';
259     memcpy(outbuf + i*4 + 1, rawbuf + i*3, 3);
260   }
261   outbuf[triples*4] = 0;
262   printf(" %-10s %s...\r", outbuf, show);
263   flushstdout();
264 }
265
266 static long long execute(mode_type mode, bool entire, const char *show) {
267   Arcfour rng((const char*)seed, seedlen);
268   FILE *fp = fopen(path, mode == VERIFY ? "rb" : "wb");
269   if(!fp)
270     fatal(errno, "%s", path);
271   if(mode == VERIFY && flush)
272     flushCache(fp);
273   if(mode == CREATE && entire)
274     setvbuf(fp, 0, _IONBF, 0);
275   char generated[4096], input[4096];
276   long long remain = size;
277   static const size_t rc4drop = 3072; // en.wikipedia.org/wiki/RC4#Security
278   assert(rc4drop <= sizeof(generated));
279   rng.stream(generated, rc4drop);
280   while(remain > 0) {
281     size_t bytesGenerated = (remain > (ssize_t)sizeof generated
282                              ? sizeof generated
283                              : remain);
284     rng.stream(generated, bytesGenerated);
285     if(mode == CREATE) {
286       size_t bytesWritten = fwrite(generated, 1, bytesGenerated, fp);
287       if(ferror(fp)) {
288         if(!entire || errno != ENOSPC)
289           fatal(errno, "%s", path);
290         remain -= bytesWritten;
291         break;
292       }
293       assert(bytesWritten == bytesGenerated);
294     } else {
295       size_t bytesRead = fread(input, 1, bytesGenerated, fp);
296       if(ferror(fp))
297         fatal(errno, "%s", path);
298       if(memcmp(generated, input, bytesRead)) {
299         for(size_t n = 0; n < bytesRead; ++n)
300           if(generated[n] != input[n])
301             fatal(0, "%s corrupted at %lld/%lld bytes (expected %d got %d)",
302                     path, size - remain + n, size,
303                     (unsigned char)generated[n], (unsigned char)input[n]);
304       }
305       if(bytesRead < bytesGenerated) {
306         if(entire) {
307           assert(feof(fp));
308           remain -= bytesRead;
309           break;
310         }
311         fatal(0, "%s: truncated at %lld/%lld bytes",
312                 path, (size - remain + bytesRead), size);
313       }
314     }
315     remain -= bytesGenerated;
316     showprogress(size - remain, mode == VERIFY ? "verifying" : "writing");
317   }
318   clearprogress();
319   if(mode == VERIFY && !entire && getc(fp) != EOF)
320     fatal(0, "%s: extended beyond %lld bytes",
321             path, size);
322   if(mode == CREATE && flush) {
323     if(fflush(fp) < 0)
324       fatal(errno, "%s", path);
325     flushCache(fp);
326   }
327   if(fclose(fp) < 0)
328     fatal(errno, "%s", path);
329   long long done = size - remain;
330   if(show) {
331     printf("%lld bytes (%lldM, %lldG) %s\n",
332            done, done >> 20, done >> 30,
333            show);
334     flushstdout();
335   }
336   return done;
337 }