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 * - persistence (can wait)
27 * - location URI suppport (can wait, easy)
28 * - different priority for scheduling probe downloads?
29 * - check if iblocks can be computed from existing blocks (can wait, hard)
32 #include "gnunet_constants.h"
33 #include "gnunet_fs_service.h"
37 #define DEBUG_DOWNLOAD GNUNET_NO
40 * Determine if the given download (options and meta data) should cause
41 * use to try to do a recursive download.
44 is_recursive_download (struct GNUNET_FS_DownloadContext *dc)
46 return (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
47 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
48 ( (dc->meta == NULL) &&
49 ( (NULL == dc->filename) ||
50 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
52 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
53 GNUNET_FS_DIRECTORY_EXT)) ) ) ) );
58 * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
59 * only have to truncate the file once we're done).
61 * Given the offset of a block (with respect to the DBLOCKS) and its
62 * depth, return the offset where we would store this block in the
65 * @param fsize overall file size
66 * @param off offset of the block in the file
67 * @param depth depth of the block in the tree
68 * @param treedepth maximum depth of the tree
69 * @return off for DBLOCKS (depth == treedepth),
70 * otherwise an offset past the end
71 * of the file that does not overlap
72 * with the range for any other block
75 compute_disk_offset (uint64_t fsize,
78 unsigned int treedepth)
81 uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
82 uint64_t loff; /* where do IBlocks for depth "i" start? */
83 unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
85 if (depth == treedepth)
87 /* first IBlocks start at the end of file, rounded up
88 to full DBLOCK_SIZE */
89 loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
90 lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
91 GNUNET_assert (0 == (off % DBLOCK_SIZE));
92 ioff = (off / DBLOCK_SIZE);
93 for (i=treedepth-1;i>depth;i--)
96 lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
97 GNUNET_assert (lsize > 0);
98 GNUNET_assert (0 == (ioff % CHK_PER_INODE));
99 ioff /= CHK_PER_INODE;
101 return loff + ioff * sizeof (struct ContentHashKey);
106 * Given a file of the specified treedepth and a block at the given
107 * offset and depth, calculate the offset for the CHK at the given
110 * @param offset the offset of the first
111 * DBLOCK in the subtree of the
113 * @param depth the depth of the IBLOCK in the tree
114 * @param treedepth overall depth of the tree
115 * @param k which CHK in the IBLOCK are we
117 * @return offset if k=0, otherwise an appropriately
118 * larger value (i.e., if depth = treedepth-1,
119 * the returned value should be offset+DBLOCK_SIZE)
122 compute_dblock_offset (uint64_t offset,
124 unsigned int treedepth,
128 uint64_t lsize; /* what is the size of the sum of all DBlocks
129 that a CHK at depth i corresponds to? */
131 if (depth == treedepth)
134 for (i=treedepth-1;i>depth;i--)
135 lsize *= CHK_PER_INODE;
136 return offset + k * lsize;
141 * Fill in all of the generic fields for a download event and call the
144 * @param pi structure to fill in
145 * @param dc overall download context
148 make_download_status (struct GNUNET_FS_ProgressInfo *pi,
149 struct GNUNET_FS_DownloadContext *dc)
151 pi->value.download.dc = dc;
152 pi->value.download.cctx
154 pi->value.download.pctx
155 = (dc->parent == NULL) ? NULL : dc->parent->client_info;
156 pi->value.download.uri
158 pi->value.download.filename
160 pi->value.download.size
162 pi->value.download.duration
163 = GNUNET_TIME_absolute_get_duration (dc->start_time);
164 pi->value.download.completed
166 pi->value.download.anonymity
168 pi->value.download.eta
169 = GNUNET_TIME_calculate_eta (dc->start_time,
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,
253 * Schedule the download of the specified block in the tree.
255 * @param dc overall download this block belongs to
256 * @param chk content-hash-key of the block
257 * @param offset offset of the block in the file
258 * (for IBlocks, the offset is the lowest
259 * offset of any DBlock in the subtree under
261 * @param depth depth of the block, 0 is the root of the tree
264 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
265 const struct ContentHashKey *chk,
269 struct DownloadRequest *sm;
273 char block[DBLOCK_SIZE];
275 struct ProcessResultClosure prc;
278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
279 "Scheduling download at offset %llu and depth %u for `%s'\n",
280 (unsigned long long) offset,
282 GNUNET_h2s (&chk->query));
284 total = GNUNET_ntohll (dc->uri->data.chk.file_length);
285 off = compute_disk_offset (total,
289 len = GNUNET_FS_tree_calculate_block_size (total,
293 sm = GNUNET_malloc (sizeof (struct DownloadRequest));
297 sm->is_pending = GNUNET_YES;
298 sm->next = dc->pending;
300 GNUNET_CONTAINER_multihashmap_put (dc->active,
303 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
305 if ( (dc->old_file_size > off) &&
306 (dc->handle != NULL) &&
308 GNUNET_DISK_file_seek (dc->handle,
310 GNUNET_DISK_SEEK_SET) ) &&
312 GNUNET_DISK_file_read (dc->handle,
316 GNUNET_CRYPTO_hash (block, len, &key);
317 if (0 == memcmp (&key,
319 sizeof (GNUNET_HashCode)))
322 struct GNUNET_CRYPTO_AesSessionKey sk;
323 struct GNUNET_CRYPTO_AesInitializationVector iv;
324 GNUNET_HashCode query;
326 GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
327 GNUNET_CRYPTO_aes_encrypt (block, len,
331 GNUNET_CRYPTO_hash (enc, len, &query);
332 if (0 == memcmp (&query,
334 sizeof (GNUNET_HashCode)))
336 /* already got it! */
340 prc.type = (dc->treedepth == depth)
341 ? GNUNET_BLOCK_TYPE_DBLOCK
342 : GNUNET_BLOCK_TYPE_IBLOCK;
343 prc.query = chk->query;
344 prc.do_store = GNUNET_NO; /* useless */
345 process_result_with_request (&prc,
356 if (depth < dc->treedepth)
358 // FIXME: try if we could
359 // reconstitute this IBLOCK
360 // from the existing blocks on disk (can wait)
361 // (read block(s), encode, compare with
362 // query; if matches, simply return)
365 if ( (dc->th == NULL) &&
366 (dc->client != NULL) )
367 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
368 sizeof (struct SearchMessage),
369 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
371 &transmit_download_request,
378 * Suggest a filename based on given metadata.
380 * @param md given meta data
381 * @return NULL if meta data is useless for suggesting a filename
384 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
386 static const char *mimeMap[][2] = {
387 {"application/bz2", ".bz2"},
388 {"application/gnunet-directory", ".gnd"},
389 {"application/java", ".class"},
390 {"application/msword", ".doc"},
391 {"application/ogg", ".ogg"},
392 {"application/pdf", ".pdf"},
393 {"application/pgp-keys", ".key"},
394 {"application/pgp-signature", ".pgp"},
395 {"application/postscript", ".ps"},
396 {"application/rar", ".rar"},
397 {"application/rtf", ".rtf"},
398 {"application/xml", ".xml"},
399 {"application/x-debian-package", ".deb"},
400 {"application/x-dvi", ".dvi"},
401 {"applixation/x-flac", ".flac"},
402 {"applixation/x-gzip", ".gz"},
403 {"application/x-java-archive", ".jar"},
404 {"application/x-java-vm", ".class"},
405 {"application/x-python-code", ".pyc"},
406 {"application/x-redhat-package-manager", ".rpm"},
407 {"application/x-rpm", ".rpm"},
408 {"application/x-tar", ".tar"},
409 {"application/x-tex-pk", ".pk"},
410 {"application/x-texinfo", ".texinfo"},
411 {"application/x-xcf", ".xcf"},
412 {"application/x-xfig", ".xfig"},
413 {"application/zip", ".zip"},
415 {"audio/midi", ".midi"},
416 {"audio/mpeg", ".mp3"},
417 {"audio/real", ".rm"},
418 {"audio/x-wav", ".wav"},
420 {"image/gif", ".gif"},
421 {"image/jpeg", ".jpg"},
422 {"image/pcx", ".pcx"},
423 {"image/png", ".png"},
424 {"image/tiff", ".tiff"},
425 {"image/x-ms-bmp", ".bmp"},
426 {"image/x-xpixmap", ".xpm"},
428 {"text/css", ".css"},
429 {"text/html", ".html"},
430 {"text/plain", ".txt"},
431 {"text/rtf", ".rtf"},
432 {"text/x-c++hdr", ".h++"},
433 {"text/x-c++src", ".c++"},
434 {"text/x-chdr", ".h"},
435 {"text/x-csrc", ".c"},
436 {"text/x-java", ".java"},
437 {"text/x-moc", ".moc"},
438 {"text/x-pascal", ".pas"},
439 {"text/x-perl", ".pl"},
440 {"text/x-python", ".py"},
441 {"text/x-tex", ".tex"},
443 {"video/avi", ".avi"},
444 {"video/mpeg", ".mpeg"},
445 {"video/quicktime", ".qt"},
446 {"video/real", ".rm"},
447 {"video/x-msvideo", ".avi"},
456 ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
457 EXTRACTOR_METATYPE_FILENAME);
461 mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
462 EXTRACTOR_METATYPE_MIMETYPE);
466 while ( (mimeMap[i][0] != NULL) &&
467 (0 != strcmp (mime, mimeMap[i][0])))
469 if (mimeMap[i][1] == NULL)
470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
471 GNUNET_ERROR_TYPE_BULK,
472 _("Did not find mime type `%s' in extension list.\n"),
478 base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
479 EXTRACTOR_METATYPE_TITLE,
480 EXTRACTOR_METATYPE_BOOK_TITLE,
481 EXTRACTOR_METATYPE_ORIGINAL_TITLE,
482 EXTRACTOR_METATYPE_PACKAGE_NAME,
483 EXTRACTOR_METATYPE_URL,
484 EXTRACTOR_METATYPE_URI,
485 EXTRACTOR_METATYPE_DESCRIPTION,
486 EXTRACTOR_METATYPE_ISRC,
487 EXTRACTOR_METATYPE_JOURNAL_NAME,
488 EXTRACTOR_METATYPE_AUTHOR_NAME,
489 EXTRACTOR_METATYPE_SUBJECT,
490 EXTRACTOR_METATYPE_ALBUM,
491 EXTRACTOR_METATYPE_ARTIST,
492 EXTRACTOR_METATYPE_KEYWORDS,
493 EXTRACTOR_METATYPE_COMMENT,
494 EXTRACTOR_METATYPE_UNKNOWN,
496 if ( (base == NULL) &&
500 return GNUNET_strdup (ext);
503 GNUNET_asprintf (&ret,
513 * We've lost our connection with the FS service.
514 * Re-establish it and re-transmit all of our
517 * @param dc download context that is having trouble
520 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
524 * We found an entry in a directory. Check if the respective child
525 * already exists and if not create the respective child download.
527 * @param cls the parent download
528 * @param filename name of the file in the directory
529 * @param uri URI of the file (CHK or LOC)
530 * @param meta meta data of the file
531 * @param length number of bytes in data
532 * @param data contents of the file (or NULL if they were not inlined)
535 trigger_recursive_download (void *cls,
536 const char *filename,
537 const struct GNUNET_FS_Uri *uri,
538 const struct GNUNET_CONTAINER_MetaData *meta,
544 * We're done downloading a directory. Open the file and
545 * trigger all of the (remaining) child downloads.
547 * @param dc context of download that just completed
550 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
555 struct GNUNET_DISK_FileHandle *h;
556 struct GNUNET_DISK_MapHandle *m;
558 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
559 size = (size_t) size64;
560 if (size64 != (uint64_t) size)
562 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
563 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
566 if (dc->filename != NULL)
568 h = GNUNET_DISK_file_open (dc->filename,
569 GNUNET_DISK_OPEN_READ,
570 GNUNET_DISK_PERM_NONE);
574 GNUNET_assert (dc->temp_filename != NULL);
575 h = GNUNET_DISK_file_open (dc->temp_filename,
576 GNUNET_DISK_OPEN_READ,
577 GNUNET_DISK_PERM_NONE);
581 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
584 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
585 _("Directory too large for system address space\n"));
589 GNUNET_FS_directory_list_contents (size,
592 &trigger_recursive_download,
594 GNUNET_DISK_file_unmap (m);
596 GNUNET_DISK_file_close (h);
597 if (dc->filename == NULL)
599 if (0 != UNLINK (dc->temp_filename))
600 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
603 GNUNET_free (dc->temp_filename);
604 dc->temp_filename = NULL;
610 * Check if all child-downloads have completed and
611 * if so, signal completion (and possibly recurse to
615 check_completed (struct GNUNET_FS_DownloadContext *dc)
617 struct GNUNET_FS_ProgressInfo pi;
618 struct GNUNET_FS_DownloadContext *pos;
620 pos = dc->child_head;
623 if ( (pos->emsg == NULL) &&
624 (pos->completed < pos->length) )
625 return; /* not done yet */
626 if ( (pos->child_head != NULL) &&
627 (pos->has_finished != GNUNET_YES) )
628 return; /* not transitively done yet */
631 dc->has_finished = GNUNET_YES;
632 /* signal completion */
633 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
634 make_download_status (&pi, dc);
635 if (dc->parent != NULL)
636 check_completed (dc->parent);
641 * We found an entry in a directory. Check if the respective child
642 * already exists and if not create the respective child download.
644 * @param cls the parent download
645 * @param filename name of the file in the directory
646 * @param uri URI of the file (CHK or LOC)
647 * @param meta meta data of the file
648 * @param length number of bytes in data
649 * @param data contents of the file (or NULL if they were not inlined)
652 trigger_recursive_download (void *cls,
653 const char *filename,
654 const struct GNUNET_FS_Uri *uri,
655 const struct GNUNET_CONTAINER_MetaData *meta,
659 struct GNUNET_FS_DownloadContext *dc = cls;
660 struct GNUNET_FS_DownloadContext *cpos;
661 struct GNUNET_DISK_FileHandle *fh;
663 const char *real_name;
671 return; /* entry for the directory itself */
672 cpos = dc->child_head;
675 if ( (GNUNET_FS_uri_test_equal (uri,
677 ( (filename != NULL) &&
678 (0 == strcmp (cpos->filename,
684 return; /* already exists */
686 if (NULL == filename)
688 fn = GNUNET_FS_meta_data_suggest_filename (meta);
691 us = GNUNET_FS_uri_to_string (uri);
692 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
693 GNUNET_FS_URI_CHK_INFIX)]);
696 else if (fn[0] == '.')
699 us = GNUNET_FS_uri_to_string (uri);
700 GNUNET_asprintf (&fn,
702 &us[strlen (GNUNET_FS_URI_PREFIX
703 GNUNET_FS_URI_CHK_INFIX)], ext);
709 if (dc->filename == NULL)
715 dn = GNUNET_strdup (dc->filename);
716 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
718 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
719 GNUNET_FS_DIRECTORY_EXT)) );
720 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
722 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
723 GNUNET_FS_DIRECTORY_EXT)) )
724 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
725 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
726 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
728 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
729 GNUNET_FS_DIRECTORY_EXT)) ) )
731 GNUNET_asprintf (&full_name,
736 GNUNET_FS_DIRECTORY_EXT);
740 GNUNET_asprintf (&full_name,
748 if ( (full_name != NULL) &&
750 GNUNET_DISK_directory_create_for_file (full_name)) )
752 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
753 _("Failed to create directory for recursive download of `%s'\n"),
755 GNUNET_free (full_name);
756 GNUNET_free_non_null (fn);
761 if ( (data != NULL) &&
762 (GNUNET_FS_uri_chk_get_file_size (uri) == length) )
764 if (full_name == NULL)
766 temp_name = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
767 real_name = temp_name;
771 real_name = full_name;
773 /* write to disk, then trigger normal download which will instantly progress to completion */
774 fh = GNUNET_DISK_file_open (real_name,
775 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
776 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
779 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
782 GNUNET_free (full_name);
783 GNUNET_free_non_null (fn);
787 GNUNET_DISK_file_write (fh,
791 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
795 GNUNET_DISK_file_close (fh);
797 GNUNET_FS_download_start (dc->h,
800 full_name, temp_name,
802 GNUNET_FS_uri_chk_get_file_size (uri),
807 GNUNET_free_non_null (full_name);
808 GNUNET_free_non_null (temp_name);
809 GNUNET_free_non_null (fn);
814 * Iterator over entries in the pending requests in the 'active' map for the
815 * reply that we just got.
817 * @param cls closure (our 'struct ProcessResultClosure')
818 * @param key query for the given value / request
819 * @param value value in the hash map (a 'struct DownloadRequest')
820 * @return GNUNET_YES (we should continue to iterate); unless serious error
823 process_result_with_request (void *cls,
824 const GNUNET_HashCode * key,
827 struct ProcessResultClosure *prc = cls;
828 struct DownloadRequest *sm = value;
829 struct DownloadRequest *ppos;
830 struct DownloadRequest *pprev;
831 struct GNUNET_FS_DownloadContext *dc = prc->dc;
832 struct GNUNET_CRYPTO_AesSessionKey skey;
833 struct GNUNET_CRYPTO_AesInitializationVector iv;
835 struct GNUNET_FS_ProgressInfo pi;
840 struct ContentHashKey *chk;
843 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
851 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
855 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
857 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
858 pi.value.download.specifics.error.message = dc->emsg;
859 make_download_status (&pi, dc);
860 /* abort all pending requests */
863 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
866 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
870 GNUNET_assert (GNUNET_YES ==
871 GNUNET_CONTAINER_multihashmap_remove (dc->active,
874 /* if this request is on the pending list, remove it! */
882 dc->pending = ppos->next;
884 pprev->next = ppos->next;
890 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
891 GNUNET_CRYPTO_aes_decrypt (prc->data,
896 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
901 if ( ( GNUNET_YES == prc->do_store) &&
902 (NULL != dc->handle) &&
903 ( (sm->depth == dc->treedepth) ||
904 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
909 "Saving decrypted block to disk at offset %llu\n",
910 (unsigned long long) off);
913 GNUNET_DISK_file_seek (dc->handle,
915 GNUNET_DISK_SEEK_SET) ) )
916 GNUNET_asprintf (&emsg,
917 _("Failed to seek to offset %llu in file `%s': %s\n"),
918 (unsigned long long) off,
921 else if (prc->size !=
922 GNUNET_DISK_file_write (dc->handle,
925 GNUNET_asprintf (&emsg,
926 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
927 (unsigned int) prc->size,
928 (unsigned long long) off,
934 // FIXME: make persistent
937 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
938 pi.value.download.specifics.error.message = emsg;
939 make_download_status (&pi, dc);
940 /* abort all pending requests */
943 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
946 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
952 if (sm->depth == dc->treedepth)
955 if (sm->offset < dc->offset)
957 /* starting offset begins in the middle of pt,
958 do not count first bytes as progress */
959 GNUNET_assert (app > (dc->offset - sm->offset));
960 app -= (dc->offset - sm->offset);
962 if (sm->offset + prc->size > dc->offset + dc->length)
964 /* end of block is after relevant range,
965 do not count last bytes as progress */
966 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
967 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
969 dc->completed += app;
971 /* do recursive download if option is set and either meta data
972 says it is a directory or if no meta data is given AND filename
973 ends in '.gnd' (top-level case) */
974 if (is_recursive_download (dc))
975 GNUNET_FS_directory_list_contents (prc->size,
978 &trigger_recursive_download,
982 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
983 pi.value.download.specifics.progress.data = pt;
984 pi.value.download.specifics.progress.offset = sm->offset;
985 pi.value.download.specifics.progress.data_len = prc->size;
986 pi.value.download.specifics.progress.depth = sm->depth;
987 make_download_status (&pi, dc);
988 GNUNET_assert (dc->completed <= dc->length);
989 if (dc->completed == dc->length)
992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
993 "Download completed, truncating file to desired length %llu\n",
994 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
996 /* truncate file to size (since we store IBlocks at the end) */
997 if (dc->handle != NULL)
999 GNUNET_DISK_file_close (dc->handle);
1001 if (0 != truncate (dc->filename,
1002 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1003 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1007 if (dc->job_queue != NULL)
1009 GNUNET_FS_dequeue_ (dc->job_queue);
1010 dc->job_queue = NULL;
1012 if (is_recursive_download (dc))
1013 full_recursive_download (dc);
1014 if (dc->child_head == NULL)
1016 /* signal completion */
1017 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
1018 make_download_status (&pi, dc);
1019 if (dc->parent != NULL)
1020 check_completed (dc->parent);
1022 GNUNET_assert (sm->depth == dc->treedepth);
1024 // FIXME: make persistent
1025 if (sm->depth == dc->treedepth)
1031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1032 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1034 (unsigned long long) sm->offset);
1036 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1037 chk = (struct ContentHashKey*) pt;
1038 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1040 off = compute_dblock_offset (sm->offset,
1044 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1045 (off < dc->offset + dc->length) )
1046 schedule_block_download (dc,
1057 * Process a download result.
1059 * @param dc our download context
1060 * @param type type of the result
1061 * @param data the (encrypted) response
1062 * @param size size of data
1065 process_result (struct GNUNET_FS_DownloadContext *dc,
1066 enum GNUNET_BLOCK_Type type,
1070 struct ProcessResultClosure prc;
1076 prc.do_store = GNUNET_YES;
1077 GNUNET_CRYPTO_hash (data, size, &prc.query);
1079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1080 "Received result for query `%s' from `%s'-service\n",
1081 GNUNET_h2s (&prc.query),
1084 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1086 &process_result_with_request,
1092 * Type of a function to call when we receive a message
1095 * @param cls closure
1096 * @param msg message received, NULL on timeout or fatal error
1099 receive_results (void *cls,
1100 const struct GNUNET_MessageHeader * msg)
1102 struct GNUNET_FS_DownloadContext *dc = cls;
1103 const struct PutMessage *cm;
1106 if ( (NULL == msg) ||
1107 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1108 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1110 GNUNET_break (msg == NULL);
1114 msize = ntohs(msg->size);
1115 cm = (const struct PutMessage*) msg;
1119 msize - sizeof (struct PutMessage));
1120 if (dc->client == NULL)
1121 return; /* fatal error */
1122 /* continue receiving */
1123 GNUNET_CLIENT_receive (dc->client,
1126 GNUNET_TIME_UNIT_FOREVER_REL);
1132 * We're ready to transmit a search request to the
1133 * file-sharing service. Do it. If there is
1134 * more than one request pending, try to send
1135 * multiple or request another transmission.
1137 * @param cls closure
1138 * @param size number of bytes available in buf
1139 * @param buf where the callee should write the message
1140 * @return number of bytes written to buf
1143 transmit_download_request (void *cls,
1147 struct GNUNET_FS_DownloadContext *dc = cls;
1149 struct SearchMessage *sm;
1157 GNUNET_assert (size >= sizeof (struct SearchMessage));
1160 while ( (dc->pending != NULL) &&
1161 (size > msize + sizeof (struct SearchMessage)) )
1164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1165 "Transmitting download request for `%s' to `%s'-service\n",
1166 GNUNET_h2s (&dc->pending->chk.query),
1169 memset (sm, 0, sizeof (struct SearchMessage));
1170 sm->header.size = htons (sizeof (struct SearchMessage));
1171 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1172 if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1173 sm->options = htonl (1);
1175 sm->options = htonl (0);
1176 if (dc->pending->depth == dc->treedepth)
1177 sm->type = htonl (GNUNET_BLOCK_TYPE_DBLOCK);
1179 sm->type = htonl (GNUNET_BLOCK_TYPE_IBLOCK);
1180 sm->anonymity_level = htonl (dc->anonymity);
1181 sm->target = dc->target.hashPubKey;
1182 sm->query = dc->pending->chk.query;
1183 dc->pending->is_pending = GNUNET_NO;
1184 dc->pending = dc->pending->next;
1185 msize += sizeof (struct SearchMessage);
1188 if (dc->pending != NULL)
1189 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1190 sizeof (struct SearchMessage),
1191 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1193 &transmit_download_request,
1200 * Reconnect to the FS service and transmit our queries NOW.
1202 * @param cls our download context
1206 do_reconnect (void *cls,
1207 const struct GNUNET_SCHEDULER_TaskContext *tc)
1209 struct GNUNET_FS_DownloadContext *dc = cls;
1210 struct GNUNET_CLIENT_Connection *client;
1212 dc->task = GNUNET_SCHEDULER_NO_TASK;
1213 client = GNUNET_CLIENT_connect (dc->h->sched,
1218 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1219 "Connecting to `%s'-service failed, will try again.\n",
1224 dc->client = client;
1225 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1226 sizeof (struct SearchMessage),
1227 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1229 &transmit_download_request,
1231 GNUNET_CLIENT_receive (client,
1234 GNUNET_TIME_UNIT_FOREVER_REL);
1239 * Add entries that are not yet pending back to the pending list.
1241 * @param cls our download context
1243 * @param entry entry of type "struct DownloadRequest"
1247 retry_entry (void *cls,
1248 const GNUNET_HashCode *key,
1251 struct GNUNET_FS_DownloadContext *dc = cls;
1252 struct DownloadRequest *dr = entry;
1254 if (! dr->is_pending)
1256 dr->next = dc->pending;
1257 dr->is_pending = GNUNET_YES;
1258 dc->pending = entry;
1265 * We've lost our connection with the FS service.
1266 * Re-establish it and re-transmit all of our
1269 * @param dc download context that is having trouble
1272 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1275 if (NULL != dc->client)
1279 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1282 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1285 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1289 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1290 GNUNET_TIME_UNIT_SECONDS,
1298 * We're allowed to ask the FS service for our blocks. Start the download.
1300 * @param cls the 'struct GNUNET_FS_DownloadContext'
1301 * @param client handle to use for communcation with FS (we must destroy it!)
1304 activate_fs_download (void *cls,
1305 struct GNUNET_CLIENT_Connection *client)
1307 struct GNUNET_FS_DownloadContext *dc = cls;
1308 struct GNUNET_FS_ProgressInfo pi;
1310 GNUNET_assert (NULL != client);
1311 dc->client = client;
1312 GNUNET_CLIENT_receive (client,
1315 GNUNET_TIME_UNIT_FOREVER_REL);
1316 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1317 make_download_status (&pi, dc);
1318 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1321 if ( (dc->th == NULL) &&
1322 (dc->client != NULL) )
1323 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1324 sizeof (struct SearchMessage),
1325 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1327 &transmit_download_request,
1333 * We must stop to ask the FS service for our blocks. Pause the download.
1335 * @param cls the 'struct GNUNET_FS_DownloadContext'
1338 deactivate_fs_download (void *cls)
1340 struct GNUNET_FS_DownloadContext *dc = cls;
1341 struct GNUNET_FS_ProgressInfo pi;
1345 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1348 if (NULL != dc->client)
1350 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1353 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1354 make_download_status (&pi, dc);
1359 * Download parts of a file. Note that this will store
1360 * the blocks at the respective offset in the given file. Also, the
1361 * download is still using the blocking of the underlying FS
1362 * encoding. As a result, the download may *write* outside of the
1363 * given boundaries (if offset and length do not match the 32k FS
1364 * block boundaries). <p>
1366 * This function should be used to focus a download towards a
1367 * particular portion of the file (optimization), not to strictly
1368 * limit the download to exactly those bytes.
1370 * @param h handle to the file sharing subsystem
1371 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1372 * @param meta known metadata for the file (can be NULL)
1373 * @param filename where to store the file, maybe NULL (then no file is
1374 * created on disk and data must be grabbed from the callbacks)
1375 * @param tempname where to store temporary file data, not used if filename is non-NULL;
1376 * can be NULL (in which case we will pick a name if needed); the temporary file
1377 * may already exist, in which case we will try to use the data that is there and
1378 * if it is not what is desired, will overwrite it
1379 * @param offset at what offset should we start the download (typically 0)
1380 * @param length how many bytes should be downloaded starting at offset
1381 * @param anonymity anonymity level to use for the download
1382 * @param options various options
1383 * @param cctx initial value for the client context for this download
1384 * @param parent parent download to associate this download with (use NULL
1385 * for top-level downloads; useful for manually-triggered recursive downloads)
1386 * @return context that can be used to control this download
1388 struct GNUNET_FS_DownloadContext *
1389 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1390 const struct GNUNET_FS_Uri *uri,
1391 const struct GNUNET_CONTAINER_MetaData *meta,
1392 const char *filename,
1393 const char *tempname,
1397 enum GNUNET_FS_DownloadOptions options,
1399 struct GNUNET_FS_DownloadContext *parent)
1401 struct GNUNET_FS_ProgressInfo pi;
1402 struct GNUNET_FS_DownloadContext *dc;
1404 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1405 if ( (offset + length < offset) ||
1406 (offset + length > uri->data.chk.file_length) )
1411 // FIXME: add support for "loc" URIs!
1413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1414 "Starting download `%s' of %llu bytes\n",
1416 (unsigned long long) length);
1418 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1420 dc->parent = parent;
1423 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1427 dc->uri = GNUNET_FS_uri_dup (uri);
1428 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1429 dc->client_info = cctx;
1430 dc->start_time = GNUNET_TIME_absolute_get ();
1431 if (NULL != filename)
1433 dc->filename = GNUNET_strdup (filename);
1434 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1435 GNUNET_DISK_file_size (filename,
1438 dc->handle = GNUNET_DISK_file_open (filename,
1439 GNUNET_DISK_OPEN_READWRITE |
1440 GNUNET_DISK_OPEN_CREATE,
1441 GNUNET_DISK_PERM_USER_READ |
1442 GNUNET_DISK_PERM_USER_WRITE |
1443 GNUNET_DISK_PERM_GROUP_READ |
1444 GNUNET_DISK_PERM_OTHER_READ);
1445 if (dc->handle == NULL)
1447 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1448 _("Download failed: could not open file `%s': %s\n"),
1451 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1452 GNUNET_FS_uri_destroy (dc->uri);
1453 GNUNET_free (dc->filename);
1458 // FIXME: set "dc->target" for LOC uris!
1459 dc->offset = offset;
1460 dc->length = length;
1461 dc->anonymity = anonymity;
1462 dc->options = options;
1463 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1464 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1465 if ( (filename == NULL) &&
1466 (is_recursive_download (dc) ) )
1468 if (tempname != NULL)
1469 dc->temp_filename = GNUNET_strdup (tempname);
1471 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
1475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476 "Download tree has depth %u\n",
1479 // FIXME: make persistent
1480 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1481 pi.value.download.specifics.start.meta = meta;
1482 make_download_status (&pi, dc);
1483 schedule_block_download (dc,
1484 &dc->uri->data.chk.chk,
1486 1 /* 0 == CHK, 1 == top */);
1487 dc->job_queue = GNUNET_FS_queue_ (h,
1488 &activate_fs_download,
1489 &deactivate_fs_download,
1491 (length + DBLOCK_SIZE-1) / DBLOCK_SIZE);
1497 * Free entries in the map.
1499 * @param cls unused (NULL)
1501 * @param entry entry of type "struct DownloadRequest" which is freed
1505 free_entry (void *cls,
1506 const GNUNET_HashCode *key,
1509 GNUNET_free (entry);
1515 * Stop a download (aborts if download is incomplete).
1517 * @param dc handle for the download
1518 * @param do_delete delete files of incomplete downloads
1521 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1524 struct GNUNET_FS_ProgressInfo pi;
1526 if (dc->job_queue != NULL)
1528 GNUNET_FS_dequeue_ (dc->job_queue);
1529 dc->job_queue = NULL;
1531 while (NULL != dc->child_head)
1532 GNUNET_FS_download_stop (dc->child_head,
1534 // FIXME: make unpersistent
1535 if (dc->parent != NULL)
1536 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1537 dc->parent->child_tail,
1540 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1541 make_download_status (&pi, dc);
1542 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1543 GNUNET_SCHEDULER_cancel (dc->h->sched,
1545 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1548 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1549 if (dc->filename != NULL)
1551 if (NULL != dc->handle)
1552 GNUNET_DISK_file_close (dc->handle);
1553 if ( (dc->completed != dc->length) &&
1554 (GNUNET_YES == do_delete) )
1556 if (0 != UNLINK (dc->filename))
1557 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1561 GNUNET_free (dc->filename);
1563 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1564 GNUNET_FS_uri_destroy (dc->uri);
1565 if (NULL != dc->temp_filename)
1567 if (0 != UNLINK (dc->temp_filename))
1568 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1571 GNUNET_free (dc->temp_filename);
1576 /* end of fs_download.c */