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