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