2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file fs/fs_download.c
22 * @brief download methods
23 * @author Christian Grothoff
26 * - handle recursive downloads (need directory &
27 * fs-level download-parallelism management)
28 * - location URI suppport (can wait, easy)
29 * - check if blocks exist already (can wait, easy)
30 * - check if iblocks can be computed from existing blocks (can wait, hard)
31 * - persistence (can wait)
34 #include "gnunet_constants.h"
35 #include "gnunet_fs_service.h"
39 #define DEBUG_DOWNLOAD GNUNET_NO
42 * Determine if the given download (options and meta data) should cause
43 * use to try to do a recursive download.
46 is_recursive_download (struct GNUNET_FS_DownloadContext *dc)
48 return (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
49 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
50 ( (dc->meta == NULL) &&
51 ( (NULL == dc->filename) ||
52 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
54 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
55 GNUNET_FS_DIRECTORY_EXT)) ) ) ) );
60 * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
61 * only have to truncate the file once we're done).
63 * Given the offset of a block (with respect to the DBLOCKS) and its
64 * depth, return the offset where we would store this block in the
67 * @param fsize overall file size
68 * @param off offset of the block in the file
69 * @param depth depth of the block in the tree
70 * @param treedepth maximum depth of the tree
71 * @return off for DBLOCKS (depth == treedepth),
72 * otherwise an offset past the end
73 * of the file that does not overlap
74 * with the range for any other block
77 compute_disk_offset (uint64_t fsize,
80 unsigned int treedepth)
83 uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
84 uint64_t loff; /* where do IBlocks for depth "i" start? */
85 unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
87 if (depth == treedepth)
89 /* first IBlocks start at the end of file, rounded up
90 to full DBLOCK_SIZE */
91 loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
92 lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
93 GNUNET_assert (0 == (off % DBLOCK_SIZE));
94 ioff = (off / DBLOCK_SIZE);
95 for (i=treedepth-1;i>depth;i--)
98 lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
99 GNUNET_assert (lsize > 0);
100 GNUNET_assert (0 == (ioff % CHK_PER_INODE));
101 ioff /= CHK_PER_INODE;
103 return loff + ioff * sizeof (struct ContentHashKey);
108 * Given a file of the specified treedepth and a block at the given
109 * offset and depth, calculate the offset for the CHK at the given
112 * @param offset the offset of the first
113 * DBLOCK in the subtree of the
115 * @param depth the depth of the IBLOCK in the tree
116 * @param treedepth overall depth of the tree
117 * @param k which CHK in the IBLOCK are we
119 * @return offset if k=0, otherwise an appropriately
120 * larger value (i.e., if depth = treedepth-1,
121 * the returned value should be offset+DBLOCK_SIZE)
124 compute_dblock_offset (uint64_t offset,
126 unsigned int treedepth,
130 uint64_t lsize; /* what is the size of the sum of all DBlocks
131 that a CHK at depth i corresponds to? */
133 if (depth == treedepth)
136 for (i=treedepth-1;i>depth;i--)
137 lsize *= CHK_PER_INODE;
138 return offset + k * lsize;
143 * Fill in all of the generic fields for
146 * @param pi structure to fill in
147 * @param dc overall download context
150 make_download_status (struct GNUNET_FS_ProgressInfo *pi,
151 struct GNUNET_FS_DownloadContext *dc)
153 pi->value.download.dc = dc;
154 pi->value.download.cctx
156 pi->value.download.pctx
157 = (dc->parent == NULL) ? NULL : dc->parent->client_info;
158 pi->value.download.uri
160 pi->value.download.filename
162 pi->value.download.size
164 pi->value.download.duration
165 = GNUNET_TIME_absolute_get_duration (dc->start_time);
166 pi->value.download.completed
168 pi->value.download.anonymity
170 pi->value.download.eta
171 = GNUNET_TIME_calculate_eta (dc->start_time,
177 * We're ready to transmit a search request to the
178 * file-sharing service. Do it. If there is
179 * more than one request pending, try to send
180 * multiple or request another transmission.
183 * @param size number of bytes available in buf
184 * @param buf where the callee should write the message
185 * @return number of bytes written to buf
188 transmit_download_request (void *cls,
194 * Closure for iterator processing results.
196 struct ProcessResultClosure
202 GNUNET_HashCode query;
205 * Data found in P2P network.
210 * Our download context.
212 struct GNUNET_FS_DownloadContext *dc;
215 * Number of bytes in data.
225 * Flag to indicate if this block should be stored on disk.
233 * Iterator over entries in the pending requests in the 'active' map for the
234 * reply that we just got.
236 * @param cls closure (our 'struct ProcessResultClosure')
237 * @param key query for the given value / request
238 * @param value value in the hash map (a 'struct DownloadRequest')
239 * @return GNUNET_YES (we should continue to iterate); unless serious error
242 process_result_with_request (void *cls,
243 const GNUNET_HashCode * key,
249 * Schedule the download of the specified block in the tree.
251 * @param dc overall download this block belongs to
252 * @param chk content-hash-key of the block
253 * @param offset offset of the block in the file
254 * (for IBlocks, the offset is the lowest
255 * offset of any DBlock in the subtree under
257 * @param depth depth of the block, 0 is the root of the tree
260 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
261 const struct ContentHashKey *chk,
265 struct DownloadRequest *sm;
269 char block[DBLOCK_SIZE];
271 struct ProcessResultClosure prc;
274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
275 "Scheduling download at offset %llu and depth %u for `%s'\n",
276 (unsigned long long) offset,
278 GNUNET_h2s (&chk->query));
280 total = GNUNET_ntohll (dc->uri->data.chk.file_length);
281 off = compute_disk_offset (total,
285 len = GNUNET_FS_tree_calculate_block_size (total,
289 sm = GNUNET_malloc (sizeof (struct DownloadRequest));
293 sm->is_pending = GNUNET_YES;
294 sm->next = dc->pending;
296 GNUNET_CONTAINER_multihashmap_put (dc->active,
299 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
301 if ( (dc->old_file_size > off) &&
302 (dc->handle != NULL) &&
304 GNUNET_DISK_file_seek (dc->handle,
306 GNUNET_DISK_SEEK_SET) ) &&
308 GNUNET_DISK_file_read (dc->handle,
312 if (0 == memcmp (&key,
314 sizeof (GNUNET_HashCode)))
317 struct GNUNET_CRYPTO_AesSessionKey sk;
318 struct GNUNET_CRYPTO_AesInitializationVector iv;
319 GNUNET_HashCode query;
321 GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
322 GNUNET_CRYPTO_aes_encrypt (block, len,
326 GNUNET_CRYPTO_hash (enc, len, &query);
327 if (0 == memcmp (&query,
329 sizeof (GNUNET_HashCode)))
331 /* already got it! */
335 prc.type = (dc->treedepth == depth)
336 ? GNUNET_DATASTORE_BLOCKTYPE_DBLOCK
337 : GNUNET_DATASTORE_BLOCKTYPE_IBLOCK;
338 prc.query = chk->query;
339 prc.do_store = GNUNET_NO; /* useless */
340 process_result_with_request (&prc,
351 if (depth < dc->treedepth)
353 // FIXME: try if we could
354 // reconstitute this IBLOCK
355 // from the existing blocks on disk (can wait)
356 // (read block(s), encode, compare with
357 // query; if matches, simply return)
360 if ( (dc->th == NULL) &&
361 (dc->client != NULL) )
362 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
363 sizeof (struct SearchMessage),
364 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
366 &transmit_download_request,
373 * Suggest a filename based on given metadata.
375 * @param md given meta data
376 * @return NULL if meta data is useless for suggesting a filename
379 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
381 static const char *mimeMap[][2] = {
382 {"application/bz2", ".bz2"},
383 {"application/gnunet-directory", ".gnd"},
384 {"application/java", ".class"},
385 {"application/msword", ".doc"},
386 {"application/ogg", ".ogg"},
387 {"application/pdf", ".pdf"},
388 {"application/pgp-keys", ".key"},
389 {"application/pgp-signature", ".pgp"},
390 {"application/postscript", ".ps"},
391 {"application/rar", ".rar"},
392 {"application/rtf", ".rtf"},
393 {"application/xml", ".xml"},
394 {"application/x-debian-package", ".deb"},
395 {"application/x-dvi", ".dvi"},
396 {"applixation/x-flac", ".flac"},
397 {"applixation/x-gzip", ".gz"},
398 {"application/x-java-archive", ".jar"},
399 {"application/x-java-vm", ".class"},
400 {"application/x-python-code", ".pyc"},
401 {"application/x-redhat-package-manager", ".rpm"},
402 {"application/x-rpm", ".rpm"},
403 {"application/x-tar", ".tar"},
404 {"application/x-tex-pk", ".pk"},
405 {"application/x-texinfo", ".texinfo"},
406 {"application/x-xcf", ".xcf"},
407 {"application/x-xfig", ".xfig"},
408 {"application/zip", ".zip"},
410 {"audio/midi", ".midi"},
411 {"audio/mpeg", ".mp3"},
412 {"audio/real", ".rm"},
413 {"audio/x-wav", ".wav"},
415 {"image/gif", ".gif"},
416 {"image/jpeg", ".jpg"},
417 {"image/pcx", ".pcx"},
418 {"image/png", ".png"},
419 {"image/tiff", ".tiff"},
420 {"image/x-ms-bmp", ".bmp"},
421 {"image/x-xpixmap", ".xpm"},
423 {"text/css", ".css"},
424 {"text/html", ".html"},
425 {"text/plain", ".txt"},
426 {"text/rtf", ".rtf"},
427 {"text/x-c++hdr", ".h++"},
428 {"text/x-c++src", ".c++"},
429 {"text/x-chdr", ".h"},
430 {"text/x-csrc", ".c"},
431 {"text/x-java", ".java"},
432 {"text/x-moc", ".moc"},
433 {"text/x-pascal", ".pas"},
434 {"text/x-perl", ".pl"},
435 {"text/x-python", ".py"},
436 {"text/x-tex", ".tex"},
438 {"video/avi", ".avi"},
439 {"video/mpeg", ".mpeg"},
440 {"video/quicktime", ".qt"},
441 {"video/real", ".rm"},
442 {"video/x-msvideo", ".avi"},
451 ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
452 EXTRACTOR_METATYPE_FILENAME);
456 mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
457 EXTRACTOR_METATYPE_MIMETYPE);
461 while ( (mimeMap[i][0] != NULL) &&
462 (0 != strcmp (mime, mimeMap[i][0])))
464 if (mimeMap[i][1] == NULL)
465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
466 GNUNET_ERROR_TYPE_BULK,
467 _("Did not find mime type `%s' in extension list.\n"),
473 base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
474 EXTRACTOR_METATYPE_TITLE,
475 EXTRACTOR_METATYPE_BOOK_TITLE,
476 EXTRACTOR_METATYPE_ORIGINAL_TITLE,
477 EXTRACTOR_METATYPE_PACKAGE_NAME,
478 EXTRACTOR_METATYPE_URL,
479 EXTRACTOR_METATYPE_URI,
480 EXTRACTOR_METATYPE_DESCRIPTION,
481 EXTRACTOR_METATYPE_ISRC,
482 EXTRACTOR_METATYPE_JOURNAL_NAME,
483 EXTRACTOR_METATYPE_AUTHOR_NAME,
484 EXTRACTOR_METATYPE_SUBJECT,
485 EXTRACTOR_METATYPE_ALBUM,
486 EXTRACTOR_METATYPE_ARTIST,
487 EXTRACTOR_METATYPE_KEYWORDS,
488 EXTRACTOR_METATYPE_COMMENT,
489 EXTRACTOR_METATYPE_UNKNOWN,
491 if ( (base == NULL) &&
495 return GNUNET_strdup (ext);
498 GNUNET_asprintf (&ret,
508 * We've lost our connection with the FS service.
509 * Re-establish it and re-transmit all of our
512 * @param dc download context that is having trouble
515 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
519 * We found an entry in a directory. Check if the respective child
520 * already exists and if not create the respective child download.
522 * @param cls the parent download
523 * @param filename name of the file in the directory
524 * @param uri URI of the file (CHK or LOC)
525 * @param meta meta data of the file
526 * @param length number of bytes in data
527 * @param data contents of the file (or NULL if they were not inlined)
530 trigger_recursive_download (void *cls,
531 const char *filename,
532 const struct GNUNET_FS_Uri *uri,
533 const struct GNUNET_CONTAINER_MetaData *meta,
537 struct GNUNET_FS_DownloadContext *dc = cls;
538 struct GNUNET_FS_DownloadContext *cpos;
539 struct GNUNET_DISK_FileHandle *fh;
547 return; /* entry for the directory itself */
548 cpos = dc->child_head;
551 if ( (GNUNET_FS_uri_test_equal (uri,
553 ( (filename != NULL) &&
554 (0 == strcmp (cpos->filename,
560 return; /* already exists */
562 if (NULL == filename)
564 fn = GNUNET_FS_meta_data_suggest_filename (meta);
567 us = GNUNET_FS_uri_to_string (uri);
568 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
569 GNUNET_FS_URI_CHK_INFIX)]);
572 else if (fn[0] == '.')
575 us = GNUNET_FS_uri_to_string (uri);
576 GNUNET_asprintf (&fn,
578 &us[strlen (GNUNET_FS_URI_PREFIX
579 GNUNET_FS_URI_CHK_INFIX)], ext);
585 if (dc->filename == NULL)
591 dn = GNUNET_strdup (dc->filename);
592 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
594 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
595 GNUNET_FS_DIRECTORY_EXT)) );
596 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
598 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
599 GNUNET_FS_DIRECTORY_EXT)) )
600 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
601 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
602 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
604 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
605 GNUNET_FS_DIRECTORY_EXT)) ) )
607 GNUNET_asprintf (&full_name,
612 GNUNET_FS_DIRECTORY_EXT);
616 GNUNET_asprintf (&full_name,
624 if ( (full_name != NULL) &&
626 GNUNET_DISK_directory_create_for_file (full_name)) )
628 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
629 _("Failed to create directory for recursive download of `%s'\n"),
631 GNUNET_free (full_name);
632 GNUNET_free_non_null (fn);
638 if (full_name != NULL)
640 fh = GNUNET_DISK_file_open (full_name,
641 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
642 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
645 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
648 GNUNET_free (full_name);
649 GNUNET_free_non_null (fn);
653 GNUNET_DISK_file_write (fh,
657 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
661 GNUNET_DISK_file_close (fh);
665 /* FIXME: generate 'progress' events and move to
666 instant completion! */
667 GNUNET_break (0); // FIXME: not implemented
670 GNUNET_FS_download_start (dc->h,
675 GNUNET_FS_uri_chk_get_file_size (uri),
680 GNUNET_free_non_null (full_name);
681 GNUNET_free_non_null (fn);
686 * We're done downloading a directory. Open the file and
687 * trigger all of the (remaining) child downloads.
689 * @param dc context of download that just completed
692 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
697 struct GNUNET_DISK_FileHandle *h;
698 struct GNUNET_DISK_MapHandle *m;
700 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
701 size = (size_t) size64;
702 if (size64 != (uint64_t) size)
704 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
705 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
708 if (dc->filename != NULL)
710 h = GNUNET_DISK_file_open (dc->filename,
711 GNUNET_DISK_OPEN_READ,
712 GNUNET_DISK_PERM_NONE);
716 GNUNET_assert (dc->temp_filename != NULL);
717 h = GNUNET_DISK_file_open (dc->temp_filename,
718 GNUNET_DISK_OPEN_READ,
719 GNUNET_DISK_PERM_NONE);
723 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
726 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
727 _("Directory too large for system address space\n"));
731 GNUNET_FS_directory_list_contents (size,
734 &trigger_recursive_download,
736 GNUNET_DISK_file_unmap (m);
738 GNUNET_DISK_file_close (h);
739 if (dc->filename == NULL)
741 if (0 != UNLINK (dc->temp_filename))
742 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
745 GNUNET_free (dc->temp_filename);
746 dc->temp_filename = NULL;
752 * Check if all child-downloads have completed and
753 * if so, signal completion (and possibly recurse to
757 check_completed (struct GNUNET_FS_DownloadContext *dc)
759 struct GNUNET_FS_ProgressInfo pi;
760 struct GNUNET_FS_DownloadContext *pos;
762 pos = dc->child_head;
765 if ( (pos->emsg == NULL) &&
766 (pos->completed < pos->length) )
767 return; /* not done yet */
768 if ( (pos->child_head != NULL) &&
769 (pos->has_finished != GNUNET_YES) )
770 return; /* not transitively done yet */
773 dc->has_finished = GNUNET_YES;
774 /* signal completion */
775 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
776 make_download_status (&pi, dc);
777 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
779 if (dc->parent != NULL)
780 check_completed (dc->parent);
785 * Iterator over entries in the pending requests in the 'active' map for the
786 * reply that we just got.
788 * @param cls closure (our 'struct ProcessResultClosure')
789 * @param key query for the given value / request
790 * @param value value in the hash map (a 'struct DownloadRequest')
791 * @return GNUNET_YES (we should continue to iterate); unless serious error
794 process_result_with_request (void *cls,
795 const GNUNET_HashCode * key,
798 struct ProcessResultClosure *prc = cls;
799 struct DownloadRequest *sm = value;
800 struct GNUNET_FS_DownloadContext *dc = prc->dc;
801 struct GNUNET_CRYPTO_AesSessionKey skey;
802 struct GNUNET_CRYPTO_AesInitializationVector iv;
804 struct GNUNET_FS_ProgressInfo pi;
809 struct ContentHashKey *chk;
812 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
824 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
826 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
827 make_download_status (&pi, dc);
828 pi.value.download.specifics.error.message = dc->emsg;
829 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
831 /* abort all pending requests */
834 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
837 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
841 GNUNET_assert (GNUNET_YES ==
842 GNUNET_CONTAINER_multihashmap_remove (dc->active,
845 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
846 GNUNET_CRYPTO_aes_decrypt (prc->data,
851 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
856 if ( ( GNUNET_YES == prc->do_store) &&
857 (NULL != dc->handle) &&
858 ( (sm->depth == dc->treedepth) ||
859 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864 "Saving decrypted block to disk at offset %llu\n",
865 (unsigned long long) off);
868 GNUNET_DISK_file_seek (dc->handle,
870 GNUNET_DISK_SEEK_SET) ) )
871 GNUNET_asprintf (&emsg,
872 _("Failed to seek to offset %llu in file `%s': %s\n"),
873 (unsigned long long) off,
876 else if (prc->size !=
877 GNUNET_DISK_file_write (dc->handle,
880 GNUNET_asprintf (&emsg,
881 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
882 (unsigned int) prc->size,
883 (unsigned long long) off,
889 // FIXME: make persistent
892 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
893 make_download_status (&pi, dc);
894 pi.value.download.specifics.error.message = emsg;
895 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
898 /* abort all pending requests */
901 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
904 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
910 if (sm->depth == dc->treedepth)
913 if (sm->offset < dc->offset)
915 /* starting offset begins in the middle of pt,
916 do not count first bytes as progress */
917 GNUNET_assert (app > (dc->offset - sm->offset));
918 app -= (dc->offset - sm->offset);
920 if (sm->offset + prc->size > dc->offset + dc->length)
922 /* end of block is after relevant range,
923 do not count last bytes as progress */
924 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
925 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
927 dc->completed += app;
929 /* do recursive download if option is set and either meta data
930 says it is a directory or if no meta data is given AND filename
931 ends in '.gnd' (top-level case) */
932 if (is_recursive_download (dc))
933 GNUNET_FS_directory_list_contents (prc->size,
936 &trigger_recursive_download,
940 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
941 make_download_status (&pi, dc);
942 pi.value.download.specifics.progress.data = pt;
943 pi.value.download.specifics.progress.offset = sm->offset;
944 pi.value.download.specifics.progress.data_len = prc->size;
945 pi.value.download.specifics.progress.depth = sm->depth;
946 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
948 GNUNET_assert (dc->completed <= dc->length);
949 if (dc->completed == dc->length)
952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
953 "Download completed, truncating file to desired length %llu\n",
954 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
956 /* truncate file to size (since we store IBlocks at the end) */
957 if (dc->handle != NULL)
959 GNUNET_DISK_file_close (dc->handle);
961 if (0 != truncate (dc->filename,
962 GNUNET_ntohll (dc->uri->data.chk.file_length)))
963 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
968 if (is_recursive_download (dc))
969 full_recursive_download (dc);
970 if (dc->child_head == NULL)
972 /* signal completion */
973 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
974 make_download_status (&pi, dc);
975 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
977 if (dc->parent != NULL)
978 check_completed (dc->parent);
980 GNUNET_assert (sm->depth == dc->treedepth);
982 // FIXME: make persistent
983 if (sm->depth == dc->treedepth)
989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
992 (unsigned long long) sm->offset);
994 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
995 chk = (struct ContentHashKey*) pt;
996 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
998 off = compute_dblock_offset (sm->offset,
1002 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1003 (off < dc->offset + dc->length) )
1004 schedule_block_download (dc,
1015 * Process a download result.
1017 * @param dc our download context
1018 * @param type type of the result
1019 * @param data the (encrypted) response
1020 * @param size size of data
1023 process_result (struct GNUNET_FS_DownloadContext *dc,
1028 struct ProcessResultClosure prc;
1034 prc.do_store = GNUNET_YES;
1035 GNUNET_CRYPTO_hash (data, size, &prc.query);
1037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038 "Received result for query `%s' from `%s'-service\n",
1039 GNUNET_h2s (&prc.query),
1042 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1044 &process_result_with_request,
1050 * Type of a function to call when we receive a message
1053 * @param cls closure
1054 * @param msg message received, NULL on timeout or fatal error
1057 receive_results (void *cls,
1058 const struct GNUNET_MessageHeader * msg)
1060 struct GNUNET_FS_DownloadContext *dc = cls;
1061 const struct PutMessage *cm;
1064 if ( (NULL == msg) ||
1065 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1066 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1068 GNUNET_break (msg == NULL);
1072 msize = ntohs(msg->size);
1073 cm = (const struct PutMessage*) msg;
1077 msize - sizeof (struct PutMessage));
1078 if (dc->client == NULL)
1079 return; /* fatal error */
1080 /* continue receiving */
1081 GNUNET_CLIENT_receive (dc->client,
1084 GNUNET_TIME_UNIT_FOREVER_REL);
1090 * We're ready to transmit a search request to the
1091 * file-sharing service. Do it. If there is
1092 * more than one request pending, try to send
1093 * multiple or request another transmission.
1095 * @param cls closure
1096 * @param size number of bytes available in buf
1097 * @param buf where the callee should write the message
1098 * @return number of bytes written to buf
1101 transmit_download_request (void *cls,
1105 struct GNUNET_FS_DownloadContext *dc = cls;
1107 struct SearchMessage *sm;
1115 GNUNET_assert (size >= sizeof (struct SearchMessage));
1118 while ( (dc->pending != NULL) &&
1119 (size > msize + sizeof (struct SearchMessage)) )
1122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123 "Transmitting download request for `%s' to `%s'-service\n",
1124 GNUNET_h2s (&dc->pending->chk.query),
1127 memset (sm, 0, sizeof (struct SearchMessage));
1128 sm->header.size = htons (sizeof (struct SearchMessage));
1129 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1130 if (dc->pending->depth == dc->treedepth)
1131 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
1133 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
1134 sm->anonymity_level = htonl (dc->anonymity);
1135 sm->target = dc->target.hashPubKey;
1136 sm->query = dc->pending->chk.query;
1137 dc->pending->is_pending = GNUNET_NO;
1138 dc->pending = dc->pending->next;
1139 msize += sizeof (struct SearchMessage);
1142 if (dc->pending != NULL)
1143 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1144 sizeof (struct SearchMessage),
1145 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1147 &transmit_download_request,
1154 * Reconnect to the FS service and transmit our queries NOW.
1156 * @param cls our download context
1160 do_reconnect (void *cls,
1161 const struct GNUNET_SCHEDULER_TaskContext *tc)
1163 struct GNUNET_FS_DownloadContext *dc = cls;
1164 struct GNUNET_CLIENT_Connection *client;
1166 dc->task = GNUNET_SCHEDULER_NO_TASK;
1167 client = GNUNET_CLIENT_connect (dc->h->sched,
1172 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1173 "Connecting to `%s'-service failed, will try again.\n",
1178 dc->client = client;
1179 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1180 sizeof (struct SearchMessage),
1181 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1183 &transmit_download_request,
1185 GNUNET_CLIENT_receive (client,
1188 GNUNET_TIME_UNIT_FOREVER_REL);
1193 * Add entries that are not yet pending back to the pending list.
1195 * @param cls our download context
1197 * @param entry entry of type "struct DownloadRequest"
1201 retry_entry (void *cls,
1202 const GNUNET_HashCode *key,
1205 struct GNUNET_FS_DownloadContext *dc = cls;
1206 struct DownloadRequest *dr = entry;
1208 if (! dr->is_pending)
1210 dr->next = dc->pending;
1211 dr->is_pending = GNUNET_YES;
1212 dc->pending = entry;
1219 * We've lost our connection with the FS service.
1220 * Re-establish it and re-transmit all of our
1223 * @param dc download context that is having trouble
1226 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1229 if (NULL != dc->client)
1233 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1236 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1239 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1243 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1244 GNUNET_TIME_UNIT_SECONDS,
1251 * Download parts of a file. Note that this will store
1252 * the blocks at the respective offset in the given file. Also, the
1253 * download is still using the blocking of the underlying FS
1254 * encoding. As a result, the download may *write* outside of the
1255 * given boundaries (if offset and length do not match the 32k FS
1256 * block boundaries). <p>
1258 * This function should be used to focus a download towards a
1259 * particular portion of the file (optimization), not to strictly
1260 * limit the download to exactly those bytes.
1262 * @param h handle to the file sharing subsystem
1263 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1264 * @param meta known metadata for the file (can be NULL)
1265 * @param filename where to store the file, maybe NULL (then no file is
1266 * created on disk and data must be grabbed from the callbacks)
1267 * @param offset at what offset should we start the download (typically 0)
1268 * @param length how many bytes should be downloaded starting at offset
1269 * @param anonymity anonymity level to use for the download
1270 * @param options various options
1271 * @param cctx initial value for the client context for this download
1272 * @param parent parent download to associate this download with (use NULL
1273 * for top-level downloads; useful for manually-triggered recursive downloads)
1274 * @return context that can be used to control this download
1276 struct GNUNET_FS_DownloadContext *
1277 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1278 const struct GNUNET_FS_Uri *uri,
1279 const struct GNUNET_CONTAINER_MetaData *meta,
1280 const char *filename,
1284 enum GNUNET_FS_DownloadOptions options,
1286 struct GNUNET_FS_DownloadContext *parent)
1288 struct GNUNET_FS_ProgressInfo pi;
1289 struct GNUNET_FS_DownloadContext *dc;
1290 struct GNUNET_CLIENT_Connection *client;
1292 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1293 if ( (offset + length < offset) ||
1294 (offset + length > uri->data.chk.file_length) )
1299 // FIXME: add support for "loc" URIs!
1301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1302 "Starting download `%s' of %llu bytes\n",
1304 (unsigned long long) length);
1306 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1308 dc->parent = parent;
1311 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1315 dc->uri = GNUNET_FS_uri_dup (uri);
1316 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1317 dc->client_info = cctx;
1318 dc->start_time = GNUNET_TIME_absolute_get ();
1319 if (NULL != filename)
1321 dc->filename = GNUNET_strdup (filename);
1322 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1323 GNUNET_DISK_file_size (filename,
1326 dc->handle = GNUNET_DISK_file_open (filename,
1327 GNUNET_DISK_OPEN_READWRITE |
1328 GNUNET_DISK_OPEN_CREATE,
1329 GNUNET_DISK_PERM_USER_READ |
1330 GNUNET_DISK_PERM_USER_WRITE |
1331 GNUNET_DISK_PERM_GROUP_READ |
1332 GNUNET_DISK_PERM_OTHER_READ);
1333 if (dc->handle == NULL)
1335 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1336 _("Download failed: could not open file `%s': %s\n"),
1339 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1340 GNUNET_FS_uri_destroy (dc->uri);
1341 GNUNET_free (dc->filename);
1346 // FIXME: set "dc->target" for LOC uris!
1347 dc->offset = offset;
1348 dc->length = length;
1349 dc->anonymity = anonymity;
1350 dc->options = options;
1351 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1352 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1353 if ( (filename == NULL) &&
1354 (is_recursive_download (dc) ) )
1355 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
1358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359 "Download tree has depth %u\n",
1362 // FIXME: make persistent
1364 // FIXME: bound parallelism here!
1365 client = GNUNET_CLIENT_connect (h->sched,
1368 dc->client = client;
1369 schedule_block_download (dc,
1370 &dc->uri->data.chk.chk,
1372 1 /* 0 == CHK, 1 == top */);
1373 GNUNET_CLIENT_receive (client,
1376 GNUNET_TIME_UNIT_FOREVER_REL);
1377 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1378 make_download_status (&pi, dc);
1379 pi.value.download.specifics.start.meta = meta;
1380 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1388 * Free entries in the map.
1390 * @param cls unused (NULL)
1392 * @param entry entry of type "struct DownloadRequest" which is freed
1396 free_entry (void *cls,
1397 const GNUNET_HashCode *key,
1400 GNUNET_free (entry);
1406 * Stop a download (aborts if download is incomplete).
1408 * @param dc handle for the download
1409 * @param do_delete delete files of incomplete downloads
1412 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1415 struct GNUNET_FS_ProgressInfo pi;
1417 while (NULL != dc->child_head)
1418 GNUNET_FS_download_stop (dc->child_head,
1420 // FIXME: make unpersistent
1421 if (dc->parent != NULL)
1422 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1423 dc->parent->child_tail,
1426 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1427 make_download_status (&pi, dc);
1428 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1431 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1432 GNUNET_SCHEDULER_cancel (dc->h->sched,
1436 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1439 if (NULL != dc->client)
1440 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1441 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1444 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1445 if (dc->filename != NULL)
1447 if (NULL != dc->handle)
1448 GNUNET_DISK_file_close (dc->handle);
1449 if ( (dc->completed != dc->length) &&
1450 (GNUNET_YES == do_delete) )
1452 if (0 != UNLINK (dc->filename))
1453 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1457 GNUNET_free (dc->filename);
1459 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1460 GNUNET_FS_uri_destroy (dc->uri);
1461 if (NULL != dc->temp_filename)
1463 if (0 != UNLINK (dc->temp_filename))
1464 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1467 GNUNET_free (dc->temp_filename);
1472 /* end of fs_download.c */