chiark / gitweb /
Move default seed setting to main().
[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 // Command line options
33 const struct option opts[] = {
34   { "seed", required_argument, 0, 's' },
35   { "both", no_argument, 0, 'b' },
36   { "verify", no_argument, 0, 'v' },
37   { "create", no_argument, 0, 'c' },
38   { "flush", no_argument, 0, 'f' },
39   { "entire", no_argument, 0, 'e' },
40   { "help", no_argument, 0, 'h' },
41   { "version", no_argument, 0, 'V' },
42   { 0, 0, 0, 0 },
43 };
44
45 // Display help message
46 static void help(void) {
47   printf("vbig - create or verify a large but pseudo-random file\n"
48          "\n"
49          "Usage:\n"
50          "  vbig [--seed SEED] --verify|--create PATH [SIZE]\n"
51          "\n"
52          "Options:\n"
53          "  --seed, -s     Specify random seed\n"
54          "  --verify, -v   Verify that PATH contains the expected contents\n"
55          "  --create, -c   Create PATH with psuedo-random contents\n"
56          "  --flush, -f    Flush cache\n"
57          "  --entire, -e   Write until full; read until EOF\n"
58          "  --help, -h     Display usage message\n"
59          "  --version, -V  Display version string\n");
60 }
61
62 // Possible modes of operation
63 enum mode_type {
64   VERIFY,
65   CREATE,
66   BOTH
67 };
68
69 // Report an error and exit
70 static void fatal(int errno_value, const char *fmt, ...) {
71   va_list ap;
72   fprintf(stderr, "ERROR: ");
73   va_start(ap, fmt);
74   vfprintf(stderr, fmt, ap);
75   va_end(ap);
76   if(errno_value)
77     fprintf(stderr, ": %s", strerror(errno_value));
78   fputc('\n', stderr);
79   exit(1);
80 }
81
82 // Evict whatever FP points to from RAM
83 static void flushCache(FILE *fp) {
84   // drop_caches only evicts clean pages, so first the target file is
85   // synced.
86   if(fsync(fileno(fp)) < 0)
87     fatal(errno, "fsync");
88 #if defined DROP_CACHE_FILE
89   int fd;
90   if((fd = open(DROP_CACHE_FILE, O_WRONLY, 0)) < 0)
91     fatal(errno, "%s", DROP_CACHE_FILE);
92   if(write(fd, "3\n", 2) < 0)
93     fatal(errno, "%s", DROP_CACHE_FILE);
94   close(fd);
95 #elif defined PURGE_COMMAND
96   int rc;
97   if((rc = system(PURGE_COMMAND)) < 0)
98     fatal(errno, "executing %s", PURGE_COMMAND);
99   else if(rc) {
100     if(WIFSIGNALED(rc)) {
101       fprintf(stderr, "%s%s\n", 
102               strsignal(WTERMSIG(rc)),
103               WCOREDUMP(rc) ? " (core dumped)" : "");
104       exit(WTERMSIG(rc) + 128);
105     } else
106       exit(WEXITSTATUS(rc));
107   }
108 #endif
109 }
110
111 static long long execute(mode_type mode, bool entire, const char *show);
112
113 static const char default_seed[] = "hexapodia as the key insight";
114 static const void *seed;
115 static size_t seedlen;
116 static const char *path;
117 static bool entireopt = false;
118 static bool flush = false;
119 static long long size;
120
121 int main(int argc, char **argv) {
122   mode_type mode = BOTH;
123   int n;
124   while((n = getopt_long(argc, argv, "+s:vcefhV", opts, 0)) >= 0) {
125     switch(n) {
126     case 's': seed = optarg; seedlen = strlen(optarg); break;
127     case 'b': mode = BOTH; break;
128     case 'v': mode = VERIFY; break;
129     case 'c': mode = CREATE; break;
130     case 'e': entireopt = true; break;
131     case 'f': flush = true; break;
132     case 'h': help(); exit(0);
133     case 'V': puts(VERSION); exit(0);
134     default:
135       fatal(0, "unknown option");
136     }
137   }
138   argc -= optind;
139   argv += optind;
140   if(argc > 2)
141     fatal(0, "excess arguments");
142   if(argc == 1 && mode == BOTH)
143     entireopt = true;
144   if(entireopt) {
145     if(argc != 1)
146       fatal(0, "with --entire, size should not be specified");
147   } else {
148     if(argc < (mode == VERIFY ? 1 : 2))
149       fatal(0, "insufficient arguments");
150   }
151   if (!seed) {
152     seed = default_seed;
153     seedlen = sizeof(default_seed)-1;
154   }
155   path = argv[0];
156   if(argc > 1) {
157     errno = 0;
158     char *end;
159     size = strtoll(argv[1], &end, 10);
160     if(errno)
161       fatal(errno, "invalid size");
162     if(end == argv[1])
163       fatal(0, "invalid size");
164     if(!strcmp(end, "K"))
165       size *= 1024;
166     else if(!strcmp(end, "M"))
167       size *= 1024 * 1024;
168     else if(!strcmp(end, "G"))
169       size *= 1024 * 1024 * 1024;
170     else if(*end)
171       fatal(0, "invalid size");
172   } else if(entireopt) {
173     size = LONG_LONG_MAX;
174   } else {
175     struct stat sb;
176     if(stat(path, &sb) < 0)
177       fatal(errno, "stat %s", path);
178     size = sb.st_size;
179   }
180   const char *show = entireopt ? (mode == CREATE ? "written" : "verified") : 0;
181   if(mode == BOTH) {
182     size = execute(CREATE, entireopt, 0);
183     execute(VERIFY, false, show);
184   } else {
185     execute(mode, entireopt, show);
186   }
187   return 0;
188 }
189
190 static long long execute(mode_type mode, bool entire, const char *show) {
191   Arcfour rng((const char*)seed, seedlen);
192   FILE *fp = fopen(path, mode == VERIFY ? "rb" : "wb");
193   if(!fp)
194     fatal(errno, "%s", path);
195   if(mode == VERIFY && flush)
196     flushCache(fp);
197   if(mode == CREATE && entire)
198     setvbuf(fp, 0, _IONBF, 0);
199   char generated[4096], input[4096];
200   long long remain = size;
201   static const size_t rc4drop = 3072; // en.wikipedia.org/wiki/RC4#Security
202   assert(rc4drop <= sizeof(generated));
203   rng.stream(generated, rc4drop);
204   while(remain > 0) {
205     size_t bytesGenerated = (remain > (ssize_t)sizeof generated
206                              ? sizeof generated
207                              : remain);
208     rng.stream(generated, bytesGenerated);
209     if(mode == CREATE) {
210       size_t bytesWritten = fwrite(generated, 1, bytesGenerated, fp);
211       if(ferror(fp)) {
212         if(!entire || errno != ENOSPC)
213           fatal(errno, "%s", path);
214         remain -= bytesWritten;
215         break;
216       }
217       assert(bytesWritten == bytesGenerated);
218     } else {
219       size_t bytesRead = fread(input, 1, bytesGenerated, fp);
220       if(ferror(fp))
221         fatal(errno, "%s", path);
222       if(memcmp(generated, input, bytesRead)) {
223         for(size_t n = 0; n < bytesRead; ++n)
224           if(generated[n] != input[n])
225             fatal(0, "%s corrupted at %lld/%lld bytes (expected %d got %d)",
226                     path, size - remain + n, size,
227                     (unsigned char)generated[n], (unsigned char)input[n]);
228       }
229       if(bytesRead < bytesGenerated) {
230         if(entire) {
231           assert(feof(fp));
232           remain -= bytesRead;
233           break;
234         }
235         fatal(0, "%s: truncated at %lld/%lld bytes",
236                 path, (size - remain + bytesRead), size);
237       }
238     }
239     remain -= bytesGenerated;
240   }
241   if(mode == VERIFY && !entire && getc(fp) != EOF)
242     fatal(0, "%s: extended beyond %lld bytes",
243             path, size);
244   if(mode == CREATE && flush) {
245     if(fflush(fp) < 0)
246       fatal(errno, "%s", path);
247     flushCache(fp);
248   }
249   if(fclose(fp) < 0)
250     fatal(errno, "%s", path);
251   long long done = size - remain;
252   if(show) {
253     printf("%lld bytes (%lldM, %lldG) %s\n",
254            done, done >> 20, done >> 30,
255            show);
256     if(ferror(stdout) || fflush(stdout))
257       fatal(errno, "flush stdout");
258   }
259   return done;
260 }