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 GNUNET_FS_download_make_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;
276 struct GNUNET_DISK_FileHandle *fh;
279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
280 "Scheduling download at offset %llu and depth %u for `%s'\n",
281 (unsigned long long) offset,
283 GNUNET_h2s (&chk->query));
285 total = GNUNET_ntohll (dc->uri->data.chk.file_length);
286 off = compute_disk_offset (total,
290 len = GNUNET_FS_tree_calculate_block_size (total,
294 sm = GNUNET_malloc (sizeof (struct DownloadRequest));
298 sm->is_pending = GNUNET_YES;
299 sm->next = dc->pending;
301 GNUNET_CONTAINER_multihashmap_put (dc->active,
304 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
306 if ( (dc->old_file_size > off) &&
307 (dc->filename != NULL) )
309 fh = GNUNET_DISK_file_open (dc->filename,
310 GNUNET_DISK_OPEN_READ,
311 GNUNET_DISK_PERM_NONE);
315 GNUNET_DISK_file_seek (fh,
317 GNUNET_DISK_SEEK_SET) ) &&
319 GNUNET_DISK_file_read (fh,
323 GNUNET_CRYPTO_hash (block, len, &key);
324 if (0 == memcmp (&key,
326 sizeof (GNUNET_HashCode)))
329 struct GNUNET_CRYPTO_AesSessionKey sk;
330 struct GNUNET_CRYPTO_AesInitializationVector iv;
331 GNUNET_HashCode query;
333 GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
334 GNUNET_CRYPTO_aes_encrypt (block, len,
338 GNUNET_CRYPTO_hash (enc, len, &query);
339 if (0 == memcmp (&query,
341 sizeof (GNUNET_HashCode)))
343 /* already got it! */
347 prc.type = (dc->treedepth == depth)
348 ? GNUNET_BLOCK_TYPE_DBLOCK
349 : GNUNET_BLOCK_TYPE_IBLOCK;
350 prc.query = chk->query;
351 prc.do_store = GNUNET_NO; /* useless */
352 process_result_with_request (&prc,
364 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
365 if (depth < dc->treedepth)
367 // FIXME: try if we could
368 // reconstitute this IBLOCK
369 // from the existing blocks on disk (can wait)
370 // (read block(s), encode, compare with
371 // query; if matches, simply return)
374 if ( (dc->th == NULL) &&
375 (dc->client != NULL) )
376 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
377 sizeof (struct SearchMessage),
378 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
380 &transmit_download_request,
387 * Suggest a filename based on given metadata.
389 * @param md given meta data
390 * @return NULL if meta data is useless for suggesting a filename
393 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
395 static const char *mimeMap[][2] = {
396 {"application/bz2", ".bz2"},
397 {"application/gnunet-directory", ".gnd"},
398 {"application/java", ".class"},
399 {"application/msword", ".doc"},
400 {"application/ogg", ".ogg"},
401 {"application/pdf", ".pdf"},
402 {"application/pgp-keys", ".key"},
403 {"application/pgp-signature", ".pgp"},
404 {"application/postscript", ".ps"},
405 {"application/rar", ".rar"},
406 {"application/rtf", ".rtf"},
407 {"application/xml", ".xml"},
408 {"application/x-debian-package", ".deb"},
409 {"application/x-dvi", ".dvi"},
410 {"applixation/x-flac", ".flac"},
411 {"applixation/x-gzip", ".gz"},
412 {"application/x-java-archive", ".jar"},
413 {"application/x-java-vm", ".class"},
414 {"application/x-python-code", ".pyc"},
415 {"application/x-redhat-package-manager", ".rpm"},
416 {"application/x-rpm", ".rpm"},
417 {"application/x-tar", ".tar"},
418 {"application/x-tex-pk", ".pk"},
419 {"application/x-texinfo", ".texinfo"},
420 {"application/x-xcf", ".xcf"},
421 {"application/x-xfig", ".xfig"},
422 {"application/zip", ".zip"},
424 {"audio/midi", ".midi"},
425 {"audio/mpeg", ".mp3"},
426 {"audio/real", ".rm"},
427 {"audio/x-wav", ".wav"},
429 {"image/gif", ".gif"},
430 {"image/jpeg", ".jpg"},
431 {"image/pcx", ".pcx"},
432 {"image/png", ".png"},
433 {"image/tiff", ".tiff"},
434 {"image/x-ms-bmp", ".bmp"},
435 {"image/x-xpixmap", ".xpm"},
437 {"text/css", ".css"},
438 {"text/html", ".html"},
439 {"text/plain", ".txt"},
440 {"text/rtf", ".rtf"},
441 {"text/x-c++hdr", ".h++"},
442 {"text/x-c++src", ".c++"},
443 {"text/x-chdr", ".h"},
444 {"text/x-csrc", ".c"},
445 {"text/x-java", ".java"},
446 {"text/x-moc", ".moc"},
447 {"text/x-pascal", ".pas"},
448 {"text/x-perl", ".pl"},
449 {"text/x-python", ".py"},
450 {"text/x-tex", ".tex"},
452 {"video/avi", ".avi"},
453 {"video/mpeg", ".mpeg"},
454 {"video/quicktime", ".qt"},
455 {"video/real", ".rm"},
456 {"video/x-msvideo", ".avi"},
465 ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
466 EXTRACTOR_METATYPE_FILENAME);
470 mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
471 EXTRACTOR_METATYPE_MIMETYPE);
475 while ( (mimeMap[i][0] != NULL) &&
476 (0 != strcmp (mime, mimeMap[i][0])))
478 if (mimeMap[i][1] == NULL)
479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
480 GNUNET_ERROR_TYPE_BULK,
481 _("Did not find mime type `%s' in extension list.\n"),
487 base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
488 EXTRACTOR_METATYPE_TITLE,
489 EXTRACTOR_METATYPE_BOOK_TITLE,
490 EXTRACTOR_METATYPE_ORIGINAL_TITLE,
491 EXTRACTOR_METATYPE_PACKAGE_NAME,
492 EXTRACTOR_METATYPE_URL,
493 EXTRACTOR_METATYPE_URI,
494 EXTRACTOR_METATYPE_DESCRIPTION,
495 EXTRACTOR_METATYPE_ISRC,
496 EXTRACTOR_METATYPE_JOURNAL_NAME,
497 EXTRACTOR_METATYPE_AUTHOR_NAME,
498 EXTRACTOR_METATYPE_SUBJECT,
499 EXTRACTOR_METATYPE_ALBUM,
500 EXTRACTOR_METATYPE_ARTIST,
501 EXTRACTOR_METATYPE_KEYWORDS,
502 EXTRACTOR_METATYPE_COMMENT,
503 EXTRACTOR_METATYPE_UNKNOWN,
505 if ( (base == NULL) &&
509 return GNUNET_strdup (ext);
512 GNUNET_asprintf (&ret,
522 * We've lost our connection with the FS service.
523 * Re-establish it and re-transmit all of our
526 * @param dc download context that is having trouble
529 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
533 * We found an entry in a directory. Check if the respective child
534 * already exists and if not create the respective child download.
536 * @param cls the parent download
537 * @param filename name of the file in the directory
538 * @param uri URI of the file (CHK or LOC)
539 * @param meta meta data of the file
540 * @param length number of bytes in data
541 * @param data contents of the file (or NULL if they were not inlined)
544 trigger_recursive_download (void *cls,
545 const char *filename,
546 const struct GNUNET_FS_Uri *uri,
547 const struct GNUNET_CONTAINER_MetaData *meta,
553 * We're done downloading a directory. Open the file and
554 * trigger all of the (remaining) child downloads.
556 * @param dc context of download that just completed
559 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
564 struct GNUNET_DISK_FileHandle *h;
565 struct GNUNET_DISK_MapHandle *m;
567 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
568 size = (size_t) size64;
569 if (size64 != (uint64_t) size)
571 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
572 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
575 if (dc->filename != NULL)
577 h = GNUNET_DISK_file_open (dc->filename,
578 GNUNET_DISK_OPEN_READ,
579 GNUNET_DISK_PERM_NONE);
583 GNUNET_assert (dc->temp_filename != NULL);
584 h = GNUNET_DISK_file_open (dc->temp_filename,
585 GNUNET_DISK_OPEN_READ,
586 GNUNET_DISK_PERM_NONE);
590 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
593 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
594 _("Directory too large for system address space\n"));
598 GNUNET_FS_directory_list_contents (size,
601 &trigger_recursive_download,
603 GNUNET_DISK_file_unmap (m);
605 GNUNET_DISK_file_close (h);
606 if (dc->filename == NULL)
608 if (0 != UNLINK (dc->temp_filename))
609 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
612 GNUNET_free (dc->temp_filename);
613 dc->temp_filename = NULL;
619 * Check if all child-downloads have completed and
620 * if so, signal completion (and possibly recurse to
624 check_completed (struct GNUNET_FS_DownloadContext *dc)
626 struct GNUNET_FS_ProgressInfo pi;
627 struct GNUNET_FS_DownloadContext *pos;
629 pos = dc->child_head;
632 if ( (pos->emsg == NULL) &&
633 (pos->completed < pos->length) )
634 return; /* not done yet */
635 if ( (pos->child_head != NULL) &&
636 (pos->has_finished != GNUNET_YES) )
637 return; /* not transitively done yet */
640 dc->has_finished = GNUNET_YES;
641 /* signal completion */
642 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
643 GNUNET_FS_download_make_status_ (&pi, dc);
644 if (dc->parent != NULL)
645 check_completed (dc->parent);
650 * We found an entry in a directory. Check if the respective child
651 * already exists and if not create the respective child download.
653 * @param cls the parent download
654 * @param filename name of the file in the directory
655 * @param uri URI of the file (CHK or LOC)
656 * @param meta meta data of the file
657 * @param length number of bytes in data
658 * @param data contents of the file (or NULL if they were not inlined)
661 trigger_recursive_download (void *cls,
662 const char *filename,
663 const struct GNUNET_FS_Uri *uri,
664 const struct GNUNET_CONTAINER_MetaData *meta,
668 struct GNUNET_FS_DownloadContext *dc = cls;
669 struct GNUNET_FS_DownloadContext *cpos;
670 struct GNUNET_DISK_FileHandle *fh;
672 const char *real_name;
680 return; /* entry for the directory itself */
681 cpos = dc->child_head;
684 if ( (GNUNET_FS_uri_test_equal (uri,
686 ( (filename != NULL) &&
687 (0 == strcmp (cpos->filename,
693 return; /* already exists */
695 if (NULL == filename)
697 fn = GNUNET_FS_meta_data_suggest_filename (meta);
700 us = GNUNET_FS_uri_to_string (uri);
701 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
702 GNUNET_FS_URI_CHK_INFIX)]);
705 else if (fn[0] == '.')
708 us = GNUNET_FS_uri_to_string (uri);
709 GNUNET_asprintf (&fn,
711 &us[strlen (GNUNET_FS_URI_PREFIX
712 GNUNET_FS_URI_CHK_INFIX)], ext);
718 if (dc->filename == NULL)
724 dn = GNUNET_strdup (dc->filename);
725 GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
727 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
728 GNUNET_FS_DIRECTORY_EXT)) );
729 if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
731 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
732 GNUNET_FS_DIRECTORY_EXT)) )
733 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
734 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
735 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
737 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
738 GNUNET_FS_DIRECTORY_EXT)) ) )
740 GNUNET_asprintf (&full_name,
745 GNUNET_FS_DIRECTORY_EXT);
749 GNUNET_asprintf (&full_name,
757 if ( (full_name != NULL) &&
759 GNUNET_DISK_directory_create_for_file (full_name)) )
761 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
762 _("Failed to create directory for recursive download of `%s'\n"),
764 GNUNET_free (full_name);
765 GNUNET_free_non_null (fn);
770 if ( (data != NULL) &&
771 (GNUNET_FS_uri_chk_get_file_size (uri) == length) )
773 if (full_name == NULL)
775 temp_name = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
776 real_name = temp_name;
780 real_name = full_name;
782 /* write to disk, then trigger normal download which will instantly progress to completion */
783 fh = GNUNET_DISK_file_open (real_name,
784 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
785 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
788 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
791 GNUNET_free (full_name);
792 GNUNET_free_non_null (fn);
796 GNUNET_DISK_file_write (fh,
800 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
804 GNUNET_DISK_file_close (fh);
806 GNUNET_FS_download_start (dc->h,
809 full_name, temp_name,
811 GNUNET_FS_uri_chk_get_file_size (uri),
816 GNUNET_free_non_null (full_name);
817 GNUNET_free_non_null (temp_name);
818 GNUNET_free_non_null (fn);
823 * Iterator over entries in the pending requests in the 'active' map for the
824 * reply that we just got.
826 * @param cls closure (our 'struct ProcessResultClosure')
827 * @param key query for the given value / request
828 * @param value value in the hash map (a 'struct DownloadRequest')
829 * @return GNUNET_YES (we should continue to iterate); unless serious error
832 process_result_with_request (void *cls,
833 const GNUNET_HashCode * key,
836 struct ProcessResultClosure *prc = cls;
837 struct DownloadRequest *sm = value;
838 struct DownloadRequest *ppos;
839 struct DownloadRequest *pprev;
840 struct GNUNET_DISK_FileHandle *fh;
841 struct GNUNET_FS_DownloadContext *dc = prc->dc;
842 struct GNUNET_CRYPTO_AesSessionKey skey;
843 struct GNUNET_CRYPTO_AesInitializationVector iv;
845 struct GNUNET_FS_ProgressInfo pi;
850 struct ContentHashKey *chk;
853 bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
861 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
865 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
868 GNUNET_assert (GNUNET_YES ==
869 GNUNET_CONTAINER_multihashmap_remove (dc->active,
872 /* if this request is on the pending list, remove it! */
880 dc->pending = ppos->next;
882 pprev->next = ppos->next;
888 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
889 GNUNET_CRYPTO_aes_decrypt (prc->data,
894 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
899 if ( ( GNUNET_YES == prc->do_store) &&
900 ( (dc->filename != NULL) ||
901 (is_recursive_download (dc)) ) &&
902 ( (sm->depth == dc->treedepth) ||
903 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
905 fh = GNUNET_DISK_file_open (dc->filename != NULL
908 GNUNET_DISK_OPEN_READWRITE |
909 GNUNET_DISK_OPEN_CREATE,
910 GNUNET_DISK_PERM_USER_READ |
911 GNUNET_DISK_PERM_USER_WRITE |
912 GNUNET_DISK_PERM_GROUP_READ |
913 GNUNET_DISK_PERM_OTHER_READ);
916 (GNUNET_YES == prc->do_store) &&
917 ( (dc->filename != NULL) ||
918 (is_recursive_download (dc)) ) &&
919 ( (sm->depth == dc->treedepth) ||
920 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
922 GNUNET_asprintf (&dc->emsg,
923 _("Download failed: could not open file `%s': %s\n"),
931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
932 "Saving decrypted block to disk at offset %llu\n",
933 (unsigned long long) off);
936 GNUNET_DISK_file_seek (fh,
938 GNUNET_DISK_SEEK_SET) ) )
940 GNUNET_asprintf (&dc->emsg,
941 _("Failed to seek to offset %llu in file `%s': %s\n"),
942 (unsigned long long) off,
948 GNUNET_DISK_file_write (fh,
952 GNUNET_asprintf (&dc->emsg,
953 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
954 (unsigned int) prc->size,
955 (unsigned long long) off,
960 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
963 if (sm->depth == dc->treedepth)
966 if (sm->offset < dc->offset)
968 /* starting offset begins in the middle of pt,
969 do not count first bytes as progress */
970 GNUNET_assert (app > (dc->offset - sm->offset));
971 app -= (dc->offset - sm->offset);
973 if (sm->offset + prc->size > dc->offset + dc->length)
975 /* end of block is after relevant range,
976 do not count last bytes as progress */
977 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
978 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
980 dc->completed += app;
982 /* do recursive download if option is set and either meta data
983 says it is a directory or if no meta data is given AND filename
984 ends in '.gnd' (top-level case) */
985 if (is_recursive_download (dc))
986 GNUNET_FS_directory_list_contents (prc->size,
989 &trigger_recursive_download,
993 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
994 pi.value.download.specifics.progress.data = pt;
995 pi.value.download.specifics.progress.offset = sm->offset;
996 pi.value.download.specifics.progress.data_len = prc->size;
997 pi.value.download.specifics.progress.depth = sm->depth;
998 GNUNET_FS_download_make_status_ (&pi, dc);
999 GNUNET_assert (dc->completed <= dc->length);
1000 if (dc->completed == dc->length)
1003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1004 "Download completed, truncating file to desired length %llu\n",
1005 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
1007 /* truncate file to size (since we store IBlocks at the end) */
1008 if (dc->filename != NULL)
1010 if (0 != truncate (dc->filename,
1011 GNUNET_ntohll (dc->uri->data.chk.file_length)))
1012 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1016 if (dc->job_queue != NULL)
1018 GNUNET_FS_dequeue_ (dc->job_queue);
1019 dc->job_queue = NULL;
1021 if (is_recursive_download (dc))
1022 full_recursive_download (dc);
1023 if (dc->child_head == NULL)
1025 /* signal completion */
1026 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
1027 GNUNET_FS_download_make_status_ (&pi, dc);
1028 if (dc->parent != NULL)
1029 check_completed (dc->parent);
1031 GNUNET_assert (sm->depth == dc->treedepth);
1033 // FIXME: make persistent
1034 if (sm->depth == dc->treedepth)
1040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1043 (unsigned long long) sm->offset);
1045 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1046 chk = (struct ContentHashKey*) pt;
1047 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1049 off = compute_dblock_offset (sm->offset,
1053 if ( (off + DBLOCK_SIZE >= dc->offset) &&
1054 (off < dc->offset + dc->length) )
1055 schedule_block_download (dc,
1065 GNUNET_DISK_file_close (fh);
1066 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1067 pi.value.download.specifics.error.message = dc->emsg;
1068 GNUNET_FS_download_make_status_ (&pi, dc);
1069 /* abort all pending requests */
1072 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1075 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1083 * Process a download result.
1085 * @param dc our download context
1086 * @param type type of the result
1087 * @param data the (encrypted) response
1088 * @param size size of data
1091 process_result (struct GNUNET_FS_DownloadContext *dc,
1092 enum GNUNET_BLOCK_Type type,
1096 struct ProcessResultClosure prc;
1102 prc.do_store = GNUNET_YES;
1103 GNUNET_CRYPTO_hash (data, size, &prc.query);
1105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1106 "Received result for query `%s' from `%s'-service\n",
1107 GNUNET_h2s (&prc.query),
1110 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1112 &process_result_with_request,
1118 * Type of a function to call when we receive a message
1121 * @param cls closure
1122 * @param msg message received, NULL on timeout or fatal error
1125 receive_results (void *cls,
1126 const struct GNUNET_MessageHeader * msg)
1128 struct GNUNET_FS_DownloadContext *dc = cls;
1129 const struct PutMessage *cm;
1132 if ( (NULL == msg) ||
1133 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1134 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1136 GNUNET_break (msg == NULL);
1140 msize = ntohs(msg->size);
1141 cm = (const struct PutMessage*) msg;
1145 msize - sizeof (struct PutMessage));
1146 if (dc->client == NULL)
1147 return; /* fatal error */
1148 /* continue receiving */
1149 GNUNET_CLIENT_receive (dc->client,
1152 GNUNET_TIME_UNIT_FOREVER_REL);
1158 * We're ready to transmit a search request to the
1159 * file-sharing service. Do it. If there is
1160 * more than one request pending, try to send
1161 * multiple or request another transmission.
1163 * @param cls closure
1164 * @param size number of bytes available in buf
1165 * @param buf where the callee should write the message
1166 * @return number of bytes written to buf
1169 transmit_download_request (void *cls,
1173 struct GNUNET_FS_DownloadContext *dc = cls;
1175 struct SearchMessage *sm;
1183 GNUNET_assert (size >= sizeof (struct SearchMessage));
1186 while ( (dc->pending != NULL) &&
1187 (size > msize + sizeof (struct SearchMessage)) )
1190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1191 "Transmitting download request for `%s' to `%s'-service\n",
1192 GNUNET_h2s (&dc->pending->chk.query),
1195 memset (sm, 0, sizeof (struct SearchMessage));
1196 sm->header.size = htons (sizeof (struct SearchMessage));
1197 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1198 if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1199 sm->options = htonl (1);
1201 sm->options = htonl (0);
1202 if (dc->pending->depth == dc->treedepth)
1203 sm->type = htonl (GNUNET_BLOCK_TYPE_DBLOCK);
1205 sm->type = htonl (GNUNET_BLOCK_TYPE_IBLOCK);
1206 sm->anonymity_level = htonl (dc->anonymity);
1207 sm->target = dc->target.hashPubKey;
1208 sm->query = dc->pending->chk.query;
1209 dc->pending->is_pending = GNUNET_NO;
1210 dc->pending = dc->pending->next;
1211 msize += sizeof (struct SearchMessage);
1214 if (dc->pending != NULL)
1215 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1216 sizeof (struct SearchMessage),
1217 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1219 &transmit_download_request,
1226 * Reconnect to the FS service and transmit our queries NOW.
1228 * @param cls our download context
1232 do_reconnect (void *cls,
1233 const struct GNUNET_SCHEDULER_TaskContext *tc)
1235 struct GNUNET_FS_DownloadContext *dc = cls;
1236 struct GNUNET_CLIENT_Connection *client;
1238 dc->task = GNUNET_SCHEDULER_NO_TASK;
1239 client = GNUNET_CLIENT_connect (dc->h->sched,
1244 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1245 "Connecting to `%s'-service failed, will try again.\n",
1250 dc->client = client;
1251 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1252 sizeof (struct SearchMessage),
1253 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1255 &transmit_download_request,
1257 GNUNET_CLIENT_receive (client,
1260 GNUNET_TIME_UNIT_FOREVER_REL);
1265 * Add entries that are not yet pending back to the pending list.
1267 * @param cls our download context
1269 * @param entry entry of type "struct DownloadRequest"
1273 retry_entry (void *cls,
1274 const GNUNET_HashCode *key,
1277 struct GNUNET_FS_DownloadContext *dc = cls;
1278 struct DownloadRequest *dr = entry;
1280 if (! dr->is_pending)
1282 dr->next = dc->pending;
1283 dr->is_pending = GNUNET_YES;
1284 dc->pending = entry;
1291 * We've lost our connection with the FS service.
1292 * Re-establish it and re-transmit all of our
1295 * @param dc download context that is having trouble
1298 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1301 if (NULL != dc->client)
1305 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1308 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1311 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1315 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1316 GNUNET_TIME_UNIT_SECONDS,
1324 * We're allowed to ask the FS service for our blocks. Start the download.
1326 * @param cls the 'struct GNUNET_FS_DownloadContext'
1327 * @param client handle to use for communcation with FS (we must destroy it!)
1330 activate_fs_download (void *cls,
1331 struct GNUNET_CLIENT_Connection *client)
1333 struct GNUNET_FS_DownloadContext *dc = cls;
1334 struct GNUNET_FS_ProgressInfo pi;
1336 GNUNET_assert (NULL != client);
1337 dc->client = client;
1338 GNUNET_CLIENT_receive (client,
1341 GNUNET_TIME_UNIT_FOREVER_REL);
1342 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1343 GNUNET_FS_download_make_status_ (&pi, dc);
1344 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1347 if ( (dc->th == NULL) &&
1348 (dc->client != NULL) )
1349 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1350 sizeof (struct SearchMessage),
1351 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1353 &transmit_download_request,
1359 * We must stop to ask the FS service for our blocks. Pause the download.
1361 * @param cls the 'struct GNUNET_FS_DownloadContext'
1364 deactivate_fs_download (void *cls)
1366 struct GNUNET_FS_DownloadContext *dc = cls;
1367 struct GNUNET_FS_ProgressInfo pi;
1371 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1374 if (NULL != dc->client)
1376 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1379 pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1380 GNUNET_FS_download_make_status_ (&pi, dc);
1385 * Download parts of a file. Note that this will store
1386 * the blocks at the respective offset in the given file. Also, the
1387 * download is still using the blocking of the underlying FS
1388 * encoding. As a result, the download may *write* outside of the
1389 * given boundaries (if offset and length do not match the 32k FS
1390 * block boundaries). <p>
1392 * This function should be used to focus a download towards a
1393 * particular portion of the file (optimization), not to strictly
1394 * limit the download to exactly those bytes.
1396 * @param h handle to the file sharing subsystem
1397 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1398 * @param meta known metadata for the file (can be NULL)
1399 * @param filename where to store the file, maybe NULL (then no file is
1400 * created on disk and data must be grabbed from the callbacks)
1401 * @param tempname where to store temporary file data, not used if filename is non-NULL;
1402 * can be NULL (in which case we will pick a name if needed); the temporary file
1403 * may already exist, in which case we will try to use the data that is there and
1404 * if it is not what is desired, will overwrite it
1405 * @param offset at what offset should we start the download (typically 0)
1406 * @param length how many bytes should be downloaded starting at offset
1407 * @param anonymity anonymity level to use for the download
1408 * @param options various options
1409 * @param cctx initial value for the client context for this download
1410 * @param parent parent download to associate this download with (use NULL
1411 * for top-level downloads; useful for manually-triggered recursive downloads)
1412 * @return context that can be used to control this download
1414 struct GNUNET_FS_DownloadContext *
1415 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1416 const struct GNUNET_FS_Uri *uri,
1417 const struct GNUNET_CONTAINER_MetaData *meta,
1418 const char *filename,
1419 const char *tempname,
1423 enum GNUNET_FS_DownloadOptions options,
1425 struct GNUNET_FS_DownloadContext *parent)
1427 struct GNUNET_FS_ProgressInfo pi;
1428 struct GNUNET_FS_DownloadContext *dc;
1430 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1431 if ( (offset + length < offset) ||
1432 (offset + length > uri->data.chk.file_length) )
1437 // FIXME: add support for "loc" URIs!
1439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1440 "Starting download `%s' of %llu bytes\n",
1442 (unsigned long long) length);
1444 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1446 dc->parent = parent;
1449 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1453 dc->uri = GNUNET_FS_uri_dup (uri);
1454 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1455 dc->client_info = cctx;
1456 dc->start_time = GNUNET_TIME_absolute_get ();
1457 if (NULL != filename)
1459 dc->filename = GNUNET_strdup (filename);
1460 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1461 GNUNET_DISK_file_size (filename,
1465 // FIXME: set "dc->target" for LOC uris!
1466 dc->offset = offset;
1467 dc->length = length;
1468 dc->anonymity = anonymity;
1469 dc->options = options;
1470 dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1471 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1472 if ( (filename == NULL) &&
1473 (is_recursive_download (dc) ) )
1475 if (tempname != NULL)
1476 dc->temp_filename = GNUNET_strdup (tempname);
1478 dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
1482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1483 "Download tree has depth %u\n",
1486 // FIXME: make persistent
1487 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1488 pi.value.download.specifics.start.meta = meta;
1489 GNUNET_FS_download_make_status_ (&pi, dc);
1490 schedule_block_download (dc,
1491 &dc->uri->data.chk.chk,
1493 1 /* 0 == CHK, 1 == top */);
1494 GNUNET_FS_download_start_downloading_ (dc);
1500 * Start the downloading process (by entering the queue).
1502 * @param dc our download context
1505 GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc)
1507 dc->job_queue = GNUNET_FS_queue_ (dc->h,
1508 &activate_fs_download,
1509 &deactivate_fs_download,
1511 (dc->length + DBLOCK_SIZE-1) / DBLOCK_SIZE);
1516 * Free entries in the map.
1518 * @param cls unused (NULL)
1520 * @param entry entry of type "struct DownloadRequest" which is freed
1524 free_entry (void *cls,
1525 const GNUNET_HashCode *key,
1528 GNUNET_free (entry);
1534 * Stop a download (aborts if download is incomplete).
1536 * @param dc handle for the download
1537 * @param do_delete delete files of incomplete downloads
1540 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1543 struct GNUNET_FS_ProgressInfo pi;
1545 if (dc->job_queue != NULL)
1547 GNUNET_FS_dequeue_ (dc->job_queue);
1548 dc->job_queue = NULL;
1550 while (NULL != dc->child_head)
1551 GNUNET_FS_download_stop (dc->child_head,
1553 // FIXME: make unpersistent
1554 if (dc->parent != NULL)
1555 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1556 dc->parent->child_tail,
1559 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1560 GNUNET_FS_download_make_status_ (&pi, dc);
1561 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1562 GNUNET_SCHEDULER_cancel (dc->h->sched,
1564 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1567 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1568 if (dc->filename != NULL)
1570 if ( (dc->completed != dc->length) &&
1571 (GNUNET_YES == do_delete) )
1573 if (0 != UNLINK (dc->filename))
1574 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1578 GNUNET_free (dc->filename);
1580 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1581 GNUNET_FS_uri_destroy (dc->uri);
1582 if (NULL != dc->temp_filename)
1584 if (0 != UNLINK (dc->temp_filename))
1585 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1588 GNUNET_free (dc->temp_filename);
1590 /* FIXME: clean up serialization file itself! */
1591 GNUNET_free_non_null (dc->serialization);
1595 /* end of fs_download.c */