chiark / gitweb /
Add some comments.
[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 long long execute(mode_type mode, bool entire, const char *show);
125
126 static const char default_seed[] = "hexapodia as the key insight";
127 static void *seed;
128 static size_t seedlen;
129 static const char *seedpath;
130 static const char *path;
131 static bool entireopt = false;
132 static bool flush = false;
133 static bool progress = false;
134 static long long size;
135
136 int main(int argc, char **argv) {
137   mode_type mode = BOTH;
138   int n;
139   char *ep;
140   while((n = getopt_long(argc, argv, "+s:S:L:vcepfhV", opts, 0)) >= 0) {
141     switch(n) {
142     case 's': seed = optarg; seedlen = strlen(optarg); break;
143     case 'S': seedpath = optarg; break;
144     case 'L':
145       seedlen = strtoul(optarg,&ep,0);
146       if(ep==optarg || *ep) fatal(0, "bad number for -S");
147       break;
148     case 'b': mode = BOTH; break;
149     case 'v': mode = VERIFY; break;
150     case 'c': mode = CREATE; break;
151     case 'e': entireopt = true; break;
152     case 'p': progress = true; break;
153     case 'f': flush = true; break;
154     case 'h': help(); exit(0);
155     case 'V': puts(VERSION); exit(0);
156     default:
157       fatal(0, "unknown option");
158     }
159   }
160   argc -= optind;
161   argv += optind;
162   /* expect PATH [SIZE] */
163   if(argc > 2)
164     fatal(0, "excess arguments");
165   /* If --both but no SIZE, assume a block device, which is to be filled */
166   if(argc == 1 && mode == BOTH)
167     entireopt = true;
168   if(entireopt) {
169     if(argc != 1)
170       fatal(0, "with --entire, size should not be specified");
171   } else {
172     /* --create without --entire requires PATH SIZE
173      * --verify just requires PATH, SIZE is optional */
174     if(argc < (mode == VERIFY ? 1 : 2))
175       fatal(0, "insufficient arguments");
176   }
177   if(seed && seedpath)
178     fatal(0, "both --seed and --seed-file specified");
179   if(mode == BOTH && !seed && !seedpath) {
180     /* --both and no seed specified; pick a random one */
181 #ifdef HAVE_RANDOM_DEVICE
182     seedpath = RANDOM_DEVICE;
183 #else
184     fatal(0, "no --seed or --seed-file specified in --both mode"
185           " and random device not supported on this system");
186 #endif
187   }
188   if(seedpath) {
189     if(!seedlen)
190       seedlen = DEFAULT_SEED_LENGTH;
191     FILE *seedfile = fopen(seedpath, "rb");
192     if(!seedfile)
193       fatal(errno, "%s", seedpath);
194     seed = malloc(seedlen);
195     if(!seed)
196       fatal(errno, "allocate seed");
197     seedlen = fread(seed, 1, seedlen, seedfile);
198     if(ferror(seedfile))
199       fatal(errno, "read %s", seedpath);
200     fclose(seedfile);
201   }
202   if (!seed) {
203     /* No seed specified, use a constant */
204     seed = (void*)default_seed;
205     seedlen = sizeof(default_seed)-1;
206   }
207   path = argv[0];
208   if(argc > 1) {
209     /* Explicit size specified */
210     errno = 0;
211     char *end;
212     size = strtoll(argv[1], &end, 10);
213     if(errno)
214       fatal(errno, "invalid size");
215     if(end == argv[1])
216       fatal(0, "invalid size");
217     if(!strcmp(end, "K"))
218       size *= 1024;
219     else if(!strcmp(end, "M"))
220       size *= 1024 * 1024;
221     else if(!strcmp(end, "G"))
222       size *= 1024 * 1024 * 1024;
223     else if(*end)
224       fatal(0, "invalid size");
225   } else if(entireopt) {
226     /* Use stupidly large size as a proxy for 'infinite' */
227     size = LLONG_MAX;
228   } else {
229     /* Retrieve size from target (which must exist) */
230     struct stat sb;
231     if(stat(path, &sb) < 0)
232       fatal(errno, "stat %s", path);
233     size = sb.st_size;
234   }
235   const char *show = entireopt ? (mode == CREATE ? "written" : "verified") : 0;
236   if(mode == BOTH) {
237     size = execute(CREATE, entireopt, 0);
238     execute(VERIFY, false, show);
239   } else {
240     execute(mode, entireopt, show);
241   }
242   return 0;
243 }
244
245 // flush stdout, fatal on error
246 static void flushstdout() {
247   if(ferror(stdout) || fflush(stdout))
248     fatal(errno, "flush stdout");
249 }
250
251 // clear the progress indicator
252 static void clearprogress() {
253   if (!progress) return;
254   printf(" %-10s %*s   \r", "", (int)sizeof(long long)*4, "");
255   flushstdout();
256 }
257
258 // update progress indicator
259 static void showprogress(long long amount, const char *show) {
260   if (!progress) return;
261
262   static int counter;
263   if (counter++ < 1000) return;
264   counter = 0;
265
266   int triples = sizeof(amount);
267   char rawbuf[triples*3 + 1];
268   char outbuf[triples*4 + 1];
269   snprintf(rawbuf, sizeof(rawbuf), "% *lld", (int)sizeof(rawbuf)-1, amount);
270   for (int i=0; i<triples; i++) {
271     outbuf[i*4] = ' ';
272     memcpy(outbuf + i*4 + 1, rawbuf + i*3, 3);
273   }
274   outbuf[triples*4] = 0;
275   printf(" %-10s %s...\r", outbuf, show);
276   flushstdout();
277 }
278
279 // write/verify the target file
280 static long long execute(mode_type mode, bool entire, const char *show) {
281   Arcfour rng((const char*)seed, seedlen);
282   FILE *fp = fopen(path, mode == VERIFY ? "rb" : "wb");
283   if(!fp)
284     fatal(errno, "%s", path);
285   if(mode == VERIFY && flush)
286     flushCache(fp);
287   if(mode == CREATE && entire)
288     setvbuf(fp, 0, _IONBF, 0);
289   char generated[4096], input[4096];
290   long long remain = size;
291   static const size_t rc4drop = 3072; // en.wikipedia.org/wiki/RC4#Security
292   assert(rc4drop <= sizeof(generated));
293   rng.stream(generated, rc4drop);
294   while(remain > 0) {
295     size_t bytesGenerated = (remain > (ssize_t)sizeof generated
296                              ? sizeof generated
297                              : remain);
298     rng.stream(generated, bytesGenerated);
299     if(mode == CREATE) {
300       size_t bytesWritten = fwrite(generated, 1, bytesGenerated, fp);
301       if(ferror(fp)) {
302         if(!entire || errno != ENOSPC)
303           fatal(errno, "%s", path);
304         remain -= bytesWritten;
305         break;
306       }
307       assert(bytesWritten == bytesGenerated);
308     } else {
309       size_t bytesRead = fread(input, 1, bytesGenerated, fp);
310       if(ferror(fp))
311         fatal(errno, "%s", path);
312       if(memcmp(generated, input, bytesRead)) {
313         for(size_t n = 0; n < bytesRead; ++n)
314           if(generated[n] != input[n])
315             fatal(0, "%s corrupted at %lld/%lld bytes (expected %d got %d)",
316                     path, size - remain + n, size,
317                     (unsigned char)generated[n], (unsigned char)input[n]);
318       }
319       /* Truncated */
320       if(bytesRead < bytesGenerated) {
321         if(entire) {
322           assert(feof(fp));
323           remain -= bytesRead;
324           break;
325         }
326         fatal(0, "%s: truncated at %lld/%lld bytes",
327                 path, (size - remain + bytesRead), size);
328       }
329     }
330     remain -= bytesGenerated;
331     showprogress(size - remain, mode == VERIFY ? "verifying" : "writing");
332   }
333   clearprogress();
334   if(mode == VERIFY && !entire && getc(fp) != EOF)
335     fatal(0, "%s: extended beyond %lld bytes",
336             path, size);
337   if(mode == CREATE && flush) {
338     if(fflush(fp) < 0)
339       fatal(errno, "%s", path);
340     flushCache(fp);
341   }
342   if(fclose(fp) < 0)
343     fatal(errno, "%s", path);
344   /* Actual size written/verified */
345   long long done = size - remain;
346   if(show) {
347     printf("%lld bytes (%lldM, %lldG) %s\n",
348            done, done >> 20, done >> 30,
349            show);
350     flushstdout();
351   }
352   return done;
353 }