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