towards job queuing
[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 2, 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  * - handle recursive downloads (need directory & 
27  *   fs-level download-parallelism management)
28  * - location URI suppport (can wait, easy)
29  * - check if blocks exist already (can wait, easy)
30  * - check if iblocks can be computed from existing blocks (can wait, hard)
31  * - persistence (can wait)
32  */
33 #include "platform.h"
34 #include "gnunet_constants.h"
35 #include "gnunet_fs_service.h"
36 #include "fs.h"
37 #include "fs_tree.h"
38
39 #define DEBUG_DOWNLOAD GNUNET_NO
40
41 /**
42  * Determine if the given download (options and meta data) should cause
43  * use to try to do a recursive download.
44  */
45 static int
46 is_recursive_download (struct GNUNET_FS_DownloadContext *dc)
47 {
48   return  (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
49     ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
50       ( (dc->meta == NULL) &&
51         ( (NULL == dc->filename) ||            
52           ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
53             (NULL !=
54              strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
55                      GNUNET_FS_DIRECTORY_EXT)) ) ) ) );              
56 }
57
58
59 /**
60  * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
61  * only have to truncate the file once we're done).
62  *
63  * Given the offset of a block (with respect to the DBLOCKS) and its
64  * depth, return the offset where we would store this block in the
65  * file.
66  * 
67  * @param fsize overall file size
68  * @param off offset of the block in the file
69  * @param depth depth of the block in the tree
70  * @param treedepth maximum depth of the tree
71  * @return off for DBLOCKS (depth == treedepth),
72  *         otherwise an offset past the end
73  *         of the file that does not overlap
74  *         with the range for any other block
75  */
76 static uint64_t
77 compute_disk_offset (uint64_t fsize,
78                      uint64_t off,
79                      unsigned int depth,
80                      unsigned int treedepth)
81 {
82   unsigned int i;
83   uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
84   uint64_t loff; /* where do IBlocks for depth "i" start? */
85   unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
86   
87   if (depth == treedepth)
88     return off;
89   /* first IBlocks start at the end of file, rounded up
90      to full DBLOCK_SIZE */
91   loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
92   lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
93   GNUNET_assert (0 == (off % DBLOCK_SIZE));
94   ioff = (off / DBLOCK_SIZE);
95   for (i=treedepth-1;i>depth;i--)
96     {
97       loff += lsize;
98       lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
99       GNUNET_assert (lsize > 0);
100       GNUNET_assert (0 == (ioff % CHK_PER_INODE));
101       ioff /= CHK_PER_INODE;
102     }
103   return loff + ioff * sizeof (struct ContentHashKey);
104 }
105
106
107 /**
108  * Given a file of the specified treedepth and a block at the given
109  * offset and depth, calculate the offset for the CHK at the given
110  * index.
111  *
112  * @param offset the offset of the first
113  *        DBLOCK in the subtree of the 
114  *        identified IBLOCK
115  * @param depth the depth of the IBLOCK in the tree
116  * @param treedepth overall depth of the tree
117  * @param k which CHK in the IBLOCK are we 
118  *        talking about
119  * @return offset if k=0, otherwise an appropriately
120  *         larger value (i.e., if depth = treedepth-1,
121  *         the returned value should be offset+DBLOCK_SIZE)
122  */
123 static uint64_t
124 compute_dblock_offset (uint64_t offset,
125                        unsigned int depth,
126                        unsigned int treedepth,
127                        unsigned int k)
128 {
129   unsigned int i;
130   uint64_t lsize; /* what is the size of the sum of all DBlocks 
131                      that a CHK at depth i corresponds to? */
132
133   if (depth == treedepth)
134     return offset;
135   lsize = DBLOCK_SIZE;
136   for (i=treedepth-1;i>depth;i--)
137     lsize *= CHK_PER_INODE;
138   return offset + k * lsize;
139 }
140
141
142 /**
143  * Fill in all of the generic fields for 
144  * a download event.
145  *
146  * @param pi structure to fill in
147  * @param dc overall download context
148  */
149 static void
150 make_download_status (struct GNUNET_FS_ProgressInfo *pi,
151                       struct GNUNET_FS_DownloadContext *dc)
152 {
153   pi->value.download.dc = dc;
154   pi->value.download.cctx
155     = dc->client_info;
156   pi->value.download.pctx
157     = (dc->parent == NULL) ? NULL : dc->parent->client_info;
158   pi->value.download.uri 
159     = dc->uri;
160   pi->value.download.filename
161     = dc->filename;
162   pi->value.download.size
163     = dc->length;
164   pi->value.download.duration
165     = GNUNET_TIME_absolute_get_duration (dc->start_time);
166   pi->value.download.completed
167     = dc->completed;
168   pi->value.download.anonymity
169     = dc->anonymity;
170   pi->value.download.eta
171     = GNUNET_TIME_calculate_eta (dc->start_time,
172                                  dc->completed,
173                                  dc->length);
174 }
175
176 /**
177  * We're ready to transmit a search request to the
178  * file-sharing service.  Do it.  If there is 
179  * more than one request pending, try to send 
180  * multiple or request another transmission.
181  *
182  * @param cls closure
183  * @param size number of bytes available in buf
184  * @param buf where the callee should write the message
185  * @return number of bytes written to buf
186  */
187 static size_t
188 transmit_download_request (void *cls,
189                            size_t size, 
190                            void *buf);
191
192
193 /**
194  * Closure for iterator processing results.
195  */
196 struct ProcessResultClosure
197 {
198   
199   /**
200    * Hash of data.
201    */
202   GNUNET_HashCode query;
203
204   /**
205    * Data found in P2P network.
206    */ 
207   const void *data;
208
209   /**
210    * Our download context.
211    */
212   struct GNUNET_FS_DownloadContext *dc;
213                 
214   /**
215    * Number of bytes in data.
216    */
217   size_t size;
218
219   /**
220    * Type of data.
221    */
222   enum GNUNET_BLOCK_Type type;
223
224   /**
225    * Flag to indicate if this block should be stored on disk.
226    */
227   int do_store;
228   
229 };
230
231
232 /**
233  * Iterator over entries in the pending requests in the 'active' map for the
234  * reply that we just got.
235  *
236  * @param cls closure (our 'struct ProcessResultClosure')
237  * @param key query for the given value / request
238  * @param value value in the hash map (a 'struct DownloadRequest')
239  * @return GNUNET_YES (we should continue to iterate); unless serious error
240  */
241 static int
242 process_result_with_request (void *cls,
243                              const GNUNET_HashCode * key,
244                              void *value);
245
246
247
248 /**
249  * Schedule the download of the specified block in the tree.
250  *
251  * @param dc overall download this block belongs to
252  * @param chk content-hash-key of the block
253  * @param offset offset of the block in the file
254  *         (for IBlocks, the offset is the lowest
255  *          offset of any DBlock in the subtree under
256  *          the IBlock)
257  * @param depth depth of the block, 0 is the root of the tree
258  */
259 static void
260 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
261                          const struct ContentHashKey *chk,
262                          uint64_t offset,
263                          unsigned int depth)
264 {
265   struct DownloadRequest *sm;
266   uint64_t total;
267   uint64_t off;
268   size_t len;
269   char block[DBLOCK_SIZE];
270   GNUNET_HashCode key;
271   struct ProcessResultClosure prc;
272
273 #if DEBUG_DOWNLOAD
274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
275               "Scheduling download at offset %llu and depth %u for `%s'\n",
276               (unsigned long long) offset,
277               depth,
278               GNUNET_h2s (&chk->query));
279 #endif
280   total = GNUNET_ntohll (dc->uri->data.chk.file_length);
281   off = compute_disk_offset (total,
282                              offset,
283                              depth,
284                              dc->treedepth);
285   len = GNUNET_FS_tree_calculate_block_size (total,
286                                              dc->treedepth,
287                                              offset,
288                                              depth);
289   sm = GNUNET_malloc (sizeof (struct DownloadRequest));
290   sm->chk = *chk;
291   sm->offset = offset;
292   sm->depth = depth;
293   sm->is_pending = GNUNET_YES;
294   sm->next = dc->pending;
295   dc->pending = sm;
296   GNUNET_CONTAINER_multihashmap_put (dc->active,
297                                      &chk->query,
298                                      sm,
299                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
300
301   if ( (dc->old_file_size > off) &&
302        (dc->handle != NULL) &&
303        (off  == 
304         GNUNET_DISK_file_seek (dc->handle,
305                                off,
306                                GNUNET_DISK_SEEK_SET) ) &&
307        (len == 
308         GNUNET_DISK_file_read (dc->handle,
309                                block,
310                                len)) )
311     {
312       if (0 == memcmp (&key,
313                        &chk->key,
314                        sizeof (GNUNET_HashCode)))
315         {
316           char enc[len];
317           struct GNUNET_CRYPTO_AesSessionKey sk;
318           struct GNUNET_CRYPTO_AesInitializationVector iv;
319           GNUNET_HashCode query;
320
321           GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
322           GNUNET_CRYPTO_aes_encrypt (block, len,
323                                      &sk,
324                                      &iv,
325                                      enc);
326           GNUNET_CRYPTO_hash (enc, len, &query);
327           if (0 == memcmp (&query,
328                            &chk->query,
329                            sizeof (GNUNET_HashCode)))
330             {
331               /* already got it! */
332               prc.dc = dc;
333               prc.data = enc;
334               prc.size = len;
335               prc.type = (dc->treedepth == depth) 
336                 ? GNUNET_BLOCK_TYPE_DBLOCK 
337                 : GNUNET_BLOCK_TYPE_IBLOCK;
338               prc.query = chk->query;
339               prc.do_store = GNUNET_NO; /* useless */
340               process_result_with_request (&prc,
341                                            &key,
342                                            sm);
343             }
344           else
345             {
346               GNUNET_break_op (0);
347             }
348           return;
349         }
350     }
351   if (depth < dc->treedepth)
352     {
353       // FIXME: try if we could
354       // reconstitute this IBLOCK
355       // from the existing blocks on disk (can wait)
356       // (read block(s), encode, compare with
357       // query; if matches, simply return)
358     }
359
360   if ( (dc->th == NULL) &&
361        (dc->client != NULL) )
362     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
363                                                   sizeof (struct SearchMessage),
364                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
365                                                   GNUNET_NO,
366                                                   &transmit_download_request,
367                                                   dc);
368 }
369
370
371
372 /**
373  * Suggest a filename based on given metadata.
374  * 
375  * @param md given meta data
376  * @return NULL if meta data is useless for suggesting a filename
377  */
378 char *
379 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
380 {
381   static const char *mimeMap[][2] = {
382     {"application/bz2", ".bz2"},
383     {"application/gnunet-directory", ".gnd"},
384     {"application/java", ".class"},
385     {"application/msword", ".doc"},
386     {"application/ogg", ".ogg"},
387     {"application/pdf", ".pdf"},
388     {"application/pgp-keys", ".key"},
389     {"application/pgp-signature", ".pgp"},
390     {"application/postscript", ".ps"},
391     {"application/rar", ".rar"},
392     {"application/rtf", ".rtf"},
393     {"application/xml", ".xml"},
394     {"application/x-debian-package", ".deb"},
395     {"application/x-dvi", ".dvi"},
396     {"applixation/x-flac", ".flac"},
397     {"applixation/x-gzip", ".gz"},
398     {"application/x-java-archive", ".jar"},
399     {"application/x-java-vm", ".class"},
400     {"application/x-python-code", ".pyc"},
401     {"application/x-redhat-package-manager", ".rpm"},
402     {"application/x-rpm", ".rpm"},
403     {"application/x-tar", ".tar"},
404     {"application/x-tex-pk", ".pk"},
405     {"application/x-texinfo", ".texinfo"},
406     {"application/x-xcf", ".xcf"},
407     {"application/x-xfig", ".xfig"},
408     {"application/zip", ".zip"},
409     
410     {"audio/midi", ".midi"},
411     {"audio/mpeg", ".mp3"},
412     {"audio/real", ".rm"},
413     {"audio/x-wav", ".wav"},
414     
415     {"image/gif", ".gif"},
416     {"image/jpeg", ".jpg"},
417     {"image/pcx", ".pcx"},
418     {"image/png", ".png"},
419     {"image/tiff", ".tiff"},
420     {"image/x-ms-bmp", ".bmp"},
421     {"image/x-xpixmap", ".xpm"},
422     
423     {"text/css", ".css"},
424     {"text/html", ".html"},
425     {"text/plain", ".txt"},
426     {"text/rtf", ".rtf"},
427     {"text/x-c++hdr", ".h++"},
428     {"text/x-c++src", ".c++"},
429     {"text/x-chdr", ".h"},
430     {"text/x-csrc", ".c"},
431     {"text/x-java", ".java"},
432     {"text/x-moc", ".moc"},
433     {"text/x-pascal", ".pas"},
434     {"text/x-perl", ".pl"},
435     {"text/x-python", ".py"},
436     {"text/x-tex", ".tex"},
437     
438     {"video/avi", ".avi"},
439     {"video/mpeg", ".mpeg"},
440     {"video/quicktime", ".qt"},
441     {"video/real", ".rm"},
442     {"video/x-msvideo", ".avi"},
443     {NULL, NULL},
444   };
445   char *ret;
446   unsigned int i;
447   char *mime;
448   char *base;
449   const char *ext;
450
451   ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
452                                                 EXTRACTOR_METATYPE_FILENAME);
453   if (ret != NULL)
454     return ret;  
455   ext = NULL;
456   mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
457                                                  EXTRACTOR_METATYPE_MIMETYPE);
458   if (mime != NULL)
459     {
460       i = 0;
461       while ( (mimeMap[i][0] != NULL) && 
462               (0 != strcmp (mime, mimeMap[i][0])))
463         i++;
464       if (mimeMap[i][1] == NULL)
465         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | 
466                     GNUNET_ERROR_TYPE_BULK,
467                     _("Did not find mime type `%s' in extension list.\n"),
468                     mime);
469       else
470         ext = mimeMap[i][1];
471       GNUNET_free (mime);
472     }
473   base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
474                                                         EXTRACTOR_METATYPE_TITLE,
475                                                         EXTRACTOR_METATYPE_BOOK_TITLE,
476                                                         EXTRACTOR_METATYPE_ORIGINAL_TITLE,
477                                                         EXTRACTOR_METATYPE_PACKAGE_NAME,
478                                                         EXTRACTOR_METATYPE_URL,
479                                                         EXTRACTOR_METATYPE_URI, 
480                                                         EXTRACTOR_METATYPE_DESCRIPTION,
481                                                         EXTRACTOR_METATYPE_ISRC,
482                                                         EXTRACTOR_METATYPE_JOURNAL_NAME,
483                                                         EXTRACTOR_METATYPE_AUTHOR_NAME,
484                                                         EXTRACTOR_METATYPE_SUBJECT,
485                                                         EXTRACTOR_METATYPE_ALBUM,
486                                                         EXTRACTOR_METATYPE_ARTIST,
487                                                         EXTRACTOR_METATYPE_KEYWORDS,
488                                                         EXTRACTOR_METATYPE_COMMENT,
489                                                         EXTRACTOR_METATYPE_UNKNOWN,
490                                                         -1);
491   if ( (base == NULL) &&
492        (ext == NULL) )
493     return NULL;
494   if (base == NULL)
495     return GNUNET_strdup (ext);
496   if (ext == NULL)
497     return base;
498   GNUNET_asprintf (&ret,
499                    "%s%s",
500                    base,
501                    ext);
502   GNUNET_free (base);
503   return ret;
504 }
505
506
507 /**
508  * We've lost our connection with the FS service.
509  * Re-establish it and re-transmit all of our
510  * pending requests.
511  *
512  * @param dc download context that is having trouble
513  */
514 static void
515 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
516
517
518 /**
519  * We found an entry in a directory.  Check if the respective child
520  * already exists and if not create the respective child download.
521  *
522  * @param cls the parent download
523  * @param filename name of the file in the directory
524  * @param uri URI of the file (CHK or LOC)
525  * @param meta meta data of the file
526  * @param length number of bytes in data
527  * @param data contents of the file (or NULL if they were not inlined)
528  */
529 static void 
530 trigger_recursive_download (void *cls,
531                             const char *filename,
532                             const struct GNUNET_FS_Uri *uri,
533                             const struct GNUNET_CONTAINER_MetaData *meta,
534                             size_t length,
535                             const void *data);
536
537
538 /**
539  * We're done downloading a directory.  Open the file and
540  * trigger all of the (remaining) child downloads.
541  *
542  * @param dc context of download that just completed
543  */
544 static void
545 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
546 {
547   size_t size;
548   uint64_t size64;
549   void *data;
550   struct GNUNET_DISK_FileHandle *h;
551   struct GNUNET_DISK_MapHandle *m;
552   
553   size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
554   size = (size_t) size64;
555   if (size64 != (uint64_t) size)
556     {
557       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
558                   _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
559       return;
560     }
561   if (dc->filename != NULL)
562     {
563       h = GNUNET_DISK_file_open (dc->filename,
564                                  GNUNET_DISK_OPEN_READ,
565                                  GNUNET_DISK_PERM_NONE);
566     }
567   else
568     {
569       GNUNET_assert (dc->temp_filename != NULL);
570       h = GNUNET_DISK_file_open (dc->temp_filename,
571                                  GNUNET_DISK_OPEN_READ,
572                                  GNUNET_DISK_PERM_NONE);
573     }
574   if (h == NULL)
575     return; /* oops */
576   data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
577   if (data == NULL)
578     {
579       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
580                   _("Directory too large for system address space\n"));
581     }
582   else
583     {
584       GNUNET_FS_directory_list_contents (size,
585                                          data,
586                                          0,
587                                          &trigger_recursive_download,
588                                          dc);         
589       GNUNET_DISK_file_unmap (m);
590     }
591   GNUNET_DISK_file_close (h);
592   if (dc->filename == NULL)
593     {
594       if (0 != UNLINK (dc->temp_filename))
595         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
596                                   "unlink",
597                                   dc->temp_filename);
598       GNUNET_free (dc->temp_filename);
599       dc->temp_filename = NULL;
600     }
601 }
602
603
604 /**
605  * Check if all child-downloads have completed and
606  * if so, signal completion (and possibly recurse to
607  * parent).
608  */
609 static void
610 check_completed (struct GNUNET_FS_DownloadContext *dc)
611 {
612   struct GNUNET_FS_ProgressInfo pi;
613   struct GNUNET_FS_DownloadContext *pos;
614
615   pos = dc->child_head;
616   while (pos != NULL)
617     {
618       if ( (pos->emsg == NULL) &&
619            (pos->completed < pos->length) )
620         return; /* not done yet */
621       if ( (pos->child_head != NULL) &&
622            (pos->has_finished != GNUNET_YES) )
623         return; /* not transitively done yet */
624       pos = pos->next;
625     }
626   dc->has_finished = GNUNET_YES;
627   /* signal completion */
628   pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
629   make_download_status (&pi, dc);
630   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
631                                  &pi);
632   if (dc->parent != NULL)
633     check_completed (dc->parent);  
634 }
635
636
637 /**
638  * We found an entry in a directory.  Check if the respective child
639  * already exists and if not create the respective child download.
640  *
641  * @param cls the parent download
642  * @param filename name of the file in the directory
643  * @param uri URI of the file (CHK or LOC)
644  * @param meta meta data of the file
645  * @param length number of bytes in data
646  * @param data contents of the file (or NULL if they were not inlined)
647  */
648 static void 
649 trigger_recursive_download (void *cls,
650                             const char *filename,
651                             const struct GNUNET_FS_Uri *uri,
652                             const struct GNUNET_CONTAINER_MetaData *meta,
653                             size_t length,
654                             const void *data)
655 {
656   struct GNUNET_FS_DownloadContext *dc = cls;  
657   struct GNUNET_FS_DownloadContext *cpos;
658   struct GNUNET_DISK_FileHandle *fh;
659   char *temp_name;
660   const char *real_name;
661   char *fn;
662   char *us;
663   char *ext;
664   char *dn;
665   char *full_name;
666
667   if (NULL == uri)
668     return; /* entry for the directory itself */
669   cpos = dc->child_head;
670   while (cpos != NULL)
671     {
672       if ( (GNUNET_FS_uri_test_equal (uri,
673                                       cpos->uri)) ||
674            ( (filename != NULL) &&
675              (0 == strcmp (cpos->filename,
676                            filename)) ) )
677         break;  
678       cpos = cpos->next;
679     }
680   if (cpos != NULL)
681     return; /* already exists */
682   fn = NULL;
683   if (NULL == filename)
684     {
685       fn = GNUNET_FS_meta_data_suggest_filename (meta);      
686       if (fn == NULL)
687         {
688           us = GNUNET_FS_uri_to_string (uri);
689           fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX 
690                                            GNUNET_FS_URI_CHK_INFIX)]);
691           GNUNET_free (us);
692         }
693       else if (fn[0] == '.')
694         {
695           ext = fn;
696           us = GNUNET_FS_uri_to_string (uri);
697           GNUNET_asprintf (&fn,
698                            "%s%s",
699                            &us[strlen (GNUNET_FS_URI_PREFIX 
700                                        GNUNET_FS_URI_CHK_INFIX)], ext);
701           GNUNET_free (ext);
702           GNUNET_free (us);
703         }
704       filename = fn;
705     }
706   if (dc->filename == NULL)
707     {
708       full_name = NULL;
709     }
710   else
711     {
712       dn = GNUNET_strdup (dc->filename);
713       GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
714                      (NULL !=
715                       strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
716                               GNUNET_FS_DIRECTORY_EXT)) );
717       if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
718            (NULL !=
719             strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
720                     GNUNET_FS_DIRECTORY_EXT)) )      
721         dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';      
722       if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
723            ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
724              (NULL ==
725               strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
726                       GNUNET_FS_DIRECTORY_EXT)) ) )
727         {
728           GNUNET_asprintf (&full_name,
729                            "%s%s%s%s",
730                            dn,
731                            DIR_SEPARATOR_STR,
732                            filename,
733                            GNUNET_FS_DIRECTORY_EXT);
734         }
735       else
736         {
737           GNUNET_asprintf (&full_name,
738                            "%s%s%s",
739                            dn,
740                            DIR_SEPARATOR_STR,
741                            filename);
742         }
743       GNUNET_free (dn);
744     }
745   if ( (full_name != NULL) &&
746        (GNUNET_OK !=
747         GNUNET_DISK_directory_create_for_file (full_name)) )
748     {
749       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
750                   _("Failed to create directory for recursive download of `%s'\n"),
751                   full_name);
752       GNUNET_free (full_name);
753       GNUNET_free_non_null (fn);
754       return;
755     }
756
757   temp_name = NULL;
758   if ( (data != NULL) &&
759        (GNUNET_FS_uri_chk_get_file_size (uri) == length) )
760     {
761       if (full_name == NULL)
762         {
763           temp_name = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
764           real_name = temp_name;
765         }
766       else
767         {
768           real_name = full_name;
769         }
770       /* write to disk, then trigger normal download which will instantly progress to completion */
771       fh = GNUNET_DISK_file_open (real_name,
772                                   GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
773                                   GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
774       if (fh == NULL)
775         {
776           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
777                                     "open",
778                                     real_name);       
779           GNUNET_free (full_name);
780           GNUNET_free_non_null (fn);
781           return;
782         }
783       if (length != 
784           GNUNET_DISK_file_write (fh,
785                                   data,
786                                   length))
787         {
788           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
789                                     "write",
790                                     full_name);       
791         }
792       GNUNET_DISK_file_close (fh);
793     }
794   GNUNET_FS_download_start (dc->h,
795                             uri,
796                             meta,
797                             full_name, temp_name,
798                             0,
799                             GNUNET_FS_uri_chk_get_file_size (uri),
800                             dc->anonymity,
801                             dc->options,
802                             NULL,
803                             dc);
804   GNUNET_free_non_null (full_name);
805   GNUNET_free_non_null (temp_name);
806   GNUNET_free_non_null (fn);
807 }
808
809
810 /**
811  * Iterator over entries in the pending requests in the 'active' map for the
812  * reply that we just got.
813  *
814  * @param cls closure (our 'struct ProcessResultClosure')
815  * @param key query for the given value / request
816  * @param value value in the hash map (a 'struct DownloadRequest')
817  * @return GNUNET_YES (we should continue to iterate); unless serious error
818  */
819 static int
820 process_result_with_request (void *cls,
821                              const GNUNET_HashCode * key,
822                              void *value)
823 {
824   struct ProcessResultClosure *prc = cls;
825   struct DownloadRequest *sm = value;
826   struct GNUNET_FS_DownloadContext *dc = prc->dc;
827   struct GNUNET_CRYPTO_AesSessionKey skey;
828   struct GNUNET_CRYPTO_AesInitializationVector iv;
829   char pt[prc->size];
830   struct GNUNET_FS_ProgressInfo pi;
831   uint64_t off;
832   size_t bs;
833   size_t app;
834   int i;
835   struct ContentHashKey *chk;
836   char *emsg;
837
838   bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
839                                             dc->treedepth,
840                                             sm->offset,
841                                             sm->depth);
842     if (prc->size != bs)
843     {
844 #if DEBUG_DOWNLOAD
845       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
847                   bs,
848                   prc->size);
849 #endif
850       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
851       /* signal error */
852       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
853       make_download_status (&pi, dc);
854       pi.value.download.specifics.error.message = dc->emsg;
855       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
856                                      &pi);
857       /* abort all pending requests */
858       if (NULL != dc->th)
859         {
860           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
861           dc->th = NULL;
862         }
863       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
864       dc->client = NULL;
865       return GNUNET_NO;
866     }
867   GNUNET_assert (GNUNET_YES ==
868                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
869                                                        &prc->query,
870                                                        sm));
871   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
872   GNUNET_CRYPTO_aes_decrypt (prc->data,
873                              prc->size,
874                              &skey,
875                              &iv,
876                              pt);
877   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
878                              sm->offset,
879                              sm->depth,
880                              dc->treedepth);
881   /* save to disk */
882   if ( ( GNUNET_YES == prc->do_store) &&
883        (NULL != dc->handle) &&
884        ( (sm->depth == dc->treedepth) ||
885          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
886     {
887       emsg = NULL;
888 #if DEBUG_DOWNLOAD
889       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890                   "Saving decrypted block to disk at offset %llu\n",
891                   (unsigned long long) off);
892 #endif
893       if ( (off  != 
894             GNUNET_DISK_file_seek (dc->handle,
895                                    off,
896                                    GNUNET_DISK_SEEK_SET) ) )
897         GNUNET_asprintf (&emsg,
898                          _("Failed to seek to offset %llu in file `%s': %s\n"),
899                          (unsigned long long) off,
900                          dc->filename,
901                          STRERROR (errno));
902       else if (prc->size !=
903                GNUNET_DISK_file_write (dc->handle,
904                                        pt,
905                                        prc->size))
906         GNUNET_asprintf (&emsg,
907                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
908                          (unsigned int) prc->size,
909                          (unsigned long long) off,
910                          dc->filename,
911                          STRERROR (errno));
912       if (NULL != emsg)
913         {
914           dc->emsg = emsg;
915           // FIXME: make persistent
916
917           /* signal error */
918           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
919           make_download_status (&pi, dc);
920           pi.value.download.specifics.error.message = emsg;
921           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
922                                          &pi);
923
924           /* abort all pending requests */
925           if (NULL != dc->th)
926             {
927               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
928               dc->th = NULL;
929             }
930           GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
931           dc->client = NULL;
932           GNUNET_free (sm);
933           return GNUNET_NO;
934         }
935     }
936   if (sm->depth == dc->treedepth) 
937     {
938       app = prc->size;
939       if (sm->offset < dc->offset)
940         {
941           /* starting offset begins in the middle of pt,
942              do not count first bytes as progress */
943           GNUNET_assert (app > (dc->offset - sm->offset));
944           app -= (dc->offset - sm->offset);       
945         }
946       if (sm->offset + prc->size > dc->offset + dc->length)
947         {
948           /* end of block is after relevant range,
949              do not count last bytes as progress */
950           GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
951           app -= (sm->offset + prc->size) - (dc->offset + dc->length);
952         }
953       dc->completed += app;
954
955       /* do recursive download if option is set and either meta data
956          says it is a directory or if no meta data is given AND filename 
957          ends in '.gnd' (top-level case) */
958       if (is_recursive_download (dc))
959         GNUNET_FS_directory_list_contents (prc->size,
960                                            pt,
961                                            off,
962                                            &trigger_recursive_download,
963                                            dc);         
964             
965     }
966   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
967   make_download_status (&pi, dc);
968   pi.value.download.specifics.progress.data = pt;
969   pi.value.download.specifics.progress.offset = sm->offset;
970   pi.value.download.specifics.progress.data_len = prc->size;
971   pi.value.download.specifics.progress.depth = sm->depth;
972   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
973                                  &pi);
974   GNUNET_assert (dc->completed <= dc->length);
975   if (dc->completed == dc->length)
976     {
977 #if DEBUG_DOWNLOAD
978       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979                   "Download completed, truncating file to desired length %llu\n",
980                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
981 #endif
982       /* truncate file to size (since we store IBlocks at the end) */
983       if (dc->handle != NULL)
984         {
985           GNUNET_DISK_file_close (dc->handle);
986           dc->handle = NULL;
987           if (0 != truncate (dc->filename,
988                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
989             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
990                                       "truncate",
991                                       dc->filename);
992         }
993
994       if (is_recursive_download (dc))
995         full_recursive_download (dc);
996       if (dc->child_head == NULL)
997         {
998           /* signal completion */
999           pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
1000           make_download_status (&pi, dc);
1001           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1002                                          &pi);
1003           if (dc->parent != NULL)
1004             check_completed (dc->parent);
1005         }
1006       GNUNET_assert (sm->depth == dc->treedepth);
1007     }
1008   // FIXME: make persistent
1009   if (sm->depth == dc->treedepth) 
1010     {
1011       GNUNET_free (sm);      
1012       return GNUNET_YES;
1013     }
1014 #if DEBUG_DOWNLOAD
1015   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1017               sm->depth,
1018               (unsigned long long) sm->offset);
1019 #endif
1020   GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1021   chk = (struct ContentHashKey*) pt;
1022   for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1023     {
1024       off = compute_dblock_offset (sm->offset,
1025                                    sm->depth,
1026                                    dc->treedepth,
1027                                    i);
1028       if ( (off + DBLOCK_SIZE >= dc->offset) &&
1029            (off < dc->offset + dc->length) ) 
1030         schedule_block_download (dc,
1031                                  &chk[i],
1032                                  off,
1033                                  sm->depth + 1);
1034     }
1035   GNUNET_free (sm);
1036   return GNUNET_YES;
1037 }
1038
1039
1040 /**
1041  * Process a download result.
1042  *
1043  * @param dc our download context
1044  * @param type type of the result
1045  * @param data the (encrypted) response
1046  * @param size size of data
1047  */
1048 static void
1049 process_result (struct GNUNET_FS_DownloadContext *dc,
1050                 enum GNUNET_BLOCK_Type type,
1051                 const void *data,
1052                 size_t size)
1053 {
1054   struct ProcessResultClosure prc;
1055
1056   prc.dc = dc;
1057   prc.data = data;
1058   prc.size = size;
1059   prc.type = type;
1060   prc.do_store = GNUNET_YES;
1061   GNUNET_CRYPTO_hash (data, size, &prc.query);
1062 #if DEBUG_DOWNLOAD
1063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064               "Received result for query `%s' from `%s'-service\n",
1065               GNUNET_h2s (&prc.query),
1066               "FS");
1067 #endif
1068   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1069                                               &prc.query,
1070                                               &process_result_with_request,
1071                                               &prc);
1072 }
1073
1074
1075 /**
1076  * Type of a function to call when we receive a message
1077  * from the service.
1078  *
1079  * @param cls closure
1080  * @param msg message received, NULL on timeout or fatal error
1081  */
1082 static void 
1083 receive_results (void *cls,
1084                  const struct GNUNET_MessageHeader * msg)
1085 {
1086   struct GNUNET_FS_DownloadContext *dc = cls;
1087   const struct PutMessage *cm;
1088   uint16_t msize;
1089
1090   if ( (NULL == msg) ||
1091        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1092        (sizeof (struct PutMessage) > ntohs(msg->size)) )
1093     {
1094       GNUNET_break (msg == NULL);       
1095       try_reconnect (dc);
1096       return;
1097     }
1098   msize = ntohs(msg->size);
1099   cm = (const struct PutMessage*) msg;
1100   process_result (dc, 
1101                   ntohl (cm->type),
1102                   &cm[1],
1103                   msize - sizeof (struct PutMessage));
1104   if (dc->client == NULL)
1105     return; /* fatal error */
1106   /* continue receiving */
1107   GNUNET_CLIENT_receive (dc->client,
1108                          &receive_results,
1109                          dc,
1110                          GNUNET_TIME_UNIT_FOREVER_REL);
1111 }
1112
1113
1114
1115 /**
1116  * We're ready to transmit a search request to the
1117  * file-sharing service.  Do it.  If there is 
1118  * more than one request pending, try to send 
1119  * multiple or request another transmission.
1120  *
1121  * @param cls closure
1122  * @param size number of bytes available in buf
1123  * @param buf where the callee should write the message
1124  * @return number of bytes written to buf
1125  */
1126 static size_t
1127 transmit_download_request (void *cls,
1128                            size_t size, 
1129                            void *buf)
1130 {
1131   struct GNUNET_FS_DownloadContext *dc = cls;
1132   size_t msize;
1133   struct SearchMessage *sm;
1134
1135   dc->th = NULL;
1136   if (NULL == buf)
1137     {
1138       try_reconnect (dc);
1139       return 0;
1140     }
1141   GNUNET_assert (size >= sizeof (struct SearchMessage));
1142   msize = 0;
1143   sm = buf;
1144   while ( (dc->pending != NULL) &&
1145           (size > msize + sizeof (struct SearchMessage)) )
1146     {
1147 #if DEBUG_DOWNLOAD
1148       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1149                   "Transmitting download request for `%s' to `%s'-service\n",
1150                   GNUNET_h2s (&dc->pending->chk.query),
1151                   "FS");
1152 #endif
1153       memset (sm, 0, sizeof (struct SearchMessage));
1154       sm->header.size = htons (sizeof (struct SearchMessage));
1155       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1156       if (dc->pending->depth == dc->treedepth)
1157         sm->type = htonl (GNUNET_BLOCK_TYPE_DBLOCK);
1158       else
1159         sm->type = htonl (GNUNET_BLOCK_TYPE_IBLOCK);
1160       sm->anonymity_level = htonl (dc->anonymity);
1161       sm->target = dc->target.hashPubKey;
1162       sm->query = dc->pending->chk.query;
1163       dc->pending->is_pending = GNUNET_NO;
1164       dc->pending = dc->pending->next;
1165       msize += sizeof (struct SearchMessage);
1166       sm++;
1167     }
1168   if (dc->pending != NULL)
1169     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1170                                                   sizeof (struct SearchMessage),
1171                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1172                                                   GNUNET_NO,
1173                                                   &transmit_download_request,
1174                                                   dc); 
1175   return msize;
1176 }
1177
1178
1179 /**
1180  * Reconnect to the FS service and transmit our queries NOW.
1181  *
1182  * @param cls our download context
1183  * @param tc unused
1184  */
1185 static void
1186 do_reconnect (void *cls,
1187               const struct GNUNET_SCHEDULER_TaskContext *tc)
1188 {
1189   struct GNUNET_FS_DownloadContext *dc = cls;
1190   struct GNUNET_CLIENT_Connection *client;
1191   
1192   dc->task = GNUNET_SCHEDULER_NO_TASK;
1193   client = GNUNET_CLIENT_connect (dc->h->sched,
1194                                   "fs",
1195                                   dc->h->cfg);
1196   if (NULL == client)
1197     {
1198       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1199                   "Connecting to `%s'-service failed, will try again.\n",
1200                   "FS");
1201       try_reconnect (dc);
1202       return;
1203     }
1204   dc->client = client;
1205   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1206                                                 sizeof (struct SearchMessage),
1207                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1208                                                 GNUNET_NO,
1209                                                 &transmit_download_request,
1210                                                 dc);  
1211   GNUNET_CLIENT_receive (client,
1212                          &receive_results,
1213                          dc,
1214                          GNUNET_TIME_UNIT_FOREVER_REL);
1215 }
1216
1217
1218 /**
1219  * Add entries that are not yet pending back to the pending list.
1220  *
1221  * @param cls our download context
1222  * @param key unused
1223  * @param entry entry of type "struct DownloadRequest"
1224  * @return GNUNET_OK
1225  */
1226 static int
1227 retry_entry (void *cls,
1228              const GNUNET_HashCode *key,
1229              void *entry)
1230 {
1231   struct GNUNET_FS_DownloadContext *dc = cls;
1232   struct DownloadRequest *dr = entry;
1233
1234   if (! dr->is_pending)
1235     {
1236       dr->next = dc->pending;
1237       dr->is_pending = GNUNET_YES;
1238       dc->pending = entry;
1239     }
1240   return GNUNET_OK;
1241 }
1242
1243
1244 /**
1245  * We've lost our connection with the FS service.
1246  * Re-establish it and re-transmit all of our
1247  * pending requests.
1248  *
1249  * @param dc download context that is having trouble
1250  */
1251 static void
1252 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1253 {
1254   
1255   if (NULL != dc->client)
1256     {
1257       if (NULL != dc->th)
1258         {
1259           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1260           dc->th = NULL;
1261         }
1262       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1263                                              &retry_entry,
1264                                              dc);
1265       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1266       dc->client = NULL;
1267     }
1268   dc->task
1269     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1270                                     GNUNET_TIME_UNIT_SECONDS,
1271                                     &do_reconnect,
1272                                     dc);
1273 }
1274
1275
1276 /**
1277  * Download parts of a file.  Note that this will store
1278  * the blocks at the respective offset in the given file.  Also, the
1279  * download is still using the blocking of the underlying FS
1280  * encoding.  As a result, the download may *write* outside of the
1281  * given boundaries (if offset and length do not match the 32k FS
1282  * block boundaries). <p>
1283  *
1284  * This function should be used to focus a download towards a
1285  * particular portion of the file (optimization), not to strictly
1286  * limit the download to exactly those bytes.
1287  *
1288  * @param h handle to the file sharing subsystem
1289  * @param uri the URI of the file (determines what to download); CHK or LOC URI
1290  * @param meta known metadata for the file (can be NULL)
1291  * @param filename where to store the file, maybe NULL (then no file is
1292  *        created on disk and data must be grabbed from the callbacks)
1293  * @param tempname where to store temporary file data, not used if filename is non-NULL;
1294  *        can be NULL (in which case we will pick a name if needed); the temporary file
1295  *        may already exist, in which case we will try to use the data that is there and
1296  *        if it is not what is desired, will overwrite it
1297  * @param offset at what offset should we start the download (typically 0)
1298  * @param length how many bytes should be downloaded starting at offset
1299  * @param anonymity anonymity level to use for the download
1300  * @param options various options
1301  * @param cctx initial value for the client context for this download
1302  * @param parent parent download to associate this download with (use NULL
1303  *        for top-level downloads; useful for manually-triggered recursive downloads)
1304  * @return context that can be used to control this download
1305  */
1306 struct GNUNET_FS_DownloadContext *
1307 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1308                           const struct GNUNET_FS_Uri *uri,
1309                           const struct GNUNET_CONTAINER_MetaData *meta,
1310                           const char *filename,
1311                           const char *tempname,
1312                           uint64_t offset,
1313                           uint64_t length,
1314                           uint32_t anonymity,
1315                           enum GNUNET_FS_DownloadOptions options,
1316                           void *cctx,
1317                           struct GNUNET_FS_DownloadContext *parent)
1318 {
1319   struct GNUNET_FS_ProgressInfo pi;
1320   struct GNUNET_FS_DownloadContext *dc;
1321   struct GNUNET_CLIENT_Connection *client;
1322
1323   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1324   if ( (offset + length < offset) ||
1325        (offset + length > uri->data.chk.file_length) )
1326     {      
1327       GNUNET_break (0);
1328       return NULL;
1329     }
1330   // FIXME: add support for "loc" URIs!
1331 #if DEBUG_DOWNLOAD
1332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1333               "Starting download `%s' of %llu bytes\n",
1334               filename,
1335               (unsigned long long) length);
1336 #endif
1337   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1338   dc->h = h;
1339   dc->parent = parent;
1340   if (parent != NULL)
1341     {
1342       GNUNET_CONTAINER_DLL_insert (parent->child_head,
1343                                    parent->child_tail,
1344                                    dc);
1345     }
1346   dc->uri = GNUNET_FS_uri_dup (uri);
1347   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1348   dc->client_info = cctx;
1349   dc->start_time = GNUNET_TIME_absolute_get ();
1350   if (NULL != filename)
1351     {
1352       dc->filename = GNUNET_strdup (filename);
1353       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1354         GNUNET_DISK_file_size (filename,
1355                                &dc->old_file_size,
1356                                GNUNET_YES);
1357       dc->handle = GNUNET_DISK_file_open (filename, 
1358                                           GNUNET_DISK_OPEN_READWRITE | 
1359                                           GNUNET_DISK_OPEN_CREATE,
1360                                           GNUNET_DISK_PERM_USER_READ |
1361                                           GNUNET_DISK_PERM_USER_WRITE |
1362                                           GNUNET_DISK_PERM_GROUP_READ |
1363                                           GNUNET_DISK_PERM_OTHER_READ);
1364       if (dc->handle == NULL)
1365         {
1366           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1367                       _("Download failed: could not open file `%s': %s\n"),
1368                       dc->filename,
1369                       STRERROR (errno));
1370           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1371           GNUNET_FS_uri_destroy (dc->uri);
1372           GNUNET_free (dc->filename);
1373           GNUNET_free (dc);
1374           return NULL;
1375         }
1376     }
1377   // FIXME: set "dc->target" for LOC uris!
1378   dc->offset = offset;
1379   dc->length = length;
1380   dc->anonymity = anonymity;
1381   dc->options = options;
1382   dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1383   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1384   if ( (filename == NULL) &&
1385        (is_recursive_download (dc) ) )
1386     {
1387       if (tempname != NULL)
1388         dc->temp_filename = GNUNET_strdup (tempname);
1389       else
1390         dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");    
1391     }
1392
1393 #if DEBUG_DOWNLOAD
1394   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1395               "Download tree has depth %u\n",
1396               dc->treedepth);
1397 #endif
1398   // FIXME: make persistent
1399   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1400   make_download_status (&pi, dc);
1401   pi.value.download.specifics.start.meta = meta;
1402   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1403                                  &pi);
1404
1405   
1406   // FIXME: bound parallelism here
1407   client = GNUNET_CLIENT_connect (h->sched,
1408                                   "fs",
1409                                   h->cfg);
1410   GNUNET_assert (NULL != client);
1411   dc->client = client;
1412   GNUNET_CLIENT_receive (client,
1413                          &receive_results,
1414                          dc,
1415                          GNUNET_TIME_UNIT_FOREVER_REL);
1416   pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1417   make_download_status (&pi, dc);
1418   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1419                                  &pi);
1420   schedule_block_download (dc, 
1421                            &dc->uri->data.chk.chk,
1422                            0, 
1423                            1 /* 0 == CHK, 1 == top */);
1424   return dc;
1425 }
1426
1427
1428 /**
1429  * Free entries in the map.
1430  *
1431  * @param cls unused (NULL)
1432  * @param key unused
1433  * @param entry entry of type "struct DownloadRequest" which is freed
1434  * @return GNUNET_OK
1435  */
1436 static int
1437 free_entry (void *cls,
1438             const GNUNET_HashCode *key,
1439             void *entry)
1440 {
1441   GNUNET_free (entry);
1442   return GNUNET_OK;
1443 }
1444
1445
1446 /**
1447  * Stop a download (aborts if download is incomplete).
1448  *
1449  * @param dc handle for the download
1450  * @param do_delete delete files of incomplete downloads
1451  */
1452 void
1453 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1454                          int do_delete)
1455 {
1456   struct GNUNET_FS_ProgressInfo pi;
1457
1458   while (NULL != dc->child_head)
1459     GNUNET_FS_download_stop (dc->child_head, 
1460                              do_delete);
1461   // FIXME: make unpersistent  
1462   if (dc->parent != NULL)
1463     GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1464                                  dc->parent->child_tail,
1465                                  dc);
1466   
1467   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1468   make_download_status (&pi, dc);
1469   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1470                                  &pi);
1471
1472   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1473     GNUNET_SCHEDULER_cancel (dc->h->sched,
1474                              dc->task);
1475   if (NULL != dc->th)
1476     {
1477       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1478       dc->th = NULL;
1479     }
1480   if (NULL != dc->client)
1481     GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1482   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1483                                          &free_entry,
1484                                          NULL);
1485   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1486   if (dc->filename != NULL)
1487     {
1488       if (NULL != dc->handle)
1489         GNUNET_DISK_file_close (dc->handle);
1490       if ( (dc->completed != dc->length) &&
1491            (GNUNET_YES == do_delete) )
1492         {
1493           if (0 != UNLINK (dc->filename))
1494             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1495                                       "unlink",
1496                                       dc->filename);
1497         }
1498       GNUNET_free (dc->filename);
1499     }
1500   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1501   GNUNET_FS_uri_destroy (dc->uri);
1502   if (NULL != dc->temp_filename)
1503     {
1504       if (0 != UNLINK (dc->temp_filename))
1505         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1506                                   "unlink",
1507                                   dc->temp_filename);
1508       GNUNET_free (dc->temp_filename);
1509     }
1510   GNUNET_free (dc);
1511 }
1512
1513 /* end of fs_download.c */