Debian Codegraph @

libhc.c

raw symbols SCIP
1 /* -*- Mode: C; c-file-style: "stroustrup" -*- */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <time.h>
7
8 #if defined( REGEXP_BSD )
9 #define _REGEX_RE_COMP
10 #include <regex.h>
11 #elif defined( REGEXP_POSIX )
12 #include <sys/types.h>
13 #include <regex.h>
14 #else
15 /* no regular expression support */
16 #endif
17
18 #define BUILD_DLL
19 #include "hashcash.h"
20 #include "utct.h"
21 #include "libfastmint.h"
22 #include "sha1.h"
23 #include "random.h"
24 #include "sstring.h"
25
26
27 time_t round_off( time_t now_time, int digits );
28
29 #if DEBUG
30 /* smaller base for debugging */
31 #define GROUP_SIZE 255
32 #define GROUP_DIGITS 2
33 #define GFFORMAT "%x"
34 #define GFORMAT "%02x"
35 #else
36 #define GROUP_SIZE 0xFFFFFFFFU
37 #define GROUP_DIGITS 8
38 #define GFFORMAT "%x"
39 #define GFORMAT "%08x"
40 #endif
41
42 long per_sec = 0; /* cache calculation */
43
44 char *strrstr(char *s1,char *s2)
45 {
46 char *sc2 = NULL , *psc1 = NULL , *ps1 = NULL ;
47
48 if ( *s2 == '\0' ) { return s1; }
49 ps1 = s1 + strlen(s1);
50
51 while( ps1 != s1 ) {
52 --ps1;
53 for ( psc1 = ps1, sc2 = s2; ; ) {
54 if (*(psc1++) != *(sc2++)) { break; }
55 else if ( *sc2 == '\0' ) { return ps1; }
56 }
57 }
58 return NULL;
59 }
60
61 int wild_match( char* pat, char* str )
62 {
63 int num = 1, last = 0, first = 1;
64 char* term = NULL , *ptr = pat, *pos = str;
65
66 do {
67 term = ptr; ptr = strchr( ptr, '*' );
68 if ( ptr ) { *ptr = '\0'; ptr++; }
69 else { last = 1; }
70
71 if ( *term != '\0' ) {
72 if ( first ) { /* begin */
73 if ( strncmp( pos, term, strlen( term ) ) != 0 ) {
74 return 0;
75 }
76 pos += strlen( term );
77 } else if ( !first ) { /* middle */
78 if ( last ) {
79 pos = strrstr( pos, term );
80 } else {
81 pos = strstr( pos, term );
82 }
83 if ( pos == 0 ) { return 0; }
84 pos += strlen( term );
85 }
86 if ( last && *pos != '\0' ) {
87 return 0;
88 }
89 }
90
91 num++; first = 0;
92 } while ( term && !last );
93
94 return 1;
95 }
96
97 int email_match( const char* email, const char* pattern )
98 {
99 int len = 0 , ret = 0;
100 char *pat_user = NULL, *pat_dom = NULL;
101 char *em_user = NULL, *em_dom = NULL;
102 char *pat_sub = NULL , *em_sub = NULL , *pat_next = NULL , *em_next = NULL , *state = NULL ;
103
104 sstrtok( pattern, "@", &pat_user, 0, &len, &state );
105 sstrtok( NULL, "@", &pat_dom, 0, &len, &state );
106
107 sstrtok( email, "@", &em_user, 0, &len, &state );
108 sstrtok( NULL, "@", &em_dom, 0, &len, &state );
109
110 /* if @ in pattern, must have @ sign in email too */
111 if ( pat_dom && em_dom == NULL ) { goto done; }
112
113 if ( !wild_match( pat_user, em_user ) ) { goto done; }
114
115 if ( !pat_dom && !em_dom ) { ret = 1; goto done; } /* no @ in either, ok */
116
117 pat_next = pat_dom; em_next = em_dom;
118 do {
119 pat_sub = pat_next; em_sub = em_next;
120 pat_next = strchr( pat_next, '.' );
121 if ( pat_next ) { *pat_next = '\0'; pat_next++; }
122 em_next = strchr( em_next, '.' );
123 if ( em_next ) { *em_next = '\0'; em_next++; }
124
125 if ( !wild_match( pat_sub, em_sub ) ) { goto done; }
126
127 } while ( pat_next && em_next );
128
129 /* different numbers of subdomains, fail */
130 if ( ( pat_next == NULL && em_next != NULL ) ||
131 ( pat_next != NULL && em_next == NULL ) ) { goto done; }
132
133 ret = 1;
134 done:
135 if ( pat_user ) { free( pat_user ); }
136 if ( pat_dom ) { free( pat_dom ); }
137 if ( em_user ) { free( em_user ); }
138 if ( em_dom ) { free( em_dom ); }
139 return ret;
140 }
141
142 const char* hashcash_version( void ) { return HASHCASH_VERSION_STRING; }
143
144 char* hashcash_simple_mint( const char* resource, unsigned bits,
145 long anon_period, char* ext, int compress ) {
146 time_t now_time = time( 0 );
147 char* stamp = NULL;
148 int ret = hashcash_mint( now_time, 6, resource, bits, anon_period,
149 &stamp, NULL, NULL, ext, compress, NULL, NULL );
150 if ( ret != HASHCASH_OK ) {
151 return NULL;
152 }
153 return stamp;
154 }
155
156 int hashcash_mint( time_t now_time, int time_width, const char* resource,
157 unsigned bits, long anon_period, char** new_token,
158 long* anon_random, double* tries_taken, char* ext,
159 int compress, hashcash_callback cb, void* user_arg )
160 {
161 long rnd = 0 ;
162 char now_utime[ MAX_UTC+1 ] = {0}; /* current time */
163 char* token = 0;
164 double taken;
165
166 if ( resource == NULL ) {
167 return HASHCASH_INTERNAL_ERROR;
168 }
169
170 if ( anon_random == NULL ) { anon_random = &rnd; }
171
172 *anon_random = 0;
173
174 if ( bits > SHA1_DIGEST_BYTES * 8 ) {
175 return HASHCASH_INVALID_TOK_LEN;
176 }
177
178 if ( time_width == 0 ) { time_width = 6; } /* default YYMMDD */
179
180 if ( now_time < 0 ) {
181 return HASHCASH_INVALID_TIME;
182 }
183
184 if ( anon_period != 0 ) {
185 if ( !random_rectangular( (long)anon_period, anon_random ) ) {
186 return HASHCASH_RNG_FAILED;
187 }
188 }
189
190 now_time += *anon_random;
191
192 if ( time_width != 12 && time_width != 10 && time_width != 6 ) {
193 return HASHCASH_INVALID_TIME_WIDTH;
194 }
195
196 now_time = round_off( now_time, 12-time_width );
197 hashcash_to_utctimestr( now_utime, time_width, now_time );
198
199 if ( !ext ) { ext = ""; }
200 token = malloc( MAX_TOK+strlen(ext)+1 );
201 if ( token == NULL ) { return HASHCASH_OUT_OF_MEMORY; }
202 sprintf( token, "%d:%d:%s:%s:%s:",
203 HASHCASH_FORMAT_VERSION, bits, now_utime, resource, ext );
204
205 taken = hashcash_fastmint( bits,token,compress,new_token,cb,user_arg );
206 if ( taken < 0 ) {
207 free( token );
208 return HASHCASH_USER_ABORT;
209 }
210 free( token );
211
212 if ( tries_taken ) { *tries_taken = taken; }
213
214 return HASHCASH_OK;
215 }
216
217 #define X_HASHCASH "X-Hashcash"
218 #define CONT '\t'
219 #define LF "\r\n"
220
221 char* hashcash_make_header( const char* stamp, int line_len,
222 const char* header, char cont,
223 const char* lf )
224 {
225 int stamp_len = strlen( stamp ), i, fstep, step, tstep, lf_len;
226 int stamp_left = stamp_len;
227 int lines, header_len, cont_len, max_res;
228 char* res, *resp;
229 char conts[2];
230
231 if ( header == NULL ) { header = X_HASHCASH; }
232 if ( cont == '\0' ) { cont = CONT; }
233 if ( lf == NULL ) { lf = LF; }
234
235 header_len = strlen( header );
236 cont_len = ( cont == CONT ) ? 8 : 1;
237 conts[0] = cont;
238 conts[1] = '\0';
239
240 lines = ((stamp_len+header_len+2) / (line_len-cont_len))+1;
241
242 lf_len = strlen(lf);
243 max_res = lines*(line_len+lf_len+1);
244 res = malloc( max_res+1 );
245 res[0]='\0';
246 resp = res;
247 strncat( resp, header, max_res );
248 resp += header_len;
249
250 fstep = line_len - header_len;
251 step = line_len - cont_len;
252
253 for ( i = 0; i < stamp_len; stamp += tstep, i += tstep ) {
254 tstep = i ? step : fstep;
255 if ( tstep > stamp_left ) { tstep = stamp_left; }
256 if ( i ) { strncat( resp, conts, 1 ); resp++; }
257 strncat( resp, stamp, tstep );
258 resp += tstep;
259 strncat( resp, lf, lf_len );
260 resp += lf_len;
261 stamp_left -= tstep;
262 }
263 return res;
264 }
265
266 time_t round_off( time_t now_time, int digits )
267 {
268 struct tm* now = NULL ;
269
270 if ( digits != 2 && digits != 4 &&
271 digits != 6 && digits != 8 && digits != 10 ) {
272 return now_time;
273 }
274 now = gmtime( &now_time ); /* still in UTC */
275
276 switch ( digits ) {
277 case 10: now->tm_mon = 0;
278 case 8: now->tm_mday = 1;
279 case 6: now->tm_hour = 0;
280 case 4: now->tm_min = 0;
281 case 2: now->tm_sec = 0;
282 }
283 return mk_utctime( now );
284 }
285
286 int hashcash_validity_to_width( long validity_period )
287 {
288 int time_width = 6; /* default YYMMDD */
289 if ( validity_period < 0 ) { return 0; }
290 if ( validity_period != 0 ) {
291 /* YYMMDDhhmmss or YYMMDDhhmm or YYMMDD */
292 if ( validity_period < 2*TIME_MINUTE ) { time_width = 12; }
293 else if ( validity_period < 2*TIME_HOUR ) { time_width = 10; }
294 else { time_width = 6; }
295 }
296 return time_width;
297 }
298
299 /* all chars from ascii(33) to ascii(126) inclusive, minus : */
300
301 /* limited v0 backwards compatibility: impose this valid random string
302 * alphabet limitation on v0 also retroactively even tho the internet
303 * draft did not require it. All widely used clients generate hex /
304 * base64 anyway.
305 */
306
307 #define VALID_STR_CHARS "/+0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"\
308 "abcdefghijklmnopqrstuvwxyz="
309
310 int hashcash_parse( const char* token, int* vers, int* bits, char* utct,
311 int utct_max, char* token_resource, int res_max,
312 char** ext, int ext_max )
313 {
314 char ver_arr[MAX_VER+1] = {0};
315 char bits_arr[3+1] = {0};
316 char *bits_str = bits_arr, *ver = ver_arr;
317 char *rnd = NULL, *cnt = NULL;
318 char *state = NULL ;
319 int ver_len = 0 , utct_len = 0 , res_len = 0 , bit_len = 0 , rnd_len = 0 , cnt_len = 0 ;
320
321 /* parse out the resource name component
322 * v1 format: ver:bits:utctime:resource:ext:rand:counter
323 * where utctime is [YYMMDD[hhmm[ss]]]
324 *
325 * v0 format: ver:utctime:resource:rand
326 *
327 * in v0 & v1 the resource may NOT include :s, if it needs to include
328 * :s some encoding such as URL encoding must be used
329 */
330
331 if ( ext != NULL ) { *ext = NULL; }
332 if ( !sstrtok( token, ":", &ver, MAX_VER, &ver_len, &state ) ) {
333 return 0;
334 }
335 *vers = atoi( ver ); if ( *vers < 0 ) { return 0; }
336 if ( *vers == 0 ) {
337 *bits = -1;
338 if ( !sstrtok( NULL, ":", &utct, utct_max, &utct_len, &state ) ||
339 !sstrtok( NULL, ":", &token_resource, res_max,&res_len,&state ) ||
340 !sstrtok( NULL, ":", &rnd, 0, &rnd_len, &state ) ) {
341 return 0;
342 }
343 } else if ( *vers == 1 ) {
344 if ( !sstrtok( NULL, ":", &bits_str, 3, &bit_len, &state ) ||
345 !sstrtok( NULL, ":", &utct, utct_max, &utct_len, &state ) ||
346 !sstrtok( NULL, ":", &token_resource, res_max,&res_len,&state ) ||
347 !sstrtok( NULL, ":", ext, 0, &ext_max, &state ) ||
348 !sstrtok( NULL, ":", &rnd, 0, &rnd_len, &state ) ||
349 !sstrtok( NULL, ":", &cnt, 0, &cnt_len, &state ) ) {
350 return 0;
351 }
352 *bits = atoi( bits_str ); if ( *bits < 0 ) { return 0; }
353 if ( strspn( cnt, VALID_STR_CHARS ) != cnt_len ) { return 0; }
354 }
355 if ( rnd == NULL || strspn( rnd, VALID_STR_CHARS ) != rnd_len ) { return 0; }
356 return 1;
357 }
358
359 unsigned hashcash_count( const char* token )
360 {
361 SHA1_ctx ctx;
362 byte target_digest[ SHA1_DIGEST_BYTES ] = {0};
363 byte token_digest[ SHA1_DIGEST_BYTES ] = {0};
364 char ver[MAX_VER+1] = {0};
365 int vers = 0 ;
366 char* first_colon = NULL;
367 char* second_colon = NULL;
368 int ver_len = 0 ;
369 int i = 0 ;
370 int last = 0 ;
371 int preimage_bits = 0 ;
372
373 first_colon = strchr( token, ':' );
374 if ( first_colon == NULL ) { return 0; } /* should really fail */
375 ver_len = (int)(first_colon - token);
376 if ( ver_len > MAX_VER ) { return 0; }
377 sstrncpy( ver, token, ver_len );
378 vers = atoi( ver );
379 if ( vers < 0 ) { return 0; }
380 if ( vers > 1 ) { return 0; } /* unsupported version number */
381 second_colon = strchr( first_colon+1, ':' );
382 if ( second_colon == NULL ) { return 0; } /* should really fail */
383
384 memset( target_digest, 0, SHA1_DIGEST_BYTES );
385
386 SHA1_Init( &ctx );
387 SHA1_Update( &ctx, token, strlen( token ) );
388 SHA1_Final( &ctx, token_digest );
389
390 for ( i = 0;
391 i < SHA1_DIGEST_BYTES && token_digest[ i ] == target_digest[ i ];
392 i++ ) {
393 }
394
395 last = i;
396 preimage_bits = 8 * i;
397
398 #define bit( n, c ) (((c) >> (7 - (n))) & 1)
399
400 for ( i = 0; i < 8; i++ )
401 {
402 if ( bit( i, token_digest[ last ] ) ==
403 bit( i, target_digest[ last ] ) ) {
404 preimage_bits++;
405 } else {
406 break;
407 }
408 }
409 return preimage_bits;
410 }
411
412 long hashcash_valid_for( time_t token_time, long validity_period,
413 long grace_period, time_t now_time )
414 {
415 long expiry_time = 0 ;
416
417 /* for ever -- return infinity */
418 if ( validity_period == 0 ) { return HASHCASH_VALID_FOREVER; }
419
420 /* future date in token */
421 if ( token_time > now_time + grace_period ) {
422 return HASHCASH_VALID_IN_FUTURE;
423 }
424
425 expiry_time = token_time + validity_period;
426 if ( expiry_time + grace_period > now_time ) {
427 /* valid return seconds left */
428 return expiry_time + grace_period - now_time;
429 }
430 return HASHCASH_EXPIRED; /* otherwise expired */
431 }
432
433 #define REGEXP_DIFF "(|)"
434 #define REGEXP_UNSUP "{}"
435 #define REGEXP_SAME "\\.?[]*+^$"
436
437 #define MAX_RE_ERR 256
438
439 int regexp_match( const char* str, const char* regexp,
440 void** compile, char** err )
441 {
442 #if defined( REGEXP_BSD )
443 char* q = NULL ;
444 const char *r = NULL ;
445 char* quoted_regexp = malloc( strlen( regexp ) * 2 + 3 );
446
447 *err = NULL;
448
449 if ( quoted_regexp == NULL ) { *err = "out of memory"; return 0; }
450
451 q = quoted_regexp;
452 r = regexp;
453
454 if ( *r != '^' ) { *q++ = '^'; }
455
456 for ( ; *r; *q++ = *r++ ) {
457 if ( *r == '\\' ) {
458 if ( strchr( REGEXP_SAME, *(r+1) ) ) {
459 *q++ = *r++; /* copy thru \\ unchanged */
460 } else {
461 r++; /* skip \c for any c other than \ */
462 }
463 } else if ( strchr( REGEXP_DIFF, *r ) ) {
464 *q++ = '\\';
465 } else if ( strchr( REGEXP_UNSUP, *r ) ) {
466 *err = "compiled with BSD regexp, {} not suppored";
467 free( quoted_regexp );
468 return 0;
469 }
470 }
471 if ( *(q-1) != '$' ) { *q++ = '$'; }
472 *q = '\0';
473 if ( ( *err = re_comp( quoted_regexp ) ) != NULL ) {
474 free( quoted_regexp ); return 0;
475 }
476 free( quoted_regexp );
477 return re_exec( str );
478 #elif defined( REGEXP_POSIX )
479 regex_t** comp = (regex_t**) compile;
480 int re_code = 0 ;
481 char* bound_regexp = NULL ;
482 int re_len = 0 , bre_len = 0 ;
483 static char re_err[ MAX_RE_ERR+1 ] = {0};
484 re_err[0] = '\0';
485 *err = NULL;
486
487 if ( *comp == NULL ) {
488 *comp = malloc( sizeof(regex_t) );
489 if ( *comp == NULL ) { *err = "out of memory"; return 0; }
490 bre_len = re_len = strlen(regexp);
491 if ( regexp[0] != '^' || regexp[re_len-1] != '$' ) {
492 bound_regexp = malloc( re_len+3 );
493 if ( regexp[0] != '^' ) {
494 bound_regexp[0] = '^';
495 sstrncpy( (bound_regexp+1), regexp, re_len );
496 bre_len++;
497 } else {
498 sstrncpy( bound_regexp, regexp, re_len );
499 }
500 if ( regexp[re_len-1] != '$' ) {
501 bound_regexp[bre_len] = '$';
502 bound_regexp[bre_len+1] = '\0';
503 }
504 } else {
505 bound_regexp = (char*)regexp;
506 }
507
508 if ( ( re_code = regcomp( *comp, bound_regexp,
509 REG_EXTENDED | REG_NOSUB ) ) != 0 ) {
510 regerror( re_code, *comp, re_err, MAX_RE_ERR );
511 *err = re_err;
512 if ( bound_regexp != regexp ) { free( bound_regexp ); }
513 return 0;
514 }
515 if ( bound_regexp != regexp ) { free( bound_regexp ); }
516 }
517 return regexec( *comp, str, 0, NULL, 0 ) == 0;
518 #else
519 *err = "regexps not supported on your platform, used -W wildcards";
520 return 0;
521 #endif
522 }
523
524 int hashcash_resource_match( int type, const char* token_res, const char* res,
525 void** compile, char** err )
526 {
527 switch ( type ) {
528 case TYPE_STR:
529 if ( strcmp( token_res, res ) != 0 ) { return 0; }
530 break;
531 case TYPE_WILD:
532 if ( !email_match( token_res, res ) ) { return 0; }
533 break;
534 case TYPE_REGEXP:
535 if ( !regexp_match( token_res, res, compile, err ) ) { return 0; }
536 break;
537 default:
538 return 0;
539 }
540 return 1;
541 }
542
543 int hashcash_check( const char* token, int case_flag, const char* resource,
544 void **compile, char** re_err, int type, time_t now_time,
545 long validity_period, long grace_period,
546 int required_bits, time_t* token_time ) {
547 time_t token_t = 0 ;
548 char token_utime[ MAX_UTC+1 ] = {0};
549 char token_res[ MAX_RES+1 ] = {0};
550 int bits = 0, claimed_bits = 0, vers = 0;
551
552 if ( token_time == NULL ) { token_time = &token_t; }
553
554 if ( !hashcash_parse( token, &vers, &claimed_bits, token_utime,
555 MAX_UTC, token_res, MAX_RES, NULL, 0 ) ) {
556 return HASHCASH_INVALID;
557 }
558
559 if ( vers < 0 || vers > 1 ) {
560 return HASHCASH_UNSUPPORTED_VERSION;
561 }
562
563 *token_time = hashcash_from_utctimestr( token_utime, 1 );
564 if ( *token_time == -1 ) {
565 return HASHCASH_INVALID;
566 }
567
568 if ( !case_flag ) {
569 stolower( token_res );
570 }
571
572 if ( resource &&
573 !hashcash_resource_match( type, token_res,
574 resource, compile, re_err ) ) {
575 if ( *re_err != NULL ) {
576 return HASHCASH_REGEXP_ERROR;
577 } else {
578 return HASHCASH_WRONG_RESOURCE;
579 }
580 }
581 bits = hashcash_count( token );
582 if ( vers == 1 ) {
583 bits = ( bits < claimed_bits ) ? 0 : claimed_bits;
584 }
585
586 if ( bits < required_bits ) {
587 return HASHCASH_INSUFFICIENT_BITS;
588 }
589 return hashcash_valid_for( *token_time, validity_period,
590 grace_period, now_time );
591 }
592
593 double hashcash_estimate_time( int b )
594 {
595 return hashcash_expected_tries( b ) / (double)hashcash_per_sec();
596 }
597
598 double hashcash_expected_tries( int b )
599 {
600 double expected_tests = 1;
601 #define CHUNK ( sizeof( unsigned long )*8 - 1 )
602 for ( ; b > CHUNK; b -= CHUNK ) {
603 expected_tests *= ((unsigned long)1) << CHUNK;
604 }
605 expected_tests *= ((unsigned long)1) << b;
606 return expected_tests;
607 }
608
609 void hashcash_free( void* ptr )
610 {
611 if ( ptr != NULL ) { free( ptr ); }
612 }