isProper - small changes.
[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 /* Return: -1 = Error, 0 = Mismatch, 1 = Match */
214 int HashMatch(const char StoredDigest[], const char *filename, int quiet)
215 {
216         char mode = 't';
217         if (filename[0] == '*') {
218                 filename++;
219                 mode = 'b';
220         }
221         
222         char MsgDigest[hashbitlen/2];
223         if (HashWithMode(filename, MsgDigest, mode) < 0)
224                 return -1;
225
226         if (strcmp(MsgDigest, StoredDigest)) {
227                 printf("%s: FAILED\n", filename);
228                 return 0;
229         }
230
231         if (quiet > 0)
232                 printf("%s: OK\n", filename);
233         return 1;
234 }
235
236 /* Return: -1 = some errors/mismatches, 1 = all ok */
237 int VerifyHashesFromFile(FILE *fp, int status, int warn, int quiet)
238 {
239         char hash[PATH_MAX + hashbitlen/4 + 4];
240         char MsgDigest_tmp[hashbitlen/2];
241         int NoMatch = 0, NotProper = 0, Computed = 0;
242         int line = 0;
243
244         while (fgets(hash, sizeof(hash)-1, fp))
245         {
246                 char file_tmp[PATH_MAX];
247                 line ++;
248                 Computed++;
249                 int hashVersion = decomposeHashLine(hash,MsgDigest_tmp,file_tmp);
250                 if (hashVersion == -1)
251                 {
252                         fprintf(stderr, "skein%d: %s is using newer version of skein%d algorithm\n",hashbitlen,file_tmp,hashbitlen);
253                         fprintf(stderr, "You should update your algorithm\n");
254                         continue;
255                 }
256                 else if (hashVersion == 0)
257                 {
258                         fprintf(stderr, "skein%d: %s is using an older version of skein%d algorithm\n",hashbitlen,file_tmp,hashbitlen);
259                         fprintf(stderr, "You should use the older algorithm\n");
260                         continue;
261                 }
262                 else if (!isProper(MsgDigest_tmp))
263                 {
264                         if(status != 1 && warn == 1)
265                                 fprintf(stderr, "skein%dsum: %s: %d: improperly formatted skein%d checksum line\n",hashbitlen,file_tmp,line,hashbitlen);
266                         NotProper ++;
267                         NoMatch ++;
268                 }
269                 else if (HashMatch(MsgDigest_tmp, file_tmp, quiet) <= 0)
270                 {
271                         NoMatch++;
272                 }
273         }
274         if(NoMatch)
275         {
276                 fprintf(stderr, "skein%dsum: WARNING: %d of %d computed checksums did NOT match\n",
277                                 hashbitlen,NoMatch,Computed);
278         }
279         if(NotProper)
280         {
281                 fprintf(stderr, "skein%dsum: WARNING: %d line is improperly formatted\n",hashbitlen,NotProper);
282         }
283         return (NotProper || NoMatch) ? -1 : 1;
284 }
285
286 int isProper(const char MsgDigest[])
287 {
288         int len = strlen(MsgDigest);
289         if (len != (hashbitlen / 4))
290                 return 0;
291         int index = 0;
292         for (index = 0; index < len; index++)
293         {
294                 char c = MsgDigest[index];
295                 if (c >= '0' && c <= '9') continue;
296                 if (c >= 'A' && c <= 'F') continue;
297                 return 0;
298         }
299
300         return 1;
301 }
302
303
304 int decomposeHashLine(char hash[], char MsgDigest_tmp[], char file_tmp[])
305 {
306         char c = 0;
307         int i = 0 , j =0;
308         int isTagFile = 0;
309         char alg[20];
310         char tmp[1000];
311         while(((c = hash[i])!=' ')&&((c = hash[i])!='_'))
312         {
313                 tmp[i] = hash[i];
314                 i++;
315         }
316         tmp[i] = 0;
317
318         sprintf(alg,"skein%d",hashbitlen);
319         if(!strcmp(alg,tmp))
320         {
321                 isTagFile = 1;
322         }
323
324         if(isTagFile == 0)
325         {
326                 strcpy(MsgDigest_tmp,tmp);
327                 i++;
328                 while((c = hash[i])!= '\n')
329                 {
330                         file_tmp[j] = hash[i];
331                         i++;
332                         j++;
333                 }
334                 file_tmp[j] = 0;
335         }
336         else if((hash[i]=='_')&&(hash[i+1]=='v'))
337         {
338                 i = i + 2;
339                 j = 0;
340                 char version[5];
341                 while((c = hash[i])!=' ')
342                 {
343                         version[j] = hash[i];
344                         i++;
345                         j++;
346                 }
347                 version[i] = 0;
348                 float vers = 0, skeinVers = 0;
349                 sscanf(version,"%f",&vers);
350                 sscanf(skeinVersion,"%f",&skeinVers);
351
352                 j = 0;
353                 i = i + 2;
354                 while((c = hash[i])!=')')
355                 {
356                         file_tmp[j] = hash[i];
357                         i++;
358                         j++;
359                 }
360                 file_tmp[j] = 0;
361
362                 i = i + 4;
363                 j = 0;
364                 while((c = hash[i])!='\n')
365                 {
366                         MsgDigest_tmp[j] = hash[i];
367                         i++;
368                         j++;
369                 }
370                 MsgDigest_tmp[j] = 0;
371
372                 if(skeinVers < vers)
373                 {//version newer than mine
374                         return (-1);
375                 }
376                 else if (skeinVers > vers)
377                 {//going to use older version than mine
378                         return (0) ;
379                 }
380                 else
381                 { //versions match
382                         return (1);
383                 }
384         }
385         return 1;
386
387 }
388
389 void print_version(void)
390 {
391         printf("skein%dsum 1.0\n", hashbitlen);
392         printf("License GPLv3+: GNU GPL version 3 or later\n");
393         printf("<http://gnu.org/licenses/gpl.html>\n");
394         printf("This is free software: you are free to change and redistribute it.\n");
395         printf("There is NO WARRANTY, to the extent permitted by law.\n");
396         exit(1);
397 }
398
399 void print_usage(void)
400 {
401         printf("Usage: skein%dsum [OPTION]... [FILE]...\n",hashbitlen);
402         printf("Print or check skein (%d-bit) checksums.\n",hashbitlen);
403         printf("With no FILE, or when FILE is -, read standard input.\n");
404         printf("\n");
405         printf("-b, --binary         read in binary mode\n");
406         printf("-c, --check          read skein sums from the FILEs and check them\n");
407         printf("--tag            create a BSD-style checksum\n");
408         printf("-t, --text           read in text mode (default)\n");
409         printf("\n");
410         printf("The following three options are useful only when verifying checksums:\n");
411         printf("--quiet          don't print OK for each successfully verified file\n");
412         printf("--status         don't output anything, status code shows success\n");
413         printf("-w, --warn           warn about improperly formatted checksum lines\n");
414         printf("\n");
415         printf("--strict         with --check, exit non-zero for any invalid input\n");
416         printf("--help     display this help and exit\n");
417         printf("--version  output version information and exit\n");
418         printf("\n");
419         printf("The sums are computed as described in version 1.3 of the Skein\n");
420         printf("specification. When checking, the input should be a former output of\n");
421         printf("this program. The default mode is to print a line with checksum, a\n");
422         printf("character indicating input mode ('*' for binary, space for text), and\n");
423         printf("name for each FILE.\n");
424         exit(1);
425 }
426
427 int is_goodfile(const char filename[])
428 {
429         if (!strcmp(filename, "-"))
430                 return 1;
431
432         struct stat s;
433
434         if (stat(filename, &s) < 0) {
435                 fprintf(stderr, "skein%dsum: %s: no such file or directory\n", hashbitlen, filename);
436                 return 0;
437         }
438
439         if (s.st_mode & (S_IFREG|S_IFBLK))  /* ..regular file or block device? */
440                 return 1;
441
442         if (s.st_mode & S_IFDIR) {
443                 fprintf(stderr, "skein%dsum: %s: is a directory\n", hashbitlen, filename);
444                 return 0;
445         }
446
447         fprintf(stderr, "skein%dsum: %s: wrong filetype 0x%Xu\n", hashbitlen, filename, s.st_mode);
448         return 0;
449 }
450
451
452 int main(int argc, char** argv)
453 {
454         int number_files = 0;
455         int first_file = argc;
456         int binary = -1,
457                  check = -1,
458                  quiet = -1,
459                  warn = -1,
460                  status = -1,
461                  tag = -1,
462                  hashString = -1;
463
464         int errorFound = 0;
465         int opt = 0;
466 /*****************************************************************************************
467  ************************************* GETTING DATA ***********************************
468  *****************************************************************************************/
469         while ((opt = getopt_long (argc, argv, "bctw", long_options, NULL)) != -1)
470         {
471                 switch (opt) {
472                         case 0              : hashString = 1;  break;
473                         case 'b'            : binary     = 1;  break;
474                         case 't'            : binary     = 0;  break;
475                         case 'c'            : check      = 1;  break;
476                         case 'w'            : warn       = 1;  break;
477                         case QUIET_OPTION   : quiet      = 1;  break;
478                         case STATUS_OPTION  : status     = 1;  break;
479                         case TAG_OPTION     : tag        = 1;  break;
480                         
481                         case HELP_OPTION    : print_usage();   /* ..never returns */
482                         case VERSION_OPTION : print_version(); /* ..never returns */
483
484                         default: TRYHELP_GOODBYE();
485                 }
486         }
487
488         first_file = optind;
489
490 /*****************************************************************************************
491  ************************************* PROCESSING DATA ***********************************
492  *****************************************************************************************/
493
494         if (check < 0)   /* READ FILES, GENERATE CHECKSUMS AND PRINT TO STDOUT.. */
495         {
496                 if (quiet == 1 || warn == 1 || status == 1)
497                 {
498                         if(quiet == 1)
499                                 fprintf(stderr, "skein%dsum: the --quiet option is meaningful only when verifying checksums\n", hashbitlen);
500                         if(status ==1)
501                                 fprintf(stderr, "skein%dsum: the --status option is meaningful only when verifying checksums\n", hashbitlen);
502                         if(warn == 1)
503                                 fprintf(stderr, "skein%dsum: the --warn option is meaningful only when verifying checksums\n", hashbitlen);
504                         TRYHELP_GOODBYE();
505                 }
506
507                 int file_index;
508                 for (file_index = first_file; file_index < argc; file_index++)
509                 {
510                         const char *filename = argv[file_index];
511                         if (!is_goodfile(filename)) {
512                                 errorFound++;
513                                 continue;
514                         }
515                         number_files++;
516
517                         if (binary > 0 && hashString == 1) {
518                                 printf("skein%dsum: %s: No such file or directory\n", hashbitlen, filename);
519                                 continue;
520                         }
521
522                         char mode = binary > 0 ? 'b' : 't';
523                         if (PrintHash(filename, tag, mode) < 0)
524                                 errorFound++;
525                 }
526
527                 if (!number_files && !errorFound)
528                         HashStdin(tag);
529
530                 return (errorFound ? 1 : 0);
531         }
532
533         if (check == 1)   /* READ LISTFILES, GENERATE HASHES, COMPARE WITH STORED, PRINT RESULT */
534         {
535                 if (tag == 1 || binary >= 0)
536                 {
537                         if (tag == 1)
538                                 fprintf(stderr, "skein%dsum: the --tag option is meaningless when verifying checksums\n", hashbitlen);
539                         if (binary >= 0)
540                                 fprintf(stderr, "skein%dsum: the --text and --binary options are meaningless when verifying checksums\n", hashbitlen);
541                         TRYHELP_GOODBYE();
542                 }
543
544                 int file_index;
545                 for (file_index = first_file; file_index < argc; file_index++)
546                 {
547                         const char *filename = argv[file_index];
548                         if (!is_goodfile(filename)) {
549                                 errorFound++;
550                                 continue;
551                         }
552                         number_files++;
553
554                         FILE *fp = fopen(filename, "r");
555                         if (!fp) {
556                                 printf("skein%dsum: %s: error %d, %s\n", hashbitlen, filename, errno, strerror(errno));
557                                 continue;
558                         }
559                         if (VerifyHashesFromFile(fp, status, warn, quiet) < 0)
560                                 errorFound++;
561                         fclose(fp);
562                 }
563
564                 if (!number_files && !errorFound)
565                         if (VerifyHashesFromFile(stdin, status, warn, quiet) < 0)
566                                 errorFound++;
567
568                 return (errorFound ? 1 : 0);
569         }
570
571         return 1;
572 }