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