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