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