560fa6ec434da7ab3abb9ebff0d0d59fd7bb3414
[libdcp.git] / asdcplib / src / kmrandgen.cpp
1 /*
2 Copyright (c) 2005-2009, John Hurst
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8 1. Redistributions of source code must retain the above copyright
9    notice, this list of conditions and the following disclaimer.
10 2. Redistributions in binary form must reproduce the above copyright
11    notice, this list of conditions and the following disclaimer in the
12    documentation and/or other materials provided with the distribution.
13 3. The name of the author may not be used to endorse or promote products
14    derived from this software without specific prior written permission.
15
16 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27   /*! \file    kmrandgen.cpp
28     \version $Id: kmrandgen.cpp,v 1.8 2009/03/04 17:52:45 jhurst Exp $
29     \brief   psuedo-random number generation utility
30   */
31
32 #include "AS_DCP.h"
33 #include <KM_fileio.h>
34 #include <KM_prng.h>
35 #include <ctype.h>
36
37 using namespace Kumu;
38
39 const ui32_t RandBlockSize = 16;
40 const char* PROGRAM_NAME = "kmrandgen";
41
42 // Increment the iterator, test for an additional non-option command line argument.
43 // Causes the caller to return if there are no remaining arguments or if the next
44 // argument begins with '-'.
45 #define TEST_EXTRA_ARG(i,c)    if ( ++i >= argc || argv[(i)][0] == '-' ) \
46                                  { \
47                                    fprintf(stderr, "Argument not found for option -%c.\n", (c)); \
48                                    return; \
49                                  }
50
51 //
52 void
53 banner(FILE* stream = stdout)
54 {
55   fprintf(stream, "\n\
56 %s (asdcplib %s)\n\n\
57 Copyright (c) 2003-2009 John Hurst\n\n\
58 %s is part of the asdcp DCP tools package.\n\
59 asdcplib may be copied only under the terms of the license found at\n\
60 the top of every file in the asdcplib distribution kit.\n\n\
61 Specify the -h (help) option for further information about %s\n\n",
62           PROGRAM_NAME, Kumu::Version(), PROGRAM_NAME, PROGRAM_NAME);
63 }
64
65 //
66 void
67 usage(FILE* stream = stdout)
68 {
69   fprintf(stream, "\
70 USAGE: %s [-b|-B|-c|-x] [-n] [-s <size>] [-v]\n\
71 \n\
72        %s [-h|-help] [-V]\n\
73 \n\
74   -b          - Output a stream of binary data\n\
75   -B          - Output a Base64 string\n\
76   -c          - Output a C-language struct containing the values\n\
77   -h | -help  - Show help\n\
78   -n          - Suppress newlines\n\
79   -s <size>   - Number of random bytes to generate (default 32)\n\
80   -v          - Verbose. Prints informative messages to stderr\n\
81   -V          - Show version information\n\
82   -x          - Output hexadecimal (default)\n\
83 \n\
84   NOTES: o There is no option grouping, all options must be distinct arguments.\n\
85          o All option arguments must be separated from the option by whitespace.\n\
86 \n", PROGRAM_NAME, PROGRAM_NAME);
87 }
88
89 enum OutputFormat_t {
90   OF_HEX,
91   OF_BINARY,
92   OF_BASE64,
93   OF_CSTRUCT
94 };
95
96 //
97 class CommandOptions
98 {
99   CommandOptions();
100
101 public:
102   bool   error_flag;      // true if the given options are in error or not complete
103   bool   no_newline_flag; // 
104   bool   verbose_flag;    // true if the verbose option was selected
105   bool   version_flag;    // true if the version display option was selected
106   bool   help_flag;       // true if the help display option was selected
107   OutputFormat_t format;  // 
108   ui32_t request_size;
109
110  //
111   CommandOptions(int argc, const char** argv) :
112     error_flag(true), no_newline_flag(false), verbose_flag(false),
113     version_flag(false), help_flag(false), format(OF_HEX), request_size(RandBlockSize*2)
114   {
115     for ( int i = 1; i < argc; i++ )
116       {
117
118          if ( (strcmp( argv[i], "-help") == 0) )
119            {
120              help_flag = true;
121              continue;
122            }
123      
124         if ( argv[i][0] == '-' && isalpha(argv[i][1]) && argv[i][2] == 0 )
125           {
126             switch ( argv[i][1] )
127               {
128               case 'b': format = OF_BINARY; break;
129               case 'B': format = OF_BASE64; break;
130               case 'c': format = OF_CSTRUCT; break;
131               case 'n': no_newline_flag = true; break;
132               case 'h': help_flag = true; break;
133
134               case 's':
135                 TEST_EXTRA_ARG(i, 's');
136                 request_size = abs(atoi(argv[i]));
137                 break;
138
139               case 'v': verbose_flag = true; break;
140               case 'V': version_flag = true; break;
141               case 'x': format = OF_HEX; break;
142
143               default:
144                 fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
145                 return;
146               }
147           }
148         else
149           {
150             fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
151             return;
152           }
153       }
154
155     if ( help_flag || version_flag )
156       return;
157
158     if ( request_size == 0 )
159       {
160         fprintf(stderr, "Please use a non-zero request size\n");
161         return;
162       }
163
164     error_flag = false;
165   }
166 };
167
168
169 //
170 int
171 main(int argc, const char** argv)
172 {
173   CommandOptions Options(argc, argv);
174
175    if ( Options.version_flag )
176     banner();
177
178   if ( Options.help_flag )
179     usage();
180
181   if ( Options.version_flag || Options.help_flag )
182     return 0;
183
184   if ( Options.error_flag )
185     {
186       fprintf(stderr, "There was a problem. Type %s -h for help.\n", PROGRAM_NAME);
187       return 3;
188     }
189
190   FortunaRNG    RandGen;
191   ByteString    Buf(Kumu::Kilobyte);
192
193   if ( Options.verbose_flag )
194     fprintf(stderr, "Generating %d random byte%s.\n", Options.request_size, (Options.request_size == 1 ? "" : "s"));
195
196   if ( Options.format == OF_BINARY )
197     {
198       if ( KM_FAILURE(Buf.Capacity(Options.request_size)) )
199         {
200           fprintf(stderr, "randbuf: %s\n", RESULT_ALLOC.Label());
201           return 1;
202         }
203
204       RandGen.FillRandom(Buf.Data(), Options.request_size);
205       fwrite((byte_t*)Buf.Data(), 1, Options.request_size, stdout);
206     }
207   else if ( Options.format == OF_CSTRUCT )
208     {
209       ui32_t line_count = 0;
210       byte_t* p = Buf.Data();
211       printf("byte_t rand_buf[%u] = {\n", Options.request_size);
212
213       if ( Options.request_size > 128 )
214         fputs("  // 0x00000000\n", stdout);
215
216       while ( Options.request_size > 0 )
217         {
218           if ( line_count > 0 && (line_count % (RandBlockSize*8)) == 0 )
219             fprintf(stdout, "  // 0x%08x\n", line_count);
220
221           RandGen.FillRandom(p, RandBlockSize);
222           fputc(' ', stdout);
223
224           for ( ui32_t i = 0; i < RandBlockSize && Options.request_size > 0; i++, Options.request_size-- )
225             printf(" 0x%02x,", p[i]);
226
227           fputc('\n', stdout);
228           line_count += RandBlockSize;
229         }
230
231       fputs("};", stdout);
232
233       if ( ! Options.no_newline_flag )
234         fputc('\n', stdout);
235     }
236   else if ( Options.format == OF_BASE64 )
237     {
238       if ( KM_FAILURE(Buf.Capacity(Options.request_size)) )
239         {
240           fprintf(stderr, "randbuf: %s\n", RESULT_ALLOC.Label());
241           return 1;
242         }
243
244       ByteString Strbuf;
245       ui32_t e_len = base64_encode_length(Options.request_size) + 1;
246
247       if ( KM_FAILURE(Strbuf.Capacity(e_len)) )
248         {
249           fprintf(stderr, "strbuf: %s\n", RESULT_ALLOC.Label());
250           return 1;
251         }
252
253       RandGen.FillRandom(Buf.Data(), Options.request_size);
254
255       if ( base64encode(Buf.RoData(), Options.request_size, (char*)Strbuf.Data(), Strbuf.Capacity()) == 0 )
256         {
257           fprintf(stderr, "encode error\n");
258           return 2;
259         } 
260
261       fputs((const char*)Strbuf.RoData(), stdout);
262
263       if ( ! Options.no_newline_flag )
264         fputs("\n", stdout);
265     }
266   else // OF_HEX
267     {
268       byte_t* p = Buf.Data();
269       char hex_buf[64];
270
271       while ( Options.request_size > 0 )
272         {
273           ui32_t x_len = xmin(Options.request_size, RandBlockSize);
274           RandGen.FillRandom(p, RandBlockSize);
275           bin2hex(p, x_len, hex_buf, 64);
276           fputs(hex_buf, stdout);
277
278           if ( ! Options.no_newline_flag )
279             fputc('\n', stdout);
280
281           Options.request_size -= x_len;
282         }
283
284     }
285
286   return 0;
287 }
288
289
290 //
291 // end kmrandgen.cpp
292 //