2.5.11.
[asdcplib-cth.git] / src / asdcp-util.cpp
1 /*
2 Copyright (c) 2003-2012, 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    asdcp-util.cpp
28     \version $Id: asdcp-util.cpp,v 1.3 2015/05/21 00:10:39 jhurst Exp $       
29     \brief   Utility functions for working with AS-DCP files
30
31   This program provides utility features commonly useful in DCP workflows.
32
33   For more information about asdcplib, please refer to the header file AS_DCP.h
34 */
35
36 #include <KM_fileio.h>
37 #include <KM_prng.h>
38 #include <AS_DCP.h>
39 #include <openssl/sha.h>
40
41 using namespace Kumu;
42
43
44 //------------------------------------------------------------------------------------------
45 //
46 // command line option parser class
47
48 static const char* PROGRAM_NAME = "asdcp-util";  // program name for messages
49
50 // Increment the iterator, test for an additional non-option command line argument.
51 // Causes the caller to return if there are no remaining arguments or if the next
52 // argument begins with '-'.
53 #define TEST_EXTRA_ARG(i,c)                                             \
54   if ( ++i >= argc || argv[(i)][0] == '-' ) {                           \
55     fprintf(stderr, "Argument not found for option -%c.\n", (c));       \
56     return;                                                             \
57   }
58
59 //
60 void
61 banner(FILE* stream = stdout)
62 {
63   fprintf(stream, "\n\
64 %s (asdcplib %s)\n\n\
65 Copyright (c) 2003-2012 John Hurst\n\n\
66 asdcplib may be copied only under the terms of the license found at\n\
67 the top of every file in the asdcplib distribution kit.\n\n\
68 Specify the -h (help) option for further information about %s\n\n",
69           PROGRAM_NAME, ASDCP::Version(), PROGRAM_NAME);
70 }
71
72 //
73 void
74 usage(FILE* stream = stdout)
75 {
76   fprintf(stream, "\
77 USAGE: %s [-h|-help] [-V]\n\
78 \n\
79        %s -d <input-file>\n\
80 \n\
81        %s -g | -u\n",
82           PROGRAM_NAME, PROGRAM_NAME, PROGRAM_NAME);
83
84   fprintf(stream, "\
85 Major modes:\n\
86   -d                - Calculate message digest of input file\n\
87   -g                - Generate a random 16 byte value to stdout\n\
88   -h | -help        - Show help\n\
89   -u                - Generate a random UUID value to stdout\n\
90   -V                - Show version information\n\
91 \n\
92   NOTES: o There is no option grouping, all options must be distinct arguments.\n\
93          o All option arguments must be separated from the option by whitespace.\n\n");
94 }
95
96 //
97 enum MajorMode_t
98 {
99   MMT_NONE,
100   MMT_GEN_ID,
101   MMT_GEN_KEY,
102   MMT_DIGEST,
103 };
104
105 //
106 class CommandOptions
107 {
108   CommandOptions();
109
110 public:
111   MajorMode_t mode;
112   bool   error_flag;     // true if the given options are in error or not complete
113   bool   version_flag;   // true if the version display option was selected
114   bool   help_flag;      // true if the help display option was selected
115   PathList_t filenames;  // list of filenames to be processed
116
117   //
118   CommandOptions(int argc, const char** argv) :
119     mode(MMT_NONE), error_flag(true), version_flag(false), help_flag(false)
120   {
121     for ( int i = 1; i < argc; ++i )
122       {
123
124         if ( (strcmp( argv[i], "-help") == 0) )
125           {
126             help_flag = true;
127             continue;
128           }
129          
130         if ( argv[i][0] == '-'
131              && ( isalpha(argv[i][1]) || isdigit(argv[i][1]) )
132              && argv[i][2] == 0 )
133           {
134             switch ( argv[i][1] )
135               {
136               case 'd': mode = MMT_DIGEST; break;
137               case 'g': mode = MMT_GEN_KEY; break;
138               case 'h': help_flag = true; break;
139               case 'u': mode = MMT_GEN_ID; break;
140               case 'V': version_flag = true; break;
141
142               default:
143                 fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
144                 return;
145               }
146           }
147         else
148           {
149             if ( argv[i][0] != '-' )
150               {
151                 filenames.push_back(argv[i]);
152               }
153             else
154               {
155                 fprintf(stderr, "Unrecognized argument: %s\n", argv[i]);
156                 return;
157               }
158           }
159       }
160
161     if ( help_flag || version_flag )
162       return;
163     
164     if ( ( mode == MMT_DIGEST ) && filenames.empty() )
165       {
166         fputs("Option requires at least one filename argument.\n", stderr);
167         return;
168       }
169
170     if ( mode == MMT_NONE && ! help_flag && ! version_flag )
171       {
172         fputs("No operation selected (use one of -[dgu] or -h for help).\n", stderr);
173         return;
174       }
175
176     error_flag = false;
177   }
178 };
179
180 //
181 Result_t
182 digest_file(const std::string& filename)
183 {
184   FileReader Reader;
185   SHA_CTX Ctx;
186   SHA1_Init(&Ctx);
187   ByteString Buf(8192);
188
189   Result_t result = Reader.OpenRead(filename.c_str());
190
191   while ( ASDCP_SUCCESS(result) )
192     {
193       ui32_t read_count = 0;
194       result = Reader.Read(Buf.Data(), Buf.Capacity(), &read_count);
195
196       if ( result == RESULT_ENDOFFILE )
197         {
198           result = RESULT_OK;
199           break;
200         }
201
202       if ( ASDCP_SUCCESS(result) )
203         SHA1_Update(&Ctx, Buf.Data(), read_count);
204     }
205
206   if ( ASDCP_SUCCESS(result) )
207     {
208       const ui32_t sha_len = 20;
209       byte_t bin_buf[sha_len];
210       char sha_buf[64];
211       SHA1_Final(bin_buf, &Ctx);
212
213       fprintf(stdout, "%s %s\n",
214               base64encode(bin_buf, sha_len, sha_buf, 64),
215               filename.c_str());
216     }
217
218   return result;
219 }
220
221 //
222 int
223 main(int argc, const char** argv)
224 {
225   Result_t result = RESULT_OK;
226   char     str_buf[64];
227   CommandOptions Options(argc, argv);
228
229   if ( Options.version_flag )
230     banner();
231
232   if ( Options.help_flag )
233     usage();
234
235   if ( Options.version_flag || Options.help_flag )
236     return 0;
237
238   if ( Options.error_flag )
239     {
240       fprintf(stderr, "There was a problem. Type %s -h for help.\n",
241               PROGRAM_NAME);
242       return 3;
243     }
244
245   if ( Options.mode == MMT_GEN_KEY )
246     {
247       Kumu::FortunaRNG RNG;
248       byte_t bin_buf[ASDCP::KeyLen];
249
250       RNG.FillRandom(bin_buf, ASDCP::KeyLen);
251       printf("%s\n", Kumu::bin2hex(bin_buf, ASDCP::KeyLen, str_buf, 64));
252     }
253   else if ( Options.mode == MMT_GEN_ID )
254     {
255       UUID TmpID;
256       Kumu::GenRandomValue(TmpID);
257       printf("%s\n", TmpID.EncodeHex(str_buf, 64));
258     }
259   else if ( Options.mode == MMT_DIGEST )
260     {
261       PathList_t::iterator i;
262
263       for ( i = Options.filenames.begin();
264             i != Options.filenames.end() && ASDCP_SUCCESS(result); ++i )
265         result = digest_file(*i);
266     }
267   else
268     {
269       fprintf(stderr, "Unhandled mode: %d.\n", Options.mode);
270       return 6;
271     }
272
273   if ( ASDCP_FAILURE(result) )
274     {
275       fputs("Program stopped on error.\n", stderr);
276
277       if ( result != RESULT_FAIL )
278         {
279           fputs(result, stderr);
280           fputc('\n', stderr);
281         }
282
283       return 1;
284     }
285
286   return 0;
287 }
288
289
290 //
291 // end asdcp-util.cpp
292 //