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