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 if (0 == memcmp (&key,
318 sizeof (GNUNET_HashCode)))
321 struct GNUNET_CRYPTO_AesSessionKey sk;
322 struct GNUNET_CRYPTO_AesInitializationVector iv;
323 GNUNET_HashCode query;
325 GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
326 GNUNET_CRYPTO_aes_encrypt (block, len,
330 GNUNET_CRYPTO_hash (enc, len, &query);
331 if (0 == memcmp (&query,
333 sizeof (GNUNET_HashCode)))
335 /* already got it! */
339 prc.type = (dc->treedepth == depth)
340 ? GNUNET_BLOCK_TYPE_DBLOCK
341 : GNUNET_BLOCK_TYPE_IBLOCK;
342 prc.query = chk->query;
343 prc.do_store = GNUNET_NO; /* useless */
344 process_result_with_request (&prc,
355 if (depth < dc->treedepth)
357 // FIXME: try if we could
358 // reconstitute this IBLOCK
359 // from the existing blocks on disk (can wait)
360 // (read block(s), encode, compare with
361 // query; if matches, simply return)
364 if ( (dc->th == NULL) &&
365 (dc->client != NULL) )
366 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
367 sizeof (struct SearchMessage),
368 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
370 &transmit_download_request,
377 * Suggest a filename based on given metadata.
379 * @param md given meta data
380 * @return NULL if meta data is useless for suggesting a filename
383 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
385 static const char *mimeMap[][2] = {
386 {"application/bz2", ".bz2"},
387 {"application/gnunet-directory", ".gnd"},
388 {"application/java", ".class"},
389 {"application/msword", ".doc"},
390 {"application/ogg", ".ogg"},
391 {"application/pdf", ".pdf"},
392 {"application/pgp-keys", ".key"},
393 {"application/pgp-signature", ".pgp"},
394 {"application/postscript", ".ps"},
395 {"application/rar", ".rar"},
396 {"application/rtf", ".rtf"},
397 {"application/xml", ".xml"},
398 {"application/x-debian-package", ".deb"},
399 {"application/x-dvi", ".dvi"},
400 {"applixation/x-flac", ".flac"},
401 {"applixation/x-gzip", ".gz"},
402 {"application/x-java-archive", ".jar"},
403 {"application/x-java-vm", ".class"},
404 {"application/x-python-code", ".pyc"},
405 {"application/x-redhat-package-manager", ".rpm"},
406 {"application/x-rpm", ".rpm"},
407 {"application/x-tar", ".tar"},
408 {"application/x-tex-pk", ".pk"},
409 {"application/x-texinfo", ".texinfo"},
410 {"application/x-xcf", ".xcf"},
411 {"application/x-xfig", ".xfig"},
412 {"application/zip", ".zip"},
414 {"audio/midi", ".midi"},
415 {"audio/mpeg", ".mp3"},
416 {"audio/real", ".rm"},
417 {"audio/x-wav", ".wav"},
419 {"image/gif", ".gif"},
420 {"image/jpeg", ".jpg"},
421 {"image/pcx", ".pcx"},
422 {"image/png", ".png"},
423 {"image/tiff", ".tiff"},
424 {"image/x-ms-bmp", ".bmp"},
425 {"image/x-xpixmap", ".xpm"},
427 {"text/css", ".css"},
428 {"text/html", ".html"},
429 {"text/plain", ".txt"},
430 {"text/rtf", ".rtf"},
431 {"text/x-c++hdr", ".h++"},
432 {"text/x-c++src", ".c++"},
433 {"text/x-chdr", ".h"},
434 {"text/x-csrc", ".c"},
435 {"text/x-java", ".java"},
436 {"text/x-moc", ".moc"},
437 {"text/x-pascal", ".pas"},
438 {"text/x-perl", ".pl"},
439 {"text/x-python", ".py"},
440 {"text/x-tex", ".tex"},
442 {"video/avi", ".avi"},
443 {"video/mpeg", ".mpeg"},
444 {"video/quicktime", ".qt"},
445 {"video/real", ".rm"},
446 {"video/x-msvideo", ".avi"},
455 ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
456 EXTRACTOR_METATYPE_FILENAME);
460 mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
461 EXTRACTOR_METATYPE_MIMETYPE);
465 while ( (mimeMap[i][0] != NULL) &&
466 (0 != strcmp (mime, mimeMap[i][0])))
468 if (mimeMap[i][1] == NULL)
469 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
470 GNUNET_ERROR_TYPE_BULK,
471 _("Did not find mime type `%s' in extension list.\n"),
477 base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
478 EXTRACTOR_METATYPE_TITLE,
479 EXTRACTOR_METATYPE_BOOK_TITLE,
480 EXTRACTOR_METATYPE_ORIGINAL_TITLE,
481 EXTRACTOR_METATYPE_PACKAGE_NAME,
482 EXTRACTOR_METATYPE_URL,
483 EXTRACTOR_METATYPE_URI,
484 EXTRACTOR_METATYPE_DESCRIPTION,
485 EXTRACTOR_METATYPE_ISRC,
486 EXTRACTOR_METATYPE_JOURNAL_NAME,
487 EXTRACTOR_METATYPE_AUTHOR_NAME,
488 EXTRACTOR_METATYPE_SUBJECT,
489 EXTRACTOR_METATYPE_ALBUM,
490 EXTRACTOR_METATYPE_ARTIST,
491 EXTRACTOR_METATYPE_KEYWORDS,
492 EXTRACTOR_METATYPE_COMMENT,
493 EXTRACTOR_METATYPE_UNKNOWN,
495 if ( (base == NULL) &&
499 return GNUNET_strdup (ext);
502 GNUNET_asprintf (&ret,
512 * We've lost our connection with the FS service.
513 * Re-establish it and re-transmit all of our
516 * @param dc download context that is having trouble
519 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
523 * We found an entry in a directory. Check if the respective child
524 * already exists and if not create the respective child download.
526 * @param cls the parent download
527 * @param filename name of the file in the directory
528 * @param uri URI of the file (CHK or LOC)
529 * @param meta meta data of the file
530 * @param length number of bytes in data
531 * @param data contents of the file (or NULL if they were not inlined)
534 trigger_recursive_download (void *cls,
535 const char *filename,
536 const struct GNUNET_FS_Uri *uri,
537 const struct GNUNET_CONTAINER_MetaData *meta,
543 * We're done downloading a directory. Open the file and
544 * trigger all of the (remaining) child downloads.
546 * @param dc context of download that just completed
549 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
554 struct GNUNET_DISK_FileHandle *h;
555 struct GNUNET_DISK_MapHandle *m;
557 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
558 size = (size_t) size64;
559 if (size64 != (uint64_t) size)
561 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
562 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
565 if (dc->filename != NULL)
567 h = GNUNET_DISK_file_open (dc->filename,
568 GNUNET_DISK_OPEN_READ,
569 GNUNET_DISK_PERM_NONE);
573 GNUNET_assert (dc->temp_filename != NULL);
574 h = GNUNET_DISK_file_open (dc->temp_filename,
575 GNUNET_DISK_OPEN_READ,
576 GNUNET_DISK_PERM_NONE);
580 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
583 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
584 _("Directory too large for system address space\n"));
588 GNUNET_FS_directory_list_contents (size,
591 &trigger_recursive_download,
593 GNUNET_DISK_file_unmap (m);
595 GNUNET_DISK_file_close (h);
596 if (dc->filename == NULL)
598 if (0 != UNLINK (dc->temp_filename))
599 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
602 GNUNET_free (dc->temp_filename);
603 dc->temp_filename = NULL;
609 * Check if all child-downloads have completed and
610 * if so, signal completion (and possibly recurse to
614 check_completed (struct GNUNET_FS_DownloadContext *dc)
616 struct GNUNET_FS_ProgressInfo pi;
617 struct GNUNET_FS_DownloadContext *pos;
619 pos = dc->child_head;
622 if ( (pos->emsg == NULL) &&
623 (pos->completed < pos->length) )
624 return; /* not done yet */
625 if ( (pos->child_head != NULL) &&
626 (pos->has_finished != GNUNET_YES) )
627 return; /* not transitively done yet */
630 dc->has_finished = GNUNET_YES;
631 /* signal completion */
632 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
633 make_download_status (&pi, dc);
634 if (dc->parent != NULL)
635 check_completed (dc->parent);
640 * We found an entry in a directory. Check if the respective child
641 * already exists and if not create the respective child download.
643 * @param cls the parent download
644 * @param filename name of the file in the directory
645 * @param uri URI of the file (CHK or LOC)
646 * @param meta meta data of the file
647 * @param length number of bytes in data
648 * @param data contents of the file (or NULL if they were not inlined)
651 trigger_recursive_download (void *cls,
652 const char *filename,
653 const struct GNUNET_FS_Uri *uri,
654 const struct GNUNET_CONTAINER_MetaData *meta,
658 struct GNUNET_FS_DownloadContext *dc = cls;
659 struct GNUNET_FS_DownloadContext *cpos;
660 struct GNUNET_DISK_FileHandle *fh;
662 const char *real_name;
670 return; /* entry for the directory itself */
671 cpos = dc->child_head;
674 if ( (GNUNET_FS_uri_test_equal (uri,
676 ( (filename != NULL) &&
677 (0 == strcmp (cpos->filename,
683 return; /* already exists */
685 if (NULL == filename)
687 fn = GNUNET_FS_meta_data_suggest_filename (meta);
690 us = GNUNET_FS_uri_to_string (uri);
691 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
692 GNUNET_FS_URI_CHK_INFIX)]);
695 else if (fn[0] == '.')
698 us = GNUNET_FS_uri_to_string (uri);
699 GNUNET_asprintf (&fn,
701 &us[strlen (GNUNET_FS_URI_PREFIX
702 GNUNET_FS_URI_CHK_INFIX)], ext);
708 if (dc->filename == NULL)
714 dn = GNUNET_strdup (dc->filename);
715 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
717 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
718 GNUNET_FS_DIRECTORY_EXT)) );
719 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
721 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
722 GNUNET_FS_DIRECTORY_EXT)) )
723 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
724 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
725 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
727 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
728 GNUNET_FS_DIRECTORY_EXT)) ) )
730 GNUNET_asprintf (&full_name,
735 GNUNET_FS_DIRECTORY_EXT);
739 GNUNET_asprintf (&full_name,
747 if ( (full_name != NULL) &&
749 GNUNET_DISK_directory_create_for_file (full_name)) )
751 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
752 _("Failed to create directory for recursive download of `%s'\n"),
754 GNUNET_free (full_name);
755 GNUNET_free_non_null (fn);
760 if ( (data != NULL) &&
761 (GNUNET_FS_uri_chk_get_file_size (uri) == length) )
763 if (full_name == NULL)
765 temp_name = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
766 real_name = temp_name;
770 real_name = full_name;
772 /* write to disk, then trigger normal download which will instantly progress to completion */
773 fh = GNUNET_DISK_file_open (real_name,
774 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
775 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
778 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
781 GNUNET_free (full_name);
782 GNUNET_free_non_null (fn);
786 GNUNET_DISK_file_write (fh,
790 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
794 GNUNET_DISK_file_close (fh);
796 GNUNET_FS_download_start (dc->h,
799 full_name, temp_name,
801 GNUNET_FS_uri_chk_get_file_size (uri),
806 GNUNET_free_non_null (full_name);
807 GNUNET_free_non_null (temp_name);
808 GNUNET_free_non_null (fn);
813 * Iterator over entries in the pending requests in the 'active' map for the
814 * reply that we just got.
816 * @param cls closure (our 'struct ProcessResultClosure')
817 * @param key query for the given value / request
818 * @param value value in the hash map (a 'struct DownloadRequest')
819 * @return GNUNET_YES (we should continue to iterate); unless serious error
822 process_result_with_request (void *cls,
823 const GNUNET_HashCode * key,
826 struct ProcessResultClosure *prc = cls;
827 struct DownloadRequest *sm = value;
828 struct GNUNET_FS_DownloadContext *dc = prc->dc;
829 struct GNUNET_CRYPTO_AesSessionKey skey;
830 struct GNUNET_CRYPTO_AesInitializationVector iv;
832 struct GNUNET_FS_ProgressInfo pi;
837 struct ContentHashKey *chk;
840 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
848 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
852 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
854 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
855 pi.value.download.specifics.error.message = dc->emsg;
856 make_download_status (&pi, dc);
857 /* abort all pending requests */
860 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
863 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
867 GNUNET_assert (GNUNET_YES ==
868 GNUNET_CONTAINER_multihashmap_remove (dc->active,
871 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
872 GNUNET_CRYPTO_aes_decrypt (prc->data,
877 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
882 if ( ( GNUNET_YES == prc->do_store) &&
883 (NULL != dc->handle) &&
884 ( (sm->depth == dc->treedepth) ||
885 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890 "Saving decrypted block to disk at offset %llu\n",
891 (unsigned long long) off);
894 GNUNET_DISK_file_seek (dc->handle,
896 GNUNET_DISK_SEEK_SET) ) )
897 GNUNET_asprintf (&emsg,
898 _("Failed to seek to offset %llu in file `%s': %s\n"),
899 (unsigned long long) off,
902 else if (prc->size !=
903 GNUNET_DISK_file_write (dc->handle,
906 GNUNET_asprintf (&emsg,
907 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
908 (unsigned int) prc->size,
909 (unsigned long long) off,
915 // FIXME: make persistent
918 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
919 pi.value.download.specifics.error.message = emsg;
920 make_download_status (&pi, dc);
921 /* abort all pending requests */
924 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
927 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
933 if (sm->depth == dc->treedepth)
936 if (sm->offset < dc->offset)
938 /* starting offset begins in the middle of pt,
939 do not count first bytes as progress */
940 GNUNET_assert (app > (dc->offset - sm->offset));
941 app -= (dc->offset - sm->offset);
943 if (sm->offset + prc->size > dc->offset + dc->length)
945 /* end of block is after relevant range,
946 do not count last bytes as progress */
947 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
948 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
950 dc->completed += app;
952 /* do recursive download if option is set and either meta data
953 says it is a directory or if no meta data is given AND filename
954 ends in '.gnd' (top-level case) */
955 if (is_recursive_download (dc))
956 GNUNET_FS_directory_list_contents (prc->size,
959 &trigger_recursive_download,
963 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
964 pi.value.download.specifics.progress.data = pt;
965 pi.value.download.specifics.progress.offset = sm->offset;
966 pi.value.download.specifics.progress.data_len = prc->size;
967 pi.value.download.specifics.progress.depth = sm->depth;
968 make_download_status (&pi, dc);
969 GNUNET_assert (dc->completed <= dc->length);
970 if (dc->completed == dc->length)
973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974 "Download completed, truncating file to desired length %llu\n",
975 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
977 /* truncate file to size (since we store IBlocks at the end) */
978 if (dc->handle != NULL)
980 GNUNET_DISK_file_close (dc->handle);
982 if (0 != truncate (dc->filename,
983 GNUNET_ntohll (dc->uri->data.chk.file_length)))
984 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
988 if (dc->job_queue != NULL)
990 GNUNET_FS_dequeue_ (dc->job_queue);
991 dc->job_queue = NULL;
993 if (is_recursive_download (dc))
994 full_recursive_download (dc);
995 if (dc->child_head == NULL)
997 /* signal completion */
998 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
999 make_download_status (&pi, dc);
1000 if (dc->parent != NULL)
1001 check_completed (dc->parent);
1003 GNUNET_assert (sm->depth == dc->treedepth);
1005 // FIXME: make persistent
1006 if (sm->depth == dc->treedepth)
1012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1013 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1015 (unsigned long long) sm->offset);
1017 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1018 chk = (struct ContentHashKey*) pt;
1019 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1021 off = compute_dblock_offset (sm->offset,
1025 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1026 (off < dc->offset + dc->length) )
1027 schedule_block_download (dc,
1038 * Process a download result.
1040 * @param dc our download context
1041 * @param type type of the result
1042 * @param data the (encrypted) response
1043 * @param size size of data
1046 process_result (struct GNUNET_FS_DownloadContext *dc,
1047 enum GNUNET_BLOCK_Type type,
1051 struct ProcessResultClosure prc;
1057 prc.do_store = GNUNET_YES;
1058 GNUNET_CRYPTO_hash (data, size, &prc.query);
1060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061 "Received result for query `%s' from `%s'-service\n",
1062 GNUNET_h2s (&prc.query),
1065 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1067 &process_result_with_request,
1073 * Type of a function to call when we receive a message
1076 * @param cls closure
1077 * @param msg message received, NULL on timeout or fatal error
1080 receive_results (void *cls,
1081 const struct GNUNET_MessageHeader * msg)
1083 struct GNUNET_FS_DownloadContext *dc = cls;
1084 const struct PutMessage *cm;
1087 if ( (NULL == msg) ||
1088 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1089 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1091 GNUNET_break (msg == NULL);
1095 msize = ntohs(msg->size);
1096 cm = (const struct PutMessage*) msg;
1100 msize - sizeof (struct PutMessage));
1101 if (dc->client == NULL)
1102 return; /* fatal error */
1103 /* continue receiving */
1104 GNUNET_CLIENT_receive (dc->client,
1107 GNUNET_TIME_UNIT_FOREVER_REL);
1113 * We're ready to transmit a search request to the
1114 * file-sharing service. Do it. If there is
1115 * more than one request pending, try to send
1116 * multiple or request another transmission.
1118 * @param cls closure
1119 * @param size number of bytes available in buf
1120 * @param buf where the callee should write the message
1121 * @return number of bytes written to buf
1124 transmit_download_request (void *cls,
1128 struct GNUNET_FS_DownloadContext *dc = cls;
1130 struct SearchMessage *sm;
1138 GNUNET_assert (size >= sizeof (struct SearchMessage));
1141 while ( (dc->pending != NULL) &&
1142 (size > msize + sizeof (struct SearchMessage)) )
1145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1146 "Transmitting download request for `%s' to `%s'-service\n",
1147 GNUNET_h2s (&dc->pending->chk.query),
1150 memset (sm, 0, sizeof (struct SearchMessage));
1151 sm->header.size = htons (sizeof (struct SearchMessage));
1152 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1153 if (dc->pending->depth == dc->treedepth)
1154 sm->type = htonl (GNUNET_BLOCK_TYPE_DBLOCK);
1156 sm->type = htonl (GNUNET_BLOCK_TYPE_IBLOCK);
1157 sm->anonymity_level = htonl (dc->anonymity);
1158 sm->target = dc->target.hashPubKey;
1159 sm->query = dc->pending->chk.query;
1160 dc->pending->is_pending = GNUNET_NO;
1161 dc->pending = dc->pending->next;
1162 msize += sizeof (struct SearchMessage);
1165 if (dc->pending != NULL)
1166 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1167 sizeof (struct SearchMessage),
1168 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1170 &transmit_download_request,
1177 * Reconnect to the FS service and transmit our queries NOW.
1179 * @param cls our download context
1183 do_reconnect (void *cls,
1184 const struct GNUNET_SCHEDULER_TaskContext *tc)
1186 struct GNUNET_FS_DownloadContext *dc = cls;
1187 struct GNUNET_CLIENT_Connection *client;
1189 dc->task = GNUNET_SCHEDULER_NO_TASK;
1190 client = GNUNET_CLIENT_connect (dc->h->sched,
1195 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1196 "Connecting to `%s'-service failed, will try again.\n",
1201 dc->client = client;
1202 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1203 sizeof (struct SearchMessage),
1204 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1206 &transmit_download_request,
1208 GNUNET_CLIENT_receive (client,
1211 GNUNET_TIME_UNIT_FOREVER_REL);
1216 * Add entries that are not yet pending back to the pending list.
1218 * @param cls our download context
1220 * @param entry entry of type "struct DownloadRequest"
1224 retry_entry (void *cls,
1225 const GNUNET_HashCode *key,
1228 struct GNUNET_FS_DownloadContext *dc = cls;
1229 struct DownloadRequest *dr = entry;
1231 if (! dr->is_pending)
1233 dr->next = dc->pending;
1234 dr->is_pending = GNUNET_YES;
1235 dc->pending = entry;
1242 * We've lost our connection with the FS service.
1243 * Re-establish it and re-transmit all of our
1246 * @param dc download context that is having trouble
1249 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1252 if (NULL != dc->client)
1256 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1259 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1262 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1266 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1267 GNUNET_TIME_UNIT_SECONDS,
1275 * We're allowed to ask the FS service for our blocks. Start the download.
1277 * @param cls the 'struct GNUNET_FS_DownloadContext'
1278 * @param client handle to use for communcation with FS (we must destroy it!)
1281 activate_fs_download (void *cls,
1282 struct GNUNET_CLIENT_Connection *client)
1284 struct GNUNET_FS_DownloadContext *dc = cls;
1285 struct GNUNET_FS_ProgressInfo pi;
1287 GNUNET_assert (NULL != client);
1288 dc->client = client;
1289 GNUNET_CLIENT_receive (client,
1292 GNUNET_TIME_UNIT_FOREVER_REL);
1293 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1294 make_download_status (&pi, dc);
1295 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1298 if ( (dc->th == NULL) &&
1299 (dc->client != NULL) )
1300 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1301 sizeof (struct SearchMessage),
1302 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1304 &transmit_download_request,
1310 * We must stop to ask the FS service for our blocks. Pause the download.
1312 * @param cls the 'struct GNUNET_FS_DownloadContext'
1313 * @param client handle to use for communcation with FS (we must destroy it!)
1316 deactivate_fs_download (void *cls)
1318 struct GNUNET_FS_DownloadContext *dc = cls;
1319 struct GNUNET_FS_ProgressInfo pi;
1323 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1326 if (NULL != dc->client)
1328 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1331 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1332 make_download_status (&pi, dc);
1337 * Download parts of a file. Note that this will store
1338 * the blocks at the respective offset in the given file. Also, the
1339 * download is still using the blocking of the underlying FS
1340 * encoding. As a result, the download may *write* outside of the
1341 * given boundaries (if offset and length do not match the 32k FS
1342 * block boundaries). <p>
1344 * This function should be used to focus a download towards a
1345 * particular portion of the file (optimization), not to strictly
1346 * limit the download to exactly those bytes.
1348 * @param h handle to the file sharing subsystem
1349 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1350 * @param meta known metadata for the file (can be NULL)
1351 * @param filename where to store the file, maybe NULL (then no file is
1352 * created on disk and data must be grabbed from the callbacks)
1353 * @param tempname where to store temporary file data, not used if filename is non-NULL;
1354 * can be NULL (in which case we will pick a name if needed); the temporary file
1355 * may already exist, in which case we will try to use the data that is there and
1356 * if it is not what is desired, will overwrite it
1357 * @param offset at what offset should we start the download (typically 0)
1358 * @param length how many bytes should be downloaded starting at offset
1359 * @param anonymity anonymity level to use for the download
1360 * @param options various options
1361 * @param cctx initial value for the client context for this download
1362 * @param parent parent download to associate this download with (use NULL
1363 * for top-level downloads; useful for manually-triggered recursive downloads)
1364 * @return context that can be used to control this download
1366 struct GNUNET_FS_DownloadContext *
1367 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1368 const struct GNUNET_FS_Uri *uri,
1369 const struct GNUNET_CONTAINER_MetaData *meta,
1370 const char *filename,
1371 const char *tempname,
1375 enum GNUNET_FS_DownloadOptions options,
1377 struct GNUNET_FS_DownloadContext *parent)
1379 struct GNUNET_FS_ProgressInfo pi;
1380 struct GNUNET_FS_DownloadContext *dc;
1382 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1383 if ( (offset + length < offset) ||
1384 (offset + length > uri->data.chk.file_length) )
1389 // FIXME: add support for "loc" URIs!
1391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1392 "Starting download `%s' of %llu bytes\n",
1394 (unsigned long long) length);
1396 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1398 dc->parent = parent;
1401 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1405 dc->uri = GNUNET_FS_uri_dup (uri);
1406 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1407 dc->client_info = cctx;
1408 dc->start_time = GNUNET_TIME_absolute_get ();
1409 if (NULL != filename)
1411 dc->filename = GNUNET_strdup (filename);
1412 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1413 GNUNET_DISK_file_size (filename,
1416 dc->handle = GNUNET_DISK_file_open (filename,
1417 GNUNET_DISK_OPEN_READWRITE |
1418 GNUNET_DISK_OPEN_CREATE,
1419 GNUNET_DISK_PERM_USER_READ |
1420 GNUNET_DISK_PERM_USER_WRITE |
1421 GNUNET_DISK_PERM_GROUP_READ |
1422 GNUNET_DISK_PERM_OTHER_READ);
1423 if (dc->handle == NULL)
1425 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1426 _("Download failed: could not open file `%s': %s\n"),
1429 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1430 GNUNET_FS_uri_destroy (dc->uri);
1431 GNUNET_free (dc->filename);
1436 // FIXME: set "dc->target" for LOC uris!
1437 dc->offset = offset;
1438 dc->length = length;
1439 dc->anonymity = anonymity;
1440 dc->options = options;
1441 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1442 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1443 if ( (filename == NULL) &&
1444 (is_recursive_download (dc) ) )
1446 if (tempname != NULL)
1447 dc->temp_filename = GNUNET_strdup (tempname);
1449 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
1453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1454 "Download tree has depth %u\n",
1457 // FIXME: make persistent
1458 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1459 pi.value.download.specifics.start.meta = meta;
1460 make_download_status (&pi, dc);
1461 schedule_block_download (dc,
1462 &dc->uri->data.chk.chk,
1464 1 /* 0 == CHK, 1 == top */);
1465 dc->job_queue = GNUNET_FS_queue_ (h,
1466 &activate_fs_download,
1467 &deactivate_fs_download,
1469 (length + DBLOCK_SIZE-1) / DBLOCK_SIZE);
1475 * Free entries in the map.
1477 * @param cls unused (NULL)
1479 * @param entry entry of type "struct DownloadRequest" which is freed
1483 free_entry (void *cls,
1484 const GNUNET_HashCode *key,
1487 GNUNET_free (entry);
1493 * Stop a download (aborts if download is incomplete).
1495 * @param dc handle for the download
1496 * @param do_delete delete files of incomplete downloads
1499 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1502 struct GNUNET_FS_ProgressInfo pi;
1504 if (dc->job_queue != NULL)
1506 GNUNET_FS_dequeue_ (dc->job_queue);
1507 dc->job_queue = NULL;
1509 while (NULL != dc->child_head)
1510 GNUNET_FS_download_stop (dc->child_head,
1512 // FIXME: make unpersistent
1513 if (dc->parent != NULL)
1514 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1515 dc->parent->child_tail,
1518 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1519 make_download_status (&pi, dc);
1520 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1521 GNUNET_SCHEDULER_cancel (dc->h->sched,
1523 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1526 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1527 if (dc->filename != NULL)
1529 if (NULL != dc->handle)
1530 GNUNET_DISK_file_close (dc->handle);
1531 if ( (dc->completed != dc->length) &&
1532 (GNUNET_YES == do_delete) )
1534 if (0 != UNLINK (dc->filename))
1535 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1539 GNUNET_free (dc->filename);
1541 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1542 GNUNET_FS_uri_destroy (dc->uri);
1543 if (NULL != dc->temp_filename)
1545 if (0 != UNLINK (dc->temp_filename))
1546 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1549 GNUNET_free (dc->temp_filename);
1554 /* end of fs_download.c */