File Coverage

_aich.c
Criterion Covered Total %
statement 32 137 23.3
branch 11 122 9.0
condition n/a
subroutine n/a
pod n/a
total 43 259 16.6


line stmt bran cond sub pod time code
1             /* aich.c - an implementation of EMule AICH Algorithm.
2             * Description: http://www.amule.org/wiki/index.php/AICH.
3             *
4             * Copyright (c) 2008, Aleksey Kravchenko
5             *
6             * Permission to use, copy, modify, and/or distribute this software for any
7             * purpose with or without fee is hereby granted.
8             *
9             * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10             * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11             * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12             * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13             * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14             * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15             * PERFORMANCE OF THIS SOFTWARE.
16             *
17             * The AICH Algorithm:
18             *
19             * Each ed2k chunk (9728000 bytes) is divided into 53 parts (52x 180KB and
20             * 1x 140KB) and each of these parts are hashed using the SHA1 algorithm.
21             * Each of these hashes is called a Block Hash. By combining pairs of Block
22             * Hashes (i.e. each part with the part next to it) algorithm will get a whole
23             * tree of hashes (this tree which is therefore a hashset made of all of the
24             * other Block Hashes is called the AICH Hashset). Each hash which is neither
25             * a Block Hash nor the Root Hash, is a Verifying Hash. The hash at the top
26             * level is the Root Hash and it is supposed to be provided by the ed2k link
27             * when releasing.
28             */
29              
30             #include
31             #include
32             #include
33             #include "byte_order.h"
34             #include "algorithms.h"
35             #include "aich.h"
36              
37             #define ED2K_CHUNK_SIZE 9728000
38             #define FULL_BLOCK_SIZE 184320
39             #define LAST_BLOCK_SIZE 143360
40             #define BLOCKS_PER_CHUNK 53
41              
42             /*
43             * The Algorithm could be a little faster if it knows a
44             * hashed message size beforehand. This would allow
45             * to build balanced tree while hashing the message.
46             *
47             * But this AICH implementation works with unknown
48             * message size like other well-known hash algorithms
49             * (it was fun to write a such one).
50             * So, it just stores sha1 hashes and builds balanced tree
51             * only on the last step, when the full message processed
52             * and its size is already known.
53             */
54              
55             #ifdef USE_OPENSSL
56             #define SHA1_INIT(ctx) ((pinit_t)ctx->sha_init)(&ctx->sha1_context)
57             #define SHA1_UPDATE(ctx, msg, size) ((pupdate_t)ctx->sha_update)(&ctx->sha1_context, (msg), (size))
58             #define SHA1_FINAL(ctx, result) ((pfinal_t)ctx->sha_final)(&ctx->sha1_context, (result))
59             #else
60             #define SHA1_INIT(ctx) rhash_sha1_init(&ctx->sha1_context)
61             #define SHA1_UPDATE(ctx, msg, size) rhash_sha1_update(&ctx->sha1_context, (msg), (size))
62             #define SHA1_FINAL(ctx, result) rhash_sha1_final(&ctx->sha1_context, (result))
63             #endif
64              
65             /**
66             * Initialize algorithm context before calculaing hash.
67             *
68             * @param ctx context to initialize
69             */
70 2           void rhash_aich_init(aich_ctx* ctx)
71             {
72 2           memset(ctx, 0, sizeof(aich_ctx));
73              
74             #ifdef USE_OPENSSL
75             {
76             rhash_hash_info* sha1_info = &rhash_info_table[3];
77             assert(sha1_info->info->hash_id == RHASH_SHA1);
78             assert(sha1_info->context_size <= (sizeof(sha1_ctx) + sizeof(unsigned long)));
79             ctx->sha_init = sha1_info->init;
80             ctx->sha_update = sha1_info->update;
81             ctx->sha_final = sha1_info->final;
82             }
83             #endif
84              
85 2           SHA1_INIT(ctx);
86 2           }
87              
88             /* define macrosses to access chunk table */
89             #define CT_BITS 8
90             #define CT_GROUP_SIZE (1 << CT_BITS)
91             typedef unsigned char hash_pair_t[2][sha1_hash_size];
92             typedef hash_pair_t hash_pairs_group_t[CT_GROUP_SIZE];
93              
94             #define CT_INDEX(chunk_num) ((chunk_num) & (CT_GROUP_SIZE - 1))
95             #define GET_HASH_PAIR(ctx, chunk_num) \
96             (((hash_pair_t*)(ctx->chunk_table[chunk_num >> CT_BITS]))[CT_INDEX(chunk_num)])
97              
98             /**
99             * Resize the table if needed to ensure it contains space for given chunk_num.
100             * and allocate hash_pairs_group_t element at this index.
101             *
102             * @param ctx algorithm context
103             * @param chunk_num the number of chunks required
104             */
105 0           static void rhash_aich_chunk_table_extend(aich_ctx* ctx, unsigned chunk_num)
106             {
107 0           unsigned index = (chunk_num >> CT_BITS);
108             assert(sizeof(hash_pair_t) == 40);
109             assert(sizeof(hash_pairs_group_t) == (40 * CT_GROUP_SIZE)); /* 10KiB */
110             assert(CT_GROUP_SIZE == 256);
111 0 0         assert(CT_INDEX(chunk_num) == 0);
112              
113             /* check main assumptions */
114 0 0         assert(ctx->chunk_table == 0 || ctx->chunk_table[index - 1] != 0); /* table is empty or full */
    0          
115 0 0         assert(index <= ctx->allocated);
116              
117             /* check if there is enough space allocated */
118 0 0         if (index >= ctx->allocated) {
119             /* resize the table by allocating some extra space */
120 0 0         size_t new_size = (ctx->allocated == 0 ? 64 : ctx->allocated * 2);
121             void** new_block;
122 0 0         assert(index == ctx->allocated);
123              
124             /* re-size the chunk table to new_size */
125 0           new_block = (void**)realloc(ctx->chunk_table, new_size * sizeof(void*));
126 0 0         if (new_block == 0) {
127 0           free(ctx->chunk_table);
128 0           ctx->chunk_table = 0;
129 0           ctx->error = 1;
130 0           return;
131             }
132              
133 0           memset(new_block + ctx->allocated, 0, (new_size - ctx->allocated) * sizeof(void*));
134 0           ctx->chunk_table = new_block;
135 0           ctx->allocated = new_size;
136             }
137              
138             /* add new hash_pairs_group_t block to the table */
139 0 0         assert(index < ctx->allocated);
140 0 0         assert(ctx->chunk_table != 0);
141 0 0         assert(ctx->chunk_table[index] == 0);
142              
143 0           ctx->chunk_table[index] = malloc(sizeof(hash_pairs_group_t));
144 0 0         if (ctx->chunk_table[index] == 0) ctx->error = 1;
145             }
146              
147             /**
148             * Free dynamically allocated memory for internal structures
149             * used by hashing algorithm.
150             *
151             * @param ctx AICH algorithm context to cleanup
152             */
153 1           void rhash_aich_cleanup(aich_ctx* ctx)
154             {
155             size_t i;
156 1           size_t table_size = (ctx->chunks_number + CT_GROUP_SIZE - 1) / CT_GROUP_SIZE;
157              
158 1 50         if (ctx->chunk_table != 0) {
159 0 0         assert(table_size <= ctx->allocated);
160 0 0         assert(table_size == ctx->allocated || ctx->chunk_table[table_size] == 0);
    0          
161 0 0         for (i = 0; i < table_size; i++) free(ctx->chunk_table[i]);
162 0           free(ctx->chunk_table);
163 0           ctx->chunk_table = 0;
164             }
165              
166 1           free(ctx->block_hashes);
167 1           ctx->block_hashes = 0;
168 1           }
169              
170             #define AICH_HASH_FULL_TREE 0
171             #define AICH_HASH_LEFT_BRANCH 1
172             #define AICH_HASH_RIGHT_BRANCH 2
173              
174             /**
175             * Calculate an AICH tree hash, based ether on hashes of 180KB parts
176             * (for an ed2k chunk) or on stored ed2k chunks (for the whole tree hash).
177             *
178             * @param ctx algorithm context
179             * @param result pointer to receive calculated tree hash
180             * @param type the type of hash to calculate, can be one of constants
181             * AICH_HASH_LEFT_BRANCH, AICH_HASH_RIGHT_BRANCH or AICH_HASH_FULL_TREE.
182             */
183 0           static void rhash_aich_hash_tree(aich_ctx* ctx, unsigned char* result, int type)
184             {
185 0           unsigned index = 0; /* leaf index */
186             unsigned blocks;
187 0           int level = 0;
188 0           unsigned is_left_branch = (type == AICH_HASH_RIGHT_BRANCH ? 0x0 : 0x1);
189 0           uint64_t path = is_left_branch;
190             unsigned blocks_stack[56];
191             unsigned char sha1_stack[56][sha1_hash_size];
192              
193 0 0         if (ctx->error) return;
194 0 0         assert(ctx->index <= ED2K_CHUNK_SIZE);
195 0 0         assert(type == AICH_HASH_FULL_TREE ? ctx->chunk_table != 0 : ctx->block_hashes != 0);
    0          
196              
197             /* calculate number of leafs in the tree */
198 0 0         blocks_stack[0] = blocks = (unsigned)(type == AICH_HASH_FULL_TREE ?
199 0           ctx->chunks_number : (ctx->index + FULL_BLOCK_SIZE - 1) / FULL_BLOCK_SIZE);
200              
201             while (1) {
202             unsigned char sha1_message[sha1_hash_size];
203             unsigned char* leaf_hash;
204              
205             /* go into the left branches until a leaf block is reached */
206 0 0         while (blocks > 1) {
207             /* step down into the left branch */
208 0           blocks = (blocks + ((unsigned)path & 0x1)) / 2;
209 0           level++;
210 0 0         assert(level < 56); /* assumption filesize < (2^56 * 9MiB) */
211 0           blocks_stack[level] = blocks;
212 0           path = (path << 1) | 0x1; /* mark branch as left */
213             }
214              
215             /* read a leaf hash */
216 0           leaf_hash = &(ctx->block_hashes[index][0]);
217              
218 0 0         if (type == AICH_HASH_FULL_TREE) {
219 0           is_left_branch = (unsigned)path & 0x1;
220              
221 0           leaf_hash = GET_HASH_PAIR(ctx, index)[is_left_branch];
222             }
223 0           index++;
224              
225             /* climb up the tree until a left branch is reached */
226 0 0         for (; level > 0 && (path & 0x01) == 0; path >>= 1) {
    0          
227 0           SHA1_INIT(ctx);
228 0           SHA1_UPDATE(ctx, sha1_stack[level], sha1_hash_size);
229 0           SHA1_UPDATE(ctx, leaf_hash, sha1_hash_size);
230 0           SHA1_FINAL(ctx, sha1_message);
231 0           leaf_hash = sha1_message;
232 0           level--;
233             }
234 0 0         memcpy((level > 0 ? sha1_stack[level] : result), leaf_hash, 20);
235              
236 0 0         if (level == 0) break;
237              
238             /* jump at the current level from left to right branch */
239 0           path &= ~0x1; /* mark branch as right */
240 0           is_left_branch = ((unsigned)path >> 1) & 1;
241              
242             /* calculate number of blocks at right branch of the current level */
243 0           blocks_stack[level] =
244 0           (blocks_stack[level - 1] + 1 - is_left_branch) / 2;
245 0           blocks = blocks_stack[level];
246 0           }
247             }
248              
249             #define AICH_PROCESS_FINAL_BLOCK 1
250             #define AICH_PROCESS_FLUSH_BLOCK 2
251              
252             /**
253             * Calculate and store a hash for a 180K/140K block.
254             * Also, if it is the last block of a 9.2MiB ed2k chunk or of the hashed message,
255             * then also calculate the AICH tree-hash of the current ed2k chunk.
256             *
257             * @param ctx algorithm context
258             * @param type the actions to take, can be combination of bits AICH_PROCESS_FINAL_BLOCK
259             * and AICH_PROCESS_FLUSH_BLOCK
260             */
261 0           static void rhash_aich_process_block(aich_ctx* ctx, int type)
262             {
263 0 0         assert(type != 0);
264 0 0         assert(ctx->index <= ED2K_CHUNK_SIZE);
265              
266             /* if there is unprocessed data left in the current 180K block. */
267 0 0         if ((type & AICH_PROCESS_FLUSH_BLOCK) != 0)
268             {
269             /* ensure that the block_hashes array is allocated to save the result */
270 0 0         if (ctx->block_hashes == NULL) {
271 0           ctx->block_hashes = (unsigned char (*)[sha1_hash_size])malloc(BLOCKS_PER_CHUNK * sha1_hash_size);
272 0 0         if (ctx->block_hashes == NULL) {
273 0           ctx->error = 1;
274 0           return;
275             }
276             }
277              
278             /* store the 180-KiB block hash to the block_hashes array */
279 0 0         assert(((ctx->index - 1) / FULL_BLOCK_SIZE) < BLOCKS_PER_CHUNK);
280 0           SHA1_FINAL(ctx, ctx->block_hashes[(ctx->index - 1) / FULL_BLOCK_SIZE]);
281             }
282              
283             /* check, if it's time to calculate the tree hash for the current ed2k chunk */
284 0 0         if (ctx->index >= ED2K_CHUNK_SIZE || (type & AICH_PROCESS_FINAL_BLOCK)) {
    0          
285             unsigned char (*pair)[sha1_hash_size];
286              
287             /* ensure, that we have the space to store tree hash */
288 0 0         if (CT_INDEX(ctx->chunks_number) == 0) {
289 0           rhash_aich_chunk_table_extend(ctx, (unsigned)ctx->chunks_number);
290 0 0         if (ctx->error) return;
291             }
292 0 0         assert(ctx->chunk_table != 0);
293 0 0         assert(ctx->block_hashes != 0);
294              
295             /* calculate tree hash and save results to chunk_table */
296 0           pair = GET_HASH_PAIR(ctx, ctx->chunks_number);
297              
298             /* small optimization: skip a left-branch-hash for the last chunk */
299 0 0         if (!(type & AICH_PROCESS_FINAL_BLOCK) || ctx->chunks_number == 0) {
    0          
300             /* calculate a tree hash to be used in left branch */
301 0           rhash_aich_hash_tree(ctx, pair[1], AICH_HASH_LEFT_BRANCH);
302             }
303              
304             /* small optimization: skip right-branch-hash for the very first chunk */
305 0 0         if (ctx->chunks_number > 0) {
306             /* calculate a tree hash to be used in right branch */
307 0           rhash_aich_hash_tree(ctx, pair[0], AICH_HASH_RIGHT_BRANCH);
308             }
309              
310 0           ctx->index = 0; /* mark that the whole ed2k chunk was processed */
311 0           ctx->chunks_number++;
312             }
313             }
314              
315             /**
316             * Calculate message hash.
317             * Can be called repeatedly with chunks of the message to be hashed.
318             *
319             * @param ctx the algorithm context containing current hashing state
320             * @param msg message chunk
321             * @param size length of the message chunk
322             */
323 2           void rhash_aich_update(aich_ctx* ctx, const unsigned char* msg, size_t size)
324             {
325 2 50         if (ctx->error) return;
326              
327 2 50         while (size > 0) {
328 2           unsigned left_in_chunk = ED2K_CHUNK_SIZE - ctx->index;
329 2 50         unsigned block_left = (left_in_chunk <= LAST_BLOCK_SIZE ? left_in_chunk :
330 2           FULL_BLOCK_SIZE - ctx->index % FULL_BLOCK_SIZE);
331 2 50         assert(block_left > 0);
332              
333 2 50         if (size >= block_left) {
334 0           SHA1_UPDATE(ctx, msg, block_left);
335 0           msg += block_left;
336 0           size -= block_left;
337 0           ctx->index += block_left;
338              
339             /* process a 180KiB-blok */
340 0           rhash_aich_process_block(ctx, AICH_PROCESS_FLUSH_BLOCK);
341 0           SHA1_INIT(ctx);
342             } else {
343             /* add to a leaf block */
344 2           SHA1_UPDATE(ctx, msg, size);
345 2           ctx->index += (unsigned)size;
346 2           break;
347             }
348             }
349 2 50         assert(ctx->index < ED2K_CHUNK_SIZE);
350             }
351              
352             /**
353             * Store calculated hash into the given array.
354             *
355             * @param ctx the algorithm context containing current hashing state
356             * @param result calculated hash in binary form
357             */
358 2           void rhash_aich_final(aich_ctx* ctx, unsigned char result[20])
359             {
360 2           uint64_t total_size =
361 2           ((uint64_t)ctx->chunks_number * ED2K_CHUNK_SIZE) + ctx->index;
362 2           unsigned char* const hash = (unsigned char*)ctx->sha1_context.hash;
363              
364 2 50         if (ctx->chunks_number == 0 && ctx->block_hashes == NULL) {
    50          
365 2 50         assert(ctx->index < FULL_BLOCK_SIZE);
366             #ifdef USE_OPENSSL
367             SHA1_FINAL(ctx, hash); /* return just sha1 hash */
368             #else
369 2           SHA1_FINAL(ctx, 0); /* return just sha1 hash */
370             #if IS_LITTLE_ENDIAN
371 2           rhash_u32_mem_swap(ctx->sha1_context.hash, 5);
372             #endif
373             #endif
374 2 50         if (result) memcpy(result, hash, sha1_hash_size);
375 2           return;
376             }
377              
378             /* if there is unprocessed data left in the last 180K block */
379 0 0         if ((ctx->index % FULL_BLOCK_SIZE) > 0) {
380             /* then process the last block */
381 0 0         rhash_aich_process_block(ctx, ctx->block_hashes != NULL ?
382             AICH_PROCESS_FINAL_BLOCK | AICH_PROCESS_FLUSH_BLOCK : AICH_PROCESS_FLUSH_BLOCK);
383             }
384              
385             /* if processed message was shorter than a ed2k chunk */
386 0 0         if (ctx->chunks_number == 0) {
387             /* then return the aich hash for the first chunk */
388 0           rhash_aich_hash_tree(ctx, hash, AICH_HASH_LEFT_BRANCH);
389             } else {
390 0 0         if (ctx->index > 0) {
391             /* process the last block of the message */
392 0           rhash_aich_process_block(ctx, AICH_PROCESS_FINAL_BLOCK);
393             }
394 0 0         assert(ctx->chunks_number > 0);
395 0 0         assert(ctx->block_hashes != NULL);
396              
397 0           rhash_aich_hash_tree(ctx, hash, AICH_HASH_FULL_TREE);
398             }
399              
400 0           rhash_aich_cleanup(ctx);
401 0           ctx->sha1_context.length = total_size; /* store total message size */
402 0 0         if (result) memcpy(result, hash, sha1_hash_size);
403             }