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