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 * Closure for iterator processing results.
180 struct ProcessResultClosure
186 GNUNET_HashCode query;
189 * Data found in P2P network.
194 * Our download context.
196 struct GNUNET_FS_DownloadContext *dc;
199 * Number of bytes in data.
209 * Flag to indicate if this block should be stored on disk.
217 * Iterator over entries in the pending requests in the 'active' map for the
218 * reply that we just got.
220 * @param cls closure (our 'struct ProcessResultClosure')
221 * @param key query for the given value / request
222 * @param value value in the hash map (a 'struct DownloadRequest')
223 * @return GNUNET_YES (we should continue to iterate); unless serious error
226 process_result_with_request (void *cls,
227 const GNUNET_HashCode * key,
233 * Schedule the download of the specified block in the tree.
235 * @param dc overall download this block belongs to
236 * @param chk content-hash-key of the block
237 * @param offset offset of the block in the file
238 * (for IBlocks, the offset is the lowest
239 * offset of any DBlock in the subtree under
241 * @param depth depth of the block, 0 is the root of the tree
244 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
245 const struct ContentHashKey *chk,
249 struct DownloadRequest *sm;
253 char block[DBLOCK_SIZE];
255 struct ProcessResultClosure prc;
258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
259 "Scheduling download at offset %llu and depth %u for `%s'\n",
260 (unsigned long long) offset,
262 GNUNET_h2s (&chk->query));
264 total = GNUNET_ntohll (dc->uri->data.chk.file_length);
265 off = compute_disk_offset (total,
269 len = GNUNET_FS_tree_calculate_block_size (total,
273 sm = GNUNET_malloc (sizeof (struct DownloadRequest));
277 sm->is_pending = GNUNET_YES;
278 sm->next = dc->pending;
280 GNUNET_CONTAINER_multihashmap_put (dc->active,
283 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
285 if ( (dc->old_file_size > off) &&
286 (dc->handle != NULL) &&
288 GNUNET_DISK_file_seek (dc->handle,
290 GNUNET_DISK_SEEK_SET) ) &&
292 GNUNET_DISK_file_read (dc->handle,
296 /* FIXME: also check query matches!? */
297 if (0 == memcmp (&key,
299 sizeof (GNUNET_HashCode)))
302 struct GNUNET_CRYPTO_AesSessionKey sk;
303 struct GNUNET_CRYPTO_AesInitializationVector iv;
304 GNUNET_HashCode query;
306 GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
307 GNUNET_CRYPTO_aes_encrypt (block, len,
311 GNUNET_CRYPTO_hash (enc, len, &query);
312 if (0 == memcmp (&query,
314 sizeof (GNUNET_HashCode)))
316 /* already got it! */
320 prc.type = (dc->treedepth == depth)
321 ? GNUNET_DATASTORE_BLOCKTYPE_DBLOCK
322 : GNUNET_DATASTORE_BLOCKTYPE_IBLOCK;
323 prc.query = chk->query;
324 prc.do_store = GNUNET_NO; /* useless */
325 process_result_with_request (&prc,
336 if (depth < dc->treedepth)
338 // FIXME: try if we could
339 // reconstitute this IBLOCK
340 // from the existing blocks on disk (can wait)
341 // (read block(s), encode, compare with
342 // query; if matches, simply return)
345 if ( (dc->th == NULL) &&
346 (dc->client != NULL) )
347 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
348 sizeof (struct SearchMessage),
349 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
351 &transmit_download_request,
358 * Suggest a filename based on given metadata.
360 * @param md given meta data
361 * @return NULL if meta data is useless for suggesting a filename
364 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
366 static const char *mimeMap[][2] = {
367 {"application/bz2", ".bz2"},
368 {"application/gnunet-directory", ".gnd"},
369 {"application/java", ".class"},
370 {"application/msword", ".doc"},
371 {"application/ogg", ".ogg"},
372 {"application/pdf", ".pdf"},
373 {"application/pgp-keys", ".key"},
374 {"application/pgp-signature", ".pgp"},
375 {"application/postscript", ".ps"},
376 {"application/rar", ".rar"},
377 {"application/rtf", ".rtf"},
378 {"application/xml", ".xml"},
379 {"application/x-debian-package", ".deb"},
380 {"application/x-dvi", ".dvi"},
381 {"applixation/x-flac", ".flac"},
382 {"applixation/x-gzip", ".gz"},
383 {"application/x-java-archive", ".jar"},
384 {"application/x-java-vm", ".class"},
385 {"application/x-python-code", ".pyc"},
386 {"application/x-redhat-package-manager", ".rpm"},
387 {"application/x-rpm", ".rpm"},
388 {"application/x-tar", ".tar"},
389 {"application/x-tex-pk", ".pk"},
390 {"application/x-texinfo", ".texinfo"},
391 {"application/x-xcf", ".xcf"},
392 {"application/x-xfig", ".xfig"},
393 {"application/zip", ".zip"},
395 {"audio/midi", ".midi"},
396 {"audio/mpeg", ".mp3"},
397 {"audio/real", ".rm"},
398 {"audio/x-wav", ".wav"},
400 {"image/gif", ".gif"},
401 {"image/jpeg", ".jpg"},
402 {"image/pcx", ".pcx"},
403 {"image/png", ".png"},
404 {"image/tiff", ".tiff"},
405 {"image/x-ms-bmp", ".bmp"},
406 {"image/x-xpixmap", ".xpm"},
408 {"text/css", ".css"},
409 {"text/html", ".html"},
410 {"text/plain", ".txt"},
411 {"text/rtf", ".rtf"},
412 {"text/x-c++hdr", ".h++"},
413 {"text/x-c++src", ".c++"},
414 {"text/x-chdr", ".h"},
415 {"text/x-csrc", ".c"},
416 {"text/x-java", ".java"},
417 {"text/x-moc", ".moc"},
418 {"text/x-pascal", ".pas"},
419 {"text/x-perl", ".pl"},
420 {"text/x-python", ".py"},
421 {"text/x-tex", ".tex"},
423 {"video/avi", ".avi"},
424 {"video/mpeg", ".mpeg"},
425 {"video/quicktime", ".qt"},
426 {"video/real", ".rm"},
427 {"video/x-msvideo", ".avi"},
436 ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
437 EXTRACTOR_METATYPE_FILENAME);
441 mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
442 EXTRACTOR_METATYPE_MIMETYPE);
446 while ( (mimeMap[i][0] != NULL) &&
447 (0 != strcmp (mime, mimeMap[i][0])))
449 if (mimeMap[i][1] == NULL)
450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
451 GNUNET_ERROR_TYPE_BULK,
452 _("Did not find mime type `%s' in extension list.\n"),
458 base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
459 EXTRACTOR_METATYPE_TITLE,
460 EXTRACTOR_METATYPE_BOOK_TITLE,
461 EXTRACTOR_METATYPE_ORIGINAL_TITLE,
462 EXTRACTOR_METATYPE_PACKAGE_NAME,
463 EXTRACTOR_METATYPE_URL,
464 EXTRACTOR_METATYPE_URI,
465 EXTRACTOR_METATYPE_DESCRIPTION,
466 EXTRACTOR_METATYPE_ISRC,
467 EXTRACTOR_METATYPE_JOURNAL_NAME,
468 EXTRACTOR_METATYPE_AUTHOR_NAME,
469 EXTRACTOR_METATYPE_SUBJECT,
470 EXTRACTOR_METATYPE_ALBUM,
471 EXTRACTOR_METATYPE_ARTIST,
472 EXTRACTOR_METATYPE_KEYWORDS,
473 EXTRACTOR_METATYPE_COMMENT,
474 EXTRACTOR_METATYPE_UNKNOWN,
476 if ( (base == NULL) &&
480 return GNUNET_strdup (ext);
483 GNUNET_asprintf (&ret,
493 * We've lost our connection with the FS service.
494 * Re-establish it and re-transmit all of our
497 * @param dc download context that is having trouble
500 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
504 * We found an entry in a directory. Check if the respective child
505 * already exists and if not create the respective child download.
507 * @param cls the parent download
508 * @param filename name of the file in the directory
509 * @param uri URI of the file (CHK or LOC)
510 * @param meta meta data of the file
511 * @param length number of bytes in data
512 * @param data contents of the file (or NULL if they were not inlined)
515 trigger_recursive_download (void *cls,
516 const char *filename,
517 const struct GNUNET_FS_Uri *uri,
518 const struct GNUNET_CONTAINER_MetaData *meta,
522 struct GNUNET_FS_DownloadContext *dc = cls;
523 struct GNUNET_FS_DownloadContext *cpos;
524 struct GNUNET_DISK_FileHandle *fh;
532 return; /* entry for the directory itself */
533 cpos = dc->child_head;
536 if ( (GNUNET_FS_uri_test_equal (uri,
538 ( (filename != NULL) &&
539 (0 == strcmp (cpos->filename,
545 return; /* already exists */
547 if (NULL == filename)
549 fn = GNUNET_FS_meta_data_suggest_filename (meta);
552 us = GNUNET_FS_uri_to_string (uri);
553 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
554 GNUNET_FS_URI_CHK_INFIX)]);
557 else if (fn[0] == '.')
560 us = GNUNET_FS_uri_to_string (uri);
561 GNUNET_asprintf (&fn,
563 &us[strlen (GNUNET_FS_URI_PREFIX
564 GNUNET_FS_URI_CHK_INFIX)], ext);
570 if (dc->filename == NULL)
576 dn = GNUNET_strdup (dc->filename);
577 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
579 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
580 GNUNET_FS_DIRECTORY_EXT)) );
581 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
583 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
584 GNUNET_FS_DIRECTORY_EXT)) )
585 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
586 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
587 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
589 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
590 GNUNET_FS_DIRECTORY_EXT)) ) )
592 GNUNET_asprintf (&full_name,
597 GNUNET_FS_DIRECTORY_EXT);
601 GNUNET_asprintf (&full_name,
609 if ( (full_name != NULL) &&
611 GNUNET_DISK_directory_create_for_file (full_name)) )
613 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
614 _("Failed to create directory for recursive download of `%s'\n"),
616 GNUNET_free (full_name);
617 GNUNET_free_non_null (fn);
623 if (full_name != NULL)
625 fh = GNUNET_DISK_file_open (full_name,
626 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
627 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
630 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
633 GNUNET_free (full_name);
634 GNUNET_free_non_null (fn);
638 GNUNET_DISK_file_write (fh,
642 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
646 GNUNET_DISK_file_close (fh);
650 /* FIXME: generate 'progress' events and move to
651 instant completion! */
652 GNUNET_break (0); // FIXME: not implemented
655 GNUNET_FS_download_start (dc->h,
660 GNUNET_FS_uri_chk_get_file_size (uri),
665 GNUNET_free_non_null (full_name);
666 GNUNET_free_non_null (fn);
671 * We're done downloading a directory. Open the file and
672 * trigger all of the (remaining) child downloads.
674 * @param dc context of download that just completed
677 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
682 struct GNUNET_DISK_FileHandle *h;
683 struct GNUNET_DISK_MapHandle *m;
685 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
686 size = (size_t) size64;
687 if (size64 != (uint64_t) size)
689 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
690 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
693 if (dc->filename != NULL)
695 h = GNUNET_DISK_file_open (dc->filename,
696 GNUNET_DISK_OPEN_READ,
697 GNUNET_DISK_PERM_NONE);
701 /* FIXME: need to initialize (and use) temp_filename
702 in various places in order for this assertion to
703 not fail; right now, it will always fail! */
704 GNUNET_assert (dc->temp_filename != NULL);
705 h = GNUNET_DISK_file_open (dc->temp_filename,
706 GNUNET_DISK_OPEN_READ,
707 GNUNET_DISK_PERM_NONE);
711 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
714 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
715 _("Directory too large for system address space\n"));
719 GNUNET_FS_directory_list_contents (size,
722 &trigger_recursive_download,
724 GNUNET_DISK_file_unmap (m);
726 GNUNET_DISK_file_close (h);
727 if (dc->filename == NULL)
729 if (0 != UNLINK (dc->temp_filename))
730 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
733 GNUNET_free (dc->temp_filename);
734 dc->temp_filename = NULL;
740 * Check if all child-downloads have completed and
741 * if so, signal completion (and possibly recurse to
745 check_completed (struct GNUNET_FS_DownloadContext *dc)
747 struct GNUNET_FS_ProgressInfo pi;
748 struct GNUNET_FS_DownloadContext *pos;
750 pos = dc->child_head;
753 if ( (pos->emsg == NULL) &&
754 (pos->completed < pos->length) )
755 return; /* not done yet */
756 if ( (pos->child_head != NULL) &&
757 (pos->has_finished != GNUNET_YES) )
758 return; /* not transitively done yet */
761 dc->has_finished = GNUNET_YES;
762 /* signal completion */
763 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
764 make_download_status (&pi, dc);
765 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
767 if (dc->parent != NULL)
768 check_completed (dc->parent);
773 * Iterator over entries in the pending requests in the 'active' map for the
774 * reply that we just got.
776 * @param cls closure (our 'struct ProcessResultClosure')
777 * @param key query for the given value / request
778 * @param value value in the hash map (a 'struct DownloadRequest')
779 * @return GNUNET_YES (we should continue to iterate); unless serious error
782 process_result_with_request (void *cls,
783 const GNUNET_HashCode * key,
786 struct ProcessResultClosure *prc = cls;
787 struct DownloadRequest *sm = value;
788 struct GNUNET_FS_DownloadContext *dc = prc->dc;
789 struct GNUNET_CRYPTO_AesSessionKey skey;
790 struct GNUNET_CRYPTO_AesInitializationVector iv;
792 struct GNUNET_FS_ProgressInfo pi;
797 struct ContentHashKey *chk;
800 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
808 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
812 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
814 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
815 make_download_status (&pi, dc);
816 pi.value.download.specifics.error.message = dc->emsg;
817 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
819 /* abort all pending requests */
822 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
825 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
829 GNUNET_assert (GNUNET_YES ==
830 GNUNET_CONTAINER_multihashmap_remove (dc->active,
833 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
834 GNUNET_CRYPTO_aes_decrypt (prc->data,
839 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
844 if ( ( GNUNET_YES == prc->do_store) &&
845 (NULL != dc->handle) &&
846 ( (sm->depth == dc->treedepth) ||
847 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852 "Saving decrypted block to disk at offset %llu\n",
853 (unsigned long long) off);
856 GNUNET_DISK_file_seek (dc->handle,
858 GNUNET_DISK_SEEK_SET) ) )
859 GNUNET_asprintf (&emsg,
860 _("Failed to seek to offset %llu in file `%s': %s\n"),
861 (unsigned long long) off,
864 else if (prc->size !=
865 GNUNET_DISK_file_write (dc->handle,
868 GNUNET_asprintf (&emsg,
869 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
870 (unsigned int) prc->size,
871 (unsigned long long) off,
877 // FIXME: make persistent
880 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
881 make_download_status (&pi, dc);
882 pi.value.download.specifics.error.message = emsg;
883 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
886 /* abort all pending requests */
889 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
892 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
898 if (sm->depth == dc->treedepth)
901 if (sm->offset < dc->offset)
903 /* starting offset begins in the middle of pt,
904 do not count first bytes as progress */
905 GNUNET_assert (app > (dc->offset - sm->offset));
906 app -= (dc->offset - sm->offset);
908 if (sm->offset + prc->size > dc->offset + dc->length)
910 /* end of block is after relevant range,
911 do not count last bytes as progress */
912 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
913 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
915 dc->completed += app;
917 /* do recursive download if option is set and either meta data
918 says it is a directory or if no meta data is given AND filename
919 ends in '.gnd' (top-level case) */
920 if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
921 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
922 ( (dc->meta == NULL) &&
923 ( (NULL == dc->filename) ||
924 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
926 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
927 GNUNET_FS_DIRECTORY_EXT)) ) ) ) ) )
928 GNUNET_FS_directory_list_contents (prc->size,
931 &trigger_recursive_download,
935 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
936 make_download_status (&pi, dc);
937 pi.value.download.specifics.progress.data = pt;
938 pi.value.download.specifics.progress.offset = sm->offset;
939 pi.value.download.specifics.progress.data_len = prc->size;
940 pi.value.download.specifics.progress.depth = sm->depth;
941 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
943 GNUNET_assert (dc->completed <= dc->length);
944 if (dc->completed == dc->length)
947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
948 "Download completed, truncating file to desired length %llu\n",
949 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
951 /* truncate file to size (since we store IBlocks at the end) */
952 if (dc->handle != NULL)
954 GNUNET_DISK_file_close (dc->handle);
956 if (0 != truncate (dc->filename,
957 GNUNET_ntohll (dc->uri->data.chk.file_length)))
958 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
963 if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
964 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
965 ( (dc->meta == NULL) &&
966 ( (NULL == dc->filename) ||
967 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
969 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
970 GNUNET_FS_DIRECTORY_EXT)) ) ) ) ) )
971 full_recursive_download (dc);
972 if (dc->child_head == NULL)
974 /* signal completion */
975 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
976 make_download_status (&pi, dc);
977 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
979 if (dc->parent != NULL)
980 check_completed (dc->parent);
982 GNUNET_assert (sm->depth == dc->treedepth);
984 // FIXME: make persistent
985 if (sm->depth == dc->treedepth)
991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
992 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
994 (unsigned long long) sm->offset);
996 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
997 chk = (struct ContentHashKey*) pt;
998 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1000 off = compute_dblock_offset (sm->offset,
1004 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1005 (off < dc->offset + dc->length) )
1006 schedule_block_download (dc,
1017 * Process a download result.
1019 * @param dc our download context
1020 * @param type type of the result
1021 * @param data the (encrypted) response
1022 * @param size size of data
1025 process_result (struct GNUNET_FS_DownloadContext *dc,
1030 struct ProcessResultClosure prc;
1036 prc.do_store = GNUNET_YES;
1037 GNUNET_CRYPTO_hash (data, size, &prc.query);
1039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1040 "Received result for query `%s' from `%s'-service\n",
1041 GNUNET_h2s (&prc.query),
1044 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1046 &process_result_with_request,
1052 * Type of a function to call when we receive a message
1055 * @param cls closure
1056 * @param msg message received, NULL on timeout or fatal error
1059 receive_results (void *cls,
1060 const struct GNUNET_MessageHeader * msg)
1062 struct GNUNET_FS_DownloadContext *dc = cls;
1063 const struct PutMessage *cm;
1066 if ( (NULL == msg) ||
1067 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1068 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1070 GNUNET_break (msg == NULL);
1074 msize = ntohs(msg->size);
1075 cm = (const struct PutMessage*) msg;
1079 msize - sizeof (struct PutMessage));
1080 if (dc->client == NULL)
1081 return; /* fatal error */
1082 /* continue receiving */
1083 GNUNET_CLIENT_receive (dc->client,
1086 GNUNET_TIME_UNIT_FOREVER_REL);
1092 * We're ready to transmit a search request to the
1093 * file-sharing service. Do it. If there is
1094 * more than one request pending, try to send
1095 * multiple or request another transmission.
1097 * @param cls closure
1098 * @param size number of bytes available in buf
1099 * @param buf where the callee should write the message
1100 * @return number of bytes written to buf
1103 transmit_download_request (void *cls,
1107 struct GNUNET_FS_DownloadContext *dc = cls;
1109 struct SearchMessage *sm;
1117 GNUNET_assert (size >= sizeof (struct SearchMessage));
1120 while ( (dc->pending != NULL) &&
1121 (size > msize + sizeof (struct SearchMessage)) )
1124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1125 "Transmitting download request for `%s' to `%s'-service\n",
1126 GNUNET_h2s (&dc->pending->chk.query),
1129 memset (sm, 0, sizeof (struct SearchMessage));
1130 sm->header.size = htons (sizeof (struct SearchMessage));
1131 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1132 if (dc->pending->depth == dc->treedepth)
1133 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
1135 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
1136 sm->anonymity_level = htonl (dc->anonymity);
1137 sm->target = dc->target.hashPubKey;
1138 sm->query = dc->pending->chk.query;
1139 dc->pending->is_pending = GNUNET_NO;
1140 dc->pending = dc->pending->next;
1141 msize += sizeof (struct SearchMessage);
1144 if (dc->pending != NULL)
1145 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1146 sizeof (struct SearchMessage),
1147 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1149 &transmit_download_request,
1156 * Reconnect to the FS service and transmit our queries NOW.
1158 * @param cls our download context
1162 do_reconnect (void *cls,
1163 const struct GNUNET_SCHEDULER_TaskContext *tc)
1165 struct GNUNET_FS_DownloadContext *dc = cls;
1166 struct GNUNET_CLIENT_Connection *client;
1168 dc->task = GNUNET_SCHEDULER_NO_TASK;
1169 client = GNUNET_CLIENT_connect (dc->h->sched,
1174 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1175 "Connecting to `%s'-service failed, will try again.\n",
1180 dc->client = client;
1181 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1182 sizeof (struct SearchMessage),
1183 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1185 &transmit_download_request,
1187 GNUNET_CLIENT_receive (client,
1190 GNUNET_TIME_UNIT_FOREVER_REL);
1195 * Add entries that are not yet pending back to the pending list.
1197 * @param cls our download context
1199 * @param entry entry of type "struct DownloadRequest"
1203 retry_entry (void *cls,
1204 const GNUNET_HashCode *key,
1207 struct GNUNET_FS_DownloadContext *dc = cls;
1208 struct DownloadRequest *dr = entry;
1210 if (! dr->is_pending)
1212 dr->next = dc->pending;
1213 dr->is_pending = GNUNET_YES;
1214 dc->pending = entry;
1221 * We've lost our connection with the FS service.
1222 * Re-establish it and re-transmit all of our
1225 * @param dc download context that is having trouble
1228 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1231 if (NULL != dc->client)
1235 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1238 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1241 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1245 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1246 GNUNET_TIME_UNIT_SECONDS,
1253 * Download parts of a file. Note that this will store
1254 * the blocks at the respective offset in the given file. Also, the
1255 * download is still using the blocking of the underlying FS
1256 * encoding. As a result, the download may *write* outside of the
1257 * given boundaries (if offset and length do not match the 32k FS
1258 * block boundaries). <p>
1260 * This function should be used to focus a download towards a
1261 * particular portion of the file (optimization), not to strictly
1262 * limit the download to exactly those bytes.
1264 * @param h handle to the file sharing subsystem
1265 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1266 * @param meta known metadata for the file (can be NULL)
1267 * @param filename where to store the file, maybe NULL (then no file is
1268 * created on disk and data must be grabbed from the callbacks)
1269 * @param offset at what offset should we start the download (typically 0)
1270 * @param length how many bytes should be downloaded starting at offset
1271 * @param anonymity anonymity level to use for the download
1272 * @param options various options
1273 * @param cctx initial value for the client context for this download
1274 * @param parent parent download to associate this download with (use NULL
1275 * for top-level downloads; useful for manually-triggered recursive downloads)
1276 * @return context that can be used to control this download
1278 struct GNUNET_FS_DownloadContext *
1279 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1280 const struct GNUNET_FS_Uri *uri,
1281 const struct GNUNET_CONTAINER_MetaData *meta,
1282 const char *filename,
1286 enum GNUNET_FS_DownloadOptions options,
1288 struct GNUNET_FS_DownloadContext *parent)
1290 struct GNUNET_FS_ProgressInfo pi;
1291 struct GNUNET_FS_DownloadContext *dc;
1292 struct GNUNET_CLIENT_Connection *client;
1294 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1295 if ( (offset + length < offset) ||
1296 (offset + length > uri->data.chk.file_length) )
1301 // FIXME: add support for "loc" URIs!
1303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1304 "Starting download `%s' of %llu bytes\n",
1306 (unsigned long long) length);
1308 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1310 dc->parent = parent;
1313 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1317 dc->uri = GNUNET_FS_uri_dup (uri);
1318 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1319 dc->client_info = cctx;
1320 dc->start_time = GNUNET_TIME_absolute_get ();
1321 if (NULL != filename)
1323 dc->filename = GNUNET_strdup (filename);
1324 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1325 GNUNET_DISK_file_size (filename,
1328 dc->handle = GNUNET_DISK_file_open (filename,
1329 GNUNET_DISK_OPEN_READWRITE |
1330 GNUNET_DISK_OPEN_CREATE,
1331 GNUNET_DISK_PERM_USER_READ |
1332 GNUNET_DISK_PERM_USER_WRITE |
1333 GNUNET_DISK_PERM_GROUP_READ |
1334 GNUNET_DISK_PERM_OTHER_READ);
1335 if (dc->handle == NULL)
1337 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1338 _("Download failed: could not open file `%s': %s\n"),
1341 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1342 GNUNET_FS_uri_destroy (dc->uri);
1343 GNUNET_free (dc->filename);
1348 // FIXME: set "dc->target" for LOC uris!
1349 dc->offset = offset;
1350 dc->length = length;
1351 dc->anonymity = anonymity;
1352 dc->options = options;
1353 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1354 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1357 "Download tree has depth %u\n",
1360 // FIXME: make persistent
1362 // FIXME: bound parallelism here!
1363 client = GNUNET_CLIENT_connect (h->sched,
1366 dc->client = client;
1367 schedule_block_download (dc,
1368 &dc->uri->data.chk.chk,
1370 1 /* 0 == CHK, 1 == top */);
1371 GNUNET_CLIENT_receive (client,
1374 GNUNET_TIME_UNIT_FOREVER_REL);
1375 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1376 make_download_status (&pi, dc);
1377 pi.value.download.specifics.start.meta = meta;
1378 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1386 * Free entries in the map.
1388 * @param cls unused (NULL)
1390 * @param entry entry of type "struct DownloadRequest" which is freed
1394 free_entry (void *cls,
1395 const GNUNET_HashCode *key,
1398 GNUNET_free (entry);
1404 * Stop a download (aborts if download is incomplete).
1406 * @param dc handle for the download
1407 * @param do_delete delete files of incomplete downloads
1410 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1413 struct GNUNET_FS_ProgressInfo pi;
1415 while (NULL != dc->child_head)
1416 GNUNET_FS_download_stop (dc->child_head,
1418 // FIXME: make unpersistent
1419 if (dc->parent != NULL)
1420 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1421 dc->parent->child_tail,
1424 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1425 make_download_status (&pi, dc);
1426 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1429 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1430 GNUNET_SCHEDULER_cancel (dc->h->sched,
1434 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1437 if (NULL != dc->client)
1438 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1439 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1442 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1443 if (dc->filename != NULL)
1445 if (NULL != dc->handle)
1446 GNUNET_DISK_file_close (dc->handle);
1447 if ( (dc->completed != dc->length) &&
1448 (GNUNET_YES == do_delete) )
1450 if (0 != UNLINK (dc->filename))
1451 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1455 GNUNET_free (dc->filename);
1457 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1458 GNUNET_FS_uri_destroy (dc->uri);
1462 /* end of fs_download.c */