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