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