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 * - handle recursive downloads where directory file is
29 * NOT saved on disk (need temporary file instead then!)
30 * - location URI suppport (can wait, easy)
31 * - check if blocks exist already (can wait, easy)
32 * - check if iblocks can be computed from existing blocks (can wait, hard)
33 * - persistence (can wait)
36 #include "gnunet_constants.h"
37 #include "gnunet_fs_service.h"
41 #define DEBUG_DOWNLOAD GNUNET_NO
44 * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
45 * only have to truncate the file once we're done).
47 * Given the offset of a block (with respect to the DBLOCKS) and its
48 * depth, return the offset where we would store this block in the
51 * @param fsize overall file size
52 * @param off offset of the block in the file
53 * @param depth depth of the block in the tree
54 * @param treedepth maximum depth of the tree
55 * @return off for DBLOCKS (depth == treedepth),
56 * otherwise an offset past the end
57 * of the file that does not overlap
58 * with the range for any other block
61 compute_disk_offset (uint64_t fsize,
64 unsigned int treedepth)
67 uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
68 uint64_t loff; /* where do IBlocks for depth "i" start? */
69 unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
71 if (depth == treedepth)
73 /* first IBlocks start at the end of file, rounded up
74 to full DBLOCK_SIZE */
75 loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
76 lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
77 GNUNET_assert (0 == (off % DBLOCK_SIZE));
78 ioff = (off / DBLOCK_SIZE);
79 for (i=treedepth-1;i>depth;i--)
82 lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
83 GNUNET_assert (lsize > 0);
84 GNUNET_assert (0 == (ioff % CHK_PER_INODE));
85 ioff /= CHK_PER_INODE;
87 return loff + ioff * sizeof (struct ContentHashKey);
92 * Given a file of the specified treedepth and a block at the given
93 * offset and depth, calculate the offset for the CHK at the given
96 * @param offset the offset of the first
97 * DBLOCK in the subtree of the
99 * @param depth the depth of the IBLOCK in the tree
100 * @param treedepth overall depth of the tree
101 * @param k which CHK in the IBLOCK are we
103 * @return offset if k=0, otherwise an appropriately
104 * larger value (i.e., if depth = treedepth-1,
105 * the returned value should be offset+DBLOCK_SIZE)
108 compute_dblock_offset (uint64_t offset,
110 unsigned int treedepth,
114 uint64_t lsize; /* what is the size of the sum of all DBlocks
115 that a CHK at depth i corresponds to? */
117 if (depth == treedepth)
120 for (i=treedepth-1;i>depth;i--)
121 lsize *= CHK_PER_INODE;
122 return offset + k * lsize;
127 * Fill in all of the generic fields for
130 * @param pi structure to fill in
131 * @param dc overall download context
134 make_download_status (struct GNUNET_FS_ProgressInfo *pi,
135 struct GNUNET_FS_DownloadContext *dc)
137 pi->value.download.dc = dc;
138 pi->value.download.cctx
140 pi->value.download.pctx
141 = (dc->parent == NULL) ? NULL : dc->parent->client_info;
142 pi->value.download.uri
144 pi->value.download.filename
146 pi->value.download.size
148 pi->value.download.duration
149 = GNUNET_TIME_absolute_get_duration (dc->start_time);
150 pi->value.download.completed
152 pi->value.download.anonymity
154 pi->value.download.eta
155 = GNUNET_TIME_calculate_eta (dc->start_time,
161 * We're ready to transmit a search request to the
162 * file-sharing service. Do it. If there is
163 * more than one request pending, try to send
164 * multiple or request another transmission.
167 * @param size number of bytes available in buf
168 * @param buf where the callee should write the message
169 * @return number of bytes written to buf
172 transmit_download_request (void *cls,
178 * Schedule the download of the specified
181 * @param dc overall download this block belongs to
182 * @param chk content-hash-key of the block
183 * @param offset offset of the block in the file
184 * (for IBlocks, the offset is the lowest
185 * offset of any DBlock in the subtree under
187 * @param depth depth of the block, 0 is the root of the tree
190 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
191 const struct ContentHashKey *chk,
195 struct DownloadRequest *sm;
199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
200 "Scheduling download at offset %llu and depth %u for `%s'\n",
201 (unsigned long long) offset,
203 GNUNET_h2s (&chk->query));
205 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
209 if ( (dc->old_file_size > off) &&
210 (dc->handle != NULL) &&
212 GNUNET_DISK_file_seek (dc->handle,
214 GNUNET_DISK_SEEK_SET) ) )
216 // FIXME: check if block exists on disk!
217 // (read block, encode, compare with
218 // query; if matches, simply return)
220 if (depth < dc->treedepth)
222 // FIXME: try if we could
223 // reconstitute this IBLOCK
224 // from the existing blocks on disk (can wait)
225 // (read block(s), encode, compare with
226 // query; if matches, simply return)
228 sm = GNUNET_malloc (sizeof (struct DownloadRequest));
232 sm->is_pending = GNUNET_YES;
233 sm->next = dc->pending;
235 GNUNET_CONTAINER_multihashmap_put (dc->active,
238 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
240 if ( (dc->th == NULL) &&
241 (dc->client != NULL) )
242 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
243 sizeof (struct SearchMessage),
244 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
246 &transmit_download_request,
253 * Suggest a filename based on given metadata.
255 * @param md given meta data
256 * @return NULL if meta data is useless for suggesting a filename
259 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
261 static const char *mimeMap[][2] = {
262 {"application/bz2", ".bz2"},
263 {"application/gnunet-directory", ".gnd"},
264 {"application/java", ".class"},
265 {"application/msword", ".doc"},
266 {"application/ogg", ".ogg"},
267 {"application/pdf", ".pdf"},
268 {"application/pgp-keys", ".key"},
269 {"application/pgp-signature", ".pgp"},
270 {"application/postscript", ".ps"},
271 {"application/rar", ".rar"},
272 {"application/rtf", ".rtf"},
273 {"application/xml", ".xml"},
274 {"application/x-debian-package", ".deb"},
275 {"application/x-dvi", ".dvi"},
276 {"applixation/x-flac", ".flac"},
277 {"applixation/x-gzip", ".gz"},
278 {"application/x-java-archive", ".jar"},
279 {"application/x-java-vm", ".class"},
280 {"application/x-python-code", ".pyc"},
281 {"application/x-redhat-package-manager", ".rpm"},
282 {"application/x-rpm", ".rpm"},
283 {"application/x-tar", ".tar"},
284 {"application/x-tex-pk", ".pk"},
285 {"application/x-texinfo", ".texinfo"},
286 {"application/x-xcf", ".xcf"},
287 {"application/x-xfig", ".xfig"},
288 {"application/zip", ".zip"},
290 {"audio/midi", ".midi"},
291 {"audio/mpeg", ".mp3"},
292 {"audio/real", ".rm"},
293 {"audio/x-wav", ".wav"},
295 {"image/gif", ".gif"},
296 {"image/jpeg", ".jpg"},
297 {"image/pcx", ".pcx"},
298 {"image/png", ".png"},
299 {"image/tiff", ".tiff"},
300 {"image/x-ms-bmp", ".bmp"},
301 {"image/x-xpixmap", ".xpm"},
303 {"text/css", ".css"},
304 {"text/html", ".html"},
305 {"text/plain", ".txt"},
306 {"text/rtf", ".rtf"},
307 {"text/x-c++hdr", ".h++"},
308 {"text/x-c++src", ".c++"},
309 {"text/x-chdr", ".h"},
310 {"text/x-csrc", ".c"},
311 {"text/x-java", ".java"},
312 {"text/x-moc", ".moc"},
313 {"text/x-pascal", ".pas"},
314 {"text/x-perl", ".pl"},
315 {"text/x-python", ".py"},
316 {"text/x-tex", ".tex"},
318 {"video/avi", ".avi"},
319 {"video/mpeg", ".mpeg"},
320 {"video/quicktime", ".qt"},
321 {"video/real", ".rm"},
322 {"video/x-msvideo", ".avi"},
332 // FIXME: get mime from meta data
336 while ( (mimeMap[i][0] != NULL) &&
337 (0 != strcmp (mime, mimeMap[i][0])))
339 if (mimeMap[i][1] == NULL)
340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG |
341 GNUNET_ERROR_TYPE_BULK,
342 _("Did not find mime type `%s' in extension list.\n"),
347 // FIXME: try to get some base name...
356 struct stat filestat;
358 key = EXTRACTOR_extractLast (EXTRACTOR_TITLE, list);
360 key = EXTRACTOR_extractLast (EXTRACTOR_SOFTWARE, list);
362 key = EXTRACTOR_extractLast (EXTRACTOR_DESCRIPTION, list);
364 key = EXTRACTOR_extractLast (EXTRACTOR_COMMENT, list);
366 key = EXTRACTOR_extractLast (EXTRACTOR_SUBJECT, list);
368 key = EXTRACTOR_extractLast (EXTRACTOR_ALBUM, list);
370 key = EXTRACTOR_extractLast (EXTRACTOR_UNKNOWN, list);
371 mime = EXTRACTOR_extractLast (EXTRACTOR_MIMETYPE, list);
377 key = &filename[strlen (filename) - 1];
378 while ((key != filename) && (key[0] != DIR_SEPARATOR))
380 if (key[0] == DIR_SEPARATOR)
383 GNUNET_snprintf (renameTo,
387 (path[strlen (path) - 1] !=
388 DIR_SEPARATOR) ? DIR_SEPARATOR_STR : "",
389 GNUNET_MIN (255 - strlen (mime),
390 PATH_MAX - strlen (path) - 64), key,
392 (renameTo + strlen (renameTo) - strlen (mime),
393 mime) != 0) ? mime : "");
397 for (i = strlen (renameTo) - 1; i >= 0; i--)
398 if (!isprint (renameTo[i]))
400 else if (renameTo[i] == '.' && i > 0 && renameTo[i - 1] == '.')
402 /* remove .. to avoid directory traversal */
403 renameTo[i - 1] = renameTo[i] = '_';
408 GNUNET_break (0); // FIXME: not implemented
414 * We've lost our connection with the FS service.
415 * Re-establish it and re-transmit all of our
418 * @param dc download context that is having trouble
421 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
425 * Compute how many bytes of data should be stored in
426 * the specified node.
428 * @param fsize overall file size
429 * @param totaldepth depth of the entire tree
430 * @param offset offset of the node
431 * @param depth depth of the node
432 * @return number of bytes stored in this node
435 calculate_block_size (uint64_t fsize,
436 unsigned int totaldepth,
446 GNUNET_assert (offset < fsize);
447 if (depth == totaldepth)
450 if (offset + ret > fsize)
451 ret = (size_t) (fsize - offset);
456 for (i = totaldepth-1; i > depth; i--)
457 rsize *= CHK_PER_INODE;
458 epos = offset + rsize * CHK_PER_INODE;
459 GNUNET_assert (epos > offset);
462 /* round up when computing #CHKs in our IBlock */
463 chks = (epos - offset + rsize - 1) / rsize;
464 GNUNET_assert (chks <= CHK_PER_INODE);
465 return chks * sizeof (struct ContentHashKey);
470 * Closure for iterator processing results.
472 struct ProcessResultClosure
478 GNUNET_HashCode query;
481 * Data found in P2P network.
486 * Our download context.
488 struct GNUNET_FS_DownloadContext *dc;
491 * Number of bytes in data.
504 * We found an entry in a directory. Check if the respective child
505 * already exists and if not create the respective child download.
507 * @param cls the parent download
508 * @param filename name of the file in the directory
509 * @param uri URI of the file (CHK or LOC)
510 * @param meta meta data of the file
511 * @param length number of bytes in data
512 * @param data contents of the file (or NULL if they were not inlined)
515 trigger_recursive_download (void *cls,
516 const char *filename,
517 const struct GNUNET_FS_Uri *uri,
518 const struct GNUNET_CONTAINER_MetaData *meta,
522 struct GNUNET_FS_DownloadContext *dc = cls;
523 struct GNUNET_FS_DownloadContext *cpos;
531 return; /* entry for the directory itself */
532 cpos = dc->child_head;
535 if ( (GNUNET_FS_uri_test_equal (uri,
537 ( (filename != NULL) &&
538 (0 == strcmp (cpos->filename,
544 return; /* already exists */
546 if (NULL == filename)
548 fn = GNUNET_FS_meta_data_suggest_filename (meta);
551 us = GNUNET_FS_uri_to_string (uri);
552 fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX
553 GNUNET_FS_URI_CHK_INFIX)]);
556 else if (fn[0] == '.')
559 us = GNUNET_FS_uri_to_string (uri);
560 GNUNET_asprintf (&fn,
562 &us[strlen (GNUNET_FS_URI_PREFIX
563 GNUNET_FS_URI_CHK_INFIX)], ext);
569 if (dc->filename == NULL)
575 dn = GNUNET_strdup (dc->filename);
576 GNUNET_break ( (strlen (dn) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
578 strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
579 GNUNET_FS_DIRECTORY_EXT)) );
580 dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
581 if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
582 ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
584 strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
585 GNUNET_FS_DIRECTORY_EXT)) ) )
587 GNUNET_asprintf (&full_name,
592 GNUNET_FS_DIRECTORY_EXT);
596 GNUNET_asprintf (&full_name,
604 if ( (full_name != NULL) &&
606 GNUNET_DISK_directory_create_for_file (full_name)) )
608 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
609 _("Failed to create directory for recursive download of `%s'\n"),
611 GNUNET_free (full_name);
612 GNUNET_free_non_null (fn);
618 if (full_name != NULL)
620 /* determine on-disk filename, write data! */
621 GNUNET_break (0); // FIXME: not implemented
625 /* FIXME: generate 'progress' events and move to
626 instant completion! */
627 GNUNET_break (0); // FIXME: not implemented
630 GNUNET_FS_download_start (dc->h,
635 GNUNET_FS_uri_chk_get_file_size (uri),
640 GNUNET_free_non_null (full_name);
641 GNUNET_free_non_null (fn);
646 * We're done downloading a directory. Open the file and
647 * trigger all of the (remaining) child downloads.
649 * @param dc context of download that just completed
652 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
657 struct GNUNET_DISK_FileHandle *h;
658 struct GNUNET_DISK_MapHandle *m;
660 size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
661 size = (size_t) size64;
662 if (size64 != (uint64_t) size)
664 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
665 _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
668 if (dc->filename != NULL)
670 h = GNUNET_DISK_file_open (dc->filename,
671 GNUNET_DISK_OPEN_READ,
672 GNUNET_DISK_PERM_NONE);
676 /* FIXME: need to initialize (and use) temp_filename
677 in various places in order for this assertion to
678 not fail; right now, it will always fail! */
679 GNUNET_assert (dc->temp_filename != NULL);
680 h = GNUNET_DISK_file_open (dc->temp_filename,
681 GNUNET_DISK_OPEN_READ,
682 GNUNET_DISK_PERM_NONE);
686 data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
689 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
690 _("Directory too large for system address space\n"));
694 GNUNET_FS_directory_list_contents (size,
697 &trigger_recursive_download,
699 GNUNET_DISK_file_unmap (m);
701 GNUNET_DISK_file_close (h);
702 if (dc->filename == NULL)
704 if (0 != UNLINK (dc->temp_filename))
705 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
708 GNUNET_free (dc->temp_filename);
709 dc->temp_filename = NULL;
715 * Iterator over entries in the pending requests in the 'active' map for the
716 * reply that we just got.
718 * @param cls closure (our 'struct ProcessResultClosure')
719 * @param key query for the given value / request
720 * @param value value in the hash map (a 'struct DownloadRequest')
721 * @return GNUNET_YES (we should continue to iterate); unless serious error
724 process_result_with_request (void *cls,
725 const GNUNET_HashCode * key,
728 struct ProcessResultClosure *prc = cls;
729 struct DownloadRequest *sm = value;
730 struct GNUNET_FS_DownloadContext *dc = prc->dc;
731 struct GNUNET_CRYPTO_AesSessionKey skey;
732 struct GNUNET_CRYPTO_AesInitializationVector iv;
734 struct GNUNET_FS_ProgressInfo pi;
738 struct ContentHashKey *chk;
741 if (prc->size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748 "Internal error or bogus download URI (expected %u bytes, got %u)\n",
749 calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
755 dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
757 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
758 make_download_status (&pi, dc);
759 pi.value.download.specifics.error.message = dc->emsg;
760 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
762 /* abort all pending requests */
765 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
768 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
772 GNUNET_assert (GNUNET_YES ==
773 GNUNET_CONTAINER_multihashmap_remove (dc->active,
776 GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
777 GNUNET_CRYPTO_aes_decrypt (prc->data,
782 off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
787 if ( (NULL != dc->handle) &&
788 ( (sm->depth == dc->treedepth) ||
789 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
794 "Saving decrypted block to disk at offset %llu\n",
795 (unsigned long long) off);
798 GNUNET_DISK_file_seek (dc->handle,
800 GNUNET_DISK_SEEK_SET) ) )
801 GNUNET_asprintf (&emsg,
802 _("Failed to seek to offset %llu in file `%s': %s\n"),
803 (unsigned long long) off,
806 else if (prc->size !=
807 GNUNET_DISK_file_write (dc->handle,
810 GNUNET_asprintf (&emsg,
811 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
812 (unsigned int) prc->size,
813 (unsigned long long) off,
819 // FIXME: make persistent
822 pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
823 make_download_status (&pi, dc);
824 pi.value.download.specifics.error.message = emsg;
825 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
828 /* abort all pending requests */
831 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
834 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
840 if (sm->depth == dc->treedepth)
843 if (sm->offset < dc->offset)
845 /* starting offset begins in the middle of pt,
846 do not count first bytes as progress */
847 GNUNET_assert (app > (dc->offset - sm->offset));
848 app -= (dc->offset - sm->offset);
850 if (sm->offset + prc->size > dc->offset + dc->length)
852 /* end of block is after relevant range,
853 do not count last bytes as progress */
854 GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
855 app -= (sm->offset + prc->size) - (dc->offset + dc->length);
857 dc->completed += app;
859 /* do recursive download if option is set and either meta data
860 says it is a directory or if no meta data is given AND filename
861 ends in '.gnd' (top-level case) */
862 if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
863 ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
864 ( (dc->meta == NULL) &&
865 ( (NULL == dc->filename) ||
866 ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
868 strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
869 GNUNET_FS_DIRECTORY_EXT)) ) ) ) ) )
871 GNUNET_FS_directory_list_contents (prc->size,
874 &trigger_recursive_download,
880 pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
881 make_download_status (&pi, dc);
882 pi.value.download.specifics.progress.data = pt;
883 pi.value.download.specifics.progress.offset = sm->offset;
884 pi.value.download.specifics.progress.data_len = prc->size;
885 pi.value.download.specifics.progress.depth = sm->depth;
886 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
888 GNUNET_assert (dc->completed <= dc->length);
889 if (dc->completed == dc->length)
892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
893 "Download completed, truncating file to desired length %llu\n",
894 (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
896 /* truncate file to size (since we store IBlocks at the end) */
897 if (dc->handle != NULL)
899 GNUNET_DISK_file_close (dc->handle);
901 if (0 != truncate (dc->filename,
902 GNUNET_ntohll (dc->uri->data.chk.file_length)))
903 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
908 if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
909 (GNUNET_NO != GNUNET_FS_meta_data_test_for_directory (dc->meta)) )
910 full_recursive_download (dc);
911 if (dc->child_head == NULL)
913 /* signal completion */
914 pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
915 make_download_status (&pi, dc);
916 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
919 GNUNET_assert (sm->depth == dc->treedepth);
921 // FIXME: make persistent
922 if (sm->depth == dc->treedepth)
928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
929 "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
931 (unsigned long long) sm->offset);
933 GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
934 chk = (struct ContentHashKey*) pt;
935 for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
937 off = compute_dblock_offset (sm->offset,
941 if ( (off + DBLOCK_SIZE >= dc->offset) &&
942 (off < dc->offset + dc->length) )
943 schedule_block_download (dc,
954 * Process a download result.
956 * @param dc our download context
957 * @param type type of the result
958 * @param data the (encrypted) response
959 * @param size size of data
962 process_result (struct GNUNET_FS_DownloadContext *dc,
967 struct ProcessResultClosure prc;
973 GNUNET_CRYPTO_hash (data, size, &prc.query);
975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
976 "Received result for query `%s' from `%s'-service\n",
977 GNUNET_h2s (&prc.query),
980 GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
982 &process_result_with_request,
988 * Type of a function to call when we receive a message
992 * @param msg message received, NULL on timeout or fatal error
995 receive_results (void *cls,
996 const struct GNUNET_MessageHeader * msg)
998 struct GNUNET_FS_DownloadContext *dc = cls;
999 const struct PutMessage *cm;
1002 if ( (NULL == msg) ||
1003 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1004 (sizeof (struct PutMessage) > ntohs(msg->size)) )
1006 GNUNET_break (msg == NULL);
1010 msize = ntohs(msg->size);
1011 cm = (const struct PutMessage*) msg;
1015 msize - sizeof (struct PutMessage));
1016 if (dc->client == NULL)
1017 return; /* fatal error */
1018 /* continue receiving */
1019 GNUNET_CLIENT_receive (dc->client,
1022 GNUNET_TIME_UNIT_FOREVER_REL);
1028 * We're ready to transmit a search request to the
1029 * file-sharing service. Do it. If there is
1030 * more than one request pending, try to send
1031 * multiple or request another transmission.
1033 * @param cls closure
1034 * @param size number of bytes available in buf
1035 * @param buf where the callee should write the message
1036 * @return number of bytes written to buf
1039 transmit_download_request (void *cls,
1043 struct GNUNET_FS_DownloadContext *dc = cls;
1045 struct SearchMessage *sm;
1053 GNUNET_assert (size >= sizeof (struct SearchMessage));
1056 while ( (dc->pending != NULL) &&
1057 (size > msize + sizeof (struct SearchMessage)) )
1060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061 "Transmitting download request for `%s' to `%s'-service\n",
1062 GNUNET_h2s (&dc->pending->chk.query),
1065 memset (sm, 0, sizeof (struct SearchMessage));
1066 sm->header.size = htons (sizeof (struct SearchMessage));
1067 sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1068 if (dc->pending->depth == dc->treedepth)
1069 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
1071 sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
1072 sm->anonymity_level = htonl (dc->anonymity);
1073 sm->target = dc->target.hashPubKey;
1074 sm->query = dc->pending->chk.query;
1075 dc->pending->is_pending = GNUNET_NO;
1076 dc->pending = dc->pending->next;
1077 msize += sizeof (struct SearchMessage);
1080 if (dc->pending != NULL)
1081 dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1082 sizeof (struct SearchMessage),
1083 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1085 &transmit_download_request,
1092 * Reconnect to the FS service and transmit our queries NOW.
1094 * @param cls our download context
1098 do_reconnect (void *cls,
1099 const struct GNUNET_SCHEDULER_TaskContext *tc)
1101 struct GNUNET_FS_DownloadContext *dc = cls;
1102 struct GNUNET_CLIENT_Connection *client;
1104 dc->task = GNUNET_SCHEDULER_NO_TASK;
1105 client = GNUNET_CLIENT_connect (dc->h->sched,
1110 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1111 "Connecting to `%s'-service failed, will try again.\n",
1116 dc->client = client;
1117 dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1118 sizeof (struct SearchMessage),
1119 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1121 &transmit_download_request,
1123 GNUNET_CLIENT_receive (client,
1126 GNUNET_TIME_UNIT_FOREVER_REL);
1131 * Add entries that are not yet pending back to the pending list.
1133 * @param cls our download context
1135 * @param entry entry of type "struct DownloadRequest"
1139 retry_entry (void *cls,
1140 const GNUNET_HashCode *key,
1143 struct GNUNET_FS_DownloadContext *dc = cls;
1144 struct DownloadRequest *dr = entry;
1146 if (! dr->is_pending)
1148 dr->next = dc->pending;
1149 dr->is_pending = GNUNET_YES;
1150 dc->pending = entry;
1157 * We've lost our connection with the FS service.
1158 * Re-establish it and re-transmit all of our
1161 * @param dc download context that is having trouble
1164 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1167 if (NULL != dc->client)
1171 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1174 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1177 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1181 = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1182 GNUNET_TIME_UNIT_SECONDS,
1189 * Download parts of a file. Note that this will store
1190 * the blocks at the respective offset in the given file. Also, the
1191 * download is still using the blocking of the underlying FS
1192 * encoding. As a result, the download may *write* outside of the
1193 * given boundaries (if offset and length do not match the 32k FS
1194 * block boundaries). <p>
1196 * This function should be used to focus a download towards a
1197 * particular portion of the file (optimization), not to strictly
1198 * limit the download to exactly those bytes.
1200 * @param h handle to the file sharing subsystem
1201 * @param uri the URI of the file (determines what to download); CHK or LOC URI
1202 * @param meta known metadata for the file (can be NULL)
1203 * @param filename where to store the file, maybe NULL (then no file is
1204 * created on disk and data must be grabbed from the callbacks)
1205 * @param offset at what offset should we start the download (typically 0)
1206 * @param length how many bytes should be downloaded starting at offset
1207 * @param anonymity anonymity level to use for the download
1208 * @param options various options
1209 * @param cctx initial value for the client context for this download
1210 * @param parent parent download to associate this download with (use NULL
1211 * for top-level downloads; useful for manually-triggered recursive downloads)
1212 * @return context that can be used to control this download
1214 struct GNUNET_FS_DownloadContext *
1215 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1216 const struct GNUNET_FS_Uri *uri,
1217 const struct GNUNET_CONTAINER_MetaData *meta,
1218 const char *filename,
1222 enum GNUNET_FS_DownloadOptions options,
1224 struct GNUNET_FS_DownloadContext *parent)
1226 struct GNUNET_FS_ProgressInfo pi;
1227 struct GNUNET_FS_DownloadContext *dc;
1228 struct GNUNET_CLIENT_Connection *client;
1230 GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1231 if ( (offset + length < offset) ||
1232 (offset + length > uri->data.chk.file_length) )
1237 // FIXME: add support for "loc" URIs!
1239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1240 "Starting download `%s' of %llu bytes\n",
1242 (unsigned long long) length);
1244 dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1246 dc->parent = parent;
1249 GNUNET_CONTAINER_DLL_insert (parent->child_head,
1253 dc->uri = GNUNET_FS_uri_dup (uri);
1254 dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1255 dc->client_info = cctx;
1256 dc->start_time = GNUNET_TIME_absolute_get ();
1257 if (NULL != filename)
1259 dc->filename = GNUNET_strdup (filename);
1260 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1261 GNUNET_DISK_file_size (filename,
1264 dc->handle = GNUNET_DISK_file_open (filename,
1265 GNUNET_DISK_OPEN_READWRITE |
1266 GNUNET_DISK_OPEN_CREATE,
1267 GNUNET_DISK_PERM_USER_READ |
1268 GNUNET_DISK_PERM_USER_WRITE |
1269 GNUNET_DISK_PERM_GROUP_READ |
1270 GNUNET_DISK_PERM_OTHER_READ);
1271 if (dc->handle == NULL)
1273 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1274 _("Download failed: could not open file `%s': %s\n"),
1277 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1278 GNUNET_FS_uri_destroy (dc->uri);
1279 GNUNET_free (dc->filename);
1284 // FIXME: set "dc->target" for LOC uris!
1285 dc->offset = offset;
1286 dc->length = length;
1287 dc->anonymity = anonymity;
1288 dc->options = options;
1289 dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
1290 dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1293 "Download tree has depth %u\n",
1296 // FIXME: make persistent
1298 // FIXME: bound parallelism here!
1299 client = GNUNET_CLIENT_connect (h->sched,
1302 dc->client = client;
1303 schedule_block_download (dc,
1304 &dc->uri->data.chk.chk,
1306 1 /* 0 == CHK, 1 == top */);
1307 GNUNET_CLIENT_receive (client,
1310 GNUNET_TIME_UNIT_FOREVER_REL);
1311 pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1312 make_download_status (&pi, dc);
1313 pi.value.download.specifics.start.meta = meta;
1314 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1322 * Free entries in the map.
1324 * @param cls unused (NULL)
1326 * @param entry entry of type "struct DownloadRequest" which is freed
1330 free_entry (void *cls,
1331 const GNUNET_HashCode *key,
1334 GNUNET_free (entry);
1340 * Stop a download (aborts if download is incomplete).
1342 * @param dc handle for the download
1343 * @param do_delete delete files of incomplete downloads
1346 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1349 struct GNUNET_FS_ProgressInfo pi;
1351 while (NULL != dc->child_head)
1352 GNUNET_FS_download_stop (dc->child_head,
1354 // FIXME: make unpersistent
1355 if (dc->parent != NULL)
1356 GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1357 dc->parent->child_tail,
1360 pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1361 make_download_status (&pi, dc);
1362 dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1365 if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1366 GNUNET_SCHEDULER_cancel (dc->h->sched,
1370 GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1373 if (NULL != dc->client)
1374 GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1375 GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1378 GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1379 if (dc->filename != NULL)
1381 if (NULL != dc->handle)
1382 GNUNET_DISK_file_close (dc->handle);
1383 if ( (dc->completed != dc->length) &&
1384 (GNUNET_YES == do_delete) )
1386 if (0 != UNLINK (dc->filename))
1387 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1391 GNUNET_free (dc->filename);
1393 GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1394 GNUNET_FS_uri_destroy (dc->uri);
1398 /* end of fs_download.c */