-eliminate printing warning on MAGIC missmatch (#2138)
[oweals/gnunet.git] / src / fs / fs_download.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2011 Christian Grothoff (and other contributing authors)
4
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 3, or (at your
8      option) any later version.
9
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.
14
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.
19 */
20 /**
21  * @file fs/fs_download.c
22  * @brief download methods
23  * @author Christian Grothoff
24  *
25  * TODO:
26  * - different priority for scheduling probe downloads?
27  */
28 #include "platform.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_fs_service.h"
31 #include "fs_api.h"
32 #include "fs_tree.h"
33
34 #define DEBUG_DOWNLOAD GNUNET_EXTRA_LOGGING
35
36 /**
37  * Determine if the given download (options and meta data) should cause
38  * use to try to do a recursive download.
39  */
40 static int
41 is_recursive_download (struct GNUNET_FS_DownloadContext *dc)
42 {
43   return (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
44       ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
45        ((dc->meta == NULL) &&
46         ((NULL == dc->filename) ||
47          ((strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
48           (NULL !=
49            strstr (dc->filename + strlen (dc->filename) -
50                    strlen (GNUNET_FS_DIRECTORY_EXT),
51                    GNUNET_FS_DIRECTORY_EXT))))));
52 }
53
54
55 /**
56  * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
57  * only have to truncate the file once we're done).
58  *
59  * Given the offset of a block (with respect to the DBLOCKS) and its
60  * depth, return the offset where we would store this block in the
61  * file.
62  *
63  * @param fsize overall file size
64  * @param off offset of the block in the file
65  * @param depth depth of the block in the tree, 0 for DBLOCK
66  * @return off for DBLOCKS (depth == treedepth),
67  *         otherwise an offset past the end
68  *         of the file that does not overlap
69  *         with the range for any other block
70  */
71 static uint64_t
72 compute_disk_offset (uint64_t fsize, uint64_t off, unsigned int depth)
73 {
74   unsigned int i;
75   uint64_t lsize;               /* what is the size of all IBlocks for depth "i"? */
76   uint64_t loff;                /* where do IBlocks for depth "i" start? */
77   unsigned int ioff;            /* which IBlock corresponds to "off" at depth "i"? */
78
79   if (depth == 0)
80     return off;
81   /* first IBlocks start at the end of file, rounded up
82    * to full DBLOCK_SIZE */
83   loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
84   lsize =
85       ((fsize + DBLOCK_SIZE -
86         1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
87   GNUNET_assert (0 == (off % DBLOCK_SIZE));
88   ioff = (off / DBLOCK_SIZE);
89   for (i = 1; i < depth; i++)
90   {
91     loff += lsize;
92     lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
93     GNUNET_assert (lsize > 0);
94     GNUNET_assert (0 == (ioff % CHK_PER_INODE));
95     ioff /= CHK_PER_INODE;
96   }
97   return loff + ioff * sizeof (struct ContentHashKey);
98 }
99
100
101 /**
102  * Fill in all of the generic fields for a download event and call the
103  * callback.
104  *
105  * @param pi structure to fill in
106  * @param dc overall download context
107  */
108 void
109 GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
110                                  struct GNUNET_FS_DownloadContext *dc)
111 {
112   pi->value.download.dc = dc;
113   pi->value.download.cctx = dc->client_info;
114   pi->value.download.pctx =
115       (dc->parent == NULL) ? NULL : dc->parent->client_info;
116   pi->value.download.sctx =
117       (dc->search == NULL) ? NULL : dc->search->client_info;
118   pi->value.download.uri = dc->uri;
119   pi->value.download.filename = dc->filename;
120   pi->value.download.size = dc->length;
121   /* FIXME: Fix duration calculation to account for pauses */
122   pi->value.download.duration =
123       GNUNET_TIME_absolute_get_duration (dc->start_time);
124   pi->value.download.completed = dc->completed;
125   pi->value.download.anonymity = dc->anonymity;
126   pi->value.download.eta =
127       GNUNET_TIME_calculate_eta (dc->start_time, dc->completed, dc->length);
128   pi->value.download.is_active = (dc->client == NULL) ? GNUNET_NO : GNUNET_YES;
129   if (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE))
130     dc->client_info = dc->h->upcb (dc->h->upcb_cls, pi);
131   else
132     dc->client_info = GNUNET_FS_search_probe_progress_ (NULL, pi);
133 }
134
135
136 /**
137  * We're ready to transmit a search request to the
138  * file-sharing service.  Do it.  If there is
139  * more than one request pending, try to send
140  * multiple or request another transmission.
141  *
142  * @param cls closure
143  * @param size number of bytes available in buf
144  * @param buf where the callee should write the message
145  * @return number of bytes written to buf
146  */
147 static size_t
148 transmit_download_request (void *cls, size_t size, void *buf);
149
150
151 /**
152  * Closure for iterator processing results.
153  */
154 struct ProcessResultClosure
155 {
156
157   /**
158    * Hash of data.
159    */
160   GNUNET_HashCode query;
161
162   /**
163    * Data found in P2P network.
164    */
165   const void *data;
166
167   /**
168    * Our download context.
169    */
170   struct GNUNET_FS_DownloadContext *dc;
171
172   /**
173    * Number of bytes in data.
174    */
175   size_t size;
176
177   /**
178    * Type of data.
179    */
180   enum GNUNET_BLOCK_Type type;
181
182   /**
183    * Flag to indicate if this block should be stored on disk.
184    */
185   int do_store;
186
187   struct GNUNET_TIME_Absolute last_transmission;
188
189 };
190
191
192 /**
193  * Iterator over entries in the pending requests in the 'active' map for the
194  * reply that we just got.
195  *
196  * @param cls closure (our 'struct ProcessResultClosure')
197  * @param key query for the given value / request
198  * @param value value in the hash map (a 'struct DownloadRequest')
199  * @return GNUNET_YES (we should continue to iterate); unless serious error
200  */
201 static int
202 process_result_with_request (void *cls, const GNUNET_HashCode * key,
203                              void *value);
204
205
206 /**
207  * We've found a matching block without downloading it.
208  * Encrypt it and pass it to our "receive" function as
209  * if we had received it from the network.
210  *
211  * @param dc download in question
212  * @param chk request this relates to
213  * @param dr request details
214  * @param block plaintext data matching request
215  * @param len number of bytes in block
216  * @param do_store should we still store the block on disk?
217  * @return GNUNET_OK on success
218  */
219 static int
220 encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc,
221                         const struct ContentHashKey *chk,
222                         struct DownloadRequest *dr, const char *block,
223                         size_t len, int do_store)
224 {
225   struct ProcessResultClosure prc;
226   char enc[len];
227   struct GNUNET_CRYPTO_AesSessionKey sk;
228   struct GNUNET_CRYPTO_AesInitializationVector iv;
229   GNUNET_HashCode query;
230
231   GNUNET_CRYPTO_hash_to_aes_key (&chk->key, &sk, &iv);
232   if (-1 == GNUNET_CRYPTO_aes_encrypt (block, len, &sk, &iv, enc))
233   {
234     GNUNET_break (0);
235     return GNUNET_SYSERR;
236   }
237   GNUNET_CRYPTO_hash (enc, len, &query);
238   if (0 != memcmp (&query, &chk->query, sizeof (GNUNET_HashCode)))
239   {
240     GNUNET_break_op (0);
241     return GNUNET_SYSERR;
242   }
243 #if DEBUG_DOWNLOAD
244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
245               "Matching block for `%s' at offset %llu already present, no need for download!\n",
246               dc->filename, (unsigned long long) dr->offset);
247 #endif
248   /* already got it! */
249   prc.dc = dc;
250   prc.data = enc;
251   prc.size = len;
252   prc.type =
253       (0 ==
254        dr->depth) ? GNUNET_BLOCK_TYPE_FS_DBLOCK : GNUNET_BLOCK_TYPE_FS_IBLOCK;
255   prc.query = chk->query;
256   prc.do_store = do_store;
257   prc.last_transmission = GNUNET_TIME_UNIT_FOREVER_ABS;
258   process_result_with_request (&prc, &chk->key, dr);
259   return GNUNET_OK;
260 }
261
262
263 /**
264  * We've lost our connection with the FS service.
265  * Re-establish it and re-transmit all of our
266  * pending requests.
267  *
268  * @param dc download context that is having trouble
269  */
270 static void
271 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
272
273
274 /**
275  * We found an entry in a directory.  Check if the respective child
276  * already exists and if not create the respective child download.
277  *
278  * @param cls the parent download
279  * @param filename name of the file in the directory
280  * @param uri URI of the file (CHK or LOC)
281  * @param meta meta data of the file
282  * @param length number of bytes in data
283  * @param data contents of the file (or NULL if they were not inlined)
284  */
285 static void
286 trigger_recursive_download (void *cls, const char *filename,
287                             const struct GNUNET_FS_Uri *uri,
288                             const struct GNUNET_CONTAINER_MetaData *meta,
289                             size_t length, const void *data);
290
291
292 /**
293  * We're done downloading a directory.  Open the file and
294  * trigger all of the (remaining) child downloads.
295  *
296  * @param dc context of download that just completed
297  */
298 static void
299 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
300 {
301   size_t size;
302   uint64_t size64;
303   void *data;
304   struct GNUNET_DISK_FileHandle *h;
305   struct GNUNET_DISK_MapHandle *m;
306
307   size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
308   size = (size_t) size64;
309   if (size64 != (uint64_t) size)
310   {
311     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
312                 _
313                 ("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
314     return;
315   }
316   if (dc->filename != NULL)
317   {
318     h = GNUNET_DISK_file_open (dc->filename, GNUNET_DISK_OPEN_READ,
319                                GNUNET_DISK_PERM_NONE);
320   }
321   else
322   {
323     GNUNET_assert (dc->temp_filename != NULL);
324     h = GNUNET_DISK_file_open (dc->temp_filename, GNUNET_DISK_OPEN_READ,
325                                GNUNET_DISK_PERM_NONE);
326   }
327   if (h == NULL)
328     return;                     /* oops */
329   data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
330   if (data == NULL)
331   {
332     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
333                 _("Directory too large for system address space\n"));
334   }
335   else
336   {
337     GNUNET_FS_directory_list_contents (size, data, 0,
338                                        &trigger_recursive_download, dc);
339     GNUNET_DISK_file_unmap (m);
340   }
341   GNUNET_DISK_file_close (h);
342   if (dc->filename == NULL)
343   {
344     if (0 != UNLINK (dc->temp_filename))
345       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
346                                 dc->temp_filename);
347     GNUNET_free (dc->temp_filename);
348     dc->temp_filename = NULL;
349   }
350 }
351
352
353 /**
354  * Check if all child-downloads have completed (or trigger them if
355  * necessary) and once we're completely done, signal completion (and
356  * possibly recurse to parent).  This function MUST be called when the
357  * download of a file itself is done or when the download of a file is
358  * done and then later a direct child download has completed (and
359  * hence this download may complete itself).
360  *
361  * @param dc download to check for completion of children
362  */
363 static void
364 check_completed (struct GNUNET_FS_DownloadContext *dc)
365 {
366   struct GNUNET_FS_ProgressInfo pi;
367   struct GNUNET_FS_DownloadContext *pos;
368
369   /* first, check if we need to download children */
370   if ((dc->child_head == NULL) && (is_recursive_download (dc)))
371     full_recursive_download (dc);
372   /* then, check if children are done already */
373   pos = dc->child_head;
374   while (pos != NULL)
375   {
376     if ((pos->emsg == NULL) && (pos->completed < pos->length))
377       return;                   /* not done yet */
378     if ((pos->child_head != NULL) && (pos->has_finished != GNUNET_YES))
379       return;                   /* not transitively done yet */
380     pos = pos->next;
381   }
382   /* All of our children are done, so mark this download done */
383   dc->has_finished = GNUNET_YES;
384   if (dc->job_queue != NULL)
385   {
386     GNUNET_FS_dequeue_ (dc->job_queue);
387     dc->job_queue = NULL;
388   }
389   GNUNET_FS_download_sync_ (dc);
390
391   /* signal completion */
392   pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
393   GNUNET_FS_download_make_status_ (&pi, dc);
394
395   /* let parent know */
396   if (dc->parent != NULL)
397     check_completed (dc->parent);
398 }
399
400
401 /**
402  * We got a block of plaintext data (from the meta data).
403  * Try it for upward reconstruction of the data.  On success,
404  * the top-level block will move to state BRS_DOWNLOAD_UP.
405  *
406  * @param dc context for the download
407  * @param dr download request to match against
408  * @param data plaintext data, starting from the beginning of the file
409  * @param data_len number of bytes in data
410  */
411 static void
412 try_match_block (struct GNUNET_FS_DownloadContext *dc,
413                  struct DownloadRequest *dr, const char *data, size_t data_len)
414 {
415   struct GNUNET_FS_ProgressInfo pi;
416   unsigned int i;
417   char enc[DBLOCK_SIZE];
418   struct ContentHashKey chks[CHK_PER_INODE];
419   struct ContentHashKey in_chk;
420   struct GNUNET_CRYPTO_AesSessionKey sk;
421   struct GNUNET_CRYPTO_AesInitializationVector iv;
422   size_t dlen;
423   struct DownloadRequest *drc;
424   struct GNUNET_DISK_FileHandle *fh;
425   int complete;
426   const char *fn;
427   const char *odata;
428   size_t odata_len;
429
430   odata = data;
431   odata_len = data_len;
432   if (BRS_DOWNLOAD_UP == dr->state)
433     return;
434   if (dr->depth > 0)
435   {
436     complete = GNUNET_YES;
437     for (i = 0; i < dr->num_children; i++)
438     {
439       drc = dr->children[i];
440       try_match_block (dc, drc, data, data_len);
441       if (drc->state != BRS_RECONSTRUCT_META_UP)
442         complete = GNUNET_NO;
443       else
444         chks[i] = drc->chk;
445     }
446     if (GNUNET_YES != complete)
447       return;
448     data = (const char *) chks;
449     dlen = dr->num_children * sizeof (struct ContentHashKey);
450   }
451   else
452   {
453     if (dr->offset > data_len)
454       return;                   /* oops */
455     dlen = GNUNET_MIN (data_len - dr->offset, DBLOCK_SIZE);
456   }
457   GNUNET_CRYPTO_hash (&data[dr->offset], dlen, &in_chk.key);
458   GNUNET_CRYPTO_hash_to_aes_key (&in_chk.key, &sk, &iv);
459   if (-1 == GNUNET_CRYPTO_aes_encrypt (&data[dr->offset], dlen, &sk, &iv, enc))
460   {
461     GNUNET_break (0);
462     return;
463   }
464   GNUNET_CRYPTO_hash (enc, dlen, &in_chk.query);
465   switch (dr->state)
466   {
467   case BRS_INIT:
468     dr->chk = in_chk;
469     dr->state = BRS_RECONSTRUCT_META_UP;
470     break;
471   case BRS_CHK_SET:
472     if (0 != memcmp (&in_chk, &dr->chk, sizeof (struct ContentHashKey)))
473     {
474       /* other peer provided bogus meta data */
475       GNUNET_break_op (0);
476       break;
477     }
478     /* write block to disk */
479     fn = dc->filename != NULL ? dc->filename : dc->temp_filename;
480     fh = GNUNET_DISK_file_open (fn,
481                                 GNUNET_DISK_OPEN_READWRITE |
482                                 GNUNET_DISK_OPEN_CREATE |
483                                 GNUNET_DISK_OPEN_TRUNCATE,
484                                 GNUNET_DISK_PERM_USER_READ |
485                                 GNUNET_DISK_PERM_USER_WRITE |
486                                 GNUNET_DISK_PERM_GROUP_READ |
487                                 GNUNET_DISK_PERM_OTHER_READ);
488     if (fh == NULL)
489     {
490       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
491       GNUNET_asprintf (&dc->emsg, _("Failed to open file `%s' for writing"),
492                        fn);
493       GNUNET_DISK_file_close (fh);
494       dr->state = BRS_ERROR;
495       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
496       pi.value.download.specifics.error.message = dc->emsg;
497       GNUNET_FS_download_make_status_ (&pi, dc);
498       return;
499     }
500     if (data_len != GNUNET_DISK_file_write (fh, odata, odata_len))
501     {
502       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "write", fn);
503       GNUNET_asprintf (&dc->emsg, _("Failed to open file `%s' for writing"),
504                        fn);
505       GNUNET_DISK_file_close (fh);
506       dr->state = BRS_ERROR;
507       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
508       pi.value.download.specifics.error.message = dc->emsg;
509       GNUNET_FS_download_make_status_ (&pi, dc);
510       return;
511     }
512     GNUNET_DISK_file_close (fh);
513     /* signal success */
514     dr->state = BRS_DOWNLOAD_UP;
515     dc->completed = dc->length;
516     GNUNET_FS_download_sync_ (dc);
517     pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
518     pi.value.download.specifics.progress.data = data;
519     pi.value.download.specifics.progress.offset = 0;
520     pi.value.download.specifics.progress.data_len = dlen;
521     pi.value.download.specifics.progress.depth = 0;
522     pi.value.download.specifics.progress.trust_offered = 0;
523     GNUNET_FS_download_make_status_ (&pi, dc);
524     if ((NULL != dc->filename) &&
525         (0 !=
526          truncate (dc->filename,
527                    GNUNET_ntohll (dc->uri->data.chk.file_length))))
528       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
529                                 dc->filename);
530     check_completed (dc);
531     break;
532   default:
533     /* how did we get here? */
534     GNUNET_break (0);
535     break;
536   }
537 }
538
539
540 /**
541  * Type of a function that libextractor calls for each
542  * meta data item found.  If we find full data meta data,
543  * call 'try_match_block' on it.
544  *
545  * @param cls our 'struct GNUNET_FS_DownloadContext*'
546  * @param plugin_name name of the plugin that produced this value;
547  *        special values can be used (i.e. '&lt;zlib&gt;' for zlib being
548  *        used in the main libextractor library and yielding
549  *        meta data).
550  * @param type libextractor-type describing the meta data
551  * @param format basic format information about data
552  * @param data_mime_type mime-type of data (not of the original file);
553  *        can be NULL (if mime-type is not known)
554  * @param data actual meta-data found
555  * @param data_len number of bytes in data
556  * @return 0 to continue extracting, 1 to abort
557  */
558 static int
559 match_full_data (void *cls, const char *plugin_name,
560                  enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format,
561                  const char *data_mime_type, const char *data, size_t data_len)
562 {
563   struct GNUNET_FS_DownloadContext *dc = cls;
564
565   if (type != EXTRACTOR_METATYPE_GNUNET_FULL_DATA)
566     return 0;
567 #if DEBUG_DOWNLOAD
568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u bytes of FD!\n",
569               (unsigned int) data_len);
570 #endif
571   if (GNUNET_FS_uri_chk_get_file_size (dc->uri) != data_len)
572   {
573     GNUNET_break_op (0);
574     return 1;                   /* bogus meta data */
575   }
576   try_match_block (dc, dc->top_request, data, data_len);
577   return 1;
578 }
579
580
581 /**
582  * Set the state of the given download request to
583  * BRS_DOWNLOAD_UP and propagate it up the tree.
584  *
585  * @param dr download request that is done
586  */
587 static void
588 propagate_up (struct DownloadRequest *dr)
589 {
590   unsigned int i;
591
592   do
593   {
594     dr->state = BRS_DOWNLOAD_UP;
595     dr = dr->parent;
596     if (dr == NULL)
597       break;
598     for (i = 0; i < dr->num_children; i++)
599       if (dr->children[i]->state != BRS_DOWNLOAD_UP)
600         break;
601   }
602   while (i == dr->num_children);
603 }
604
605
606 /**
607  * Try top-down reconstruction.  Before, the given request node
608  * must have the state BRS_CHK_SET.  Afterwards, more nodes may
609  * have that state or advanced to BRS_DOWNLOAD_DOWN or even
610  * BRS_DOWNLOAD_UP.  It is also possible to get BRS_ERROR on the
611  * top level.
612  *
613  * @param dc overall download this block belongs to
614  * @param dr block to reconstruct
615  */
616 static void
617 try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc,
618                              struct DownloadRequest *dr)
619 {
620   uint64_t off;
621   char block[DBLOCK_SIZE];
622   GNUNET_HashCode key;
623   uint64_t total;
624   size_t len;
625   unsigned int i;
626   unsigned int chk_off;
627   struct DownloadRequest *drc;
628   uint64_t child_block_size;
629   const struct ContentHashKey *chks;
630   int up_done;
631
632   GNUNET_assert (dc->rfh != NULL);
633   GNUNET_assert (dr->state == BRS_CHK_SET);
634   total = GNUNET_FS_uri_chk_get_file_size (dc->uri);
635   GNUNET_assert (dr->depth < dc->treedepth);
636   len = GNUNET_FS_tree_calculate_block_size (total, dr->offset, dr->depth);
637   GNUNET_assert (len <= DBLOCK_SIZE);
638   off = compute_disk_offset (total, dr->offset, dr->depth);
639   if (dc->old_file_size < off + len)
640     return;                     /* failure */
641   if (off != GNUNET_DISK_file_seek (dc->rfh, off, GNUNET_DISK_SEEK_SET))
642   {
643     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "seek", dc->filename);
644     return;                     /* failure */
645   }
646   if (len != GNUNET_DISK_file_read (dc->rfh, block, len))
647   {
648     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "read", dc->filename);
649     return;                     /* failure */
650   }
651   GNUNET_CRYPTO_hash (block, len, &key);
652   if (0 != memcmp (&key, &dr->chk.key, sizeof (GNUNET_HashCode)))
653     return;                     /* mismatch */
654   if (GNUNET_OK !=
655       encrypt_existing_match (dc, &dr->chk, dr, block, len, GNUNET_NO))
656   {
657     /* hash matches but encrypted block does not, really bad */
658     dr->state = BRS_ERROR;
659     /* propagate up */
660     while (dr->parent != NULL)
661     {
662       dr = dr->parent;
663       dr->state = BRS_ERROR;
664     }
665     return;
666   }
667   /* block matches */
668   dr->state = BRS_DOWNLOAD_DOWN;
669
670   /* set CHKs for children */
671   up_done = GNUNET_YES;
672   chks = (const struct ContentHashKey *) block;
673   for (i = 0; i < dr->num_children; i++)
674   {
675     drc = dr->children[i];
676     GNUNET_assert (drc->offset >= dr->offset);
677     child_block_size = GNUNET_FS_tree_compute_tree_size (drc->depth);
678     GNUNET_assert (0 == (drc->offset - dr->offset) % child_block_size);
679     chk_off = (drc->offset - dr->offset) / child_block_size;
680     if (drc->state == BRS_INIT)
681     {
682       drc->state = BRS_CHK_SET;
683       drc->chk = chks[chk_off];
684       try_top_down_reconstruction (dc, drc);
685     }
686     if (drc->state != BRS_DOWNLOAD_UP)
687       up_done = GNUNET_NO;      /* children not all done */
688   }
689   if (up_done == GNUNET_YES)
690     propagate_up (dr);          /* children all done (or no children...) */
691 }
692
693
694 /**
695  * Schedule the download of the specified block in the tree.
696  *
697  * @param dc overall download this block belongs to
698  * @param dr request to schedule
699  */
700 static void
701 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
702                          struct DownloadRequest *dr)
703 {
704   unsigned int i;
705
706   switch (dr->state)
707   {
708   case BRS_INIT:
709     GNUNET_assert (0);
710     break;
711   case BRS_RECONSTRUCT_DOWN:
712     GNUNET_assert (0);
713     break;
714   case BRS_RECONSTRUCT_META_UP:
715     GNUNET_assert (0);
716     break;
717   case BRS_RECONSTRUCT_UP:
718     GNUNET_assert (0);
719     break;
720   case BRS_CHK_SET:
721     /* normal case, start download */
722     break;
723   case BRS_DOWNLOAD_DOWN:
724     for (i = 0; i < dr->num_children; i++)
725       schedule_block_download (dc, dr->children[i]);
726     return;
727   case BRS_DOWNLOAD_UP:
728     /* We're done! */
729     return;
730   case BRS_ERROR:
731     GNUNET_break (0);
732     return;
733   }
734 #if DEBUG_DOWNLOAD
735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
736               "Scheduling download at offset %llu and depth %u for `%s'\n",
737               (unsigned long long) dr->offset, dr->depth,
738               GNUNET_h2s (&dr->chk.query));
739 #endif
740   if (GNUNET_NO !=
741       GNUNET_CONTAINER_multihashmap_contains_value (dc->active, &dr->chk.query,
742                                                     dr))
743     return;                     /* already active */
744   GNUNET_CONTAINER_multihashmap_put (dc->active, &dr->chk.query, dr,
745                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
746   if (dc->client == NULL)
747     return;                     /* download not active */
748   GNUNET_CONTAINER_DLL_insert (dc->pending_head, dc->pending_tail, dr);
749   dr->is_pending = GNUNET_YES;
750   if (NULL == dc->th)
751     dc->th =
752         GNUNET_CLIENT_notify_transmit_ready (dc->client,
753                                              sizeof (struct SearchMessage),
754                                              GNUNET_CONSTANTS_SERVICE_TIMEOUT,
755                                              GNUNET_NO,
756                                              &transmit_download_request, dc);
757 }
758
759
760 #define GNUNET_FS_URI_CHK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_CHK_INFIX
761
762 /**
763  * We found an entry in a directory.  Check if the respective child
764  * already exists and if not create the respective child download.
765  *
766  * @param cls the parent download
767  * @param filename name of the file in the directory
768  * @param uri URI of the file (CHK or LOC)
769  * @param meta meta data of the file
770  * @param length number of bytes in data
771  * @param data contents of the file (or NULL if they were not inlined)
772  */
773 static void
774 trigger_recursive_download (void *cls, const char *filename,
775                             const struct GNUNET_FS_Uri *uri,
776                             const struct GNUNET_CONTAINER_MetaData *meta,
777                             size_t length, const void *data)
778 {
779   struct GNUNET_FS_DownloadContext *dc = cls;
780   struct GNUNET_FS_DownloadContext *cpos;
781   char *temp_name;
782   char *fn;
783   char *us;
784   char *ext;
785   char *dn;
786   char *pos;
787   char *full_name;
788   char *sfn;
789
790   if (NULL == uri)
791     return;                     /* entry for the directory itself */
792   cpos = dc->child_head;
793   while (cpos != NULL)
794   {
795     if ((GNUNET_FS_uri_test_equal (uri, cpos->uri)) ||
796         ((filename != NULL) && (0 == strcmp (cpos->filename, filename))))
797       break;
798     cpos = cpos->next;
799   }
800   if (cpos != NULL)
801     return;                     /* already exists */
802   fn = NULL;
803   if (NULL == filename)
804   {
805     fn = GNUNET_FS_meta_data_suggest_filename (meta);
806     if (fn == NULL)
807     {
808       us = GNUNET_FS_uri_to_string (uri);
809       fn = GNUNET_strdup (&us[strlen (GNUNET_FS_URI_CHK_PREFIX)]);
810       GNUNET_free (us);
811     }
812     else if (fn[0] == '.')
813     {
814       ext = fn;
815       us = GNUNET_FS_uri_to_string (uri);
816       GNUNET_asprintf (&fn, "%s%s", &us[strlen (GNUNET_FS_URI_CHK_PREFIX)],
817                        ext);
818       GNUNET_free (ext);
819       GNUNET_free (us);
820     }
821     /* change '\' to '/' (this should have happened
822      * during insertion, but malicious peers may
823      * not have done this) */
824     while (NULL != (pos = strstr (fn, "\\")))
825       *pos = '/';
826     /* remove '../' everywhere (again, well-behaved
827      * peers don't do this, but don't trust that
828      * we did not get something nasty) */
829     while (NULL != (pos = strstr (fn, "../")))
830     {
831       pos[0] = '_';
832       pos[1] = '_';
833       pos[2] = '_';
834     }
835     filename = fn;
836   }
837   if (dc->filename == NULL)
838   {
839     full_name = NULL;
840   }
841   else
842   {
843     dn = GNUNET_strdup (dc->filename);
844     GNUNET_break ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
845                   (NULL !=
846                    strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
847                            GNUNET_FS_DIRECTORY_EXT)));
848     sfn = GNUNET_strdup (filename);
849     while ((strlen (sfn) > 0) && (filename[strlen (sfn) - 1] == '/'))
850       sfn[strlen (sfn) - 1] = '\0';
851     if ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
852         (NULL !=
853          strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT),
854                  GNUNET_FS_DIRECTORY_EXT)))
855       dn[strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';
856     if ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
857         ((strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
858          (NULL ==
859           strstr (filename + strlen (filename) -
860                   strlen (GNUNET_FS_DIRECTORY_EXT), GNUNET_FS_DIRECTORY_EXT))))
861     {
862       GNUNET_asprintf (&full_name, "%s%s%s%s", dn, DIR_SEPARATOR_STR, sfn,
863                        GNUNET_FS_DIRECTORY_EXT);
864     }
865     else
866     {
867       GNUNET_asprintf (&full_name, "%s%s%s", dn, DIR_SEPARATOR_STR, sfn);
868     }
869     GNUNET_free (sfn);
870     GNUNET_free (dn);
871   }
872   if ((full_name != NULL) &&
873       (GNUNET_OK != GNUNET_DISK_directory_create_for_file (full_name)))
874   {
875     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
876                 _
877                 ("Failed to create directory for recursive download of `%s'\n"),
878                 full_name);
879     GNUNET_free (full_name);
880     GNUNET_free_non_null (fn);
881     return;
882   }
883
884   temp_name = NULL;
885 #if DEBUG_DOWNLOAD
886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887               "Triggering recursive download of size %llu with %u bytes MD\n",
888               (unsigned long long) GNUNET_FS_uri_chk_get_file_size (uri),
889               (unsigned int)
890               GNUNET_CONTAINER_meta_data_get_serialized_size (meta));
891 #endif
892   GNUNET_FS_download_start (dc->h, uri, meta, full_name, temp_name, 0,
893                             GNUNET_FS_uri_chk_get_file_size (uri),
894                             dc->anonymity, dc->options, NULL, dc);
895   GNUNET_free_non_null (full_name);
896   GNUNET_free_non_null (temp_name);
897   GNUNET_free_non_null (fn);
898 }
899
900
901 /**
902  * (recursively) free download request structure
903  *
904  * @param dr request to free
905  */
906 void
907 GNUNET_FS_free_download_request_ (struct DownloadRequest *dr)
908 {
909   unsigned int i;
910
911   if (dr == NULL)
912     return;
913   for (i = 0; i < dr->num_children; i++)
914     GNUNET_FS_free_download_request_ (dr->children[i]);
915   GNUNET_free_non_null (dr->children);
916   GNUNET_free (dr);
917 }
918
919
920 /**
921  * Iterator over entries in the pending requests in the 'active' map for the
922  * reply that we just got.
923  *
924  * @param cls closure (our 'struct ProcessResultClosure')
925  * @param key query for the given value / request
926  * @param value value in the hash map (a 'struct DownloadRequest')
927  * @return GNUNET_YES (we should continue to iterate); unless serious error
928  */
929 static int
930 process_result_with_request (void *cls, const GNUNET_HashCode * key,
931                              void *value)
932 {
933   struct ProcessResultClosure *prc = cls;
934   struct DownloadRequest *dr = value;
935   struct GNUNET_FS_DownloadContext *dc = prc->dc;
936   struct DownloadRequest *drc;
937   struct GNUNET_DISK_FileHandle *fh = NULL;
938   struct GNUNET_CRYPTO_AesSessionKey skey;
939   struct GNUNET_CRYPTO_AesInitializationVector iv;
940   char pt[prc->size];
941   struct GNUNET_FS_ProgressInfo pi;
942   uint64_t off;
943   size_t bs;
944   size_t app;
945   int i;
946   struct ContentHashKey *chkarr;
947
948 #if DEBUG_DOWNLOAD
949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
950               "Received block `%s' matching pending request at depth %u and offset %llu/%llu\n",
951               GNUNET_h2s (key), dr->depth, (unsigned long long) dr->offset,
952               (unsigned long long) GNUNET_ntohll (dc->uri->data.
953                                                   chk.file_length));
954
955 #endif
956   bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll
957                                             (dc->uri->data.chk.file_length),
958                                             dr->offset, dr->depth);
959   if (prc->size != bs)
960   {
961     GNUNET_asprintf (&dc->emsg,
962                      _
963                      ("Internal error or bogus download URI (expected %u bytes at depth %u and offset %llu/%llu, got %u bytes)\n"),
964                      bs, dr->depth, (unsigned long long) dr->offset,
965                      (unsigned long long) GNUNET_ntohll (dc->uri->data.
966                                                          chk.file_length),
967                      prc->size);
968     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s", dc->emsg);
969     while (dr->parent != NULL)
970     {
971       dr->state = BRS_ERROR;
972       dr = dr->parent;
973     }
974     dr->state = BRS_ERROR;
975     goto signal_error;
976   }
977
978   (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &prc->query, dr);
979   if (GNUNET_YES == dr->is_pending)
980   {
981     GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
982     dr->is_pending = GNUNET_NO;
983   }
984
985
986   GNUNET_CRYPTO_hash_to_aes_key (&dr->chk.key, &skey, &iv);
987   if (-1 == GNUNET_CRYPTO_aes_decrypt (prc->data, prc->size, &skey, &iv, pt))
988   {
989     GNUNET_break (0);
990     dc->emsg = GNUNET_strdup (_("internal error decrypting content"));
991     goto signal_error;
992   }
993   off =
994       compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
995                            dr->offset, dr->depth);
996   /* save to disk */
997   if ((GNUNET_YES == prc->do_store) &&
998       ((dc->filename != NULL) || (is_recursive_download (dc))) &&
999       ((dr->depth == dc->treedepth) ||
1000        (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES))))
1001   {
1002     fh = GNUNET_DISK_file_open (dc->filename !=
1003                                 NULL ? dc->filename : dc->temp_filename,
1004                                 GNUNET_DISK_OPEN_READWRITE |
1005                                 GNUNET_DISK_OPEN_CREATE,
1006                                 GNUNET_DISK_PERM_USER_READ |
1007                                 GNUNET_DISK_PERM_USER_WRITE |
1008                                 GNUNET_DISK_PERM_GROUP_READ |
1009                                 GNUNET_DISK_PERM_OTHER_READ);
1010     if (NULL == fh)
1011     {
1012       GNUNET_asprintf (&dc->emsg,
1013                        _("Download failed: could not open file `%s': %s\n"),
1014                        dc->filename, STRERROR (errno));
1015       goto signal_error;
1016     }
1017 #if DEBUG_DOWNLOAD
1018     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019                 "Saving decrypted block to disk at offset %llu\n",
1020                 (unsigned long long) off);
1021 #endif
1022     if ((off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)))
1023     {
1024       GNUNET_asprintf (&dc->emsg,
1025                        _("Failed to seek to offset %llu in file `%s': %s\n"),
1026                        (unsigned long long) off, dc->filename,
1027                        STRERROR (errno));
1028       goto signal_error;
1029     }
1030     if (prc->size != GNUNET_DISK_file_write (fh, pt, prc->size))
1031     {
1032       GNUNET_asprintf (&dc->emsg,
1033                        _
1034                        ("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
1035                        (unsigned int) prc->size, (unsigned long long) off,
1036                        dc->filename, STRERROR (errno));
1037       goto signal_error;
1038     }
1039     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh));
1040     fh = NULL;
1041   }
1042
1043   if (dr->depth == 0)
1044   {
1045     /* DBLOCK, update progress and try recursion if applicable */
1046     app = prc->size;
1047     if (dr->offset < dc->offset)
1048     {
1049       /* starting offset begins in the middle of pt,
1050        * do not count first bytes as progress */
1051       GNUNET_assert (app > (dc->offset - dr->offset));
1052       app -= (dc->offset - dr->offset);
1053     }
1054     if (dr->offset + prc->size > dc->offset + dc->length)
1055     {
1056       /* end of block is after relevant range,
1057        * do not count last bytes as progress */
1058       GNUNET_assert (app >
1059                      (dr->offset + prc->size) - (dc->offset + dc->length));
1060       app -= (dr->offset + prc->size) - (dc->offset + dc->length);
1061     }
1062     dc->completed += app;
1063
1064     /* do recursive download if option is set and either meta data
1065      * says it is a directory or if no meta data is given AND filename
1066      * ends in '.gnd' (top-level case) */
1067     if (is_recursive_download (dc))
1068       GNUNET_FS_directory_list_contents (prc->size, pt, off,
1069                                          &trigger_recursive_download, dc);
1070
1071   }
1072   dr->state = BRS_DOWNLOAD_DOWN;
1073   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1074   pi.value.download.specifics.progress.data = pt;
1075   pi.value.download.specifics.progress.offset = dr->offset;
1076   pi.value.download.specifics.progress.data_len = prc->size;
1077   pi.value.download.specifics.progress.depth = dr->depth;
1078   pi.value.download.specifics.progress.trust_offered = 0;
1079   if (prc->last_transmission.abs_value != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
1080     pi.value.download.specifics.progress.block_download_duration =
1081         GNUNET_TIME_absolute_get_duration (prc->last_transmission);
1082   else
1083     pi.value.download.specifics.progress.block_download_duration.rel_value = 
1084         GNUNET_TIME_UNIT_FOREVER_REL.rel_value;
1085   GNUNET_FS_download_make_status_ (&pi, dc);
1086   GNUNET_assert (dc->completed <= dc->length);
1087   if (dr->depth == 0)
1088     propagate_up (dr);
1089
1090   if (dc->completed == dc->length)
1091   {
1092     /* download completed, signal */
1093 #if DEBUG_DOWNLOAD
1094     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1095                 "Download completed, truncating file to desired length %llu\n",
1096                 (unsigned long long) GNUNET_ntohll (dc->uri->data.
1097                                                     chk.file_length));
1098 #endif
1099     /* truncate file to size (since we store IBlocks at the end) */
1100     if (dc->filename != NULL)
1101     {
1102       if (0 !=
1103           truncate (dc->filename,
1104                     GNUNET_ntohll (dc->uri->data.chk.file_length)))
1105         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate",
1106                                   dc->filename);
1107     }
1108     GNUNET_assert (dr->depth == 0);
1109     check_completed (dc);
1110   }
1111   if (dr->depth == 0)
1112   {
1113     /* bottom of the tree, no child downloads possible, just sync */
1114     GNUNET_FS_download_sync_ (dc);
1115     return GNUNET_YES;
1116   }
1117
1118 #if DEBUG_DOWNLOAD
1119   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1120               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1121               dr->depth, (unsigned long long) dr->offset);
1122 #endif
1123   GNUNET_assert (0 == (prc->size % sizeof (struct ContentHashKey)));
1124   chkarr = (struct ContentHashKey *) pt;
1125   for (i = (prc->size / sizeof (struct ContentHashKey)) - 1; i >= 0; i--)
1126   {
1127     drc = dr->children[i];
1128     switch (drc->state)
1129     {
1130     case BRS_INIT:
1131       drc->chk = chkarr[i];
1132       drc->state = BRS_CHK_SET;
1133       schedule_block_download (dc, drc);
1134       break;
1135     case BRS_RECONSTRUCT_DOWN:
1136       GNUNET_assert (0);
1137       break;
1138     case BRS_RECONSTRUCT_META_UP:
1139       GNUNET_assert (0);
1140       break;
1141     case BRS_RECONSTRUCT_UP:
1142       GNUNET_assert (0);
1143       break;
1144     case BRS_CHK_SET:
1145       GNUNET_assert (0);
1146       break;
1147     case BRS_DOWNLOAD_DOWN:
1148       GNUNET_assert (0);
1149       break;
1150     case BRS_DOWNLOAD_UP:
1151       GNUNET_assert (0);
1152       break;
1153     case BRS_ERROR:
1154       GNUNET_assert (0);
1155       break;
1156     default:
1157       GNUNET_assert (0);
1158       break;
1159     }
1160   }
1161   GNUNET_FS_download_sync_ (dc);
1162   return GNUNET_YES;
1163
1164 signal_error:
1165   if (fh != NULL)
1166     GNUNET_DISK_file_close (fh);
1167   pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1168   pi.value.download.specifics.error.message = dc->emsg;
1169   GNUNET_FS_download_make_status_ (&pi, dc);
1170   /* abort all pending requests */
1171   if (NULL != dc->th)
1172   {
1173     GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1174     dc->th = NULL;
1175   }
1176   GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1177   dc->in_receive = GNUNET_NO;
1178   dc->client = NULL;
1179   GNUNET_FS_free_download_request_ (dc->top_request);
1180   dc->top_request = NULL;
1181   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1182   dc->active = NULL;
1183   dc->pending_head = NULL;
1184   dc->pending_tail = NULL;
1185   GNUNET_FS_download_sync_ (dc);
1186   return GNUNET_NO;
1187 }
1188
1189
1190 /**
1191  * Process a download result.
1192  *
1193  * @param dc our download context
1194  * @param type type of the result
1195  * @param last_transmission when was this block requested the last time? (FOREVER if unknown/not applicable)
1196  * @param data the (encrypted) response
1197  * @param size size of data
1198  */
1199 static void
1200 process_result (struct GNUNET_FS_DownloadContext *dc,
1201                 enum GNUNET_BLOCK_Type type,
1202                 struct GNUNET_TIME_Absolute last_transmission,
1203                 const void *data, size_t size)
1204 {
1205   struct ProcessResultClosure prc;
1206
1207   prc.dc = dc;
1208   prc.data = data;
1209   prc.size = size;
1210   prc.type = type;
1211   prc.do_store = GNUNET_YES;
1212   prc.last_transmission = last_transmission;
1213   GNUNET_CRYPTO_hash (data, size, &prc.query);
1214 #if DEBUG_DOWNLOAD
1215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1216               "Received result for query `%s' from `%s'-service\n",
1217               GNUNET_h2s (&prc.query), "FS");
1218 #endif
1219   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active, &prc.query,
1220                                               &process_result_with_request,
1221                                               &prc);
1222 }
1223
1224
1225 /**
1226  * Type of a function to call when we receive a message
1227  * from the service.
1228  *
1229  * @param cls closure
1230  * @param msg message received, NULL on timeout or fatal error
1231  */
1232 static void
1233 receive_results (void *cls, const struct GNUNET_MessageHeader *msg)
1234 {
1235   struct GNUNET_FS_DownloadContext *dc = cls;
1236   const struct ClientPutMessage *cm;
1237   uint16_t msize;
1238
1239   if ((NULL == msg) || (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1240       (sizeof (struct ClientPutMessage) > ntohs (msg->size)))
1241   {
1242     GNUNET_break (msg == NULL);
1243     try_reconnect (dc);
1244     return;
1245   }
1246   msize = ntohs (msg->size);
1247   cm = (const struct ClientPutMessage *) msg;
1248   process_result (dc, ntohl (cm->type),
1249                   GNUNET_TIME_absolute_ntoh (cm->last_transmission), &cm[1],
1250                   msize - sizeof (struct ClientPutMessage));
1251   if (dc->client == NULL)
1252     return;                     /* fatal error */
1253   /* continue receiving */
1254   GNUNET_CLIENT_receive (dc->client, &receive_results, dc,
1255                          GNUNET_TIME_UNIT_FOREVER_REL);
1256 }
1257
1258
1259
1260 /**
1261  * We're ready to transmit a search request to the
1262  * file-sharing service.  Do it.  If there is
1263  * more than one request pending, try to send
1264  * multiple or request another transmission.
1265  *
1266  * @param cls closure
1267  * @param size number of bytes available in buf
1268  * @param buf where the callee should write the message
1269  * @return number of bytes written to buf
1270  */
1271 static size_t
1272 transmit_download_request (void *cls, size_t size, void *buf)
1273 {
1274   struct GNUNET_FS_DownloadContext *dc = cls;
1275   size_t msize;
1276   struct SearchMessage *sm;
1277   struct DownloadRequest *dr;
1278
1279   dc->th = NULL;
1280   if (NULL == buf)
1281   {
1282 #if DEBUG_DOWNLOAD
1283     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1284                 "Transmitting download request failed, trying to reconnect\n");
1285 #endif
1286     try_reconnect (dc);
1287     return 0;
1288   }
1289   GNUNET_assert (size >= sizeof (struct SearchMessage));
1290   msize = 0;
1291   sm = buf;
1292   while ((NULL != (dr = dc->pending_head)) &&
1293          (size >= msize + sizeof (struct SearchMessage)))
1294   {
1295 #if DEBUG_DOWNLOAD
1296     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1297                 "Transmitting download request for `%s' to `%s'-service\n",
1298                 GNUNET_h2s (&dr->chk.query), "FS");
1299 #endif
1300     memset (sm, 0, sizeof (struct SearchMessage));
1301     sm->header.size = htons (sizeof (struct SearchMessage));
1302     sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1303     if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1304       sm->options = htonl (GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY);
1305     else
1306       sm->options = htonl (GNUNET_FS_SEARCH_OPTION_NONE);
1307     if (dr->depth == 0)
1308       sm->type = htonl (GNUNET_BLOCK_TYPE_FS_DBLOCK);
1309     else
1310       sm->type = htonl (GNUNET_BLOCK_TYPE_FS_IBLOCK);
1311     sm->anonymity_level = htonl (dc->anonymity);
1312     sm->target = dc->target.hashPubKey;
1313     sm->query = dr->chk.query;
1314     GNUNET_CONTAINER_DLL_remove (dc->pending_head, dc->pending_tail, dr);
1315     dr->is_pending = GNUNET_NO;
1316     msize += sizeof (struct SearchMessage);
1317     sm++;
1318   }
1319   if (dc->pending_head != NULL)
1320   {
1321     dc->th =
1322         GNUNET_CLIENT_notify_transmit_ready (dc->client,
1323                                              sizeof (struct SearchMessage),
1324                                              GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1325                                              GNUNET_NO,
1326                                              &transmit_download_request, dc);
1327     GNUNET_assert (dc->th != NULL);
1328   }
1329   if (GNUNET_NO == dc->in_receive)
1330   {
1331     dc->in_receive = GNUNET_YES;
1332     GNUNET_CLIENT_receive (dc->client, &receive_results, dc,
1333                            GNUNET_TIME_UNIT_FOREVER_REL);
1334   }
1335   return msize;
1336 }
1337
1338
1339 /**
1340  * Reconnect to the FS service and transmit our queries NOW.
1341  *
1342  * @param cls our download context
1343  * @param tc unused
1344  */
1345 static void
1346 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1347 {
1348   struct GNUNET_FS_DownloadContext *dc = cls;
1349   struct GNUNET_CLIENT_Connection *client;
1350
1351   dc->task = GNUNET_SCHEDULER_NO_TASK;
1352   client = GNUNET_CLIENT_connect ("fs", dc->h->cfg);
1353   if (NULL == client)
1354   {
1355     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1356                 "Connecting to `%s'-service failed, will try again.\n", "FS");
1357     try_reconnect (dc);
1358     return;
1359   }
1360   dc->client = client;
1361   if (dc->pending_head != NULL)
1362   {
1363     dc->th =
1364         GNUNET_CLIENT_notify_transmit_ready (client,
1365                                              sizeof (struct SearchMessage),
1366                                              GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1367                                              GNUNET_NO,
1368                                              &transmit_download_request, dc);
1369     GNUNET_assert (dc->th != NULL);
1370   }
1371 }
1372
1373
1374 /**
1375  * Add entries to the pending list.
1376  *
1377  * @param cls our download context
1378  * @param key unused
1379  * @param entry entry of type "struct DownloadRequest"
1380  * @return GNUNET_OK
1381  */
1382 static int
1383 retry_entry (void *cls, const GNUNET_HashCode * key, void *entry)
1384 {
1385   struct GNUNET_FS_DownloadContext *dc = cls;
1386   struct DownloadRequest *dr = entry;
1387
1388   dr->next = NULL;
1389   dr->prev = NULL;
1390   GNUNET_CONTAINER_DLL_insert (dc->pending_head, dc->pending_tail, dr);
1391   dr->is_pending = GNUNET_YES;
1392   return GNUNET_OK;
1393 }
1394
1395
1396 /**
1397  * We've lost our connection with the FS service.
1398  * Re-establish it and re-transmit all of our
1399  * pending requests.
1400  *
1401  * @param dc download context that is having trouble
1402  */
1403 static void
1404 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1405 {
1406
1407   if (NULL != dc->client)
1408   {
1409 #if DEBUG_DOWNLOAD
1410     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1411                 "Moving all requests back to pending list\n");
1412 #endif
1413     if (NULL != dc->th)
1414     {
1415       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1416       dc->th = NULL;
1417     }
1418     /* full reset of the pending list */
1419     dc->pending_head = NULL;
1420     dc->pending_tail = NULL;
1421     GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1422     GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1423     dc->in_receive = GNUNET_NO;
1424     dc->client = NULL;
1425   }
1426 #if DEBUG_DOWNLOAD
1427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Will try to reconnect in 1s\n");
1428 #endif
1429   dc->task =
1430       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &do_reconnect,
1431                                     dc);
1432 }
1433
1434
1435 /**
1436  * We're allowed to ask the FS service for our blocks.  Start the download.
1437  *
1438  * @param cls the 'struct GNUNET_FS_DownloadContext'
1439  * @param client handle to use for communcation with FS (we must destroy it!)
1440  */
1441 static void
1442 activate_fs_download (void *cls, struct GNUNET_CLIENT_Connection *client)
1443 {
1444   struct GNUNET_FS_DownloadContext *dc = cls;
1445   struct GNUNET_FS_ProgressInfo pi;
1446
1447 #if DEBUG_DOWNLOAD
1448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download activated\n");
1449 #endif
1450   GNUNET_assert (NULL != client);
1451   GNUNET_assert (dc->client == NULL);
1452   GNUNET_assert (dc->th == NULL);
1453   dc->client = client;
1454   pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1455   GNUNET_FS_download_make_status_ (&pi, dc);
1456   dc->pending_head = NULL;
1457   dc->pending_tail = NULL;
1458   GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc);
1459 #if DEBUG_DOWNLOAD
1460   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1461               "Asking for transmission to FS service\n");
1462 #endif
1463   if (dc->pending_head != NULL)
1464   {
1465     dc->th =
1466         GNUNET_CLIENT_notify_transmit_ready (dc->client,
1467                                              sizeof (struct SearchMessage),
1468                                              GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1469                                              GNUNET_NO,
1470                                              &transmit_download_request, dc);
1471     GNUNET_assert (dc->th != NULL);
1472   }
1473 }
1474
1475
1476 /**
1477  * We must stop to ask the FS service for our blocks.  Pause the download.
1478  *
1479  * @param cls the 'struct GNUNET_FS_DownloadContext'
1480  */
1481 static void
1482 deactivate_fs_download (void *cls)
1483 {
1484   struct GNUNET_FS_DownloadContext *dc = cls;
1485   struct GNUNET_FS_ProgressInfo pi;
1486
1487 #if DEBUG_DOWNLOAD
1488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download deactivated\n");
1489 #endif
1490   if (NULL != dc->th)
1491   {
1492     GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1493     dc->th = NULL;
1494   }
1495   if (NULL != dc->client)
1496   {
1497     GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1498     dc->in_receive = GNUNET_NO;
1499     dc->client = NULL;
1500   }
1501   dc->pending_head = NULL;
1502   dc->pending_tail = NULL;
1503   pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE;
1504   GNUNET_FS_download_make_status_ (&pi, dc);
1505 }
1506
1507
1508 /**
1509  * (recursively) Create a download request structure.
1510  *
1511  * @param parent parent of the current entry
1512  * @param depth depth of the current entry, 0 are the DBLOCKs,
1513  *              top level block is 'dc->treedepth - 1'
1514  * @param dr_offset offset in the original file this block maps to
1515  *              (as in, offset of the first byte of the first DBLOCK
1516  *               in the subtree rooted in the returned download request tree)
1517  * @param file_start_offset desired starting offset for the download
1518  *             in the original file; requesting tree should not contain
1519  *             DBLOCKs prior to the file_start_offset
1520  * @param desired_length desired number of bytes the user wanted to access
1521  *        (from file_start_offset).  Resulting tree should not contain
1522  *        DBLOCKs after file_start_offset + file_length.
1523  * @return download request tree for the given range of DBLOCKs at
1524  *         the specified depth
1525  */
1526 static struct DownloadRequest *
1527 create_download_request (struct DownloadRequest *parent, unsigned int depth,
1528                          uint64_t dr_offset, uint64_t file_start_offset,
1529                          uint64_t desired_length)
1530 {
1531   struct DownloadRequest *dr;
1532   unsigned int i;
1533   unsigned int head_skip;
1534   uint64_t child_block_size;
1535
1536   dr = GNUNET_malloc (sizeof (struct DownloadRequest));
1537   dr->parent = parent;
1538   dr->depth = depth;
1539   dr->offset = dr_offset;
1540   if (depth > 0)
1541   {
1542     child_block_size = GNUNET_FS_tree_compute_tree_size (depth - 1);
1543
1544     /* calculate how many blocks at this level are not interesting
1545      * from the start (rounded down), either because of the requested
1546      * file offset or because this IBlock is further along */
1547     if (dr_offset < file_start_offset)
1548       head_skip = file_start_offset / child_block_size;
1549     else
1550       head_skip = dr_offset / child_block_size;
1551
1552     /* calculate index of last block at this level that is interesting (rounded up) */
1553     dr->num_children = file_start_offset + desired_length / child_block_size;
1554     if (dr->num_children * child_block_size <
1555         file_start_offset + desired_length)
1556       dr->num_children++;       /* round up */
1557
1558     /* now we can get the total number of children for this block */
1559     dr->num_children -= head_skip;
1560     if (dr->num_children > CHK_PER_INODE)
1561       dr->num_children = CHK_PER_INODE; /* cap at max */
1562
1563     /* why else would we have gotten here to begin with? (that'd be a bad logic error) */
1564     GNUNET_assert (dr->num_children > 0);
1565
1566     dr->children =
1567         GNUNET_malloc (dr->num_children * sizeof (struct DownloadRequest *));
1568     for (i = 0; i < dr->num_children; i++)
1569       dr->children[i] =
1570           create_download_request (dr, depth - 1,
1571                                    dr_offset + i * child_block_size,
1572                                    file_start_offset, desired_length);
1573   }
1574   return dr;
1575 }
1576
1577
1578 /**
1579  * Continuation after a possible attempt to reconstruct
1580  * the current IBlock from the existing file.
1581  *
1582  * @param cls the 'struct ReconstructContext'
1583  * @param tc scheduler context
1584  */
1585 static void
1586 reconstruct_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1587 {
1588   struct GNUNET_FS_DownloadContext *dc = cls;
1589
1590   /* clean up state from tree encoder */
1591   if (dc->te != NULL)
1592   {
1593     GNUNET_FS_tree_encoder_finish (dc->te, NULL, NULL);
1594     dc->te = NULL;
1595   }
1596   if (dc->task != GNUNET_SCHEDULER_NO_TASK)
1597   {
1598     GNUNET_SCHEDULER_cancel (dc->task);
1599     dc->task = GNUNET_SCHEDULER_NO_TASK;
1600   }
1601   if (dc->rfh != NULL)
1602   {
1603     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh));
1604     dc->rfh = NULL;
1605   }
1606   /* start "normal" download */
1607   schedule_block_download (dc, dc->top_request);
1608 }
1609
1610
1611 /**
1612  * Task requesting the next block from the tree encoder.
1613  *
1614  * @param cls the 'struct GNUJNET_FS_DownloadContext' we're processing
1615  * @param tc task context
1616  */
1617 static void
1618 get_next_block (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1619 {
1620   struct GNUNET_FS_DownloadContext *dc = cls;
1621
1622   dc->task = GNUNET_SCHEDULER_NO_TASK;
1623   GNUNET_FS_tree_encoder_next (dc->te);
1624 }
1625
1626
1627
1628 /**
1629  * Function called asking for the current (encoded)
1630  * block to be processed.  After processing the
1631  * client should either call "GNUNET_FS_tree_encode_next"
1632  * or (on error) "GNUNET_FS_tree_encode_finish".
1633  *
1634  * This function checks if the content on disk matches
1635  * the expected content based on the URI.
1636  *
1637  * @param cls closure
1638  * @param chk content hash key for the block
1639  * @param offset offset of the block
1640  * @param depth depth of the block, 0 for DBLOCK
1641  * @param type type of the block (IBLOCK or DBLOCK)
1642  * @param block the (encrypted) block
1643  * @param block_size size of block (in bytes)
1644  */
1645 static void
1646 reconstruct_cb (void *cls, const struct ContentHashKey *chk, uint64_t offset,
1647                 unsigned int depth, enum GNUNET_BLOCK_Type type,
1648                 const void *block, uint16_t block_size)
1649 {
1650   struct GNUNET_FS_DownloadContext *dc = cls;
1651   struct GNUNET_FS_ProgressInfo pi;
1652   struct DownloadRequest *dr;
1653   uint64_t blen;
1654   unsigned int chld;
1655
1656   /* find corresponding request entry */
1657   dr = dc->top_request;
1658   while (dr->depth > depth)
1659   {
1660     blen = GNUNET_FS_tree_compute_tree_size (dr->depth);
1661     chld = (offset - dr->offset) / blen;
1662     GNUNET_assert (chld < dr->num_children);
1663     dr = dr->children[chld];
1664   }
1665   switch (dr->state)
1666   {
1667   case BRS_INIT:
1668     break;
1669   case BRS_RECONSTRUCT_DOWN:
1670     break;
1671   case BRS_RECONSTRUCT_META_UP:
1672     break;
1673   case BRS_RECONSTRUCT_UP:
1674     break;
1675   case BRS_CHK_SET:
1676     if (0 == memcmp (chk, &dr->chk, sizeof (struct ContentHashKey)))
1677     {
1678       /* block matches, hence tree below matches;
1679        * this request is done! */
1680       dr->state = BRS_DOWNLOAD_UP;
1681       /* calculate how many bytes of payload this block
1682        * corresponds to */
1683       blen = GNUNET_FS_tree_compute_tree_size (dr->depth);
1684       /* how many of those bytes are in the requested range? */
1685       blen = GNUNET_MIN (blen, dc->length + dc->offset - dr->offset);
1686       /* signal progress */
1687       dc->completed += blen;
1688       pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
1689       pi.value.download.specifics.progress.data = NULL;
1690       pi.value.download.specifics.progress.offset = offset;
1691       pi.value.download.specifics.progress.data_len = 0;
1692       pi.value.download.specifics.progress.depth = 0;
1693       pi.value.download.specifics.progress.trust_offered = 0;
1694       GNUNET_FS_download_make_status_ (&pi, dc);
1695     }
1696     else
1697     {
1698     }
1699     break;
1700   case BRS_DOWNLOAD_DOWN:
1701     break;
1702   case BRS_DOWNLOAD_UP:
1703     break;
1704   case BRS_ERROR:
1705     break;
1706   default:
1707     GNUNET_assert (0);
1708     break;
1709   }
1710   if ((dr == dc->top_request) && (dr->state == BRS_DOWNLOAD_UP))
1711   {
1712     check_completed (dc);
1713     return;
1714   }
1715   dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1716 }
1717
1718
1719 /**
1720  * Function called by the tree encoder to obtain a block of plaintext
1721  * data (for the lowest level of the tree).
1722  *
1723  * @param cls our 'struct ReconstructContext'
1724  * @param offset identifies which block to get
1725  * @param max (maximum) number of bytes to get; returning
1726  *        fewer will also cause errors
1727  * @param buf where to copy the plaintext buffer
1728  * @param emsg location to store an error message (on error)
1729  * @return number of bytes copied to buf, 0 on error
1730  */
1731 static size_t
1732 fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg)
1733 {
1734   struct GNUNET_FS_DownloadContext *dc = cls;
1735   struct GNUNET_DISK_FileHandle *fh = dc->rfh;
1736   ssize_t ret;
1737
1738   *emsg = NULL;
1739   if (offset != GNUNET_DISK_file_seek (fh, offset, GNUNET_DISK_SEEK_SET))
1740   {
1741     *emsg = GNUNET_strdup (strerror (errno));
1742     return 0;
1743   }
1744   ret = GNUNET_DISK_file_read (fh, buf, max);
1745   if (ret < 0)
1746   {
1747     *emsg = GNUNET_strdup (strerror (errno));
1748     return 0;
1749   }
1750   return ret;
1751 }
1752
1753
1754 /**
1755  * Task that creates the initial (top-level) download
1756  * request for the file.
1757  *
1758  * @param cls the 'struct GNUNET_FS_DownloadContext'
1759  * @param tc scheduler context
1760  */
1761 void
1762 GNUNET_FS_download_start_task_ (void *cls,
1763                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1764 {
1765   struct GNUNET_FS_DownloadContext *dc = cls;
1766   struct GNUNET_FS_ProgressInfo pi;
1767   struct GNUNET_DISK_FileHandle *fh;
1768
1769 #if DEBUG_DOWNLOAD
1770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start task running...\n");
1771 #endif
1772   dc->task = GNUNET_SCHEDULER_NO_TASK;
1773   if (dc->length == 0)
1774   {
1775     /* no bytes required! */
1776     if (dc->filename != NULL)
1777     {
1778       fh = GNUNET_DISK_file_open (dc->filename,
1779                                   GNUNET_DISK_OPEN_READWRITE |
1780                                   GNUNET_DISK_OPEN_CREATE |
1781                                   ((0 ==
1782                                     GNUNET_FS_uri_chk_get_file_size (dc->uri)) ?
1783                                    GNUNET_DISK_OPEN_TRUNCATE : 0),
1784                                   GNUNET_DISK_PERM_USER_READ |
1785                                   GNUNET_DISK_PERM_USER_WRITE |
1786                                   GNUNET_DISK_PERM_GROUP_READ |
1787                                   GNUNET_DISK_PERM_OTHER_READ);
1788       GNUNET_DISK_file_close (fh);
1789     }
1790     GNUNET_FS_download_sync_ (dc);
1791     pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1792     pi.value.download.specifics.start.meta = dc->meta;
1793     GNUNET_FS_download_make_status_ (&pi, dc);
1794     check_completed (dc);
1795     return;
1796   }
1797   if (dc->emsg != NULL)
1798     return;
1799   if (dc->top_request == NULL)
1800   {
1801     dc->top_request =
1802         create_download_request (NULL, dc->treedepth - 1, 0, dc->offset,
1803                                  dc->length);
1804     dc->top_request->state = BRS_CHK_SET;
1805     dc->top_request->chk =
1806         (dc->uri->type ==
1807          chk) ? dc->uri->data.chk.chk : dc->uri->data.loc.fi.chk;
1808     /* signal start */
1809     GNUNET_FS_download_sync_ (dc);
1810     pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1811     pi.value.download.specifics.start.meta = dc->meta;
1812     GNUNET_FS_download_make_status_ (&pi, dc);
1813   }
1814   GNUNET_FS_download_start_downloading_ (dc);
1815   /* attempt reconstruction from disk */
1816   if (GNUNET_YES == GNUNET_DISK_file_test (dc->filename))
1817     dc->rfh =
1818         GNUNET_DISK_file_open (dc->filename, GNUNET_DISK_OPEN_READ,
1819                                GNUNET_DISK_PERM_NONE);
1820   if (dc->top_request->state == BRS_CHK_SET)
1821   {
1822     if (dc->rfh != NULL)
1823     {
1824       /* first, try top-down */
1825 #if DEBUG_DOWNLOAD
1826       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1827                   "Trying top-down reconstruction for `%s'\n", dc->filename);
1828 #endif
1829       try_top_down_reconstruction (dc, dc->top_request);
1830       switch (dc->top_request->state)
1831       {
1832       case BRS_CHK_SET:
1833         break;                  /* normal */
1834       case BRS_DOWNLOAD_DOWN:
1835         break;                  /* normal, some blocks already down */
1836       case BRS_DOWNLOAD_UP:
1837         /* already done entirely, party! */
1838         if (dc->rfh != NULL)
1839         {
1840           /* avoid hanging on to file handle longer than
1841            * necessary */
1842           GNUNET_DISK_file_close (dc->rfh);
1843           dc->rfh = NULL;
1844         }
1845         return;
1846       case BRS_ERROR:
1847         GNUNET_asprintf (&dc->emsg, _("Invalid URI"));
1848         GNUNET_FS_download_sync_ (dc);
1849         pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
1850         pi.value.download.specifics.error.message = dc->emsg;
1851         GNUNET_FS_download_make_status_ (&pi, dc);
1852         return;
1853       default:
1854         GNUNET_assert (0);
1855         break;
1856       }
1857     }
1858   }
1859   /* attempt reconstruction from meta data */
1860   if ((GNUNET_FS_uri_chk_get_file_size (dc->uri) <= MAX_INLINE_SIZE) &&
1861       (NULL != dc->meta))
1862   {
1863 #if DEBUG_DOWNLOAD
1864     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1865                 "Trying to find embedded meta data for download of size %llu with %u bytes MD\n",
1866                 (unsigned long long) GNUNET_FS_uri_chk_get_file_size (dc->uri),
1867                 (unsigned int)
1868                 GNUNET_CONTAINER_meta_data_get_serialized_size (dc->meta));
1869 #endif
1870     GNUNET_CONTAINER_meta_data_iterate (dc->meta, &match_full_data, dc);
1871     if (dc->top_request->state == BRS_DOWNLOAD_UP)
1872     {
1873       if (dc->rfh != NULL)
1874       {
1875         /* avoid hanging on to file handle longer than
1876          * necessary */
1877         GNUNET_DISK_file_close (dc->rfh);
1878         dc->rfh = NULL;
1879       }
1880       return;                   /* finished, status update was already done for us */
1881     }
1882   }
1883   if (dc->rfh != NULL)
1884   {
1885     /* finally, try bottom-up */
1886 #if DEBUG_DOWNLOAD
1887     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1888                 "Trying bottom-up reconstruction of file `%s'\n", dc->filename);
1889 #endif
1890     dc->te =
1891         GNUNET_FS_tree_encoder_create (dc->h, dc->old_file_size, dc, &fh_reader,
1892                                        &reconstruct_cb, NULL,
1893                                        &reconstruct_cont);
1894     dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc);
1895   }
1896   else
1897   {
1898     /* simple, top-level download */
1899     schedule_block_download (dc, dc->top_request);
1900   }
1901   if (dc->top_request->state == BRS_DOWNLOAD_UP)
1902     check_completed (dc);
1903 }
1904
1905
1906 /**
1907  * Create SUSPEND event for the given download operation
1908  * and then clean up our state (without stop signal).
1909  *
1910  * @param cls the 'struct GNUNET_FS_DownloadContext' to signal for
1911  */
1912 void
1913 GNUNET_FS_download_signal_suspend_ (void *cls)
1914 {
1915   struct GNUNET_FS_DownloadContext *dc = cls;
1916   struct GNUNET_FS_ProgressInfo pi;
1917
1918   if (dc->top != NULL)
1919     GNUNET_FS_end_top (dc->h, dc->top);
1920   while (NULL != dc->child_head)
1921     GNUNET_FS_download_signal_suspend_ (dc->child_head);
1922   if (dc->search != NULL)
1923   {
1924     dc->search->download = NULL;
1925     dc->search = NULL;
1926   }
1927   if (dc->job_queue != NULL)
1928   {
1929     GNUNET_FS_dequeue_ (dc->job_queue);
1930     dc->job_queue = NULL;
1931   }
1932   if (dc->parent != NULL)
1933     GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, dc->parent->child_tail,
1934                                  dc);
1935   if (dc->task != GNUNET_SCHEDULER_NO_TASK)
1936   {
1937     GNUNET_SCHEDULER_cancel (dc->task);
1938     dc->task = GNUNET_SCHEDULER_NO_TASK;
1939   }
1940   pi.status = GNUNET_FS_STATUS_DOWNLOAD_SUSPEND;
1941   GNUNET_FS_download_make_status_ (&pi, dc);
1942   if (dc->te != NULL)
1943   {
1944     GNUNET_FS_tree_encoder_finish (dc->te, NULL, NULL);
1945     dc->te = NULL;
1946   }
1947   if (dc->rfh != NULL)
1948   {
1949     GNUNET_DISK_file_close (dc->rfh);
1950     dc->rfh = NULL;
1951   }
1952   GNUNET_FS_free_download_request_ (dc->top_request);
1953   if (dc->active != NULL)
1954   {
1955     GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1956     dc->active = NULL;
1957   }
1958   GNUNET_free_non_null (dc->filename);
1959   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1960   GNUNET_FS_uri_destroy (dc->uri);
1961   GNUNET_free_non_null (dc->temp_filename);
1962   GNUNET_free_non_null (dc->serialization);
1963   GNUNET_free (dc);
1964 }
1965
1966
1967 /**
1968  * Download parts of a file.  Note that this will store
1969  * the blocks at the respective offset in the given file.  Also, the
1970  * download is still using the blocking of the underlying FS
1971  * encoding.  As a result, the download may *write* outside of the
1972  * given boundaries (if offset and length do not match the 32k FS
1973  * block boundaries). <p>
1974  *
1975  * This function should be used to focus a download towards a
1976  * particular portion of the file (optimization), not to strictly
1977  * limit the download to exactly those bytes.
1978  *
1979  * @param h handle to the file sharing subsystem
1980  * @param uri the URI of the file (determines what to download); CHK or LOC URI
1981  * @param meta known metadata for the file (can be NULL)
1982  * @param filename where to store the file, maybe NULL (then no file is
1983  *        created on disk and data must be grabbed from the callbacks)
1984  * @param tempname where to store temporary file data, not used if filename is non-NULL;
1985  *        can be NULL (in which case we will pick a name if needed); the temporary file
1986  *        may already exist, in which case we will try to use the data that is there and
1987  *        if it is not what is desired, will overwrite it
1988  * @param offset at what offset should we start the download (typically 0)
1989  * @param length how many bytes should be downloaded starting at offset
1990  * @param anonymity anonymity level to use for the download
1991  * @param options various options
1992  * @param cctx initial value for the client context for this download
1993  * @param parent parent download to associate this download with (use NULL
1994  *        for top-level downloads; useful for manually-triggered recursive downloads)
1995  * @return context that can be used to control this download
1996  */
1997 struct GNUNET_FS_DownloadContext *
1998 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1999                           const struct GNUNET_FS_Uri *uri,
2000                           const struct GNUNET_CONTAINER_MetaData *meta,
2001                           const char *filename, const char *tempname,
2002                           uint64_t offset, uint64_t length, uint32_t anonymity,
2003                           enum GNUNET_FS_DownloadOptions options, void *cctx,
2004                           struct GNUNET_FS_DownloadContext *parent)
2005 {
2006   struct GNUNET_FS_DownloadContext *dc;
2007
2008   GNUNET_assert (GNUNET_FS_uri_test_chk (uri) || GNUNET_FS_uri_test_loc (uri));
2009
2010   if ((offset + length < offset) ||
2011       (offset + length > GNUNET_FS_uri_chk_get_file_size (uri)))
2012   {
2013     GNUNET_break (0);
2014     return NULL;
2015   }
2016 #if DEBUG_DOWNLOAD
2017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting download `%s' of %llu bytes\n",
2018               filename, (unsigned long long) length);
2019 #endif
2020   dc = GNUNET_malloc (sizeof (struct GNUNET_FS_DownloadContext));
2021   dc->h = h;
2022   dc->parent = parent;
2023   if (parent != NULL)
2024   {
2025     GNUNET_CONTAINER_DLL_insert (parent->child_head, parent->child_tail, dc);
2026   }
2027   dc->uri = GNUNET_FS_uri_dup (uri);
2028   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
2029   dc->client_info = cctx;
2030   dc->start_time = GNUNET_TIME_absolute_get ();
2031   if (NULL != filename)
2032   {
2033     dc->filename = GNUNET_strdup (filename);
2034     if (GNUNET_YES == GNUNET_DISK_file_test (filename))
2035       GNUNET_DISK_file_size (filename, &dc->old_file_size, GNUNET_YES);
2036   }
2037   if (GNUNET_FS_uri_test_loc (dc->uri))
2038     GNUNET_assert (GNUNET_OK ==
2039                    GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target));
2040   dc->offset = offset;
2041   dc->length = length;
2042   dc->anonymity = anonymity;
2043   dc->options = options;
2044   dc->active =
2045       GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
2046   dc->treedepth =
2047       GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri));
2048   if ((filename == NULL) && (is_recursive_download (dc)))
2049   {
2050     if (tempname != NULL)
2051       dc->temp_filename = GNUNET_strdup (tempname);
2052     else
2053       dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2054   }
2055
2056 #if DEBUG_DOWNLOAD
2057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download tree has depth %u\n",
2058               dc->treedepth);
2059 #endif
2060   if (parent == NULL)
2061   {
2062     dc->top =
2063         GNUNET_FS_make_top (dc->h, &GNUNET_FS_download_signal_suspend_, dc);
2064   }
2065   dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2066   return dc;
2067 }
2068
2069
2070 /**
2071  * Download parts of a file based on a search result.  The download
2072  * will be associated with the search result (and the association
2073  * will be preserved when serializing/deserializing the state).
2074  * If the search is stopped, the download will not be aborted but
2075  * be 'promoted' to a stand-alone download.
2076  *
2077  * As with the other download function, this will store
2078  * the blocks at the respective offset in the given file.  Also, the
2079  * download is still using the blocking of the underlying FS
2080  * encoding.  As a result, the download may *write* outside of the
2081  * given boundaries (if offset and length do not match the 32k FS
2082  * block boundaries). <p>
2083  *
2084  * The given range can be used to focus a download towards a
2085  * particular portion of the file (optimization), not to strictly
2086  * limit the download to exactly those bytes.
2087  *
2088  * @param h handle to the file sharing subsystem
2089  * @param sr the search result to use for the download (determines uri and
2090  *        meta data and associations)
2091  * @param filename where to store the file, maybe NULL (then no file is
2092  *        created on disk and data must be grabbed from the callbacks)
2093  * @param tempname where to store temporary file data, not used if filename is non-NULL;
2094  *        can be NULL (in which case we will pick a name if needed); the temporary file
2095  *        may already exist, in which case we will try to use the data that is there and
2096  *        if it is not what is desired, will overwrite it
2097  * @param offset at what offset should we start the download (typically 0)
2098  * @param length how many bytes should be downloaded starting at offset
2099  * @param anonymity anonymity level to use for the download
2100  * @param options various download options
2101  * @param cctx initial value for the client context for this download
2102  * @return context that can be used to control this download
2103  */
2104 struct GNUNET_FS_DownloadContext *
2105 GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h,
2106                                       struct GNUNET_FS_SearchResult *sr,
2107                                       const char *filename,
2108                                       const char *tempname, uint64_t offset,
2109                                       uint64_t length, uint32_t anonymity,
2110                                       enum GNUNET_FS_DownloadOptions options,
2111                                       void *cctx)
2112 {
2113   struct GNUNET_FS_DownloadContext *dc;
2114
2115   if ((sr == NULL) || (sr->download != NULL))
2116   {
2117     GNUNET_break (0);
2118     return NULL;
2119   }
2120   GNUNET_assert (GNUNET_FS_uri_test_chk (sr->uri) ||
2121                  GNUNET_FS_uri_test_loc (sr->uri));
2122   if ((offset + length < offset) ||
2123       (offset + length > sr->uri->data.chk.file_length))
2124   {
2125     GNUNET_break (0);
2126     return NULL;
2127   }
2128 #if DEBUG_DOWNLOAD
2129   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting download `%s' of %llu bytes\n",
2130               filename, (unsigned long long) length);
2131 #endif
2132   dc = GNUNET_malloc (sizeof (struct GNUNET_FS_DownloadContext));
2133   dc->h = h;
2134   dc->search = sr;
2135   sr->download = dc;
2136   if (sr->probe_ctx != NULL)
2137   {
2138     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
2139     sr->probe_ctx = NULL;
2140   }
2141   dc->uri = GNUNET_FS_uri_dup (sr->uri);
2142   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (sr->meta);
2143   dc->client_info = cctx;
2144   dc->start_time = GNUNET_TIME_absolute_get ();
2145   if (NULL != filename)
2146   {
2147     dc->filename = GNUNET_strdup (filename);
2148     if (GNUNET_YES == GNUNET_DISK_file_test (filename))
2149       GNUNET_DISK_file_size (filename, &dc->old_file_size, GNUNET_YES);
2150   }
2151   if (GNUNET_FS_uri_test_loc (dc->uri))
2152     GNUNET_assert (GNUNET_OK ==
2153                    GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target));
2154   dc->offset = offset;
2155   dc->length = length;
2156   dc->anonymity = anonymity;
2157   dc->options = options;
2158   dc->active =
2159       GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
2160   dc->treedepth =
2161       GNUNET_FS_compute_depth (GNUNET_ntohll (dc->uri->data.chk.file_length));
2162   if ((filename == NULL) && (is_recursive_download (dc)))
2163   {
2164     if (tempname != NULL)
2165       dc->temp_filename = GNUNET_strdup (tempname);
2166     else
2167       dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
2168   }
2169
2170 #if DEBUG_DOWNLOAD
2171   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download tree has depth %u\n",
2172               dc->treedepth);
2173 #endif
2174   dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc);
2175   return dc;
2176 }
2177
2178
2179 /**
2180  * Start the downloading process (by entering the queue).
2181  *
2182  * @param dc our download context
2183  */
2184 void
2185 GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc)
2186 {
2187   if (dc->completed == dc->length)
2188     return;
2189   GNUNET_assert (dc->job_queue == NULL);
2190   dc->job_queue =
2191       GNUNET_FS_queue_ (dc->h, &activate_fs_download, &deactivate_fs_download,
2192                         dc, (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE);
2193 }
2194
2195
2196 /**
2197  * Stop a download (aborts if download is incomplete).
2198  *
2199  * @param dc handle for the download
2200  * @param do_delete delete files of incomplete downloads
2201  */
2202 void
2203 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete)
2204 {
2205   struct GNUNET_FS_ProgressInfo pi;
2206   int have_children;
2207
2208   if (dc->top != NULL)
2209     GNUNET_FS_end_top (dc->h, dc->top);
2210
2211
2212   if (dc->task != GNUNET_SCHEDULER_NO_TASK)
2213   {
2214     GNUNET_SCHEDULER_cancel (dc->task);
2215     dc->task = GNUNET_SCHEDULER_NO_TASK;
2216   }
2217   if (dc->search != NULL)
2218   {
2219     dc->search->download = NULL;
2220     dc->search = NULL;
2221   }
2222   if (dc->job_queue != NULL)
2223   {
2224     GNUNET_FS_dequeue_ (dc->job_queue);
2225     dc->job_queue = NULL;
2226   }
2227   if (dc->te != NULL)
2228   {
2229     GNUNET_FS_tree_encoder_finish (dc->te, NULL, NULL);
2230     dc->te = NULL;
2231   }
2232   have_children = (NULL != dc->child_head) ? GNUNET_YES : GNUNET_NO;
2233   while (NULL != dc->child_head)
2234     GNUNET_FS_download_stop (dc->child_head, do_delete);
2235   if (dc->parent != NULL)
2236     GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, dc->parent->child_tail,
2237                                  dc);
2238   if (dc->serialization != NULL)
2239     GNUNET_FS_remove_sync_file_ (dc->h,
2240                                  ((dc->parent != NULL) ||
2241                                   (dc->search !=
2242                                    NULL)) ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD :
2243                                  GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2244                                  dc->serialization);
2245   if ((GNUNET_YES == have_children) && (dc->parent == NULL))
2246     GNUNET_FS_remove_sync_dir_ (dc->h,
2247                                 (dc->search !=
2248                                  NULL) ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD :
2249                                 GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD,
2250                                 dc->serialization);
2251   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
2252   GNUNET_FS_download_make_status_ (&pi, dc);
2253   GNUNET_FS_free_download_request_ (dc->top_request);
2254   dc->top_request = NULL;
2255   if (dc->active != NULL)
2256   {
2257     GNUNET_CONTAINER_multihashmap_destroy (dc->active);
2258     dc->active = NULL;
2259   }
2260   if (dc->filename != NULL)
2261   {
2262     if ((dc->completed != dc->length) && (GNUNET_YES == do_delete))
2263     {
2264       if (0 != UNLINK (dc->filename))
2265         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
2266                                   dc->filename);
2267     }
2268     GNUNET_free (dc->filename);
2269   }
2270   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
2271   GNUNET_FS_uri_destroy (dc->uri);
2272   if (NULL != dc->temp_filename)
2273   {
2274     if (0 != UNLINK (dc->temp_filename))
2275       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "unlink",
2276                                 dc->temp_filename);
2277     GNUNET_free (dc->temp_filename);
2278   }
2279   GNUNET_free_non_null (dc->serialization);
2280   GNUNET_free (dc);
2281 }
2282
2283 /* end of fs_download.c */