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_AesSessionKey sk;
238 struct GNUNET_CRYPTO_AesInitializationVector iv;
239 struct GNUNET_HashCode query;
241 GNUNET_CRYPTO_hash_to_aes_key (&chk->key, &sk, &iv);
242 if (-1 == GNUNET_CRYPTO_aes_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_AesSessionKey sk;
438 struct GNUNET_CRYPTO_AesInitializationVector iv;
440 struct DownloadRequest *drc;
441 struct GNUNET_DISK_FileHandle *fh;
448 odata_len = data_len;
449 if (BRS_DOWNLOAD_UP == dr->state)
453 complete = GNUNET_YES;
454 for (i = 0; i < dr->num_children; i++)
456 drc = dr->children[i];
457 try_match_block (dc, drc, data, data_len);
458 if (drc->state != BRS_RECONSTRUCT_META_UP)
459 complete = GNUNET_NO;
463 if (GNUNET_YES != complete)
465 data = (const char *) chks;
466 dlen = dr->num_children * sizeof (struct ContentHashKey);
470 if (dr->offset > data_len)
472 dlen = GNUNET_MIN (data_len - dr->offset, DBLOCK_SIZE);
474 GNUNET_CRYPTO_hash (&data[dr->offset], dlen, &in_chk.key);
475 GNUNET_CRYPTO_hash_to_aes_key (&in_chk.key, &sk, &iv);
476 if (-1 == GNUNET_CRYPTO_aes_encrypt (&data[dr->offset], dlen, &sk, &iv, enc))
481 GNUNET_CRYPTO_hash (enc, dlen, &in_chk.query);
486 dr->state = BRS_RECONSTRUCT_META_UP;
489 if (0 != memcmp (&in_chk, &dr->chk, sizeof (struct ContentHashKey)))
491 /* other peer provided bogus meta data */
495 /* write block to disk */
496 fn = (NULL != dc->filename) ? dc->filename : dc->temp_filename;
497 fh = GNUNET_DISK_file_open (fn,
498 GNUNET_DISK_OPEN_READWRITE |
499 GNUNET_DISK_OPEN_CREATE |
500 GNUNET_DISK_OPEN_TRUNCATE,
501 GNUNET_DISK_PERM_USER_READ |
502 GNUNET_DISK_PERM_USER_WRITE |
503 GNUNET_DISK_PERM_GROUP_READ |
504 GNUNET_DISK_PERM_OTHER_READ);
507 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
508 GNUNET_asprintf (&dc->emsg, _("Failed to open file `%s' for writing"),
510 GNUNET_DISK_file_close (fh);
511 dr->state = BRS_ERROR;
512 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
513 pi.value.download.specifics.error.message = dc->emsg;
514 GNUNET_FS_download_make_status_ (&pi, dc);
517 if (data_len != GNUNET_DISK_file_write (fh, odata, odata_len))
519 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "write", fn);
520 GNUNET_asprintf (&dc->emsg, _("Failed to open file `%s' for writing"),
522 GNUNET_DISK_file_close (fh);
523 dr->state = BRS_ERROR;
524 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
525 pi.value.download.specifics.error.message = dc->emsg;
526 GNUNET_FS_download_make_status_ (&pi, dc);
529 GNUNET_DISK_file_close (fh);
531 dr->state = BRS_DOWNLOAD_UP;
532 dc->completed = dc->length;
533 GNUNET_FS_download_sync_ (dc);
534 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
535 pi.value.download.specifics.progress.data = data;
536 pi.value.download.specifics.progress.offset = 0;
537 pi.value.download.specifics.progress.data_len = dlen;
538 pi.value.download.specifics.progress.depth = 0;
539 pi.value.download.specifics.progress.respect_offered = 0;
540 pi.value.download.specifics.progress.block_download_duration = GNUNET_TIME_UNIT_ZERO;
541 GNUNET_FS_download_make_status_ (&pi, dc);
542 if ((NULL != dc->filename) &&
544 TRUNCATE (dc->filename,
545 GNUNET_ntohll (dc->uri->data.chk.file_length))))
546 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
548 check_completed (dc);
551 /* how did we get here? */
559 * Type of a function that libextractor calls for each
560 * meta data item found. If we find full data meta data,
561 * call 'try_match_block' on it.
563 * @param cls our 'struct GNUNET_FS_DownloadContext*'
564 * @param plugin_name name of the plugin that produced this value;
565 * special values can be used (i.e. '<zlib>' for zlib being
566 * used in the main libextractor library and yielding
568 * @param type libextractor-type describing the meta data
569 * @param format basic format information about data
570 * @param data_mime_type mime-type of data (not of the original file);
571 * can be NULL (if mime-type is not known)
572 * @param data actual meta-data found
573 * @param data_len number of bytes in data
574 * @return 0 to continue extracting, 1 to abort
577 match_full_data (void *cls, const char *plugin_name,
578 enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format,
579 const char *data_mime_type, const char *data, size_t data_len)
581 struct GNUNET_FS_DownloadContext *dc = cls;
583 if (EXTRACTOR_METATYPE_GNUNET_FULL_DATA != type)
585 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u bytes of FD!\n",
586 (unsigned int) data_len);
587 if (GNUNET_FS_uri_chk_get_file_size (dc->uri) != data_len)
590 return 1; /* bogus meta data */
592 try_match_block (dc, dc->top_request, data, data_len);
598 * Set the state of the given download request to
599 * BRS_DOWNLOAD_UP and propagate it up the tree.
601 * @param dr download request that is done
604 propagate_up (struct DownloadRequest *dr)
610 dr->state = BRS_DOWNLOAD_UP;
614 for (i = 0; i < dr->num_children; i++)
615 if (dr->children[i]->state != BRS_DOWNLOAD_UP)
618 while (i == dr->num_children);
623 * Try top-down reconstruction. Before, the given request node
624 * must have the state BRS_CHK_SET. Afterwards, more nodes may
625 * have that state or advanced to BRS_DOWNLOAD_DOWN or even
626 * BRS_DOWNLOAD_UP. It is also possible to get BRS_ERROR on the
629 * @param dc overall download this block belongs to
630 * @param dr block to reconstruct
633 try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc,
634 struct DownloadRequest *dr)
637 char block[DBLOCK_SIZE];
638 struct GNUNET_HashCode key;
642 struct DownloadRequest *drc;
643 uint64_t child_block_size;
644 const struct ContentHashKey *chks;
647 GNUNET_assert (NULL != dc->rfh);
648 GNUNET_assert (BRS_CHK_SET == dr->state);
649 total = GNUNET_FS_uri_chk_get_file_size (dc->uri);
650 GNUNET_assert (dr->depth < dc->treedepth);
651 len = GNUNET_FS_tree_calculate_block_size (total, dr->offset, dr->depth);
652 GNUNET_assert (len <= DBLOCK_SIZE);
653 off = compute_disk_offset (total, dr->offset, dr->depth);
654 if (dc->old_file_size < off + len)
655 return; /* failure */
656 if (off != GNUNET_DISK_file_seek (dc->rfh, off, GNUNET_DISK_SEEK_SET))
658 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "seek", dc->filename);
659 return; /* failure */
661 if (len != GNUNET_DISK_file_read (dc->rfh, block, len))
663 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "read", dc->filename);
664 return; /* failure */
666 GNUNET_CRYPTO_hash (block, len, &key);
667 if (0 != memcmp (&key, &dr->chk.key, sizeof (struct GNUNET_HashCode)))
668 return; /* mismatch */
670 encrypt_existing_match (dc, &dr->chk, dr, block, len, GNUNET_NO))
672 /* hash matches but encrypted block does not, really bad */
673 dr->state = BRS_ERROR;
675 while (NULL != dr->parent)
678 dr->state = BRS_ERROR;
683 dr->state = BRS_DOWNLOAD_DOWN;
685 /* set CHKs for children */
686 up_done = GNUNET_YES;
687 chks = (const struct ContentHashKey *) block;
688 for (i = 0; i < dr->num_children; i++)
690 drc = dr->children[i];
691 GNUNET_assert (drc->offset >= dr->offset);
692 child_block_size = GNUNET_FS_tree_compute_tree_size (drc->depth);
693 GNUNET_assert (0 == (drc->offset - dr->offset) % child_block_size);
694 if (BRS_INIT == drc->state)
696 drc->state = BRS_CHK_SET;
697 drc->chk = chks[drc->chk_idx];
698 try_top_down_reconstruction (dc, drc);
700 if (BRS_DOWNLOAD_UP != drc->state)
701 up_done = GNUNET_NO; /* children not all done */
703 if (GNUNET_YES == up_done)
704 propagate_up (dr); /* children all done (or no children...) */
709 * Schedule the download of the specified block in the tree.
711 * @param dc overall download this block belongs to
712 * @param dr request to schedule
715 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
716 struct DownloadRequest *dr)
725 case BRS_RECONSTRUCT_DOWN:
728 case BRS_RECONSTRUCT_META_UP:
731 case BRS_RECONSTRUCT_UP:
735 /* normal case, start download */
737 case BRS_DOWNLOAD_DOWN:
738 for (i = 0; i < dr->num_children; i++)
739 schedule_block_download (dc, dr->children[i]);
741 case BRS_DOWNLOAD_UP:
748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
749 "Scheduling download at offset %llu and depth %u for `%s'\n",
750 (unsigned long long) dr->offset, dr->depth,
751 GNUNET_h2s (&dr->chk.query));
753 GNUNET_CONTAINER_multihashmap_contains_value (dc->active, &dr->chk.query,
755 return; /* already active */
756 GNUNET_CONTAINER_multihashmap_put (dc->active, &dr->chk.query, dr,
757 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
758 if (NULL == dc->client)
759 return; /* download not active */
760 GNUNET_CONTAINER_DLL_insert (dc->pending_head, dc->pending_tail, dr);
761 dr->is_pending = GNUNET_YES;
764 GNUNET_CLIENT_notify_transmit_ready (dc->client,
765 sizeof (struct SearchMessage),
766 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
768 &transmit_download_request, dc);
772 #define GNUNET_FS_URI_CHK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_CHK_INFIX
775 * We found an entry in a directory. Check if the respective child
776 * already exists and if not create the respective child download.
778 * @param cls the parent download
779 * @param filename name of the file in the directory
780 * @param uri URI of the file (CHK or LOC)
781 * @param meta meta data of the file
782 * @param length number of bytes in data
783 * @param data contents of the file (or NULL if they were not inlined)
786 trigger_recursive_download (void *cls, const char *filename,
787 const struct GNUNET_FS_Uri *uri,
788 const struct GNUNET_CONTAINER_MetaData *meta,
789 size_t length, const void *data)
791 struct GNUNET_FS_DownloadContext *dc = cls;
792 struct GNUNET_FS_DownloadContext *cpos;
803 return; /* entry for the directory itself */
804 cpos = dc->child_head;
807 if ((GNUNET_FS_uri_test_equal (uri, cpos->uri)) ||
808 ((NULL != filename) && (0 == strcmp (cpos->filename, filename))))
813 return; /* already exists */
815 if (NULL == filename)
817 fn = GNUNET_FS_meta_data_suggest_filename (meta);
820 us = GNUNET_FS_uri_to_string (uri);
821 fn = GNUNET_strdup (&us[strlen (GNUNET_FS_URI_CHK_PREFIX)]);
824 else if ('.' == fn[0])
827 us = GNUNET_FS_uri_to_string (uri);
828 GNUNET_asprintf (&fn, "%s%s", &us[strlen (GNUNET_FS_URI_CHK_PREFIX)],
833 /* change '\' to '/' (this should have happened
834 * during insertion, but malicious peers may
835 * not have done this) */
836 while (NULL != (pos = strstr (fn, "\\")))
838 /* remove '../' everywhere (again, well-behaved
839 * peers don't do this, but don't trust that
840 * we did not get something nasty) */
841 while (NULL != (pos = strstr (fn, "../")))
849 if (NULL == dc->filename)
855 dn = GNUNET_strdup (dc->filename);
856 GNUNET_break ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
858 strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
859 GNUNET_FS_DIRECTORY_EXT)));
860 sfn = GNUNET_strdup (filename);
861 while ((strlen (sfn) > 0) && ('/' == filename[strlen (sfn) - 1]))
862 sfn[strlen (sfn) - 1] = '\0';
863 if ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
865 strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
866 GNUNET_FS_DIRECTORY_EXT)))
867 dn[strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
868 if ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
869 ((strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
871 strstr (filename + strlen (filename) -
872 strlen (GNUNET_FS_DIRECTORY_EXT), GNUNET_FS_DIRECTORY_EXT))))
874 GNUNET_asprintf (&full_name, "%s%s%s%s", dn, DIR_SEPARATOR_STR, sfn,
875 GNUNET_FS_DIRECTORY_EXT);
879 GNUNET_asprintf (&full_name, "%s%s%s", dn, DIR_SEPARATOR_STR, sfn);
884 if ((NULL != full_name) &&
885 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (full_name)))
887 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
889 ("Failed to create directory for recursive download of `%s'\n"),
891 GNUNET_free (full_name);
892 GNUNET_free_non_null (fn);
897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898 "Triggering recursive download of size %llu with %u bytes MD\n",
899 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (uri),
901 GNUNET_CONTAINER_meta_data_get_serialized_size (meta));
902 GNUNET_FS_download_start (dc->h, uri, meta, full_name, temp_name, 0,
903 GNUNET_FS_uri_chk_get_file_size (uri),
904 dc->anonymity, dc->options, NULL, dc);
905 GNUNET_free_non_null (full_name);
906 GNUNET_free_non_null (temp_name);
907 GNUNET_free_non_null (fn);
912 * (recursively) free download request structure
914 * @param dr request to free
917 GNUNET_FS_free_download_request_ (struct DownloadRequest *dr)
923 for (i = 0; i < dr->num_children; i++)
924 GNUNET_FS_free_download_request_ (dr->children[i]);
925 GNUNET_free_non_null (dr->children);
931 * Iterator over entries in the pending requests in the 'active' map for the
932 * reply that we just got.
934 * @param cls closure (our 'struct ProcessResultClosure')
935 * @param key query for the given value / request
936 * @param value value in the hash map (a 'struct DownloadRequest')
937 * @return GNUNET_YES (we should continue to iterate); unless serious error
940 process_result_with_request (void *cls, const struct GNUNET_HashCode * key,
943 struct ProcessResultClosure *prc = cls;
944 struct DownloadRequest *dr = value;
945 struct GNUNET_FS_DownloadContext *dc = prc->dc;
946 struct DownloadRequest *drc;
947 struct GNUNET_DISK_FileHandle *fh = NULL;
948 struct GNUNET_CRYPTO_AesSessionKey skey;
949 struct GNUNET_CRYPTO_AesInitializationVector iv;
951 struct GNUNET_FS_ProgressInfo pi;
956 struct ContentHashKey *chkarr;
958 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
959 "Received %u byte block `%s' matching pending request at depth %u and offset %llu/%llu\n",
960 (unsigned int) prc->size,
961 GNUNET_h2s (key), dr->depth, (unsigned long long) dr->offset,
962 (unsigned long long) GNUNET_ntohll (dc->uri->data.
964 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll
965 (dc->uri->data.chk.file_length),
966 dr->offset, dr->depth);
969 GNUNET_asprintf (&dc->emsg,
971 ("Internal error or bogus download URI (expected %u bytes at depth %u and offset %llu/%llu, got %u bytes)"),
972 bs, dr->depth, (unsigned long long) dr->offset,
973 (unsigned long long) GNUNET_ntohll (dc->uri->data.
976 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s\n", dc->emsg);
977 while (NULL != dr->parent)
979 dr->state = BRS_ERROR;
982 dr->state = BRS_ERROR;
986 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &prc->query, dr);
987 if (GNUNET_YES == dr->is_pending)
989 GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
990 dr->is_pending = GNUNET_NO;
993 GNUNET_CRYPTO_hash_to_aes_key (&dr->chk.key, &skey, &iv);
994 if (-1 == GNUNET_CRYPTO_aes_decrypt (prc->data, prc->size, &skey, &iv, pt))
997 dc->emsg = GNUNET_strdup (_("internal error decrypting content"));
1001 compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
1002 dr->offset, dr->depth);
1004 if ((GNUNET_YES == prc->do_store) &&
1005 ((NULL != dc->filename) || (is_recursive_download (dc))) &&
1006 ((dr->depth == dc->treedepth) ||
1007 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES))))
1009 fh = GNUNET_DISK_file_open (NULL != dc->filename
1010 ? dc->filename : dc->temp_filename,
1011 GNUNET_DISK_OPEN_READWRITE |
1012 GNUNET_DISK_OPEN_CREATE,
1013 GNUNET_DISK_PERM_USER_READ |
1014 GNUNET_DISK_PERM_USER_WRITE |
1015 GNUNET_DISK_PERM_GROUP_READ |
1016 GNUNET_DISK_PERM_OTHER_READ);
1019 GNUNET_asprintf (&dc->emsg,
1020 _("Download failed: could not open file `%s': %s"),
1021 dc->filename, STRERROR (errno));
1024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1025 "Saving decrypted block to disk at offset %llu\n",
1026 (unsigned long long) off);
1027 if ((off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)))
1029 GNUNET_asprintf (&dc->emsg,
1030 _("Failed to seek to offset %llu in file `%s': %s"),
1031 (unsigned long long) off, dc->filename,
1035 if (prc->size != GNUNET_DISK_file_write (fh, pt, prc->size))
1037 GNUNET_asprintf (&dc->emsg,
1039 ("Failed to write block of %u bytes at offset %llu in file `%s': %s"),
1040 (unsigned int) prc->size, (unsigned long long) off,
1041 dc->filename, STRERROR (errno));
1044 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
1050 /* DBLOCK, update progress and try recursion if applicable */
1052 if (dr->offset < dc->offset)
1054 /* starting offset begins in the middle of pt,
1055 * do not count first bytes as progress */
1056 GNUNET_assert (app > (dc->offset - dr->offset));
1057 app -= (dc->offset - dr->offset);
1059 if (dr->offset + prc->size > dc->offset + dc->length)
1061 /* end of block is after relevant range,
1062 * do not count last bytes as progress */
1063 GNUNET_assert (app >
1064 (dr->offset + prc->size) - (dc->offset + dc->length));
1065 app -= (dr->offset + prc->size) - (dc->offset + dc->length);
1067 dc->completed += app;
1069 /* do recursive download if option is set and either meta data
1070 * says it is a directory or if no meta data is given AND filename
1071 * ends in '.gnd' (top-level case) */
1072 if (is_recursive_download (dc))
1073 GNUNET_FS_directory_list_contents (prc->size, pt, off,
1074 &trigger_recursive_download, dc);
1076 GNUNET_assert (dc->completed <= dc->length);
1077 dr->state = BRS_DOWNLOAD_DOWN;
1078 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1079 pi.value.download.specifics.progress.data = pt;
1080 pi.value.download.specifics.progress.offset = dr->offset;
1081 pi.value.download.specifics.progress.data_len = prc->size;
1082 pi.value.download.specifics.progress.depth = dr->depth;
1083 pi.value.download.specifics.progress.respect_offered = prc->respect_offered;
1084 pi.value.download.specifics.progress.num_transmissions = prc->num_transmissions;
1085 if (prc->last_transmission.abs_value_us != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
1086 pi.value.download.specifics.progress.block_download_duration
1087 = GNUNET_TIME_absolute_get_duration (prc->last_transmission);
1089 pi.value.download.specifics.progress.block_download_duration
1090 = GNUNET_TIME_UNIT_ZERO; /* found locally */
1091 GNUNET_FS_download_make_status_ (&pi, dc);
1095 if (dc->completed == dc->length)
1097 /* download completed, signal */
1098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1099 "Download completed, truncating file to desired length %llu\n",
1100 (unsigned long long) GNUNET_ntohll (dc->uri->data.
1102 /* truncate file to size (since we store IBlocks at the end) */
1103 if (NULL != dc->filename)
1106 TRUNCATE (dc->filename,
1107 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1108 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
1111 GNUNET_assert (0 == dr->depth);
1112 check_completed (dc);
1116 /* bottom of the tree, no child downloads possible, just sync */
1117 GNUNET_FS_download_sync_ (dc);
1121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1122 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1123 dr->depth, (unsigned long long) dr->offset);
1124 GNUNET_assert (0 == (prc->size % sizeof (struct ContentHashKey)));
1125 chkarr = (struct ContentHashKey *) pt;
1126 for (i = dr->num_children - 1; i >= 0; i--)
1128 drc = dr->children[i];
1132 if ((drc->chk_idx + 1) * sizeof (struct ContentHashKey) > prc->size)
1134 /* 'chkarr' does not have enough space for this chk_idx;
1136 GNUNET_break (0); GNUNET_assert (0);
1137 dc->emsg = GNUNET_strdup (_("internal error decoding tree"));
1140 drc->chk = chkarr[drc->chk_idx];
1141 drc->state = BRS_CHK_SET;
1142 if (GNUNET_YES == dc->issue_requests)
1143 schedule_block_download (dc, drc);
1145 case BRS_RECONSTRUCT_DOWN:
1148 case BRS_RECONSTRUCT_META_UP:
1151 case BRS_RECONSTRUCT_UP:
1157 case BRS_DOWNLOAD_DOWN:
1160 case BRS_DOWNLOAD_UP:
1171 GNUNET_FS_download_sync_ (dc);
1176 GNUNET_DISK_file_close (fh);
1177 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1178 pi.value.download.specifics.error.message = dc->emsg;
1179 GNUNET_FS_download_make_status_ (&pi, dc);
1180 /* abort all pending requests */
1183 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1186 GNUNET_CLIENT_disconnect (dc->client);
1187 dc->in_receive = GNUNET_NO;
1189 GNUNET_FS_free_download_request_ (dc->top_request);
1190 dc->top_request = NULL;
1191 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1193 if (NULL != dc->job_queue)
1195 GNUNET_FS_dequeue_ (dc->job_queue);
1196 dc->job_queue = NULL;
1198 dc->pending_head = NULL;
1199 dc->pending_tail = NULL;
1200 GNUNET_FS_download_sync_ (dc);
1206 * Process a download result.
1208 * @param dc our download context
1209 * @param type type of the result
1210 * @param respect_offered how much respect did we offer to get this reply?
1211 * @param num_transmissions how often did we transmit the query?
1212 * @param last_transmission when was this block requested the last time? (FOREVER if unknown/not applicable)
1213 * @param data the (encrypted) response
1214 * @param size size of data
1217 process_result (struct GNUNET_FS_DownloadContext *dc,
1218 enum GNUNET_BLOCK_Type type,
1219 uint32_t respect_offered,
1220 uint32_t num_transmissions,
1221 struct GNUNET_TIME_Absolute last_transmission,
1222 const void *data, size_t size)
1224 struct ProcessResultClosure prc;
1228 prc.last_transmission = last_transmission;
1231 prc.do_store = GNUNET_YES;
1232 prc.respect_offered = respect_offered;
1233 prc.num_transmissions = num_transmissions;
1234 GNUNET_CRYPTO_hash (data, size, &prc.query);
1235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1236 "Received result for query `%s' from `%s'-service\n",
1237 GNUNET_h2s (&prc.query), "FS");
1238 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active, &prc.query,
1239 &process_result_with_request,
1245 * Type of a function to call when we receive a message
1248 * @param cls closure
1249 * @param msg message received, NULL on timeout or fatal error
1252 receive_results (void *cls, const struct GNUNET_MessageHeader *msg)
1254 struct GNUNET_FS_DownloadContext *dc = cls;
1255 const struct ClientPutMessage *cm;
1258 if ((NULL == msg) || (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1259 (sizeof (struct ClientPutMessage) > ntohs (msg->size)))
1261 GNUNET_break (NULL == msg);
1265 msize = ntohs (msg->size);
1266 cm = (const struct ClientPutMessage *) msg;
1267 process_result (dc, ntohl (cm->type),
1268 ntohl (cm->respect_offered),
1269 ntohl (cm->num_transmissions),
1270 GNUNET_TIME_absolute_ntoh (cm->last_transmission), &cm[1],
1271 msize - sizeof (struct ClientPutMessage));
1272 if (NULL == dc->client)
1273 return; /* fatal error */
1274 /* continue receiving */
1275 GNUNET_CLIENT_receive (dc->client, &receive_results, dc,
1276 GNUNET_TIME_UNIT_FOREVER_REL);
1281 * We're ready to transmit a search request to the
1282 * file-sharing service. Do it. If there is
1283 * more than one request pending, try to send
1284 * multiple or request another transmission.
1286 * @param cls closure
1287 * @param size number of bytes available in buf
1288 * @param buf where the callee should write the message
1289 * @return number of bytes written to buf
1292 transmit_download_request (void *cls, size_t size, void *buf)
1294 struct GNUNET_FS_DownloadContext *dc = cls;
1296 struct SearchMessage *sm;
1297 struct DownloadRequest *dr;
1302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1303 "Transmitting download request failed, trying to reconnect\n");
1307 GNUNET_assert (size >= sizeof (struct SearchMessage));
1310 while ((NULL != (dr = dc->pending_head)) &&
1311 (size >= msize + sizeof (struct SearchMessage)))
1313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1314 "Transmitting download request for `%s' to `%s'-service\n",
1315 GNUNET_h2s (&dr->chk.query), "FS");
1316 memset (sm, 0, sizeof (struct SearchMessage));
1317 sm->header.size = htons (sizeof (struct SearchMessage));
1318 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1319 if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1320 sm->options = htonl (GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY);
1322 sm->options = htonl (GNUNET_FS_SEARCH_OPTION_NONE);
1324 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_DBLOCK);
1326 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_IBLOCK);
1327 sm->anonymity_level = htonl (dc->anonymity);
1328 sm->target = dc->target.hashPubKey;
1329 sm->query = dr->chk.query;
1330 GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
1331 dr->is_pending = GNUNET_NO;
1332 msize += sizeof (struct SearchMessage);
1335 if (NULL != dc->pending_head)
1338 GNUNET_CLIENT_notify_transmit_ready (dc->client,
1339 sizeof (struct SearchMessage),
1340 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1342 &transmit_download_request, dc);
1343 GNUNET_assert (NULL != dc->th);
1345 if (GNUNET_NO == dc->in_receive)
1347 dc->in_receive = GNUNET_YES;
1348 GNUNET_CLIENT_receive (dc->client, &receive_results, dc,
1349 GNUNET_TIME_UNIT_FOREVER_REL);
1356 * Reconnect to the FS service and transmit our queries NOW.
1358 * @param cls our download context
1362 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1364 struct GNUNET_FS_DownloadContext *dc = cls;
1365 struct GNUNET_CLIENT_Connection *client;
1367 dc->task = GNUNET_SCHEDULER_NO_TASK;
1368 client = GNUNET_CLIENT_connect ("fs", dc->h->cfg);
1371 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1372 "Connecting to `%s'-service failed, will try again.\n", "FS");
1376 dc->client = client;
1377 if (NULL != dc->pending_head)
1380 GNUNET_CLIENT_notify_transmit_ready (client,
1381 sizeof (struct SearchMessage),
1382 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1384 &transmit_download_request, dc);
1385 GNUNET_assert (NULL != dc->th);
1391 * Add entries to the pending list.
1393 * @param cls our download context
1395 * @param entry entry of type "struct DownloadRequest"
1399 retry_entry (void *cls, const struct GNUNET_HashCode * key, void *entry)
1401 struct GNUNET_FS_DownloadContext *dc = cls;
1402 struct DownloadRequest *dr = entry;
1406 GNUNET_CONTAINER_DLL_insert (dc->pending_head, dc->pending_tail, dr);
1407 dr->is_pending = GNUNET_YES;
1413 * We've lost our connection with the FS service.
1414 * Re-establish it and re-transmit all of our
1417 * @param dc download context that is having trouble
1420 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1423 if (NULL != dc->client)
1425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1426 "Moving all requests back to pending list\n");
1429 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1432 /* full reset of the pending list */
1433 dc->pending_head = NULL;
1434 dc->pending_tail = NULL;
1435 GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1436 GNUNET_CLIENT_disconnect (dc->client);
1437 dc->in_receive = GNUNET_NO;
1440 if (0 == dc->reconnect_backoff.rel_value_us)
1441 dc->reconnect_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1443 dc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (dc->reconnect_backoff);
1445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Will try to reconnect in %s\n",
1446 GNUNET_STRINGS_relative_time_to_string (dc->reconnect_backoff, GNUNET_YES));
1448 GNUNET_SCHEDULER_add_delayed (dc->reconnect_backoff,
1455 * We're allowed to ask the FS service for our blocks. Start the download.
1457 * @param cls the 'struct GNUNET_FS_DownloadContext'
1458 * @param client handle to use for communcation with FS (we must destroy it!)
1461 activate_fs_download (void *cls, struct GNUNET_CLIENT_Connection *client)
1463 struct GNUNET_FS_DownloadContext *dc = cls;
1464 struct GNUNET_FS_ProgressInfo pi;
1466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download activated\n");
1467 GNUNET_assert (NULL != client);
1468 GNUNET_assert (NULL == dc->client);
1469 GNUNET_assert (NULL == dc->th);
1470 GNUNET_assert (NULL != dc->active);
1471 dc->client = client;
1472 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1473 GNUNET_FS_download_make_status_ (&pi, dc);
1474 dc->pending_head = NULL;
1475 dc->pending_tail = NULL;
1476 GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1478 "Asking for transmission to FS service\n");
1479 if (NULL != dc->pending_head)
1482 GNUNET_CLIENT_notify_transmit_ready (dc->client,
1483 sizeof (struct SearchMessage),
1484 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1486 &transmit_download_request, dc);
1487 GNUNET_assert (NULL != dc->th);
1493 * We must stop to ask the FS service for our blocks. Pause the download.
1495 * @param cls the 'struct GNUNET_FS_DownloadContext'
1498 deactivate_fs_download (void *cls)
1500 struct GNUNET_FS_DownloadContext *dc = cls;
1501 struct GNUNET_FS_ProgressInfo pi;
1503 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download deactivated\n");
1506 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1509 if (NULL != dc->client)
1511 GNUNET_CLIENT_disconnect (dc->client);
1512 dc->in_receive = GNUNET_NO;
1515 dc->pending_head = NULL;
1516 dc->pending_tail = NULL;
1517 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1518 GNUNET_FS_download_make_status_ (&pi, dc);
1523 * (recursively) Create a download request structure.
1525 * @param parent parent of the current entry
1526 * @param chk_idx index of the chk for this block in the parent block
1527 * @param depth depth of the current entry, 0 are the DBLOCKs,
1528 * top level block is 'dc->treedepth - 1'
1529 * @param dr_offset offset in the original file this block maps to
1530 * (as in, offset of the first byte of the first DBLOCK
1531 * in the subtree rooted in the returned download request tree)
1532 * @param file_start_offset desired starting offset for the download
1533 * in the original file; requesting tree should not contain
1534 * DBLOCKs prior to the file_start_offset
1535 * @param desired_length desired number of bytes the user wanted to access
1536 * (from file_start_offset). Resulting tree should not contain
1537 * DBLOCKs after file_start_offset + file_length.
1538 * @return download request tree for the given range of DBLOCKs at
1539 * the specified depth
1541 static struct DownloadRequest *
1542 create_download_request (struct DownloadRequest *parent,
1543 unsigned int chk_idx,
1545 uint64_t dr_offset, uint64_t file_start_offset,
1546 uint64_t desired_length)
1548 struct DownloadRequest *dr;
1550 unsigned int head_skip;
1551 uint64_t child_block_size;
1553 dr = GNUNET_malloc (sizeof (struct DownloadRequest));
1554 dr->parent = parent;
1556 dr->offset = dr_offset;
1557 dr->chk_idx = chk_idx;
1560 child_block_size = GNUNET_FS_tree_compute_tree_size (depth - 1);
1562 /* calculate how many blocks at this level are not interesting
1563 * from the start (rounded down), either because of the requested
1564 * file offset or because this IBlock is further along */
1565 if (dr_offset < file_start_offset)
1567 head_skip = (file_start_offset - dr_offset) / child_block_size;
1574 /* calculate index of last block at this level that is interesting (rounded up) */
1575 dr->num_children = (file_start_offset + desired_length - dr_offset) / child_block_size;
1576 if (dr->num_children * child_block_size <
1577 file_start_offset + desired_length - dr_offset)
1578 dr->num_children++; /* round up */
1579 GNUNET_assert (dr->num_children > head_skip);
1580 dr->num_children -= head_skip;
1581 if (dr->num_children > CHK_PER_INODE)
1582 dr->num_children = CHK_PER_INODE; /* cap at max */
1583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584 "Block at offset %llu and depth %u has %u children\n",
1585 (unsigned long long) dr_offset,
1589 /* now we can get the total number of *interesting* children for this block */
1591 /* why else would we have gotten here to begin with? (that'd be a bad logic error) */
1592 GNUNET_assert (dr->num_children > 0);
1595 GNUNET_malloc (dr->num_children * sizeof (struct DownloadRequest *));
1596 for (i = 0; i < dr->num_children; i++)
1599 create_download_request (dr, i + head_skip, depth - 1,
1600 dr_offset + (i + head_skip) * child_block_size,
1601 file_start_offset, desired_length);
1608 * Continuation after a possible attempt to reconstruct
1609 * the current IBlock from the existing file.
1611 * @param cls the 'struct ReconstructContext'
1612 * @param tc scheduler context
1615 reconstruct_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1617 struct GNUNET_FS_DownloadContext *dc = cls;
1619 /* clean up state from tree encoder */
1620 if (dc->task != GNUNET_SCHEDULER_NO_TASK)
1622 GNUNET_SCHEDULER_cancel (dc->task);
1623 dc->task = GNUNET_SCHEDULER_NO_TASK;
1625 if (NULL != dc->rfh)
1627 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
1630 /* start "normal" download */
1631 dc->issue_requests = GNUNET_YES;
1632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1633 "Starting normal download\n");
1634 schedule_block_download (dc, dc->top_request);
1639 * Task requesting the next block from the tree encoder.
1641 * @param cls the 'struct GNUJNET_FS_DownloadContext' we're processing
1642 * @param tc task context
1645 get_next_block (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1647 struct GNUNET_FS_DownloadContext *dc = cls;
1649 dc->task = GNUNET_SCHEDULER_NO_TASK;
1650 GNUNET_FS_tree_encoder_next (dc->te);
1655 * Function called asking for the current (encoded)
1656 * block to be processed. After processing the
1657 * client should either call "GNUNET_FS_tree_encode_next"
1658 * or (on error) "GNUNET_FS_tree_encode_finish".
1660 * This function checks if the content on disk matches
1661 * the expected content based on the URI.
1663 * @param cls closure
1664 * @param chk content hash key for the block
1665 * @param offset offset of the block
1666 * @param depth depth of the block, 0 for DBLOCK
1667 * @param type type of the block (IBLOCK or DBLOCK)
1668 * @param block the (encrypted) block
1669 * @param block_size size of block (in bytes)
1672 reconstruct_cb (void *cls, const struct ContentHashKey *chk, uint64_t offset,
1673 unsigned int depth, enum GNUNET_BLOCK_Type type,
1674 const void *block, uint16_t block_size)
1676 struct GNUNET_FS_DownloadContext *dc = cls;
1677 struct GNUNET_FS_ProgressInfo pi;
1678 struct DownloadRequest *dr;
1682 /* find corresponding request entry */
1683 dr = dc->top_request;
1684 while (dr->depth > depth)
1686 GNUNET_assert (dr->num_children > 0);
1687 blen = GNUNET_FS_tree_compute_tree_size (dr->depth - 1);
1688 chld = (offset - dr->offset) / blen;
1689 if (chld < dr->children[0]->chk_idx)
1691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1692 "Block %u < %u irrelevant for our range\n",
1694 dr->children[0]->chk_idx);
1695 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1696 return; /* irrelevant block */
1698 if (chld > dr->children[dr->num_children-1]->chk_idx)
1700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1701 "Block %u > %u irrelevant for our range\n",
1703 dr->children[dr->num_children-1]->chk_idx);
1704 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1705 return; /* irrelevant block */
1707 dr = dr->children[chld - dr->children[0]->chk_idx];
1709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1710 "Matched TE block with request at offset %llu and depth %u in state %d\n",
1711 (unsigned long long) dr->offset,
1714 /* FIXME: this code needs more testing and might
1715 need to handle more states... */
1720 case BRS_RECONSTRUCT_DOWN:
1722 case BRS_RECONSTRUCT_META_UP:
1724 case BRS_RECONSTRUCT_UP:
1727 if (0 == memcmp (chk, &dr->chk, sizeof (struct ContentHashKey)))
1729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1730 "Reconstruction succeeded, can use block at offset %llu, depth %u\n",
1731 (unsigned long long) offset,
1733 /* block matches, hence tree below matches;
1734 * this request is done! */
1735 dr->state = BRS_DOWNLOAD_UP;
1736 (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &dr->chk.query, dr);
1737 if (GNUNET_YES == dr->is_pending)
1739 GNUNET_break (0); /* how did we get here? */
1740 GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
1741 dr->is_pending = GNUNET_NO;
1743 /* calculate how many bytes of payload this block
1745 blen = GNUNET_FS_tree_compute_tree_size (dr->depth);
1746 /* how many of those bytes are in the requested range? */
1747 blen = GNUNET_MIN (blen, dc->length + dc->offset - dr->offset);
1748 /* signal progress */
1749 dc->completed += blen;
1750 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1751 pi.value.download.specifics.progress.data = NULL;
1752 pi.value.download.specifics.progress.offset = offset;
1753 pi.value.download.specifics.progress.data_len = 0;
1754 pi.value.download.specifics.progress.depth = 0;
1755 pi.value.download.specifics.progress.respect_offered = 0;
1756 pi.value.download.specifics.progress.block_download_duration = GNUNET_TIME_UNIT_ZERO;
1757 GNUNET_FS_download_make_status_ (&pi, dc);
1758 /* FIXME: duplicated code from 'process_result_with_request - refactor */
1759 if (dc->completed == dc->length)
1761 /* download completed, signal */
1762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763 "Download completed, truncating file to desired length %llu\n",
1764 (unsigned long long) GNUNET_ntohll (dc->uri->data.
1766 /* truncate file to size (since we store IBlocks at the end) */
1767 if (NULL != dc->filename)
1770 TRUNCATE (dc->filename,
1771 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1772 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
1778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1779 "Reconstruction failed, need to download block at offset %llu, depth %u\n",
1780 (unsigned long long) offset,
1783 case BRS_DOWNLOAD_DOWN:
1785 case BRS_DOWNLOAD_UP:
1793 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1794 if ((dr == dc->top_request) && (dr->state == BRS_DOWNLOAD_UP))
1795 check_completed (dc);
1800 * Function called by the tree encoder to obtain a block of plaintext
1801 * data (for the lowest level of the tree).
1803 * @param cls our 'struct ReconstructContext'
1804 * @param offset identifies which block to get
1805 * @param max (maximum) number of bytes to get; returning
1806 * fewer will also cause errors
1807 * @param buf where to copy the plaintext buffer
1808 * @param emsg location to store an error message (on error)
1809 * @return number of bytes copied to buf, 0 on error
1812 fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg)
1814 struct GNUNET_FS_DownloadContext *dc = cls;
1815 struct GNUNET_DISK_FileHandle *fh = dc->rfh;
1820 if (offset != GNUNET_DISK_file_seek (fh, offset, GNUNET_DISK_SEEK_SET))
1823 *emsg = GNUNET_strdup (strerror (errno));
1826 ret = GNUNET_DISK_file_read (fh, buf, max);
1830 *emsg = GNUNET_strdup (strerror (errno));
1838 * Task that creates the initial (top-level) download
1839 * request for the file.
1841 * @param cls the 'struct GNUNET_FS_DownloadContext'
1842 * @param tc scheduler context
1845 GNUNET_FS_download_start_task_ (void *cls,
1846 const struct GNUNET_SCHEDULER_TaskContext *tc)
1848 struct GNUNET_FS_DownloadContext *dc = cls;
1849 struct GNUNET_FS_ProgressInfo pi;
1850 struct GNUNET_DISK_FileHandle *fh;
1852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start task running...\n");
1853 dc->task = GNUNET_SCHEDULER_NO_TASK;
1854 if (0 == dc->length)
1856 /* no bytes required! */
1857 if (NULL != dc->filename)
1859 fh = GNUNET_DISK_file_open (dc->filename,
1860 GNUNET_DISK_OPEN_READWRITE |
1861 GNUNET_DISK_OPEN_CREATE |
1863 GNUNET_FS_uri_chk_get_file_size (dc->uri)) ?
1864 GNUNET_DISK_OPEN_TRUNCATE : 0),
1865 GNUNET_DISK_PERM_USER_READ |
1866 GNUNET_DISK_PERM_USER_WRITE |
1867 GNUNET_DISK_PERM_GROUP_READ |
1868 GNUNET_DISK_PERM_OTHER_READ);
1869 GNUNET_DISK_file_close (fh);
1871 GNUNET_FS_download_sync_ (dc);
1872 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1873 pi.value.download.specifics.start.meta = dc->meta;
1874 GNUNET_FS_download_make_status_ (&pi, dc);
1875 check_completed (dc);
1878 if (NULL != dc->emsg)
1880 if (NULL == dc->top_request)
1883 create_download_request (NULL, 0, dc->treedepth - 1, 0, dc->offset,
1885 dc->top_request->state = BRS_CHK_SET;
1886 dc->top_request->chk =
1888 GNUNET_FS_URI_CHK) ? dc->uri->data.chk.chk : dc->uri->data.loc.fi.chk;
1890 GNUNET_FS_download_sync_ (dc);
1891 if (NULL != dc->search)
1892 GNUNET_FS_search_result_sync_ (dc->search);
1893 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1894 pi.value.download.specifics.start.meta = dc->meta;
1895 GNUNET_FS_download_make_status_ (&pi, dc);
1897 GNUNET_FS_download_start_downloading_ (dc);
1898 /* attempt reconstruction from disk */
1899 if (GNUNET_YES == GNUNET_DISK_file_test (dc->filename))
1901 GNUNET_DISK_file_open (dc->filename, GNUNET_DISK_OPEN_READ,
1902 GNUNET_DISK_PERM_NONE);
1903 if (dc->top_request->state == BRS_CHK_SET)
1905 if (NULL != dc->rfh)
1907 /* first, try top-down */
1908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1909 "Trying top-down reconstruction for `%s'\n", dc->filename);
1910 try_top_down_reconstruction (dc, dc->top_request);
1911 switch (dc->top_request->state)
1915 case BRS_DOWNLOAD_DOWN:
1916 break; /* normal, some blocks already down */
1917 case BRS_DOWNLOAD_UP:
1918 /* already done entirely, party! */
1919 if (NULL != dc->rfh)
1921 /* avoid hanging on to file handle longer than
1923 GNUNET_DISK_file_close (dc->rfh);
1928 GNUNET_asprintf (&dc->emsg, _("Invalid URI"));
1929 GNUNET_FS_download_sync_ (dc);
1930 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1931 pi.value.download.specifics.error.message = dc->emsg;
1932 GNUNET_FS_download_make_status_ (&pi, dc);
1940 /* attempt reconstruction from meta data */
1941 if ((GNUNET_FS_uri_chk_get_file_size (dc->uri) <= MAX_INLINE_SIZE) &&
1944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945 "Trying to find embedded meta data for download of size %llu with %u bytes MD\n",
1946 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (dc->uri),
1948 GNUNET_CONTAINER_meta_data_get_serialized_size (dc->meta));
1949 GNUNET_CONTAINER_meta_data_iterate (dc->meta, &match_full_data, dc);
1950 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1952 if (NULL != dc->rfh)
1954 /* avoid hanging on to file handle longer than
1956 GNUNET_DISK_file_close (dc->rfh);
1959 return; /* finished, status update was already done for us */
1962 if (NULL != dc->rfh)
1964 /* finally, actually run bottom-up */
1965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1966 "Trying bottom-up reconstruction of file `%s'\n", dc->filename);
1968 GNUNET_FS_tree_encoder_create (dc->h,
1969 GNUNET_FS_uri_chk_get_file_size (dc->uri),
1971 &reconstruct_cb, NULL,
1973 dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1977 /* simple, top-level download */
1978 dc->issue_requests = GNUNET_YES;
1979 schedule_block_download (dc, dc->top_request);
1981 if (BRS_DOWNLOAD_UP == dc->top_request->state)
1982 check_completed (dc);
1987 * Create SUSPEND event for the given download operation
1988 * and then clean up our state (without stop signal).
1990 * @param cls the 'struct GNUNET_FS_DownloadContext' to signal for
1993 GNUNET_FS_download_signal_suspend_ (void *cls)
1995 struct GNUNET_FS_DownloadContext *dc = cls;
1996 struct GNUNET_FS_ProgressInfo pi;
1998 if (NULL != dc->top)
1999 GNUNET_FS_end_top (dc->h, dc->top);
2000 while (NULL != dc->child_head)
2001 GNUNET_FS_download_signal_suspend_ (dc->child_head);
2002 if (NULL != dc->search)
2004 dc->search->download = NULL;
2007 if (NULL != dc->job_queue)
2009 GNUNET_FS_dequeue_ (dc->job_queue);
2010 dc->job_queue = NULL;
2012 if (NULL != dc->parent)
2013 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, dc->parent->child_tail,
2015 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
2017 GNUNET_SCHEDULER_cancel (dc->task);
2018 dc->task = GNUNET_SCHEDULER_NO_TASK;
2020 pi.status = GNUNET_FS_STATUS_DOWNLOAD_SUSPEND;
2021 GNUNET_FS_download_make_status_ (&pi, dc);
2024 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
2027 if (NULL != dc->rfh)
2029 GNUNET_DISK_file_close (dc->rfh);
2032 GNUNET_FS_free_download_request_ (dc->top_request);
2033 if (NULL != dc->active)
2035 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2038 GNUNET_free_non_null (dc->filename);
2039 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2040 GNUNET_FS_uri_destroy (dc->uri);
2041 GNUNET_free_non_null (dc->temp_filename);
2042 GNUNET_free_non_null (dc->serialization);
2043 GNUNET_assert (NULL == dc->job_queue);
2049 * Helper function to setup the download context.
2051 * @param h handle to the file sharing subsystem
2052 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2053 * @param meta known metadata for the file (can be NULL)
2054 * @param filename where to store the file, maybe NULL (then no file is
2055 * created on disk and data must be grabbed from the callbacks)
2056 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2057 * can be NULL (in which case we will pick a name if needed); the temporary file
2058 * may already exist, in which case we will try to use the data that is there and
2059 * if it is not what is desired, will overwrite it
2060 * @param offset at what offset should we start the download (typically 0)
2061 * @param length how many bytes should be downloaded starting at offset
2062 * @param anonymity anonymity level to use for the download
2063 * @param options various options
2064 * @param cctx initial value for the client context for this download
2065 * @return context that can be used to control this download
2067 struct GNUNET_FS_DownloadContext *
2068 create_download_context (struct GNUNET_FS_Handle *h,
2069 const struct GNUNET_FS_Uri *uri,
2070 const struct GNUNET_CONTAINER_MetaData *meta,
2071 const char *filename, const char *tempname,
2072 uint64_t offset, uint64_t length, uint32_t anonymity,
2073 enum GNUNET_FS_DownloadOptions options, void *cctx)
2075 struct GNUNET_FS_DownloadContext *dc;
2077 GNUNET_assert (GNUNET_FS_uri_test_chk (uri) || GNUNET_FS_uri_test_loc (uri));
2078 if ((offset + length < offset) ||
2079 (offset + length > GNUNET_FS_uri_chk_get_file_size (uri)))
2084 dc = GNUNET_malloc (sizeof (struct GNUNET_FS_DownloadContext));
2085 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2086 "Starting download %p, %u bytes at offset %llu\n",
2088 (unsigned long long) length,
2089 (unsigned long long) offset);
2091 dc->uri = GNUNET_FS_uri_dup (uri);
2092 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
2093 dc->client_info = cctx;
2094 dc->start_time = GNUNET_TIME_absolute_get ();
2095 if (NULL != filename)
2097 dc->filename = GNUNET_strdup (filename);
2098 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
2099 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_size (filename, &dc->old_file_size, GNUNET_YES, GNUNET_YES));
2101 if (GNUNET_FS_uri_test_loc (dc->uri))
2102 GNUNET_assert (GNUNET_OK ==
2103 GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target));
2104 dc->offset = offset;
2105 dc->length = length;
2106 dc->anonymity = anonymity;
2107 dc->options = options;
2109 GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE), GNUNET_NO);
2111 GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri));
2112 if ((NULL == filename) && (is_recursive_download (dc)))
2114 if (NULL != tempname)
2115 dc->temp_filename = GNUNET_strdup (tempname);
2117 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2120 "Starting download `%s' of %llu bytes with tree depth %u\n",
2122 (unsigned long long) length,
2124 dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2130 * Download parts of a file. Note that this will store
2131 * the blocks at the respective offset in the given file. Also, the
2132 * download is still using the blocking of the underlying FS
2133 * encoding. As a result, the download may *write* outside of the
2134 * given boundaries (if offset and length do not match the 32k FS
2135 * block boundaries). <p>
2137 * This function should be used to focus a download towards a
2138 * particular portion of the file (optimization), not to strictly
2139 * limit the download to exactly those bytes.
2141 * @param h handle to the file sharing subsystem
2142 * @param uri the URI of the file (determines what to download); CHK or LOC URI
2143 * @param meta known metadata for the file (can be NULL)
2144 * @param filename where to store the file, maybe NULL (then no file is
2145 * created on disk and data must be grabbed from the callbacks)
2146 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2147 * can be NULL (in which case we will pick a name if needed); the temporary file
2148 * may already exist, in which case we will try to use the data that is there and
2149 * if it is not what is desired, will overwrite it
2150 * @param offset at what offset should we start the download (typically 0)
2151 * @param length how many bytes should be downloaded starting at offset
2152 * @param anonymity anonymity level to use for the download
2153 * @param options various options
2154 * @param cctx initial value for the client context for this download
2155 * @param parent parent download to associate this download with (use NULL
2156 * for top-level downloads; useful for manually-triggered recursive downloads)
2157 * @return context that can be used to control this download
2159 struct GNUNET_FS_DownloadContext *
2160 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
2161 const struct GNUNET_FS_Uri *uri,
2162 const struct GNUNET_CONTAINER_MetaData *meta,
2163 const char *filename, const char *tempname,
2164 uint64_t offset, uint64_t length, uint32_t anonymity,
2165 enum GNUNET_FS_DownloadOptions options, void *cctx,
2166 struct GNUNET_FS_DownloadContext *parent)
2168 struct GNUNET_FS_DownloadContext *dc;
2170 dc = create_download_context (h, uri, meta, filename, tempname,
2171 offset, length, anonymity, options, cctx);
2174 dc->parent = parent;
2176 GNUNET_CONTAINER_DLL_insert (parent->child_head, parent->child_tail, dc);
2177 else if (0 == (GNUNET_FS_DOWNLOAD_IS_PROBE & options) )
2179 GNUNET_FS_make_top (dc->h, &GNUNET_FS_download_signal_suspend_, dc);
2185 * Download parts of a file based on a search result. The download
2186 * will be associated with the search result (and the association
2187 * will be preserved when serializing/deserializing the state).
2188 * If the search is stopped, the download will not be aborted but
2189 * be 'promoted' to a stand-alone download.
2191 * As with the other download function, this will store
2192 * the blocks at the respective offset in the given file. Also, the
2193 * download is still using the blocking of the underlying FS
2194 * encoding. As a result, the download may *write* outside of the
2195 * given boundaries (if offset and length do not match the 32k FS
2196 * block boundaries). <p>
2198 * The given range can be used to focus a download towards a
2199 * particular portion of the file (optimization), not to strictly
2200 * limit the download to exactly those bytes.
2202 * @param h handle to the file sharing subsystem
2203 * @param sr the search result to use for the download (determines uri and
2204 * meta data and associations)
2205 * @param filename where to store the file, maybe NULL (then no file is
2206 * created on disk and data must be grabbed from the callbacks)
2207 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2208 * can be NULL (in which case we will pick a name if needed); the temporary file
2209 * may already exist, in which case we will try to use the data that is there and
2210 * if it is not what is desired, will overwrite it
2211 * @param offset at what offset should we start the download (typically 0)
2212 * @param length how many bytes should be downloaded starting at offset
2213 * @param anonymity anonymity level to use for the download
2214 * @param options various download options
2215 * @param cctx initial value for the client context for this download
2216 * @return context that can be used to control this download
2218 struct GNUNET_FS_DownloadContext *
2219 GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h,
2220 struct GNUNET_FS_SearchResult *sr,
2221 const char *filename,
2222 const char *tempname, uint64_t offset,
2223 uint64_t length, uint32_t anonymity,
2224 enum GNUNET_FS_DownloadOptions options,
2227 struct GNUNET_FS_DownloadContext *dc;
2229 if ((NULL == sr) || (NULL != sr->download))
2234 dc = create_download_context (h, sr->uri, sr->meta, filename, tempname,
2235 offset, length, anonymity, options, cctx);
2240 if (NULL != sr->probe_ctx)
2242 GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
2243 sr->probe_ctx = NULL;
2245 if (GNUNET_SCHEDULER_NO_TASK != sr->probe_ping_task)
2247 GNUNET_SCHEDULER_cancel (sr->probe_ping_task);
2248 sr->probe_ping_task = GNUNET_SCHEDULER_NO_TASK;
2255 * Start the downloading process (by entering the queue).
2257 * @param dc our download context
2260 GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc)
2262 if (dc->completed == dc->length)
2264 GNUNET_assert (NULL == dc->job_queue);
2265 GNUNET_assert (NULL != dc->active);
2267 GNUNET_FS_queue_ (dc->h, &activate_fs_download, &deactivate_fs_download,
2268 dc, (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE,
2269 (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
2270 ? GNUNET_FS_QUEUE_PRIORITY_NORMAL
2271 : GNUNET_FS_QUEUE_PRIORITY_PROBE);
2272 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2273 "Download %p put into queue as job %p\n",
2280 * Stop a download (aborts if download is incomplete).
2282 * @param dc handle for the download
2283 * @param do_delete delete files of incomplete downloads
2286 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete)
2288 struct GNUNET_FS_ProgressInfo pi;
2290 int search_was_null;
2292 if (NULL != dc->top)
2293 GNUNET_FS_end_top (dc->h, dc->top);
2294 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
2296 GNUNET_SCHEDULER_cancel (dc->task);
2297 dc->task = GNUNET_SCHEDULER_NO_TASK;
2299 search_was_null = (NULL == dc->search);
2300 if (NULL != dc->search)
2302 dc->search->download = NULL;
2303 GNUNET_FS_search_result_sync_ (dc->search);
2306 if (NULL != dc->job_queue)
2308 GNUNET_FS_dequeue_ (dc->job_queue);
2309 dc->job_queue = NULL;
2313 GNUNET_FS_tree_encoder_finish (dc->te, NULL);
2316 have_children = (NULL != dc->child_head) ? GNUNET_YES : GNUNET_NO;
2317 while (NULL != dc->child_head)
2318 GNUNET_FS_download_stop (dc->child_head, do_delete);
2319 if (NULL != dc->parent)
2320 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, dc->parent->child_tail,
2322 if (NULL != dc->serialization)
2323 GNUNET_FS_remove_sync_file_ (dc->h,
2324 ((NULL != dc->parent) ||
2325 (! search_was_null)) ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD :
2326 GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2328 if ((GNUNET_YES == have_children) && (NULL == dc->parent))
2329 GNUNET_FS_remove_sync_dir_ (dc->h,
2330 (! search_was_null) ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD :
2331 GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2333 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
2334 GNUNET_FS_download_make_status_ (&pi, dc);
2335 GNUNET_FS_free_download_request_ (dc->top_request);
2336 dc->top_request = NULL;
2337 if (NULL != dc->active)
2339 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2342 if (NULL != dc->filename)
2344 if ((dc->completed != dc->length) && (GNUNET_YES == do_delete))
2346 if ( (0 != UNLINK (dc->filename)) &&
2348 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
2351 GNUNET_free (dc->filename);
2353 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2354 GNUNET_FS_uri_destroy (dc->uri);
2355 if (NULL != dc->temp_filename)
2357 if (0 != UNLINK (dc->temp_filename))
2358 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "unlink",
2360 GNUNET_free (dc->temp_filename);
2362 GNUNET_free_non_null (dc->serialization);
2363 GNUNET_assert (NULL == dc->job_queue);
2367 /* end of fs_download.c */