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