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