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