7bdf6902b5f39674b02cbc18aa8c94aaa1c5c3fc
[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   uint32_t 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_DATASTORE_BLOCKTYPE_DBLOCK 
337                 : GNUNET_DATASTORE_BLOCKTYPE_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   struct GNUNET_FS_DownloadContext *dc = cls;  
538   struct GNUNET_FS_DownloadContext *cpos;
539   struct GNUNET_DISK_FileHandle *fh;
540   char *fn;
541   char *us;
542   char *ext;
543   char *dn;
544   char *full_name;
545
546   if (NULL == uri)
547     return; /* entry for the directory itself */
548   cpos = dc->child_head;
549   while (cpos != NULL)
550     {
551       if ( (GNUNET_FS_uri_test_equal (uri,
552                                       cpos->uri)) ||
553            ( (filename != NULL) &&
554              (0 == strcmp (cpos->filename,
555                            filename)) ) )
556         break;  
557       cpos = cpos->next;
558     }
559   if (cpos != NULL)
560     return; /* already exists */
561   fn = NULL;
562   if (NULL == filename)
563     {
564       fn = GNUNET_FS_meta_data_suggest_filename (meta);      
565       if (fn == NULL)
566         {
567           us = GNUNET_FS_uri_to_string (uri);
568           fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX 
569                                            GNUNET_FS_URI_CHK_INFIX)]);
570           GNUNET_free (us);
571         }
572       else if (fn[0] == '.')
573         {
574           ext = fn;
575           us = GNUNET_FS_uri_to_string (uri);
576           GNUNET_asprintf (&fn,
577                            "%s%s",
578                            &us[strlen (GNUNET_FS_URI_PREFIX 
579                                        GNUNET_FS_URI_CHK_INFIX)], ext);
580           GNUNET_free (ext);
581           GNUNET_free (us);
582         }
583       filename = fn;
584     }
585   if (dc->filename == NULL)
586     {
587       full_name = NULL;
588     }
589   else
590     {
591       dn = GNUNET_strdup (dc->filename);
592       GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
593                      (NULL !=
594                       strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
595                               GNUNET_FS_DIRECTORY_EXT)) );
596       if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
597            (NULL !=
598             strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
599                     GNUNET_FS_DIRECTORY_EXT)) )      
600         dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';      
601       if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
602            ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
603              (NULL ==
604               strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
605                       GNUNET_FS_DIRECTORY_EXT)) ) )
606         {
607           GNUNET_asprintf (&full_name,
608                            "%s%s%s%s",
609                            dn,
610                            DIR_SEPARATOR_STR,
611                            filename,
612                            GNUNET_FS_DIRECTORY_EXT);
613         }
614       else
615         {
616           GNUNET_asprintf (&full_name,
617                            "%s%s%s",
618                            dn,
619                            DIR_SEPARATOR_STR,
620                            filename);
621         }
622       GNUNET_free (dn);
623     }
624   if ( (full_name != NULL) &&
625        (GNUNET_OK !=
626         GNUNET_DISK_directory_create_for_file (full_name)) )
627     {
628       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
629                   _("Failed to create directory for recursive download of `%s'\n"),
630                   full_name);
631       GNUNET_free (full_name);
632       GNUNET_free_non_null (fn);
633       return;
634     }
635     
636   if (data != NULL) 
637     {
638       if (full_name != NULL)
639         {
640           fh = GNUNET_DISK_file_open (full_name,
641                                       GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
642                                       GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
643           if (fh == NULL)
644             {
645               GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
646                                         "open",
647                                         full_name);           
648               GNUNET_free (full_name);
649               GNUNET_free_non_null (fn);
650               return;
651             }
652           if (length != 
653               GNUNET_DISK_file_write (fh,
654                                       data,
655                                       length))
656             {
657               GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
658                                         "write",
659                                         full_name);           
660             }
661           GNUNET_DISK_file_close (fh);
662         }
663       else
664         {
665           /* FIXME: generate 'progress' events and move to
666              instant completion! */
667           GNUNET_break (0); // FIXME: not implemented
668         }
669     }
670   GNUNET_FS_download_start (dc->h,
671                             uri,
672                             meta,
673                             full_name,
674                             0,
675                             GNUNET_FS_uri_chk_get_file_size (uri),
676                             dc->anonymity,
677                             dc->options,
678                             NULL,
679                             dc);
680   GNUNET_free_non_null (full_name);
681   GNUNET_free_non_null (fn);
682 }
683
684
685 /**
686  * We're done downloading a directory.  Open the file and
687  * trigger all of the (remaining) child downloads.
688  *
689  * @param dc context of download that just completed
690  */
691 static void
692 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
693 {
694   size_t size;
695   uint64_t size64;
696   void *data;
697   struct GNUNET_DISK_FileHandle *h;
698   struct GNUNET_DISK_MapHandle *m;
699   
700   size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
701   size = (size_t) size64;
702   if (size64 != (uint64_t) size)
703     {
704       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
705                   _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
706       return;
707     }
708   if (dc->filename != NULL)
709     {
710       h = GNUNET_DISK_file_open (dc->filename,
711                                  GNUNET_DISK_OPEN_READ,
712                                  GNUNET_DISK_PERM_NONE);
713     }
714   else
715     {
716       GNUNET_assert (dc->temp_filename != NULL);
717       h = GNUNET_DISK_file_open (dc->temp_filename,
718                                  GNUNET_DISK_OPEN_READ,
719                                  GNUNET_DISK_PERM_NONE);
720     }
721   if (h == NULL)
722     return; /* oops */
723   data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
724   if (data == NULL)
725     {
726       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
727                   _("Directory too large for system address space\n"));
728     }
729   else
730     {
731       GNUNET_FS_directory_list_contents (size,
732                                          data,
733                                          0,
734                                          &trigger_recursive_download,
735                                          dc);         
736       GNUNET_DISK_file_unmap (m);
737     }
738   GNUNET_DISK_file_close (h);
739   if (dc->filename == NULL)
740     {
741       if (0 != UNLINK (dc->temp_filename))
742         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
743                                   "unlink",
744                                   dc->temp_filename);
745       GNUNET_free (dc->temp_filename);
746       dc->temp_filename = NULL;
747     }
748 }
749
750
751 /**
752  * Check if all child-downloads have completed and
753  * if so, signal completion (and possibly recurse to
754  * parent).
755  */
756 static void
757 check_completed (struct GNUNET_FS_DownloadContext *dc)
758 {
759   struct GNUNET_FS_ProgressInfo pi;
760   struct GNUNET_FS_DownloadContext *pos;
761
762   pos = dc->child_head;
763   while (pos != NULL)
764     {
765       if ( (pos->emsg == NULL) &&
766            (pos->completed < pos->length) )
767         return; /* not done yet */
768       if ( (pos->child_head != NULL) &&
769            (pos->has_finished != GNUNET_YES) )
770         return; /* not transitively done yet */
771       pos = pos->next;
772     }
773   dc->has_finished = GNUNET_YES;
774   /* signal completion */
775   pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
776   make_download_status (&pi, dc);
777   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
778                                  &pi);
779   if (dc->parent != NULL)
780     check_completed (dc->parent);  
781 }
782
783
784 /**
785  * Iterator over entries in the pending requests in the 'active' map for the
786  * reply that we just got.
787  *
788  * @param cls closure (our 'struct ProcessResultClosure')
789  * @param key query for the given value / request
790  * @param value value in the hash map (a 'struct DownloadRequest')
791  * @return GNUNET_YES (we should continue to iterate); unless serious error
792  */
793 static int
794 process_result_with_request (void *cls,
795                              const GNUNET_HashCode * key,
796                              void *value)
797 {
798   struct ProcessResultClosure *prc = cls;
799   struct DownloadRequest *sm = value;
800   struct GNUNET_FS_DownloadContext *dc = prc->dc;
801   struct GNUNET_CRYPTO_AesSessionKey skey;
802   struct GNUNET_CRYPTO_AesInitializationVector iv;
803   char pt[prc->size];
804   struct GNUNET_FS_ProgressInfo pi;
805   uint64_t off;
806   size_t bs;
807   size_t app;
808   int i;
809   struct ContentHashKey *chk;
810   char *emsg;
811
812   bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
813                                             dc->treedepth,
814                                             sm->offset,
815                                             sm->depth);
816     if (prc->size != bs)
817     {
818 #if DEBUG_DOWNLOAD
819       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
821                   bs,
822                   prc->size);
823 #endif
824       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
825       /* signal error */
826       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
827       make_download_status (&pi, dc);
828       pi.value.download.specifics.error.message = dc->emsg;
829       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
830                                      &pi);
831       /* abort all pending requests */
832       if (NULL != dc->th)
833         {
834           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
835           dc->th = NULL;
836         }
837       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
838       dc->client = NULL;
839       return GNUNET_NO;
840     }
841   GNUNET_assert (GNUNET_YES ==
842                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
843                                                        &prc->query,
844                                                        sm));
845   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
846   GNUNET_CRYPTO_aes_decrypt (prc->data,
847                              prc->size,
848                              &skey,
849                              &iv,
850                              pt);
851   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
852                              sm->offset,
853                              sm->depth,
854                              dc->treedepth);
855   /* save to disk */
856   if ( ( GNUNET_YES == prc->do_store) &&
857        (NULL != dc->handle) &&
858        ( (sm->depth == dc->treedepth) ||
859          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
860     {
861       emsg = NULL;
862 #if DEBUG_DOWNLOAD
863       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864                   "Saving decrypted block to disk at offset %llu\n",
865                   (unsigned long long) off);
866 #endif
867       if ( (off  != 
868             GNUNET_DISK_file_seek (dc->handle,
869                                    off,
870                                    GNUNET_DISK_SEEK_SET) ) )
871         GNUNET_asprintf (&emsg,
872                          _("Failed to seek to offset %llu in file `%s': %s\n"),
873                          (unsigned long long) off,
874                          dc->filename,
875                          STRERROR (errno));
876       else if (prc->size !=
877                GNUNET_DISK_file_write (dc->handle,
878                                        pt,
879                                        prc->size))
880         GNUNET_asprintf (&emsg,
881                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
882                          (unsigned int) prc->size,
883                          (unsigned long long) off,
884                          dc->filename,
885                          STRERROR (errno));
886       if (NULL != emsg)
887         {
888           dc->emsg = emsg;
889           // FIXME: make persistent
890
891           /* signal error */
892           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
893           make_download_status (&pi, dc);
894           pi.value.download.specifics.error.message = emsg;
895           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
896                                          &pi);
897
898           /* abort all pending requests */
899           if (NULL != dc->th)
900             {
901               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
902               dc->th = NULL;
903             }
904           GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
905           dc->client = NULL;
906           GNUNET_free (sm);
907           return GNUNET_NO;
908         }
909     }
910   if (sm->depth == dc->treedepth) 
911     {
912       app = prc->size;
913       if (sm->offset < dc->offset)
914         {
915           /* starting offset begins in the middle of pt,
916              do not count first bytes as progress */
917           GNUNET_assert (app > (dc->offset - sm->offset));
918           app -= (dc->offset - sm->offset);       
919         }
920       if (sm->offset + prc->size > dc->offset + dc->length)
921         {
922           /* end of block is after relevant range,
923              do not count last bytes as progress */
924           GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
925           app -= (sm->offset + prc->size) - (dc->offset + dc->length);
926         }
927       dc->completed += app;
928
929       /* do recursive download if option is set and either meta data
930          says it is a directory or if no meta data is given AND filename 
931          ends in '.gnd' (top-level case) */
932       if (is_recursive_download (dc))
933         GNUNET_FS_directory_list_contents (prc->size,
934                                            pt,
935                                            off,
936                                            &trigger_recursive_download,
937                                            dc);         
938             
939     }
940   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
941   make_download_status (&pi, dc);
942   pi.value.download.specifics.progress.data = pt;
943   pi.value.download.specifics.progress.offset = sm->offset;
944   pi.value.download.specifics.progress.data_len = prc->size;
945   pi.value.download.specifics.progress.depth = sm->depth;
946   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
947                                  &pi);
948   GNUNET_assert (dc->completed <= dc->length);
949   if (dc->completed == dc->length)
950     {
951 #if DEBUG_DOWNLOAD
952       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
953                   "Download completed, truncating file to desired length %llu\n",
954                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
955 #endif
956       /* truncate file to size (since we store IBlocks at the end) */
957       if (dc->handle != NULL)
958         {
959           GNUNET_DISK_file_close (dc->handle);
960           dc->handle = NULL;
961           if (0 != truncate (dc->filename,
962                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
963             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
964                                       "truncate",
965                                       dc->filename);
966         }
967
968       if (is_recursive_download (dc))
969         full_recursive_download (dc);
970       if (dc->child_head == NULL)
971         {
972           /* signal completion */
973           pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
974           make_download_status (&pi, dc);
975           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
976                                          &pi);
977           if (dc->parent != NULL)
978             check_completed (dc->parent);
979         }
980       GNUNET_assert (sm->depth == dc->treedepth);
981     }
982   // FIXME: make persistent
983   if (sm->depth == dc->treedepth) 
984     {
985       GNUNET_free (sm);      
986       return GNUNET_YES;
987     }
988 #if DEBUG_DOWNLOAD
989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
991               sm->depth,
992               (unsigned long long) sm->offset);
993 #endif
994   GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
995   chk = (struct ContentHashKey*) pt;
996   for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
997     {
998       off = compute_dblock_offset (sm->offset,
999                                    sm->depth,
1000                                    dc->treedepth,
1001                                    i);
1002       if ( (off + DBLOCK_SIZE >= dc->offset) &&
1003            (off < dc->offset + dc->length) ) 
1004         schedule_block_download (dc,
1005                                  &chk[i],
1006                                  off,
1007                                  sm->depth + 1);
1008     }
1009   GNUNET_free (sm);
1010   return GNUNET_YES;
1011 }
1012
1013
1014 /**
1015  * Process a download result.
1016  *
1017  * @param dc our download context
1018  * @param type type of the result
1019  * @param data the (encrypted) response
1020  * @param size size of data
1021  */
1022 static void
1023 process_result (struct GNUNET_FS_DownloadContext *dc,
1024                 uint32_t type,
1025                 const void *data,
1026                 size_t size)
1027 {
1028   struct ProcessResultClosure prc;
1029
1030   prc.dc = dc;
1031   prc.data = data;
1032   prc.size = size;
1033   prc.type = type;
1034   prc.do_store = GNUNET_YES;
1035   GNUNET_CRYPTO_hash (data, size, &prc.query);
1036 #if DEBUG_DOWNLOAD
1037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038               "Received result for query `%s' from `%s'-service\n",
1039               GNUNET_h2s (&prc.query),
1040               "FS");
1041 #endif
1042   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1043                                               &prc.query,
1044                                               &process_result_with_request,
1045                                               &prc);
1046 }
1047
1048
1049 /**
1050  * Type of a function to call when we receive a message
1051  * from the service.
1052  *
1053  * @param cls closure
1054  * @param msg message received, NULL on timeout or fatal error
1055  */
1056 static void 
1057 receive_results (void *cls,
1058                  const struct GNUNET_MessageHeader * msg)
1059 {
1060   struct GNUNET_FS_DownloadContext *dc = cls;
1061   const struct PutMessage *cm;
1062   uint16_t msize;
1063
1064   if ( (NULL == msg) ||
1065        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1066        (sizeof (struct PutMessage) > ntohs(msg->size)) )
1067     {
1068       GNUNET_break (msg == NULL);       
1069       try_reconnect (dc);
1070       return;
1071     }
1072   msize = ntohs(msg->size);
1073   cm = (const struct PutMessage*) msg;
1074   process_result (dc, 
1075                   ntohl (cm->type),
1076                   &cm[1],
1077                   msize - sizeof (struct PutMessage));
1078   if (dc->client == NULL)
1079     return; /* fatal error */
1080   /* continue receiving */
1081   GNUNET_CLIENT_receive (dc->client,
1082                          &receive_results,
1083                          dc,
1084                          GNUNET_TIME_UNIT_FOREVER_REL);
1085 }
1086
1087
1088
1089 /**
1090  * We're ready to transmit a search request to the
1091  * file-sharing service.  Do it.  If there is 
1092  * more than one request pending, try to send 
1093  * multiple or request another transmission.
1094  *
1095  * @param cls closure
1096  * @param size number of bytes available in buf
1097  * @param buf where the callee should write the message
1098  * @return number of bytes written to buf
1099  */
1100 static size_t
1101 transmit_download_request (void *cls,
1102                            size_t size, 
1103                            void *buf)
1104 {
1105   struct GNUNET_FS_DownloadContext *dc = cls;
1106   size_t msize;
1107   struct SearchMessage *sm;
1108
1109   dc->th = NULL;
1110   if (NULL == buf)
1111     {
1112       try_reconnect (dc);
1113       return 0;
1114     }
1115   GNUNET_assert (size >= sizeof (struct SearchMessage));
1116   msize = 0;
1117   sm = buf;
1118   while ( (dc->pending != NULL) &&
1119           (size > msize + sizeof (struct SearchMessage)) )
1120     {
1121 #if DEBUG_DOWNLOAD
1122       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123                   "Transmitting download request for `%s' to `%s'-service\n",
1124                   GNUNET_h2s (&dc->pending->chk.query),
1125                   "FS");
1126 #endif
1127       memset (sm, 0, sizeof (struct SearchMessage));
1128       sm->header.size = htons (sizeof (struct SearchMessage));
1129       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1130       if (dc->pending->depth == dc->treedepth)
1131         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
1132       else
1133         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
1134       sm->anonymity_level = htonl (dc->anonymity);
1135       sm->target = dc->target.hashPubKey;
1136       sm->query = dc->pending->chk.query;
1137       dc->pending->is_pending = GNUNET_NO;
1138       dc->pending = dc->pending->next;
1139       msize += sizeof (struct SearchMessage);
1140       sm++;
1141     }
1142   if (dc->pending != NULL)
1143     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1144                                                   sizeof (struct SearchMessage),
1145                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1146                                                   GNUNET_NO,
1147                                                   &transmit_download_request,
1148                                                   dc); 
1149   return msize;
1150 }
1151
1152
1153 /**
1154  * Reconnect to the FS service and transmit our queries NOW.
1155  *
1156  * @param cls our download context
1157  * @param tc unused
1158  */
1159 static void
1160 do_reconnect (void *cls,
1161               const struct GNUNET_SCHEDULER_TaskContext *tc)
1162 {
1163   struct GNUNET_FS_DownloadContext *dc = cls;
1164   struct GNUNET_CLIENT_Connection *client;
1165   
1166   dc->task = GNUNET_SCHEDULER_NO_TASK;
1167   client = GNUNET_CLIENT_connect (dc->h->sched,
1168                                   "fs",
1169                                   dc->h->cfg);
1170   if (NULL == client)
1171     {
1172       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1173                   "Connecting to `%s'-service failed, will try again.\n",
1174                   "FS");
1175       try_reconnect (dc);
1176       return;
1177     }
1178   dc->client = client;
1179   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1180                                                 sizeof (struct SearchMessage),
1181                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1182                                                 GNUNET_NO,
1183                                                 &transmit_download_request,
1184                                                 dc);  
1185   GNUNET_CLIENT_receive (client,
1186                          &receive_results,
1187                          dc,
1188                          GNUNET_TIME_UNIT_FOREVER_REL);
1189 }
1190
1191
1192 /**
1193  * Add entries that are not yet pending back to the pending list.
1194  *
1195  * @param cls our download context
1196  * @param key unused
1197  * @param entry entry of type "struct DownloadRequest"
1198  * @return GNUNET_OK
1199  */
1200 static int
1201 retry_entry (void *cls,
1202              const GNUNET_HashCode *key,
1203              void *entry)
1204 {
1205   struct GNUNET_FS_DownloadContext *dc = cls;
1206   struct DownloadRequest *dr = entry;
1207
1208   if (! dr->is_pending)
1209     {
1210       dr->next = dc->pending;
1211       dr->is_pending = GNUNET_YES;
1212       dc->pending = entry;
1213     }
1214   return GNUNET_OK;
1215 }
1216
1217
1218 /**
1219  * We've lost our connection with the FS service.
1220  * Re-establish it and re-transmit all of our
1221  * pending requests.
1222  *
1223  * @param dc download context that is having trouble
1224  */
1225 static void
1226 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1227 {
1228   
1229   if (NULL != dc->client)
1230     {
1231       if (NULL != dc->th)
1232         {
1233           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1234           dc->th = NULL;
1235         }
1236       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1237                                              &retry_entry,
1238                                              dc);
1239       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1240       dc->client = NULL;
1241     }
1242   dc->task
1243     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1244                                     GNUNET_TIME_UNIT_SECONDS,
1245                                     &do_reconnect,
1246                                     dc);
1247 }
1248
1249
1250 /**
1251  * Download parts of a file.  Note that this will store
1252  * the blocks at the respective offset in the given file.  Also, the
1253  * download is still using the blocking of the underlying FS
1254  * encoding.  As a result, the download may *write* outside of the
1255  * given boundaries (if offset and length do not match the 32k FS
1256  * block boundaries). <p>
1257  *
1258  * This function should be used to focus a download towards a
1259  * particular portion of the file (optimization), not to strictly
1260  * limit the download to exactly those bytes.
1261  *
1262  * @param h handle to the file sharing subsystem
1263  * @param uri the URI of the file (determines what to download); CHK or LOC URI
1264  * @param meta known metadata for the file (can be NULL)
1265  * @param filename where to store the file, maybe NULL (then no file is
1266  *        created on disk and data must be grabbed from the callbacks)
1267  * @param offset at what offset should we start the download (typically 0)
1268  * @param length how many bytes should be downloaded starting at offset
1269  * @param anonymity anonymity level to use for the download
1270  * @param options various options
1271  * @param cctx initial value for the client context for this download
1272  * @param parent parent download to associate this download with (use NULL
1273  *        for top-level downloads; useful for manually-triggered recursive downloads)
1274  * @return context that can be used to control this download
1275  */
1276 struct GNUNET_FS_DownloadContext *
1277 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1278                           const struct GNUNET_FS_Uri *uri,
1279                           const struct GNUNET_CONTAINER_MetaData *meta,
1280                           const char *filename,
1281                           uint64_t offset,
1282                           uint64_t length,
1283                           uint32_t anonymity,
1284                           enum GNUNET_FS_DownloadOptions options,
1285                           void *cctx,
1286                           struct GNUNET_FS_DownloadContext *parent)
1287 {
1288   struct GNUNET_FS_ProgressInfo pi;
1289   struct GNUNET_FS_DownloadContext *dc;
1290   struct GNUNET_CLIENT_Connection *client;
1291
1292   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1293   if ( (offset + length < offset) ||
1294        (offset + length > uri->data.chk.file_length) )
1295     {      
1296       GNUNET_break (0);
1297       return NULL;
1298     }
1299   // FIXME: add support for "loc" URIs!
1300 #if DEBUG_DOWNLOAD
1301   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1302               "Starting download `%s' of %llu bytes\n",
1303               filename,
1304               (unsigned long long) length);
1305 #endif
1306   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1307   dc->h = h;
1308   dc->parent = parent;
1309   if (parent != NULL)
1310     {
1311       GNUNET_CONTAINER_DLL_insert (parent->child_head,
1312                                    parent->child_tail,
1313                                    dc);
1314     }
1315   dc->uri = GNUNET_FS_uri_dup (uri);
1316   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1317   dc->client_info = cctx;
1318   dc->start_time = GNUNET_TIME_absolute_get ();
1319   if (NULL != filename)
1320     {
1321       dc->filename = GNUNET_strdup (filename);
1322       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1323         GNUNET_DISK_file_size (filename,
1324                                &dc->old_file_size,
1325                                GNUNET_YES);
1326       dc->handle = GNUNET_DISK_file_open (filename, 
1327                                           GNUNET_DISK_OPEN_READWRITE | 
1328                                           GNUNET_DISK_OPEN_CREATE,
1329                                           GNUNET_DISK_PERM_USER_READ |
1330                                           GNUNET_DISK_PERM_USER_WRITE |
1331                                           GNUNET_DISK_PERM_GROUP_READ |
1332                                           GNUNET_DISK_PERM_OTHER_READ);
1333       if (dc->handle == NULL)
1334         {
1335           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1336                       _("Download failed: could not open file `%s': %s\n"),
1337                       dc->filename,
1338                       STRERROR (errno));
1339           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1340           GNUNET_FS_uri_destroy (dc->uri);
1341           GNUNET_free (dc->filename);
1342           GNUNET_free (dc);
1343           return NULL;
1344         }
1345     }
1346   // FIXME: set "dc->target" for LOC uris!
1347   dc->offset = offset;
1348   dc->length = length;
1349   dc->anonymity = anonymity;
1350   dc->options = options;
1351   dc->active = GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE));
1352   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1353   if ( (filename == NULL) &&
1354        (is_recursive_download (dc) ) )
1355     dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");    
1356
1357 #if DEBUG_DOWNLOAD
1358   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359               "Download tree has depth %u\n",
1360               dc->treedepth);
1361 #endif
1362   // FIXME: make persistent
1363   
1364   // FIXME: bound parallelism here!
1365   client = GNUNET_CLIENT_connect (h->sched,
1366                                   "fs",
1367                                   h->cfg);
1368   dc->client = client;
1369   schedule_block_download (dc, 
1370                            &dc->uri->data.chk.chk,
1371                            0, 
1372                            1 /* 0 == CHK, 1 == top */);
1373   GNUNET_CLIENT_receive (client,
1374                          &receive_results,
1375                          dc,
1376                          GNUNET_TIME_UNIT_FOREVER_REL);
1377   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1378   make_download_status (&pi, dc);
1379   pi.value.download.specifics.start.meta = meta;
1380   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1381                                  &pi);
1382
1383   return dc;
1384 }
1385
1386
1387 /**
1388  * Free entries in the map.
1389  *
1390  * @param cls unused (NULL)
1391  * @param key unused
1392  * @param entry entry of type "struct DownloadRequest" which is freed
1393  * @return GNUNET_OK
1394  */
1395 static int
1396 free_entry (void *cls,
1397             const GNUNET_HashCode *key,
1398             void *entry)
1399 {
1400   GNUNET_free (entry);
1401   return GNUNET_OK;
1402 }
1403
1404
1405 /**
1406  * Stop a download (aborts if download is incomplete).
1407  *
1408  * @param dc handle for the download
1409  * @param do_delete delete files of incomplete downloads
1410  */
1411 void
1412 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1413                          int do_delete)
1414 {
1415   struct GNUNET_FS_ProgressInfo pi;
1416
1417   while (NULL != dc->child_head)
1418     GNUNET_FS_download_stop (dc->child_head, 
1419                              do_delete);
1420   // FIXME: make unpersistent  
1421   if (dc->parent != NULL)
1422     GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1423                                  dc->parent->child_tail,
1424                                  dc);
1425   
1426   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1427   make_download_status (&pi, dc);
1428   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1429                                  &pi);
1430
1431   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1432     GNUNET_SCHEDULER_cancel (dc->h->sched,
1433                              dc->task);
1434   if (NULL != dc->th)
1435     {
1436       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1437       dc->th = NULL;
1438     }
1439   if (NULL != dc->client)
1440     GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1441   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1442                                          &free_entry,
1443                                          NULL);
1444   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1445   if (dc->filename != NULL)
1446     {
1447       if (NULL != dc->handle)
1448         GNUNET_DISK_file_close (dc->handle);
1449       if ( (dc->completed != dc->length) &&
1450            (GNUNET_YES == do_delete) )
1451         {
1452           if (0 != UNLINK (dc->filename))
1453             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1454                                       "unlink",
1455                                       dc->filename);
1456         }
1457       GNUNET_free (dc->filename);
1458     }
1459   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1460   GNUNET_FS_uri_destroy (dc->uri);
1461   if (NULL != dc->temp_filename)
1462     {
1463       if (0 != UNLINK (dc->temp_filename))
1464         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1465                                   "unlink",
1466                                   dc->temp_filename);
1467       GNUNET_free (dc->temp_filename);
1468     }
1469   GNUNET_free (dc);
1470 }
1471
1472 /* end of fs_download.c */