-
-
Notifications
You must be signed in to change notification settings - Fork 117
/
hash_check.c
1587 lines (1475 loc) · 47.9 KB
/
hash_check.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* hash_check.c - functions to parse and verify a hash file contianing message digests */
#include "hash_check.h"
#include "calc_sums.h"
#include "common_func.h"
#include "hash_print.h"
#include "output.h"
#include "parse_cmdline.h"
#include "rhash_main.h"
#include "librhash/rhash.h"
#include <assert.h>
#include <ctype.h> /* isspace */
#include <errno.h>
#include <stdlib.h>
#include <string.h>
/* size of the buffer to receive a hash file line */
#define LINE_BUFFER_SIZE 4096
/* message digest conversion macros and functions */
#define HEX_TO_DIGIT(c) ((c) <= '9' ? (c) & 0xF : ((c) - 'a' + 10) & 0xF)
#define BASE32_TO_DIGIT(c) ((c) < 'A' ? (c) - '2' + 26 : ((c) & ~0x20) - 'A')
#define BASE32_LENGTH(bits) (((bits) + 4) / 5)
#define BASE64_LENGTH(bits) (((bits) + 5) / 6)
#define BASE32_BIT_SIZE(length) (((length) * 5) & ~7)
#define BASE64_BIT_SIZE(length) (((length) * 6) & ~7)
/* pack a character sequence into a single unsigned integer */
#define THREEC2U(c1, c2, c3) (((unsigned)(c1) << 16) | \
((unsigned)(c2) << 8) | (unsigned)(c3))
#define FOURC2U(c1, c2, c3, c4) (((unsigned)(c1) << 24) | \
((unsigned)(c2) << 16) | ((unsigned)(c3) << 8) | (unsigned)(c4))
/**
* Convert a hexadecimal string to a string of bytes.
*
* @param str string to parse
* @param bin result
* @param len string length
*/
void rhash_hex_to_byte(const char* str, unsigned char* bin, int len)
{
/* parse the highest hexadecimal digit */
if ((len & 1) != 0) {
*(bin++) = HEX_TO_DIGIT(*(str++));
len--;
}
/* parse the rest - an even-sized hexadecimal string */
for (; len >= 2; len -= 2, str += 2) {
*(bin++) = (HEX_TO_DIGIT(str[0]) << 4) | HEX_TO_DIGIT(str[1]);
}
}
/**
* Decode an URL-encoded string into the specified buffer.
*
* @param buffer buffer to decode string into
* @param buffer_size buffer size
* @param src URL-encoded string
* @param src_length length of the string to decode
* @return length of the decoded string
*/
static size_t urldecode(char* buffer, size_t buffer_size, const char* src, size_t src_length)
{
char* dst = buffer;
char* dst_back = dst + buffer_size - 1;
const char* src_end = src + src_length;
assert(src_length < buffer_size);
for (; src < src_end && dst < dst_back; dst++) {
*dst = *(src++); /* copy non-escaped characters */
if (*dst == '%') {
if (*src == '%') {
src++; /* interpret '%%' as single '%' */
} else if (IS_HEX(*src)) {
/* decode character from the %<hex-digit><hex-digit> form */
int ch = HEX_TO_DIGIT(*src);
src++;
if (IS_HEX(*src)) {
ch = (ch << 4) | HEX_TO_DIGIT(*src);
src++;
}
*dst = (char)ch;
}
}
}
assert(dst <= dst_back);
*dst = '\0'; /* terminate decoded string */
return (dst - buffer);
}
/**
* Decode a string with escaped characters into the specified buffer.
*
* @param buffer buffer to decode string into
* @param buffer_size buffer size
* @param src string with escaped characters
* @param src_length length of the source string
* @return length of the decoded string
*/
static size_t unescape_characters(char* buffer, size_t buffer_size, const char* src, size_t src_length)
{
char* dst = buffer;
char* dst_back = dst + buffer_size - 1;
const char* src_end = src + src_length;
assert(src_length < buffer_size);
for (; src < src_end && dst < dst_back; dst++) {
*dst = *(src++); /* copy non-escaped characters */
if (*dst == '\\') {
if (*src == 'r')
*dst = '\r';
else if (*src == 'n')
*dst = '\n';
else if (*src != '\\')
continue;
src++;
}
}
assert(dst <= dst_back);
*dst = '\0'; /* terminate decoded string */
return (dst - buffer);
}
/**
* Encode a hash function digest size into a small number in [0,...,7].
* The digest size must be in the set { 4, 16, 20, 24, 28, 32, 48, 64 }.
*
* @param digest_size digest size (aka hash length) in bytes
* @return code for digest size on success, 32 on error
*/
static int code_digest_size(int digest_size)
{
static int size_codes[17] = {
-1, 0,-1, -1, 1, 2, 3, 4, 5, -1,
-1, -1, 6, -1, -1, -1, 7
};
return (digest_size <= 64 ? size_codes[digest_size / 4] : -1);
}
/**
* Compute a bit mask for hash functions that have a specified length
* (in bytes) of their message digest.
*
* @param digest_size length (in bytes) of a binary message digest
* @return bit mask for found hash functions, 0 on fail
*/
static uint64_t hash_bitmask_by_digest_size(int digest_size)
{
static uint64_t hash_masks[10] = { 0,0,0,0,0,0,0,0,0,0 };
int code;
if (hash_masks[9] == 0) {
unsigned hash_ids[64];
size_t count = rhash_get_all_algorithms(64, hash_ids);
size_t i;
RSH_REQUIRE(count != RHASH_ERROR, "failed to get all hash ids\n");
for (i = 0; i < count; i++) {
code = code_digest_size(rhash_get_digest_size(hash_ids[i]));
assert(0 <= code && code <= 7);
if (code >= 0)
hash_masks[code] |= hash_id_to_bit64(hash_ids[i]);
}
hash_masks[9] = 1;
}
code = code_digest_size(digest_size);
return (code >= 0 ? hash_masks[code] : 0);
}
/**
* Bit flags corresponding to possible formats of a message digest.
*/
enum FmtBitFlags {
FmtHex = 1,
FmtBase32LoweCase = 2,
FmtBase32UpperCase = 4,
FmtBase64 = 8,
FmtBase32 = (FmtBase32LoweCase | FmtBase32UpperCase),
FmtAll = (FmtHex | FmtBase32 | FmtBase64)
};
/**
* Test if a character is a hexadecimal/base32 digit.
*
* @param c the character to test
* @return a combination of Fmt* bits
*/
static int test_hash_char(char c)
{
static unsigned char char_bits[80] = {
8, 0, 0, 0, 8, 9, 9, 15, 15, 15, 15, 15, 15, 9, 9, 0, 0, 0, 0, 0,
0, 0, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10
};
c -= '+';
return ((unsigned)c <= 80 ? char_bits[(unsigned)c] : 0);
}
/**
* Detect if given string contains a hexadecimal or base32 hash.
*
* @param ptr the pointer to start scanning from
* @param end pointer to scan to
* @param p_len pointer to a number to store length of detected message digest
* @return type of detected hash as combination of Fmt* flags
*/
static int detect_hash_type(char** ptr, char* end, int* p_len)
{
char* p = *ptr;
size_t len = 0;
size_t eq_num = 0;
int char_type = 0;
int next_type = FmtAll;
if (p < end) {
/* search forward (but no more then 129 symbols) */
if ((end - p) >= 129) end = p + 129;
for (; p <= end && (next_type &= test_hash_char(*p)); len++, p++)
char_type = next_type;
if ((char_type & FmtBase64) && *p == '=')
{
char_type = FmtBase64;
for (; *p == '=' && p <= end; eq_num++, p++);
}
} else {
/* search backward (but no more then 129 symbols) */
if ((p - end) >= 129) end = p - 129;
for (; p > end && p[-1] == '='; eq_num++, p--)
char_type = FmtBase64;
for (; p > end && (next_type &= test_hash_char(p[-1])); len++, p--)
char_type = next_type;
}
if ((char_type & FmtBase64) != 0)
{
size_t hash_len = (len * 6) & ~7;
if (eq_num > 3 || ((len + eq_num) & 3) || len != (hash_len + 5) / 6)
char_type &= ~FmtBase64;
}
*ptr = p;
*p_len = (int)len;
return char_type;
}
/**
* Check if a message digest of the specified bit length is supported by the program.
*
* @param length the bit length of a binary message digest value
* @return 1 if a message digest of the specified bit length is supported, 0 otherwise
*/
static int is_acceptable_bit_length(int length)
{
if ((length & 31) == 0 && length <= 512)
{
int pow = get_ctz(length >> 5);
int code = ((length >> (pow + 6)) << 3) | pow;
return (code < 32 && ((1 << code) & 0x101061d));
}
return 0;
}
/**
* Test the given substring to be a hexadecimal or base32
* message digest of one of the supported hash functions.
*
* @param ptr the pointer to start scanning from
* @param end pointer to scan to
* @param p_len pointer to a number to store length of detected message digest
* @return possible type of detected hash as algorithm RHASH id
*/
static unsigned char test_hash_string(char** ptr, char* end, int* p_len)
{
int len = 0;
int char_type = detect_hash_type(ptr, end, &len);
unsigned char hash_type = 0;
if ((char_type & FmtHex) && is_acceptable_bit_length(len * 4))
hash_type |= FmtHex;
if ((char_type & FmtBase32) && is_acceptable_bit_length(BASE32_BIT_SIZE(len)))
hash_type |= FmtBase32;
if ((char_type & FmtBase64) && is_acceptable_bit_length(BASE64_BIT_SIZE(len)))
hash_type |= FmtBase64;
if (hash_type != 0)
*p_len = len;
return hash_type;
}
enum HashNameMatchModes {
ExactMatch,
PrefixMatch
};
/**
* Detect a hash-function id by its BSD name.
*
* @param name an uppercase string, a possible name of a hash-function
* @param length length of the name string
* @param match_mode whether the name parameter must match the name of a
* known hash algorithm exactly, or trailing chars are
* allowed.
* @return id of hash function if found, zero otherwise
*/
static unsigned bsd_hash_name_to_id(const char* name, unsigned length, enum HashNameMatchModes match_mode)
{
#define code2mask_size (19 * 2)
static unsigned code2mask[code2mask_size] = {
FOURC2U('A', 'I', 'C', 'H'), RHASH_AICH,
FOURC2U('B', 'L', 'A', 'K'), (RHASH_BLAKE2S | RHASH_BLAKE2B),
FOURC2U('B', 'T', 'I', 'H'), RHASH_BTIH,
FOURC2U('C', 'R', 'C', '3'), (RHASH_CRC32 | RHASH_CRC32C),
FOURC2U('E', 'D', '2', 'K'), RHASH_ED2K,
FOURC2U('E', 'D', 'O', 'N'), (RHASH_EDONR256 | RHASH_EDONR512),
FOURC2U('G', 'O', 'S', 'T'),
(RHASH_GOST12_256 | RHASH_GOST12_512 | RHASH_GOST94 | RHASH_GOST94_CRYPTOPRO),
FOURC2U('H', 'A', 'S', '1'), RHASH_HAS160,
FOURC2U('M', 'D', '4', 0), RHASH_MD4,
FOURC2U('M', 'D', '5', 0), RHASH_MD5,
FOURC2U('R', 'I', 'P', 'E'), RHASH_RIPEMD160,
FOURC2U('S', 'H', 'A', '1'), RHASH_SHA1,
FOURC2U('S', 'H', 'A', '2'), (RHASH_SHA224 | RHASH_SHA256),
FOURC2U('S', 'H', 'A', '3'),
(RHASH_SHA384 | RHASH_SHA3_224 | RHASH_SHA3_256 | RHASH_SHA3_384 | RHASH_SHA3_512),
FOURC2U('S', 'H', 'A', '5'), RHASH_SHA512,
FOURC2U('S', 'N', 'E', 'F'), (RHASH_SNEFRU128 | RHASH_SNEFRU256),
FOURC2U('T', 'I', 'G', 'E'), RHASH_TIGER,
FOURC2U('T', 'T', 'H', 0), RHASH_TTH,
FOURC2U('W', 'H', 'I', 'R'), RHASH_WHIRLPOOL
};
unsigned code, i, hash_mask, hash_id;
char fourth_char;
if (length < 3) return 0;
fourth_char = (name[3] != '-' ? name[3] : name[4]);
code = FOURC2U(name[0], name[1], name[2], fourth_char);
/* quick fix to detect "RMD160" as RIPEMD160 */
if (code == FOURC2U('R', 'M', 'D', '1'))
return (length == 6 && name[4] == '6' && name[5] == '0' ? RHASH_RIPEMD160 : 0);
for (i = 0; code2mask[i] != code; i += 2)
if (i >= (code2mask_size - 2)) return 0;
hash_mask = code2mask[i + 1];
i = get_ctz(hash_mask);
if (length <= 4)
{
assert((hash_mask & (hash_mask - 1)) == 0);
return (length == strlen(hash_info_table[i].name) ? hash_mask : 0);
}
/* look for the hash_id in the hash_mask */
for (hash_id = 1 << i; hash_id && hash_id <= hash_mask; i++, hash_id <<= 1)
{
const char* a;
const char* b;
if ((hash_id & hash_mask) == 0)
continue;
assert(length > 4);
assert(strlen(hash_info_table[i].name) >= 4);
/* check the name tail, starting from &name[3] to detect names like "SHA-1" or "SHA256" */
for (a = hash_info_table[i].name + 3, b = name + 3; *a; a++, b++)
{
if (*a == *b)
continue;
else if (*a == '-')
b--;
else if (*b == '-')
a--;
else
break;
}
if (!*a && (match_mode == PrefixMatch || !*b))
return hash_id;
}
return 0;
}
/**
* Detect ASCII-7 white spaces (0x09=\t, 0x0a=\n, 0x0b=\v, 0x0c=\f, 0x0d=\r, 0x20=' ').
* Note that standard C function isspace() is locale specific and
* detects Unicode spaces, like U+00A0.
*
* @param ch character to check
* @return non-zero if ch is space, zero otherwise
*/
static int rhash_isspace(char ch)
{
unsigned code = (unsigned)(ch - 9);
return (code < 0x18 && ((1u << code) & 0x80001f));
}
/**
* Extended hash parser data.
*/
struct hash_parser_ext {
struct hash_parser hp;
file_t* hash_file;
file_t parent_dir;
FILE* fd;
uint64_t expected_hash_mask;
unsigned is_sfv;
unsigned line_number;
char buffer[LINE_BUFFER_SIZE];
};
/**
* Information about found token.
*/
struct hash_token
{
char* begin; /* start of the buffer to parse */
char* end; /* end of the buffer to parse */
file_t* p_parsed_path;
struct hash_parser_ext* parser;
struct hash_value* p_hashes;
unsigned expected_hash_id;
int hash_type;
};
/**
* Bit-flags for the fstat_path_token().
*/
enum FstatPathBitFlags {
PathUrlDecode = 1,
PathUnescape = 2
};
static int fstat_path_token(struct hash_token* token, char* path, size_t path_length, int is_url);
/**
* Bit-flags for the match_hash_tokens().
*/
enum MhtOptionsBitFlags {
MhtFstatPath = 1,
MhtAllowOneHash = 2,
MhtAllowEscapedPath = 4
};
/**
* Constants returned by match_hash_tokens() and some other functions.
*/
enum MhtResults {
ResFailed = 0,
ResAllMatched = 1,
ResPathNotExists = 2,
ResOneHashDetected = 3
};
/**
* Parse the buffer pointed by token->begin, into tokens specified by format string.
* The format string can contain the following special characters:
* '\1' - BSD hash function name, '\2' - any hash, '\3' - specified hash,
* '\4' - an URL-encoded file name, '\5' - a file size,
* '\6' - a required space or line end.
* A space ' ' means 0 or more space characters.
* '$' - parse the rest of the buffer and the format string backward.
* Other (non-special) symbols mean themselves.
* The function updates token->begin and token->end pointers on success.
*
* @param token the structure to store parsed tokens info
* @param format the format string
* @param bit_flags MhtFstatPath flag to run fstat on parsed path,
* MhtAllowOneHash to allow line containing one message digest without a file path
* @return one of the MhtResults constants
*/
static int match_hash_tokens(struct hash_token* token, const char* format, unsigned bit_flags)
{
int backward = 0;
char buf[20];
const char* fend = strchr(format, '\0');
char* begin = token->begin;
char* end = token->end;
char* url_path = 0;
size_t url_length = 0;
struct hash_parser* hp = &token->parser->hp;
struct hash_value hv;
int unsaved_hashval = 0;
int unescape_flag = 0;
memset(&hv, 0, sizeof(hv));
if ((bit_flags & MhtAllowEscapedPath) && (opt.flags & OPT_NO_PATH_ESCAPING) == 0 &&
begin[0] == '\\' && !(begin[1] == '\\' && begin[2] == '?' && begin[3] == '\\')) {
begin++;
unescape_flag = PathUnescape;
}
while (format < fend) {
const char* search_str;
int len = 0;
uint64_t file_size;
if (backward) {
for (; fend[-1] >= '-' && format < fend; fend--, len++);
if (len == 0)
fend--;
search_str = fend;
} else {
search_str = format;
for (; *format >= '-' && format < fend; format++, len++);
if (len == 0)
format++;
}
if (len > 0) {
if ((end - begin) < len)
return ResFailed;
if (0 != memcmp(search_str, (backward ? end - len : begin), len))
return ResFailed;
if (backward)
end -= len;
else
begin += len;
continue;
}
assert(len == 0);
/* find substring specified by single character */
switch (*search_str) {
case '\1': /* parse BSD hash function name */
/* the name should contain alphanumeric or '-' symbols, but */
/* actually the loop shall stop at characters [:& \(\t] */
for (; (begin[len] <= '9' ? begin[len] >= '0' || begin[len] == '-' : begin[len] >= 'A'); len++) {
if (len >= 20)
return ResFailed; /* limit name length */
buf[len] = toupper(begin[len]);
}
buf[len] = '\0';
token->expected_hash_id = bsd_hash_name_to_id(buf, len, ExactMatch);
if (!token->expected_hash_id)
return ResFailed;
token->hash_type = FmtAll;
begin += len;
break;
case '\2':
case '\3':
if (backward) {
/* trim right */
for (; begin < end && rhash_isspace(end[-1]); end--, len++);
if (begin == end)
return ResFailed;
hv.format = test_hash_string(&end, begin, &len);
hv.offset = (unsigned short)(end - hp->line_begin);
} else {
/* trim left */
for (; rhash_isspace(*begin) && begin < end; begin++, len++);
if (begin == end)
return ResFailed;
hv.offset = (unsigned short)(begin - hp->line_begin);
hv.format = test_hash_string(&begin, end, &len) & token->hash_type;
}
if (!hv.format)
return ResFailed;
if (*search_str == '\3') {
/* verify message digest type */
int bit_length = rhash_get_digest_size(token->expected_hash_id) * 8;
hv.format &= token->hash_type;
if ((len * 4) != bit_length)
hv.format &= ~FmtHex;
if (len != BASE32_LENGTH(bit_length))
hv.format &= ~FmtBase32;
if (len != BASE64_LENGTH(bit_length))
hv.format &= ~FmtBase64;
if (!hv.format)
return ResFailed;
hv.hash_mask = hash_id_to_bit64(token->expected_hash_id);
} else hv.hash_mask = 0;
hv.length = (unsigned char)len;
unsaved_hashval = 1;
break;
case '\4': /* get URL-encoded name */
url_path = begin;
url_length = strcspn(begin, "?&|");
if (url_length == 0)
return ResFailed; /* empty name */
begin += url_length;
break;
case '\5': /* retrieve file size */
assert(!backward);
file_size = 0L;
for (; '0' <= *begin && *begin <= '9'; begin++, len++) {
file_size = file_size * 10 + (*begin - '0');
}
if (len == 0)
return ResFailed;
else {
hp->file_size = file_size;
hp->bit_flags |= HpHasFileSize;
}
break;
case '\6':
case ' ':
if (backward) {
char* low_limit = (begin < end && *search_str == '\6' ? end - 1 : begin);
for (; low_limit < end && rhash_isspace(end[-1]); end--, len++);
} else {
char* hi_limit = (begin < end && *search_str == '\6' ? begin + 1 : end);
for (; begin < hi_limit && rhash_isspace(*begin); begin++, len++);
}
/* check if space is mandatory */
if (*search_str == '\6' && len == 0) {
/* for '\6' verify (len > 0 || (MhtAllowOneHash is set && begin == end)) */
if (!(bit_flags & MhtAllowOneHash) || begin < end)
return ResFailed;
}
break;
case '$':
backward = 1; /* switch to parsing string backward */
break;
default:
if ((backward ? *(--end) : *(begin++)) != *search_str)
return ResFailed;
}
}
if (unsaved_hashval && hp->hashes_num < HP_MAX_HASHES) {
token->p_hashes[hp->hashes_num++] = hv;
}
if (!backward) {
/* eat zero or one leading space */
if (begin < end && rhash_isspace(*begin))
begin++;
}
/* the rest is stored as a file path */
token->begin = begin;
token->end = end;
if ((bit_flags & MhtAllowOneHash) != 0 && hp->hashes_num == 1 && begin == end)
{
/* a single hash without a file path was detected */
struct hash_parser_ext* const parser = token->parser;
file_t* parsed_path = &parser->hp.parsed_path;
if (file_modify_path(parsed_path, parser->hash_file, NULL, FModifyRemoveExtension) < 0)
return ResFailed;
if ((bit_flags & MhtFstatPath) != 0 && file_stat(parsed_path, 0) < 0)
hp->parsed_path_errno = errno;
return ResOneHashDetected;
}
if ((bit_flags & MhtFstatPath) != 0) {
int fstat_res;
if (url_path != 0) {
fstat_res = fstat_path_token(token, url_path, url_length, PathUrlDecode);
} else {
size_t path_length;
if (begin[0] == '*' && unescape_flag == 0)
begin++;
path_length = end - begin;
fstat_res = fstat_path_token(token, begin, path_length, unescape_flag);
}
if (fstat_res < 0)
return ResPathNotExists;
}
return ResAllMatched;
}
/**
* Fstat given file path. Optionally prepend it, if needed, by parent directory.
* Depending on bit_flags, the path is url-decoded or decoded using escape sequences.
* Fstat result is stored into token->p_parsed_path.
*
* @param token current tokens parsing context
* @param str pointer to the path start
* @param str_length length of the path
* @param bit_flags PathUrlDecode or PathUnescape to decode path
* @return 0 on success, -1 on fstat fail
*/
static int fstat_path_token(struct hash_token* token, char* str, size_t str_length, int bit_flags)
{
static char buffer[LINE_BUFFER_SIZE];
file_t* parent_dir = &token->parser->parent_dir;
unsigned init_flags = (FILE_IS_IN_UTF8(token->parser->hash_file) ?
FileInitRunFstat | FileInitUtf8PrintPath : FileInitRunFstat);
char* path = (bit_flags == 0 ? str : buffer);
size_t path_length = (bit_flags == 0 ? str_length : (bit_flags & PathUrlDecode ?
urldecode(buffer, LINE_BUFFER_SIZE, str, str_length) :
unescape_characters(buffer, LINE_BUFFER_SIZE, str, str_length)));
int res;
int is_absolute = IS_PATH_SEPARATOR(path[0]);
char saved_char = path[path_length];
path[path_length] = '\0';
IF_WINDOWS(is_absolute = is_absolute || (path[0] && path[1] == ':'));
if (is_absolute || !parent_dir->real_path)
parent_dir = NULL;
if ((bit_flags & PathUnescape) != 0)
init_flags |= FileInitUseRealPathAsIs;
res = file_init_by_print_path(token->p_parsed_path, parent_dir, path, init_flags);
if (res < 0 && token->p_parsed_path == &token->parser->hp.parsed_path)
token->parser->hp.parsed_path_errno = errno;
path[path_length] = saved_char;
return res;
}
/**
* Cleanup token context and fill hash_mask of the parser.
*
* @param token token parsing context
* @return ResPathNotExists if path has not been found, ResAllMatched otherwise
*/
static int finalize_parsed_data(struct hash_token* token)
{
int i;
struct hash_parser* const parser = &token->parser->hp;
if (token->p_parsed_path != &parser->parsed_path) {
file_cleanup(&parser->parsed_path);
parser->parsed_path = *token->p_parsed_path;
}
if (FILE_ISBAD(&parser->parsed_path) || !parser->parsed_path.real_path)
return ResPathNotExists;
if (token->p_hashes != parser->hashes) {
assert(parser->hashes_num == 1);
parser->hashes[0] = token->p_hashes[0];
}
/* post-process parsed message digests */
for (i = 0; i < parser->hashes_num; i++) {
struct hash_value* hv = &parser->hashes[i];
char* hash_str = parser->line_begin + hv->offset;
hash_str[hv->length] = '\0'; /* terminate the message digest */
if (hv->hash_mask == 0) {
/* calculate bit-mask of hash function */
uint64_t hash_mask = 0;
if (hv->format & FmtHex) {
hash_mask |= hash_bitmask_by_digest_size(hv->length >> 1);
}
if (hv->format & FmtBase32) {
assert(((hv->length * 5 / 8) & 3) == 0);
hash_mask |= hash_bitmask_by_digest_size(BASE32_BIT_SIZE(hv->length) / 8);
}
if (hv->format & FmtBase64) {
hash_mask |= hash_bitmask_by_digest_size(BASE64_BIT_SIZE(hv->length) / 8);
}
assert(hash_mask != 0);
if ((hash_mask & token->parser->expected_hash_mask) != 0)
hash_mask &= token->parser->expected_hash_mask;
hv->hash_mask = hash_mask;
}
parser->hash_mask |= hv->hash_mask;
}
return ResAllMatched;
}
/**
* Parse the rest of magnet link.
*
* @param token tokens parsing context
* @return ResAllMatched on success, ResFailed on a bad magnet link
*/
static int parse_magnet_url(struct hash_token* token)
{
char* url_path = 0;
size_t url_length;
/* loop by magnet link parameters */
while (1) {
char* next = strchr(token->begin, '&');
char* param_end = (next ? next++ : token->end);
char* hf_end;
if ((token->begin += 3) < param_end) {
switch (THREEC2U(token->begin[-3], token->begin[-2], token->begin[-1])) {
case THREEC2U('d', 'n', '='): /* URL-encoded file path */
url_path = token->begin;
url_length = param_end - token->begin;
break;
case THREEC2U('x', 'l', '='): /* file size */
if (!match_hash_tokens(token, "\5", 0))
return ResFailed;
if (token->begin != param_end)
return ResFailed;
break;
case THREEC2U('x', 't', '='): /* a file hash */
{
int i;
/* find last ':' character (hash name can be complex like tree:tiger) */
for (hf_end = param_end - 1; *hf_end != ':' && hf_end > token->begin; hf_end--);
/* test for the "urn:" string */
if ((token->begin += 4) >= hf_end)
return ResFailed;
if (FOURC2U(token->begin[-4], token->begin[-3], token->begin[-2], token->begin[-1]) !=
FOURC2U('u', 'r', 'n', ':'))
return ResFailed;
/* find hash by its magnet link specific URN name */
for (i = 0; i < RHASH_HASH_COUNT; i++) {
const char* urn = rhash_get_magnet_name(1 << i);
size_t len = hf_end - token->begin;
if (strncmp(token->begin, urn, len) == 0 && urn[len] == '\0')
break;
}
if (i >= RHASH_HASH_COUNT) {
if (opt.verbose) {
*hf_end = '\0';
log_warning(_("unknown hash in magnet link: %s\n"), token->begin);
}
return ResFailed;
}
token->begin = hf_end + 1;
token->expected_hash_id = 1 << i;
token->hash_type = (FmtHex | FmtBase32);
if (!match_hash_tokens(token, "\3", 0))
return ResFailed;
if (token->begin != param_end)
return ResFailed;
break;
}
/* note: this switch () skips all unknown parameters */
}
}
if (next)
token->begin = next;
else
break;
}
if (!url_path || token->parser->hp.hashes_num == 0)
return ResFailed;
fstat_path_token(token, url_path, url_length, PathUrlDecode);
return finalize_parsed_data(token);
}
/**
* Parse the rest of ed2k link.
*
* @param token the structure to store parsed tokens info
* @return ResAllMatched on success, ResFailed on a bad ed2k link
*/
static int parse_ed2k_link(struct hash_token* token)
{
token->expected_hash_id = RHASH_ED2K;
token->hash_type = FmtHex;
if (!match_hash_tokens(token, "\4|\5|\3|", MhtFstatPath))
return ResFailed;
/* try to parse optional AICH hash */
token->expected_hash_id = RHASH_AICH;
token->hash_type = (FmtHex | FmtBase32); /* AICH is usually base32-encoded*/
match_hash_tokens(token, "h=\3|", 0);
return finalize_parsed_data(token);
}
/**
* Parse a line of a hash-file. This function accepts five formats.
* <ul>
* <li/> magnet links
* <li/> EDonkey/EMule ed2k links
* <li/> BSD format: HASH_FUNCTION ( filepath ) = FILE_HASH
* <li/> filepath FILE_HASH1 FILE_HASH2...
* <li/> FILE_HASH1 FILE_HASH2... filepath
* </ul>
* For a magnet/ed2k links file size is also parsed.
*
* @param parser structure to store parsed message digests, file path and file size
* @param check_eol boolean flag meaning that '\n' at the end of the line is required
* @return non-zero on success (ResAllMatched, ResOneHashDetected, ResPathNotExists),
* ResFailed if couldn't parse the line
*/
static int parse_hash_file_line(struct hash_parser_ext* parser, int check_eol)
{
struct hash_token token;
char* const line_start = parser->hp.line_begin;
char* token_start = line_start;
char* line_end = strchr(line_start, '\0');
int res;
assert(line_start[0] != '\0');
/* return if EOL not found at the end of the line */
if (line_end[-1] != '\n' && check_eol)
return ResFailed;
/* remove trailing CR and LF */
while ((line_end[-1] == '\n' || line_end[-1] == '\r') && line_end > line_start)
*(--line_end) = 0;
/* skip white spaces at the start of the line */
while (rhash_isspace(*token_start))
token_start++;
memset(&token, 0, sizeof(token));
token.begin = token_start;
token.end = line_end;
token.parser = parser;
token.p_parsed_path = &parser->hp.parsed_path;
token.p_hashes = parser->hp.hashes;
memset(&parser->hp, 0, sizeof(parser->hp));
parser->hp.line_begin = line_start;
parser->hp.file_size = (uint64_t)-1;
/* check for a minimum acceptable message digest length */
if ((token_start + 8) > line_end)
return ResFailed;
if (strncmp(token.begin, "ed2k://|file|", 13) == 0) {
token.begin += 13;
return parse_ed2k_link(&token);
}
if (strncmp(token.begin, "magnet:?", 8) == 0) {
token.begin += 8;
return parse_magnet_url(&token);
}
/* check for BSD-formatted line has been processed */
res = match_hash_tokens(&token, "\1 ($) = \3", MhtFstatPath | MhtAllowEscapedPath);
if (res != ResFailed)
return finalize_parsed_data(&token);
token.hash_type = FmtAll;
token.begin = line_start;
{
const unsigned is_sfv_format = parser->is_sfv;
unsigned valid_direction = 0;
unsigned state;
unsigned token_flags = (MhtFstatPath | MhtAllowEscapedPath | MhtAllowOneHash);
struct file_t secondary_path;
struct hash_token secondary_token;
struct hash_token *cur_token = &token;
struct hash_value secondary_hash[1];
memset(&secondary_path, 0, sizeof(secondary_path));
memcpy(&secondary_token, &token, sizeof(token));
secondary_token.p_hashes = secondary_hash;
/* parse one hash from each line end */
for (state = 0; state < 2; state++)
{
const unsigned is_backward = (state ^ is_sfv_format);
const char* token_format = (is_backward ? "$\6\2" : "\2\6");
int res = match_hash_tokens(cur_token, token_format, token_flags);
if (res == ResAllMatched || res == ResOneHashDetected)
{
return finalize_parsed_data(cur_token);
}
else if (res == ResPathNotExists)
{
assert(parser->hp.hashes_num == 1);
valid_direction |= (1 << state); /* mark the current parsing direction as valid */
if (token.p_parsed_path == &parser->hp.parsed_path)
token.p_parsed_path = secondary_token.p_parsed_path = &secondary_path;
cur_token = &secondary_token;
parser->hp.hashes_num = 0;
}
token_flags &= ~MhtAllowOneHash;
}
token_flags = MhtFstatPath;
/* parse the rest of hashes */
for (state = 0; state < 2; state++)
{
if ((valid_direction & (1 << state)) != 0)
{
const unsigned is_backward = (state ^ is_sfv_format);
const char* token_format = (is_backward ? "$\6\2" : "\2\6");
/* restore parsing state and a parsed hash */
parser->hp.hashes_num = 1;
if (state == 1 && valid_direction == 3)
{
token.begin = secondary_token.begin;
token.end = secondary_token.end;
token.p_hashes[0] = secondary_token.p_hashes[0];
}
/* allow FmtBase64 only if the first hash can be interpreted only as Base64-encoded */
token.hash_type = (token.hash_type & ~FmtBase64) |
(token.p_hashes[0].format == FmtBase64 ? FmtBase64 : 0);
for (;;)
{
int res = match_hash_tokens(&token, token_format, token_flags);
assert(res != ResOneHashDetected);
if (res == ResAllMatched)
return finalize_parsed_data(&token);
else if (res == ResFailed)
break;
}
}
}
file_cleanup(&secondary_path);
if (token.p_parsed_path != &parser->hp.parsed_path)
return ResPathNotExists;
}
return ResFailed; /* could not parse line */
}
/**
* Bit-flags for the hash.
*/
enum CompareHashBitFlags {
CompareHashCaseSensitive = 1,
CompareHashReversed = 2
};
/**
* Compare two message digests. For base64 encoding, the case-sensitive comparasion is done.
* For hexadecimal or base32 encodings, the case-insensitive match occurs.
* For the GOST94 hash, the additional reversed case-insensitive match is done.
*
* @param calculated_hash the calculated message digest, for the hex/base32 the value must be in upper case
* @param expected a message digest from a hash file to match against
* @param length length of the message digests
* @param comparision_mode 0, CompareHashCaseSensitive or CompareHashReversed comparision mode
* @return 1 if message digests match, 0 otherwise
*/
static int is_hash_string_equal(const char* calculated_hash, const char* expected, size_t length, int comparision_mode)
{
if (comparision_mode == CompareHashCaseSensitive)
return (memcmp(calculated_hash, expected, length) == 0);
{