2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010 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 * - different priority for scheduling probe downloads?
29 #include "gnunet_constants.h"
30 #include "gnunet_fs_service.h"
34 #define DEBUG_DOWNLOAD GNUNET_NO
37 * Determine if the given download (options and meta data) should cause
38 * use to try to do a recursive download.
41 is_recursive_download (struct GNUNET_FS_DownloadContext *dc)
43 return (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
44 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
45 ( (dc->meta == NULL) &&
46 ( (NULL == dc->filename) ||
47 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
49 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
50 GNUNET_FS_DIRECTORY_EXT)) ) ) ) );
55 * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
56 * only have to truncate the file once we're done).
58 * Given the offset of a block (with respect to the DBLOCKS) and its
59 * depth, return the offset where we would store this block in the
62 * @param fsize overall file size
63 * @param off offset of the block in the file
64 * @param depth depth of the block in the tree
65 * @param treedepth maximum depth of the tree
66 * @return off for DBLOCKS (depth == treedepth),
67 * otherwise an offset past the end
68 * of the file that does not overlap
69 * with the range for any other block
72 compute_disk_offset (uint64_t fsize,
75 unsigned int treedepth)
78 uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
79 uint64_t loff; /* where do IBlocks for depth "i" start? */
80 unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
82 if (depth == treedepth)
84 /* first IBlocks start at the end of file, rounded up
85 to full DBLOCK_SIZE */
86 loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
87 lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
88 GNUNET_assert (0 == (off % DBLOCK_SIZE));
89 ioff = (off / DBLOCK_SIZE);
90 for (i=treedepth-1;i>depth;i--)
93 lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
94 GNUNET_assert (lsize > 0);
95 GNUNET_assert (0 == (ioff % CHK_PER_INODE));
96 ioff /= CHK_PER_INODE;
98 return loff + ioff * sizeof (struct ContentHashKey);
103 * Given a file of the specified treedepth and a block at the given
104 * offset and depth, calculate the offset for the CHK at the given
107 * @param offset the offset of the first
108 * DBLOCK in the subtree of the
110 * @param depth the depth of the IBLOCK in the tree
111 * @param treedepth overall depth of the tree
112 * @param k which CHK in the IBLOCK are we
114 * @return offset if k=0, otherwise an appropriately
115 * larger value (i.e., if depth = treedepth-1,
116 * the returned value should be offset+DBLOCK_SIZE)
119 compute_dblock_offset (uint64_t offset,
121 unsigned int treedepth,
125 uint64_t lsize; /* what is the size of the sum of all DBlocks
126 that a CHK at depth i corresponds to? */
128 if (depth == treedepth)
131 for (i=treedepth-1;i>depth;i--)
132 lsize *= CHK_PER_INODE;
133 return offset + k * lsize;
138 * Fill in all of the generic fields for a download event and call the
141 * @param pi structure to fill in
142 * @param dc overall download context
145 GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
146 struct GNUNET_FS_DownloadContext *dc)
148 pi->value.download.dc = dc;
149 pi->value.download.cctx
151 pi->value.download.pctx
152 = (dc->parent == NULL) ? NULL : dc->parent->client_info;
153 pi->value.download.sctx
154 = (dc->search == NULL) ? NULL : dc->search->client_info;
155 pi->value.download.uri
157 pi->value.download.filename
159 pi->value.download.size
161 pi->value.download.duration
162 = GNUNET_TIME_absolute_get_duration (dc->start_time);
163 pi->value.download.completed
165 pi->value.download.anonymity
167 pi->value.download.eta
168 = GNUNET_TIME_calculate_eta (dc->start_time,
171 pi->value.download.is_active = (dc->client == NULL) ? GNUNET_NO : GNUNET_YES;
172 if (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
173 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
176 dc->client_info = GNUNET_FS_search_probe_progress_ (NULL,
181 * We're ready to transmit a search request to the
182 * file-sharing service. Do it. If there is
183 * more than one request pending, try to send
184 * multiple or request another transmission.
187 * @param size number of bytes available in buf
188 * @param buf where the callee should write the message
189 * @return number of bytes written to buf
192 transmit_download_request (void *cls,
198 * Closure for iterator processing results.
200 struct ProcessResultClosure
206 GNUNET_HashCode query;
209 * Data found in P2P network.
214 * Our download context.
216 struct GNUNET_FS_DownloadContext *dc;
219 * Number of bytes in data.
226 enum GNUNET_BLOCK_Type type;
229 * Flag to indicate if this block should be stored on disk.
237 * Iterator over entries in the pending requests in the 'active' map for the
238 * reply that we just got.
240 * @param cls closure (our 'struct ProcessResultClosure')
241 * @param key query for the given value / request
242 * @param value value in the hash map (a 'struct DownloadRequest')
243 * @return GNUNET_YES (we should continue to iterate); unless serious error
246 process_result_with_request (void *cls,
247 const GNUNET_HashCode * key,
252 * We've found a matching block without downloading it.
253 * Encrypt it and pass it to our "receive" function as
254 * if we had received it from the network.
256 * @param dc download in question
257 * @param chk request this relates to
258 * @param sm request details
259 * @param block plaintext data matching request
260 * @param len number of bytes in block
261 * @param depth depth of the block
262 * @param do_store should we still store the block on disk?
263 * @return GNUNET_OK on success
266 encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc,
267 const struct ContentHashKey *chk,
268 struct DownloadRequest *sm,
274 struct ProcessResultClosure prc;
276 struct GNUNET_CRYPTO_AesSessionKey sk;
277 struct GNUNET_CRYPTO_AesInitializationVector iv;
278 GNUNET_HashCode query;
280 GNUNET_CRYPTO_hash_to_aes_key (&chk->key, &sk, &iv);
281 if (-1 == GNUNET_CRYPTO_aes_encrypt (block, len,
287 return GNUNET_SYSERR;
289 GNUNET_CRYPTO_hash (enc, len, &query);
290 if (0 != memcmp (&query,
292 sizeof (GNUNET_HashCode)))
295 return GNUNET_SYSERR;
298 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
299 "Matching block already present, no need for download!\n");
301 /* already got it! */
305 prc.type = (dc->treedepth == depth)
306 ? GNUNET_BLOCK_TYPE_FS_DBLOCK
307 : GNUNET_BLOCK_TYPE_FS_IBLOCK;
308 prc.query = chk->query;
309 prc.do_store = do_store;
310 process_result_with_request (&prc,
318 * Closure for match_full_data.
320 struct MatchDataContext
323 * CHK we are looking for.
325 const struct ContentHashKey *chk;
328 * Download we're processing.
330 struct GNUNET_FS_DownloadContext *dc;
335 struct DownloadRequest *sm;
338 * Overall offset in the file.
343 * Desired length of the block.
348 * Flag set to GNUNET_YES on success.
354 * Type of a function that libextractor calls for each
355 * meta data item found.
357 * @param cls closure (user-defined)
358 * @param plugin_name name of the plugin that produced this value;
359 * special values can be used (i.e. '<zlib>' for zlib being
360 * used in the main libextractor library and yielding
362 * @param type libextractor-type describing the meta data
363 * @param format basic format information about data
364 * @param data_mime_type mime-type of data (not of the original file);
365 * can be NULL (if mime-type is not known)
366 * @param data actual meta-data found
367 * @param data_len number of bytes in data
368 * @return 0 to continue extracting, 1 to abort
371 match_full_data (void *cls,
372 const char *plugin_name,
373 enum EXTRACTOR_MetaType type,
374 enum EXTRACTOR_MetaFormat format,
375 const char *data_mime_type,
379 struct MatchDataContext *mdc = cls;
382 if (type == EXTRACTOR_METATYPE_GNUNET_FULL_DATA)
384 if ( (mdc->offset > data_len) ||
385 (mdc->offset + mdc->len > data_len) )
387 GNUNET_CRYPTO_hash (&data[mdc->offset],
390 if (0 != memcmp (&key,
392 sizeof (GNUNET_HashCode)))
399 encrypt_existing_match (mdc->dc,
410 mdc->done = GNUNET_YES;
419 * Closure for 'reconstruct_cont' and 'reconstruct_cb'.
421 struct ReconstructContext
424 * File handle open for the reconstruction.
426 struct GNUNET_DISK_FileHandle *fh;
429 * the download context.
431 struct GNUNET_FS_DownloadContext *dc;
434 * Tree encoder used for the reconstruction.
436 struct GNUNET_FS_TreeEncoder *te;
439 * CHK of block we are trying to reconstruct.
441 struct ContentHashKey chk;
444 * Request that was generated.
446 struct DownloadRequest *sm;
449 * Offset of block we are trying to reconstruct.
454 * Depth of block we are trying to reconstruct.
462 * Continuation after a possible attempt to reconstruct
463 * the current IBlock from the existing file.
465 * @param cls the 'struct ReconstructContext'
466 * @param tc scheduler context
469 reconstruct_cont (void *cls,
470 const struct GNUNET_SCHEDULER_TaskContext *tc)
472 struct ReconstructContext *rcc = cls;
475 GNUNET_FS_tree_encoder_finish (rcc->te, NULL, NULL);
476 rcc->dc->reconstruct_failed = GNUNET_YES;
478 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (rcc->fh));
479 if ( (rcc->dc->th == NULL) &&
480 (rcc->dc->client != NULL) )
483 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
484 "Asking for transmission to FS service\n");
486 rcc->dc->th = GNUNET_CLIENT_notify_transmit_ready (rcc->dc->client,
487 sizeof (struct SearchMessage),
488 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
490 &transmit_download_request,
496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497 "Transmission request not issued (%p %p)\n",
507 get_next_block (void *cls,
508 const struct GNUNET_SCHEDULER_TaskContext *tc)
510 struct ReconstructContext *rcc = cls;
511 GNUNET_FS_tree_encoder_next (rcc->te);
516 * Function called asking for the current (encoded)
517 * block to be processed. After processing the
518 * client should either call "GNUNET_FS_tree_encode_next"
519 * or (on error) "GNUNET_FS_tree_encode_finish".
521 * This function checks if the content on disk matches
522 * the expected content based on the URI.
525 * @param query the query for the block (key for lookup in the datastore)
526 * @param offset offset of the block
527 * @param type type of the block (IBLOCK or DBLOCK)
528 * @param block the (encrypted) block
529 * @param block_size size of block (in bytes)
532 reconstruct_cb (void *cls,
533 const GNUNET_HashCode *query,
536 enum GNUNET_BLOCK_Type type,
540 struct ReconstructContext *rcc = cls;
541 struct ProcessResultClosure prc;
542 struct GNUNET_FS_TreeEncoder *te;
548 roff = offset / DBLOCK_SIZE;
549 for (i=rcc->dc->treedepth;i>depth;i--)
550 roff /= CHK_PER_INODE;
551 boff = roff * DBLOCK_SIZE;
552 for (i=rcc->dc->treedepth;i>depth;i--)
553 boff *= CHK_PER_INODE;
554 /* convert reading offset into IBLOCKs on-disk offset */
555 off = compute_disk_offset (GNUNET_FS_uri_chk_get_file_size (rcc->dc->uri),
559 if ( (off == rcc->offset) &&
560 (depth == rcc->depth) &&
563 sizeof (GNUNET_HashCode))) )
565 /* already got it! */
566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567 _("Block reconstruction at offset %llu and depth %u successful\n"),
568 (unsigned long long) offset,
572 prc.size = block_size;
574 prc.query = rcc->chk.query;
575 prc.do_store = GNUNET_NO;
576 process_result_with_request (&prc,
581 GNUNET_FS_tree_encoder_finish (te, NULL, NULL);
585 GNUNET_SCHEDULER_add_continuation (&get_next_block,
587 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
592 * Function called by the tree encoder to obtain
593 * a block of plaintext data (for the lowest level
596 * @param cls our 'struct ReconstructContext'
597 * @param offset identifies which block to get
598 * @param max (maximum) number of bytes to get; returning
599 * fewer will also cause errors
600 * @param buf where to copy the plaintext buffer
601 * @param emsg location to store an error message (on error)
602 * @return number of bytes copied to buf, 0 on error
605 fh_reader (void *cls,
611 struct ReconstructContext *rcc = cls;
612 struct GNUNET_DISK_FileHandle *fh = rcc->fh;
617 GNUNET_DISK_file_seek (fh,
619 GNUNET_DISK_SEEK_SET))
621 *emsg = GNUNET_strdup (strerror (errno));
624 ret = GNUNET_DISK_file_read (fh, buf, max);
627 *emsg = GNUNET_strdup (strerror (errno));
635 * Schedule the download of the specified block in the tree.
637 * @param dc overall download this block belongs to
638 * @param chk content-hash-key of the block
639 * @param offset offset of the block in the file
640 * (for IBlocks, the offset is the lowest
641 * offset of any DBlock in the subtree under
643 * @param depth depth of the block, 0 is the root of the tree
646 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
647 const struct ContentHashKey *chk,
651 struct DownloadRequest *sm;
655 char block[DBLOCK_SIZE];
657 struct MatchDataContext mdc;
658 struct GNUNET_DISK_FileHandle *fh;
659 struct ReconstructContext *rcc;
661 total = GNUNET_FS_uri_chk_get_file_size (dc->uri);
662 len = GNUNET_FS_tree_calculate_block_size (total,
666 off = compute_disk_offset (total,
670 sm = GNUNET_malloc (sizeof (struct DownloadRequest));
674 sm->is_pending = GNUNET_YES;
675 sm->next = dc->pending;
677 GNUNET_CONTAINER_multihashmap_put (dc->active,
680 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
681 if ( (dc->tried_full_data == GNUNET_NO) &&
689 mdc.done = GNUNET_NO;
690 GNUNET_CONTAINER_meta_data_iterate (dc->meta,
693 if (mdc.done == GNUNET_YES)
695 dc->tried_full_data = GNUNET_YES;
698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
699 "Scheduling download at offset %llu and depth %u for `%s'\n",
700 (unsigned long long) offset,
702 GNUNET_h2s (&chk->query));
705 if ( ( (dc->old_file_size > off) ||
706 ( (depth < dc->treedepth) &&
707 (dc->reconstruct_failed == GNUNET_NO) ) ) &&
708 (dc->filename != NULL) )
709 fh = GNUNET_DISK_file_open (dc->filename,
710 GNUNET_DISK_OPEN_READ,
711 GNUNET_DISK_PERM_NONE);
713 (dc->old_file_size > off) &&
715 GNUNET_DISK_file_seek (fh,
717 GNUNET_DISK_SEEK_SET) ) &&
719 GNUNET_DISK_file_read (fh,
723 GNUNET_CRYPTO_hash (block, len, &key);
724 if ( (0 == memcmp (&key,
726 sizeof (GNUNET_HashCode))) &&
728 encrypt_existing_match (dc,
736 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
740 rcc = GNUNET_malloc (sizeof (struct ReconstructContext));
747 if ( (depth < dc->treedepth) &&
748 (dc->reconstruct_failed == GNUNET_NO) &&
751 rcc->te = GNUNET_FS_tree_encoder_create (dc->h,
758 GNUNET_FS_tree_encoder_next (rcc->te);
761 reconstruct_cont (rcc, NULL);
766 * Suggest a filename based on given metadata.
768 * @param md given meta data
769 * @return NULL if meta data is useless for suggesting a filename
772 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
774 static const char *mimeMap[][2] = {
775 {"application/bz2", ".bz2"},
776 {"application/gnunet-directory", ".gnd"},
777 {"application/java", ".class"},
778 {"application/msword", ".doc"},
779 {"application/ogg", ".ogg"},
780 {"application/pdf", ".pdf"},
781 {"application/pgp-keys", ".key"},
782 {"application/pgp-signature", ".pgp"},
783 {"application/postscript", ".ps"},
784 {"application/rar", ".rar"},
785 {"application/rtf", ".rtf"},
786 {"application/xml", ".xml"},
787 {"application/x-debian-package", ".deb"},
788 {"application/x-dvi", ".dvi"},
789 {"applixation/x-flac", ".flac"},
790 {"applixation/x-gzip", ".gz"},
791 {"application/x-java-archive", ".jar"},
792 {"application/x-java-vm", ".class"},
793 {"application/x-python-code", ".pyc"},
794 {"application/x-redhat-package-manager", ".rpm"},
795 {"application/x-rpm", ".rpm"},
796 {"application/x-tar", ".tar"},
797 {"application/x-tex-pk", ".pk"},
798 {"application/x-texinfo", ".texinfo"},
799 {"application/x-xcf", ".xcf"},
800 {"application/x-xfig", ".xfig"},
801 {"application/zip", ".zip"},
803 {"audio/midi", ".midi"},
804 {"audio/mpeg", ".mp3"},
805 {"audio/real", ".rm"},
806 {"audio/x-wav", ".wav"},
808 {"image/gif", ".gif"},
809 {"image/jpeg", ".jpg"},
810 {"image/pcx", ".pcx"},
811 {"image/png", ".png"},
812 {"image/tiff", ".tiff"},
813 {"image/x-ms-bmp", ".bmp"},
814 {"image/x-xpixmap", ".xpm"},
816 {"text/css", ".css"},
817 {"text/html", ".html"},
818 {"text/plain", ".txt"},
819 {"text/rtf", ".rtf"},
820 {"text/x-c++hdr", ".h++"},
821 {"text/x-c++src", ".c++"},
822 {"text/x-chdr", ".h"},
823 {"text/x-csrc", ".c"},
824 {"text/x-java", ".java"},
825 {"text/x-moc", ".moc"},
826 {"text/x-pascal", ".pas"},
827 {"text/x-perl", ".pl"},
828 {"text/x-python", ".py"},
829 {"text/x-tex", ".tex"},
831 {"video/avi", ".avi"},
832 {"video/mpeg", ".mpeg"},
833 {"video/quicktime", ".qt"},
834 {"video/real", ".rm"},
835 {"video/x-msvideo", ".avi"},
844 ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
845 EXTRACTOR_METATYPE_FILENAME);
849 mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
850 EXTRACTOR_METATYPE_MIMETYPE);
854 while ( (mimeMap[i][0] != NULL) &&
855 (0 != strcmp (mime, mimeMap[i][0])))
857 if (mimeMap[i][1] == NULL)
858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
859 GNUNET_ERROR_TYPE_BULK,
860 _("Did not find mime type `%s' in extension list.\n"),
866 base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
867 EXTRACTOR_METATYPE_TITLE,
868 EXTRACTOR_METATYPE_BOOK_TITLE,
869 EXTRACTOR_METATYPE_ORIGINAL_TITLE,
870 EXTRACTOR_METATYPE_PACKAGE_NAME,
871 EXTRACTOR_METATYPE_URL,
872 EXTRACTOR_METATYPE_URI,
873 EXTRACTOR_METATYPE_DESCRIPTION,
874 EXTRACTOR_METATYPE_ISRC,
875 EXTRACTOR_METATYPE_JOURNAL_NAME,
876 EXTRACTOR_METATYPE_AUTHOR_NAME,
877 EXTRACTOR_METATYPE_SUBJECT,
878 EXTRACTOR_METATYPE_ALBUM,
879 EXTRACTOR_METATYPE_ARTIST,
880 EXTRACTOR_METATYPE_KEYWORDS,
881 EXTRACTOR_METATYPE_COMMENT,
882 EXTRACTOR_METATYPE_UNKNOWN,
884 if ( (base == NULL) &&
888 return GNUNET_strdup (ext);
891 GNUNET_asprintf (&ret,
901 * We've lost our connection with the FS service.
902 * Re-establish it and re-transmit all of our
905 * @param dc download context that is having trouble
908 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
912 * We found an entry in a directory. Check if the respective child
913 * already exists and if not create the respective child download.
915 * @param cls the parent download
916 * @param filename name of the file in the directory
917 * @param uri URI of the file (CHK or LOC)
918 * @param meta meta data of the file
919 * @param length number of bytes in data
920 * @param data contents of the file (or NULL if they were not inlined)
923 trigger_recursive_download (void *cls,
924 const char *filename,
925 const struct GNUNET_FS_Uri *uri,
926 const struct GNUNET_CONTAINER_MetaData *meta,
932 * We're done downloading a directory. Open the file and
933 * trigger all of the (remaining) child downloads.
935 * @param dc context of download that just completed
938 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
943 struct GNUNET_DISK_FileHandle *h;
944 struct GNUNET_DISK_MapHandle *m;
946 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
947 size = (size_t) size64;
948 if (size64 != (uint64_t) size)
950 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
951 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
954 if (dc->filename != NULL)
956 h = GNUNET_DISK_file_open (dc->filename,
957 GNUNET_DISK_OPEN_READ,
958 GNUNET_DISK_PERM_NONE);
962 GNUNET_assert (dc->temp_filename != NULL);
963 h = GNUNET_DISK_file_open (dc->temp_filename,
964 GNUNET_DISK_OPEN_READ,
965 GNUNET_DISK_PERM_NONE);
969 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
972 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
973 _("Directory too large for system address space\n"));
977 GNUNET_FS_directory_list_contents (size,
980 &trigger_recursive_download,
982 GNUNET_DISK_file_unmap (m);
984 GNUNET_DISK_file_close (h);
985 if (dc->filename == NULL)
987 if (0 != UNLINK (dc->temp_filename))
988 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
991 GNUNET_free (dc->temp_filename);
992 dc->temp_filename = NULL;
998 * Check if all child-downloads have completed and
999 * if so, signal completion (and possibly recurse to
1003 check_completed (struct GNUNET_FS_DownloadContext *dc)
1005 struct GNUNET_FS_ProgressInfo pi;
1006 struct GNUNET_FS_DownloadContext *pos;
1008 pos = dc->child_head;
1011 if ( (pos->emsg == NULL) &&
1012 (pos->completed < pos->length) )
1013 return; /* not done yet */
1014 if ( (pos->child_head != NULL) &&
1015 (pos->has_finished != GNUNET_YES) )
1016 return; /* not transitively done yet */
1019 dc->has_finished = GNUNET_YES;
1020 GNUNET_FS_download_sync_ (dc);
1021 /* signal completion */
1022 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
1023 GNUNET_FS_download_make_status_ (&pi, dc);
1024 if (dc->parent != NULL)
1025 check_completed (dc->parent);
1029 #define GNUNET_FS_URI_CHK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_CHK_INFIX
1032 * We found an entry in a directory. Check if the respective child
1033 * already exists and if not create the respective child download.
1035 * @param cls the parent download
1036 * @param filename name of the file in the directory
1037 * @param uri URI of the file (CHK or LOC)
1038 * @param meta meta data of the file
1039 * @param length number of bytes in data
1040 * @param data contents of the file (or NULL if they were not inlined)
1043 trigger_recursive_download (void *cls,
1044 const char *filename,
1045 const struct GNUNET_FS_Uri *uri,
1046 const struct GNUNET_CONTAINER_MetaData *meta,
1050 struct GNUNET_FS_DownloadContext *dc = cls;
1051 struct GNUNET_FS_DownloadContext *cpos;
1052 struct GNUNET_DISK_FileHandle *fh;
1054 const char *real_name;
1063 return; /* entry for the directory itself */
1064 cpos = dc->child_head;
1065 while (cpos != NULL)
1067 if ( (GNUNET_FS_uri_test_equal (uri,
1069 ( (filename != NULL) &&
1070 (0 == strcmp (cpos->filename,
1076 return; /* already exists */
1078 if (NULL == filename)
1080 fn = GNUNET_FS_meta_data_suggest_filename (meta);
1083 us = GNUNET_FS_uri_to_string (uri);
1084 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_CHK_PREFIX)]);
1087 else if (fn[0] == '.')
1090 us = GNUNET_FS_uri_to_string (uri);
1091 GNUNET_asprintf (&fn,
1093 &us[strlen (GNUNET_FS_URI_CHK_PREFIX)], ext);
1097 /* change '\' to '/' (this should have happened
1098 during insertion, but malicious peers may
1099 not have done this) */
1100 while (NULL != (pos = strstr (fn, "\\")))
1102 /* remove '../' everywhere (again, well-behaved
1103 peers don't do this, but don't trust that
1104 we did not get something nasty) */
1105 while (NULL != (pos = strstr (fn, "../")))
1113 if (dc->filename == NULL)
1119 dn = GNUNET_strdup (dc->filename);
1120 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
1122 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
1123 GNUNET_FS_DIRECTORY_EXT)) );
1124 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
1126 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
1127 GNUNET_FS_DIRECTORY_EXT)) )
1128 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
1129 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
1130 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
1132 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
1133 GNUNET_FS_DIRECTORY_EXT)) ) )
1135 GNUNET_asprintf (&full_name,
1140 GNUNET_FS_DIRECTORY_EXT);
1144 GNUNET_asprintf (&full_name,
1152 if ( (full_name != NULL) &&
1154 GNUNET_DISK_directory_create_for_file (full_name)) )
1156 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1157 _("Failed to create directory for recursive download of `%s'\n"),
1159 GNUNET_free (full_name);
1160 GNUNET_free_non_null (fn);
1165 if ( (data != NULL) &&
1166 (GNUNET_FS_uri_chk_get_file_size (uri) == length) )
1168 if (full_name == NULL)
1170 temp_name = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
1171 real_name = temp_name;
1175 real_name = full_name;
1177 /* write to disk, then trigger normal download which will instantly progress to completion */
1178 fh = GNUNET_DISK_file_open (real_name,
1179 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
1180 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
1183 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1186 GNUNET_free (full_name);
1187 GNUNET_free_non_null (fn);
1191 GNUNET_DISK_file_write (fh,
1195 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1199 GNUNET_DISK_file_close (fh);
1201 GNUNET_FS_download_start (dc->h,
1204 full_name, temp_name,
1206 GNUNET_FS_uri_chk_get_file_size (uri),
1211 GNUNET_free_non_null (full_name);
1212 GNUNET_free_non_null (temp_name);
1213 GNUNET_free_non_null (fn);
1218 * Free entries in the map.
1220 * @param cls unused (NULL)
1222 * @param entry entry of type "struct DownloadRequest" which is freed
1226 free_entry (void *cls,
1227 const GNUNET_HashCode *key,
1230 GNUNET_free (entry);
1236 * Iterator over entries in the pending requests in the 'active' map for the
1237 * reply that we just got.
1239 * @param cls closure (our 'struct ProcessResultClosure')
1240 * @param key query for the given value / request
1241 * @param value value in the hash map (a 'struct DownloadRequest')
1242 * @return GNUNET_YES (we should continue to iterate); unless serious error
1245 process_result_with_request (void *cls,
1246 const GNUNET_HashCode * key,
1249 struct ProcessResultClosure *prc = cls;
1250 struct DownloadRequest *sm = value;
1251 struct DownloadRequest *ppos;
1252 struct DownloadRequest *pprev;
1253 struct GNUNET_DISK_FileHandle *fh;
1254 struct GNUNET_FS_DownloadContext *dc = prc->dc;
1255 struct GNUNET_CRYPTO_AesSessionKey skey;
1256 struct GNUNET_CRYPTO_AesInitializationVector iv;
1258 struct GNUNET_FS_ProgressInfo pi;
1263 struct ContentHashKey *chk;
1266 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
1270 if (prc->size != bs)
1273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1274 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
1278 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
1281 GNUNET_assert (GNUNET_YES ==
1282 GNUNET_CONTAINER_multihashmap_remove (dc->active,
1285 /* if this request is on the pending list, remove it! */
1288 while (ppos != NULL)
1293 dc->pending = ppos->next;
1295 pprev->next = ppos->next;
1301 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
1302 if (-1 == GNUNET_CRYPTO_aes_decrypt (prc->data,
1309 dc->emsg = GNUNET_strdup ("internal error decrypting content");
1312 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
1317 if ( ( GNUNET_YES == prc->do_store) &&
1318 ( (dc->filename != NULL) ||
1319 (is_recursive_download (dc)) ) &&
1320 ( (sm->depth == dc->treedepth) ||
1321 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
1323 fh = GNUNET_DISK_file_open (dc->filename != NULL
1325 : dc->temp_filename,
1326 GNUNET_DISK_OPEN_READWRITE |
1327 GNUNET_DISK_OPEN_CREATE,
1328 GNUNET_DISK_PERM_USER_READ |
1329 GNUNET_DISK_PERM_USER_WRITE |
1330 GNUNET_DISK_PERM_GROUP_READ |
1331 GNUNET_DISK_PERM_OTHER_READ);
1333 if ( (NULL == fh) &&
1334 (GNUNET_YES == prc->do_store) &&
1335 ( (dc->filename != NULL) ||
1336 (is_recursive_download (dc)) ) &&
1337 ( (sm->depth == dc->treedepth) ||
1338 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
1340 GNUNET_asprintf (&dc->emsg,
1341 _("Download failed: could not open file `%s': %s\n"),
1349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1350 "Saving decrypted block to disk at offset %llu\n",
1351 (unsigned long long) off);
1354 GNUNET_DISK_file_seek (fh,
1356 GNUNET_DISK_SEEK_SET) ) )
1358 GNUNET_asprintf (&dc->emsg,
1359 _("Failed to seek to offset %llu in file `%s': %s\n"),
1360 (unsigned long long) off,
1366 GNUNET_DISK_file_write (fh,
1370 GNUNET_asprintf (&dc->emsg,
1371 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
1372 (unsigned int) prc->size,
1373 (unsigned long long) off,
1378 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
1381 if (sm->depth == dc->treedepth)
1384 if (sm->offset < dc->offset)
1386 /* starting offset begins in the middle of pt,
1387 do not count first bytes as progress */
1388 GNUNET_assert (app > (dc->offset - sm->offset));
1389 app -= (dc->offset - sm->offset);
1391 if (sm->offset + prc->size > dc->offset + dc->length)
1393 /* end of block is after relevant range,
1394 do not count last bytes as progress */
1395 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
1396 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
1398 dc->completed += app;
1400 /* do recursive download if option is set and either meta data
1401 says it is a directory or if no meta data is given AND filename
1402 ends in '.gnd' (top-level case) */
1403 if (is_recursive_download (dc))
1404 GNUNET_FS_directory_list_contents (prc->size,
1407 &trigger_recursive_download,
1411 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1412 pi.value.download.specifics.progress.data = pt;
1413 pi.value.download.specifics.progress.offset = sm->offset;
1414 pi.value.download.specifics.progress.data_len = prc->size;
1415 pi.value.download.specifics.progress.depth = sm->depth;
1416 GNUNET_FS_download_make_status_ (&pi, dc);
1417 GNUNET_assert (dc->completed <= dc->length);
1418 if (dc->completed == dc->length)
1421 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1422 "Download completed, truncating file to desired length %llu\n",
1423 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
1425 /* truncate file to size (since we store IBlocks at the end) */
1426 if (dc->filename != NULL)
1428 if (0 != truncate (dc->filename,
1429 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1430 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1434 if (dc->job_queue != NULL)
1436 GNUNET_FS_dequeue_ (dc->job_queue);
1437 dc->job_queue = NULL;
1439 if (is_recursive_download (dc))
1440 full_recursive_download (dc);
1441 if (dc->child_head == NULL)
1443 /* signal completion */
1444 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
1445 GNUNET_FS_download_make_status_ (&pi, dc);
1446 if (dc->parent != NULL)
1447 check_completed (dc->parent);
1449 GNUNET_assert (sm->depth == dc->treedepth);
1451 if (sm->depth == dc->treedepth)
1453 GNUNET_FS_download_sync_ (dc);
1458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1459 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1461 (unsigned long long) sm->offset);
1463 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1464 chk = (struct ContentHashKey*) pt;
1465 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1467 off = compute_dblock_offset (sm->offset,
1471 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1472 (off < dc->offset + dc->length) )
1473 schedule_block_download (dc,
1479 GNUNET_FS_download_sync_ (dc);
1484 GNUNET_DISK_file_close (fh);
1485 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1486 pi.value.download.specifics.error.message = dc->emsg;
1487 GNUNET_FS_download_make_status_ (&pi, dc);
1488 /* abort all pending requests */
1491 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1494 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1495 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1501 GNUNET_FS_download_sync_ (dc);
1507 * Process a download result.
1509 * @param dc our download context
1510 * @param type type of the result
1511 * @param data the (encrypted) response
1512 * @param size size of data
1515 process_result (struct GNUNET_FS_DownloadContext *dc,
1516 enum GNUNET_BLOCK_Type type,
1520 struct ProcessResultClosure prc;
1526 prc.do_store = GNUNET_YES;
1527 GNUNET_CRYPTO_hash (data, size, &prc.query);
1529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1530 "Received result for query `%s' from `%s'-service\n",
1531 GNUNET_h2s (&prc.query),
1534 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1536 &process_result_with_request,
1542 * Type of a function to call when we receive a message
1545 * @param cls closure
1546 * @param msg message received, NULL on timeout or fatal error
1549 receive_results (void *cls,
1550 const struct GNUNET_MessageHeader * msg)
1552 struct GNUNET_FS_DownloadContext *dc = cls;
1553 const struct PutMessage *cm;
1556 if ( (NULL == msg) ||
1557 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1558 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1560 GNUNET_break (msg == NULL);
1564 msize = ntohs(msg->size);
1565 cm = (const struct PutMessage*) msg;
1569 msize - sizeof (struct PutMessage));
1570 if (dc->client == NULL)
1571 return; /* fatal error */
1572 /* continue receiving */
1573 GNUNET_CLIENT_receive (dc->client,
1576 GNUNET_TIME_UNIT_FOREVER_REL);
1582 * We're ready to transmit a search request to the
1583 * file-sharing service. Do it. If there is
1584 * more than one request pending, try to send
1585 * multiple or request another transmission.
1587 * @param cls closure
1588 * @param size number of bytes available in buf
1589 * @param buf where the callee should write the message
1590 * @return number of bytes written to buf
1593 transmit_download_request (void *cls,
1597 struct GNUNET_FS_DownloadContext *dc = cls;
1599 struct SearchMessage *sm;
1605 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1606 "Transmitting download request failed, trying to reconnect\n");
1611 GNUNET_assert (size >= sizeof (struct SearchMessage));
1614 while ( (dc->pending != NULL) &&
1615 (size >= msize + sizeof (struct SearchMessage)) )
1618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1619 "Transmitting download request for `%s' to `%s'-service\n",
1620 GNUNET_h2s (&dc->pending->chk.query),
1623 memset (sm, 0, sizeof (struct SearchMessage));
1624 sm->header.size = htons (sizeof (struct SearchMessage));
1625 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1626 if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1627 sm->options = htonl (1);
1629 sm->options = htonl (0);
1630 if (dc->pending->depth == dc->treedepth)
1631 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_DBLOCK);
1633 sm->type = htonl (GNUNET_BLOCK_TYPE_FS_IBLOCK);
1634 sm->anonymity_level = htonl (dc->anonymity);
1635 sm->target = dc->target.hashPubKey;
1636 sm->query = dc->pending->chk.query;
1637 dc->pending->is_pending = GNUNET_NO;
1638 dc->pending = dc->pending->next;
1639 msize += sizeof (struct SearchMessage);
1642 if (dc->pending != NULL)
1643 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1644 sizeof (struct SearchMessage),
1645 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1647 &transmit_download_request,
1654 * Reconnect to the FS service and transmit our queries NOW.
1656 * @param cls our download context
1660 do_reconnect (void *cls,
1661 const struct GNUNET_SCHEDULER_TaskContext *tc)
1663 struct GNUNET_FS_DownloadContext *dc = cls;
1664 struct GNUNET_CLIENT_Connection *client;
1666 dc->task = GNUNET_SCHEDULER_NO_TASK;
1667 client = GNUNET_CLIENT_connect ("fs",
1671 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1672 "Connecting to `%s'-service failed, will try again.\n",
1677 dc->client = client;
1678 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1679 sizeof (struct SearchMessage),
1680 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1682 &transmit_download_request,
1684 GNUNET_CLIENT_receive (client,
1687 GNUNET_TIME_UNIT_FOREVER_REL);
1692 * Add entries that are not yet pending back to the pending list.
1694 * @param cls our download context
1696 * @param entry entry of type "struct DownloadRequest"
1700 retry_entry (void *cls,
1701 const GNUNET_HashCode *key,
1704 struct GNUNET_FS_DownloadContext *dc = cls;
1705 struct DownloadRequest *dr = entry;
1707 if (! dr->is_pending)
1709 dr->next = dc->pending;
1710 dr->is_pending = GNUNET_YES;
1711 dc->pending = entry;
1718 * We've lost our connection with the FS service.
1719 * Re-establish it and re-transmit all of our
1722 * @param dc download context that is having trouble
1725 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1728 if (NULL != dc->client)
1731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1732 "Moving all requests back to pending list\n");
1736 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1739 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1742 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1747 "Will try to reconnect in 1s\n");
1750 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1758 * We're allowed to ask the FS service for our blocks. Start the download.
1760 * @param cls the 'struct GNUNET_FS_DownloadContext'
1761 * @param client handle to use for communcation with FS (we must destroy it!)
1764 activate_fs_download (void *cls,
1765 struct GNUNET_CLIENT_Connection *client)
1767 struct GNUNET_FS_DownloadContext *dc = cls;
1768 struct GNUNET_FS_ProgressInfo pi;
1771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1772 "Download activated\n");
1774 GNUNET_assert (NULL != client);
1775 GNUNET_assert (dc->client == NULL);
1776 GNUNET_assert (dc->th == NULL);
1777 dc->client = client;
1778 GNUNET_CLIENT_receive (client,
1781 GNUNET_TIME_UNIT_FOREVER_REL);
1782 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1783 GNUNET_FS_download_make_status_ (&pi, dc);
1784 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1789 "Asking for transmission to FS service\n");
1791 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1792 sizeof (struct SearchMessage),
1793 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1795 &transmit_download_request,
1797 GNUNET_assert (dc->th != NULL);
1802 * We must stop to ask the FS service for our blocks. Pause the download.
1804 * @param cls the 'struct GNUNET_FS_DownloadContext'
1807 deactivate_fs_download (void *cls)
1809 struct GNUNET_FS_DownloadContext *dc = cls;
1810 struct GNUNET_FS_ProgressInfo pi;
1813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1814 "Download deactivated\n");
1818 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1821 if (NULL != dc->client)
1823 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1826 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1827 GNUNET_FS_download_make_status_ (&pi, dc);
1832 * Task that creates the initial (top-level) download
1833 * request for the file.
1835 * @param cls the 'struct GNUNET_FS_DownloadContext'
1836 * @param tc scheduler context
1839 GNUNET_FS_download_start_task_ (void *cls,
1840 const struct GNUNET_SCHEDULER_TaskContext *tc)
1842 struct GNUNET_FS_DownloadContext *dc = cls;
1844 dc->start_task = GNUNET_SCHEDULER_NO_TASK;
1845 schedule_block_download (dc,
1846 (dc->uri->type == chk)
1847 ? &dc->uri->data.chk.chk
1848 : &dc->uri->data.loc.fi.chk,
1850 1 /* 0 == CHK, 1 == top */);
1855 * Create SUSPEND event for the given download operation
1856 * and then clean up our state (without stop signal).
1858 * @param cls the 'struct GNUNET_FS_DownloadContext' to signal for
1861 GNUNET_FS_download_signal_suspend_ (void *cls)
1863 struct GNUNET_FS_DownloadContext *dc = cls;
1864 struct GNUNET_FS_ProgressInfo pi;
1866 if (dc->start_task != GNUNET_SCHEDULER_NO_TASK)
1868 GNUNET_SCHEDULER_cancel (dc->start_task);
1869 dc->start_task = GNUNET_SCHEDULER_NO_TASK;
1871 if (dc->top != NULL)
1872 GNUNET_FS_end_top (dc->h, dc->top);
1873 while (NULL != dc->child_head)
1874 GNUNET_FS_download_signal_suspend_ (dc->child_head);
1875 if (dc->search != NULL)
1877 dc->search->download = NULL;
1880 if (dc->job_queue != NULL)
1882 GNUNET_FS_dequeue_ (dc->job_queue);
1883 dc->job_queue = NULL;
1885 if (dc->parent != NULL)
1886 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1887 dc->parent->child_tail,
1889 pi.status = GNUNET_FS_STATUS_DOWNLOAD_SUSPEND;
1890 GNUNET_FS_download_make_status_ (&pi, dc);
1891 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1892 GNUNET_SCHEDULER_cancel (dc->task);
1893 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1896 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1897 GNUNET_free_non_null (dc->filename);
1898 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1899 GNUNET_FS_uri_destroy (dc->uri);
1900 GNUNET_free_non_null (dc->temp_filename);
1901 GNUNET_free_non_null (dc->serialization);
1907 * Download parts of a file. Note that this will store
1908 * the blocks at the respective offset in the given file. Also, the
1909 * download is still using the blocking of the underlying FS
1910 * encoding. As a result, the download may *write* outside of the
1911 * given boundaries (if offset and length do not match the 32k FS
1912 * block boundaries). <p>
1914 * This function should be used to focus a download towards a
1915 * particular portion of the file (optimization), not to strictly
1916 * limit the download to exactly those bytes.
1918 * @param h handle to the file sharing subsystem
1919 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1920 * @param meta known metadata for the file (can be NULL)
1921 * @param filename where to store the file, maybe NULL (then no file is
1922 * created on disk and data must be grabbed from the callbacks)
1923 * @param tempname where to store temporary file data, not used if filename is non-NULL;
1924 * can be NULL (in which case we will pick a name if needed); the temporary file
1925 * may already exist, in which case we will try to use the data that is there and
1926 * if it is not what is desired, will overwrite it
1927 * @param offset at what offset should we start the download (typically 0)
1928 * @param length how many bytes should be downloaded starting at offset
1929 * @param anonymity anonymity level to use for the download
1930 * @param options various options
1931 * @param cctx initial value for the client context for this download
1932 * @param parent parent download to associate this download with (use NULL
1933 * for top-level downloads; useful for manually-triggered recursive downloads)
1934 * @return context that can be used to control this download
1936 struct GNUNET_FS_DownloadContext *
1937 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1938 const struct GNUNET_FS_Uri *uri,
1939 const struct GNUNET_CONTAINER_MetaData *meta,
1940 const char *filename,
1941 const char *tempname,
1945 enum GNUNET_FS_DownloadOptions options,
1947 struct GNUNET_FS_DownloadContext *parent)
1949 struct GNUNET_FS_ProgressInfo pi;
1950 struct GNUNET_FS_DownloadContext *dc;
1952 GNUNET_assert (GNUNET_FS_uri_test_chk (uri) ||
1953 GNUNET_FS_uri_test_loc (uri) );
1955 if ( (offset + length < offset) ||
1956 (offset + length > GNUNET_FS_uri_chk_get_file_size (uri)) )
1962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1963 "Starting download `%s' of %llu bytes\n",
1965 (unsigned long long) length);
1967 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1969 dc->parent = parent;
1972 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1976 dc->uri = GNUNET_FS_uri_dup (uri);
1977 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1978 dc->client_info = cctx;
1979 dc->start_time = GNUNET_TIME_absolute_get ();
1980 if (NULL != filename)
1982 dc->filename = GNUNET_strdup (filename);
1983 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1984 GNUNET_DISK_file_size (filename,
1988 if (GNUNET_FS_uri_test_loc (dc->uri))
1989 GNUNET_assert (GNUNET_OK ==
1990 GNUNET_FS_uri_loc_get_peer_identity (dc->uri,
1992 dc->offset = offset;
1993 dc->length = length;
1994 dc->anonymity = anonymity;
1995 dc->options = options;
1996 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1997 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size(dc->uri));
1998 if ( (filename == NULL) &&
1999 (is_recursive_download (dc) ) )
2001 if (tempname != NULL)
2002 dc->temp_filename = GNUNET_strdup (tempname);
2004 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2009 "Download tree has depth %u\n",
2014 dc->top = GNUNET_FS_make_top (dc->h,
2015 &GNUNET_FS_download_signal_suspend_,
2018 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
2019 pi.value.download.specifics.start.meta = meta;
2020 GNUNET_FS_download_make_status_ (&pi, dc);
2021 dc->start_task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2022 GNUNET_FS_download_sync_ (dc);
2023 GNUNET_FS_download_start_downloading_ (dc);
2029 * Download parts of a file based on a search result. The download
2030 * will be associated with the search result (and the association
2031 * will be preserved when serializing/deserializing the state).
2032 * If the search is stopped, the download will not be aborted but
2033 * be 'promoted' to a stand-alone download.
2035 * As with the other download function, this will store
2036 * the blocks at the respective offset in the given file. Also, the
2037 * download is still using the blocking of the underlying FS
2038 * encoding. As a result, the download may *write* outside of the
2039 * given boundaries (if offset and length do not match the 32k FS
2040 * block boundaries). <p>
2042 * The given range can be used to focus a download towards a
2043 * particular portion of the file (optimization), not to strictly
2044 * limit the download to exactly those bytes.
2046 * @param h handle to the file sharing subsystem
2047 * @param sr the search result to use for the download (determines uri and
2048 * meta data and associations)
2049 * @param filename where to store the file, maybe NULL (then no file is
2050 * created on disk and data must be grabbed from the callbacks)
2051 * @param tempname where to store temporary file data, not used if filename is non-NULL;
2052 * can be NULL (in which case we will pick a name if needed); the temporary file
2053 * may already exist, in which case we will try to use the data that is there and
2054 * if it is not what is desired, will overwrite it
2055 * @param offset at what offset should we start the download (typically 0)
2056 * @param length how many bytes should be downloaded starting at offset
2057 * @param anonymity anonymity level to use for the download
2058 * @param options various download options
2059 * @param cctx initial value for the client context for this download
2060 * @return context that can be used to control this download
2062 struct GNUNET_FS_DownloadContext *
2063 GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h,
2064 struct GNUNET_FS_SearchResult *sr,
2065 const char *filename,
2066 const char *tempname,
2070 enum GNUNET_FS_DownloadOptions options,
2073 struct GNUNET_FS_ProgressInfo pi;
2074 struct GNUNET_FS_DownloadContext *dc;
2076 if ( (sr == NULL) ||
2077 (sr->download != NULL) )
2082 GNUNET_assert (GNUNET_FS_uri_test_chk (sr->uri) ||
2083 GNUNET_FS_uri_test_loc (sr->uri) );
2084 if ( (offset + length < offset) ||
2085 (offset + length > sr->uri->data.chk.file_length) )
2091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2092 "Starting download `%s' of %llu bytes\n",
2094 (unsigned long long) length);
2096 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
2100 if (sr->probe_ctx != NULL)
2102 GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
2103 sr->probe_ctx = NULL;
2105 dc->uri = GNUNET_FS_uri_dup (sr->uri);
2106 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (sr->meta);
2107 dc->client_info = cctx;
2108 dc->start_time = GNUNET_TIME_absolute_get ();
2109 if (NULL != filename)
2111 dc->filename = GNUNET_strdup (filename);
2112 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
2113 GNUNET_DISK_file_size (filename,
2117 if (GNUNET_FS_uri_test_loc (dc->uri))
2118 GNUNET_assert (GNUNET_OK ==
2119 GNUNET_FS_uri_loc_get_peer_identity (dc->uri,
2121 dc->offset = offset;
2122 dc->length = length;
2123 dc->anonymity = anonymity;
2124 dc->options = options;
2125 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
2126 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
2127 if ( (filename == NULL) &&
2128 (is_recursive_download (dc) ) )
2130 if (tempname != NULL)
2131 dc->temp_filename = GNUNET_strdup (tempname);
2133 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2138 "Download tree has depth %u\n",
2141 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
2142 pi.value.download.specifics.start.meta = dc->meta;
2143 GNUNET_FS_download_make_status_ (&pi, dc);
2144 dc->start_task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2145 GNUNET_FS_download_sync_ (dc);
2146 GNUNET_FS_download_start_downloading_ (dc);
2151 * Start the downloading process (by entering the queue).
2153 * @param dc our download context
2156 GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc)
2158 if (dc->completed == dc->length)
2160 GNUNET_assert (dc->job_queue == NULL);
2161 dc->job_queue = GNUNET_FS_queue_ (dc->h,
2162 &activate_fs_download,
2163 &deactivate_fs_download,
2165 (dc->length + DBLOCK_SIZE-1) / DBLOCK_SIZE);
2170 * Stop a download (aborts if download is incomplete).
2172 * @param dc handle for the download
2173 * @param do_delete delete files of incomplete downloads
2176 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
2179 struct GNUNET_FS_ProgressInfo pi;
2182 if (dc->top != NULL)
2183 GNUNET_FS_end_top (dc->h, dc->top);
2184 if (dc->start_task != GNUNET_SCHEDULER_NO_TASK)
2186 GNUNET_SCHEDULER_cancel (dc->start_task);
2187 dc->start_task = GNUNET_SCHEDULER_NO_TASK;
2189 if (dc->search != NULL)
2191 dc->search->download = NULL;
2194 if (dc->job_queue != NULL)
2196 GNUNET_FS_dequeue_ (dc->job_queue);
2197 dc->job_queue = NULL;
2199 have_children = (NULL != dc->child_head) ? GNUNET_YES : GNUNET_NO;
2200 while (NULL != dc->child_head)
2201 GNUNET_FS_download_stop (dc->child_head,
2203 if (dc->parent != NULL)
2204 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
2205 dc->parent->child_tail,
2207 if (dc->serialization != NULL)
2208 GNUNET_FS_remove_sync_file_ (dc->h,
2209 ( (dc->parent != NULL) || (dc->search != NULL) )
2210 ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD
2211 : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD ,
2213 if ( (GNUNET_YES == have_children) &&
2214 (dc->parent == NULL) )
2215 GNUNET_FS_remove_sync_dir_ (dc->h,
2216 (dc->search != NULL)
2217 ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD
2218 : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2220 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
2221 GNUNET_FS_download_make_status_ (&pi, dc);
2222 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
2223 GNUNET_SCHEDULER_cancel (dc->task);
2224 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
2227 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2228 if (dc->filename != NULL)
2230 if ( (dc->completed != dc->length) &&
2231 (GNUNET_YES == do_delete) )
2233 if (0 != UNLINK (dc->filename))
2234 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
2238 GNUNET_free (dc->filename);
2240 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2241 GNUNET_FS_uri_destroy (dc->uri);
2242 if (NULL != dc->temp_filename)
2244 if (0 != UNLINK (dc->temp_filename))
2245 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2248 GNUNET_free (dc->temp_filename);
2250 GNUNET_free_non_null (dc->serialization);
2254 /* end of fs_download.c */