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