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 GNUNET_FS_DownloadContext *dc = prc->dc;
830 struct GNUNET_CRYPTO_AesSessionKey skey;
831 struct GNUNET_CRYPTO_AesInitializationVector iv;
833 struct GNUNET_FS_ProgressInfo pi;
838 struct ContentHashKey *chk;
841 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
849 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
853 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
855 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
856 pi.value.download.specifics.error.message = dc->emsg;
857 make_download_status (&pi, dc);
858 /* abort all pending requests */
861 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
864 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
868 GNUNET_assert (GNUNET_YES ==
869 GNUNET_CONTAINER_multihashmap_remove (dc->active,
872 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
873 GNUNET_CRYPTO_aes_decrypt (prc->data,
878 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
883 if ( ( GNUNET_YES == prc->do_store) &&
884 (NULL != dc->handle) &&
885 ( (sm->depth == dc->treedepth) ||
886 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
891 "Saving decrypted block to disk at offset %llu\n",
892 (unsigned long long) off);
895 GNUNET_DISK_file_seek (dc->handle,
897 GNUNET_DISK_SEEK_SET) ) )
898 GNUNET_asprintf (&emsg,
899 _("Failed to seek to offset %llu in file `%s': %s\n"),
900 (unsigned long long) off,
903 else if (prc->size !=
904 GNUNET_DISK_file_write (dc->handle,
907 GNUNET_asprintf (&emsg,
908 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
909 (unsigned int) prc->size,
910 (unsigned long long) off,
916 // FIXME: make persistent
919 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
920 pi.value.download.specifics.error.message = emsg;
921 make_download_status (&pi, dc);
922 /* abort all pending requests */
925 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
928 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
934 if (sm->depth == dc->treedepth)
937 if (sm->offset < dc->offset)
939 /* starting offset begins in the middle of pt,
940 do not count first bytes as progress */
941 GNUNET_assert (app > (dc->offset - sm->offset));
942 app -= (dc->offset - sm->offset);
944 if (sm->offset + prc->size > dc->offset + dc->length)
946 /* end of block is after relevant range,
947 do not count last bytes as progress */
948 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
949 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
951 dc->completed += app;
953 /* do recursive download if option is set and either meta data
954 says it is a directory or if no meta data is given AND filename
955 ends in '.gnd' (top-level case) */
956 if (is_recursive_download (dc))
957 GNUNET_FS_directory_list_contents (prc->size,
960 &trigger_recursive_download,
964 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
965 pi.value.download.specifics.progress.data = pt;
966 pi.value.download.specifics.progress.offset = sm->offset;
967 pi.value.download.specifics.progress.data_len = prc->size;
968 pi.value.download.specifics.progress.depth = sm->depth;
969 make_download_status (&pi, dc);
970 GNUNET_assert (dc->completed <= dc->length);
971 if (dc->completed == dc->length)
974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
975 "Download completed, truncating file to desired length %llu\n",
976 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
978 /* truncate file to size (since we store IBlocks at the end) */
979 if (dc->handle != NULL)
981 GNUNET_DISK_file_close (dc->handle);
983 if (0 != truncate (dc->filename,
984 GNUNET_ntohll (dc->uri->data.chk.file_length)))
985 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
989 if (dc->job_queue != NULL)
991 GNUNET_FS_dequeue_ (dc->job_queue);
992 dc->job_queue = NULL;
994 if (is_recursive_download (dc))
995 full_recursive_download (dc);
996 if (dc->child_head == NULL)
998 /* signal completion */
999 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
1000 make_download_status (&pi, dc);
1001 if (dc->parent != NULL)
1002 check_completed (dc->parent);
1004 GNUNET_assert (sm->depth == dc->treedepth);
1006 // FIXME: make persistent
1007 if (sm->depth == dc->treedepth)
1013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1016 (unsigned long long) sm->offset);
1018 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1019 chk = (struct ContentHashKey*) pt;
1020 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1022 off = compute_dblock_offset (sm->offset,
1026 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1027 (off < dc->offset + dc->length) )
1028 schedule_block_download (dc,
1039 * Process a download result.
1041 * @param dc our download context
1042 * @param type type of the result
1043 * @param data the (encrypted) response
1044 * @param size size of data
1047 process_result (struct GNUNET_FS_DownloadContext *dc,
1048 enum GNUNET_BLOCK_Type type,
1052 struct ProcessResultClosure prc;
1058 prc.do_store = GNUNET_YES;
1059 GNUNET_CRYPTO_hash (data, size, &prc.query);
1061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1062 "Received result for query `%s' from `%s'-service\n",
1063 GNUNET_h2s (&prc.query),
1066 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1068 &process_result_with_request,
1074 * Type of a function to call when we receive a message
1077 * @param cls closure
1078 * @param msg message received, NULL on timeout or fatal error
1081 receive_results (void *cls,
1082 const struct GNUNET_MessageHeader * msg)
1084 struct GNUNET_FS_DownloadContext *dc = cls;
1085 const struct PutMessage *cm;
1088 if ( (NULL == msg) ||
1089 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1090 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1092 GNUNET_break (msg == NULL);
1096 msize = ntohs(msg->size);
1097 cm = (const struct PutMessage*) msg;
1101 msize - sizeof (struct PutMessage));
1102 if (dc->client == NULL)
1103 return; /* fatal error */
1104 /* continue receiving */
1105 GNUNET_CLIENT_receive (dc->client,
1108 GNUNET_TIME_UNIT_FOREVER_REL);
1114 * We're ready to transmit a search request to the
1115 * file-sharing service. Do it. If there is
1116 * more than one request pending, try to send
1117 * multiple or request another transmission.
1119 * @param cls closure
1120 * @param size number of bytes available in buf
1121 * @param buf where the callee should write the message
1122 * @return number of bytes written to buf
1125 transmit_download_request (void *cls,
1129 struct GNUNET_FS_DownloadContext *dc = cls;
1131 struct SearchMessage *sm;
1139 GNUNET_assert (size >= sizeof (struct SearchMessage));
1142 while ( (dc->pending != NULL) &&
1143 (size > msize + sizeof (struct SearchMessage)) )
1146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1147 "Transmitting download request for `%s' to `%s'-service\n",
1148 GNUNET_h2s (&dc->pending->chk.query),
1151 memset (sm, 0, sizeof (struct SearchMessage));
1152 sm->header.size = htons (sizeof (struct SearchMessage));
1153 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1154 if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1155 sm->options = htonl (1);
1157 sm->options = htonl (0);
1158 if (dc->pending->depth == dc->treedepth)
1159 sm->type = htonl (GNUNET_BLOCK_TYPE_DBLOCK);
1161 sm->type = htonl (GNUNET_BLOCK_TYPE_IBLOCK);
1162 sm->anonymity_level = htonl (dc->anonymity);
1163 sm->target = dc->target.hashPubKey;
1164 sm->query = dc->pending->chk.query;
1165 dc->pending->is_pending = GNUNET_NO;
1166 dc->pending = dc->pending->next;
1167 msize += sizeof (struct SearchMessage);
1170 if (dc->pending != NULL)
1171 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1172 sizeof (struct SearchMessage),
1173 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1175 &transmit_download_request,
1182 * Reconnect to the FS service and transmit our queries NOW.
1184 * @param cls our download context
1188 do_reconnect (void *cls,
1189 const struct GNUNET_SCHEDULER_TaskContext *tc)
1191 struct GNUNET_FS_DownloadContext *dc = cls;
1192 struct GNUNET_CLIENT_Connection *client;
1194 dc->task = GNUNET_SCHEDULER_NO_TASK;
1195 client = GNUNET_CLIENT_connect (dc->h->sched,
1200 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1201 "Connecting to `%s'-service failed, will try again.\n",
1206 dc->client = client;
1207 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1208 sizeof (struct SearchMessage),
1209 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1211 &transmit_download_request,
1213 GNUNET_CLIENT_receive (client,
1216 GNUNET_TIME_UNIT_FOREVER_REL);
1221 * Add entries that are not yet pending back to the pending list.
1223 * @param cls our download context
1225 * @param entry entry of type "struct DownloadRequest"
1229 retry_entry (void *cls,
1230 const GNUNET_HashCode *key,
1233 struct GNUNET_FS_DownloadContext *dc = cls;
1234 struct DownloadRequest *dr = entry;
1236 if (! dr->is_pending)
1238 dr->next = dc->pending;
1239 dr->is_pending = GNUNET_YES;
1240 dc->pending = entry;
1247 * We've lost our connection with the FS service.
1248 * Re-establish it and re-transmit all of our
1251 * @param dc download context that is having trouble
1254 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1257 if (NULL != dc->client)
1261 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1264 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1267 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1271 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1272 GNUNET_TIME_UNIT_SECONDS,
1280 * We're allowed to ask the FS service for our blocks. Start the download.
1282 * @param cls the 'struct GNUNET_FS_DownloadContext'
1283 * @param client handle to use for communcation with FS (we must destroy it!)
1286 activate_fs_download (void *cls,
1287 struct GNUNET_CLIENT_Connection *client)
1289 struct GNUNET_FS_DownloadContext *dc = cls;
1290 struct GNUNET_FS_ProgressInfo pi;
1292 GNUNET_assert (NULL != client);
1293 dc->client = client;
1294 GNUNET_CLIENT_receive (client,
1297 GNUNET_TIME_UNIT_FOREVER_REL);
1298 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1299 make_download_status (&pi, dc);
1300 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1303 if ( (dc->th == NULL) &&
1304 (dc->client != NULL) )
1305 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1306 sizeof (struct SearchMessage),
1307 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1309 &transmit_download_request,
1315 * We must stop to ask the FS service for our blocks. Pause the download.
1317 * @param cls the 'struct GNUNET_FS_DownloadContext'
1320 deactivate_fs_download (void *cls)
1322 struct GNUNET_FS_DownloadContext *dc = cls;
1323 struct GNUNET_FS_ProgressInfo pi;
1327 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1330 if (NULL != dc->client)
1332 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1335 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1336 make_download_status (&pi, dc);
1341 * Download parts of a file. Note that this will store
1342 * the blocks at the respective offset in the given file. Also, the
1343 * download is still using the blocking of the underlying FS
1344 * encoding. As a result, the download may *write* outside of the
1345 * given boundaries (if offset and length do not match the 32k FS
1346 * block boundaries). <p>
1348 * This function should be used to focus a download towards a
1349 * particular portion of the file (optimization), not to strictly
1350 * limit the download to exactly those bytes.
1352 * @param h handle to the file sharing subsystem
1353 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1354 * @param meta known metadata for the file (can be NULL)
1355 * @param filename where to store the file, maybe NULL (then no file is
1356 * created on disk and data must be grabbed from the callbacks)
1357 * @param tempname where to store temporary file data, not used if filename is non-NULL;
1358 * can be NULL (in which case we will pick a name if needed); the temporary file
1359 * may already exist, in which case we will try to use the data that is there and
1360 * if it is not what is desired, will overwrite it
1361 * @param offset at what offset should we start the download (typically 0)
1362 * @param length how many bytes should be downloaded starting at offset
1363 * @param anonymity anonymity level to use for the download
1364 * @param options various options
1365 * @param cctx initial value for the client context for this download
1366 * @param parent parent download to associate this download with (use NULL
1367 * for top-level downloads; useful for manually-triggered recursive downloads)
1368 * @return context that can be used to control this download
1370 struct GNUNET_FS_DownloadContext *
1371 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1372 const struct GNUNET_FS_Uri *uri,
1373 const struct GNUNET_CONTAINER_MetaData *meta,
1374 const char *filename,
1375 const char *tempname,
1379 enum GNUNET_FS_DownloadOptions options,
1381 struct GNUNET_FS_DownloadContext *parent)
1383 struct GNUNET_FS_ProgressInfo pi;
1384 struct GNUNET_FS_DownloadContext *dc;
1386 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1387 if ( (offset + length < offset) ||
1388 (offset + length > uri->data.chk.file_length) )
1393 // FIXME: add support for "loc" URIs!
1395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1396 "Starting download `%s' of %llu bytes\n",
1398 (unsigned long long) length);
1400 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1402 dc->parent = parent;
1405 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1409 dc->uri = GNUNET_FS_uri_dup (uri);
1410 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1411 dc->client_info = cctx;
1412 dc->start_time = GNUNET_TIME_absolute_get ();
1413 if (NULL != filename)
1415 dc->filename = GNUNET_strdup (filename);
1416 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1417 GNUNET_DISK_file_size (filename,
1420 dc->handle = GNUNET_DISK_file_open (filename,
1421 GNUNET_DISK_OPEN_READWRITE |
1422 GNUNET_DISK_OPEN_CREATE,
1423 GNUNET_DISK_PERM_USER_READ |
1424 GNUNET_DISK_PERM_USER_WRITE |
1425 GNUNET_DISK_PERM_GROUP_READ |
1426 GNUNET_DISK_PERM_OTHER_READ);
1427 if (dc->handle == NULL)
1429 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1430 _("Download failed: could not open file `%s': %s\n"),
1433 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1434 GNUNET_FS_uri_destroy (dc->uri);
1435 GNUNET_free (dc->filename);
1440 // FIXME: set "dc->target" for LOC uris!
1441 dc->offset = offset;
1442 dc->length = length;
1443 dc->anonymity = anonymity;
1444 dc->options = options;
1445 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1446 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1447 if ( (filename == NULL) &&
1448 (is_recursive_download (dc) ) )
1450 if (tempname != NULL)
1451 dc->temp_filename = GNUNET_strdup (tempname);
1453 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
1457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1458 "Download tree has depth %u\n",
1461 // FIXME: make persistent
1462 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1463 pi.value.download.specifics.start.meta = meta;
1464 make_download_status (&pi, dc);
1465 schedule_block_download (dc,
1466 &dc->uri->data.chk.chk,
1468 1 /* 0 == CHK, 1 == top */);
1469 dc->job_queue = GNUNET_FS_queue_ (h,
1470 &activate_fs_download,
1471 &deactivate_fs_download,
1473 (length + DBLOCK_SIZE-1) / DBLOCK_SIZE);
1479 * Free entries in the map.
1481 * @param cls unused (NULL)
1483 * @param entry entry of type "struct DownloadRequest" which is freed
1487 free_entry (void *cls,
1488 const GNUNET_HashCode *key,
1491 GNUNET_free (entry);
1497 * Stop a download (aborts if download is incomplete).
1499 * @param dc handle for the download
1500 * @param do_delete delete files of incomplete downloads
1503 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1506 struct GNUNET_FS_ProgressInfo pi;
1508 if (dc->job_queue != NULL)
1510 GNUNET_FS_dequeue_ (dc->job_queue);
1511 dc->job_queue = NULL;
1513 while (NULL != dc->child_head)
1514 GNUNET_FS_download_stop (dc->child_head,
1516 // FIXME: make unpersistent
1517 if (dc->parent != NULL)
1518 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1519 dc->parent->child_tail,
1522 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1523 make_download_status (&pi, dc);
1524 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1525 GNUNET_SCHEDULER_cancel (dc->h->sched,
1527 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1530 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1531 if (dc->filename != NULL)
1533 if (NULL != dc->handle)
1534 GNUNET_DISK_file_close (dc->handle);
1535 if ( (dc->completed != dc->length) &&
1536 (GNUNET_YES == do_delete) )
1538 if (0 != UNLINK (dc->filename))
1539 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1543 GNUNET_free (dc->filename);
1545 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1546 GNUNET_FS_uri_destroy (dc->uri);
1547 if (NULL != dc->temp_filename)
1549 if (0 != UNLINK (dc->temp_filename))
1550 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1553 GNUNET_free (dc->temp_filename);
1558 /* end of fs_download.c */