2 This file is part of GNUnet.
3 (C) 2001-2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
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)) &&
45 strstr (dc->filename + strlen (dc->filename) -
46 strlen (GNUNET_FS_DIRECTORY_EXT),
47 GNUNET_FS_DIRECTORY_EXT))))));
52 * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
53 * only have to truncate the file once we're done).
55 * Given the offset of a block (with respect to the DBLOCKS) and its
56 * depth, return the offset where we would store this block in the
59 * @param fsize overall file size
60 * @param off offset of the block in the file
61 * @param depth depth of the block in the tree, 0 for DBLOCK
62 * @return off for DBLOCKS (depth == treedepth),
63 * otherwise an offset past the end
64 * of the file that does not overlap
65 * with the range for any other block
68 compute_disk_offset (uint64_t fsize, uint64_t off, unsigned int depth)
71 uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
72 uint64_t loff; /* where do IBlocks for depth "i" start? */
73 unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
77 /* first IBlocks start at the end of file, rounded up
78 * to full DBLOCK_SIZE */
79 loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
81 ((fsize + DBLOCK_SIZE -
82 1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
83 GNUNET_assert (0 == (off % DBLOCK_SIZE));
84 ioff = (off / DBLOCK_SIZE);
85 for (i = 1; i < depth; i++)
88 lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
89 GNUNET_assert (lsize > 0);
90 GNUNET_assert (0 == (ioff % CHK_PER_INODE));
91 ioff /= CHK_PER_INODE;
93 return loff + ioff * sizeof (struct ContentHashKey);
98 * Fill in all of the generic fields for a download event and call the
101 * @param pi structure to fill in
102 * @param dc overall download context
105 GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
106 struct GNUNET_FS_DownloadContext *dc)
108 pi->value.download.dc = dc;
109 pi->value.download.cctx = dc->client_info;
110 pi->value.download.pctx =
111 (NULL == dc->parent) ? NULL : dc->parent->client_info;
112 pi->value.download.sctx =
113 (NULL == dc->search) ? NULL : dc->search->client_info;
114 pi->value.download.uri = dc->uri;
115 pi->value.download.filename = dc->filename;
116 pi->value.download.size = dc->length;
117 /* FIXME: Fix duration calculation to account for pauses */
118 pi->value.download.duration =
119 GNUNET_TIME_absolute_get_duration (dc->start_time);
120 pi->value.download.completed = dc->completed;
121 pi->value.download.anonymity = dc->anonymity;
122 pi->value.download.eta =
123 GNUNET_TIME_calculate_eta (dc->start_time, dc->completed, dc->length);
124 pi->value.download.is_active = (NULL == dc->client) ? GNUNET_NO : GNUNET_YES;
126 if (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
127 dc->client_info = dc->h->upcb (dc->h->upcb_cls, pi);
129 dc->client_info = GNUNET_FS_search_probe_progress_ (NULL, pi);
134 * We're ready to transmit a search request to the
135 * file-sharing service. Do it. If there is
136 * more than one request pending, try to send
137 * multiple or request another transmission.
140 * @param size number of bytes available in buf
141 * @param buf where the callee should write the message
142 * @return number of bytes written to buf
145 transmit_download_request (void *cls, size_t size, void *buf);
149 * Closure for iterator processing results.
151 struct ProcessResultClosure
157 struct GNUNET_HashCode query;
160 * Data found in P2P network.
165 * Our download context.
167 struct GNUNET_FS_DownloadContext *dc;
170 * When did we last transmit the request?
172 struct GNUNET_TIME_Absolute last_transmission;
175 * Number of bytes in data.
182 enum GNUNET_BLOCK_Type type;
185 * Flag to indicate if this block should be stored on disk.
190 * how much respect did we offer to get this reply?
192 uint32_t respect_offered;
195 * how often did we transmit the query?
197 uint32_t num_transmissions;
203 * Iterator over entries in the pending requests in the 'active' map for the
204 * reply that we just got.
206 * @param cls closure (our 'struct ProcessResultClosure')
207 * @param key query for the given value / request
208 * @param value value in the hash map (a 'struct DownloadRequest')
209 * @return GNUNET_YES (we should continue to iterate); unless serious error
212 process_result_with_request (void *cls, const struct GNUNET_HashCode * key,
217 * We've found a matching block without downloading it.
218 * Encrypt it and pass it to our "receive" function as
219 * if we had received it from the network.
221 * @param dc download in question
222 * @param chk request this relates to
223 * @param dr request details
224 * @param block plaintext data matching request
225 * @param len number of bytes in block
226 * @param do_store should we still store the block on disk?
227 * @return GNUNET_OK on success
230 encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc,
231 const struct ContentHashKey *chk,
232 struct DownloadRequest *dr, const char *block,
233 size_t len, int do_store)
235 struct ProcessResultClosure prc;
237 struct GNUNET_CRYPTO_SymmetricSessionKey sk;
238 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
239 struct GNUNET_HashCode query;
241 GNUNET_CRYPTO_hash_to_aes_key (&chk->key, &sk, &iv);
242 if (-1 == GNUNET_CRYPTO_symmetric_encrypt (block, len, &sk, &iv, enc))
245 return GNUNET_SYSERR;
247 GNUNET_CRYPTO_hash (enc, len, &query);
248 if (0 != memcmp (&query, &chk->query, sizeof (struct GNUNET_HashCode)))
251 return GNUNET_SYSERR;
253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
254 "Matching %u byte block for `%s' at offset %llu already present, no need for download!\n",
256 dc->filename, (unsigned long long) dr->offset);
257 /* already got it! */
263 dr->depth) ? GNUNET_BLOCK_TYPE_FS_DBLOCK : GNUNET_BLOCK_TYPE_FS_IBLOCK;
264 prc.query = chk->query;
265 prc.do_store = do_store;
266 prc.last_transmission = GNUNET_TIME_UNIT_FOREVER_ABS;
267 process_result_with_request (&prc, &chk->key, dr);
273 * We've lost our connection with the FS service.
274 * Re-establish it and re-transmit all of our
277 * @param dc download context that is having trouble
280 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
284 * We found an entry in a directory. Check if the respective child
285 * already exists and if not create the respective child download.
287 * @param cls the parent download
288 * @param filename name of the file in the directory
289 * @param uri URI of the file (CHK or LOC)
290 * @param meta meta data of the file
291 * @param length number of bytes in data
292 * @param data contents of the file (or NULL if they were not inlined)
295 trigger_recursive_download (void *cls, const char *filename,
296 const struct GNUNET_FS_Uri *uri,
297 const struct GNUNET_CONTAINER_MetaData *meta,
298 size_t length, const void *data);
302 * We're done downloading a directory. Open the file and
303 * trigger all of the (remaining) child downloads.
305 * @param dc context of download that just completed
308 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
313 struct GNUNET_DISK_FileHandle *h;
314 struct GNUNET_DISK_MapHandle *m;
316 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
317 size = (size_t) size64;
318 if (size64 != (uint64_t) size)
320 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
322 ("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
325 if (NULL != dc->filename)
327 h = GNUNET_DISK_file_open (dc->filename, GNUNET_DISK_OPEN_READ,
328 GNUNET_DISK_PERM_NONE);
332 GNUNET_assert (NULL != dc->temp_filename);
333 h = GNUNET_DISK_file_open (dc->temp_filename, GNUNET_DISK_OPEN_READ,
334 GNUNET_DISK_PERM_NONE);
338 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
341 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
342 _("Directory too large for system address space\n"));
346 GNUNET_FS_directory_list_contents (size, data, 0,
347 &trigger_recursive_download, dc);
348 GNUNET_DISK_file_unmap (m);
350 GNUNET_DISK_file_close (h);
351 if (NULL == dc->filename)
353 if (0 != UNLINK (dc->temp_filename))
354 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
356 GNUNET_free (dc->temp_filename);
357 dc->temp_filename = NULL;
363 * Check if all child-downloads have completed (or trigger them if
364 * necessary) and once we're completely done, signal completion (and
365 * possibly recurse to parent). This function MUST be called when the
366 * download of a file itself is done or when the download of a file is
367 * done and then later a direct child download has completed (and
368 * hence this download may complete itself).
370 * @param dc download to check for completion of children
373 check_completed (struct GNUNET_FS_DownloadContext *dc)
375 struct GNUNET_FS_ProgressInfo pi;
376 struct GNUNET_FS_DownloadContext *pos;
378 /* first, check if we need to download children */
379 if ((NULL == dc->child_head) && (is_recursive_download (dc)))
380 full_recursive_download (dc);
381 /* then, check if children are done already */
382 for (pos = dc->child_head; NULL != pos; pos = pos->next)
384 if ((pos->emsg == NULL) && (pos->completed < pos->length))
385 return; /* not done yet */
386 if ((pos->child_head != NULL) && (pos->has_finished != GNUNET_YES))
387 return; /* not transitively done yet */
389 /* All of our children are done, so mark this download done */
390 dc->has_finished = GNUNET_YES;
391 if (NULL != dc->job_queue)
393 GNUNET_FS_dequeue_ (dc->job_queue);
394 dc->job_queue = NULL;
396 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
398 GNUNET_SCHEDULER_cancel (dc->task);
399 dc->task = GNUNET_SCHEDULER_NO_TASK;
403 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
406 GNUNET_FS_download_sync_ (dc);
408 /* signal completion */
409 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
410 GNUNET_FS_download_make_status_ (&pi, dc);
412 /* let parent know */
413 if (NULL != dc->parent)
414 check_completed (dc->parent);
419 * We got a block of plaintext data (from the meta data).
420 * Try it for upward reconstruction of the data. On success,
421 * the top-level block will move to state BRS_DOWNLOAD_UP.
423 * @param dc context for the download
424 * @param dr download request to match against
425 * @param data plaintext data, starting from the beginning of the file
426 * @param data_len number of bytes in data
429 try_match_block (struct GNUNET_FS_DownloadContext *dc,
430 struct DownloadRequest *dr, const char *data, size_t data_len)
432 struct GNUNET_FS_ProgressInfo pi;
434 char enc[DBLOCK_SIZE];
435 struct ContentHashKey chks[CHK_PER_INODE];
436 struct ContentHashKey in_chk;
437 struct GNUNET_CRYPTO_SymmetricSessionKey sk;
438 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
440 struct DownloadRequest *drc;
441 struct GNUNET_DISK_FileHandle *fh;
448 odata_len = data_len;
449 if (BRS_DOWNLOAD_UP == dr->state)
453 if ( (dc->offset > 0) ||
454 (dc->length < GNUNET_ntohll (dc->uri->data.chk.file_length)) )
456 /* NOTE: this test is not tight, but should suffice; the issue
457 here is that 'dr->num_children' may inherently only specify a
458 smaller range than what is in the original file;
459 thus, reconstruction of (some) inner blocks will fail.
460 FIXME: we might eventually want to write a tighter test to
461 maximize the circumstances under which we do succeed with
462 IBlock reconstruction. (need good tests though). */
465 complete = GNUNET_YES;
466 for (i = 0; i < dr->num_children; i++)
468 drc = dr->children[i];
469 try_match_block (dc, drc, data, data_len);
470 if (drc->state != BRS_RECONSTRUCT_META_UP)
471 complete = GNUNET_NO;
475 if (GNUNET_YES != complete)
477 data = (const char *) chks;
478 dlen = dr->num_children * sizeof (struct ContentHashKey);
482 if (dr->offset > data_len)
484 dlen = GNUNET_MIN (data_len - dr->offset, DBLOCK_SIZE);
486 GNUNET_CRYPTO_hash (&data[dr->offset], dlen, &in_chk.key);
487 GNUNET_CRYPTO_hash_to_aes_key (&in_chk.key, &sk, &iv);
488 if (-1 == GNUNET_CRYPTO_symmetric_encrypt (&data[dr->offset], dlen, &sk, &iv, enc))
493 GNUNET_CRYPTO_hash (enc, dlen, &in_chk.query);
498 dr->state = BRS_RECONSTRUCT_META_UP;
501 if (0 != memcmp (&in_chk, &dr->chk, sizeof (struct ContentHashKey)))
503 /* other peer provided bogus meta data */
507 /* write block to disk */
508 fn = (NULL != dc->filename) ? dc->filename : dc->temp_filename;
511 fh = GNUNET_DISK_file_open (fn,
512 GNUNET_DISK_OPEN_READWRITE |
513 GNUNET_DISK_OPEN_CREATE |
514 GNUNET_DISK_OPEN_TRUNCATE,
515 GNUNET_DISK_PERM_USER_READ |
516 GNUNET_DISK_PERM_USER_WRITE |
517 GNUNET_DISK_PERM_GROUP_READ |
518 GNUNET_DISK_PERM_OTHER_READ);
521 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
522 GNUNET_asprintf (&dc->emsg,
523 _("Failed to open file `%s' for writing"),
525 GNUNET_DISK_file_close (fh);
526 dr->state = BRS_ERROR;
527 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
528 pi.value.download.specifics.error.message = dc->emsg;
529 GNUNET_FS_download_make_status_ (&pi, dc);
532 if (data_len != GNUNET_DISK_file_write (fh, odata, odata_len))
534 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "write", fn);
535 GNUNET_asprintf (&dc->emsg, _("Failed to open file `%s' for writing"),
537 GNUNET_DISK_file_close (fh);
538 dr->state = BRS_ERROR;
539 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
540 pi.value.download.specifics.error.message = dc->emsg;
541 GNUNET_FS_download_make_status_ (&pi, dc);
544 GNUNET_DISK_file_close (fh);
547 dr->state = BRS_DOWNLOAD_UP;
548 dc->completed = dc->length;
549 GNUNET_FS_download_sync_ (dc);
550 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
551 pi.value.download.specifics.progress.data = data;
552 pi.value.download.specifics.progress.offset = 0;
553 pi.value.download.specifics.progress.data_len = dlen;
554 pi.value.download.specifics.progress.depth = 0;
555 pi.value.download.specifics.progress.respect_offered = 0;
556 pi.value.download.specifics.progress.block_download_duration = GNUNET_TIME_UNIT_ZERO;
557 GNUNET_FS_download_make_status_ (&pi, dc);
558 if ((NULL != dc->filename) &&
560 TRUNCATE (dc->filename,
561 GNUNET_ntohll (dc->uri->data.chk.file_length))))
562 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
564 check_completed (dc);
567 /* how did we get here? */
575 * Type of a function that libextractor calls for each
576 * meta data item found. If we find full data meta data,
577 * call 'try_match_block' on it.
579 * @param cls our 'struct GNUNET_FS_DownloadContext*'
580 * @param plugin_name name of the plugin that produced this value;
581 * special values can be used (i.e. '<zlib>' for zlib being
582 * used in the main libextractor library and yielding
584 * @param type libextractor-type describing the meta data
585 * @param format basic format information about data
586 * @param data_mime_type mime-type of data (not of the original file);
587 * can be NULL (if mime-type is not known)
588 * @param data actual meta-data found
589 * @param data_len number of bytes in data
590 * @return 0 to continue extracting, 1 to abort
593 match_full_data (void *cls, const char *plugin_name,
594 enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format,
595 const char *data_mime_type, const char *data, size_t data_len)
597 struct GNUNET_FS_DownloadContext *dc = cls;
599 if (EXTRACTOR_METATYPE_GNUNET_FULL_DATA != type)
601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u bytes of FD!\n",
602 (unsigned int) data_len);
603 if (GNUNET_FS_uri_chk_get_file_size (dc->uri) != data_len)
606 return 1; /* bogus meta data */
608 try_match_block (dc, dc->top_request, data, data_len);
614 * Set the state of the given download request to
615 * BRS_DOWNLOAD_UP and propagate it up the tree.
617 * @param dr download request that is done
620 propagate_up (struct DownloadRequest *dr)
626 dr->state = BRS_DOWNLOAD_UP;
630 for (i = 0; i < dr->num_children; i++)
631 if (dr->children[i]->state != BRS_DOWNLOAD_UP)
634 while (i == dr->num_children);
639 * Try top-down reconstruction. Before, the given request node
640 * must have the state BRS_CHK_SET. Afterwards, more nodes may
641 * have that state or advanced to BRS_DOWNLOAD_DOWN or even
642 * BRS_DOWNLOAD_UP. It is also possible to get BRS_ERROR on the
645 * @param dc overall download this block belongs to
646 * @param dr block to reconstruct
649 try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc,
650 struct DownloadRequest *dr)
653 char block[DBLOCK_SIZE];
654 struct GNUNET_HashCode key;
658 struct DownloadRequest *drc;
659 uint64_t child_block_size;
660 const struct ContentHashKey *chks;
663 GNUNET_assert (NULL != dc->rfh);
664 GNUNET_assert (BRS_CHK_SET == dr->state);
665 total = GNUNET_FS_uri_chk_get_file_size (dc->uri);
666 GNUNET_assert (dr->depth < dc->treedepth);
667 len = GNUNET_FS_tree_calculate_block_size (total, dr->offset, dr->depth);
668 GNUNET_assert (len <= DBLOCK_SIZE);
669 off = compute_disk_offset (total, dr->offset, dr->depth);
670 if (dc->old_file_size < off + len)
671 return; /* failure */
672 if (off != GNUNET_DISK_file_seek (dc->rfh, off, GNUNET_DISK_SEEK_SET))
674 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "seek", dc->filename);
675 return; /* failure */
677 if (len != GNUNET_DISK_file_read (dc->rfh, block, len))
679 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "read", dc->filename);
680 return; /* failure */
682 GNUNET_CRYPTO_hash (block, len, &key);
683 if (0 != memcmp (&key, &dr->chk.key, sizeof (struct GNUNET_HashCode)))
684 return; /* mismatch */
686 encrypt_existing_match (dc, &dr->chk, dr, block, len, GNUNET_NO))
688 /* hash matches but encrypted block does not, really bad */
689 dr->state = BRS_ERROR;
691 while (NULL != dr->parent)
694 dr->state = BRS_ERROR;
699 dr->state = BRS_DOWNLOAD_DOWN;
701 /* set CHKs for children */
702 up_done = GNUNET_YES;
703 chks = (const struct ContentHashKey *) block;
704 for (i = 0; i < dr->num_children; i++)
706 drc = dr->children[i];
707 GNUNET_assert (drc->offset >= dr->offset);
708 child_block_size = GNUNET_FS_tree_compute_tree_size (drc->depth);
709 GNUNET_assert (0 == (drc->offset - dr->offset) % child_block_size);
710 if (BRS_INIT == drc->state)
712 drc->state = BRS_CHK_SET;
713 drc->chk = chks[drc->chk_idx];
714 try_top_down_reconstruction (dc, drc);
716 if (BRS_DOWNLOAD_UP != drc->state)
717 up_done = GNUNET_NO; /* children not all done */
719 if (GNUNET_YES == up_done)
720 propagate_up (dr); /* children all done (or no children...) */
725 * Schedule the download of the specified block in the tree.
727 * @param dc overall download this block belongs to
728 * @param dr request to schedule
731 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
732 struct DownloadRequest *dr)
741 case BRS_RECONSTRUCT_DOWN:
744 case BRS_RECONSTRUCT_META_UP:
747 case BRS_RECONSTRUCT_UP:
751 /* normal case, start download */
753 case BRS_DOWNLOAD_DOWN:
754 for (i = 0; i < dr->num_children; i++)
755 schedule_block_download (dc, dr->children[i]);
757 case BRS_DOWNLOAD_UP:
764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
765 "Scheduling download at offset %llu and depth %u for `%s'\n",
766 (unsigned long long) dr->offset, dr->depth,
767 GNUNET_h2s (&dr->chk.query));
769 GNUNET_CONTAINER_multihashmap_contains_value (dc->active, &dr->chk.query,
771 return; /* already active */
772 GNUNET_CONTAINER_multihashmap_put (dc->active, &dr->chk.query, dr,
773 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
774 if (NULL == dc->client)
775 return; /* download not active */
776 GNUNET_CONTAINER_DLL_insert (dc->pending_head, dc->pending_tail, dr);
777 dr->is_pending = GNUNET_YES;
780 GNUNET_CLIENT_notify_transmit_ready (dc->client,
781 sizeof (struct SearchMessage),
782 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
784 &transmit_download_request, dc);
788 #define GNUNET_FS_URI_CHK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_CHK_INFIX
791 * We found an entry in a directory. Check if the respective child
792 * already exists and if not create the respective child download.
794 * @param cls the parent download
795 * @param filename name of the file in the directory
796 * @param uri URI of the file (CHK or LOC)
797 * @param meta meta data of the file
798 * @param length number of bytes in data
799 * @param data contents of the file (or NULL if they were not inlined)
802 trigger_recursive_download (void *cls, const char *filename,
803 const struct GNUNET_FS_Uri *uri,
804 const struct GNUNET_CONTAINER_MetaData *meta,
805 size_t length, const void *data)
807 struct GNUNET_FS_DownloadContext *dc = cls;
808 struct GNUNET_FS_DownloadContext *cpos;
819 return; /* entry for the directory itself */
820 cpos = dc->child_head;
823 if ((GNUNET_FS_uri_test_equal (uri, cpos->uri)) ||
824 ((NULL != filename) && (0 == strcmp (cpos->filename, filename))))
829 return; /* already exists */
831 if (NULL == filename)
833 fn = GNUNET_FS_meta_data_suggest_filename (meta);
836 us = GNUNET_FS_uri_to_string (uri);
837 fn = GNUNET_strdup (&us[strlen (GNUNET_FS_URI_CHK_PREFIX)]);
840 else if ('.' == fn[0])
843 us = GNUNET_FS_uri_to_string (uri);
844 GNUNET_asprintf (&fn, "%s%s", &us[strlen (GNUNET_FS_URI_CHK_PREFIX)],
849 /* change '\' to '/' (this should have happened
850 * during insertion, but malicious peers may
851 * not have done this) */
852 while (NULL != (pos = strstr (fn, "\\")))
854 /* remove '../' everywhere (again, well-behaved
855 * peers don't do this, but don't trust that
856 * we did not get something nasty) */
857 while (NULL != (pos = strstr (fn, "../")))
865 if (NULL == dc->filename)
871 dn = GNUNET_strdup (dc->filename);
872 GNUNET_break ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
874 strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
875 GNUNET_FS_DIRECTORY_EXT)));
876 sfn = GNUNET_strdup (filename);
877 while ((strlen (sfn) > 0) && ('/' == filename[strlen (sfn) - 1]))
878 sfn[strlen (sfn) - 1] = '\0';
879 if ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
881 strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
882 GNUNET_FS_DIRECTORY_EXT)))
883 dn[strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
884 if ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
885 ((strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
887 strstr (filename + strlen (filename) -
888 strlen (GNUNET_FS_DIRECTORY_EXT), GNUNET_FS_DIRECTORY_EXT))))
890 GNUNET_asprintf (&full_name, "%s%s%s%s", dn, DIR_SEPARATOR_STR, sfn,
891 GNUNET_FS_DIRECTORY_EXT);
895 GNUNET_asprintf (&full_name, "%s%s%s", dn, DIR_SEPARATOR_STR, sfn);
900 if ((NULL != full_name) &&
901 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (full_name)))
903 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
905 ("Failed to create directory for recursive download of `%s'\n"),
907 GNUNET_free (full_name);
908 GNUNET_free_non_null (fn);
913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914 "Triggering recursive download of size %llu with %u bytes MD\n",
915 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (uri),
917 GNUNET_CONTAINER_meta_data_get_serialized_size (meta));
918 GNUNET_FS_download_start (dc->h, uri, meta, full_name, temp_name, 0,
919 GNUNET_FS_uri_chk_get_file_size (uri),
920 dc->anonymity, dc->options, NULL, dc);
921 GNUNET_free_non_null (full_name);
922 GNUNET_free_non_null (temp_name);
923 GNUNET_free_non_null (fn);
928 * (recursively) free download request structure
930 * @param dr request to free
933 GNUNET_FS_free_download_request_ (struct DownloadRequest *dr)
939 for (i = 0; i < dr->num_children; i++)
940 GNUNET_FS_free_download_request_ (dr->children[i]);
941 GNUNET_free_non_null (dr->children);
947 * Iterator over entries in the pending requests in the 'active' map for the
948 * reply that we just got.
950 * @param cls closure (our 'struct ProcessResultClosure')
951 * @param key query for the given value / request
952 * @param value value in the hash map (a 'struct DownloadRequest')
953 * @return #GNUNET_YES (we should continue to iterate); unless serious error
956 process_result_with_request (void *cls, const struct GNUNET_HashCode * key,
959 struct ProcessResultClosure *prc = cls;
960 struct DownloadRequest *dr = value;
961 struct GNUNET_FS_DownloadContext *dc = prc->dc;
962 struct DownloadRequest *drc;
963 struct GNUNET_DISK_FileHandle *fh = NULL;
964 struct GNUNET_CRYPTO_SymmetricSessionKey skey;
965 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
967 struct GNUNET_FS_ProgressInfo pi;
972 struct ContentHashKey *chkarr;
974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
975 "Received %u byte block `%s' matching pending request at depth %u and offset %llu/%llu\n",
976 (unsigned int) prc->size,
977 GNUNET_h2s (key), dr->depth, (unsigned long long) dr->offset,
978 (unsigned long long) GNUNET_ntohll (dc->uri->data.
980 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll
981 (dc->uri->data.chk.file_length),
982 dr->offset, dr->depth);
985 GNUNET_asprintf (&dc->emsg,
987 ("Internal error or bogus download URI (expected %u bytes at depth %u and offset %llu/%llu, got %u bytes)"),
988 bs, dr->depth, (unsigned long long) dr->offset,
989 (unsigned long long) GNUNET_ntohll (dc->uri->data.
992 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s\n", dc->emsg);
993 while (NULL != dr->parent)
995 dr->state = BRS_ERROR;
998 dr->state = BRS_ERROR;
1002 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &prc->query, dr);
1003 if (GNUNET_YES == dr->is_pending)
1005 GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
1006 dr->is_pending = GNUNET_NO;
1009 GNUNET_CRYPTO_hash_to_aes_key (&dr->chk.key, &skey, &iv);
1010 if (-1 == GNUNET_CRYPTO_symmetric_decrypt (prc->data, prc->size, &skey, &iv, pt))
1013 dc->emsg = GNUNET_strdup (_("internal error decrypting content"));
1017 compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
1018 dr->offset, dr->depth);
1020 if ((GNUNET_YES == prc->do_store) &&
1021 ((NULL != dc->filename) || (is_recursive_download (dc))) &&
1022 ((dr->depth == dc->treedepth) ||
1023 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES))))
1025 fh = GNUNET_DISK_file_open (NULL != dc->filename
1026 ? dc->filename : dc->temp_filename,
1027 GNUNET_DISK_OPEN_READWRITE |
1028 GNUNET_DISK_OPEN_CREATE,
1029 GNUNET_DISK_PERM_USER_READ |
1030 GNUNET_DISK_PERM_USER_WRITE |
1031 GNUNET_DISK_PERM_GROUP_READ |
1032 GNUNET_DISK_PERM_OTHER_READ);
1035 GNUNET_asprintf (&dc->emsg,
1036 _("Download failed: could not open file `%s': %s"),
1037 dc->filename, STRERROR (errno));
1040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041 "Saving decrypted block to disk at offset %llu\n",
1042 (unsigned long long) off);
1043 if ((off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)))
1045 GNUNET_asprintf (&dc->emsg,
1046 _("Failed to seek to offset %llu in file `%s': %s"),
1047 (unsigned long long) off, dc->filename,
1051 if (prc->size != GNUNET_DISK_file_write (fh, pt, prc->size))
1053 GNUNET_asprintf (&dc->emsg,
1055 ("Failed to write block of %u bytes at offset %llu in file `%s': %s"),
1056 (unsigned int) prc->size, (unsigned long long) off,
1057 dc->filename, STRERROR (errno));
1060 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
1066 /* DBLOCK, update progress and try recursion if applicable */
1068 if (dr->offset < dc->offset)
1070 /* starting offset begins in the middle of pt,
1071 * do not count first bytes as progress */
1072 GNUNET_assert (app > (dc->offset - dr->offset));
1073 app -= (dc->offset - dr->offset);
1075 if (dr->offset + prc->size > dc->offset + dc->length)
1077 /* end of block is after relevant range,
1078 * do not count last bytes as progress */
1079 GNUNET_assert (app >
1080 (dr->offset + prc->size) - (dc->offset + dc->length));
1081 app -= (dr->offset + prc->size) - (dc->offset + dc->length);
1083 dc->completed += app;
1085 /* do recursive download if option is set and either meta data
1086 * says it is a directory or if no meta data is given AND filename
1087 * ends in '.gnd' (top-level case) */
1088 if (is_recursive_download (dc))
1089 GNUNET_FS_directory_list_contents (prc->size, pt, off,
1090 &trigger_recursive_download, dc);
1092 GNUNET_assert (dc->completed <= dc->length);
1093 dr->state = BRS_DOWNLOAD_DOWN;
1094 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1095 pi.value.download.specifics.progress.data = pt;
1096 pi.value.download.specifics.progress.offset = dr->offset;
1097 pi.value.download.specifics.progress.data_len = prc->size;
1098 pi.value.download.specifics.progress.depth = dr->depth;
1099 pi.value.download.specifics.progress.respect_offered = prc->respect_offered;
1100 pi.value.download.specifics.progress.num_transmissions = prc->num_transmissions;
1101 if (prc->last_transmission.abs_value_us != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
1102 pi.value.download.specifics.progress.block_download_duration
1103 = GNUNET_TIME_absolute_get_duration (prc->last_transmission);
1105 pi.value.download.specifics.progress.block_download_duration
1106 = GNUNET_TIME_UNIT_ZERO; /* found locally */
1107 GNUNET_FS_download_make_status_ (&pi, dc);
1111 if (dc->completed == dc->length)
1113 /* download completed, signal */
1114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1115 "Download completed, truncating file to desired length %llu\n",
1116 (unsigned long long) GNUNET_ntohll (dc->uri->data.
1118 /* truncate file to size (since we store IBlocks at the end) */
1119 if (NULL != dc->filename)
1122 TRUNCATE (dc->filename,
1123 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1124 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
1127 GNUNET_assert (0 == dr->depth);
1128 check_completed (dc);
1132 /* bottom of the tree, no child downloads possible, just sync */
1133 GNUNET_FS_download_sync_ (dc);
1137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1138 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1139 dr->depth, (unsigned long long) dr->offset);
1140 GNUNET_assert (0 == (prc->size % sizeof (struct ContentHashKey)));
1141 chkarr = (struct ContentHashKey *) pt;
1142 for (i = dr->num_children - 1; i >= 0; i--)
1144 drc = dr->children[i];
1148 if ((drc->chk_idx + 1) * sizeof (struct ContentHashKey) > prc->size)
1150 /* 'chkarr' does not have enough space for this chk_idx;
1152 GNUNET_break (0); GNUNET_assert (0);
1153 dc->emsg = GNUNET_strdup (_("internal error decoding tree"));
1156 drc->chk = chkarr[drc->chk_idx];
1157 drc->state = BRS_CHK_SET;
1158 if (GNUNET_YES == dc->issue_requests)
1159 schedule_block_download (dc, drc);
1161 case BRS_RECONSTRUCT_DOWN:
1164 case BRS_RECONSTRUCT_META_UP:
1167 case BRS_RECONSTRUCT_UP:
1173 case BRS_DOWNLOAD_DOWN:
1176 case BRS_DOWNLOAD_UP:
1187 GNUNET_FS_download_sync_ (dc);
1192 GNUNET_DISK_file_close (fh);
1193 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1194 pi.value.download.specifics.error.message = dc->emsg;
1195 GNUNET_FS_download_make_status_ (&pi, dc);
1196 /* abort all pending requests */
1199 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1202 GNUNET_CLIENT_disconnect (dc->client);
1203 dc->in_receive = GNUNET_NO;
1205 GNUNET_FS_free_download_request_ (dc->top_request);
1206 dc->top_request = NULL;
1207 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1209 if (NULL != dc->job_queue)
1211 GNUNET_FS_dequeue_ (dc->job_queue);
1212 dc->job_queue = NULL;
1214 dc->pending_head = NULL;
1215 dc->pending_tail = NULL;
1216 GNUNET_FS_download_sync_ (dc);
1222 * Process a download result.
1224 * @param dc our download context
1225 * @param type type of the result
1226 * @param respect_offered how much respect did we offer to get this reply?
1227 * @param num_transmissions how often did we transmit the query?
1228 * @param last_transmission when was this block requested the last time? (FOREVER if unknown/not applicable)
1229 * @param data the (encrypted) response
1230 * @param size size of data
1233 process_result (struct GNUNET_FS_DownloadContext *dc,
1234 enum GNUNET_BLOCK_Type type,
1235 uint32_t respect_offered,
1236 uint32_t num_transmissions,
1237 struct GNUNET_TIME_Absolute last_transmission,
1238 const void *data, size_t size)
1240 struct ProcessResultClosure prc;
1244 prc.last_transmission = last_transmission;
1247 prc.do_store = GNUNET_YES;
1248 prc.respect_offered = respect_offered;
1249 prc.num_transmissions = num_transmissions;
1250 GNUNET_CRYPTO_hash (data, size, &prc.query);
1251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1252 "Received result for query `%s' from `%s'-service\n",
1253 GNUNET_h2s (&prc.query), "FS");
1254 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active, &prc.query,
1255 &process_result_with_request,
1261 * Type of a function to call when we receive a message
1264 * @param cls closure
1265 * @param msg message received, NULL on timeout or fatal error
1268 receive_results (void *cls, const struct GNUNET_MessageHeader *msg)
1270 struct GNUNET_FS_DownloadContext *dc = cls;
1271 const struct ClientPutMessage *cm;
1274 if ((NULL == msg) || (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1275 (sizeof (struct ClientPutMessage) > ntohs (msg->size)))
1277 GNUNET_break (NULL == msg);
1281 msize = ntohs (msg->size);
1282 cm = (const struct ClientPutMessage *) msg;
1283 process_result (dc, ntohl (cm->type),
1284 ntohl (cm->respect_offered),
1285 ntohl (cm->num_transmissions),
1286 GNUNET_TIME_absolute_ntoh (cm->last_transmission), &cm[1],
1287 msize - sizeof (struct ClientPutMessage));
1288 if (NULL == dc->client)
1289 return; /* fatal error */
1290 /* continue receiving */
1291 GNUNET_CLIENT_receive (dc->client, &receive_results, dc,
1292 GNUNET_TIME_UNIT_FOREVER_REL);
1297 * We're ready to transmit a search request to the
1298 * file-sharing service. Do it. If there is
1299 * more than one request pending, try to send
1300 * multiple or request another transmission.
1302 * @param cls closure
1303 * @param size number of bytes available in buf
1304 * @param buf where the callee should write the message
1305 * @return number of bytes written to buf
1308 transmit_download_request (void *cls, size_t size, void *buf)
1310 struct GNUNET_FS_DownloadContext *dc = cls;
1312 struct SearchMessage *sm;
1313 struct DownloadRequest *dr;
1318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1319 "Transmitting download request failed, trying to reconnect\n");
1323 GNUNET_assert (size >= sizeof (struct SearchMessage));
1326 while ((NULL != (dr = dc->pending_head)) &&
1327 (size >= msize + sizeof (struct SearchMessage)))
1329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1330 "Transmitting download request for `%s' to `%s'-service\n",
1331 GNUNET_h2s (&dr->chk.query), "FS");
1332 memset (sm, 0, sizeof (struct SearchMessage));
1333 sm->header.size = htons (sizeof (struct SearchMessage));
1334 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1335 if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1336 sm->options = htonl (GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY);
1338 sm->options = htonl (GNUNET_FS_SEARCH_OPTION_NONE);
1340 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_DBLOCK);
1342 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_IBLOCK);
1343 sm->anonymity_level = htonl (dc->anonymity);
1344 sm->target = dc->target;
1345 sm->query = dr->chk.query;
1346 GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
1347 dr->is_pending = GNUNET_NO;
1348 msize += sizeof (struct SearchMessage);
1351 if (NULL != dc->pending_head)
1354 GNUNET_CLIENT_notify_transmit_ready (dc->client,
1355 sizeof (struct SearchMessage),
1356 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1358 &transmit_download_request, dc);
1359 GNUNET_assert (NULL != dc->th);
1361 if (GNUNET_NO == dc->in_receive)
1363 dc->in_receive = GNUNET_YES;
1364 GNUNET_CLIENT_receive (dc->client, &receive_results, dc,
1365 GNUNET_TIME_UNIT_FOREVER_REL);
1372 * Reconnect to the FS service and transmit our queries NOW.
1374 * @param cls our download context
1378 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1380 struct GNUNET_FS_DownloadContext *dc = cls;
1381 struct GNUNET_CLIENT_Connection *client;
1383 dc->task = GNUNET_SCHEDULER_NO_TASK;
1384 client = GNUNET_CLIENT_connect ("fs", dc->h->cfg);
1387 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1388 "Connecting to `%s'-service failed, will try again.\n", "FS");
1392 dc->client = client;
1393 if (NULL != dc->pending_head)
1396 GNUNET_CLIENT_notify_transmit_ready (client,
1397 sizeof (struct SearchMessage),
1398 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1400 &transmit_download_request, dc);
1401 GNUNET_assert (NULL != dc->th);
1407 * Add entries to the pending list.
1409 * @param cls our download context
1411 * @param entry entry of type "struct DownloadRequest"
1415 retry_entry (void *cls, const struct GNUNET_HashCode * key, void *entry)
1417 struct GNUNET_FS_DownloadContext *dc = cls;
1418 struct DownloadRequest *dr = entry;
1422 GNUNET_CONTAINER_DLL_insert (dc->pending_head, dc->pending_tail, dr);
1423 dr->is_pending = GNUNET_YES;
1429 * We've lost our connection with the FS service.
1430 * Re-establish it and re-transmit all of our
1433 * @param dc download context that is having trouble
1436 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1439 if (NULL != dc->client)
1441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1442 "Moving all requests back to pending list\n");
1445 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1448 /* full reset of the pending list */
1449 dc->pending_head = NULL;
1450 dc->pending_tail = NULL;
1451 GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1452 GNUNET_CLIENT_disconnect (dc->client);
1453 dc->in_receive = GNUNET_NO;
1456 if (0 == dc->reconnect_backoff.rel_value_us)
1457 dc->reconnect_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1459 dc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (dc->reconnect_backoff);
1461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Will try to reconnect in %s\n",
1462 GNUNET_STRINGS_relative_time_to_string (dc->reconnect_backoff, GNUNET_YES));
1464 GNUNET_SCHEDULER_add_delayed (dc->reconnect_backoff,
1471 * We're allowed to ask the FS service for our blocks. Start the download.
1473 * @param cls the 'struct GNUNET_FS_DownloadContext'
1474 * @param client handle to use for communcation with FS (we must destroy it!)
1477 activate_fs_download (void *cls, struct GNUNET_CLIENT_Connection *client)
1479 struct GNUNET_FS_DownloadContext *dc = cls;
1480 struct GNUNET_FS_ProgressInfo pi;
1482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download activated\n");
1483 GNUNET_assert (NULL != client);
1484 GNUNET_assert (NULL == dc->client);
1485 GNUNET_assert (NULL == dc->th);
1486 GNUNET_assert (NULL != dc->active);
1487 dc->client = client;
1488 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1489 GNUNET_FS_download_make_status_ (&pi, dc);
1490 dc->pending_head = NULL;
1491 dc->pending_tail = NULL;
1492 GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1494 "Asking for transmission to FS service\n");
1495 if (NULL != dc->pending_head)
1498 GNUNET_CLIENT_notify_transmit_ready (dc->client,
1499 sizeof (struct SearchMessage),
1500 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1502 &transmit_download_request, dc);
1503 GNUNET_assert (NULL != dc->th);
1509 * We must stop to ask the FS service for our blocks. Pause the download.
1511 * @param cls the `struct GNUNET_FS_DownloadContext`
1514 deactivate_fs_download (void *cls)
1516 struct GNUNET_FS_DownloadContext *dc = cls;
1517 struct GNUNET_FS_ProgressInfo pi;
1519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download deactivated\n");
1522 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1525 if (NULL != dc->client)
1527 GNUNET_CLIENT_disconnect (dc->client);
1528 dc->in_receive = GNUNET_NO;
1531 dc->pending_head = NULL;
1532 dc->pending_tail = NULL;
1533 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1534 GNUNET_FS_download_make_status_ (&pi, dc);
1539 * (recursively) Create a download request structure.
1541 * @param parent parent of the current entry
1542 * @param chk_idx index of the chk for this block in the parent block
1543 * @param depth depth of the current entry, 0 are the DBLOCKs,
1544 * top level block is 'dc->treedepth - 1'
1545 * @param dr_offset offset in the original file this block maps to
1546 * (as in, offset of the first byte of the first DBLOCK
1547 * in the subtree rooted in the returned download request tree)
1548 * @param file_start_offset desired starting offset for the download
1549 * in the original file; requesting tree should not contain
1550 * DBLOCKs prior to the file_start_offset
1551 * @param desired_length desired number of bytes the user wanted to access
1552 * (from file_start_offset). Resulting tree should not contain
1553 * DBLOCKs after file_start_offset + file_length.
1554 * @return download request tree for the given range of DBLOCKs at
1555 * the specified depth
1557 static struct DownloadRequest *
1558 create_download_request (struct DownloadRequest *parent,
1559 unsigned int chk_idx,
1561 uint64_t dr_offset, uint64_t file_start_offset,
1562 uint64_t desired_length)
1564 struct DownloadRequest *dr;
1566 unsigned int head_skip;
1567 uint64_t child_block_size;
1569 dr = GNUNET_new (struct DownloadRequest);
1570 dr->parent = parent;
1572 dr->offset = dr_offset;
1573 dr->chk_idx = chk_idx;
1576 child_block_size = GNUNET_FS_tree_compute_tree_size (depth - 1);
1578 /* calculate how many blocks at this level are not interesting
1579 * from the start (rounded down), either because of the requested
1580 * file offset or because this IBlock is further along */
1581 if (dr_offset < file_start_offset)
1583 head_skip = (file_start_offset - dr_offset) / child_block_size;
1590 /* calculate index of last block at this level that is interesting (rounded up) */
1591 dr->num_children = (file_start_offset + desired_length - dr_offset) / child_block_size;
1592 if (dr->num_children * child_block_size <
1593 file_start_offset + desired_length - dr_offset)
1594 dr->num_children++; /* round up */
1595 GNUNET_assert (dr->num_children > head_skip);
1596 dr->num_children -= head_skip;
1597 if (dr->num_children > CHK_PER_INODE)
1598 dr->num_children = CHK_PER_INODE; /* cap at max */
1599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600 "Block at offset %llu and depth %u has %u children\n",
1601 (unsigned long long) dr_offset,
1605 /* now we can get the total number of *interesting* children for this block */
1607 /* why else would we have gotten here to begin with? (that'd be a bad logic error) */
1608 GNUNET_assert (dr->num_children > 0);
1611 GNUNET_malloc (dr->num_children * sizeof (struct DownloadRequest *));
1612 for (i = 0; i < dr->num_children; i++)
1615 create_download_request (dr, i + head_skip, depth - 1,
1616 dr_offset + (i + head_skip) * child_block_size,
1617 file_start_offset, desired_length);
1624 * Continuation after a possible attempt to reconstruct
1625 * the current IBlock from the existing file.
1627 * @param cls the 'struct ReconstructContext'
1628 * @param tc scheduler context
1631 reconstruct_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1633 struct GNUNET_FS_DownloadContext *dc = cls;
1635 /* clean up state from tree encoder */
1636 if (dc->task != GNUNET_SCHEDULER_NO_TASK)
1638 GNUNET_SCHEDULER_cancel (dc->task);
1639 dc->task = GNUNET_SCHEDULER_NO_TASK;
1641 if (NULL != dc->rfh)
1643 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
1646 /* start "normal" download */
1647 dc->issue_requests = GNUNET_YES;
1648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1649 "Starting normal download\n");
1650 schedule_block_download (dc, dc->top_request);
1655 * Task requesting the next block from the tree encoder.
1657 * @param cls the 'struct GNUJNET_FS_DownloadContext' we're processing
1658 * @param tc task context
1661 get_next_block (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1663 struct GNUNET_FS_DownloadContext *dc = cls;
1665 dc->task = GNUNET_SCHEDULER_NO_TASK;
1666 GNUNET_FS_tree_encoder_next (dc->te);
1671 * Function called asking for the current (encoded)
1672 * block to be processed. After processing the
1673 * client should either call "GNUNET_FS_tree_encode_next"
1674 * or (on error) "GNUNET_FS_tree_encode_finish".
1676 * This function checks if the content on disk matches
1677 * the expected content based on the URI.
1679 * @param cls closure
1680 * @param chk content hash key for the block
1681 * @param offset offset of the block
1682 * @param depth depth of the block, 0 for DBLOCK
1683 * @param type type of the block (IBLOCK or DBLOCK)
1684 * @param block the (encrypted) block
1685 * @param block_size size of block (in bytes)
1688 reconstruct_cb (void *cls, const struct ContentHashKey *chk, uint64_t offset,
1689 unsigned int depth, enum GNUNET_BLOCK_Type type,
1690 const void *block, uint16_t block_size)
1692 struct GNUNET_FS_DownloadContext *dc = cls;
1693 struct GNUNET_FS_ProgressInfo pi;
1694 struct DownloadRequest *dr;
1698 /* find corresponding request entry */
1699 dr = dc->top_request;
1700 while (dr->depth > depth)
1702 GNUNET_assert (dr->num_children > 0);
1703 blen = GNUNET_FS_tree_compute_tree_size (dr->depth - 1);
1704 chld = (offset - dr->offset) / blen;
1705 if (chld < dr->children[0]->chk_idx)
1707 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1708 "Block %u < %u irrelevant for our range\n",
1710 dr->children[0]->chk_idx);
1711 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1712 return; /* irrelevant block */
1714 if (chld > dr->children[dr->num_children-1]->chk_idx)
1716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1717 "Block %u > %u irrelevant for our range\n",
1719 dr->children[dr->num_children-1]->chk_idx);
1720 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1721 return; /* irrelevant block */
1723 dr = dr->children[chld - dr->children[0]->chk_idx];
1725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1726 "Matched TE block with request at offset %llu and depth %u in state %d\n",
1727 (unsigned long long) dr->offset,
1730 /* FIXME: this code needs more testing and might
1731 need to handle more states... */
1736 case BRS_RECONSTRUCT_DOWN:
1738 case BRS_RECONSTRUCT_META_UP:
1740 case BRS_RECONSTRUCT_UP:
1743 if (0 == memcmp (chk, &dr->chk, sizeof (struct ContentHashKey)))
1745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1746 "Reconstruction succeeded, can use block at offset %llu, depth %u\n",
1747 (unsigned long long) offset,
1749 /* block matches, hence tree below matches;
1750 * this request is done! */
1751 dr->state = BRS_DOWNLOAD_UP;
1752 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &dr->chk.query, dr);
1753 if (GNUNET_YES == dr->is_pending)
1755 GNUNET_break (0); /* how did we get here? */
1756 GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
1757 dr->is_pending = GNUNET_NO;
1759 /* calculate how many bytes of payload this block
1761 blen = GNUNET_FS_tree_compute_tree_size (dr->depth);
1762 /* how many of those bytes are in the requested range? */
1763 blen = GNUNET_MIN (blen, dc->length + dc->offset - dr->offset);
1764 /* signal progress */
1765 dc->completed += blen;
1766 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1767 pi.value.download.specifics.progress.data = NULL;
1768 pi.value.download.specifics.progress.offset = offset;
1769 pi.value.download.specifics.progress.data_len = 0;
1770 pi.value.download.specifics.progress.depth = 0;
1771 pi.value.download.specifics.progress.respect_offered = 0;
1772 pi.value.download.specifics.progress.block_download_duration = GNUNET_TIME_UNIT_ZERO;
1773 GNUNET_FS_download_make_status_ (&pi, dc);
1774 /* FIXME: duplicated code from 'process_result_with_request - refactor */
1775 if (dc->completed == dc->length)
1777 /* download completed, signal */
1778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1779 "Download completed, truncating file to desired length %llu\n",
1780 (unsigned long long) GNUNET_ntohll (dc->uri->data.
1782 /* truncate file to size (since we store IBlocks at the end) */
1783 if (NULL != dc->filename)
1786 TRUNCATE (dc->filename,
1787 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1788 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
1794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1795 "Reconstruction failed, need to download block at offset %llu, depth %u\n",
1796 (unsigned long long) offset,
1799 case BRS_DOWNLOAD_DOWN:
1801 case BRS_DOWNLOAD_UP:
1809 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1810 if ((dr == dc->top_request) && (dr->state == BRS_DOWNLOAD_UP))
1811 check_completed (dc);
1816 * Function called by the tree encoder to obtain a block of plaintext
1817 * data (for the lowest level of the tree).
1819 * @param cls our 'struct ReconstructContext'
1820 * @param offset identifies which block to get
1821 * @param max (maximum) number of bytes to get; returning
1822 * fewer will also cause errors
1823 * @param buf where to copy the plaintext buffer
1824 * @param emsg location to store an error message (on error)
1825 * @return number of bytes copied to buf, 0 on error
1828 fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg)
1830 struct GNUNET_FS_DownloadContext *dc = cls;
1831 struct GNUNET_DISK_FileHandle *fh = dc->rfh;
1836 if (offset != GNUNET_DISK_file_seek (fh, offset, GNUNET_DISK_SEEK_SET))
1839 *emsg = GNUNET_strdup (strerror (errno));
1842 ret = GNUNET_DISK_file_read (fh, buf, max);
1846 *emsg = GNUNET_strdup (strerror (errno));
1854 * Task that creates the initial (top-level) download
1855 * request for the file.
1857 * @param cls the 'struct GNUNET_FS_DownloadContext'
1858 * @param tc scheduler context
1861 GNUNET_FS_download_start_task_ (void *cls,
1862 const struct GNUNET_SCHEDULER_TaskContext *tc)
1864 struct GNUNET_FS_DownloadContext *dc = cls;
1865 struct GNUNET_FS_ProgressInfo pi;
1866 struct GNUNET_DISK_FileHandle *fh;
1868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start task running...\n");
1869 dc->task = GNUNET_SCHEDULER_NO_TASK;
1870 if (0 == dc->length)
1872 /* no bytes required! */
1873 if (NULL != dc->filename)
1875 fh = GNUNET_DISK_file_open (dc->filename,
1876 GNUNET_DISK_OPEN_READWRITE |
1877 GNUNET_DISK_OPEN_CREATE |
1879 GNUNET_FS_uri_chk_get_file_size (dc->uri)) ?
1880 GNUNET_DISK_OPEN_TRUNCATE : 0),
1881 GNUNET_DISK_PERM_USER_READ |
1882 GNUNET_DISK_PERM_USER_WRITE |
1883 GNUNET_DISK_PERM_GROUP_READ |
1884 GNUNET_DISK_PERM_OTHER_READ);
1885 GNUNET_DISK_file_close (fh);
1887 GNUNET_FS_download_sync_ (dc);
1888 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1889 pi.value.download.specifics.start.meta = dc->meta;
1890 GNUNET_FS_download_make_status_ (&pi, dc);
1891 check_completed (dc);
1894 if (NULL != dc->emsg)
1896 if (NULL == dc->top_request)
1899 create_download_request (NULL, 0, dc->treedepth - 1, 0, dc->offset,
1901 dc->top_request->state = BRS_CHK_SET;
1902 dc->top_request->chk =
1904 GNUNET_FS_URI_CHK) ? dc->uri->data.chk.chk : dc->uri->data.loc.fi.chk;
1906 GNUNET_FS_download_sync_ (dc);
1907 if (NULL != dc->search)
1908 GNUNET_FS_search_result_sync_ (dc->search);
1909 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1910 pi.value.download.specifics.start.meta = dc->meta;
1911 GNUNET_FS_download_make_status_ (&pi, dc);
1913 GNUNET_FS_download_start_downloading_ (dc);
1914 /* attempt reconstruction from disk */
1915 if (GNUNET_YES == GNUNET_DISK_file_test (dc->filename))
1917 GNUNET_DISK_file_open (dc->filename, GNUNET_DISK_OPEN_READ,
1918 GNUNET_DISK_PERM_NONE);
1919 if (dc->top_request->state == BRS_CHK_SET)
1921 if (NULL != dc->rfh)
1923 /* first, try top-down */
1924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1925 "Trying top-down reconstruction for `%s'\n", dc->filename);
1926 try_top_down_reconstruction (dc, dc->top_request);
1927 switch (dc->top_request->state)
1931 case BRS_DOWNLOAD_DOWN:
1932 break; /* normal, some blocks already down */
1933 case BRS_DOWNLOAD_UP:
1934 /* already done entirely, party! */
1935 if (NULL != dc->rfh)
1937 /* avoid hanging on to file handle longer than
1939 GNUNET_DISK_file_close (dc->rfh);
1944 GNUNET_asprintf (&dc->emsg, _("Invalid URI"));
1945 GNUNET_FS_download_sync_ (dc);
1946 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1947 pi.value.download.specifics.error.message = dc->emsg;
1948 GNUNET_FS_download_make_status_ (&pi, dc);
1956 /* attempt reconstruction from meta data */
1957 if ((GNUNET_FS_uri_chk_get_file_size (dc->uri) <= MAX_INLINE_SIZE) &&
1960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1961 "Trying to find embedded meta data for download of size %llu with %u bytes MD\n",
1962 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (dc->uri),
1964 GNUNET_CONTAINER_meta_data_get_serialized_size (dc->meta));
1965 GNUNET_CONTAINER_meta_data_iterate (dc->meta, &match_full_data, dc);
1966 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1968 if (NULL != dc->rfh)
1970 /* avoid hanging on to file handle longer than
1972 GNUNET_DISK_file_close (dc->rfh);
1975 return; /* finished, status update was already done for us */
1978 if (NULL != dc->rfh)
1980 /* finally, actually run bottom-up */
1981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982 "Trying bottom-up reconstruction of file `%s'\n", dc->filename);
1984 GNUNET_FS_tree_encoder_create (dc->h,
1985 GNUNET_FS_uri_chk_get_file_size (dc->uri),
1987 &reconstruct_cb, NULL,
1989 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1993 /* simple, top-level download */
1994 dc->issue_requests = GNUNET_YES;
1995 schedule_block_download (dc, dc->top_request);
1997 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1998 check_completed (dc);
2003 * Create SUSPEND event for the given download operation
2004 * and then clean up our state (without stop signal).
2006 * @param cls the 'struct GNUNET_FS_DownloadContext' to signal for
2009 GNUNET_FS_download_signal_suspend_ (void *cls)
2011 struct GNUNET_FS_DownloadContext *dc = cls;
2012 struct GNUNET_FS_ProgressInfo pi;
2014 if (NULL != dc->top)
2015 GNUNET_FS_end_top (dc->h, dc->top);
2016 while (NULL != dc->child_head)
2017 GNUNET_FS_download_signal_suspend_ (dc->child_head);
2018 if (NULL != dc->search)
2020 dc->search->download = NULL;
2023 if (NULL != dc->job_queue)
2025 GNUNET_FS_dequeue_ (dc->job_queue);
2026 dc->job_queue = NULL;
2028 if (NULL != dc->parent)
2029 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, dc->parent->child_tail,
2031 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
2033 GNUNET_SCHEDULER_cancel (dc->task);
2034 dc->task = GNUNET_SCHEDULER_NO_TASK;
2036 pi.status = GNUNET_FS_STATUS_DOWNLOAD_SUSPEND;
2037 GNUNET_FS_download_make_status_ (&pi, dc);
2040 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
2043 if (NULL != dc->rfh)
2045 GNUNET_DISK_file_close (dc->rfh);
2048 GNUNET_FS_free_download_request_ (dc->top_request);
2049 if (NULL != dc->active)
2051 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2054 GNUNET_free_non_null (dc->filename);
2055 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2056 GNUNET_FS_uri_destroy (dc->uri);
2057 GNUNET_free_non_null (dc->temp_filename);
2058 GNUNET_free_non_null (dc->serialization);
2059 GNUNET_assert (NULL == dc->job_queue);
2065 * Helper function to setup the download context.
2067 * @param h handle to the file sharing subsystem
2068 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2069 * @param meta known metadata for the file (can be NULL)
2070 * @param filename where to store the file, maybe NULL (then no file is
2071 * created on disk and data must be grabbed from the callbacks)
2072 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2073 * can be NULL (in which case we will pick a name if needed); the temporary file
2074 * may already exist, in which case we will try to use the data that is there and
2075 * if it is not what is desired, will overwrite it
2076 * @param offset at what offset should we start the download (typically 0)
2077 * @param length how many bytes should be downloaded starting at offset
2078 * @param anonymity anonymity level to use for the download
2079 * @param options various options
2080 * @param cctx initial value for the client context for this download
2081 * @return context that can be used to control this download
2083 struct GNUNET_FS_DownloadContext *
2084 create_download_context (struct GNUNET_FS_Handle *h,
2085 const struct GNUNET_FS_Uri *uri,
2086 const struct GNUNET_CONTAINER_MetaData *meta,
2087 const char *filename, const char *tempname,
2088 uint64_t offset, uint64_t length, uint32_t anonymity,
2089 enum GNUNET_FS_DownloadOptions options, void *cctx)
2091 struct GNUNET_FS_DownloadContext *dc;
2093 GNUNET_assert (GNUNET_FS_uri_test_chk (uri) || GNUNET_FS_uri_test_loc (uri));
2094 if ((offset + length < offset) ||
2095 (offset + length > GNUNET_FS_uri_chk_get_file_size (uri)))
2100 dc = GNUNET_new (struct GNUNET_FS_DownloadContext);
2101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2102 "Starting download %p, %u bytes at offset %llu\n",
2104 (unsigned long long) length,
2105 (unsigned long long) offset);
2107 dc->uri = GNUNET_FS_uri_dup (uri);
2108 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
2109 dc->client_info = cctx;
2110 dc->start_time = GNUNET_TIME_absolute_get ();
2111 if (NULL != filename)
2113 dc->filename = GNUNET_strdup (filename);
2114 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
2115 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_size (filename, &dc->old_file_size, GNUNET_YES, GNUNET_YES));
2117 if (GNUNET_FS_uri_test_loc (dc->uri))
2118 GNUNET_assert (GNUNET_OK ==
2119 GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target));
2120 dc->offset = offset;
2121 dc->length = length;
2122 dc->anonymity = anonymity;
2123 dc->options = options;
2125 GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE), GNUNET_NO);
2127 GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri));
2128 if ((NULL == filename) && (is_recursive_download (dc)))
2130 if (NULL != tempname)
2131 dc->temp_filename = GNUNET_strdup (tempname);
2133 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2136 "Starting download `%s' of %llu bytes with tree depth %u\n",
2138 (unsigned long long) length,
2140 dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2146 * Download parts of a file. Note that this will store
2147 * the blocks at the respective offset in the given file. Also, the
2148 * download is still using the blocking of the underlying FS
2149 * encoding. As a result, the download may *write* outside of the
2150 * given boundaries (if offset and length do not match the 32k FS
2151 * block boundaries). <p>
2153 * This function should be used to focus a download towards a
2154 * particular portion of the file (optimization), not to strictly
2155 * limit the download to exactly those bytes.
2157 * @param h handle to the file sharing subsystem
2158 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2159 * @param meta known metadata for the file (can be NULL)
2160 * @param filename where to store the file, maybe NULL (then no file is
2161 * created on disk and data must be grabbed from the callbacks)
2162 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2163 * can be NULL (in which case we will pick a name if needed); the temporary file
2164 * may already exist, in which case we will try to use the data that is there and
2165 * if it is not what is desired, will overwrite it
2166 * @param offset at what offset should we start the download (typically 0)
2167 * @param length how many bytes should be downloaded starting at offset
2168 * @param anonymity anonymity level to use for the download
2169 * @param options various options
2170 * @param cctx initial value for the client context for this download
2171 * @param parent parent download to associate this download with (use NULL
2172 * for top-level downloads; useful for manually-triggered recursive downloads)
2173 * @return context that can be used to control this download
2175 struct GNUNET_FS_DownloadContext *
2176 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
2177 const struct GNUNET_FS_Uri *uri,
2178 const struct GNUNET_CONTAINER_MetaData *meta,
2179 const char *filename, const char *tempname,
2180 uint64_t offset, uint64_t length, uint32_t anonymity,
2181 enum GNUNET_FS_DownloadOptions options, void *cctx,
2182 struct GNUNET_FS_DownloadContext *parent)
2184 struct GNUNET_FS_DownloadContext *dc;
2186 dc = create_download_context (h, uri, meta, filename, tempname,
2187 offset, length, anonymity, options, cctx);
2190 dc->parent = parent;
2192 GNUNET_CONTAINER_DLL_insert (parent->child_head, parent->child_tail, dc);
2193 else if (0 == (GNUNET_FS_DOWNLOAD_IS_PROBE & options) )
2195 GNUNET_FS_make_top (dc->h, &GNUNET_FS_download_signal_suspend_, dc);
2201 * Download parts of a file based on a search result. The download
2202 * will be associated with the search result (and the association
2203 * will be preserved when serializing/deserializing the state).
2204 * If the search is stopped, the download will not be aborted but
2205 * be 'promoted' to a stand-alone download.
2207 * As with the other download function, this will store
2208 * the blocks at the respective offset in the given file. Also, the
2209 * download is still using the blocking of the underlying FS
2210 * encoding. As a result, the download may *write* outside of the
2211 * given boundaries (if offset and length do not match the 32k FS
2212 * block boundaries). <p>
2214 * The given range can be used to focus a download towards a
2215 * particular portion of the file (optimization), not to strictly
2216 * limit the download to exactly those bytes.
2218 * @param h handle to the file sharing subsystem
2219 * @param sr the search result to use for the download (determines uri and
2220 * meta data and associations)
2221 * @param filename where to store the file, maybe NULL (then no file is
2222 * created on disk and data must be grabbed from the callbacks)
2223 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2224 * can be NULL (in which case we will pick a name if needed); the temporary file
2225 * may already exist, in which case we will try to use the data that is there and
2226 * if it is not what is desired, will overwrite it
2227 * @param offset at what offset should we start the download (typically 0)
2228 * @param length how many bytes should be downloaded starting at offset
2229 * @param anonymity anonymity level to use for the download
2230 * @param options various download options
2231 * @param cctx initial value for the client context for this download
2232 * @return context that can be used to control this download
2234 struct GNUNET_FS_DownloadContext *
2235 GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h,
2236 struct GNUNET_FS_SearchResult *sr,
2237 const char *filename,
2238 const char *tempname, uint64_t offset,
2239 uint64_t length, uint32_t anonymity,
2240 enum GNUNET_FS_DownloadOptions options,
2243 struct GNUNET_FS_DownloadContext *dc;
2245 if ((NULL == sr) || (NULL != sr->download))
2250 dc = create_download_context (h, sr->uri, sr->meta, filename, tempname,
2251 offset, length, anonymity, options, cctx);
2256 if (NULL != sr->probe_ctx)
2258 GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
2259 sr->probe_ctx = NULL;
2260 GNUNET_FS_stop_probe_ping_task_ (sr);
2267 * Start the downloading process (by entering the queue).
2269 * @param dc our download context
2272 GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc)
2274 if (dc->completed == dc->length)
2276 GNUNET_assert (NULL == dc->job_queue);
2277 GNUNET_assert (NULL != dc->active);
2279 GNUNET_FS_queue_ (dc->h, &activate_fs_download, &deactivate_fs_download,
2280 dc, (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE,
2281 (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
2282 ? GNUNET_FS_QUEUE_PRIORITY_NORMAL
2283 : GNUNET_FS_QUEUE_PRIORITY_PROBE);
2284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2285 "Download %p put into queue as job %p\n",
2291 * Suspend a download.
2293 * @param dc handle for the download
2296 GNUNET_FS_download_suspend (struct GNUNET_FS_DownloadContext *dc)
2298 deactivate_fs_download(dc);
2302 * Resume a suspended download.
2304 * @param dc handle for the download
2307 GNUNET_FS_download_resume (struct GNUNET_FS_DownloadContext *dc)
2309 struct GNUNET_FS_ProgressInfo pi;
2311 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
2312 GNUNET_FS_download_make_status_ (&pi, dc);
2315 GNUNET_FS_queue_ (dc->h, &activate_fs_download, &deactivate_fs_download,
2316 dc, (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE,
2317 (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
2318 ? GNUNET_FS_QUEUE_PRIORITY_NORMAL
2319 : GNUNET_FS_QUEUE_PRIORITY_PROBE);
2325 * Stop a download (aborts if download is incomplete).
2327 * @param dc handle for the download
2328 * @param do_delete delete files of incomplete downloads
2331 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete)
2333 struct GNUNET_FS_ProgressInfo pi;
2335 int search_was_null;
2337 if (NULL != dc->top)
2338 GNUNET_FS_end_top (dc->h, dc->top);
2339 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
2341 GNUNET_SCHEDULER_cancel (dc->task);
2342 dc->task = GNUNET_SCHEDULER_NO_TASK;
2344 search_was_null = (NULL == dc->search);
2345 if (NULL != dc->search)
2347 dc->search->download = NULL;
2348 GNUNET_FS_search_result_sync_ (dc->search);
2351 if (NULL != dc->job_queue)
2353 GNUNET_FS_dequeue_ (dc->job_queue);
2354 dc->job_queue = NULL;
2358 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
2361 have_children = (NULL != dc->child_head) ? GNUNET_YES : GNUNET_NO;
2362 while (NULL != dc->child_head)
2363 GNUNET_FS_download_stop (dc->child_head, do_delete);
2364 if (NULL != dc->parent)
2365 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, dc->parent->child_tail,
2367 if (NULL != dc->serialization)
2368 GNUNET_FS_remove_sync_file_ (dc->h,
2369 ((NULL != dc->parent) ||
2370 (! search_was_null)) ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD :
2371 GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2373 if ((GNUNET_YES == have_children) && (NULL == dc->parent))
2374 GNUNET_FS_remove_sync_dir_ (dc->h,
2375 (! search_was_null) ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD :
2376 GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2378 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
2379 GNUNET_FS_download_make_status_ (&pi, dc);
2380 GNUNET_FS_free_download_request_ (dc->top_request);
2381 dc->top_request = NULL;
2382 if (NULL != dc->active)
2384 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2387 if (NULL != dc->filename)
2389 if ((dc->completed != dc->length) && (GNUNET_YES == do_delete))
2391 if ( (0 != UNLINK (dc->filename)) &&
2393 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
2396 GNUNET_free (dc->filename);
2398 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2399 GNUNET_FS_uri_destroy (dc->uri);
2400 if (NULL != dc->temp_filename)
2402 if (0 != UNLINK (dc->temp_filename))
2403 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "unlink",
2405 GNUNET_free (dc->temp_filename);
2407 GNUNET_free_non_null (dc->serialization);
2408 GNUNET_assert (NULL == dc->job_queue);
2412 /* end of fs_download.c */