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