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.
222 enum GNUNET_BLOCK_Type type;
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_BLOCK_TYPE_DBLOCK
337 : GNUNET_BLOCK_TYPE_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,
539 * We're done downloading a directory. Open the file and
540 * trigger all of the (remaining) child downloads.
542 * @param dc context of download that just completed
545 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
550 struct GNUNET_DISK_FileHandle *h;
551 struct GNUNET_DISK_MapHandle *m;
553 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
554 size = (size_t) size64;
555 if (size64 != (uint64_t) size)
557 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
558 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
561 if (dc->filename != NULL)
563 h = GNUNET_DISK_file_open (dc->filename,
564 GNUNET_DISK_OPEN_READ,
565 GNUNET_DISK_PERM_NONE);
569 GNUNET_assert (dc->temp_filename != NULL);
570 h = GNUNET_DISK_file_open (dc->temp_filename,
571 GNUNET_DISK_OPEN_READ,
572 GNUNET_DISK_PERM_NONE);
576 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
579 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
580 _("Directory too large for system address space\n"));
584 GNUNET_FS_directory_list_contents (size,
587 &trigger_recursive_download,
589 GNUNET_DISK_file_unmap (m);
591 GNUNET_DISK_file_close (h);
592 if (dc->filename == NULL)
594 if (0 != UNLINK (dc->temp_filename))
595 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
598 GNUNET_free (dc->temp_filename);
599 dc->temp_filename = NULL;
605 * Check if all child-downloads have completed and
606 * if so, signal completion (and possibly recurse to
610 check_completed (struct GNUNET_FS_DownloadContext *dc)
612 struct GNUNET_FS_ProgressInfo pi;
613 struct GNUNET_FS_DownloadContext *pos;
615 pos = dc->child_head;
618 if ( (pos->emsg == NULL) &&
619 (pos->completed < pos->length) )
620 return; /* not done yet */
621 if ( (pos->child_head != NULL) &&
622 (pos->has_finished != GNUNET_YES) )
623 return; /* not transitively done yet */
626 dc->has_finished = GNUNET_YES;
627 /* signal completion */
628 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
629 make_download_status (&pi, dc);
630 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
632 if (dc->parent != NULL)
633 check_completed (dc->parent);
638 * We found an entry in a directory. Check if the respective child
639 * already exists and if not create the respective child download.
641 * @param cls the parent download
642 * @param filename name of the file in the directory
643 * @param uri URI of the file (CHK or LOC)
644 * @param meta meta data of the file
645 * @param length number of bytes in data
646 * @param data contents of the file (or NULL if they were not inlined)
649 trigger_recursive_download (void *cls,
650 const char *filename,
651 const struct GNUNET_FS_Uri *uri,
652 const struct GNUNET_CONTAINER_MetaData *meta,
656 struct GNUNET_FS_DownloadContext *dc = cls;
657 struct GNUNET_FS_DownloadContext *cpos;
658 struct GNUNET_DISK_FileHandle *fh;
660 const char *real_name;
668 return; /* entry for the directory itself */
669 cpos = dc->child_head;
672 if ( (GNUNET_FS_uri_test_equal (uri,
674 ( (filename != NULL) &&
675 (0 == strcmp (cpos->filename,
681 return; /* already exists */
683 if (NULL == filename)
685 fn = GNUNET_FS_meta_data_suggest_filename (meta);
688 us = GNUNET_FS_uri_to_string (uri);
689 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
690 GNUNET_FS_URI_CHK_INFIX)]);
693 else if (fn[0] == '.')
696 us = GNUNET_FS_uri_to_string (uri);
697 GNUNET_asprintf (&fn,
699 &us[strlen (GNUNET_FS_URI_PREFIX
700 GNUNET_FS_URI_CHK_INFIX)], ext);
706 if (dc->filename == NULL)
712 dn = GNUNET_strdup (dc->filename);
713 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
715 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
716 GNUNET_FS_DIRECTORY_EXT)) );
717 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
719 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
720 GNUNET_FS_DIRECTORY_EXT)) )
721 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
722 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
723 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
725 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
726 GNUNET_FS_DIRECTORY_EXT)) ) )
728 GNUNET_asprintf (&full_name,
733 GNUNET_FS_DIRECTORY_EXT);
737 GNUNET_asprintf (&full_name,
745 if ( (full_name != NULL) &&
747 GNUNET_DISK_directory_create_for_file (full_name)) )
749 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
750 _("Failed to create directory for recursive download of `%s'\n"),
752 GNUNET_free (full_name);
753 GNUNET_free_non_null (fn);
758 if ( (data != NULL) &&
759 (GNUNET_FS_uri_chk_get_file_size (uri) == length) )
761 if (full_name == NULL)
763 temp_name = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
764 real_name = temp_name;
768 real_name = full_name;
770 /* write to disk, then trigger normal download which will instantly progress to completion */
771 fh = GNUNET_DISK_file_open (real_name,
772 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
773 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
776 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
779 GNUNET_free (full_name);
780 GNUNET_free_non_null (fn);
784 GNUNET_DISK_file_write (fh,
788 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
792 GNUNET_DISK_file_close (fh);
794 GNUNET_FS_download_start (dc->h,
797 full_name, temp_name,
799 GNUNET_FS_uri_chk_get_file_size (uri),
804 GNUNET_free_non_null (full_name);
805 GNUNET_free_non_null (temp_name);
806 GNUNET_free_non_null (fn);
811 * Iterator over entries in the pending requests in the 'active' map for the
812 * reply that we just got.
814 * @param cls closure (our 'struct ProcessResultClosure')
815 * @param key query for the given value / request
816 * @param value value in the hash map (a 'struct DownloadRequest')
817 * @return GNUNET_YES (we should continue to iterate); unless serious error
820 process_result_with_request (void *cls,
821 const GNUNET_HashCode * key,
824 struct ProcessResultClosure *prc = cls;
825 struct DownloadRequest *sm = value;
826 struct GNUNET_FS_DownloadContext *dc = prc->dc;
827 struct GNUNET_CRYPTO_AesSessionKey skey;
828 struct GNUNET_CRYPTO_AesInitializationVector iv;
830 struct GNUNET_FS_ProgressInfo pi;
835 struct ContentHashKey *chk;
838 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
850 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
852 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
853 make_download_status (&pi, dc);
854 pi.value.download.specifics.error.message = dc->emsg;
855 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
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 make_download_status (&pi, dc);
920 pi.value.download.specifics.error.message = emsg;
921 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
924 /* abort all pending requests */
927 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
930 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
936 if (sm->depth == dc->treedepth)
939 if (sm->offset < dc->offset)
941 /* starting offset begins in the middle of pt,
942 do not count first bytes as progress */
943 GNUNET_assert (app > (dc->offset - sm->offset));
944 app -= (dc->offset - sm->offset);
946 if (sm->offset + prc->size > dc->offset + dc->length)
948 /* end of block is after relevant range,
949 do not count last bytes as progress */
950 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
951 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
953 dc->completed += app;
955 /* do recursive download if option is set and either meta data
956 says it is a directory or if no meta data is given AND filename
957 ends in '.gnd' (top-level case) */
958 if (is_recursive_download (dc))
959 GNUNET_FS_directory_list_contents (prc->size,
962 &trigger_recursive_download,
966 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
967 make_download_status (&pi, dc);
968 pi.value.download.specifics.progress.data = pt;
969 pi.value.download.specifics.progress.offset = sm->offset;
970 pi.value.download.specifics.progress.data_len = prc->size;
971 pi.value.download.specifics.progress.depth = sm->depth;
972 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
974 GNUNET_assert (dc->completed <= dc->length);
975 if (dc->completed == dc->length)
978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979 "Download completed, truncating file to desired length %llu\n",
980 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
982 /* truncate file to size (since we store IBlocks at the end) */
983 if (dc->handle != NULL)
985 GNUNET_DISK_file_close (dc->handle);
987 if (0 != truncate (dc->filename,
988 GNUNET_ntohll (dc->uri->data.chk.file_length)))
989 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
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 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1003 if (dc->parent != NULL)
1004 check_completed (dc->parent);
1006 GNUNET_assert (sm->depth == dc->treedepth);
1008 // FIXME: make persistent
1009 if (sm->depth == dc->treedepth)
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1018 (unsigned long long) sm->offset);
1020 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1021 chk = (struct ContentHashKey*) pt;
1022 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1024 off = compute_dblock_offset (sm->offset,
1028 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1029 (off < dc->offset + dc->length) )
1030 schedule_block_download (dc,
1041 * Process a download result.
1043 * @param dc our download context
1044 * @param type type of the result
1045 * @param data the (encrypted) response
1046 * @param size size of data
1049 process_result (struct GNUNET_FS_DownloadContext *dc,
1050 enum GNUNET_BLOCK_Type type,
1054 struct ProcessResultClosure prc;
1060 prc.do_store = GNUNET_YES;
1061 GNUNET_CRYPTO_hash (data, size, &prc.query);
1063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064 "Received result for query `%s' from `%s'-service\n",
1065 GNUNET_h2s (&prc.query),
1068 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1070 &process_result_with_request,
1076 * Type of a function to call when we receive a message
1079 * @param cls closure
1080 * @param msg message received, NULL on timeout or fatal error
1083 receive_results (void *cls,
1084 const struct GNUNET_MessageHeader * msg)
1086 struct GNUNET_FS_DownloadContext *dc = cls;
1087 const struct PutMessage *cm;
1090 if ( (NULL == msg) ||
1091 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1092 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1094 GNUNET_break (msg == NULL);
1098 msize = ntohs(msg->size);
1099 cm = (const struct PutMessage*) msg;
1103 msize - sizeof (struct PutMessage));
1104 if (dc->client == NULL)
1105 return; /* fatal error */
1106 /* continue receiving */
1107 GNUNET_CLIENT_receive (dc->client,
1110 GNUNET_TIME_UNIT_FOREVER_REL);
1116 * We're ready to transmit a search request to the
1117 * file-sharing service. Do it. If there is
1118 * more than one request pending, try to send
1119 * multiple or request another transmission.
1121 * @param cls closure
1122 * @param size number of bytes available in buf
1123 * @param buf where the callee should write the message
1124 * @return number of bytes written to buf
1127 transmit_download_request (void *cls,
1131 struct GNUNET_FS_DownloadContext *dc = cls;
1133 struct SearchMessage *sm;
1141 GNUNET_assert (size >= sizeof (struct SearchMessage));
1144 while ( (dc->pending != NULL) &&
1145 (size > msize + sizeof (struct SearchMessage)) )
1148 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1149 "Transmitting download request for `%s' to `%s'-service\n",
1150 GNUNET_h2s (&dc->pending->chk.query),
1153 memset (sm, 0, sizeof (struct SearchMessage));
1154 sm->header.size = htons (sizeof (struct SearchMessage));
1155 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1156 if (dc->pending->depth == dc->treedepth)
1157 sm->type = htonl (GNUNET_BLOCK_TYPE_DBLOCK);
1159 sm->type = htonl (GNUNET_BLOCK_TYPE_IBLOCK);
1160 sm->anonymity_level = htonl (dc->anonymity);
1161 sm->target = dc->target.hashPubKey;
1162 sm->query = dc->pending->chk.query;
1163 dc->pending->is_pending = GNUNET_NO;
1164 dc->pending = dc->pending->next;
1165 msize += sizeof (struct SearchMessage);
1168 if (dc->pending != NULL)
1169 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1170 sizeof (struct SearchMessage),
1171 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1173 &transmit_download_request,
1180 * Reconnect to the FS service and transmit our queries NOW.
1182 * @param cls our download context
1186 do_reconnect (void *cls,
1187 const struct GNUNET_SCHEDULER_TaskContext *tc)
1189 struct GNUNET_FS_DownloadContext *dc = cls;
1190 struct GNUNET_CLIENT_Connection *client;
1192 dc->task = GNUNET_SCHEDULER_NO_TASK;
1193 client = GNUNET_CLIENT_connect (dc->h->sched,
1198 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1199 "Connecting to `%s'-service failed, will try again.\n",
1204 dc->client = client;
1205 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1206 sizeof (struct SearchMessage),
1207 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1209 &transmit_download_request,
1211 GNUNET_CLIENT_receive (client,
1214 GNUNET_TIME_UNIT_FOREVER_REL);
1219 * Add entries that are not yet pending back to the pending list.
1221 * @param cls our download context
1223 * @param entry entry of type "struct DownloadRequest"
1227 retry_entry (void *cls,
1228 const GNUNET_HashCode *key,
1231 struct GNUNET_FS_DownloadContext *dc = cls;
1232 struct DownloadRequest *dr = entry;
1234 if (! dr->is_pending)
1236 dr->next = dc->pending;
1237 dr->is_pending = GNUNET_YES;
1238 dc->pending = entry;
1245 * We've lost our connection with the FS service.
1246 * Re-establish it and re-transmit all of our
1249 * @param dc download context that is having trouble
1252 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1255 if (NULL != dc->client)
1259 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1262 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1265 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1269 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1270 GNUNET_TIME_UNIT_SECONDS,
1277 * Download parts of a file. Note that this will store
1278 * the blocks at the respective offset in the given file. Also, the
1279 * download is still using the blocking of the underlying FS
1280 * encoding. As a result, the download may *write* outside of the
1281 * given boundaries (if offset and length do not match the 32k FS
1282 * block boundaries). <p>
1284 * This function should be used to focus a download towards a
1285 * particular portion of the file (optimization), not to strictly
1286 * limit the download to exactly those bytes.
1288 * @param h handle to the file sharing subsystem
1289 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1290 * @param meta known metadata for the file (can be NULL)
1291 * @param filename where to store the file, maybe NULL (then no file is
1292 * created on disk and data must be grabbed from the callbacks)
1293 * @param tempname where to store temporary file data, not used if filename is non-NULL;
1294 * can be NULL (in which case we will pick a name if needed); the temporary file
1295 * may already exist, in which case we will try to use the data that is there and
1296 * if it is not what is desired, will overwrite it
1297 * @param offset at what offset should we start the download (typically 0)
1298 * @param length how many bytes should be downloaded starting at offset
1299 * @param anonymity anonymity level to use for the download
1300 * @param options various options
1301 * @param cctx initial value for the client context for this download
1302 * @param parent parent download to associate this download with (use NULL
1303 * for top-level downloads; useful for manually-triggered recursive downloads)
1304 * @return context that can be used to control this download
1306 struct GNUNET_FS_DownloadContext *
1307 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1308 const struct GNUNET_FS_Uri *uri,
1309 const struct GNUNET_CONTAINER_MetaData *meta,
1310 const char *filename,
1311 const char *tempname,
1315 enum GNUNET_FS_DownloadOptions options,
1317 struct GNUNET_FS_DownloadContext *parent)
1319 struct GNUNET_FS_ProgressInfo pi;
1320 struct GNUNET_FS_DownloadContext *dc;
1321 struct GNUNET_CLIENT_Connection *client;
1323 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1324 if ( (offset + length < offset) ||
1325 (offset + length > uri->data.chk.file_length) )
1330 // FIXME: add support for "loc" URIs!
1332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1333 "Starting download `%s' of %llu bytes\n",
1335 (unsigned long long) length);
1337 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1339 dc->parent = parent;
1342 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1346 dc->uri = GNUNET_FS_uri_dup (uri);
1347 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1348 dc->client_info = cctx;
1349 dc->start_time = GNUNET_TIME_absolute_get ();
1350 if (NULL != filename)
1352 dc->filename = GNUNET_strdup (filename);
1353 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1354 GNUNET_DISK_file_size (filename,
1357 dc->handle = GNUNET_DISK_file_open (filename,
1358 GNUNET_DISK_OPEN_READWRITE |
1359 GNUNET_DISK_OPEN_CREATE,
1360 GNUNET_DISK_PERM_USER_READ |
1361 GNUNET_DISK_PERM_USER_WRITE |
1362 GNUNET_DISK_PERM_GROUP_READ |
1363 GNUNET_DISK_PERM_OTHER_READ);
1364 if (dc->handle == NULL)
1366 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1367 _("Download failed: could not open file `%s': %s\n"),
1370 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1371 GNUNET_FS_uri_destroy (dc->uri);
1372 GNUNET_free (dc->filename);
1377 // FIXME: set "dc->target" for LOC uris!
1378 dc->offset = offset;
1379 dc->length = length;
1380 dc->anonymity = anonymity;
1381 dc->options = options;
1382 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1383 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1384 if ( (filename == NULL) &&
1385 (is_recursive_download (dc) ) )
1387 if (tempname != NULL)
1388 dc->temp_filename = GNUNET_strdup (tempname);
1390 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
1394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1395 "Download tree has depth %u\n",
1398 // FIXME: make persistent
1399 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1400 make_download_status (&pi, dc);
1401 pi.value.download.specifics.start.meta = meta;
1402 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1406 // FIXME: bound parallelism here
1407 client = GNUNET_CLIENT_connect (h->sched,
1410 GNUNET_assert (NULL != client);
1411 dc->client = client;
1412 GNUNET_CLIENT_receive (client,
1415 GNUNET_TIME_UNIT_FOREVER_REL);
1416 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1417 make_download_status (&pi, dc);
1418 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1420 schedule_block_download (dc,
1421 &dc->uri->data.chk.chk,
1423 1 /* 0 == CHK, 1 == top */);
1429 * Free entries in the map.
1431 * @param cls unused (NULL)
1433 * @param entry entry of type "struct DownloadRequest" which is freed
1437 free_entry (void *cls,
1438 const GNUNET_HashCode *key,
1441 GNUNET_free (entry);
1447 * Stop a download (aborts if download is incomplete).
1449 * @param dc handle for the download
1450 * @param do_delete delete files of incomplete downloads
1453 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1456 struct GNUNET_FS_ProgressInfo pi;
1458 while (NULL != dc->child_head)
1459 GNUNET_FS_download_stop (dc->child_head,
1461 // FIXME: make unpersistent
1462 if (dc->parent != NULL)
1463 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1464 dc->parent->child_tail,
1467 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1468 make_download_status (&pi, dc);
1469 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1472 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1473 GNUNET_SCHEDULER_cancel (dc->h->sched,
1477 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1480 if (NULL != dc->client)
1481 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1482 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1485 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1486 if (dc->filename != NULL)
1488 if (NULL != dc->handle)
1489 GNUNET_DISK_file_close (dc->handle);
1490 if ( (dc->completed != dc->length) &&
1491 (GNUNET_YES == do_delete) )
1493 if (0 != UNLINK (dc->filename))
1494 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1498 GNUNET_free (dc->filename);
1500 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1501 GNUNET_FS_uri_destroy (dc->uri);
1502 if (NULL != dc->temp_filename)
1504 if (0 != UNLINK (dc->temp_filename))
1505 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1508 GNUNET_free (dc->temp_filename);
1513 /* end of fs_download.c */