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