chiark / gitweb /
New --progress option
[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 [--seed SEED] --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          "  --flush, -f       Flush cache\n"
64          "  --entire, -e      Write until full; read until EOF\n"
65          "  --progress, -p    Show progress as we go\n"
66          "  --help, -h        Display usage message\n"
67          "  --version, -V     Display version string\n");
68 }
69
70 // Possible modes of operation
71 enum mode_type {
72   VERIFY,
73   CREATE,
74   BOTH
75 };
76
77 static void clearprogress();
78
79 // Report an error and exit
80 static void fatal(int errno_value, const char *fmt, ...) {
81   va_list ap;
82   clearprogress();
83   fprintf(stderr, "ERROR: ");
84   va_start(ap, fmt);
85   vfprintf(stderr, fmt, ap);
86   va_end(ap);
87   if(errno_value)
88     fprintf(stderr, ": %s", strerror(errno_value));
89   fputc('\n', stderr);
90   exit(1);
91 }
92
93 // Evict whatever FP points to from RAM
94 static void flushCache(FILE *fp) {
95   // drop_caches only evicts clean pages, so first the target file is
96   // synced.
97   if(fsync(fileno(fp)) < 0)
98     fatal(errno, "fsync");
99 #if defined DROP_CACHE_FILE
100   int fd;
101   if((fd = open(DROP_CACHE_FILE, O_WRONLY, 0)) < 0)
102     fatal(errno, "%s", DROP_CACHE_FILE);
103   if(write(fd, "3\n", 2) < 0)
104     fatal(errno, "%s", DROP_CACHE_FILE);
105   close(fd);
106 #elif defined PURGE_COMMAND
107   int rc;
108   if((rc = system(PURGE_COMMAND)) < 0)
109     fatal(errno, "executing %s", PURGE_COMMAND);
110   else if(rc) {
111     if(WIFSIGNALED(rc)) {
112       fprintf(stderr, "%s%s\n", 
113               strsignal(WTERMSIG(rc)),
114               WCOREDUMP(rc) ? " (core dumped)" : "");
115       exit(WTERMSIG(rc) + 128);
116     } else
117       exit(WEXITSTATUS(rc));
118   }
119 #endif
120 }
121
122 static long long execute(mode_type mode, bool entire, const char *show);
123
124 static const char default_seed[] = "hexapodia as the key insight";
125 static void *seed;
126 static size_t seedlen;
127 static const char *seedpath;
128 static const char *path;
129 static bool entireopt = false;
130 static bool flush = false;
131 static bool progress = false;
132 static long long size;
133
134 int main(int argc, char **argv) {
135   mode_type mode = BOTH;
136   int n;
137   char *ep;
138   while((n = getopt_long(argc, argv, "+s:S:L:vcepfhV", opts, 0)) >= 0) {
139     switch(n) {
140     case 's': seed = optarg; seedlen = strlen(optarg); break;
141     case 'S': seedpath = optarg; break;
142     case 'L':
143       seedlen = strtoul(optarg,&ep,0);
144       if(ep==optarg || *ep) fatal(0, "bad number for -S");
145       break;
146     case 'b': mode = BOTH; break;
147     case 'v': mode = VERIFY; break;
148     case 'c': mode = CREATE; break;
149     case 'e': entireopt = true; break;
150     case 'p': progress = true; break;
151     case 'f': flush = true; break;
152     case 'h': help(); exit(0);
153     case 'V': puts(VERSION); exit(0);
154     default:
155       fatal(0, "unknown option");
156     }
157   }
158   argc -= optind;
159   argv += optind;
160   if(argc > 2)
161     fatal(0, "excess arguments");
162   if(argc == 1 && mode == BOTH)
163     entireopt = true;
164   if(entireopt) {
165     if(argc != 1)
166       fatal(0, "with --entire, size should not be specified");
167   } else {
168     if(argc < (mode == VERIFY ? 1 : 2))
169       fatal(0, "insufficient arguments");
170   }
171   if(seed && seedpath)
172     fatal(0, "both --seed and --seed-file specified");
173   if(mode == BOTH && !seed && !seedpath) {
174 #ifdef HAVE_RANDOM_DEVICE
175     seedpath = RANDOM_DEVICE;
176 #else
177     fatal(0, "no --seed or --seed-file specified in --both mode"
178           " and random device not supported on this system");
179 #endif
180   }
181   if(seedpath) {
182     if(!seedlen)
183       seedlen = DEFAULT_SEED_LENGTH;
184     FILE *seedfile = fopen(seedpath, "rb");
185     if(!seedfile)
186       fatal(errno, "%s", seedpath);
187     seed = malloc(seedlen);
188     if(!seed)
189       fatal(errno, "allocate seed");
190     seedlen = fread(seed, 1, seedlen, seedfile);
191     if(ferror(seedfile))
192       fatal(errno, "read %s", seedpath);
193     fclose(seedfile);
194   }
195   if (!seed) {
196     seed = (void*)default_seed;
197     seedlen = sizeof(default_seed)-1;
198   }
199   path = argv[0];
200   if(argc > 1) {
201     errno = 0;
202     char *end;
203     size = strtoll(argv[1], &end, 10);
204     if(errno)
205       fatal(errno, "invalid size");
206     if(end == argv[1])
207       fatal(0, "invalid size");
208     if(!strcmp(end, "K"))
209       size *= 1024;
210     else if(!strcmp(end, "M"))
211       size *= 1024 * 1024;
212     else if(!strcmp(end, "G"))
213       size *= 1024 * 1024 * 1024;
214     else if(*end)
215       fatal(0, "invalid size");
216   } else if(entireopt) {
217     size = LONG_LONG_MAX;
218   } else {
219     struct stat sb;
220     if(stat(path, &sb) < 0)
221       fatal(errno, "stat %s", path);
222     size = sb.st_size;
223   }
224   const char *show = entireopt ? (mode == CREATE ? "written" : "verified") : 0;
225   if(mode == BOTH) {
226     size = execute(CREATE, entireopt, 0);
227     execute(VERIFY, false, show);
228   } else {
229     execute(mode, entireopt, show);
230   }
231   return 0;
232 }
233
234 static void flushstdout() {
235   if(ferror(stdout) || fflush(stdout))
236     fatal(errno, "flush stdout");
237 }
238
239 static void clearprogress() {
240   if (!progress) return;
241   printf(" %-10s %*s   \r", "", sizeof(long long)*4, "");
242   flushstdout();
243 }
244
245 static void showprogress(long long amount, const char *show) {
246   if (!progress) return;
247
248   static int counter;
249   if (counter++ < 1000) return;
250   counter = 0;
251
252   int triples = sizeof(amount);
253   char rawbuf[triples*3 + 1];
254   char outbuf[triples*4 + 1];
255   snprintf(rawbuf, sizeof(rawbuf), "% *lld", sizeof(rawbuf)-1, amount);
256   for (int i=0; i<triples; i++) {
257     outbuf[i*4] = ' ';
258     memcpy(outbuf + i*4 + 1, rawbuf + i*3, 3);
259   }
260   outbuf[triples*4] = 0;
261   printf(" %-10s %s...\r", outbuf, show);
262   flushstdout();
263 }
264
265 static long long execute(mode_type mode, bool entire, const char *show) {
266   Arcfour rng((const char*)seed, seedlen);
267   FILE *fp = fopen(path, mode == VERIFY ? "rb" : "wb");
268   if(!fp)
269     fatal(errno, "%s", path);
270   if(mode == VERIFY && flush)
271     flushCache(fp);
272   if(mode == CREATE && entire)
273     setvbuf(fp, 0, _IONBF, 0);
274   char generated[4096], input[4096];
275   long long remain = size;
276   static const size_t rc4drop = 3072; // en.wikipedia.org/wiki/RC4#Security
277   assert(rc4drop <= sizeof(generated));
278   rng.stream(generated, rc4drop);
279   while(remain > 0) {
280     size_t bytesGenerated = (remain > (ssize_t)sizeof generated
281                              ? sizeof generated
282                              : remain);
283     rng.stream(generated, bytesGenerated);
284     if(mode == CREATE) {
285       size_t bytesWritten = fwrite(generated, 1, bytesGenerated, fp);
286       if(ferror(fp)) {
287         if(!entire || errno != ENOSPC)
288           fatal(errno, "%s", path);
289         remain -= bytesWritten;
290         break;
291       }
292       assert(bytesWritten == bytesGenerated);
293     } else {
294       size_t bytesRead = fread(input, 1, bytesGenerated, fp);
295       if(ferror(fp))
296         fatal(errno, "%s", path);
297       if(memcmp(generated, input, bytesRead)) {
298         for(size_t n = 0; n < bytesRead; ++n)
299           if(generated[n] != input[n])
300             fatal(0, "%s corrupted at %lld/%lld bytes (expected %d got %d)",
301                     path, size - remain + n, size,
302                     (unsigned char)generated[n], (unsigned char)input[n]);
303       }
304       if(bytesRead < bytesGenerated) {
305         if(entire) {
306           assert(feof(fp));
307           remain -= bytesRead;
308           break;
309         }
310         fatal(0, "%s: truncated at %lld/%lld bytes",
311                 path, (size - remain + bytesRead), size);
312       }
313     }
314     remain -= bytesGenerated;
315     showprogress(size - remain, mode == VERIFY ? "verifying" : "writing");
316   }
317   clearprogress();
318   if(mode == VERIFY && !entire && getc(fp) != EOF)
319     fatal(0, "%s: extended beyond %lld bytes",
320             path, size);
321   if(mode == CREATE && flush) {
322     if(fflush(fp) < 0)
323       fatal(errno, "%s", path);
324     flushCache(fp);
325   }
326   if(fclose(fp) < 0)
327     fatal(errno, "%s", path);
328   long long done = size - remain;
329   if(show) {
330     printf("%lld bytes (%lldM, %lldG) %s\n",
331            done, done >> 20, done >> 30,
332            show);
333     flushstdout();
334   }
335   return done;
336 }