aboutsummaryrefslogtreecommitdiff
path: root/src/fs/fs_download.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/fs/fs_download.c')
-rw-r--r--src/fs/fs_download.c2403
1 files changed, 0 insertions, 2403 deletions
diff --git a/src/fs/fs_download.c b/src/fs/fs_download.c
deleted file mode 100644
index e0ad8cd1d..000000000
--- a/src/fs/fs_download.c
+++ /dev/null
@@ -1,2403 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2001-2012 GNUnet e.V.
4
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
14
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 SPDX-License-Identifier: AGPL3.0-or-later
19 */
20/**
21 * @file fs/fs_download.c
22 * @brief download methods
23 * @author Christian Grothoff
24 */
25#include "platform.h"
26#include "gnunet_constants.h"
27#include "gnunet_fs_service.h"
28#include "fs_api.h"
29#include "fs_tree.h"
30
31
32/**
33 * Determine if the given download (options and meta data) should cause
34 * use to try to do a recursive download.
35 */
36static int
37is_recursive_download (struct GNUNET_FS_DownloadContext *dc)
38{
39 return (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
40 ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
41 ((NULL == dc->meta) &&
42 ((NULL == dc->filename) ||
43 ((strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
44 (NULL != strstr (dc->filename + strlen (dc->filename)
45 - strlen (GNUNET_FS_DIRECTORY_EXT),
46 GNUNET_FS_DIRECTORY_EXT))))));
47}
48
49
50/**
51 * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
52 * only have to truncate the file once we're done).
53 *
54 * Given the offset of a block (with respect to the DBLOCKS) and its
55 * depth, return the offset where we would store this block in the
56 * file.
57 *
58 * @param fsize overall file size
59 * @param off offset of the block in the file
60 * @param depth depth of the block in the tree, 0 for DBLOCK
61 * @return off for DBLOCKS (depth == treedepth),
62 * otherwise an offset past the end
63 * of the file that does not overlap
64 * with the range for any other block
65 */
66static uint64_t
67compute_disk_offset (uint64_t fsize, uint64_t off, unsigned int depth)
68{
69 unsigned int i;
70 uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
71 uint64_t loff; /* where do IBlocks for depth "i" start? */
72 unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
73
74 if (0 == depth)
75 return off;
76 /* first IBlocks start at the end of file, rounded up
77 * to full DBLOCK_SIZE */
78 loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
79 lsize =
80 ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * sizeof(struct ContentHashKey);
81 GNUNET_assert (0 == (off % DBLOCK_SIZE));
82 ioff = (off / DBLOCK_SIZE);
83 for (i = 1; i < depth; i++)
84 {
85 loff += lsize;
86 lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
87 GNUNET_assert (lsize > 0);
88 GNUNET_assert (0 == (ioff % CHK_PER_INODE));
89 ioff /= CHK_PER_INODE;
90 }
91 return loff + ioff * sizeof(struct ContentHashKey);
92}
93
94
95/**
96 * Fill in all of the generic fields for a download event and call the
97 * callback.
98 *
99 * @param pi structure to fill in
100 * @param dc overall download context
101 */
102void
103GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
104 struct GNUNET_FS_DownloadContext *dc)
105{
106 pi->value.download.dc = dc;
107 pi->value.download.cctx = dc->client_info;
108 pi->value.download.pctx =
109 (NULL == dc->parent) ? NULL : dc->parent->client_info;
110 pi->value.download.sctx =
111 (NULL == dc->search) ? NULL : dc->search->client_info;
112 pi->value.download.uri = dc->uri;
113 pi->value.download.filename = dc->filename;
114 pi->value.download.size = dc->length;
115 /* FIXME: Fix duration calculation to account for pauses */
116 pi->value.download.duration =
117 GNUNET_TIME_absolute_get_duration (dc->start_time);
118 pi->value.download.completed = dc->completed;
119 pi->value.download.anonymity = dc->anonymity;
120 pi->value.download.eta =
121 GNUNET_TIME_calculate_eta (dc->start_time, dc->completed, dc->length);
122 pi->value.download.is_active = (NULL == dc->mq) ? GNUNET_NO : GNUNET_YES;
123 pi->fsh = dc->h;
124 if (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
125 dc->client_info = dc->h->upcb (dc->h->upcb_cls, pi);
126 else
127 dc->client_info = GNUNET_FS_search_probe_progress_ (NULL, pi);
128}
129
130
131/**
132 * Closure for iterator processing results.
133 */
134struct ProcessResultClosure
135{
136 /**
137 * Hash of data.
138 */
139 struct GNUNET_HashCode query;
140
141 /**
142 * Data found in P2P network.
143 */
144 const void *data;
145
146 /**
147 * Our download context.
148 */
149 struct GNUNET_FS_DownloadContext *dc;
150
151 /**
152 * When did we last transmit the request?
153 */
154 struct GNUNET_TIME_Absolute last_transmission;
155
156 /**
157 * Number of bytes in data.
158 */
159 size_t size;
160
161 /**
162 * Type of data.
163 */
164 enum GNUNET_BLOCK_Type type;
165
166 /**
167 * Flag to indicate if this block should be stored on disk.
168 */
169 int do_store;
170
171 /**
172 * how much respect did we offer to get this reply?
173 */
174 uint32_t respect_offered;
175
176 /**
177 * how often did we transmit the query?
178 */
179 uint32_t num_transmissions;
180};
181
182
183/**
184 * Iterator over entries in the pending requests in the 'active' map for the
185 * reply that we just got.
186 *
187 * @param cls closure (our `struct ProcessResultClosure`)
188 * @param key query for the given value / request
189 * @param value value in the hash map (a `struct DownloadRequest`)
190 * @return #GNUNET_YES (we should continue to iterate); unless serious error
191 */
192static int
193process_result_with_request (void *cls,
194 const struct GNUNET_HashCode *key,
195 void *value);
196
197
198/**
199 * We've found a matching block without downloading it.
200 * Encrypt it and pass it to our "receive" function as
201 * if we had received it from the network.
202 *
203 * @param dc download in question
204 * @param chk request this relates to
205 * @param dr request details
206 * @param block plaintext data matching request
207 * @param len number of bytes in block
208 * @param do_store should we still store the block on disk?
209 * @return GNUNET_OK on success
210 */
211static int
212encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc,
213 const struct ContentHashKey *chk,
214 struct DownloadRequest *dr,
215 const char *block,
216 size_t len,
217 int do_store)
218{
219 struct ProcessResultClosure prc;
220 char enc[len];
221 struct GNUNET_CRYPTO_SymmetricSessionKey sk;
222 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
223 struct GNUNET_HashCode query;
224
225 GNUNET_CRYPTO_hash_to_aes_key (&chk->key, &sk, &iv);
226 if (-1 == GNUNET_CRYPTO_symmetric_encrypt (block, len, &sk, &iv, enc))
227 {
228 GNUNET_break (0);
229 return GNUNET_SYSERR;
230 }
231 GNUNET_CRYPTO_hash (enc, len, &query);
232 if (0 != memcmp (&query, &chk->query, sizeof(struct GNUNET_HashCode)))
233 {
234 GNUNET_break_op (0);
235 return GNUNET_SYSERR;
236 }
237 GNUNET_log (
238 GNUNET_ERROR_TYPE_DEBUG,
239 "Matching %u byte block for `%s' at offset %llu already present, no need for download!\n",
240 (unsigned int) len,
241 dc->filename,
242 (unsigned long long) dr->offset);
243 /* already got it! */
244 prc.dc = dc;
245 prc.data = enc;
246 prc.size = len;
247 prc.type = (0 == dr->depth) ? GNUNET_BLOCK_TYPE_FS_DBLOCK
248 : GNUNET_BLOCK_TYPE_FS_IBLOCK;
249 prc.query = chk->query;
250 prc.do_store = do_store;
251 prc.last_transmission = GNUNET_TIME_UNIT_FOREVER_ABS;
252 process_result_with_request (&prc, &chk->key, dr);
253 return GNUNET_OK;
254}
255
256
257/**
258 * We've lost our connection with the FS service.
259 * Re-establish it and re-transmit all of our
260 * pending requests.
261 *
262 * @param dc download context that is having trouble
263 */
264static void
265try_reconnect (struct GNUNET_FS_DownloadContext *dc);
266
267
268/**
269 * We found an entry in a directory. Check if the respective child
270 * already exists and if not create the respective child download.
271 *
272 * @param cls the parent download
273 * @param filename name of the file in the directory
274 * @param uri URI of the file (CHK or LOC)
275 * @param meta meta data of the file
276 * @param length number of bytes in data
277 * @param data contents of the file (or NULL if they were not inlined)
278 */
279static void
280trigger_recursive_download (void *cls,
281 const char *filename,
282 const struct GNUNET_FS_Uri *uri,
283 const struct GNUNET_CONTAINER_MetaData *meta,
284 size_t length,
285 const void *data);
286
287
288/**
289 * We're done downloading a directory. Open the file and
290 * trigger all of the (remaining) child downloads.
291 *
292 * @param dc context of download that just completed
293 */
294static void
295full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
296{
297 size_t size;
298 uint64_t size64;
299 void *data;
300 struct GNUNET_DISK_FileHandle *h;
301 struct GNUNET_DISK_MapHandle *m;
302
303 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
304 size = (size_t) size64;
305 if (size64 != (uint64_t) size)
306 {
307 GNUNET_log (
308 GNUNET_ERROR_TYPE_ERROR,
309 _ (
310 "Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
311 return;
312 }
313 if (NULL != dc->filename)
314 {
315 h = GNUNET_DISK_file_open (dc->filename,
316 GNUNET_DISK_OPEN_READ,
317 GNUNET_DISK_PERM_NONE);
318 }
319 else
320 {
321 GNUNET_assert (NULL != dc->temp_filename);
322 h = GNUNET_DISK_file_open (dc->temp_filename,
323 GNUNET_DISK_OPEN_READ,
324 GNUNET_DISK_PERM_NONE);
325 }
326 if (NULL == h)
327 return; /* oops */
328 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
329 if (NULL == data)
330 {
331 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
332 _ ("Directory too large for system address space\n"));
333 }
334 else
335 {
336 if (GNUNET_OK !=
337 GNUNET_FS_directory_list_contents (size,
338 data,
339 0,
340 &trigger_recursive_download,
341 dc))
342 {
343 GNUNET_log (
344 GNUNET_ERROR_TYPE_WARNING,
345 _ (
346 "Failed to access full directory contents of `%s' for recursive download\n"),
347 dc->filename);
348 }
349 GNUNET_DISK_file_unmap (m);
350 }
351 GNUNET_DISK_file_close (h);
352 if (NULL == dc->filename)
353 {
354 if (0 != unlink (dc->temp_filename))
355 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
356 "unlink",
357 dc->temp_filename);
358 GNUNET_free (dc->temp_filename);
359 dc->temp_filename = NULL;
360 }
361}
362
363
364/**
365 * Check if all child-downloads have completed (or trigger them if
366 * necessary) and once we're completely done, signal completion (and
367 * possibly recurse to parent). This function MUST be called when the
368 * download of a file itself is done or when the download of a file is
369 * done and then later a direct child download has completed (and
370 * hence this download may complete itself).
371 *
372 * @param dc download to check for completion of children
373 */
374static void
375check_completed (struct GNUNET_FS_DownloadContext *dc)
376{
377 struct GNUNET_FS_ProgressInfo pi;
378 struct GNUNET_FS_DownloadContext *pos;
379
380 /* first, check if we need to download children */
381 if (is_recursive_download (dc))
382 full_recursive_download (dc);
383 /* then, check if children are done already */
384 for (pos = dc->child_head; NULL != pos; pos = pos->next)
385 {
386 if ((NULL == pos->emsg) && (pos->completed < pos->length))
387 return; /* not done yet */
388 if ((NULL != pos->child_head) && (pos->has_finished != GNUNET_YES))
389 return; /* not transitively done yet */
390 }
391 /* All of our children are done, so mark this download done */
392 dc->has_finished = GNUNET_YES;
393 if (NULL != dc->job_queue)
394 {
395 GNUNET_FS_dequeue_ (dc->job_queue);
396 dc->job_queue = NULL;
397 }
398 if (NULL != dc->task)
399 {
400 GNUNET_SCHEDULER_cancel (dc->task);
401 dc->task = NULL;
402 }
403 if (NULL != dc->rfh)
404 {
405 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
406 dc->rfh = NULL;
407 }
408 GNUNET_FS_download_sync_ (dc);
409
410 /* signal completion */
411 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
412 GNUNET_FS_download_make_status_ (&pi, dc);
413
414 /* let parent know */
415 if (NULL != dc->parent)
416 check_completed (dc->parent);
417}
418
419
420/**
421 * We got a block of plaintext data (from the meta data).
422 * Try it for upward reconstruction of the data. On success,
423 * the top-level block will move to state BRS_DOWNLOAD_UP.
424 *
425 * @param dc context for the download
426 * @param dr download request to match against
427 * @param data plaintext data, starting from the beginning of the file
428 * @param data_len number of bytes in data
429 */
430static void
431try_match_block (struct GNUNET_FS_DownloadContext *dc,
432 struct DownloadRequest *dr,
433 const char *data,
434 size_t data_len)
435{
436 struct GNUNET_FS_ProgressInfo pi;
437 unsigned int i;
438 char enc[DBLOCK_SIZE];
439 struct ContentHashKey chks[CHK_PER_INODE];
440 struct ContentHashKey in_chk;
441 struct GNUNET_CRYPTO_SymmetricSessionKey sk;
442 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
443 size_t dlen;
444 struct DownloadRequest *drc;
445 struct GNUNET_DISK_FileHandle *fh;
446 int complete;
447 const char *fn;
448 const char *odata;
449 size_t odata_len;
450
451 odata = data;
452 odata_len = data_len;
453 if (BRS_DOWNLOAD_UP == dr->state)
454 return;
455 if (dr->depth > 0)
456 {
457 if ((dc->offset > 0) ||
458 (dc->length < GNUNET_ntohll (dc->uri->data.chk.file_length)))
459 {
460 /* NOTE: this test is not tight, but should suffice; the issue
461 here is that 'dr->num_children' may inherently only specify a
462 smaller range than what is in the original file;
463 thus, reconstruction of (some) inner blocks will fail.
464 FIXME: we might eventually want to write a tighter test to
465 maximize the circumstances under which we do succeed with
466 IBlock reconstruction. (need good tests though). */return;
467 }
468 complete = GNUNET_YES;
469 for (i = 0; i < dr->num_children; i++)
470 {
471 drc = dr->children[i];
472 try_match_block (dc, drc, data, data_len);
473 if (drc->state != BRS_RECONSTRUCT_META_UP)
474 complete = GNUNET_NO;
475 else
476 chks[i] = drc->chk;
477 }
478 if (GNUNET_YES != complete)
479 return;
480 data = (const char *) chks;
481 dlen = dr->num_children * sizeof(struct ContentHashKey);
482 }
483 else
484 {
485 if (dr->offset > data_len)
486 return; /* oops */
487 dlen = GNUNET_MIN (data_len - dr->offset, DBLOCK_SIZE);
488 }
489 GNUNET_CRYPTO_hash (&data[dr->offset], dlen, &in_chk.key);
490 GNUNET_CRYPTO_hash_to_aes_key (&in_chk.key, &sk, &iv);
491 if (-1 ==
492 GNUNET_CRYPTO_symmetric_encrypt (&data[dr->offset], dlen, &sk, &iv, enc))
493 {
494 GNUNET_break (0);
495 return;
496 }
497 GNUNET_CRYPTO_hash (enc, dlen, &in_chk.query);
498 switch (dr->state)
499 {
500 case BRS_INIT:
501 dr->chk = in_chk;
502 dr->state = BRS_RECONSTRUCT_META_UP;
503 break;
504
505 case BRS_CHK_SET:
506 if (0 != memcmp (&in_chk, &dr->chk, sizeof(struct ContentHashKey)))
507 {
508 /* other peer provided bogus meta data */
509 GNUNET_break_op (0);
510 break;
511 }
512 /* write block to disk */
513 fn = (NULL != dc->filename) ? dc->filename : dc->temp_filename;
514 if (NULL != fn)
515 {
516 fh = GNUNET_DISK_file_open (fn,
517 GNUNET_DISK_OPEN_READWRITE
518 | GNUNET_DISK_OPEN_CREATE
519 | GNUNET_DISK_OPEN_TRUNCATE,
520 GNUNET_DISK_PERM_USER_READ
521 | GNUNET_DISK_PERM_USER_WRITE
522 | GNUNET_DISK_PERM_GROUP_READ
523 | GNUNET_DISK_PERM_OTHER_READ);
524 if (NULL == fh)
525 {
526 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
527 GNUNET_asprintf (&dc->emsg,
528 _ ("Failed to open file `%s' for writing"),
529 fn);
530 GNUNET_DISK_file_close (fh);
531 dr->state = BRS_ERROR;
532 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
533 pi.value.download.specifics.error.message = dc->emsg;
534 GNUNET_FS_download_make_status_ (&pi, dc);
535 return;
536 }
537 if (data_len != GNUNET_DISK_file_write (fh, odata, odata_len))
538 {
539 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "write", fn);
540 GNUNET_asprintf (&dc->emsg,
541 _ ("Failed to open file `%s' for writing"),
542 fn);
543 GNUNET_DISK_file_close (fh);
544 dr->state = BRS_ERROR;
545 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
546 pi.value.download.specifics.error.message = dc->emsg;
547 GNUNET_FS_download_make_status_ (&pi, dc);
548 return;
549 }
550 GNUNET_DISK_file_close (fh);
551 }
552 /* signal success */
553 dr->state = BRS_DOWNLOAD_UP;
554 dc->completed = dc->length;
555 GNUNET_FS_download_sync_ (dc);
556 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
557 pi.value.download.specifics.progress.data = data;
558 pi.value.download.specifics.progress.offset = 0;
559 pi.value.download.specifics.progress.data_len = dlen;
560 pi.value.download.specifics.progress.depth = 0;
561 pi.value.download.specifics.progress.respect_offered = 0;
562 pi.value.download.specifics.progress.block_download_duration =
563 GNUNET_TIME_UNIT_ZERO;
564 GNUNET_FS_download_make_status_ (&pi, dc);
565 if ((NULL != dc->filename) &&
566 (0 != truncate (dc->filename,
567 GNUNET_ntohll (dc->uri->data.chk.file_length))))
568 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
569 "truncate",
570 dc->filename);
571 check_completed (dc);
572 break;
573
574 default:
575 /* how did we get here? */
576 GNUNET_break (0);
577 break;
578 }
579}
580
581
582/**
583 * Type of a function that libextractor calls for each
584 * meta data item found. If we find full data meta data,
585 * call 'try_match_block' on it.
586 *
587 * @param cls our 'struct GNUNET_FS_DownloadContext*'
588 * @param plugin_name name of the plugin that produced this value;
589 * special values can be used (e.g. '&lt;zlib&gt;' for zlib being
590 * used in the main libextractor library and yielding
591 * meta data).
592 * @param type libextractor-type describing the meta data
593 * @param format basic format information about data
594 * @param data_mime_type mime-type of data (not of the original file);
595 * can be NULL (if mime-type is not known)
596 * @param data actual meta-data found
597 * @param data_len number of bytes in data
598 * @return 0 to continue extracting, 1 to abort
599 */
600static int
601match_full_data (void *cls,
602 const char *plugin_name,
603 enum EXTRACTOR_MetaType type,
604 enum EXTRACTOR_MetaFormat format,
605 const char *data_mime_type,
606 const char *data,
607 size_t data_len)
608{
609 struct GNUNET_FS_DownloadContext *dc = cls;
610
611 if (EXTRACTOR_METATYPE_GNUNET_FULL_DATA != type)
612 return 0;
613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
614 "Found %u bytes of FD!\n",
615 (unsigned int) data_len);
616 if (GNUNET_FS_uri_chk_get_file_size (dc->uri) != data_len)
617 {
618 GNUNET_break_op (0);
619 return 1; /* bogus meta data */
620 }
621 try_match_block (dc, dc->top_request, data, data_len);
622 return 1;
623}
624
625
626/**
627 * Set the state of the given download request to
628 * BRS_DOWNLOAD_UP and propagate it up the tree.
629 *
630 * @param dr download request that is done
631 */
632static void
633propagate_up (struct DownloadRequest *dr)
634{
635 unsigned int i;
636
637 do
638 {
639 dr->state = BRS_DOWNLOAD_UP;
640 dr = dr->parent;
641 if (NULL == dr)
642 break;
643 for (i = 0; i < dr->num_children; i++)
644 if (dr->children[i]->state != BRS_DOWNLOAD_UP)
645 break;
646 }
647 while (i == dr->num_children);
648}
649
650
651/**
652 * Try top-down reconstruction. Before, the given request node
653 * must have the state BRS_CHK_SET. Afterwards, more nodes may
654 * have that state or advanced to BRS_DOWNLOAD_DOWN or even
655 * BRS_DOWNLOAD_UP. It is also possible to get BRS_ERROR on the
656 * top level.
657 *
658 * @param dc overall download this block belongs to
659 * @param dr block to reconstruct
660 */
661static void
662try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc,
663 struct DownloadRequest *dr)
664{
665 uint64_t off;
666 char block[DBLOCK_SIZE];
667 struct GNUNET_HashCode key;
668 uint64_t total;
669 size_t len;
670 unsigned int i;
671 struct DownloadRequest *drc;
672 uint64_t child_block_size;
673 const struct ContentHashKey *chks;
674 int up_done;
675
676 GNUNET_assert (NULL != dc->rfh);
677 GNUNET_assert (BRS_CHK_SET == dr->state);
678 total = GNUNET_FS_uri_chk_get_file_size (dc->uri);
679 GNUNET_assert (dr->depth < dc->treedepth);
680 len = GNUNET_FS_tree_calculate_block_size (total, dr->offset, dr->depth);
681 GNUNET_assert (len <= DBLOCK_SIZE);
682 off = compute_disk_offset (total, dr->offset, dr->depth);
683 if (dc->old_file_size < off + len)
684 return; /* failure */
685 if (off != GNUNET_DISK_file_seek (dc->rfh, off, GNUNET_DISK_SEEK_SET))
686 {
687 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "seek", dc->filename);
688 return; /* failure */
689 }
690 if (len != GNUNET_DISK_file_read (dc->rfh, block, len))
691 {
692 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "read", dc->filename);
693 return; /* failure */
694 }
695 GNUNET_CRYPTO_hash (block, len, &key);
696 if (0 != memcmp (&key, &dr->chk.key, sizeof(struct GNUNET_HashCode)))
697 return; /* mismatch */
698 if (GNUNET_OK !=
699 encrypt_existing_match (dc, &dr->chk, dr, block, len, GNUNET_NO))
700 {
701 /* hash matches but encrypted block does not, really bad */
702 dr->state = BRS_ERROR;
703 /* propagate up */
704 while (NULL != dr->parent)
705 {
706 dr = dr->parent;
707 dr->state = BRS_ERROR;
708 }
709 return;
710 }
711 /* block matches */
712 dr->state = BRS_DOWNLOAD_DOWN;
713
714 /* set CHKs for children */
715 up_done = GNUNET_YES;
716 chks = (const struct ContentHashKey *) block;
717 for (i = 0; i < dr->num_children; i++)
718 {
719 drc = dr->children[i];
720 GNUNET_assert (drc->offset >= dr->offset);
721 child_block_size = GNUNET_FS_tree_compute_tree_size (drc->depth);
722 GNUNET_assert (0 == (drc->offset - dr->offset) % child_block_size);
723 if (BRS_INIT == drc->state)
724 {
725 drc->state = BRS_CHK_SET;
726 drc->chk = chks[drc->chk_idx];
727 try_top_down_reconstruction (dc, drc);
728 }
729 if (BRS_DOWNLOAD_UP != drc->state)
730 up_done = GNUNET_NO; /* children not all done */
731 }
732 if (GNUNET_YES == up_done)
733 propagate_up (dr); /* children all done (or no children...) */
734}
735
736
737/**
738 * Add entries to the message queue.
739 *
740 * @param cls our download context
741 * @param key unused
742 * @param entry entry of type `struct DownloadRequest`
743 * @return #GNUNET_OK
744 */
745static int
746retry_entry (void *cls, const struct GNUNET_HashCode *key, void *entry)
747{
748 struct GNUNET_FS_DownloadContext *dc = cls;
749 struct DownloadRequest *dr = entry;
750 struct SearchMessage *sm;
751 struct GNUNET_MQ_Envelope *env;
752
753 env = GNUNET_MQ_msg (sm, GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
754 if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
755 sm->options = htonl (GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY);
756 else
757 sm->options = htonl (GNUNET_FS_SEARCH_OPTION_NONE);
758 if (0 == dr->depth)
759 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_DBLOCK);
760 else
761 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_IBLOCK);
762 sm->anonymity_level = htonl (dc->anonymity);
763 sm->target = dc->target;
764 sm->query = dr->chk.query;
765 GNUNET_MQ_send (dc->mq, env);
766 return GNUNET_OK;
767}
768
769
770/**
771 * Schedule the download of the specified block in the tree.
772 *
773 * @param dc overall download this block belongs to
774 * @param dr request to schedule
775 */
776static void
777schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
778 struct DownloadRequest *dr)
779{
780 unsigned int i;
781
782 switch (dr->state)
783 {
784 case BRS_INIT:
785 GNUNET_assert (0);
786 break;
787
788 case BRS_RECONSTRUCT_DOWN:
789 GNUNET_assert (0);
790 break;
791
792 case BRS_RECONSTRUCT_META_UP:
793 GNUNET_assert (0);
794 break;
795
796 case BRS_RECONSTRUCT_UP:
797 GNUNET_assert (0);
798 break;
799
800 case BRS_CHK_SET:
801 /* normal case, start download */
802 break;
803
804 case BRS_DOWNLOAD_DOWN:
805 for (i = 0; i < dr->num_children; i++)
806 schedule_block_download (dc, dr->children[i]);
807 return;
808
809 case BRS_DOWNLOAD_UP:
810 /* We're done! */
811 return;
812
813 case BRS_ERROR:
814 GNUNET_break (0);
815 return;
816 }
817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
818 "Scheduling download at offset %llu and depth %u for `%s'\n",
819 (unsigned long long) dr->offset,
820 dr->depth,
821 GNUNET_h2s (&dr->chk.query));
822 if (GNUNET_NO != GNUNET_CONTAINER_multihashmap_contains_value (dc->active,
823 &dr->chk.query,
824 dr))
825 return; /* already active */
826 GNUNET_CONTAINER_multihashmap_put (dc->active,
827 &dr->chk.query,
828 dr,
829 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
830 if (NULL == dc->mq)
831 return; /* download not active */
832 retry_entry (dc, &dr->chk.query, dr);
833}
834
835
836#define GNUNET_FS_URI_CHK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_CHK_INFIX
837
838/**
839 * We found an entry in a directory. Check if the respective child
840 * already exists and if not create the respective child download.
841 *
842 * @param cls the parent download
843 * @param filename name of the file in the directory
844 * @param uri URI of the file (CHK or LOC)
845 * @param meta meta data of the file
846 * @param length number of bytes in data
847 * @param data contents of the file (or NULL if they were not inlined)
848 */
849static void
850trigger_recursive_download (void *cls,
851 const char *filename,
852 const struct GNUNET_FS_Uri *uri,
853 const struct GNUNET_CONTAINER_MetaData *meta,
854 size_t length,
855 const void *data)
856{
857 struct GNUNET_FS_DownloadContext *dc = cls;
858 struct GNUNET_FS_DownloadContext *cpos;
859 char *temp_name;
860 char *fn;
861 char *us;
862 char *ext;
863 char *dn;
864 char *pos;
865 char *full_name;
866 char *sfn;
867
868 if (NULL == uri)
869 return; /* entry for the directory itself */
870 cpos = dc->child_head;
871 while (NULL != cpos)
872 {
873 if ((GNUNET_FS_uri_test_equal (uri, cpos->uri)) ||
874 ((NULL != filename) && (0 == strcmp (cpos->filename, filename))))
875 break;
876 cpos = cpos->next;
877 }
878 if (NULL != cpos)
879 return; /* already exists */
880 fn = NULL;
881 if (NULL == filename)
882 {
883 fn = GNUNET_FS_meta_data_suggest_filename (meta);
884 if (NULL == fn)
885 {
886 us = GNUNET_FS_uri_to_string (uri);
887 fn = GNUNET_strdup (&us[strlen (GNUNET_FS_URI_CHK_PREFIX)]);
888 GNUNET_free (us);
889 }
890 else if ('.' == fn[0])
891 {
892 ext = fn;
893 us = GNUNET_FS_uri_to_string (uri);
894 GNUNET_asprintf (&fn,
895 "%s%s",
896 &us[strlen (GNUNET_FS_URI_CHK_PREFIX)],
897 ext);
898 GNUNET_free (ext);
899 GNUNET_free (us);
900 }
901 /* change '\' to '/' (this should have happened
902 * during insertion, but malicious peers may
903 * not have done this) */
904 while (NULL != (pos = strstr (fn, "\\")))
905 *pos = '/';
906 /* remove '../' everywhere (again, well-behaved
907 * peers don't do this, but don't trust that
908 * we did not get something nasty) */
909 while (NULL != (pos = strstr (fn, "../")))
910 {
911 pos[0] = '_';
912 pos[1] = '_';
913 pos[2] = '_';
914 }
915 filename = fn;
916 }
917 if (NULL == dc->filename)
918 {
919 full_name = NULL;
920 }
921 else
922 {
923 dn = GNUNET_strdup (dc->filename);
924 GNUNET_break (
925 (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
926 (NULL != strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
927 GNUNET_FS_DIRECTORY_EXT)));
928 sfn = GNUNET_strdup (filename);
929 while ((strlen (sfn) > 0) && ('/' == filename[strlen (sfn) - 1]))
930 sfn[strlen (sfn) - 1] = '\0';
931 if ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
932 (NULL != strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
933 GNUNET_FS_DIRECTORY_EXT)))
934 dn[strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
935 if ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
936 ((strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
937 (NULL == strstr (filename + strlen (filename)
938 - strlen (GNUNET_FS_DIRECTORY_EXT),
939 GNUNET_FS_DIRECTORY_EXT))))
940 {
941 GNUNET_asprintf (&full_name,
942 "%s%s%s%s",
943 dn,
944 DIR_SEPARATOR_STR,
945 sfn,
946 GNUNET_FS_DIRECTORY_EXT);
947 }
948 else
949 {
950 GNUNET_asprintf (&full_name, "%s%s%s", dn, DIR_SEPARATOR_STR, sfn);
951 }
952 GNUNET_free (sfn);
953 GNUNET_free (dn);
954 }
955 if ((NULL != full_name) &&
956 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (full_name)))
957 {
958 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
959 _ (
960 "Failed to create directory for recursive download of `%s'\n"),
961 full_name);
962 GNUNET_free (full_name);
963 GNUNET_free (fn);
964 return;
965 }
966
967 temp_name = NULL;
968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
969 "Triggering recursive download of size %llu with %u bytes MD\n",
970 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (uri),
971 (unsigned int) GNUNET_CONTAINER_meta_data_get_serialized_size (
972 meta));
973 GNUNET_FS_download_start (dc->h,
974 uri,
975 meta,
976 full_name,
977 temp_name,
978 0,
979 GNUNET_FS_uri_chk_get_file_size (uri),
980 dc->anonymity,
981 dc->options,
982 NULL,
983 dc);
984 GNUNET_free (full_name);
985 GNUNET_free (temp_name);
986 GNUNET_free (fn);
987}
988
989
990/**
991 * (recursively) free download request structure
992 *
993 * @param dr request to free
994 */
995void
996GNUNET_FS_free_download_request_ (struct DownloadRequest *dr)
997{
998 if (NULL == dr)
999 return;
1000 for (unsigned int i = 0; i < dr->num_children; i++)
1001 GNUNET_FS_free_download_request_ (dr->children[i]);
1002 GNUNET_free (dr->children);
1003 GNUNET_free (dr);
1004}
1005
1006
1007static int
1008process_result_with_request (void *cls,
1009 const struct GNUNET_HashCode *key,
1010 void *value)
1011{
1012 struct ProcessResultClosure *prc = cls;
1013 struct DownloadRequest *dr = value;
1014 struct GNUNET_FS_DownloadContext *dc = prc->dc;
1015 struct DownloadRequest *drc;
1016 struct GNUNET_DISK_FileHandle *fh = NULL;
1017 struct GNUNET_CRYPTO_SymmetricSessionKey skey;
1018 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1019 char pt[prc->size];
1020 struct GNUNET_FS_ProgressInfo pi;
1021 uint64_t off;
1022 size_t bs;
1023 size_t app;
1024 int i;
1025 struct ContentHashKey *chkarr;
1026
1027 GNUNET_log (
1028 GNUNET_ERROR_TYPE_DEBUG,
1029 "Received %u byte block `%s' matching pending request at depth %u and offset %llu/%llu\n",
1030 (unsigned int) prc->size,
1031 GNUNET_h2s (key),
1032 dr->depth,
1033 (unsigned long long) dr->offset,
1034 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
1035 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (
1036 dc->uri->data.chk.file_length),
1037 dr->offset,
1038 dr->depth);
1039 if (prc->size != bs)
1040 {
1041 GNUNET_asprintf (
1042 &dc->emsg,
1043 _ (
1044 "Internal error or bogus download URI (expected %lu bytes at depth %u and offset %llu/%llu, got %lu bytes)"),
1045 bs,
1046 dr->depth,
1047 (unsigned long long) dr->offset,
1048 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length),
1049 prc->size);
1050 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s\n", dc->emsg);
1051 while (NULL != dr->parent)
1052 {
1053 dr->state = BRS_ERROR;
1054 dr = dr->parent;
1055 }
1056 dr->state = BRS_ERROR;
1057 goto signal_error;
1058 }
1059
1060 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &prc->query, dr);
1061 GNUNET_CRYPTO_hash_to_aes_key (&dr->chk.key, &skey, &iv);
1062 if (-1 ==
1063 GNUNET_CRYPTO_symmetric_decrypt (prc->data, prc->size, &skey, &iv, pt))
1064 {
1065 GNUNET_break (0);
1066 dc->emsg = GNUNET_strdup (_ ("internal error decrypting content"));
1067 goto signal_error;
1068 }
1069 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
1070 dr->offset,
1071 dr->depth);
1072 /* save to disk */
1073 if ((GNUNET_YES == prc->do_store) &&
1074 ((NULL != dc->filename) || (is_recursive_download (dc))) &&
1075 ((dr->depth == dc->treedepth) ||
1076 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES))))
1077 {
1078 fh = GNUNET_DISK_file_open (NULL != dc->filename ? dc->filename
1079 : dc->temp_filename,
1080 GNUNET_DISK_OPEN_READWRITE
1081 | GNUNET_DISK_OPEN_CREATE,
1082 GNUNET_DISK_PERM_USER_READ
1083 | GNUNET_DISK_PERM_USER_WRITE
1084 | GNUNET_DISK_PERM_GROUP_READ
1085 | GNUNET_DISK_PERM_OTHER_READ);
1086 if (NULL == fh)
1087 {
1088 GNUNET_asprintf (&dc->emsg,
1089 _ ("Download failed: could not open file `%s': %s"),
1090 dc->filename,
1091 strerror (errno));
1092 goto signal_error;
1093 }
1094 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1095 "Saving decrypted block to disk at offset %llu\n",
1096 (unsigned long long) off);
1097 if ((off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)))
1098 {
1099 GNUNET_asprintf (&dc->emsg,
1100 _ ("Failed to seek to offset %llu in file `%s': %s"),
1101 (unsigned long long) off,
1102 dc->filename,
1103 strerror (errno));
1104 goto signal_error;
1105 }
1106 if (prc->size != GNUNET_DISK_file_write (fh, pt, prc->size))
1107 {
1108 GNUNET_asprintf (
1109 &dc->emsg,
1110 _ ("Failed to write block of %u bytes at offset %llu in file `%s': %s"),
1111 (unsigned int) prc->size,
1112 (unsigned long long) off,
1113 dc->filename,
1114 strerror (errno));
1115 goto signal_error;
1116 }
1117 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
1118 fh = NULL;
1119 }
1120
1121 if (0 == dr->depth)
1122 {
1123 /* DBLOCK, update progress and try recursion if applicable */
1124 app = prc->size;
1125 if (dr->offset < dc->offset)
1126 {
1127 /* starting offset begins in the middle of pt,
1128 * do not count first bytes as progress */
1129 GNUNET_assert (app > (dc->offset - dr->offset));
1130 app -= (dc->offset - dr->offset);
1131 }
1132 if (dr->offset + prc->size > dc->offset + dc->length)
1133 {
1134 /* end of block is after relevant range,
1135 * do not count last bytes as progress */
1136 GNUNET_assert (app >
1137 (dr->offset + prc->size) - (dc->offset + dc->length));
1138 app -= (dr->offset + prc->size) - (dc->offset + dc->length);
1139 }
1140 dc->completed += app;
1141
1142 /* do recursive download if option is set and either meta data
1143 * says it is a directory or if no meta data is given AND filename
1144 * ends in '.gnd' (top-level case) */
1145 if (is_recursive_download (dc))
1146 GNUNET_FS_directory_list_contents (prc->size,
1147 pt,
1148 off,
1149 &trigger_recursive_download,
1150 dc);
1151 }
1152 GNUNET_assert (dc->completed <= dc->length);
1153 dr->state = BRS_DOWNLOAD_DOWN;
1154 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1155 pi.value.download.specifics.progress.data = pt;
1156 pi.value.download.specifics.progress.offset = dr->offset;
1157 pi.value.download.specifics.progress.data_len = prc->size;
1158 pi.value.download.specifics.progress.depth = dr->depth;
1159 pi.value.download.specifics.progress.respect_offered = prc->respect_offered;
1160 pi.value.download.specifics.progress.num_transmissions =
1161 prc->num_transmissions;
1162 if (prc->last_transmission.abs_value_us !=
1163 GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
1164 pi.value.download.specifics.progress.block_download_duration =
1165 GNUNET_TIME_absolute_get_duration (prc->last_transmission);
1166 else
1167 pi.value.download.specifics.progress.block_download_duration =
1168 GNUNET_TIME_UNIT_ZERO; /* found locally */
1169 GNUNET_FS_download_make_status_ (&pi, dc);
1170 if (0 == dr->depth)
1171 propagate_up (dr);
1172
1173 if (dc->completed == dc->length)
1174 {
1175 /* download completed, signal */
1176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1177 "Download completed, truncating file to desired length %llu\n",
1178 (unsigned long long) GNUNET_ntohll (
1179 dc->uri->data.chk.file_length));
1180 /* truncate file to size (since we store IBlocks at the end) */
1181 if (NULL != dc->filename)
1182 {
1183 if (0 != truncate (dc->filename,
1184 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1185 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1186 "truncate",
1187 dc->filename);
1188 }
1189 GNUNET_assert (0 == dr->depth);
1190 check_completed (dc);
1191 }
1192 if (0 == dr->depth)
1193 {
1194 /* bottom of the tree, no child downloads possible, just sync */
1195 GNUNET_FS_download_sync_ (dc);
1196 return GNUNET_YES;
1197 }
1198
1199 GNUNET_log (
1200 GNUNET_ERROR_TYPE_DEBUG,
1201 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1202 dr->depth,
1203 (unsigned long long) dr->offset);
1204 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1205 chkarr = (struct ContentHashKey *) pt;
1206 for (i = dr->num_children - 1; i >= 0; i--)
1207 {
1208 drc = dr->children[i];
1209 switch (drc->state)
1210 {
1211 case BRS_INIT:
1212 if ((drc->chk_idx + 1) * sizeof(struct ContentHashKey) > prc->size)
1213 {
1214 /* 'chkarr' does not have enough space for this chk_idx;
1215 internal error! */
1216 GNUNET_break (0);
1217 GNUNET_assert (0);
1218 dc->emsg = GNUNET_strdup (_ ("internal error decoding tree"));
1219 goto signal_error;
1220 }
1221 drc->chk = chkarr[drc->chk_idx];
1222 drc->state = BRS_CHK_SET;
1223 if (GNUNET_YES == dc->issue_requests)
1224 schedule_block_download (dc, drc);
1225 break;
1226
1227 case BRS_RECONSTRUCT_DOWN:
1228 GNUNET_assert (0);
1229 break;
1230
1231 case BRS_RECONSTRUCT_META_UP:
1232 GNUNET_assert (0);
1233 break;
1234
1235 case BRS_RECONSTRUCT_UP:
1236 GNUNET_assert (0);
1237 break;
1238
1239 case BRS_CHK_SET:
1240 GNUNET_assert (0);
1241 break;
1242
1243 case BRS_DOWNLOAD_DOWN:
1244 GNUNET_assert (0);
1245 break;
1246
1247 case BRS_DOWNLOAD_UP:
1248 GNUNET_assert (0);
1249 break;
1250
1251 case BRS_ERROR:
1252 GNUNET_assert (0);
1253 break;
1254
1255 default:
1256 GNUNET_assert (0);
1257 break;
1258 }
1259 }
1260 GNUNET_FS_download_sync_ (dc);
1261 return GNUNET_YES;
1262
1263signal_error:
1264 if (NULL != fh)
1265 GNUNET_DISK_file_close (fh);
1266 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1267 pi.value.download.specifics.error.message = dc->emsg;
1268 GNUNET_FS_download_make_status_ (&pi, dc);
1269 GNUNET_MQ_destroy (dc->mq);
1270 dc->mq = NULL;
1271 GNUNET_FS_free_download_request_ (dc->top_request);
1272 dc->top_request = NULL;
1273 if (NULL != dc->job_queue)
1274 {
1275 GNUNET_FS_dequeue_ (dc->job_queue);
1276 dc->job_queue = NULL;
1277 }
1278 GNUNET_FS_download_sync_ (dc);
1279 return GNUNET_NO;
1280}
1281
1282
1283/**
1284 * Type of a function to call when we check the PUT message
1285 * from the service.
1286 *
1287 * @param cls closure
1288 * @param msg message received
1289 */
1290static int
1291check_put (void *cls, const struct ClientPutMessage *cm)
1292{
1293 /* any varsize length is OK */
1294 return GNUNET_OK;
1295}
1296
1297
1298/**
1299 * Type of a function to call when we receive a message
1300 * from the service.
1301 *
1302 * @param cls closure
1303 * @param msg message received
1304 */
1305static void
1306handle_put (void *cls, const struct ClientPutMessage *cm)
1307{
1308 struct GNUNET_FS_DownloadContext *dc = cls;
1309 uint16_t msize = ntohs (cm->header.size) - sizeof(*cm);
1310 struct ProcessResultClosure prc;
1311
1312 prc.dc = dc;
1313 prc.data = &cm[1];
1314 prc.last_transmission = GNUNET_TIME_absolute_ntoh (cm->last_transmission);
1315 prc.size = msize;
1316 prc.type = ntohl (cm->type);
1317 prc.do_store = GNUNET_YES;
1318 prc.respect_offered = ntohl (cm->respect_offered);
1319 prc.num_transmissions = ntohl (cm->num_transmissions);
1320 GNUNET_CRYPTO_hash (prc.data, msize, &prc.query);
1321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1322 "Received result for query `%s' from FS service\n",
1323 GNUNET_h2s (&prc.query));
1324 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1325 &prc.query,
1326 &process_result_with_request,
1327 &prc);
1328}
1329
1330
1331/**
1332 * Generic error handler, called with the appropriate error code and
1333 * the same closure specified at the creation of the message queue.
1334 * Not every message queue implementation supports an error handler.
1335 *
1336 * @param cls closure with the `struct GNUNET_FS_DownloadContext *`
1337 * @param error error code
1338 */
1339static void
1340download_mq_error_handler (void *cls, enum GNUNET_MQ_Error error)
1341{
1342 struct GNUNET_FS_DownloadContext *dc = cls;
1343
1344 if (NULL != dc->mq)
1345 {
1346 GNUNET_MQ_destroy (dc->mq);
1347 dc->mq = NULL;
1348 }
1349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1350 "Transmitting download request failed, trying to reconnect\n");
1351 try_reconnect (dc);
1352}
1353
1354
1355/**
1356 * Reconnect to the FS service and transmit our queries NOW.
1357 *
1358 * @param cls our download context
1359 */
1360static void
1361do_reconnect (void *cls)
1362{
1363 struct GNUNET_FS_DownloadContext *dc = cls;
1364 struct GNUNET_MQ_MessageHandler handlers[] =
1365 { GNUNET_MQ_hd_var_size (put,
1366 GNUNET_MESSAGE_TYPE_FS_PUT,
1367 struct ClientPutMessage,
1368 dc),
1369 GNUNET_MQ_handler_end () };
1370
1371 dc->task = NULL;
1372 dc->mq = GNUNET_CLIENT_connect (dc->h->cfg,
1373 "fs",
1374 handlers,
1375 &download_mq_error_handler,
1376 dc);
1377 if (NULL == dc->mq)
1378 {
1379 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1380 "Connecting to `%s'-service failed, will try again.\n",
1381 "FS");
1382 try_reconnect (dc);
1383 return;
1384 }
1385 GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1386}
1387
1388
1389/**
1390 * We've lost our connection with the FS service.
1391 * Re-establish it and re-transmit all of our
1392 * pending requests.
1393 *
1394 * @param dc download context that is having trouble
1395 */
1396static void
1397try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1398{
1399 if (NULL != dc->mq)
1400 {
1401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402 "Moving all requests back to pending list\n");
1403 GNUNET_MQ_destroy (dc->mq);
1404 dc->mq = NULL;
1405 }
1406 if (0 == dc->reconnect_backoff.rel_value_us)
1407 dc->reconnect_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1408 else
1409 dc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (dc->reconnect_backoff);
1410
1411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1412 "Will try to reconnect in %s\n",
1413 GNUNET_STRINGS_relative_time_to_string (dc->reconnect_backoff,
1414 GNUNET_YES));
1415 GNUNET_break (NULL != dc->job_queue);
1416 dc->task =
1417 GNUNET_SCHEDULER_add_delayed (dc->reconnect_backoff, &do_reconnect, dc);
1418}
1419
1420
1421/**
1422 * We're allowed to ask the FS service for our blocks. Start the download.
1423 *
1424 * @param cls the 'struct GNUNET_FS_DownloadContext'
1425 * @param mq handle to use for communication with FS (we must destroy it!)
1426 */
1427static void
1428activate_fs_download (void *cls)
1429{
1430 struct GNUNET_FS_DownloadContext *dc = cls;
1431 struct GNUNET_FS_ProgressInfo pi;
1432
1433 GNUNET_assert (NULL == dc->mq);
1434 GNUNET_assert (NULL != dc->active);
1435 do_reconnect (dc);
1436 if (NULL != dc->mq)
1437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download activated\n");
1438 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1439 GNUNET_FS_download_make_status_ (&pi, dc);
1440}
1441
1442
1443/**
1444 * We must stop to ask the FS service for our blocks. Pause the download.
1445 *
1446 * @param cls the `struct GNUNET_FS_DownloadContext`
1447 */
1448static void
1449deactivate_fs_download (void *cls)
1450{
1451 struct GNUNET_FS_DownloadContext *dc = cls;
1452 struct GNUNET_FS_ProgressInfo pi;
1453
1454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download deactivated\n");
1455 if (NULL != dc->mq)
1456 {
1457 GNUNET_MQ_destroy (dc->mq);
1458 dc->mq = NULL;
1459 }
1460 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1461 GNUNET_FS_download_make_status_ (&pi, dc);
1462}
1463
1464
1465/**
1466 * (recursively) Create a download request structure.
1467 *
1468 * @param parent parent of the current entry
1469 * @param chk_idx index of the chk for this block in the parent block
1470 * @param depth depth of the current entry, 0 are the DBLOCKs,
1471 * top level block is 'dc->treedepth - 1'
1472 * @param dr_offset offset in the original file this block maps to
1473 * (as in, offset of the first byte of the first DBLOCK
1474 * in the subtree rooted in the returned download request tree)
1475 * @param file_start_offset desired starting offset for the download
1476 * in the original file; requesting tree should not contain
1477 * DBLOCKs prior to the file_start_offset
1478 * @param desired_length desired number of bytes the user wanted to access
1479 * (from file_start_offset). Resulting tree should not contain
1480 * DBLOCKs after file_start_offset + file_length.
1481 * @return download request tree for the given range of DBLOCKs at
1482 * the specified depth
1483 */
1484static struct DownloadRequest *
1485create_download_request (struct DownloadRequest *parent,
1486 unsigned int chk_idx,
1487 unsigned int depth,
1488 uint64_t dr_offset,
1489 uint64_t file_start_offset,
1490 uint64_t desired_length)
1491{
1492 struct DownloadRequest *dr;
1493 unsigned int i;
1494 unsigned int head_skip;
1495 uint64_t child_block_size;
1496
1497 dr = GNUNET_new (struct DownloadRequest);
1498 dr->parent = parent;
1499 dr->depth = depth;
1500 dr->offset = dr_offset;
1501 dr->chk_idx = chk_idx;
1502 if (0 == depth)
1503 return dr;
1504 child_block_size = GNUNET_FS_tree_compute_tree_size (depth - 1);
1505
1506 /* calculate how many blocks at this level are not interesting
1507 * from the start (rounded down), either because of the requested
1508 * file offset or because this IBlock is further along */
1509 if (dr_offset < file_start_offset)
1510 {
1511 head_skip = (file_start_offset - dr_offset) / child_block_size;
1512 }
1513 else
1514 {
1515 head_skip = 0;
1516 }
1517
1518 /* calculate index of last block at this level that is interesting (rounded up) */
1519 dr->num_children =
1520 (file_start_offset + desired_length - dr_offset) / child_block_size;
1521 if (dr->num_children * child_block_size <
1522 file_start_offset + desired_length - dr_offset)
1523 dr->num_children++; /* round up */
1524 GNUNET_assert (dr->num_children > head_skip);
1525 dr->num_children -= head_skip;
1526 if (dr->num_children > CHK_PER_INODE)
1527 dr->num_children = CHK_PER_INODE; /* cap at max */
1528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1529 "Block at offset %llu and depth %u has %u children\n",
1530 (unsigned long long) dr_offset,
1531 depth,
1532 dr->num_children);
1533
1534 /* now we can get the total number of *interesting* children for this block */
1535
1536 /* why else would we have gotten here to begin with? (that'd be a bad logic error) */
1537 GNUNET_assert (dr->num_children > 0);
1538
1539 dr->children = GNUNET_new_array (dr->num_children, struct DownloadRequest *);
1540 for (i = 0; i < dr->num_children; i++)
1541 {
1542 dr->children[i] =
1543 create_download_request (dr,
1544 i + head_skip,
1545 depth - 1,
1546 dr_offset + (i + head_skip) * child_block_size,
1547 file_start_offset,
1548 desired_length);
1549 }
1550 return dr;
1551}
1552
1553
1554/**
1555 * Continuation after a possible attempt to reconstruct
1556 * the current IBlock from the existing file.
1557 *
1558 * @param cls the 'struct ReconstructContext'
1559 */
1560static void
1561reconstruct_cont (void *cls)
1562{
1563 struct GNUNET_FS_DownloadContext *dc = cls;
1564
1565 /* clean up state from tree encoder */
1566 if (NULL != dc->task)
1567 {
1568 GNUNET_SCHEDULER_cancel (dc->task);
1569 dc->task = NULL;
1570 }
1571 if (NULL != dc->rfh)
1572 {
1573 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
1574 dc->rfh = NULL;
1575 }
1576 /* start "normal" download */
1577 dc->issue_requests = GNUNET_YES;
1578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting normal download\n");
1579 schedule_block_download (dc, dc->top_request);
1580}
1581
1582
1583/**
1584 * Task requesting the next block from the tree encoder.
1585 *
1586 * @param cls the 'struct GNUJNET_FS_DownloadContext' we're processing
1587 */
1588static void
1589get_next_block (void *cls)
1590{
1591 struct GNUNET_FS_DownloadContext *dc = cls;
1592
1593 dc->task = NULL;
1594 GNUNET_FS_tree_encoder_next (dc->te);
1595}
1596
1597
1598/**
1599 * Function called asking for the current (encoded)
1600 * block to be processed. After processing the
1601 * client should either call "GNUNET_FS_tree_encode_next"
1602 * or (on error) "GNUNET_FS_tree_encode_finish".
1603 *
1604 * This function checks if the content on disk matches
1605 * the expected content based on the URI.
1606 *
1607 * @param cls closure
1608 * @param chk content hash key for the block
1609 * @param offset offset of the block
1610 * @param depth depth of the block, 0 for DBLOCK
1611 * @param type type of the block (IBLOCK or DBLOCK)
1612 * @param block the (encrypted) block
1613 * @param block_size size of block (in bytes)
1614 */
1615static void
1616reconstruct_cb (void *cls,
1617 const struct ContentHashKey *chk,
1618 uint64_t offset,
1619 unsigned int depth,
1620 enum GNUNET_BLOCK_Type type,
1621 const void *block,
1622 uint16_t block_size)
1623{
1624 struct GNUNET_FS_DownloadContext *dc = cls;
1625 struct GNUNET_FS_ProgressInfo pi;
1626 struct DownloadRequest *dr;
1627 uint64_t blen;
1628 unsigned int chld;
1629
1630 /* find corresponding request entry */
1631 dr = dc->top_request;
1632 while (dr->depth > depth)
1633 {
1634 GNUNET_assert (dr->num_children > 0);
1635 blen = GNUNET_FS_tree_compute_tree_size (dr->depth - 1);
1636 chld = (offset - dr->offset) / blen;
1637 if (chld < dr->children[0]->chk_idx)
1638 {
1639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1640 "Block %u < %u irrelevant for our range\n",
1641 chld,
1642 dr->children[0]->chk_idx);
1643 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1644 return; /* irrelevant block */
1645 }
1646 if (chld > dr->children[dr->num_children - 1]->chk_idx)
1647 {
1648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1649 "Block %u > %u irrelevant for our range\n",
1650 chld,
1651 dr->children[dr->num_children - 1]->chk_idx);
1652 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1653 return; /* irrelevant block */
1654 }
1655 dr = dr->children[chld - dr->children[0]->chk_idx];
1656 }
1657 GNUNET_log (
1658 GNUNET_ERROR_TYPE_DEBUG,
1659 "Matched TE block with request at offset %llu and depth %u in state %d\n",
1660 (unsigned long long) dr->offset,
1661 dr->depth,
1662 dr->state);
1663 /* FIXME: this code needs more testing and might
1664 need to handle more states... */
1665 switch (dr->state)
1666 {
1667 case BRS_INIT:
1668 break;
1669
1670 case BRS_RECONSTRUCT_DOWN:
1671 break;
1672
1673 case BRS_RECONSTRUCT_META_UP:
1674 break;
1675
1676 case BRS_RECONSTRUCT_UP:
1677 break;
1678
1679 case BRS_CHK_SET:
1680 if (0 == memcmp (chk, &dr->chk, sizeof(struct ContentHashKey)))
1681 {
1682 GNUNET_log (
1683 GNUNET_ERROR_TYPE_DEBUG,
1684 "Reconstruction succeeded, can use block at offset %llu, depth %u\n",
1685 (unsigned long long) offset,
1686 depth);
1687 /* block matches, hence tree below matches;
1688 * this request is done! */
1689 dr->state = BRS_DOWNLOAD_UP;
1690 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active,
1691 &dr->chk.query,
1692 dr);
1693 /* calculate how many bytes of payload this block
1694 * corresponds to */
1695 blen = GNUNET_FS_tree_compute_tree_size (dr->depth);
1696 /* how many of those bytes are in the requested range? */
1697 blen = GNUNET_MIN (blen, dc->length + dc->offset - dr->offset);
1698 /* signal progress */
1699 dc->completed += blen;
1700 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1701 pi.value.download.specifics.progress.data = NULL;
1702 pi.value.download.specifics.progress.offset = offset;
1703 pi.value.download.specifics.progress.data_len = 0;
1704 pi.value.download.specifics.progress.depth = 0;
1705 pi.value.download.specifics.progress.respect_offered = 0;
1706 pi.value.download.specifics.progress.block_download_duration =
1707 GNUNET_TIME_UNIT_ZERO;
1708 GNUNET_FS_download_make_status_ (&pi, dc);
1709 /* FIXME: duplicated code from 'process_result_with_request - refactor */
1710 if (dc->completed == dc->length)
1711 {
1712 /* download completed, signal */
1713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714 "Download completed, truncating file to desired length %llu\n",
1715 (unsigned long long) GNUNET_ntohll (
1716 dc->uri->data.chk.file_length));
1717 /* truncate file to size (since we store IBlocks at the end) */
1718 if (NULL != dc->filename)
1719 {
1720 if (0 != truncate (dc->filename,
1721 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1722 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1723 "truncate",
1724 dc->filename);
1725 }
1726 }
1727 }
1728 else
1729 GNUNET_log (
1730 GNUNET_ERROR_TYPE_DEBUG,
1731 "Reconstruction failed, need to download block at offset %llu, depth %u\n",
1732 (unsigned long long) offset,
1733 depth);
1734 break;
1735
1736 case BRS_DOWNLOAD_DOWN:
1737 break;
1738
1739 case BRS_DOWNLOAD_UP:
1740 break;
1741
1742 case BRS_ERROR:
1743 break;
1744
1745 default:
1746 GNUNET_assert (0);
1747 break;
1748 }
1749 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1750 if ((dr == dc->top_request) && (dr->state == BRS_DOWNLOAD_UP))
1751 check_completed (dc);
1752}
1753
1754
1755/**
1756 * Function called by the tree encoder to obtain a block of plaintext
1757 * data (for the lowest level of the tree).
1758 *
1759 * @param cls our 'struct ReconstructContext'
1760 * @param offset identifies which block to get
1761 * @param max (maximum) number of bytes to get; returning
1762 * fewer will also cause errors
1763 * @param buf where to copy the plaintext buffer
1764 * @param emsg location to store an error message (on error)
1765 * @return number of bytes copied to buf, 0 on error
1766 */
1767static size_t
1768fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg)
1769{
1770 struct GNUNET_FS_DownloadContext *dc = cls;
1771 struct GNUNET_DISK_FileHandle *fh = dc->rfh;
1772 ssize_t ret;
1773
1774 if (NULL != emsg)
1775 *emsg = NULL;
1776 if (offset != GNUNET_DISK_file_seek (fh, offset, GNUNET_DISK_SEEK_SET))
1777 {
1778 if (NULL != emsg)
1779 *emsg = GNUNET_strdup (strerror (errno));
1780 return 0;
1781 }
1782 ret = GNUNET_DISK_file_read (fh, buf, max);
1783 if (ret < 0)
1784 {
1785 if (NULL != emsg)
1786 *emsg = GNUNET_strdup (strerror (errno));
1787 return 0;
1788 }
1789 return ret;
1790}
1791
1792
1793/**
1794 * Task that creates the initial (top-level) download
1795 * request for the file.
1796 *
1797 * @param cls the 'struct GNUNET_FS_DownloadContext'
1798 */
1799void
1800GNUNET_FS_download_start_task_ (void *cls)
1801{
1802 struct GNUNET_FS_DownloadContext *dc = cls;
1803 struct GNUNET_FS_ProgressInfo pi;
1804 struct GNUNET_DISK_FileHandle *fh;
1805
1806 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start task running...\n");
1807 dc->task = NULL;
1808 if (0 == dc->length)
1809 {
1810 /* no bytes required! */
1811 if (NULL != dc->filename)
1812 {
1813 fh = GNUNET_DISK_file_open (dc->filename,
1814 GNUNET_DISK_OPEN_READWRITE
1815 | GNUNET_DISK_OPEN_CREATE
1816 | ((0 ==
1817 GNUNET_FS_uri_chk_get_file_size (dc->uri))
1818 ? GNUNET_DISK_OPEN_TRUNCATE
1819 : 0),
1820 GNUNET_DISK_PERM_USER_READ
1821 | GNUNET_DISK_PERM_USER_WRITE
1822 | GNUNET_DISK_PERM_GROUP_READ
1823 | GNUNET_DISK_PERM_OTHER_READ);
1824 GNUNET_DISK_file_close (fh);
1825 }
1826 GNUNET_FS_download_sync_ (dc);
1827 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1828 pi.value.download.specifics.start.meta = dc->meta;
1829 GNUNET_FS_download_make_status_ (&pi, dc);
1830 check_completed (dc);
1831 return;
1832 }
1833 if (NULL != dc->emsg)
1834 return;
1835 if (NULL == dc->top_request)
1836 {
1837 dc->top_request = create_download_request (NULL,
1838 0,
1839 dc->treedepth - 1,
1840 0,
1841 dc->offset,
1842 dc->length);
1843 dc->top_request->state = BRS_CHK_SET;
1844 dc->top_request->chk = (dc->uri->type == GNUNET_FS_URI_CHK)
1845 ? dc->uri->data.chk.chk
1846 : dc->uri->data.loc.fi.chk;
1847 /* signal start */
1848 GNUNET_FS_download_sync_ (dc);
1849 if (NULL != dc->search)
1850 GNUNET_FS_search_result_sync_ (dc->search);
1851 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1852 pi.value.download.specifics.start.meta = dc->meta;
1853 GNUNET_FS_download_make_status_ (&pi, dc);
1854 }
1855 GNUNET_FS_download_start_downloading_ (dc);
1856 /* attempt reconstruction from disk */
1857 if (GNUNET_YES == GNUNET_DISK_file_test (dc->filename))
1858 dc->rfh = GNUNET_DISK_file_open (dc->filename,
1859 GNUNET_DISK_OPEN_READ,
1860 GNUNET_DISK_PERM_NONE);
1861 if (dc->top_request->state == BRS_CHK_SET)
1862 {
1863 if (NULL != dc->rfh)
1864 {
1865 /* first, try top-down */
1866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1867 "Trying top-down reconstruction for `%s'\n",
1868 dc->filename);
1869 try_top_down_reconstruction (dc, dc->top_request);
1870 switch (dc->top_request->state)
1871 {
1872 case BRS_CHK_SET:
1873 break; /* normal */
1874
1875 case BRS_DOWNLOAD_DOWN:
1876 break; /* normal, some blocks already down */
1877
1878 case BRS_DOWNLOAD_UP:
1879 /* already done entirely, party! */
1880 if (NULL != dc->rfh)
1881 {
1882 /* avoid hanging on to file handle longer than
1883 * necessary */
1884 GNUNET_DISK_file_close (dc->rfh);
1885 dc->rfh = NULL;
1886 }
1887 return;
1888
1889 case BRS_ERROR:
1890 GNUNET_asprintf (&dc->emsg, _ ("Invalid URI"));
1891 GNUNET_FS_download_sync_ (dc);
1892 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1893 pi.value.download.specifics.error.message = dc->emsg;
1894 GNUNET_FS_download_make_status_ (&pi, dc);
1895 return;
1896
1897 default:
1898 GNUNET_assert (0);
1899 break;
1900 }
1901 }
1902 }
1903 /* attempt reconstruction from meta data */
1904 if ((GNUNET_FS_uri_chk_get_file_size (dc->uri) <= MAX_INLINE_SIZE) &&
1905 (NULL != dc->meta))
1906 {
1907 GNUNET_log (
1908 GNUNET_ERROR_TYPE_DEBUG,
1909 "Trying to find embedded meta data for download of size %llu with %u bytes MD\n",
1910 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (dc->uri),
1911 (unsigned int) GNUNET_CONTAINER_meta_data_get_serialized_size (dc->meta));
1912 GNUNET_CONTAINER_meta_data_iterate (dc->meta, &match_full_data, dc);
1913 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1914 {
1915 if (NULL != dc->rfh)
1916 {
1917 /* avoid hanging on to file handle longer than
1918 * necessary */
1919 GNUNET_DISK_file_close (dc->rfh);
1920 dc->rfh = NULL;
1921 }
1922 return; /* finished, status update was already done for us */
1923 }
1924 }
1925 if (NULL != dc->rfh)
1926 {
1927 /* finally, actually run bottom-up */
1928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1929 "Trying bottom-up reconstruction of file `%s'\n",
1930 dc->filename);
1931 dc->te =
1932 GNUNET_FS_tree_encoder_create (dc->h,
1933 GNUNET_FS_uri_chk_get_file_size (dc->uri),
1934 dc,
1935 &fh_reader,
1936 &reconstruct_cb,
1937 NULL,
1938 &reconstruct_cont);
1939 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1940 }
1941 else
1942 {
1943 /* simple, top-level download */
1944 dc->issue_requests = GNUNET_YES;
1945 schedule_block_download (dc, dc->top_request);
1946 }
1947 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1948 check_completed (dc);
1949}
1950
1951
1952void
1953GNUNET_FS_download_signal_suspend_ (void *cls)
1954{
1955 struct GNUNET_FS_DownloadContext *dc = cls;
1956 struct GNUNET_FS_ProgressInfo pi;
1957
1958 if (NULL != dc->top)
1959 GNUNET_FS_end_top (dc->h, dc->top);
1960 while (NULL != dc->child_head)
1961 GNUNET_FS_download_signal_suspend_ (dc->child_head);
1962 if (NULL != dc->search)
1963 {
1964 dc->search->download = NULL;
1965 dc->search = NULL;
1966 }
1967 if (NULL != dc->job_queue)
1968 {
1969 GNUNET_FS_dequeue_ (dc->job_queue);
1970 dc->job_queue = NULL;
1971 }
1972 if (NULL != dc->parent)
1973 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1974 dc->parent->child_tail,
1975 dc);
1976 if (NULL != dc->task)
1977 {
1978 GNUNET_SCHEDULER_cancel (dc->task);
1979 dc->task = NULL;
1980 }
1981 pi.status = GNUNET_FS_STATUS_DOWNLOAD_SUSPEND;
1982 GNUNET_FS_download_make_status_ (&pi, dc);
1983 if (NULL != dc->te)
1984 {
1985 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
1986 dc->te = NULL;
1987 }
1988 if (NULL != dc->rfh)
1989 {
1990 GNUNET_DISK_file_close (dc->rfh);
1991 dc->rfh = NULL;
1992 }
1993 GNUNET_FS_free_download_request_ (dc->top_request);
1994 if (NULL != dc->active)
1995 {
1996 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1997 dc->active = NULL;
1998 }
1999 GNUNET_free (dc->filename);
2000 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2001 GNUNET_FS_uri_destroy (dc->uri);
2002 GNUNET_free (dc->temp_filename);
2003 GNUNET_free (dc->serialization);
2004 GNUNET_assert (NULL == dc->job_queue);
2005 GNUNET_free (dc);
2006}
2007
2008
2009/**
2010 * Helper function to setup the download context.
2011 *
2012 * @param h handle to the file sharing subsystem
2013 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2014 * @param meta known metadata for the file (can be NULL)
2015 * @param filename where to store the file, maybe NULL (then no file is
2016 * created on disk and data must be grabbed from the callbacks)
2017 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2018 * can be NULL (in which case we will pick a name if needed); the temporary file
2019 * may already exist, in which case we will try to use the data that is there and
2020 * if it is not what is desired, will overwrite it
2021 * @param offset at what offset should we start the download (typically 0)
2022 * @param length how many bytes should be downloaded starting at offset
2023 * @param anonymity anonymity level to use for the download
2024 * @param options various options
2025 * @param cctx initial value for the client context for this download
2026 * @return context that can be used to control this download
2027 */
2028struct GNUNET_FS_DownloadContext *
2029create_download_context (struct GNUNET_FS_Handle *h,
2030 const struct GNUNET_FS_Uri *uri,
2031 const struct GNUNET_CONTAINER_MetaData *meta,
2032 const char *filename,
2033 const char *tempname,
2034 uint64_t offset,
2035 uint64_t length,
2036 uint32_t anonymity,
2037 enum GNUNET_FS_DownloadOptions options,
2038 void *cctx)
2039{
2040 struct GNUNET_FS_DownloadContext *dc;
2041
2042 GNUNET_assert (GNUNET_FS_uri_test_chk (uri) || GNUNET_FS_uri_test_loc (uri));
2043 if ((offset + length < offset) ||
2044 (offset + length > GNUNET_FS_uri_chk_get_file_size (uri)))
2045 {
2046 GNUNET_break (0);
2047 return NULL;
2048 }
2049 dc = GNUNET_new (struct GNUNET_FS_DownloadContext);
2050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051 "Starting download %p, %u bytes at offset %llu\n",
2052 dc,
2053 (unsigned int) length,
2054 (unsigned long long) offset);
2055 dc->h = h;
2056 dc->uri = GNUNET_FS_uri_dup (uri);
2057 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
2058 dc->client_info = cctx;
2059 dc->start_time = GNUNET_TIME_absolute_get ();
2060 if (NULL != filename)
2061 {
2062 dc->filename = GNUNET_strdup (filename);
2063 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
2064 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_size (filename,
2065 &dc->old_file_size,
2066 GNUNET_YES,
2067 GNUNET_YES));
2068 }
2069 if (GNUNET_FS_uri_test_loc (dc->uri))
2070 GNUNET_assert (GNUNET_OK ==
2071 GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target));
2072 dc->offset = offset;
2073 dc->length = length;
2074 dc->anonymity = anonymity;
2075 dc->options = options;
2076 dc->active =
2077 GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE),
2078 GNUNET_NO);
2079 dc->treedepth =
2080 GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri));
2081 if ((NULL == filename) && (is_recursive_download (dc)))
2082 {
2083 if (NULL != tempname)
2084 dc->temp_filename = GNUNET_strdup (tempname);
2085 else
2086 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2087 }
2088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2089 "Starting download `%s' of %llu bytes with tree depth %u\n",
2090 filename,
2091 (unsigned long long) length,
2092 dc->treedepth);
2093 GNUNET_assert (NULL == dc->job_queue);
2094 dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2095 return dc;
2096}
2097
2098
2099/**
2100 * Download parts of a file. Note that this will store
2101 * the blocks at the respective offset in the given file. Also, the
2102 * download is still using the blocking of the underlying FS
2103 * encoding. As a result, the download may *write* outside of the
2104 * given boundaries (if offset and length do not match the 32k FS
2105 * block boundaries). <p>
2106 *
2107 * This function should be used to focus a download towards a
2108 * particular portion of the file (optimization), not to strictly
2109 * limit the download to exactly those bytes.
2110 *
2111 * @param h handle to the file sharing subsystem
2112 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2113 * @param meta known metadata for the file (can be NULL)
2114 * @param filename where to store the file, maybe NULL (then no file is
2115 * created on disk and data must be grabbed from the callbacks)
2116 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2117 * can be NULL (in which case we will pick a name if needed); the temporary file
2118 * may already exist, in which case we will try to use the data that is there and
2119 * if it is not what is desired, will overwrite it
2120 * @param offset at what offset should we start the download (typically 0)
2121 * @param length how many bytes should be downloaded starting at offset
2122 * @param anonymity anonymity level to use for the download
2123 * @param options various options
2124 * @param cctx initial value for the client context for this download
2125 * @param parent parent download to associate this download with (use NULL
2126 * for top-level downloads; useful for manually-triggered recursive downloads)
2127 * @return context that can be used to control this download
2128 */
2129struct GNUNET_FS_DownloadContext *
2130GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
2131 const struct GNUNET_FS_Uri *uri,
2132 const struct GNUNET_CONTAINER_MetaData *meta,
2133 const char *filename,
2134 const char *tempname,
2135 uint64_t offset,
2136 uint64_t length,
2137 uint32_t anonymity,
2138 enum GNUNET_FS_DownloadOptions options,
2139 void *cctx,
2140 struct GNUNET_FS_DownloadContext *parent)
2141{
2142 struct GNUNET_FS_DownloadContext *dc;
2143
2144 dc = create_download_context (h,
2145 uri,
2146 meta,
2147 filename,
2148 tempname,
2149 offset,
2150 length,
2151 anonymity,
2152 options,
2153 cctx);
2154 if (NULL == dc)
2155 return NULL;
2156 dc->parent = parent;
2157 if (NULL != parent)
2158 GNUNET_CONTAINER_DLL_insert (parent->child_head, parent->child_tail, dc);
2159 else if (0 == (GNUNET_FS_DOWNLOAD_IS_PROBE & options))
2160 dc->top =
2161 GNUNET_FS_make_top (dc->h, &GNUNET_FS_download_signal_suspend_, dc);
2162 return dc;
2163}
2164
2165
2166/**
2167 * Download parts of a file based on a search result. The download
2168 * will be associated with the search result (and the association
2169 * will be preserved when serializing/deserializing the state).
2170 * If the search is stopped, the download will not be aborted but
2171 * be 'promoted' to a stand-alone download.
2172 *
2173 * As with the other download function, this will store
2174 * the blocks at the respective offset in the given file. Also, the
2175 * download is still using the blocking of the underlying FS
2176 * encoding. As a result, the download may *write* outside of the
2177 * given boundaries (if offset and length do not match the 32k FS
2178 * block boundaries). <p>
2179 *
2180 * The given range can be used to focus a download towards a
2181 * particular portion of the file (optimization), not to strictly
2182 * limit the download to exactly those bytes.
2183 *
2184 * @param h handle to the file sharing subsystem
2185 * @param sr the search result to use for the download (determines uri and
2186 * meta data and associations)
2187 * @param filename where to store the file, maybe NULL (then no file is
2188 * created on disk and data must be grabbed from the callbacks)
2189 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2190 * can be NULL (in which case we will pick a name if needed); the temporary file
2191 * may already exist, in which case we will try to use the data that is there and
2192 * if it is not what is desired, will overwrite it
2193 * @param offset at what offset should we start the download (typically 0)
2194 * @param length how many bytes should be downloaded starting at offset
2195 * @param anonymity anonymity level to use for the download
2196 * @param options various download options
2197 * @param cctx initial value for the client context for this download
2198 * @return context that can be used to control this download
2199 */
2200struct GNUNET_FS_DownloadContext *
2201GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h,
2202 struct GNUNET_FS_SearchResult *sr,
2203 const char *filename,
2204 const char *tempname,
2205 uint64_t offset,
2206 uint64_t length,
2207 uint32_t anonymity,
2208 enum GNUNET_FS_DownloadOptions options,
2209 void *cctx)
2210{
2211 struct GNUNET_FS_DownloadContext *dc;
2212
2213 if ((NULL == sr) || (NULL != sr->download))
2214 {
2215 GNUNET_break (0);
2216 return NULL;
2217 }
2218 dc = create_download_context (h,
2219 sr->uri,
2220 sr->meta,
2221 filename,
2222 tempname,
2223 offset,
2224 length,
2225 anonymity,
2226 options,
2227 cctx);
2228 if (NULL == dc)
2229 return NULL;
2230 dc->search = sr;
2231 sr->download = dc;
2232 if (NULL != sr->probe_ctx)
2233 {
2234 GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
2235 sr->probe_ctx = NULL;
2236 GNUNET_FS_stop_probe_ping_task_ (sr);
2237 }
2238 return dc;
2239}
2240
2241
2242/**
2243 * Start the downloading process (by entering the queue).
2244 *
2245 * @param dc our download context
2246 */
2247void
2248GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc)
2249{
2250 if (dc->completed == dc->length)
2251 return;
2252 if (NULL != dc->mq)
2253 return; /* already running */
2254 GNUNET_assert (NULL == dc->job_queue);
2255 GNUNET_assert (NULL == dc->task);
2256 GNUNET_assert (NULL != dc->active);
2257 dc->job_queue =
2258 GNUNET_FS_queue_ (dc->h,
2259 &activate_fs_download,
2260 &deactivate_fs_download,
2261 dc,
2262 (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE,
2263 (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
2264 ? GNUNET_FS_QUEUE_PRIORITY_NORMAL
2265 : GNUNET_FS_QUEUE_PRIORITY_PROBE);
2266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2267 "Download %p put into queue as job %p\n",
2268 dc,
2269 dc->job_queue);
2270}
2271
2272
2273/**
2274 * Suspend a download.
2275 *
2276 * @param dc handle for the download
2277 */
2278void
2279GNUNET_FS_download_suspend (struct GNUNET_FS_DownloadContext *dc)
2280{
2281 deactivate_fs_download (dc);
2282}
2283
2284
2285/**
2286 * Resume a suspended download.
2287 *
2288 * @param dc handle for the download
2289 */
2290void
2291GNUNET_FS_download_resume (struct GNUNET_FS_DownloadContext *dc)
2292{
2293 struct GNUNET_FS_ProgressInfo pi;
2294
2295 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
2296 GNUNET_FS_download_make_status_ (&pi, dc);
2297
2298 GNUNET_assert (NULL == dc->task);
2299 dc->job_queue =
2300 GNUNET_FS_queue_ (dc->h,
2301 &activate_fs_download,
2302 &deactivate_fs_download,
2303 dc,
2304 (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE,
2305 (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
2306 ? GNUNET_FS_QUEUE_PRIORITY_NORMAL
2307 : GNUNET_FS_QUEUE_PRIORITY_PROBE);
2308}
2309
2310
2311/**
2312 * Stop a download (aborts if download is incomplete).
2313 *
2314 * @param dc handle for the download
2315 * @param do_delete delete files of incomplete downloads
2316 */
2317void
2318GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete)
2319{
2320 struct GNUNET_FS_ProgressInfo pi;
2321 int have_children;
2322 int search_was_null;
2323
2324 if (NULL != dc->top)
2325 GNUNET_FS_end_top (dc->h, dc->top);
2326 if (NULL != dc->task)
2327 {
2328 GNUNET_SCHEDULER_cancel (dc->task);
2329 dc->task = NULL;
2330 }
2331 search_was_null = (NULL == dc->search);
2332 if (NULL != dc->search)
2333 {
2334 dc->search->download = NULL;
2335 GNUNET_FS_search_result_sync_ (dc->search);
2336 dc->search = NULL;
2337 }
2338 if (NULL != dc->job_queue)
2339 {
2340 GNUNET_FS_dequeue_ (dc->job_queue);
2341 dc->job_queue = NULL;
2342 }
2343 if (NULL != dc->te)
2344 {
2345 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
2346 dc->te = NULL;
2347 }
2348 have_children = (NULL != dc->child_head) ? GNUNET_YES : GNUNET_NO;
2349 while (NULL != dc->child_head)
2350 GNUNET_FS_download_stop (dc->child_head, do_delete);
2351 if (NULL != dc->parent)
2352 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
2353 dc->parent->child_tail,
2354 dc);
2355 if (NULL != dc->serialization)
2356 GNUNET_FS_remove_sync_file_ (dc->h,
2357 ((NULL != dc->parent) || (! search_was_null))
2358 ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD
2359 : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2360 dc->serialization);
2361 if ((GNUNET_YES == have_children) && (NULL == dc->parent))
2362 GNUNET_FS_remove_sync_dir_ (dc->h,
2363 (! search_was_null)
2364 ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD
2365 : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2366 dc->serialization);
2367 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
2368 GNUNET_FS_download_make_status_ (&pi, dc);
2369 GNUNET_FS_free_download_request_ (dc->top_request);
2370 dc->top_request = NULL;
2371 if (NULL != dc->active)
2372 {
2373 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2374 dc->active = NULL;
2375 }
2376 if (NULL != dc->filename)
2377 {
2378 if ((dc->completed != dc->length) && (GNUNET_YES == do_delete))
2379 {
2380 if ((0 != unlink (dc->filename)) && (ENOENT != errno))
2381 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
2382 "unlink",
2383 dc->filename);
2384 }
2385 GNUNET_free (dc->filename);
2386 }
2387 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2388 GNUNET_FS_uri_destroy (dc->uri);
2389 if (NULL != dc->temp_filename)
2390 {
2391 if (0 != unlink (dc->temp_filename))
2392 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2393 "unlink",
2394 dc->temp_filename);
2395 GNUNET_free (dc->temp_filename);
2396 }
2397 GNUNET_free (dc->serialization);
2398 GNUNET_assert (NULL == dc->job_queue);
2399 GNUNET_free (dc);
2400}
2401
2402
2403/* end of fs_download.c */