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