rhash.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /* rhash.c - implementation of LibRHash library calls
  2. *
  3. * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a
  6. * copy of this software and associated documentation files (the "Software"),
  7. * to deal in the Software without restriction, including without limitation
  8. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. * and/or sell copies of the Software, and to permit persons to whom the
  10. * Software is furnished to do so.
  11. *
  12. * This program is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  14. * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
  15. */
  16. /* macros for large file support, must be defined before any include file */
  17. #define _LARGEFILE64_SOURCE
  18. #define _FILE_OFFSET_BITS 64
  19. #include <string.h> /* memset() */
  20. #include <stdlib.h> /* free() */
  21. #include <stddef.h> /* ptrdiff_t */
  22. #include <stdio.h>
  23. #include <assert.h>
  24. #include <errno.h>
  25. /* modifier for Windows DLL */
  26. #if defined(_WIN32) && defined(RHASH_EXPORTS)
  27. # define RHASH_API __declspec(dllexport)
  28. #endif
  29. #include "byte_order.h"
  30. #include "algorithms.h"
  31. #include "util.h"
  32. #include "hex.h"
  33. #include "rhash.h" /* RHash library interface */
  34. #define STATE_ACTIVE 0xb01dbabe
  35. #define STATE_STOPED 0xdeadbeef
  36. #define STATE_DELETED 0xdecea5ed
  37. #define RCTX_AUTO_FINAL 0x1
  38. #define RCTX_FINALIZED 0x2
  39. #define RCTX_FINALIZED_MASK (RCTX_AUTO_FINAL | RCTX_FINALIZED)
  40. #define RHPR_FORMAT (RHPR_RAW | RHPR_HEX | RHPR_BASE32 | RHPR_BASE64)
  41. #define RHPR_MODIFIER (RHPR_UPPERCASE | RHPR_REVERSE)
  42. /**
  43. * Initialize static data of rhash algorithms
  44. */
  45. void rhash_library_init(void)
  46. {
  47. rhash_init_algorithms(RHASH_ALL_HASHES);
  48. #ifdef USE_OPENSSL
  49. rhash_plug_openssl();
  50. #endif
  51. }
  52. /**
  53. * Returns the number of supported hash algorithms.
  54. *
  55. * @return the number of supported hash functions
  56. */
  57. int RHASH_API rhash_count(void)
  58. {
  59. return rhash_info_size;
  60. }
  61. /* Lo-level rhash library functions */
  62. /**
  63. * Allocate and initialize RHash context for calculating hash(es).
  64. * After initializing rhash_update()/rhash_final() functions should be used.
  65. * Then the context must be freed by calling rhash_free().
  66. *
  67. * @param hash_id union of bit flags, containing ids of hashes to calculate.
  68. * @return initialized rhash context, NULL on error and errno is set
  69. */
  70. RHASH_API rhash rhash_init(unsigned hash_id)
  71. {
  72. unsigned tail_bit_index; /* index of hash_id trailing bit */
  73. unsigned num = 0; /* number of hashes to compute */
  74. rhash_context_ext *rctx = NULL; /* allocated rhash context */
  75. size_t hash_size_sum = 0; /* size of hash contexts to store in rctx */
  76. unsigned i, bit_index, id;
  77. struct rhash_hash_info* info;
  78. size_t aligned_size;
  79. char* phash_ctx;
  80. hash_id &= RHASH_ALL_HASHES;
  81. if (hash_id == 0) {
  82. errno = EINVAL;
  83. return NULL;
  84. }
  85. tail_bit_index = rhash_ctz(hash_id); /* get trailing bit index */
  86. assert(tail_bit_index < RHASH_HASH_COUNT);
  87. id = 1 << tail_bit_index;
  88. if (hash_id == id) {
  89. /* handle the most common case of only one hash */
  90. num = 1;
  91. info = &rhash_info_table[tail_bit_index];
  92. hash_size_sum = info->context_size;
  93. } else {
  94. /* another case: hash_id contains several hashes */
  95. for (bit_index = tail_bit_index; id <= hash_id; bit_index++, id = id << 1) {
  96. assert(id != 0);
  97. assert(bit_index < RHASH_HASH_COUNT);
  98. info = &rhash_info_table[bit_index];
  99. if (hash_id & id) {
  100. /* align sizes by 8 bytes */
  101. aligned_size = (info->context_size + 7) & ~7;
  102. hash_size_sum += aligned_size;
  103. num++;
  104. }
  105. }
  106. assert(num > 1);
  107. }
  108. /* align the size of the rhash context common part */
  109. aligned_size = (offsetof(rhash_context_ext, vector[num]) + 7) & ~7;
  110. assert(aligned_size >= sizeof(rhash_context_ext));
  111. /* allocate rhash context with enough memory to store contexts of all used hashes */
  112. rctx = (rhash_context_ext*)malloc(aligned_size + hash_size_sum);
  113. if (rctx == NULL) return NULL;
  114. /* initialize common fields of the rhash context */
  115. memset(rctx, 0, sizeof(rhash_context_ext));
  116. rctx->rc.hash_id = hash_id;
  117. rctx->flags = RCTX_AUTO_FINAL; /* turn on auto-final by default */
  118. rctx->state = STATE_ACTIVE;
  119. rctx->hash_vector_size = num;
  120. /* aligned hash contexts follows rctx->vector[num] in the same memory block */
  121. phash_ctx = (char*)rctx + aligned_size;
  122. assert(phash_ctx >= (char*)&rctx->vector[num]);
  123. /* initialize context for every hash in a loop */
  124. for (bit_index = tail_bit_index, id = 1 << tail_bit_index, i = 0;
  125. id <= hash_id; bit_index++, id = id << 1)
  126. {
  127. /* check if a hash function with given id shall be included into rctx */
  128. if ((hash_id & id) != 0) {
  129. info = &rhash_info_table[bit_index];
  130. assert(info->context_size > 0);
  131. assert(((phash_ctx - (char*)0) & 7) == 0); /* hash context is aligned */
  132. assert(info->init != NULL);
  133. rctx->vector[i].hash_info = info;
  134. rctx->vector[i].context = phash_ctx;
  135. #if 0
  136. /* BTIH initialization is complex, save pointer for later */
  137. if ((id & RHASH_BTIH) != 0) rctx->bt_ctx = phash_ctx;
  138. #endif
  139. phash_ctx += (info->context_size + 7) & ~7;
  140. /* initialize the i-th hash context */
  141. info->init(rctx->vector[i].context);
  142. i++;
  143. }
  144. }
  145. return &rctx->rc; /* return allocated and initialized rhash context */
  146. }
  147. /**
  148. * Free RHash context memory.
  149. *
  150. * @param ctx the context to free.
  151. */
  152. void rhash_free(rhash ctx)
  153. {
  154. rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
  155. unsigned i;
  156. if (ctx == 0) return;
  157. assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
  158. ectx->state = STATE_DELETED; /* mark memory block as being removed */
  159. /* clean the hash functions, which require additional clean up */
  160. for (i = 0; i < ectx->hash_vector_size; i++) {
  161. struct rhash_hash_info* info = ectx->vector[i].hash_info;
  162. if (info->cleanup != 0) {
  163. info->cleanup(ectx->vector[i].context);
  164. }
  165. }
  166. free(ectx);
  167. }
  168. /**
  169. * Re-initialize RHash context to reuse it.
  170. * Useful to speed up processing of many small messages.
  171. *
  172. * @param ctx context to reinitialize
  173. */
  174. RHASH_API void rhash_reset(rhash ctx)
  175. {
  176. rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
  177. unsigned i;
  178. assert(ectx->hash_vector_size > 0);
  179. assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
  180. ectx->state = STATE_ACTIVE; /* re-activate the structure */
  181. /* re-initialize every hash in a loop */
  182. for (i = 0; i < ectx->hash_vector_size; i++) {
  183. struct rhash_hash_info* info = ectx->vector[i].hash_info;
  184. if (info->cleanup != 0) {
  185. info->cleanup(ectx->vector[i].context);
  186. }
  187. assert(info->init != NULL);
  188. info->init(ectx->vector[i].context);
  189. }
  190. ectx->flags &= ~RCTX_FINALIZED; /* clear finalized state */
  191. }
  192. /**
  193. * Calculate hashes of message.
  194. * Can be called repeatedly with chunks of the message to be hashed.
  195. *
  196. * @param ctx the rhash context
  197. * @param message message chunk
  198. * @param length length of the message chunk
  199. * @return 0 on success; On fail return -1 and set errno
  200. */
  201. RHASH_API int rhash_update(rhash ctx, const void* message, size_t length)
  202. {
  203. rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
  204. unsigned i;
  205. assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
  206. if (ectx->state != STATE_ACTIVE) return 0; /* do nothing if canceled */
  207. ctx->msg_size += length;
  208. /* call update method for every algorithm */
  209. for (i = 0; i < ectx->hash_vector_size; i++) {
  210. struct rhash_hash_info* info = ectx->vector[i].hash_info;
  211. assert(info->update != 0);
  212. info->update(ectx->vector[i].context, message, length);
  213. }
  214. return 0; /* no error processing at the moment */
  215. }
  216. /**
  217. * Finalize hash calculation and optionally store the first hash.
  218. *
  219. * @param ctx the rhash context
  220. * @param first_result optional buffer to store a calculated hash with the lowest available id
  221. * @return 0 on success; On fail return -1 and set errno
  222. */
  223. RHASH_API int rhash_final(rhash ctx, unsigned char* first_result)
  224. {
  225. unsigned i = 0;
  226. unsigned char buffer[130];
  227. unsigned char* out = (first_result ? first_result : buffer);
  228. rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
  229. assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
  230. /* skip final call if already finalized and auto-final is on */
  231. if ((ectx->flags & RCTX_FINALIZED_MASK) ==
  232. (RCTX_AUTO_FINAL | RCTX_FINALIZED)) return 0;
  233. /* call final method for every algorithm */
  234. for (i = 0; i < ectx->hash_vector_size; i++) {
  235. struct rhash_hash_info* info = ectx->vector[i].hash_info;
  236. assert(info->final != 0);
  237. assert(info->info->digest_size < sizeof(buffer));
  238. info->final(ectx->vector[i].context, out);
  239. out = buffer;
  240. }
  241. ectx->flags |= RCTX_FINALIZED;
  242. return 0; /* no error processing at the moment */
  243. }
  244. /**
  245. * Store digest for given hash_id.
  246. * If hash_id is zero, function stores digest for a hash with the lowest id found in the context.
  247. * For nonzero hash_id the context must contain it, otherwise function silently does nothing.
  248. *
  249. * @param ctx rhash context
  250. * @param hash_id id of hash to retrieve or zero for hash with the lowest available id
  251. * @param result buffer to put the hash into
  252. */
  253. static void rhash_put_digest(rhash ctx, unsigned hash_id, unsigned char* result)
  254. {
  255. rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
  256. unsigned i;
  257. rhash_vector_item *item;
  258. struct rhash_hash_info* info;
  259. unsigned char* digest;
  260. assert(ectx);
  261. assert(ectx->hash_vector_size > 0 && ectx->hash_vector_size <= RHASH_HASH_COUNT);
  262. /* finalize context if not yet finalized and auto-final is on */
  263. if ((ectx->flags & RCTX_FINALIZED_MASK) == RCTX_AUTO_FINAL) {
  264. rhash_final(ctx, NULL);
  265. }
  266. if (hash_id == 0) {
  267. item = &ectx->vector[0]; /* get the first hash */
  268. info = item->hash_info;
  269. } else {
  270. for (i = 0;; i++) {
  271. if (i >= ectx->hash_vector_size) {
  272. return; /* hash_id not found, do nothing */
  273. }
  274. item = &ectx->vector[i];
  275. info = item->hash_info;
  276. if (info->info->hash_id == hash_id) break;
  277. }
  278. }
  279. digest = ((unsigned char*)item->context + info->digest_diff);
  280. if (info->info->flags & F_SWAP32) {
  281. assert((info->info->digest_size & 3) == 0);
  282. /* NB: the next call is correct only for multiple of 4 byte size */
  283. rhash_swap_copy_str_to_u32(result, 0, digest, info->info->digest_size);
  284. } else if (info->info->flags & F_SWAP64) {
  285. rhash_swap_copy_u64_to_str(result, digest, info->info->digest_size);
  286. } else {
  287. memcpy(result, digest, info->info->digest_size);
  288. }
  289. }
  290. /**
  291. * Set the callback function to be called from the
  292. * rhash_file() and rhash_file_update() functions
  293. * on processing every file block. The file block
  294. * size is set internally by rhash and now is 8 KiB.
  295. *
  296. * @param ctx rhash context
  297. * @param callback pointer to the callback function
  298. * @param callback_data pointer to data passed to the callback
  299. */
  300. RHASH_API void rhash_set_callback(rhash ctx, rhash_callback_t callback, void* callback_data)
  301. {
  302. ((rhash_context_ext*)ctx)->callback = callback;
  303. ((rhash_context_ext*)ctx)->callback_data = callback_data;
  304. }
  305. /* hi-level message hashing interface */
  306. /**
  307. * Compute a hash of the given message.
  308. *
  309. * @param hash_id id of hash sum to compute
  310. * @param message the message to process
  311. * @param length message length
  312. * @param result buffer to receive binary hash string
  313. * @return 0 on success, -1 on error
  314. */
  315. RHASH_API int rhash_msg(unsigned hash_id, const void* message, size_t length, unsigned char* result)
  316. {
  317. rhash ctx;
  318. hash_id &= RHASH_ALL_HASHES;
  319. ctx = rhash_init(hash_id);
  320. if (ctx == NULL) return -1;
  321. rhash_update(ctx, message, length);
  322. rhash_final(ctx, result);
  323. rhash_free(ctx);
  324. return 0;
  325. }
  326. /**
  327. * Hash a file or stream. Multiple hashes can be computed.
  328. * First, inintialize ctx parameter with rhash_init() before calling
  329. * rhash_file_update(). Then use rhash_final() and rhash_print()
  330. * to retrive hash values. Finaly call rhash_free() on ctx
  331. * to free allocated memory or call rhash_reset() to reuse ctx.
  332. *
  333. * @param ctx rhash context
  334. * @param fd descriptor of the file to hash
  335. * @return 0 on success, -1 on error and errno is set
  336. */
  337. RHASH_API int rhash_file_update(rhash ctx, FILE* fd)
  338. {
  339. rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
  340. const size_t block_size = 8192;
  341. unsigned char *buffer, *pmem;
  342. size_t length = 0, align8;
  343. int res = 0;
  344. if (ectx->state != STATE_ACTIVE) return 0; /* do nothing if canceled */
  345. if (ctx == NULL) {
  346. errno = EINVAL;
  347. return -1;
  348. }
  349. pmem = (unsigned char*)malloc(block_size + 8);
  350. if (!pmem) return -1; /* errno is set to ENOMEM according to UNIX 98 */
  351. align8 = ((unsigned char*)0 - pmem) & 7;
  352. buffer = pmem + align8;
  353. while (!feof(fd)) {
  354. /* stop if canceled */
  355. if (ectx->state != STATE_ACTIVE) break;
  356. length = fread(buffer, 1, block_size, fd);
  357. if (ferror(fd)) {
  358. res = -1; /* note: errno contains error code */
  359. break;
  360. } else if (length) {
  361. rhash_update(ctx, buffer, length);
  362. if (ectx->callback) {
  363. ((rhash_callback_t)ectx->callback)(ectx->callback_data, ectx->rc.msg_size);
  364. }
  365. }
  366. }
  367. free(buffer);
  368. return res;
  369. }
  370. /**
  371. * Compute a single hash for given file.
  372. *
  373. * @param hash_id id of hash sum to compute
  374. * @param filepath path to the file to hash
  375. * @param result buffer to receive hash value with the lowest requested id
  376. * @return 0 on success, -1 on error and errno is set
  377. */
  378. RHASH_API int rhash_file(unsigned hash_id, const char* filepath, unsigned char* result)
  379. {
  380. FILE* fd;
  381. rhash ctx;
  382. int res;
  383. hash_id &= RHASH_ALL_HASHES;
  384. if (hash_id == 0) {
  385. errno = EINVAL;
  386. return -1;
  387. }
  388. if ((fd = fopen(filepath, "rb")) == NULL) return -1;
  389. if ((ctx = rhash_init(hash_id)) == NULL) return -1;
  390. res = rhash_file_update(ctx, fd); /* hash the file */
  391. fclose(fd);
  392. rhash_final(ctx, result);
  393. rhash_free(ctx);
  394. return res;
  395. }
  396. #ifdef _WIN32 /* windows only function */
  397. #include <share.h>
  398. /**
  399. * Compute a single hash for given file.
  400. *
  401. * @param hash_id id of hash sum to compute
  402. * @param filepath path to the file to hash
  403. * @param result buffer to receive hash value with the lowest requested id
  404. * @return 0 on success, -1 on error, -1 on error and errno is set
  405. */
  406. RHASH_API int rhash_wfile(unsigned hash_id, const wchar_t* filepath, unsigned char* result)
  407. {
  408. FILE* fd;
  409. rhash ctx;
  410. int res;
  411. hash_id &= RHASH_ALL_HASHES;
  412. if (hash_id == 0) {
  413. errno = EINVAL;
  414. return -1;
  415. }
  416. if ((fd = _wfsopen(filepath, L"rb", _SH_DENYWR)) == NULL) return -1;
  417. if ((ctx = rhash_init(hash_id)) == NULL) return -1;
  418. res = rhash_file_update(ctx, fd); /* hash the file */
  419. fclose(fd);
  420. rhash_final(ctx, result);
  421. rhash_free(ctx);
  422. return res;
  423. }
  424. #endif
  425. /* RHash information functions */
  426. /**
  427. * Returns information about a hash function by its hash_id.
  428. *
  429. * @param hash_id the id of hash algorithm
  430. * @return pointer to the rhash_info structure containing the information
  431. */
  432. const rhash_info* rhash_info_by_id(unsigned hash_id)
  433. {
  434. hash_id &= RHASH_ALL_HASHES;
  435. /* check that only one bit is set */
  436. if (hash_id != (hash_id & -(int)hash_id)) return NULL;
  437. /* note: alternative condition is (hash_id == 0 || (hash_id & (hash_id - 1)) != 0) */
  438. return rhash_info_table[rhash_ctz(hash_id)].info;
  439. }
  440. #if 0
  441. /**
  442. * Detect default digest output format for given hash algorithm.
  443. *
  444. * @param hash_id the id of hash algorithm
  445. * @return 1 for base32 format, 0 for hexadecimal
  446. */
  447. RHASH_API int rhash_is_base32(unsigned hash_id)
  448. {
  449. /* fast method is just to test a bit-mask */
  450. return ((hash_id & (RHASH_TTH | RHASH_AICH)) != 0);
  451. }
  452. #endif
  453. /**
  454. * Returns size of binary digest for given hash algorithm.
  455. *
  456. * @param hash_id the id of hash algorithm
  457. * @return digest size in bytes
  458. */
  459. RHASH_API int rhash_get_digest_size(unsigned hash_id)
  460. {
  461. hash_id &= RHASH_ALL_HASHES;
  462. if (hash_id == 0 || (hash_id & (hash_id - 1)) != 0) return -1;
  463. return (int)rhash_info_table[rhash_ctz(hash_id)].info->digest_size;
  464. }
  465. /**
  466. * Returns length of digest hash string in default output format.
  467. *
  468. * @param hash_id the id of hash algorithm
  469. * @return the length of hash string
  470. */
  471. RHASH_API int rhash_get_hash_length(unsigned hash_id)
  472. {
  473. const rhash_info* info = rhash_info_by_id(hash_id);
  474. return (int)(info ? (info->flags & F_BS32 ?
  475. BASE32_LENGTH(info->digest_size) : info->digest_size * 2) : 0);
  476. }
  477. /**
  478. * Returns a name of given hash algorithm.
  479. *
  480. * @param hash_id the id of hash algorithm
  481. * @return algorithm name
  482. */
  483. RHASH_API const char* rhash_get_name(unsigned hash_id)
  484. {
  485. const rhash_info* info = rhash_info_by_id(hash_id);
  486. return (info ? info->name : 0);
  487. }
  488. /**
  489. * Returns a name part of magnet urn of the given hash algorithm.
  490. * Such magnet_name is used to generate a magnet link of the form
  491. * urn:&lt;magnet_name&gt;=&lt;hash_value&gt;.
  492. *
  493. * @param hash_id the id of hash algorithm
  494. * @return name
  495. */
  496. RHASH_API const char* rhash_get_magnet_name(unsigned hash_id)
  497. {
  498. const rhash_info* info = rhash_info_by_id(hash_id);
  499. return (info ? info->magnet_name : 0);
  500. }
  501. #if 0
  502. static size_t rhash_get_magnet_url_size(const char* filepath,
  503. rhash context, unsigned hash_mask, int flags)
  504. {
  505. size_t size = 0; /* count terminating '\0' */
  506. unsigned bit, hash = context->hash_id & hash_mask;
  507. /* RHPR_NO_MAGNET, RHPR_FILESIZE */
  508. if ((flags & RHPR_NO_MAGNET) == 0) {
  509. size += 8;
  510. }
  511. if ((flags & RHPR_FILESIZE) != 0) {
  512. uint64_t num = context->msg_size;
  513. size += 4;
  514. if (num == 0) size++;
  515. else {
  516. for (; num; num /= 10, size++);
  517. }
  518. }
  519. if (filepath) {
  520. size += 4 + rhash_urlencode(NULL, filepath);
  521. }
  522. /* loop through hash values */
  523. for (bit = hash & -(int)hash; bit <= hash; bit <<= 1) {
  524. const char* name;
  525. if ((bit & hash) == 0) continue;
  526. if ((name = rhash_get_magnet_name(bit)) == 0) continue;
  527. size += (7 + 2) + strlen(name);
  528. size += rhash_print(NULL, context, bit,
  529. (bit & (RHASH_SHA1 | RHASH_BTIH) ? RHPR_BASE32 : 0));
  530. }
  531. return size;
  532. }
  533. /**
  534. * Print magnet link with given filepath and calculated hash sums into the
  535. * output buffer. The hash_mask can limit which hash values will be printed.
  536. * The function returns the size of the required buffer.
  537. * If output is NULL the .
  538. *
  539. * @param output a string buffer to receive the magnet link or NULL
  540. * @param filepath the file path to be printed or NULL
  541. * @param context algorithms state
  542. * @param hash_mask bit mask of the hash sums to add to the link
  543. * @param flags can be combination of bits RHPR_UPPERCASE, RHPR_NO_MAGNET,
  544. * RHPR_FILESIZE
  545. * @return number of written characters, including terminating '\0' on success, 0 on fail
  546. */
  547. RHASH_API size_t rhash_print_magnet(char* output, const char* filepath,
  548. rhash context, unsigned hash_mask, int flags)
  549. {
  550. int i;
  551. const char* begin = output;
  552. if (output == NULL) return rhash_get_magnet_url_size(
  553. filepath, context, hash_mask, flags);
  554. /* RHPR_NO_MAGNET, RHPR_FILESIZE */
  555. if ((flags & RHPR_NO_MAGNET) == 0) {
  556. strcpy(output, "magnet:?");
  557. output += 8;
  558. }
  559. if ((flags & RHPR_FILESIZE) != 0) {
  560. strcpy(output, "xl=");
  561. output += 3;
  562. output += rhash_sprintI64(output, context->msg_size);
  563. *(output++) = '&';
  564. }
  565. if (filepath) {
  566. strcpy(output, "dn=");
  567. output += 3;
  568. output += rhash_urlencode(output, filepath);
  569. *(output++) = '&';
  570. }
  571. flags &= RHPR_UPPERCASE;
  572. for (i = 0; i < 2; i++) {
  573. unsigned bit;
  574. unsigned hash = context->hash_id & hash_mask;
  575. hash = (i == 0 ? hash & (RHASH_ED2K | RHASH_AICH)
  576. : hash & ~(RHASH_ED2K | RHASH_AICH));
  577. if (!hash) continue;
  578. /* loop through hash values */
  579. for (bit = hash & -(int)hash; bit <= hash; bit <<= 1) {
  580. const char* name;
  581. if ((bit & hash) == 0) continue;
  582. if (!(name = rhash_get_magnet_name(bit))) continue;
  583. strcpy(output, "xt=urn:");
  584. output += 7;
  585. strcpy(output, name);
  586. output += strlen(name);
  587. *(output++) = ':';
  588. output += rhash_print(output, context, bit,
  589. (bit & (RHASH_SHA1 | RHASH_BTIH) ? flags | RHPR_BASE32 : flags));
  590. *(output++) = '&';
  591. }
  592. }
  593. output[-1] = '\0'; /* terminate the line */
  594. return (output - begin);
  595. }
  596. /* hash sum output */
  597. /**
  598. * Print a text presentation of a given hash sum to the specified buffer,
  599. *
  600. * @param output a buffer to print the hash to
  601. * @param bytes a hash sum to print
  602. * @param size a size of hash sum in bytes
  603. * @param flags a bit-mask controlling how to format the hash sum,
  604. * can be a mix of the flags: RHPR_RAW, RHPR_HEX, RHPR_BASE32,
  605. * RHPR_BASE64, RHPR_UPPERCASE, RHPR_REVERSE
  606. * @return the number of written characters
  607. */
  608. size_t rhash_print_bytes(char* output, const unsigned char* bytes,
  609. size_t size, int flags)
  610. {
  611. size_t str_len;
  612. int upper_case = (flags & RHPR_UPPERCASE);
  613. int format = (flags & ~RHPR_MODIFIER);
  614. switch (format) {
  615. case RHPR_HEX:
  616. str_len = size * 2;
  617. rhash_byte_to_hex(output, bytes, (unsigned)size, upper_case);
  618. break;
  619. case RHPR_BASE32:
  620. str_len = BASE32_LENGTH(size);
  621. rhash_byte_to_base32(output, bytes, (unsigned)size, upper_case);
  622. break;
  623. case RHPR_BASE64:
  624. str_len = BASE64_LENGTH(size);
  625. rhash_byte_to_base64(output, bytes, (unsigned)size);
  626. break;
  627. default:
  628. str_len = size;
  629. memcpy(output, bytes, size);
  630. break;
  631. }
  632. return str_len;
  633. }
  634. /**
  635. * Print text presentation of a hash sum with given hash_id to the specified
  636. * output buffer. If the hash_id is zero, then print the hash sum with
  637. * the lowest id stored in the hash context.
  638. * The function call fails if the context doesn't include a hash with the
  639. * given hash_id.
  640. *
  641. * @param output a buffer to print the hash to
  642. * @param context algorithms state
  643. * @param hash_id id of the hash sum to print or 0 to print the first hash
  644. * saved in the context.
  645. * @param flags a bitmask controlling how to print the hash. Can contain flags
  646. * RHPR_UPPERCASE, RHPR_HEX, RHPR_BASE32, RHPR_BASE64, etc.
  647. * @return the number of written characters on success or 0 on fail
  648. */
  649. size_t RHASH_API rhash_print(char* output, rhash context, unsigned hash_id, int flags)
  650. {
  651. const rhash_info* info;
  652. unsigned char digest[80];
  653. size_t digest_size;
  654. info = (hash_id != 0 ? rhash_info_by_id(hash_id) :
  655. ((rhash_context_ext*)context)->vector[0].hash_info->info);
  656. if (info == NULL) return 0;
  657. digest_size = info->digest_size;
  658. assert(digest_size <= 64);
  659. flags &= (RHPR_FORMAT | RHPR_MODIFIER);
  660. if ((flags & RHPR_FORMAT) == 0) {
  661. /* use default format if not specified by flags */
  662. flags |= (info->flags & RHASH_INFO_BASE32 ? RHPR_BASE32 : RHPR_HEX);
  663. }
  664. if (output == NULL) {
  665. switch (flags & RHPR_FORMAT) {
  666. case RHPR_HEX:
  667. return (digest_size * 2);
  668. case RHPR_BASE32:
  669. return BASE32_LENGTH(digest_size);
  670. case RHPR_BASE64:
  671. return BASE64_LENGTH(digest_size);
  672. default:
  673. return digest_size;
  674. }
  675. }
  676. /* note: use info->hash_id, cause hash_id can be 0 */
  677. rhash_put_digest(context, info->hash_id, digest);
  678. if ((flags & ~RHPR_UPPERCASE) == (RHPR_REVERSE | RHPR_HEX)) {
  679. /* reverse the digest */
  680. unsigned char *p = digest, *r = digest + digest_size - 1;
  681. char tmp;
  682. for (; p < r; p++, r--) {
  683. tmp = *p;
  684. *p = *r;
  685. *r = tmp;
  686. }
  687. }
  688. return rhash_print_bytes(output, digest, digest_size, flags);
  689. }
  690. #if defined(_WIN32) && defined(RHASH_EXPORTS)
  691. #include <windows.h>
  692. BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved);
  693. BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved)
  694. {
  695. (void)hModule;
  696. (void)reserved;
  697. switch (reason) {
  698. case DLL_PROCESS_ATTACH:
  699. rhash_library_init();
  700. break;
  701. case DLL_PROCESS_DETACH:
  702. /*rhash_library_free();*/
  703. case DLL_THREAD_ATTACH:
  704. case DLL_THREAD_DETACH:
  705. break;
  706. }
  707. return TRUE;
  708. }
  709. #endif
  710. #define PVOID2UPTR(p) ((rhash_uptr_t)((char*)p - 0))
  711. /**
  712. * Process a rhash message.
  713. *
  714. * @param msg_id message identifier
  715. * @param dst message destination (can be NULL for generic messages)
  716. * @param ldata data depending on message
  717. * @param rdata data depending on message
  718. * @return message-specific data
  719. */
  720. RHASH_API rhash_uptr_t rhash_transmit(unsigned msg_id, void* dst, rhash_uptr_t ldata, rhash_uptr_t rdata)
  721. {
  722. /* for messages working with rhash context */
  723. rhash_context_ext* const ctx = (rhash_context_ext*)dst;
  724. switch (msg_id) {
  725. case RMSG_GET_CONTEXT:
  726. {
  727. unsigned i;
  728. for (i = 0; i < ctx->hash_vector_size; i++) {
  729. struct rhash_hash_info* info = ctx->vector[i].hash_info;
  730. if (info->info->hash_id == (unsigned)ldata)
  731. return PVOID2UPTR(ctx->vector[i].context);
  732. }
  733. return (rhash_uptr_t)0;
  734. }
  735. case RMSG_CANCEL:
  736. /* mark rhash context as canceled, in a multithreaded program */
  737. atomic_compare_and_swap(&ctx->state, STATE_ACTIVE, STATE_STOPED);
  738. return 0;
  739. case RMSG_IS_CANCELED:
  740. return (ctx->state == STATE_STOPED);
  741. case RMSG_GET_FINALIZED:
  742. return ((ctx->flags & RCTX_FINALIZED) != 0);
  743. case RMSG_SET_AUTOFINAL:
  744. ctx->flags &= ~RCTX_AUTO_FINAL;
  745. if (ldata) ctx->flags |= RCTX_AUTO_FINAL;
  746. break;
  747. /* OpenSSL related messages */
  748. #ifdef USE_OPENSSL
  749. case RMSG_SET_OPENSSL_MASK:
  750. rhash_openssl_hash_mask = (unsigned)ldata;
  751. break;
  752. case RMSG_GET_OPENSSL_MASK:
  753. return rhash_openssl_hash_mask;
  754. #endif
  755. default:
  756. return RHASH_ERROR; /* unknown message */
  757. }
  758. return 0;
  759. }
  760. #endif