is_goodfile: no special verbose mode, always verbose now.
[skeinsum.git] / skein_cli.c
1 /* Copyright (C) 2014 2015 Jason Self <j@jxself.org>
2
3 This file is part of skeinsum.
4
5 skeinsum is free software: you can redistribute it and/or modify it 
6 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 skeinsum is distributed in the hope that it will be useful, but 
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with skeinsum. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "config.h"
20
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <dirent.h>
26 #include <getopt.h>
27 #include <malloc.h>
28 #include <math.h>
29 #include <glob.h>
30 #include <sys/stat.h>
31 #include <errno.h>
32 #include "SHA3api_ref.h"
33
34 #define TRYHELP_GOODBYE() do { printf("Try 'skein%dsum --help' for more information.\n", hashbitlen); exit(1); } while(0)
35
36 extern const int hashbitlen;
37
38 #define skeinVersion "1.3"
39 const size_t input_minbufsize = 32 * 1024;
40 const size_t input_maxbufsize = 32 * 1024 * 1024;
41
42
43 char invalidOption = 0;
44
45 enum
46 {
47   QUIET_OPTION = 11,
48   STATUS_OPTION,
49   TAG_OPTION,
50   HELP_OPTION,
51   VERSION_OPTION
52 };
53
54 static struct option const long_options[] =
55 {
56   { "binary",  no_argument, NULL, 'b' },
57   { "check",   no_argument, NULL, 'c' },
58   { "quiet",   no_argument, NULL, QUIET_OPTION },
59   { "status",  no_argument, NULL, STATUS_OPTION },
60   { "text",    no_argument, NULL, 't' },
61   { "warn",    no_argument, NULL, 'w' },
62   { "tag",     no_argument, NULL, TAG_OPTION },
63   { "help",    no_argument, NULL, HELP_OPTION },
64   { "version", no_argument, NULL, VERSION_OPTION },
65   { NULL, 0, NULL, 0 }
66 };
67
68 void printHexMsg(unsigned char *ptr, int size, char result[])
69 {
70         int i = 0;
71         int j = 0;
72         char High, Low;
73         for (i = 0 ; i < size ; i ++)
74         {
75                 High = ptr[i]>>4;
76                 Low = ptr[i]&0x0F;
77
78                 if (High >= 0xA && High <= 0xF)
79                         High += 0x37;
80                 else if(High >= 0x0 && High <= 0x9)
81                         High += 0x30;
82
83                 if (Low >= 0xA && Low <= 0xF)
84                         Low += 0x37;
85                 else if(Low >= 0x0 && Low <= 0x9)
86                         Low += 0x30;
87
88                 result[j++] = High;
89                 result[j++] = Low;
90         }
91         result[i] = 0;
92 }
93
94 int HashWithMode(const char file_name[], char MsgDigest[], char mode)
95 {
96         /* Try to get file info */
97         struct stat st;
98         if (stat(file_name, &st) < 0) {
99                 printf("skein%dsum: %s: STAT FAILED: %s\n", hashbitlen, file_name, strerror(errno));
100                 return -1;
101         }
102
103         /* Get filesize */
104         size_t fsize = st.st_size;
105         if (fsize != st.st_size) {
106                 printf("skein%dsum: %s: SIZE WARNING: filesize %llu is too big for reading into memory!\n",
107                         hashbitlen, file_name, (long long unsigned)st.st_size);
108         }
109
110         /* Open file */
111         FILE *fp_in = fopen(file_name, (mode == 't' ? "r" : "rb") );
112         if (!fp_in) {
113                 printf("skein%dsum: %s: OPEN FAILED: %s\n", hashbitlen, file_name, strerror(errno));
114                 return -1;
115         }
116
117         /* Allocate buffer */
118         size_t bufsize = fsize + 1;
119         if (bufsize < input_minbufsize)
120                 bufsize = input_minbufsize;
121
122         char *readbuf = malloc (bufsize);
123         if (!readbuf && bufsize > input_maxbufsize) {  /* ..Try to get contents by smaller portions */
124                 bufsize = input_maxbufsize;
125                 readbuf = malloc (bufsize);
126         }
127
128         if (!readbuf) {
129                 printf("skein%dsum: %s: MEM FAILED: %s\n", hashbitlen, file_name, strerror(errno));
130                 fclose(fp_in);
131                 return -1;
132         }
133
134         /* Read contents */
135         size_t readpos = 0, readed, total_readed = 0;
136
137         while (1) {
138                 size_t maxread = bufsize - readpos;
139                 readed = fread(readbuf, 1, maxread, fp_in);
140                 if (readed > 0 && readed <= maxread)
141                         total_readed += readed;
142                 if (readed != maxread)
143                         break;
144                 if (getenv("SKEIN_DEBUG"))
145                         printf("DEBUG: bufsize=%u (0x%x), readpos=%u (0x%x), maxread=%u (0x%x), total=%u (0x%x)\n",
146                                 bufsize, bufsize, readpos, readpos, maxread, maxread, total_readed, total_readed);
147                 char *newbuf = NULL;
148                 if (bufsize * 2 > bufsize)  /* ..check overflow */
149                         newbuf = realloc(readbuf, bufsize * 2);
150                 if (!newbuf) {
151                         printf("skein%dsum: %s: MEM WARNING: %u bytes only readed from %llu\n",
152                                 hashbitlen, file_name, total_readed, (long long unsigned)st.st_size);
153                         break;
154                 }
155                 readbuf = newbuf;
156                 readpos += readed;
157                 bufsize *= 2;
158         }
159
160         if (total_readed < st.st_size && total_readed < bufsize) {
161                 printf("skein%dsum: %s: READ WARNING: filesize=%llu, readed=%u, %s\n",
162                         hashbitlen, file_name, (long long unsigned)st.st_size, total_readed, strerror(errno));
163         }
164
165         fclose(fp_in);
166
167         unsigned char output[hashbitlen/4];
168         Hash(hashbitlen, (unsigned char*) readbuf, total_readed, output);
169
170         free(readbuf);
171
172         printHexMsg(output,hashbitlen/4,MsgDigest);
173
174         return 1;
175 }
176
177 int PrintHash(const char filename[], int tag, char mode)
178 {
179         char MsgDigest[hashbitlen/2];
180         if (HashWithMode(filename, MsgDigest, mode) < 0)
181                 return -1;
182         if (tag == 1) {
183                 printf("skein%d_v%s (%s) = %s\n", hashbitlen, skeinVersion, filename, MsgDigest);
184         } else {
185                 printf("%s %s%s\n", MsgDigest, (mode == 'b' ? "*" : ""), filename);
186         }
187         return 1;
188 }
189
190 void HashStringMode(const char Msg[], char MsgDigest[])
191 {
192         unsigned char output[hashbitlen/4];
193         Hash(hashbitlen, (unsigned char*) Msg, strlen(Msg), output);
194         printHexMsg(output,hashbitlen/4,MsgDigest);
195 }
196
197 void HashStdin(int tag)
198 {
199         char MsgDigest[hashbitlen/2];
200         char stri[100];             /* TODO!!! REWRITE THIS HARDCORE!!! */
201         char longstring[1000];
202         longstring[0] = 0;
203         while(fgets(stri,100,stdin))
204                 strcat(longstring, stri);
205         HashStringMode(longstring, MsgDigest);
206         if (tag == 1) {
207                 printf("skein%d_v%s (-) = %s\n", hashbitlen, skeinVersion, MsgDigest);
208         } else {
209                 printf("%s *-\n", MsgDigest);
210         }
211 }
212
213 int HashMatch(const char StoredDigest[], const char *filename, int quiet)
214 {
215         char mode = 't';
216         if (filename[0] == '*') {
217                 filename++;
218                 mode = 'b';
219         }
220         
221         char MsgDigest[hashbitlen/2];
222         if (HashWithMode(filename, MsgDigest, mode) < 0)
223                 return 0;
224
225         if (strcmp(MsgDigest, StoredDigest)) {
226                 printf("%s: FAILED\n", filename);
227                 return 0;
228         }
229         if (quiet > 0)
230                 printf("%s: OK\n", filename);
231         return 1;
232 }
233
234 int VerifyHashesFromFile(FILE *fp, int status, int warn, int quiet)
235 {
236         char hash[500], MsgDigest_tmp[hashbitlen/2];
237         int NoMatch = 0, NotProper = 0, Computed = 0;
238         int line = 0;
239
240         while (fgets(hash, sizeof(hash)-1, fp))
241         {
242                 char file_tmp[PATH_MAX];
243                 line ++;
244                 Computed++;
245                 unsigned int hashVersion = decomposeHashLine(hash,MsgDigest_tmp,file_tmp);
246                 if (hashVersion == -1)
247                 {
248                         fprintf(stderr, "skein%d: %s is using newer version of skein%d algorithm\n",hashbitlen,file_tmp,hashbitlen);
249                         fprintf(stderr, "You should update your algorithm\n");
250                         continue;
251                 }
252                 else if (hashVersion == 0)
253                 {
254                         fprintf(stderr, "skein%d: %s is using an older version of skein%d algorithm\n",hashbitlen,file_tmp,hashbitlen);
255                         fprintf(stderr, "You should use the older algorithm\n");
256                         continue;
257                 }
258                 else if (!isProper(MsgDigest_tmp))
259                 {
260                         if(status != 1 && warn == 1)
261                                 fprintf(stderr, "skein%dsum: %s: %d: improperly formatted skein%d checksum line\n",hashbitlen,file_tmp,line,hashbitlen);
262                         NotProper ++;
263                         NoMatch ++;
264                 }
265                 else if (!HashMatch(MsgDigest_tmp, file_tmp, quiet))
266                 {
267                         NoMatch++;
268                 }
269         }
270         if(NoMatch)
271         {
272                 fprintf(stderr, "skein%dsum: WARNING: %d of %d computed checksums did NOT match\n",
273                                 hashbitlen,NoMatch,Computed);
274         }
275         if(NotProper)
276         {
277                 fprintf(stderr, "skein%dsum: WARNING: %d line is improperly formatted\n",hashbitlen,NotProper);
278         }
279         return (NotProper || NoMatch) ? -1 : 1;
280 }
281
282 int isProper(char MsgDigest[])
283 {
284         if ((strlen(MsgDigest) - hashbitlen/4) != 0)
285                 return 0;
286         int index = 0;
287         char c = 0;
288         for(index = 0; index < strlen(MsgDigest);index++)
289         {
290                 c = MsgDigest[index];
291                 if(!(( c >= '0' && c <= '9' ) || ( c >= 'A' && c <= 'F')))
292                         return 0;
293         }
294
295         return 1;
296 }
297
298
299 int decomposeHashLine(char hash[], char MsgDigest_tmp[], char file_tmp[])
300 {
301         char c = 0;
302         int i = 0 , j =0;
303         int isTagFile = 0;
304         char alg[20];
305         char tmp[1000];
306         while(((c = hash[i])!=' ')&&((c = hash[i])!='_'))
307         {
308                 tmp[i] = hash[i];
309                 i++;
310         }
311         tmp[i] = 0;
312
313         sprintf(alg,"skein%d",hashbitlen);
314         if(!strcmp(alg,tmp))
315         {
316                 isTagFile = 1;
317         }
318
319         if(isTagFile == 0)
320         {
321                 strcpy(MsgDigest_tmp,tmp);
322                 i++;
323                 while((c = hash[i])!= '\n')
324                 {
325                         file_tmp[j] = hash[i];
326                         i++;
327                         j++;
328                 }
329                 file_tmp[j] = 0;
330         }
331         else if((hash[i]=='_')&&(hash[i+1]=='v'))
332         {
333                 i = i + 2;
334                 j = 0;
335                 char version[5];
336                 while((c = hash[i])!=' ')
337                 {
338                         version[j] = hash[i];
339                         i++;
340                         j++;
341                 }
342                 version[i] = 0;
343                 float vers = 0, skeinVers = 0;
344                 sscanf(version,"%f",&vers);
345                 sscanf(skeinVersion,"%f",&skeinVers);
346
347                 j = 0;
348                 i = i + 2;
349                 while((c = hash[i])!=')')
350                 {
351                         file_tmp[j] = hash[i];
352                         i++;
353                         j++;
354                 }
355                 file_tmp[j] = 0;
356
357                 i = i + 4;
358                 j = 0;
359                 while((c = hash[i])!='\n')
360                 {
361                         MsgDigest_tmp[j] = hash[i];
362                         i++;
363                         j++;
364                 }
365                 MsgDigest_tmp[j] = 0;
366
367                 if(skeinVers < vers)
368                 {//version newer than mine
369                         return (-1);
370                 }
371                 else if (skeinVers > vers)
372                 {//going to use older version than mine
373                         return (0) ;
374                 }
375                 else
376                 { //versions match
377                         return (1);
378                 }
379         }
380         return 1;
381
382 }
383
384 void print_version(void)
385 {
386         printf("skein%dsum 1.0\n", hashbitlen);
387         printf("License GPLv3+: GNU GPL version 3 or later\n");
388         printf("<http://gnu.org/licenses/gpl.html>\n");
389         printf("This is free software: you are free to change and redistribute it.\n");
390         printf("There is NO WARRANTY, to the extent permitted by law.\n");
391         exit(1);
392 }
393
394 void print_usage(void)
395 {
396         printf("Usage: skein%dsum [OPTION]... [FILE]...\n",hashbitlen);
397         printf("Print or check skein (%d-bit) checksums.\n",hashbitlen);
398         printf("With no FILE, or when FILE is -, read standard input.\n");
399         printf("\n");
400         printf("-b, --binary         read in binary mode\n");
401         printf("-c, --check          read skein sums from the FILEs and check them\n");
402         printf("--tag            create a BSD-style checksum\n");
403         printf("-t, --text           read in text mode (default)\n");
404         printf("\n");
405         printf("The following three options are useful only when verifying checksums:\n");
406         printf("--quiet          don't print OK for each successfully verified file\n");
407         printf("--status         don't output anything, status code shows success\n");
408         printf("-w, --warn           warn about improperly formatted checksum lines\n");
409         printf("\n");
410         printf("--strict         with --check, exit non-zero for any invalid input\n");
411         printf("--help     display this help and exit\n");
412         printf("--version  output version information and exit\n");
413         printf("\n");
414         printf("The sums are computed as described in version 1.3 of the Skein\n");
415         printf("specification. When checking, the input should be a former output of\n");
416         printf("this program. The default mode is to print a line with checksum, a\n");
417         printf("character indicating input mode ('*' for binary, space for text), and\n");
418         printf("name for each FILE.\n");
419         exit(1);
420 }
421
422 int is_goodfile(const char filename[])
423 {
424         if (!strcmp(filename, "-"))
425                 return 1;
426
427         struct stat s;
428
429         if (stat(filename, &s) < 0) {
430                 fprintf(stderr, "skein%dsum: %s: no such file or directory\n", hashbitlen, filename);
431                 return 0;
432         }
433
434         if (s.st_mode & (S_IFREG|S_IFBLK))  /* ..regular file or block device? */
435                 return 1;
436
437         if (s.st_mode & S_IFDIR) {
438                 fprintf(stderr, "skein%dsum: %s: is a directory\n", hashbitlen, filename);
439                 return 0;
440         }
441
442         fprintf(stderr, "skein%dsum: %s: wrong filetype 0x%Xu\n", hashbitlen, filename, s.st_mode);
443         return 0;
444 }
445
446
447 int main(int argc, char** argv)
448 {
449         int number_files = 0;
450         int first_file = argc;
451         int binary = -1,
452                  check = -1,
453                  quiet = -1,
454                  warn = -1,
455                  status = -1,
456                  tag = -1,
457                  hashString = -1;
458
459         int errorFound = 0;
460         int opt = 0;
461 /*****************************************************************************************
462  ************************************* GETTING DATA ***********************************
463  *****************************************************************************************/
464         while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
465         {
466                 switch (opt) {
467                         case 0              : hashString = 1;  break;
468                         case 'b'            : binary     = 1;  break;
469                         case 't'            : binary     = 0;  break;
470                         case 'c'            : check      = 1;  break;
471                         case 'w'            : warn       = 1;  break;
472                         case QUIET_OPTION   : quiet      = 1;  break;
473                         case STATUS_OPTION  : status     = 1;  break;
474                         case TAG_OPTION     : tag        = 1;  break;
475                         
476                         case HELP_OPTION    : print_usage();   /* ..never returns */
477                         case VERSION_OPTION : print_version(); /* ..never returns */
478
479                         default: TRYHELP_GOODBYE();
480                 }
481         }
482
483         first_file = optind;
484
485 /*****************************************************************************************
486  ************************************* PROCESSING DATA ***********************************
487  *****************************************************************************************/
488
489         if (check < 0)   /* READ FILES, GENERATE CHECKSUMS AND PRINT TO STDOUT.. */
490         {
491                 if (quiet == 1 || warn == 1 || status == 1)
492                 {
493                         if(quiet == 1)
494                                 fprintf(stderr, "skein%dsum: the --quiet option is meaningful only when verifying checksums\n", hashbitlen);
495                         if(status ==1)
496                                 fprintf(stderr, "skein%dsum: the --status option is meaningful only when verifying checksums\n", hashbitlen);
497                         if(warn == 1)
498                                 fprintf(stderr, "skein%dsum: the --warn option is meaningful only when verifying checksums\n", hashbitlen);
499                         TRYHELP_GOODBYE();
500                 }
501
502                 int file_index;
503                 for (file_index = first_file; file_index < argc; file_index++)
504                 {
505                         const char *filename = argv[file_index];
506                         if (!is_goodfile(filename)) {
507                                 errorFound++;
508                                 continue;
509                         }
510                         number_files++;
511
512                         if (binary > 0 && hashString == 1) {
513                                 printf("skein%dsum: %s: No such file or directory\n", hashbitlen, filename);
514                                 continue;
515                         }
516
517                         char mode = binary > 0 ? 'b' : 't';
518                         if (PrintHash(filename, tag, mode) < 0)
519                                 errorFound++;
520                 }
521
522                 if (!number_files && !errorFound)
523                         HashStdin(tag);
524
525                 return (errorFound ? 1 : 0);
526         }
527
528         if (check == 1)   /* READ LISTFILES, GENERATE HASHES, COMPARE WITH STORED, PRINT RESULT */
529         {
530                 if (tag == 1 || binary >= 0)
531                 {
532                         if (tag == 1)
533                                 fprintf(stderr, "skein%dsum: the --tag option is meaningless when verifying checksums\n", hashbitlen);
534                         if (binary >= 0)
535                                 fprintf(stderr, "skein%dsum: the --text and --binary options are meaningless when verifying checksums\n", hashbitlen);
536                         TRYHELP_GOODBYE();
537                 }
538
539                 int file_index;
540                 for (file_index = first_file; file_index < argc; file_index++)
541                 {
542                         const char *filename = argv[file_index];
543                         if (!is_goodfile(filename)) {
544                                 errorFound++;
545                                 continue;
546                         }
547                         number_files++;
548
549                         FILE *fp = fopen(filename, "r");
550                         if (!fp) {
551                                 printf("skein%dsum: %s: error %d, %s\n", hashbitlen, filename, errno, strerror(errno));
552                                 continue;
553                         }
554                         if (VerifyHashesFromFile(fp, status, warn, quiet) < 0)
555                                 errorFound++;
556                         fclose(fp);
557                 }
558
559                 if (!number_files && !errorFound)
560                         if (VerifyHashesFromFile(stdin, status, warn, quiet) < 0)
561                                 errorFound++;
562
563                 return (errorFound ? 1 : 0);
564         }
565
566         return 1;
567 }