2 This file is part of GNUnet.
3 Copyright (C) 2001-2012 GNUnet e.V.
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.
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.
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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
21 * @file fs/fs_download.c
22 * @brief download methods
23 * @author Christian Grothoff
26 #include "gnunet_constants.h"
27 #include "gnunet_fs_service.h"
33 * Determine if the given download (options and meta data) should cause
34 * use to try to do a recursive download.
37 is_recursive_download (struct GNUNET_FS_DownloadContext *dc)
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))))));
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).
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
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
67 compute_disk_offset (uint64_t fsize, uint64_t off, unsigned int depth)
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"? */
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;
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++)
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;
91 return loff + ioff * sizeof(struct ContentHashKey);
96 * Fill in all of the generic fields for a download event and call the
99 * @param pi structure to fill in
100 * @param dc overall download context
103 GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
104 struct GNUNET_FS_DownloadContext *dc)
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;
124 if (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
125 dc->client_info = dc->h->upcb (dc->h->upcb_cls, pi);
127 dc->client_info = GNUNET_FS_search_probe_progress_ (NULL, pi);
132 * Closure for iterator processing results.
134 struct ProcessResultClosure
139 struct GNUNET_HashCode query;
142 * Data found in P2P network.
147 * Our download context.
149 struct GNUNET_FS_DownloadContext *dc;
152 * When did we last transmit the request?
154 struct GNUNET_TIME_Absolute last_transmission;
157 * Number of bytes in data.
164 enum GNUNET_BLOCK_Type type;
167 * Flag to indicate if this block should be stored on disk.
172 * how much respect did we offer to get this reply?
174 uint32_t respect_offered;
177 * how often did we transmit the query?
179 uint32_t num_transmissions;
184 * Iterator over entries in the pending requests in the 'active' map for the
185 * reply that we just got.
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
193 process_result_with_request (void *cls,
194 const struct GNUNET_HashCode *key,
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.
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
212 encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc,
213 const struct ContentHashKey *chk,
214 struct DownloadRequest *dr,
219 struct ProcessResultClosure prc;
221 struct GNUNET_CRYPTO_SymmetricSessionKey sk;
222 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
223 struct GNUNET_HashCode query;
225 GNUNET_CRYPTO_hash_to_aes_key (&chk->key, &sk, &iv);
226 if (-1 == GNUNET_CRYPTO_symmetric_encrypt (block, len, &sk, &iv, enc))
229 return GNUNET_SYSERR;
231 GNUNET_CRYPTO_hash (enc, len, &query);
232 if (0 != memcmp (&query, &chk->query, sizeof(struct GNUNET_HashCode)))
235 return GNUNET_SYSERR;
238 GNUNET_ERROR_TYPE_DEBUG,
239 "Matching %u byte block for `%s' at offset %llu already present, no need for download!\n",
242 (unsigned long long) dr->offset);
243 /* already got it! */
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);
258 * We've lost our connection with the FS service.
259 * Re-establish it and re-transmit all of our
262 * @param dc download context that is having trouble
265 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
269 * We found an entry in a directory. Check if the respective child
270 * already exists and if not create the respective child download.
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)
280 trigger_recursive_download (void *cls,
281 const char *filename,
282 const struct GNUNET_FS_Uri *uri,
283 const struct GNUNET_CONTAINER_MetaData *meta,
289 * We're done downloading a directory. Open the file and
290 * trigger all of the (remaining) child downloads.
292 * @param dc context of download that just completed
295 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
300 struct GNUNET_DISK_FileHandle *h;
301 struct GNUNET_DISK_MapHandle *m;
303 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
304 size = (size_t) size64;
305 if (size64 != (uint64_t) size)
308 GNUNET_ERROR_TYPE_ERROR,
310 "Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
313 if (NULL != dc->filename)
315 h = GNUNET_DISK_file_open (dc->filename,
316 GNUNET_DISK_OPEN_READ,
317 GNUNET_DISK_PERM_NONE);
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);
328 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
331 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
332 _ ("Directory too large for system address space\n"));
337 GNUNET_FS_directory_list_contents (size,
340 &trigger_recursive_download,
344 GNUNET_ERROR_TYPE_WARNING,
346 "Failed to access full directroy contents of `%s' for recursive download\n"),
349 GNUNET_DISK_file_unmap (m);
351 GNUNET_DISK_file_close (h);
352 if (NULL == dc->filename)
354 if (0 != unlink (dc->temp_filename))
355 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
358 GNUNET_free (dc->temp_filename);
359 dc->temp_filename = NULL;
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).
372 * @param dc download to check for completion of children
375 check_completed (struct GNUNET_FS_DownloadContext *dc)
377 struct GNUNET_FS_ProgressInfo pi;
378 struct GNUNET_FS_DownloadContext *pos;
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)
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 */
391 /* All of our children are done, so mark this download done */
392 dc->has_finished = GNUNET_YES;
393 if (NULL != dc->job_queue)
395 GNUNET_FS_dequeue_ (dc->job_queue);
396 dc->job_queue = NULL;
398 if (NULL != dc->task)
400 GNUNET_SCHEDULER_cancel (dc->task);
405 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
408 GNUNET_FS_download_sync_ (dc);
410 /* signal completion */
411 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
412 GNUNET_FS_download_make_status_ (&pi, dc);
414 /* let parent know */
415 if (NULL != dc->parent)
416 check_completed (dc->parent);
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.
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
431 try_match_block (struct GNUNET_FS_DownloadContext *dc,
432 struct DownloadRequest *dr,
436 struct GNUNET_FS_ProgressInfo pi;
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;
444 struct DownloadRequest *drc;
445 struct GNUNET_DISK_FileHandle *fh;
452 odata_len = data_len;
453 if (BRS_DOWNLOAD_UP == dr->state)
457 if ((dc->offset > 0) ||
458 (dc->length < GNUNET_ntohll (dc->uri->data.chk.file_length)))
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;
468 complete = GNUNET_YES;
469 for (i = 0; i < dr->num_children; i++)
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;
478 if (GNUNET_YES != complete)
480 data = (const char *) chks;
481 dlen = dr->num_children * sizeof(struct ContentHashKey);
485 if (dr->offset > data_len)
487 dlen = GNUNET_MIN (data_len - dr->offset, DBLOCK_SIZE);
489 GNUNET_CRYPTO_hash (&data[dr->offset], dlen, &in_chk.key);
490 GNUNET_CRYPTO_hash_to_aes_key (&in_chk.key, &sk, &iv);
492 GNUNET_CRYPTO_symmetric_encrypt (&data[dr->offset], dlen, &sk, &iv, enc))
497 GNUNET_CRYPTO_hash (enc, dlen, &in_chk.query);
502 dr->state = BRS_RECONSTRUCT_META_UP;
506 if (0 != memcmp (&in_chk, &dr->chk, sizeof(struct ContentHashKey)))
508 /* other peer provided bogus meta data */
512 /* write block to disk */
513 fn = (NULL != dc->filename) ? dc->filename : dc->temp_filename;
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);
526 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
527 GNUNET_asprintf (&dc->emsg,
528 _ ("Failed to open file `%s' for writing"),
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);
537 if (data_len != GNUNET_DISK_file_write (fh, odata, odata_len))
539 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "write", fn);
540 GNUNET_asprintf (&dc->emsg,
541 _ ("Failed to open file `%s' for writing"),
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);
550 GNUNET_DISK_file_close (fh);
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,
571 check_completed (dc);
575 /* how did we get here? */
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.
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 (i.e. '<zlib>' for zlib being
590 * used in the main libextractor library and yielding
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
601 match_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,
609 struct GNUNET_FS_DownloadContext *dc = cls;
611 if (EXTRACTOR_METATYPE_GNUNET_FULL_DATA != type)
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)
619 return 1; /* bogus meta data */
621 try_match_block (dc, dc->top_request, data, data_len);
627 * Set the state of the given download request to
628 * BRS_DOWNLOAD_UP and propagate it up the tree.
630 * @param dr download request that is done
633 propagate_up (struct DownloadRequest *dr)
639 dr->state = BRS_DOWNLOAD_UP;
643 for (i = 0; i < dr->num_children; i++)
644 if (dr->children[i]->state != BRS_DOWNLOAD_UP)
647 while (i == dr->num_children);
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
658 * @param dc overall download this block belongs to
659 * @param dr block to reconstruct
662 try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc,
663 struct DownloadRequest *dr)
666 char block[DBLOCK_SIZE];
667 struct GNUNET_HashCode key;
671 struct DownloadRequest *drc;
672 uint64_t child_block_size;
673 const struct ContentHashKey *chks;
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))
687 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "seek", dc->filename);
688 return; /* failure */
690 if (len != GNUNET_DISK_file_read (dc->rfh, block, len))
692 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "read", dc->filename);
693 return; /* failure */
695 GNUNET_CRYPTO_hash (block, len, &key);
696 if (0 != memcmp (&key, &dr->chk.key, sizeof(struct GNUNET_HashCode)))
697 return; /* mismatch */
699 encrypt_existing_match (dc, &dr->chk, dr, block, len, GNUNET_NO))
701 /* hash matches but encrypted block does not, really bad */
702 dr->state = BRS_ERROR;
704 while (NULL != dr->parent)
707 dr->state = BRS_ERROR;
712 dr->state = BRS_DOWNLOAD_DOWN;
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++)
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)
725 drc->state = BRS_CHK_SET;
726 drc->chk = chks[drc->chk_idx];
727 try_top_down_reconstruction (dc, drc);
729 if (BRS_DOWNLOAD_UP != drc->state)
730 up_done = GNUNET_NO; /* children not all done */
732 if (GNUNET_YES == up_done)
733 propagate_up (dr); /* children all done (or no children...) */
738 * Add entries to the message queue.
740 * @param cls our download context
742 * @param entry entry of type `struct DownloadRequest`
746 retry_entry (void *cls, const struct GNUNET_HashCode *key, void *entry)
748 struct GNUNET_FS_DownloadContext *dc = cls;
749 struct DownloadRequest *dr = entry;
750 struct SearchMessage *sm;
751 struct GNUNET_MQ_Envelope *env;
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);
757 sm->options = htonl (GNUNET_FS_SEARCH_OPTION_NONE);
759 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_DBLOCK);
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);
771 * Schedule the download of the specified block in the tree.
773 * @param dc overall download this block belongs to
774 * @param dr request to schedule
777 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
778 struct DownloadRequest *dr)
788 case BRS_RECONSTRUCT_DOWN:
792 case BRS_RECONSTRUCT_META_UP:
796 case BRS_RECONSTRUCT_UP:
801 /* normal case, start download */
804 case BRS_DOWNLOAD_DOWN:
805 for (i = 0; i < dr->num_children; i++)
806 schedule_block_download (dc, dr->children[i]);
809 case BRS_DOWNLOAD_UP:
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,
821 GNUNET_h2s (&dr->chk.query));
822 if (GNUNET_NO != GNUNET_CONTAINER_multihashmap_contains_value (dc->active,
825 return; /* already active */
826 GNUNET_CONTAINER_multihashmap_put (dc->active,
829 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
831 return; /* download not active */
832 retry_entry (dc, &dr->chk.query, dr);
836 #define GNUNET_FS_URI_CHK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_CHK_INFIX
839 * We found an entry in a directory. Check if the respective child
840 * already exists and if not create the respective child download.
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)
850 trigger_recursive_download (void *cls,
851 const char *filename,
852 const struct GNUNET_FS_Uri *uri,
853 const struct GNUNET_CONTAINER_MetaData *meta,
857 struct GNUNET_FS_DownloadContext *dc = cls;
858 struct GNUNET_FS_DownloadContext *cpos;
869 return; /* entry for the directory itself */
870 cpos = dc->child_head;
873 if ((GNUNET_FS_uri_test_equal (uri, cpos->uri)) ||
874 ((NULL != filename) && (0 == strcmp (cpos->filename, filename))))
879 return; /* already exists */
881 if (NULL == filename)
883 fn = GNUNET_FS_meta_data_suggest_filename (meta);
886 us = GNUNET_FS_uri_to_string (uri);
887 fn = GNUNET_strdup (&us[strlen (GNUNET_FS_URI_CHK_PREFIX)]);
890 else if ('.' == fn[0])
893 us = GNUNET_FS_uri_to_string (uri);
894 GNUNET_asprintf (&fn,
896 &us[strlen (GNUNET_FS_URI_CHK_PREFIX)],
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, "\\")))
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, "../")))
917 if (NULL == dc->filename)
923 dn = GNUNET_strdup (dc->filename);
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))))
941 GNUNET_asprintf (&full_name,
946 GNUNET_FS_DIRECTORY_EXT);
950 GNUNET_asprintf (&full_name, "%s%s%s", dn, DIR_SEPARATOR_STR, sfn);
955 if ((NULL != full_name) &&
956 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (full_name)))
958 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
960 "Failed to create directory for recursive download of `%s'\n"),
962 GNUNET_free (full_name);
963 GNUNET_free_non_null (fn);
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 (
973 GNUNET_FS_download_start (dc->h,
979 GNUNET_FS_uri_chk_get_file_size (uri),
984 GNUNET_free_non_null (full_name);
985 GNUNET_free_non_null (temp_name);
986 GNUNET_free_non_null (fn);
991 * (recursively) free download request structure
993 * @param dr request to free
996 GNUNET_FS_free_download_request_ (struct DownloadRequest *dr)
1000 for (unsigned int i = 0; i < dr->num_children; i++)
1001 GNUNET_FS_free_download_request_ (dr->children[i]);
1002 GNUNET_free_non_null (dr->children);
1008 * Iterator over entries in the pending requests in the 'active' map for the
1009 * reply that we just got.
1011 * @param cls closure (our `struct ProcessResultClosure`)
1012 * @param key query for the given value / request
1013 * @param value value in the hash map (a `struct DownloadRequest`)
1014 * @return #GNUNET_YES (we should continue to iterate); unless serious error
1017 process_result_with_request (void *cls,
1018 const struct GNUNET_HashCode *key,
1021 struct ProcessResultClosure *prc = cls;
1022 struct DownloadRequest *dr = value;
1023 struct GNUNET_FS_DownloadContext *dc = prc->dc;
1024 struct DownloadRequest *drc;
1025 struct GNUNET_DISK_FileHandle *fh = NULL;
1026 struct GNUNET_CRYPTO_SymmetricSessionKey skey;
1027 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1029 struct GNUNET_FS_ProgressInfo pi;
1034 struct ContentHashKey *chkarr;
1037 GNUNET_ERROR_TYPE_DEBUG,
1038 "Received %u byte block `%s' matching pending request at depth %u and offset %llu/%llu\n",
1039 (unsigned int) prc->size,
1042 (unsigned long long) dr->offset,
1043 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
1044 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (
1045 dc->uri->data.chk.file_length),
1048 if (prc->size != bs)
1053 "Internal error or bogus download URI (expected %u bytes at depth %u and offset %llu/%llu, got %u bytes)"),
1056 (unsigned long long) dr->offset,
1057 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length),
1059 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s\n", dc->emsg);
1060 while (NULL != dr->parent)
1062 dr->state = BRS_ERROR;
1065 dr->state = BRS_ERROR;
1069 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &prc->query, dr);
1070 GNUNET_CRYPTO_hash_to_aes_key (&dr->chk.key, &skey, &iv);
1072 GNUNET_CRYPTO_symmetric_decrypt (prc->data, prc->size, &skey, &iv, pt))
1075 dc->emsg = GNUNET_strdup (_ ("internal error decrypting content"));
1078 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
1082 if ((GNUNET_YES == prc->do_store) &&
1083 ((NULL != dc->filename) || (is_recursive_download (dc))) &&
1084 ((dr->depth == dc->treedepth) ||
1085 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES))))
1087 fh = GNUNET_DISK_file_open (NULL != dc->filename ? dc->filename
1088 : dc->temp_filename,
1089 GNUNET_DISK_OPEN_READWRITE
1090 | GNUNET_DISK_OPEN_CREATE,
1091 GNUNET_DISK_PERM_USER_READ
1092 | GNUNET_DISK_PERM_USER_WRITE
1093 | GNUNET_DISK_PERM_GROUP_READ
1094 | GNUNET_DISK_PERM_OTHER_READ);
1097 GNUNET_asprintf (&dc->emsg,
1098 _ ("Download failed: could not open file `%s': %s"),
1103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1104 "Saving decrypted block to disk at offset %llu\n",
1105 (unsigned long long) off);
1106 if ((off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)))
1108 GNUNET_asprintf (&dc->emsg,
1109 _ ("Failed to seek to offset %llu in file `%s': %s"),
1110 (unsigned long long) off,
1115 if (prc->size != GNUNET_DISK_file_write (fh, pt, prc->size))
1119 _ ("Failed to write block of %u bytes at offset %llu in file `%s': %s"),
1120 (unsigned int) prc->size,
1121 (unsigned long long) off,
1126 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
1132 /* DBLOCK, update progress and try recursion if applicable */
1134 if (dr->offset < dc->offset)
1136 /* starting offset begins in the middle of pt,
1137 * do not count first bytes as progress */
1138 GNUNET_assert (app > (dc->offset - dr->offset));
1139 app -= (dc->offset - dr->offset);
1141 if (dr->offset + prc->size > dc->offset + dc->length)
1143 /* end of block is after relevant range,
1144 * do not count last bytes as progress */
1145 GNUNET_assert (app >
1146 (dr->offset + prc->size) - (dc->offset + dc->length));
1147 app -= (dr->offset + prc->size) - (dc->offset + dc->length);
1149 dc->completed += app;
1151 /* do recursive download if option is set and either meta data
1152 * says it is a directory or if no meta data is given AND filename
1153 * ends in '.gnd' (top-level case) */
1154 if (is_recursive_download (dc))
1155 GNUNET_FS_directory_list_contents (prc->size,
1158 &trigger_recursive_download,
1161 GNUNET_assert (dc->completed <= dc->length);
1162 dr->state = BRS_DOWNLOAD_DOWN;
1163 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1164 pi.value.download.specifics.progress.data = pt;
1165 pi.value.download.specifics.progress.offset = dr->offset;
1166 pi.value.download.specifics.progress.data_len = prc->size;
1167 pi.value.download.specifics.progress.depth = dr->depth;
1168 pi.value.download.specifics.progress.respect_offered = prc->respect_offered;
1169 pi.value.download.specifics.progress.num_transmissions =
1170 prc->num_transmissions;
1171 if (prc->last_transmission.abs_value_us !=
1172 GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
1173 pi.value.download.specifics.progress.block_download_duration =
1174 GNUNET_TIME_absolute_get_duration (prc->last_transmission);
1176 pi.value.download.specifics.progress.block_download_duration =
1177 GNUNET_TIME_UNIT_ZERO; /* found locally */
1178 GNUNET_FS_download_make_status_ (&pi, dc);
1182 if (dc->completed == dc->length)
1184 /* download completed, signal */
1185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1186 "Download completed, truncating file to desired length %llu\n",
1187 (unsigned long long) GNUNET_ntohll (
1188 dc->uri->data.chk.file_length));
1189 /* truncate file to size (since we store IBlocks at the end) */
1190 if (NULL != dc->filename)
1192 if (0 != truncate (dc->filename,
1193 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1194 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1198 GNUNET_assert (0 == dr->depth);
1199 check_completed (dc);
1203 /* bottom of the tree, no child downloads possible, just sync */
1204 GNUNET_FS_download_sync_ (dc);
1209 GNUNET_ERROR_TYPE_DEBUG,
1210 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1212 (unsigned long long) dr->offset);
1213 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1214 chkarr = (struct ContentHashKey *) pt;
1215 for (i = dr->num_children - 1; i >= 0; i--)
1217 drc = dr->children[i];
1221 if ((drc->chk_idx + 1) * sizeof(struct ContentHashKey) > prc->size)
1223 /* 'chkarr' does not have enough space for this chk_idx;
1227 dc->emsg = GNUNET_strdup (_ ("internal error decoding tree"));
1230 drc->chk = chkarr[drc->chk_idx];
1231 drc->state = BRS_CHK_SET;
1232 if (GNUNET_YES == dc->issue_requests)
1233 schedule_block_download (dc, drc);
1236 case BRS_RECONSTRUCT_DOWN:
1240 case BRS_RECONSTRUCT_META_UP:
1244 case BRS_RECONSTRUCT_UP:
1252 case BRS_DOWNLOAD_DOWN:
1256 case BRS_DOWNLOAD_UP:
1269 GNUNET_FS_download_sync_ (dc);
1274 GNUNET_DISK_file_close (fh);
1275 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1276 pi.value.download.specifics.error.message = dc->emsg;
1277 GNUNET_FS_download_make_status_ (&pi, dc);
1278 GNUNET_MQ_destroy (dc->mq);
1280 GNUNET_FS_free_download_request_ (dc->top_request);
1281 dc->top_request = NULL;
1282 if (NULL != dc->job_queue)
1284 GNUNET_FS_dequeue_ (dc->job_queue);
1285 dc->job_queue = NULL;
1287 GNUNET_FS_download_sync_ (dc);
1293 * Type of a function to call when we check the PUT message
1296 * @param cls closure
1297 * @param msg message received
1300 check_put (void *cls, const struct ClientPutMessage *cm)
1302 /* any varsize length is OK */
1308 * Type of a function to call when we receive a message
1311 * @param cls closure
1312 * @param msg message received
1315 handle_put (void *cls, const struct ClientPutMessage *cm)
1317 struct GNUNET_FS_DownloadContext *dc = cls;
1318 uint16_t msize = ntohs (cm->header.size) - sizeof(*cm);
1319 struct ProcessResultClosure prc;
1323 prc.last_transmission = GNUNET_TIME_absolute_ntoh (cm->last_transmission);
1325 prc.type = ntohl (cm->type);
1326 prc.do_store = GNUNET_YES;
1327 prc.respect_offered = ntohl (cm->respect_offered);
1328 prc.num_transmissions = ntohl (cm->num_transmissions);
1329 GNUNET_CRYPTO_hash (prc.data, msize, &prc.query);
1330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1331 "Received result for query `%s' from FS service\n",
1332 GNUNET_h2s (&prc.query));
1333 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1335 &process_result_with_request,
1341 * Generic error handler, called with the appropriate error code and
1342 * the same closure specified at the creation of the message queue.
1343 * Not every message queue implementation supports an error handler.
1345 * @param cls closure with the `struct GNUNET_FS_DownloadContext *`
1346 * @param error error code
1349 download_mq_error_handler (void *cls, enum GNUNET_MQ_Error error)
1351 struct GNUNET_FS_DownloadContext *dc = cls;
1355 GNUNET_MQ_destroy (dc->mq);
1358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359 "Transmitting download request failed, trying to reconnect\n");
1365 * Reconnect to the FS service and transmit our queries NOW.
1367 * @param cls our download context
1370 do_reconnect (void *cls)
1372 struct GNUNET_FS_DownloadContext *dc = cls;
1373 struct GNUNET_MQ_MessageHandler handlers[] =
1374 { GNUNET_MQ_hd_var_size (put,
1375 GNUNET_MESSAGE_TYPE_FS_PUT,
1376 struct ClientPutMessage,
1378 GNUNET_MQ_handler_end () };
1381 dc->mq = GNUNET_CLIENT_connect (dc->h->cfg,
1384 &download_mq_error_handler,
1388 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1389 "Connecting to `%s'-service failed, will try again.\n",
1394 GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1399 * We've lost our connection with the FS service.
1400 * Re-establish it and re-transmit all of our
1403 * @param dc download context that is having trouble
1406 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1411 "Moving all requests back to pending list\n");
1412 GNUNET_MQ_destroy (dc->mq);
1415 if (0 == dc->reconnect_backoff.rel_value_us)
1416 dc->reconnect_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1418 dc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (dc->reconnect_backoff);
1420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1421 "Will try to reconnect in %s\n",
1422 GNUNET_STRINGS_relative_time_to_string (dc->reconnect_backoff,
1424 GNUNET_break (NULL != dc->job_queue);
1426 GNUNET_SCHEDULER_add_delayed (dc->reconnect_backoff, &do_reconnect, dc);
1431 * We're allowed to ask the FS service for our blocks. Start the download.
1433 * @param cls the 'struct GNUNET_FS_DownloadContext'
1434 * @param mq handle to use for communcation with FS (we must destroy it!)
1437 activate_fs_download (void *cls)
1439 struct GNUNET_FS_DownloadContext *dc = cls;
1440 struct GNUNET_FS_ProgressInfo pi;
1442 GNUNET_assert (NULL == dc->mq);
1443 GNUNET_assert (NULL != dc->active);
1446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download activated\n");
1447 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1448 GNUNET_FS_download_make_status_ (&pi, dc);
1453 * We must stop to ask the FS service for our blocks. Pause the download.
1455 * @param cls the `struct GNUNET_FS_DownloadContext`
1458 deactivate_fs_download (void *cls)
1460 struct GNUNET_FS_DownloadContext *dc = cls;
1461 struct GNUNET_FS_ProgressInfo pi;
1463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download deactivated\n");
1466 GNUNET_MQ_destroy (dc->mq);
1469 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1470 GNUNET_FS_download_make_status_ (&pi, dc);
1475 * (recursively) Create a download request structure.
1477 * @param parent parent of the current entry
1478 * @param chk_idx index of the chk for this block in the parent block
1479 * @param depth depth of the current entry, 0 are the DBLOCKs,
1480 * top level block is 'dc->treedepth - 1'
1481 * @param dr_offset offset in the original file this block maps to
1482 * (as in, offset of the first byte of the first DBLOCK
1483 * in the subtree rooted in the returned download request tree)
1484 * @param file_start_offset desired starting offset for the download
1485 * in the original file; requesting tree should not contain
1486 * DBLOCKs prior to the file_start_offset
1487 * @param desired_length desired number of bytes the user wanted to access
1488 * (from file_start_offset). Resulting tree should not contain
1489 * DBLOCKs after file_start_offset + file_length.
1490 * @return download request tree for the given range of DBLOCKs at
1491 * the specified depth
1493 static struct DownloadRequest *
1494 create_download_request (struct DownloadRequest *parent,
1495 unsigned int chk_idx,
1498 uint64_t file_start_offset,
1499 uint64_t desired_length)
1501 struct DownloadRequest *dr;
1503 unsigned int head_skip;
1504 uint64_t child_block_size;
1506 dr = GNUNET_new (struct DownloadRequest);
1507 dr->parent = parent;
1509 dr->offset = dr_offset;
1510 dr->chk_idx = chk_idx;
1513 child_block_size = GNUNET_FS_tree_compute_tree_size (depth - 1);
1515 /* calculate how many blocks at this level are not interesting
1516 * from the start (rounded down), either because of the requested
1517 * file offset or because this IBlock is further along */
1518 if (dr_offset < file_start_offset)
1520 head_skip = (file_start_offset - dr_offset) / child_block_size;
1527 /* calculate index of last block at this level that is interesting (rounded up) */
1529 (file_start_offset + desired_length - dr_offset) / child_block_size;
1530 if (dr->num_children * child_block_size <
1531 file_start_offset + desired_length - dr_offset)
1532 dr->num_children++; /* round up */
1533 GNUNET_assert (dr->num_children > head_skip);
1534 dr->num_children -= head_skip;
1535 if (dr->num_children > CHK_PER_INODE)
1536 dr->num_children = CHK_PER_INODE; /* cap at max */
1537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1538 "Block at offset %llu and depth %u has %u children\n",
1539 (unsigned long long) dr_offset,
1543 /* now we can get the total number of *interesting* children for this block */
1545 /* why else would we have gotten here to begin with? (that'd be a bad logic error) */
1546 GNUNET_assert (dr->num_children > 0);
1548 dr->children = GNUNET_new_array (dr->num_children, struct DownloadRequest *);
1549 for (i = 0; i < dr->num_children; i++)
1552 create_download_request (dr,
1555 dr_offset + (i + head_skip) * child_block_size,
1564 * Continuation after a possible attempt to reconstruct
1565 * the current IBlock from the existing file.
1567 * @param cls the 'struct ReconstructContext'
1570 reconstruct_cont (void *cls)
1572 struct GNUNET_FS_DownloadContext *dc = cls;
1574 /* clean up state from tree encoder */
1575 if (NULL != dc->task)
1577 GNUNET_SCHEDULER_cancel (dc->task);
1580 if (NULL != dc->rfh)
1582 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
1585 /* start "normal" download */
1586 dc->issue_requests = GNUNET_YES;
1587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting normal download\n");
1588 schedule_block_download (dc, dc->top_request);
1593 * Task requesting the next block from the tree encoder.
1595 * @param cls the 'struct GNUJNET_FS_DownloadContext' we're processing
1598 get_next_block (void *cls)
1600 struct GNUNET_FS_DownloadContext *dc = cls;
1603 GNUNET_FS_tree_encoder_next (dc->te);
1608 * Function called asking for the current (encoded)
1609 * block to be processed. After processing the
1610 * client should either call "GNUNET_FS_tree_encode_next"
1611 * or (on error) "GNUNET_FS_tree_encode_finish".
1613 * This function checks if the content on disk matches
1614 * the expected content based on the URI.
1616 * @param cls closure
1617 * @param chk content hash key for the block
1618 * @param offset offset of the block
1619 * @param depth depth of the block, 0 for DBLOCK
1620 * @param type type of the block (IBLOCK or DBLOCK)
1621 * @param block the (encrypted) block
1622 * @param block_size size of block (in bytes)
1625 reconstruct_cb (void *cls,
1626 const struct ContentHashKey *chk,
1629 enum GNUNET_BLOCK_Type type,
1631 uint16_t block_size)
1633 struct GNUNET_FS_DownloadContext *dc = cls;
1634 struct GNUNET_FS_ProgressInfo pi;
1635 struct DownloadRequest *dr;
1639 /* find corresponding request entry */
1640 dr = dc->top_request;
1641 while (dr->depth > depth)
1643 GNUNET_assert (dr->num_children > 0);
1644 blen = GNUNET_FS_tree_compute_tree_size (dr->depth - 1);
1645 chld = (offset - dr->offset) / blen;
1646 if (chld < dr->children[0]->chk_idx)
1648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1649 "Block %u < %u irrelevant for our range\n",
1651 dr->children[0]->chk_idx);
1652 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1653 return; /* irrelevant block */
1655 if (chld > dr->children[dr->num_children - 1]->chk_idx)
1657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1658 "Block %u > %u irrelevant for our range\n",
1660 dr->children[dr->num_children - 1]->chk_idx);
1661 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1662 return; /* irrelevant block */
1664 dr = dr->children[chld - dr->children[0]->chk_idx];
1667 GNUNET_ERROR_TYPE_DEBUG,
1668 "Matched TE block with request at offset %llu and depth %u in state %d\n",
1669 (unsigned long long) dr->offset,
1672 /* FIXME: this code needs more testing and might
1673 need to handle more states... */
1679 case BRS_RECONSTRUCT_DOWN:
1682 case BRS_RECONSTRUCT_META_UP:
1685 case BRS_RECONSTRUCT_UP:
1689 if (0 == memcmp (chk, &dr->chk, sizeof(struct ContentHashKey)))
1692 GNUNET_ERROR_TYPE_DEBUG,
1693 "Reconstruction succeeded, can use block at offset %llu, depth %u\n",
1694 (unsigned long long) offset,
1696 /* block matches, hence tree below matches;
1697 * this request is done! */
1698 dr->state = BRS_DOWNLOAD_UP;
1699 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active,
1702 /* calculate how many bytes of payload this block
1704 blen = GNUNET_FS_tree_compute_tree_size (dr->depth);
1705 /* how many of those bytes are in the requested range? */
1706 blen = GNUNET_MIN (blen, dc->length + dc->offset - dr->offset);
1707 /* signal progress */
1708 dc->completed += blen;
1709 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1710 pi.value.download.specifics.progress.data = NULL;
1711 pi.value.download.specifics.progress.offset = offset;
1712 pi.value.download.specifics.progress.data_len = 0;
1713 pi.value.download.specifics.progress.depth = 0;
1714 pi.value.download.specifics.progress.respect_offered = 0;
1715 pi.value.download.specifics.progress.block_download_duration =
1716 GNUNET_TIME_UNIT_ZERO;
1717 GNUNET_FS_download_make_status_ (&pi, dc);
1718 /* FIXME: duplicated code from 'process_result_with_request - refactor */
1719 if (dc->completed == dc->length)
1721 /* download completed, signal */
1722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1723 "Download completed, truncating file to desired length %llu\n",
1724 (unsigned long long) GNUNET_ntohll (
1725 dc->uri->data.chk.file_length));
1726 /* truncate file to size (since we store IBlocks at the end) */
1727 if (NULL != dc->filename)
1729 if (0 != truncate (dc->filename,
1730 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1731 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1739 GNUNET_ERROR_TYPE_DEBUG,
1740 "Reconstruction failed, need to download block at offset %llu, depth %u\n",
1741 (unsigned long long) offset,
1745 case BRS_DOWNLOAD_DOWN:
1748 case BRS_DOWNLOAD_UP:
1758 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1759 if ((dr == dc->top_request) && (dr->state == BRS_DOWNLOAD_UP))
1760 check_completed (dc);
1765 * Function called by the tree encoder to obtain a block of plaintext
1766 * data (for the lowest level of the tree).
1768 * @param cls our 'struct ReconstructContext'
1769 * @param offset identifies which block to get
1770 * @param max (maximum) number of bytes to get; returning
1771 * fewer will also cause errors
1772 * @param buf where to copy the plaintext buffer
1773 * @param emsg location to store an error message (on error)
1774 * @return number of bytes copied to buf, 0 on error
1777 fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg)
1779 struct GNUNET_FS_DownloadContext *dc = cls;
1780 struct GNUNET_DISK_FileHandle *fh = dc->rfh;
1785 if (offset != GNUNET_DISK_file_seek (fh, offset, GNUNET_DISK_SEEK_SET))
1788 *emsg = GNUNET_strdup (strerror (errno));
1791 ret = GNUNET_DISK_file_read (fh, buf, max);
1795 *emsg = GNUNET_strdup (strerror (errno));
1803 * Task that creates the initial (top-level) download
1804 * request for the file.
1806 * @param cls the 'struct GNUNET_FS_DownloadContext'
1809 GNUNET_FS_download_start_task_ (void *cls)
1811 struct GNUNET_FS_DownloadContext *dc = cls;
1812 struct GNUNET_FS_ProgressInfo pi;
1813 struct GNUNET_DISK_FileHandle *fh;
1815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start task running...\n");
1817 if (0 == dc->length)
1819 /* no bytes required! */
1820 if (NULL != dc->filename)
1822 fh = GNUNET_DISK_file_open (dc->filename,
1823 GNUNET_DISK_OPEN_READWRITE
1824 | GNUNET_DISK_OPEN_CREATE
1826 GNUNET_FS_uri_chk_get_file_size (dc->uri))
1827 ? GNUNET_DISK_OPEN_TRUNCATE
1829 GNUNET_DISK_PERM_USER_READ
1830 | GNUNET_DISK_PERM_USER_WRITE
1831 | GNUNET_DISK_PERM_GROUP_READ
1832 | GNUNET_DISK_PERM_OTHER_READ);
1833 GNUNET_DISK_file_close (fh);
1835 GNUNET_FS_download_sync_ (dc);
1836 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1837 pi.value.download.specifics.start.meta = dc->meta;
1838 GNUNET_FS_download_make_status_ (&pi, dc);
1839 check_completed (dc);
1842 if (NULL != dc->emsg)
1844 if (NULL == dc->top_request)
1846 dc->top_request = create_download_request (NULL,
1852 dc->top_request->state = BRS_CHK_SET;
1853 dc->top_request->chk = (dc->uri->type == GNUNET_FS_URI_CHK)
1854 ? dc->uri->data.chk.chk
1855 : dc->uri->data.loc.fi.chk;
1857 GNUNET_FS_download_sync_ (dc);
1858 if (NULL != dc->search)
1859 GNUNET_FS_search_result_sync_ (dc->search);
1860 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1861 pi.value.download.specifics.start.meta = dc->meta;
1862 GNUNET_FS_download_make_status_ (&pi, dc);
1864 GNUNET_FS_download_start_downloading_ (dc);
1865 /* attempt reconstruction from disk */
1866 if (GNUNET_YES == GNUNET_DISK_file_test (dc->filename))
1867 dc->rfh = GNUNET_DISK_file_open (dc->filename,
1868 GNUNET_DISK_OPEN_READ,
1869 GNUNET_DISK_PERM_NONE);
1870 if (dc->top_request->state == BRS_CHK_SET)
1872 if (NULL != dc->rfh)
1874 /* first, try top-down */
1875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1876 "Trying top-down reconstruction for `%s'\n",
1878 try_top_down_reconstruction (dc, dc->top_request);
1879 switch (dc->top_request->state)
1884 case BRS_DOWNLOAD_DOWN:
1885 break; /* normal, some blocks already down */
1887 case BRS_DOWNLOAD_UP:
1888 /* already done entirely, party! */
1889 if (NULL != dc->rfh)
1891 /* avoid hanging on to file handle longer than
1893 GNUNET_DISK_file_close (dc->rfh);
1899 GNUNET_asprintf (&dc->emsg, _ ("Invalid URI"));
1900 GNUNET_FS_download_sync_ (dc);
1901 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1902 pi.value.download.specifics.error.message = dc->emsg;
1903 GNUNET_FS_download_make_status_ (&pi, dc);
1912 /* attempt reconstruction from meta data */
1913 if ((GNUNET_FS_uri_chk_get_file_size (dc->uri) <= MAX_INLINE_SIZE) &&
1917 GNUNET_ERROR_TYPE_DEBUG,
1918 "Trying to find embedded meta data for download of size %llu with %u bytes MD\n",
1919 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (dc->uri),
1920 (unsigned int) GNUNET_CONTAINER_meta_data_get_serialized_size (dc->meta));
1921 GNUNET_CONTAINER_meta_data_iterate (dc->meta, &match_full_data, dc);
1922 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1924 if (NULL != dc->rfh)
1926 /* avoid hanging on to file handle longer than
1928 GNUNET_DISK_file_close (dc->rfh);
1931 return; /* finished, status update was already done for us */
1934 if (NULL != dc->rfh)
1936 /* finally, actually run bottom-up */
1937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1938 "Trying bottom-up reconstruction of file `%s'\n",
1941 GNUNET_FS_tree_encoder_create (dc->h,
1942 GNUNET_FS_uri_chk_get_file_size (dc->uri),
1948 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1952 /* simple, top-level download */
1953 dc->issue_requests = GNUNET_YES;
1954 schedule_block_download (dc, dc->top_request);
1956 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1957 check_completed (dc);
1962 * Create SUSPEND event for the given download operation
1963 * and then clean up our state (without stop signal).
1965 * @param cls the 'struct GNUNET_FS_DownloadContext' to signal for
1968 GNUNET_FS_download_signal_suspend_ (void *cls)
1970 struct GNUNET_FS_DownloadContext *dc = cls;
1971 struct GNUNET_FS_ProgressInfo pi;
1973 if (NULL != dc->top)
1974 GNUNET_FS_end_top (dc->h, dc->top);
1975 while (NULL != dc->child_head)
1976 GNUNET_FS_download_signal_suspend_ (dc->child_head);
1977 if (NULL != dc->search)
1979 dc->search->download = NULL;
1982 if (NULL != dc->job_queue)
1984 GNUNET_FS_dequeue_ (dc->job_queue);
1985 dc->job_queue = NULL;
1987 if (NULL != dc->parent)
1988 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1989 dc->parent->child_tail,
1991 if (NULL != dc->task)
1993 GNUNET_SCHEDULER_cancel (dc->task);
1996 pi.status = GNUNET_FS_STATUS_DOWNLOAD_SUSPEND;
1997 GNUNET_FS_download_make_status_ (&pi, dc);
2000 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
2003 if (NULL != dc->rfh)
2005 GNUNET_DISK_file_close (dc->rfh);
2008 GNUNET_FS_free_download_request_ (dc->top_request);
2009 if (NULL != dc->active)
2011 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2014 GNUNET_free_non_null (dc->filename);
2015 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2016 GNUNET_FS_uri_destroy (dc->uri);
2017 GNUNET_free_non_null (dc->temp_filename);
2018 GNUNET_free_non_null (dc->serialization);
2019 GNUNET_assert (NULL == dc->job_queue);
2025 * Helper function to setup the download context.
2027 * @param h handle to the file sharing subsystem
2028 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2029 * @param meta known metadata for the file (can be NULL)
2030 * @param filename where to store the file, maybe NULL (then no file is
2031 * created on disk and data must be grabbed from the callbacks)
2032 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2033 * can be NULL (in which case we will pick a name if needed); the temporary file
2034 * may already exist, in which case we will try to use the data that is there and
2035 * if it is not what is desired, will overwrite it
2036 * @param offset at what offset should we start the download (typically 0)
2037 * @param length how many bytes should be downloaded starting at offset
2038 * @param anonymity anonymity level to use for the download
2039 * @param options various options
2040 * @param cctx initial value for the client context for this download
2041 * @return context that can be used to control this download
2043 struct GNUNET_FS_DownloadContext *
2044 create_download_context (struct GNUNET_FS_Handle *h,
2045 const struct GNUNET_FS_Uri *uri,
2046 const struct GNUNET_CONTAINER_MetaData *meta,
2047 const char *filename,
2048 const char *tempname,
2052 enum GNUNET_FS_DownloadOptions options,
2055 struct GNUNET_FS_DownloadContext *dc;
2057 GNUNET_assert (GNUNET_FS_uri_test_chk (uri) || GNUNET_FS_uri_test_loc (uri));
2058 if ((offset + length < offset) ||
2059 (offset + length > GNUNET_FS_uri_chk_get_file_size (uri)))
2064 dc = GNUNET_new (struct GNUNET_FS_DownloadContext);
2065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066 "Starting download %p, %u bytes at offset %llu\n",
2068 (unsigned int) length,
2069 (unsigned long long) offset);
2071 dc->uri = GNUNET_FS_uri_dup (uri);
2072 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
2073 dc->client_info = cctx;
2074 dc->start_time = GNUNET_TIME_absolute_get ();
2075 if (NULL != filename)
2077 dc->filename = GNUNET_strdup (filename);
2078 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
2079 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_size (filename,
2084 if (GNUNET_FS_uri_test_loc (dc->uri))
2085 GNUNET_assert (GNUNET_OK ==
2086 GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target));
2087 dc->offset = offset;
2088 dc->length = length;
2089 dc->anonymity = anonymity;
2090 dc->options = options;
2092 GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE),
2095 GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri));
2096 if ((NULL == filename) && (is_recursive_download (dc)))
2098 if (NULL != tempname)
2099 dc->temp_filename = GNUNET_strdup (tempname);
2101 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104 "Starting download `%s' of %llu bytes with tree depth %u\n",
2106 (unsigned long long) length,
2108 GNUNET_assert (NULL == dc->job_queue);
2109 dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2115 * Download parts of a file. Note that this will store
2116 * the blocks at the respective offset in the given file. Also, the
2117 * download is still using the blocking of the underlying FS
2118 * encoding. As a result, the download may *write* outside of the
2119 * given boundaries (if offset and length do not match the 32k FS
2120 * block boundaries). <p>
2122 * This function should be used to focus a download towards a
2123 * particular portion of the file (optimization), not to strictly
2124 * limit the download to exactly those bytes.
2126 * @param h handle to the file sharing subsystem
2127 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2128 * @param meta known metadata for the file (can be NULL)
2129 * @param filename where to store the file, maybe NULL (then no file is
2130 * created on disk and data must be grabbed from the callbacks)
2131 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2132 * can be NULL (in which case we will pick a name if needed); the temporary file
2133 * may already exist, in which case we will try to use the data that is there and
2134 * if it is not what is desired, will overwrite it
2135 * @param offset at what offset should we start the download (typically 0)
2136 * @param length how many bytes should be downloaded starting at offset
2137 * @param anonymity anonymity level to use for the download
2138 * @param options various options
2139 * @param cctx initial value for the client context for this download
2140 * @param parent parent download to associate this download with (use NULL
2141 * for top-level downloads; useful for manually-triggered recursive downloads)
2142 * @return context that can be used to control this download
2144 struct GNUNET_FS_DownloadContext *
2145 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
2146 const struct GNUNET_FS_Uri *uri,
2147 const struct GNUNET_CONTAINER_MetaData *meta,
2148 const char *filename,
2149 const char *tempname,
2153 enum GNUNET_FS_DownloadOptions options,
2155 struct GNUNET_FS_DownloadContext *parent)
2157 struct GNUNET_FS_DownloadContext *dc;
2159 dc = create_download_context (h,
2171 dc->parent = parent;
2173 GNUNET_CONTAINER_DLL_insert (parent->child_head, parent->child_tail, dc);
2174 else if (0 == (GNUNET_FS_DOWNLOAD_IS_PROBE & options))
2176 GNUNET_FS_make_top (dc->h, &GNUNET_FS_download_signal_suspend_, dc);
2182 * Download parts of a file based on a search result. The download
2183 * will be associated with the search result (and the association
2184 * will be preserved when serializing/deserializing the state).
2185 * If the search is stopped, the download will not be aborted but
2186 * be 'promoted' to a stand-alone download.
2188 * As with the other download function, this will store
2189 * the blocks at the respective offset in the given file. Also, the
2190 * download is still using the blocking of the underlying FS
2191 * encoding. As a result, the download may *write* outside of the
2192 * given boundaries (if offset and length do not match the 32k FS
2193 * block boundaries). <p>
2195 * The given range can be used to focus a download towards a
2196 * particular portion of the file (optimization), not to strictly
2197 * limit the download to exactly those bytes.
2199 * @param h handle to the file sharing subsystem
2200 * @param sr the search result to use for the download (determines uri and
2201 * meta data and associations)
2202 * @param filename where to store the file, maybe NULL (then no file is
2203 * created on disk and data must be grabbed from the callbacks)
2204 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2205 * can be NULL (in which case we will pick a name if needed); the temporary file
2206 * may already exist, in which case we will try to use the data that is there and
2207 * if it is not what is desired, will overwrite it
2208 * @param offset at what offset should we start the download (typically 0)
2209 * @param length how many bytes should be downloaded starting at offset
2210 * @param anonymity anonymity level to use for the download
2211 * @param options various download options
2212 * @param cctx initial value for the client context for this download
2213 * @return context that can be used to control this download
2215 struct GNUNET_FS_DownloadContext *
2216 GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h,
2217 struct GNUNET_FS_SearchResult *sr,
2218 const char *filename,
2219 const char *tempname,
2223 enum GNUNET_FS_DownloadOptions options,
2226 struct GNUNET_FS_DownloadContext *dc;
2228 if ((NULL == sr) || (NULL != sr->download))
2233 dc = create_download_context (h,
2247 if (NULL != sr->probe_ctx)
2249 GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
2250 sr->probe_ctx = NULL;
2251 GNUNET_FS_stop_probe_ping_task_ (sr);
2258 * Start the downloading process (by entering the queue).
2260 * @param dc our download context
2263 GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc)
2265 if (dc->completed == dc->length)
2268 return; /* already running */
2269 GNUNET_assert (NULL == dc->job_queue);
2270 GNUNET_assert (NULL == dc->task);
2271 GNUNET_assert (NULL != dc->active);
2273 GNUNET_FS_queue_ (dc->h,
2274 &activate_fs_download,
2275 &deactivate_fs_download,
2277 (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE,
2278 (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
2279 ? GNUNET_FS_QUEUE_PRIORITY_NORMAL
2280 : GNUNET_FS_QUEUE_PRIORITY_PROBE);
2281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2282 "Download %p put into queue as job %p\n",
2289 * Suspend a download.
2291 * @param dc handle for the download
2294 GNUNET_FS_download_suspend (struct GNUNET_FS_DownloadContext *dc)
2296 deactivate_fs_download (dc);
2301 * Resume a suspended download.
2303 * @param dc handle for the download
2306 GNUNET_FS_download_resume (struct GNUNET_FS_DownloadContext *dc)
2308 struct GNUNET_FS_ProgressInfo pi;
2310 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
2311 GNUNET_FS_download_make_status_ (&pi, dc);
2313 GNUNET_assert (NULL == dc->task);
2315 GNUNET_FS_queue_ (dc->h,
2316 &activate_fs_download,
2317 &deactivate_fs_download,
2319 (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE,
2320 (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
2321 ? GNUNET_FS_QUEUE_PRIORITY_NORMAL
2322 : GNUNET_FS_QUEUE_PRIORITY_PROBE);
2327 * Stop a download (aborts if download is incomplete).
2329 * @param dc handle for the download
2330 * @param do_delete delete files of incomplete downloads
2333 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete)
2335 struct GNUNET_FS_ProgressInfo pi;
2337 int search_was_null;
2339 if (NULL != dc->top)
2340 GNUNET_FS_end_top (dc->h, dc->top);
2341 if (NULL != dc->task)
2343 GNUNET_SCHEDULER_cancel (dc->task);
2346 search_was_null = (NULL == dc->search);
2347 if (NULL != dc->search)
2349 dc->search->download = NULL;
2350 GNUNET_FS_search_result_sync_ (dc->search);
2353 if (NULL != dc->job_queue)
2355 GNUNET_FS_dequeue_ (dc->job_queue);
2356 dc->job_queue = NULL;
2360 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
2363 have_children = (NULL != dc->child_head) ? GNUNET_YES : GNUNET_NO;
2364 while (NULL != dc->child_head)
2365 GNUNET_FS_download_stop (dc->child_head, do_delete);
2366 if (NULL != dc->parent)
2367 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
2368 dc->parent->child_tail,
2370 if (NULL != dc->serialization)
2371 GNUNET_FS_remove_sync_file_ (dc->h,
2372 ((NULL != dc->parent) || (! search_was_null))
2373 ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD
2374 : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2376 if ((GNUNET_YES == have_children) && (NULL == dc->parent))
2377 GNUNET_FS_remove_sync_dir_ (dc->h,
2379 ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD
2380 : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2382 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
2383 GNUNET_FS_download_make_status_ (&pi, dc);
2384 GNUNET_FS_free_download_request_ (dc->top_request);
2385 dc->top_request = NULL;
2386 if (NULL != dc->active)
2388 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2391 if (NULL != dc->filename)
2393 if ((dc->completed != dc->length) && (GNUNET_YES == do_delete))
2395 if ((0 != unlink (dc->filename)) && (ENOENT != errno))
2396 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
2400 GNUNET_free (dc->filename);
2402 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2403 GNUNET_FS_uri_destroy (dc->uri);
2404 if (NULL != dc->temp_filename)
2406 if (0 != unlink (dc->temp_filename))
2407 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2410 GNUNET_free (dc->temp_filename);
2412 GNUNET_free_non_null (dc->serialization);
2413 GNUNET_assert (NULL == dc->job_queue);
2418 /* end of fs_download.c */