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 2, 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 * - handle recursive downloads (need directory &
27 * fs-level download-parallelism management)
28 * - handle recursive downloads where directory file is
29 * NOT saved on disk (need temporary file instead then!)
30 * - location URI suppport (can wait, easy)
31 * - check if blocks exist already (can wait, easy)
32 * - check if iblocks can be computed from existing blocks (can wait, hard)
33 * - persistence (can wait)
36 #include "gnunet_constants.h"
37 #include "gnunet_fs_service.h"
41 #define DEBUG_DOWNLOAD GNUNET_NO
44 * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
45 * only have to truncate the file once we're done).
47 * Given the offset of a block (with respect to the DBLOCKS) and its
48 * depth, return the offset where we would store this block in the
51 * @param fsize overall file size
52 * @param off offset of the block in the file
53 * @param depth depth of the block in the tree
54 * @param treedepth maximum depth of the tree
55 * @return off for DBLOCKS (depth == treedepth),
56 * otherwise an offset past the end
57 * of the file that does not overlap
58 * with the range for any other block
61 compute_disk_offset (uint64_t fsize,
64 unsigned int treedepth)
67 uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
68 uint64_t loff; /* where do IBlocks for depth "i" start? */
69 unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
71 if (depth == treedepth)
73 /* first IBlocks start at the end of file, rounded up
74 to full DBLOCK_SIZE */
75 loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
76 lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
77 GNUNET_assert (0 == (off % DBLOCK_SIZE));
78 ioff = (off / DBLOCK_SIZE);
79 for (i=treedepth-1;i>depth;i--)
82 lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
83 GNUNET_assert (lsize > 0);
84 GNUNET_assert (0 == (ioff % CHK_PER_INODE));
85 ioff /= CHK_PER_INODE;
87 return loff + ioff * sizeof (struct ContentHashKey);
92 * Given a file of the specified treedepth and a block at the given
93 * offset and depth, calculate the offset for the CHK at the given
96 * @param offset the offset of the first
97 * DBLOCK in the subtree of the
99 * @param depth the depth of the IBLOCK in the tree
100 * @param treedepth overall depth of the tree
101 * @param k which CHK in the IBLOCK are we
103 * @return offset if k=0, otherwise an appropriately
104 * larger value (i.e., if depth = treedepth-1,
105 * the returned value should be offset+DBLOCK_SIZE)
108 compute_dblock_offset (uint64_t offset,
110 unsigned int treedepth,
114 uint64_t lsize; /* what is the size of the sum of all DBlocks
115 that a CHK at depth i corresponds to? */
117 if (depth == treedepth)
120 for (i=treedepth-1;i>depth;i--)
121 lsize *= CHK_PER_INODE;
122 return offset + k * lsize;
127 * Fill in all of the generic fields for
130 * @param pi structure to fill in
131 * @param dc overall download context
134 make_download_status (struct GNUNET_FS_ProgressInfo *pi,
135 struct GNUNET_FS_DownloadContext *dc)
137 pi->value.download.dc = dc;
138 pi->value.download.cctx
140 pi->value.download.pctx
141 = (dc->parent == NULL) ? NULL : dc->parent->client_info;
142 pi->value.download.uri
144 pi->value.download.filename
146 pi->value.download.size
148 pi->value.download.duration
149 = GNUNET_TIME_absolute_get_duration (dc->start_time);
150 pi->value.download.completed
152 pi->value.download.anonymity
154 pi->value.download.eta
155 = GNUNET_TIME_calculate_eta (dc->start_time,
161 * We're ready to transmit a search request to the
162 * file-sharing service. Do it. If there is
163 * more than one request pending, try to send
164 * multiple or request another transmission.
167 * @param size number of bytes available in buf
168 * @param buf where the callee should write the message
169 * @return number of bytes written to buf
172 transmit_download_request (void *cls,
178 * Schedule the download of the specified
181 * @param dc overall download this block belongs to
182 * @param chk content-hash-key of the block
183 * @param offset offset of the block in the file
184 * (for IBlocks, the offset is the lowest
185 * offset of any DBlock in the subtree under
187 * @param depth depth of the block, 0 is the root of the tree
190 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
191 const struct ContentHashKey *chk,
195 struct DownloadRequest *sm;
199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
200 "Scheduling download at offset %llu and depth %u for `%s'\n",
201 (unsigned long long) offset,
203 GNUNET_h2s (&chk->query));
205 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
209 if ( (dc->old_file_size > off) &&
210 (dc->handle != NULL) &&
212 GNUNET_DISK_file_seek (dc->handle,
214 GNUNET_DISK_SEEK_SET) ) )
216 // FIXME: check if block exists on disk!
217 // (read block, encode, compare with
218 // query; if matches, simply return)
220 if (depth < dc->treedepth)
222 // FIXME: try if we could
223 // reconstitute this IBLOCK
224 // from the existing blocks on disk (can wait)
225 // (read block(s), encode, compare with
226 // query; if matches, simply return)
228 sm = GNUNET_malloc (sizeof (struct DownloadRequest));
232 sm->is_pending = GNUNET_YES;
233 sm->next = dc->pending;
235 GNUNET_CONTAINER_multihashmap_put (dc->active,
238 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
240 if ( (dc->th == NULL) &&
241 (dc->client != NULL) )
242 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
243 sizeof (struct SearchMessage),
244 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
246 &transmit_download_request,
253 * Suggest a filename based on given metadata.
255 * @param md given meta data
256 * @return NULL if meta data is useless for suggesting a filename
259 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
261 static const char *mimeMap[][2] = {
262 {"application/bz2", ".bz2"},
263 {"application/gnunet-directory", ".gnd"},
264 {"application/java", ".class"},
265 {"application/msword", ".doc"},
266 {"application/ogg", ".ogg"},
267 {"application/pdf", ".pdf"},
268 {"application/pgp-keys", ".key"},
269 {"application/pgp-signature", ".pgp"},
270 {"application/postscript", ".ps"},
271 {"application/rar", ".rar"},
272 {"application/rtf", ".rtf"},
273 {"application/xml", ".xml"},
274 {"application/x-debian-package", ".deb"},
275 {"application/x-dvi", ".dvi"},
276 {"applixation/x-flac", ".flac"},
277 {"applixation/x-gzip", ".gz"},
278 {"application/x-java-archive", ".jar"},
279 {"application/x-java-vm", ".class"},
280 {"application/x-python-code", ".pyc"},
281 {"application/x-redhat-package-manager", ".rpm"},
282 {"application/x-rpm", ".rpm"},
283 {"application/x-tar", ".tar"},
284 {"application/x-tex-pk", ".pk"},
285 {"application/x-texinfo", ".texinfo"},
286 {"application/x-xcf", ".xcf"},
287 {"application/x-xfig", ".xfig"},
288 {"application/zip", ".zip"},
290 {"audio/midi", ".midi"},
291 {"audio/mpeg", ".mp3"},
292 {"audio/real", ".rm"},
293 {"audio/x-wav", ".wav"},
295 {"image/gif", ".gif"},
296 {"image/jpeg", ".jpg"},
297 {"image/pcx", ".pcx"},
298 {"image/png", ".png"},
299 {"image/tiff", ".tiff"},
300 {"image/x-ms-bmp", ".bmp"},
301 {"image/x-xpixmap", ".xpm"},
303 {"text/css", ".css"},
304 {"text/html", ".html"},
305 {"text/plain", ".txt"},
306 {"text/rtf", ".rtf"},
307 {"text/x-c++hdr", ".h++"},
308 {"text/x-c++src", ".c++"},
309 {"text/x-chdr", ".h"},
310 {"text/x-csrc", ".c"},
311 {"text/x-java", ".java"},
312 {"text/x-moc", ".moc"},
313 {"text/x-pascal", ".pas"},
314 {"text/x-perl", ".pl"},
315 {"text/x-python", ".py"},
316 {"text/x-tex", ".tex"},
318 {"video/avi", ".avi"},
319 {"video/mpeg", ".mpeg"},
320 {"video/quicktime", ".qt"},
321 {"video/real", ".rm"},
322 {"video/x-msvideo", ".avi"},
331 ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
332 EXTRACTOR_METATYPE_FILENAME);
336 mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
337 EXTRACTOR_METATYPE_MIMETYPE);
341 while ( (mimeMap[i][0] != NULL) &&
342 (0 != strcmp (mime, mimeMap[i][0])))
344 if (mimeMap[i][1] == NULL)
345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
346 GNUNET_ERROR_TYPE_BULK,
347 _("Did not find mime type `%s' in extension list.\n"),
353 base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
354 EXTRACTOR_METATYPE_TITLE,
355 EXTRACTOR_METATYPE_BOOK_TITLE,
356 EXTRACTOR_METATYPE_ORIGINAL_TITLE,
357 EXTRACTOR_METATYPE_PACKAGE_NAME,
358 EXTRACTOR_METATYPE_URL,
359 EXTRACTOR_METATYPE_URI,
360 EXTRACTOR_METATYPE_DESCRIPTION,
361 EXTRACTOR_METATYPE_ISRC,
362 EXTRACTOR_METATYPE_JOURNAL_NAME,
363 EXTRACTOR_METATYPE_AUTHOR_NAME,
364 EXTRACTOR_METATYPE_SUBJECT,
365 EXTRACTOR_METATYPE_ALBUM,
366 EXTRACTOR_METATYPE_ARTIST,
367 EXTRACTOR_METATYPE_KEYWORDS,
368 EXTRACTOR_METATYPE_COMMENT,
369 EXTRACTOR_METATYPE_UNKNOWN,
371 if ( (base == NULL) &&
375 return GNUNET_strdup (ext);
378 GNUNET_asprintf (&ret,
388 * We've lost our connection with the FS service.
389 * Re-establish it and re-transmit all of our
392 * @param dc download context that is having trouble
395 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
399 * Compute how many bytes of data should be stored in
400 * the specified node.
402 * @param fsize overall file size
403 * @param totaldepth depth of the entire tree
404 * @param offset offset of the node
405 * @param depth depth of the node
406 * @return number of bytes stored in this node
409 calculate_block_size (uint64_t fsize,
410 unsigned int totaldepth,
420 GNUNET_assert (offset < fsize);
421 if (depth == totaldepth)
424 if (offset + ret > fsize)
425 ret = (size_t) (fsize - offset);
430 for (i = totaldepth-1; i > depth; i--)
431 rsize *= CHK_PER_INODE;
432 epos = offset + rsize * CHK_PER_INODE;
433 GNUNET_assert (epos > offset);
436 /* round up when computing #CHKs in our IBlock */
437 chks = (epos - offset + rsize - 1) / rsize;
438 GNUNET_assert (chks <= CHK_PER_INODE);
439 return chks * sizeof (struct ContentHashKey);
444 * Closure for iterator processing results.
446 struct ProcessResultClosure
452 GNUNET_HashCode query;
455 * Data found in P2P network.
460 * Our download context.
462 struct GNUNET_FS_DownloadContext *dc;
465 * Number of bytes in data.
478 * We found an entry in a directory. Check if the respective child
479 * already exists and if not create the respective child download.
481 * @param cls the parent download
482 * @param filename name of the file in the directory
483 * @param uri URI of the file (CHK or LOC)
484 * @param meta meta data of the file
485 * @param length number of bytes in data
486 * @param data contents of the file (or NULL if they were not inlined)
489 trigger_recursive_download (void *cls,
490 const char *filename,
491 const struct GNUNET_FS_Uri *uri,
492 const struct GNUNET_CONTAINER_MetaData *meta,
496 struct GNUNET_FS_DownloadContext *dc = cls;
497 struct GNUNET_FS_DownloadContext *cpos;
498 struct GNUNET_DISK_FileHandle *fh;
506 return; /* entry for the directory itself */
507 cpos = dc->child_head;
510 if ( (GNUNET_FS_uri_test_equal (uri,
512 ( (filename != NULL) &&
513 (0 == strcmp (cpos->filename,
519 return; /* already exists */
521 if (NULL == filename)
523 fn = GNUNET_FS_meta_data_suggest_filename (meta);
526 us = GNUNET_FS_uri_to_string (uri);
527 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
528 GNUNET_FS_URI_CHK_INFIX)]);
531 else if (fn[0] == '.')
534 us = GNUNET_FS_uri_to_string (uri);
535 GNUNET_asprintf (&fn,
537 &us[strlen (GNUNET_FS_URI_PREFIX
538 GNUNET_FS_URI_CHK_INFIX)], ext);
544 if (dc->filename == NULL)
550 dn = GNUNET_strdup (dc->filename);
551 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
553 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
554 GNUNET_FS_DIRECTORY_EXT)) );
555 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
557 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
558 GNUNET_FS_DIRECTORY_EXT)) )
559 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
560 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
561 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
563 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
564 GNUNET_FS_DIRECTORY_EXT)) ) )
566 GNUNET_asprintf (&full_name,
571 GNUNET_FS_DIRECTORY_EXT);
575 GNUNET_asprintf (&full_name,
583 if ( (full_name != NULL) &&
585 GNUNET_DISK_directory_create_for_file (full_name)) )
587 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
588 _("Failed to create directory for recursive download of `%s'\n"),
590 GNUNET_free (full_name);
591 GNUNET_free_non_null (fn);
597 if (full_name != NULL)
599 fh = GNUNET_DISK_file_open (full_name,
600 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
601 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
604 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
607 GNUNET_free (full_name);
608 GNUNET_free_non_null (fn);
612 GNUNET_DISK_file_write (fh,
616 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
620 GNUNET_DISK_file_close (fh);
624 /* FIXME: generate 'progress' events and move to
625 instant completion! */
626 GNUNET_break (0); // FIXME: not implemented
629 GNUNET_FS_download_start (dc->h,
634 GNUNET_FS_uri_chk_get_file_size (uri),
639 GNUNET_free_non_null (full_name);
640 GNUNET_free_non_null (fn);
645 * We're done downloading a directory. Open the file and
646 * trigger all of the (remaining) child downloads.
648 * @param dc context of download that just completed
651 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
656 struct GNUNET_DISK_FileHandle *h;
657 struct GNUNET_DISK_MapHandle *m;
659 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
660 size = (size_t) size64;
661 if (size64 != (uint64_t) size)
663 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
664 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
667 if (dc->filename != NULL)
669 h = GNUNET_DISK_file_open (dc->filename,
670 GNUNET_DISK_OPEN_READ,
671 GNUNET_DISK_PERM_NONE);
675 /* FIXME: need to initialize (and use) temp_filename
676 in various places in order for this assertion to
677 not fail; right now, it will always fail! */
678 GNUNET_assert (dc->temp_filename != NULL);
679 h = GNUNET_DISK_file_open (dc->temp_filename,
680 GNUNET_DISK_OPEN_READ,
681 GNUNET_DISK_PERM_NONE);
685 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
688 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
689 _("Directory too large for system address space\n"));
693 GNUNET_FS_directory_list_contents (size,
696 &trigger_recursive_download,
698 GNUNET_DISK_file_unmap (m);
700 GNUNET_DISK_file_close (h);
701 if (dc->filename == NULL)
703 if (0 != UNLINK (dc->temp_filename))
704 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
707 GNUNET_free (dc->temp_filename);
708 dc->temp_filename = NULL;
714 * Iterator over entries in the pending requests in the 'active' map for the
715 * reply that we just got.
717 * @param cls closure (our 'struct ProcessResultClosure')
718 * @param key query for the given value / request
719 * @param value value in the hash map (a 'struct DownloadRequest')
720 * @return GNUNET_YES (we should continue to iterate); unless serious error
723 process_result_with_request (void *cls,
724 const GNUNET_HashCode * key,
727 struct ProcessResultClosure *prc = cls;
728 struct DownloadRequest *sm = value;
729 struct GNUNET_FS_DownloadContext *dc = prc->dc;
730 struct GNUNET_CRYPTO_AesSessionKey skey;
731 struct GNUNET_CRYPTO_AesInitializationVector iv;
733 struct GNUNET_FS_ProgressInfo pi;
737 struct ContentHashKey *chk;
740 if (prc->size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
747 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
748 calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
754 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
756 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
757 make_download_status (&pi, dc);
758 pi.value.download.specifics.error.message = dc->emsg;
759 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
761 /* abort all pending requests */
764 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
767 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
771 GNUNET_assert (GNUNET_YES ==
772 GNUNET_CONTAINER_multihashmap_remove (dc->active,
775 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
776 GNUNET_CRYPTO_aes_decrypt (prc->data,
781 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
786 if ( (NULL != dc->handle) &&
787 ( (sm->depth == dc->treedepth) ||
788 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
793 "Saving decrypted block to disk at offset %llu\n",
794 (unsigned long long) off);
797 GNUNET_DISK_file_seek (dc->handle,
799 GNUNET_DISK_SEEK_SET) ) )
800 GNUNET_asprintf (&emsg,
801 _("Failed to seek to offset %llu in file `%s': %s\n"),
802 (unsigned long long) off,
805 else if (prc->size !=
806 GNUNET_DISK_file_write (dc->handle,
809 GNUNET_asprintf (&emsg,
810 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
811 (unsigned int) prc->size,
812 (unsigned long long) off,
818 // FIXME: make persistent
821 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
822 make_download_status (&pi, dc);
823 pi.value.download.specifics.error.message = emsg;
824 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
827 /* abort all pending requests */
830 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
833 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
839 if (sm->depth == dc->treedepth)
842 if (sm->offset < dc->offset)
844 /* starting offset begins in the middle of pt,
845 do not count first bytes as progress */
846 GNUNET_assert (app > (dc->offset - sm->offset));
847 app -= (dc->offset - sm->offset);
849 if (sm->offset + prc->size > dc->offset + dc->length)
851 /* end of block is after relevant range,
852 do not count last bytes as progress */
853 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
854 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
856 dc->completed += app;
858 /* do recursive download if option is set and either meta data
859 says it is a directory or if no meta data is given AND filename
860 ends in '.gnd' (top-level case) */
861 if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
862 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
863 ( (dc->meta == NULL) &&
864 ( (NULL == dc->filename) ||
865 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
867 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
868 GNUNET_FS_DIRECTORY_EXT)) ) ) ) ) )
869 GNUNET_FS_directory_list_contents (prc->size,
872 &trigger_recursive_download,
877 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
878 make_download_status (&pi, dc);
879 pi.value.download.specifics.progress.data = pt;
880 pi.value.download.specifics.progress.offset = sm->offset;
881 pi.value.download.specifics.progress.data_len = prc->size;
882 pi.value.download.specifics.progress.depth = sm->depth;
883 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
885 GNUNET_assert (dc->completed <= dc->length);
886 if (dc->completed == dc->length)
889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890 "Download completed, truncating file to desired length %llu\n",
891 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
893 /* truncate file to size (since we store IBlocks at the end) */
894 if (dc->handle != NULL)
896 GNUNET_DISK_file_close (dc->handle);
898 if (0 != truncate (dc->filename,
899 GNUNET_ntohll (dc->uri->data.chk.file_length)))
900 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
905 if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
906 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
907 ( (dc->meta == NULL) &&
908 ( (NULL == dc->filename) ||
909 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
911 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
912 GNUNET_FS_DIRECTORY_EXT)) ) ) ) ) )
913 full_recursive_download (dc);
914 if (dc->child_head == NULL)
916 /* signal completion */
917 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
918 make_download_status (&pi, dc);
919 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
922 GNUNET_assert (sm->depth == dc->treedepth);
924 // FIXME: make persistent
925 if (sm->depth == dc->treedepth)
931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
932 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
934 (unsigned long long) sm->offset);
936 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
937 chk = (struct ContentHashKey*) pt;
938 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
940 off = compute_dblock_offset (sm->offset,
944 if ( (off + DBLOCK_SIZE >= dc->offset) &&
945 (off < dc->offset + dc->length) )
946 schedule_block_download (dc,
957 * Process a download result.
959 * @param dc our download context
960 * @param type type of the result
961 * @param data the (encrypted) response
962 * @param size size of data
965 process_result (struct GNUNET_FS_DownloadContext *dc,
970 struct ProcessResultClosure prc;
976 GNUNET_CRYPTO_hash (data, size, &prc.query);
978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979 "Received result for query `%s' from `%s'-service\n",
980 GNUNET_h2s (&prc.query),
983 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
985 &process_result_with_request,
991 * Type of a function to call when we receive a message
995 * @param msg message received, NULL on timeout or fatal error
998 receive_results (void *cls,
999 const struct GNUNET_MessageHeader * msg)
1001 struct GNUNET_FS_DownloadContext *dc = cls;
1002 const struct PutMessage *cm;
1005 if ( (NULL == msg) ||
1006 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1007 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1009 GNUNET_break (msg == NULL);
1013 msize = ntohs(msg->size);
1014 cm = (const struct PutMessage*) msg;
1018 msize - sizeof (struct PutMessage));
1019 if (dc->client == NULL)
1020 return; /* fatal error */
1021 /* continue receiving */
1022 GNUNET_CLIENT_receive (dc->client,
1025 GNUNET_TIME_UNIT_FOREVER_REL);
1031 * We're ready to transmit a search request to the
1032 * file-sharing service. Do it. If there is
1033 * more than one request pending, try to send
1034 * multiple or request another transmission.
1036 * @param cls closure
1037 * @param size number of bytes available in buf
1038 * @param buf where the callee should write the message
1039 * @return number of bytes written to buf
1042 transmit_download_request (void *cls,
1046 struct GNUNET_FS_DownloadContext *dc = cls;
1048 struct SearchMessage *sm;
1056 GNUNET_assert (size >= sizeof (struct SearchMessage));
1059 while ( (dc->pending != NULL) &&
1060 (size > msize + sizeof (struct SearchMessage)) )
1063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064 "Transmitting download request for `%s' to `%s'-service\n",
1065 GNUNET_h2s (&dc->pending->chk.query),
1068 memset (sm, 0, sizeof (struct SearchMessage));
1069 sm->header.size = htons (sizeof (struct SearchMessage));
1070 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1071 if (dc->pending->depth == dc->treedepth)
1072 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
1074 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
1075 sm->anonymity_level = htonl (dc->anonymity);
1076 sm->target = dc->target.hashPubKey;
1077 sm->query = dc->pending->chk.query;
1078 dc->pending->is_pending = GNUNET_NO;
1079 dc->pending = dc->pending->next;
1080 msize += sizeof (struct SearchMessage);
1083 if (dc->pending != NULL)
1084 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1085 sizeof (struct SearchMessage),
1086 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1088 &transmit_download_request,
1095 * Reconnect to the FS service and transmit our queries NOW.
1097 * @param cls our download context
1101 do_reconnect (void *cls,
1102 const struct GNUNET_SCHEDULER_TaskContext *tc)
1104 struct GNUNET_FS_DownloadContext *dc = cls;
1105 struct GNUNET_CLIENT_Connection *client;
1107 dc->task = GNUNET_SCHEDULER_NO_TASK;
1108 client = GNUNET_CLIENT_connect (dc->h->sched,
1113 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1114 "Connecting to `%s'-service failed, will try again.\n",
1119 dc->client = client;
1120 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1121 sizeof (struct SearchMessage),
1122 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1124 &transmit_download_request,
1126 GNUNET_CLIENT_receive (client,
1129 GNUNET_TIME_UNIT_FOREVER_REL);
1134 * Add entries that are not yet pending back to the pending list.
1136 * @param cls our download context
1138 * @param entry entry of type "struct DownloadRequest"
1142 retry_entry (void *cls,
1143 const GNUNET_HashCode *key,
1146 struct GNUNET_FS_DownloadContext *dc = cls;
1147 struct DownloadRequest *dr = entry;
1149 if (! dr->is_pending)
1151 dr->next = dc->pending;
1152 dr->is_pending = GNUNET_YES;
1153 dc->pending = entry;
1160 * We've lost our connection with the FS service.
1161 * Re-establish it and re-transmit all of our
1164 * @param dc download context that is having trouble
1167 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1170 if (NULL != dc->client)
1174 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1177 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1180 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1184 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1185 GNUNET_TIME_UNIT_SECONDS,
1192 * Download parts of a file. Note that this will store
1193 * the blocks at the respective offset in the given file. Also, the
1194 * download is still using the blocking of the underlying FS
1195 * encoding. As a result, the download may *write* outside of the
1196 * given boundaries (if offset and length do not match the 32k FS
1197 * block boundaries). <p>
1199 * This function should be used to focus a download towards a
1200 * particular portion of the file (optimization), not to strictly
1201 * limit the download to exactly those bytes.
1203 * @param h handle to the file sharing subsystem
1204 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1205 * @param meta known metadata for the file (can be NULL)
1206 * @param filename where to store the file, maybe NULL (then no file is
1207 * created on disk and data must be grabbed from the callbacks)
1208 * @param offset at what offset should we start the download (typically 0)
1209 * @param length how many bytes should be downloaded starting at offset
1210 * @param anonymity anonymity level to use for the download
1211 * @param options various options
1212 * @param cctx initial value for the client context for this download
1213 * @param parent parent download to associate this download with (use NULL
1214 * for top-level downloads; useful for manually-triggered recursive downloads)
1215 * @return context that can be used to control this download
1217 struct GNUNET_FS_DownloadContext *
1218 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1219 const struct GNUNET_FS_Uri *uri,
1220 const struct GNUNET_CONTAINER_MetaData *meta,
1221 const char *filename,
1225 enum GNUNET_FS_DownloadOptions options,
1227 struct GNUNET_FS_DownloadContext *parent)
1229 struct GNUNET_FS_ProgressInfo pi;
1230 struct GNUNET_FS_DownloadContext *dc;
1231 struct GNUNET_CLIENT_Connection *client;
1233 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1234 if ( (offset + length < offset) ||
1235 (offset + length > uri->data.chk.file_length) )
1240 // FIXME: add support for "loc" URIs!
1242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1243 "Starting download `%s' of %llu bytes\n",
1245 (unsigned long long) length);
1247 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1249 dc->parent = parent;
1252 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1256 dc->uri = GNUNET_FS_uri_dup (uri);
1257 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1258 dc->client_info = cctx;
1259 dc->start_time = GNUNET_TIME_absolute_get ();
1260 if (NULL != filename)
1262 dc->filename = GNUNET_strdup (filename);
1263 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1264 GNUNET_DISK_file_size (filename,
1267 dc->handle = GNUNET_DISK_file_open (filename,
1268 GNUNET_DISK_OPEN_READWRITE |
1269 GNUNET_DISK_OPEN_CREATE,
1270 GNUNET_DISK_PERM_USER_READ |
1271 GNUNET_DISK_PERM_USER_WRITE |
1272 GNUNET_DISK_PERM_GROUP_READ |
1273 GNUNET_DISK_PERM_OTHER_READ);
1274 if (dc->handle == NULL)
1276 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1277 _("Download failed: could not open file `%s': %s\n"),
1280 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1281 GNUNET_FS_uri_destroy (dc->uri);
1282 GNUNET_free (dc->filename);
1287 // FIXME: set "dc->target" for LOC uris!
1288 dc->offset = offset;
1289 dc->length = length;
1290 dc->anonymity = anonymity;
1291 dc->options = options;
1292 dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
1293 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1296 "Download tree has depth %u\n",
1299 // FIXME: make persistent
1301 // FIXME: bound parallelism here!
1302 client = GNUNET_CLIENT_connect (h->sched,
1305 dc->client = client;
1306 schedule_block_download (dc,
1307 &dc->uri->data.chk.chk,
1309 1 /* 0 == CHK, 1 == top */);
1310 GNUNET_CLIENT_receive (client,
1313 GNUNET_TIME_UNIT_FOREVER_REL);
1314 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1315 make_download_status (&pi, dc);
1316 pi.value.download.specifics.start.meta = meta;
1317 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1325 * Free entries in the map.
1327 * @param cls unused (NULL)
1329 * @param entry entry of type "struct DownloadRequest" which is freed
1333 free_entry (void *cls,
1334 const GNUNET_HashCode *key,
1337 GNUNET_free (entry);
1343 * Stop a download (aborts if download is incomplete).
1345 * @param dc handle for the download
1346 * @param do_delete delete files of incomplete downloads
1349 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1352 struct GNUNET_FS_ProgressInfo pi;
1354 while (NULL != dc->child_head)
1355 GNUNET_FS_download_stop (dc->child_head,
1357 // FIXME: make unpersistent
1358 if (dc->parent != NULL)
1359 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1360 dc->parent->child_tail,
1363 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1364 make_download_status (&pi, dc);
1365 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1368 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1369 GNUNET_SCHEDULER_cancel (dc->h->sched,
1373 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1376 if (NULL != dc->client)
1377 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1378 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1381 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1382 if (dc->filename != NULL)
1384 if (NULL != dc->handle)
1385 GNUNET_DISK_file_close (dc->handle);
1386 if ( (dc->completed != dc->length) &&
1387 (GNUNET_YES == do_delete) )
1389 if (0 != UNLINK (dc->filename))
1390 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1394 GNUNET_free (dc->filename);
1396 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1397 GNUNET_FS_uri_destroy (dc->uri);
1401 /* end of fs_download.c */