towards suggesting filenames
[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
326   unsigned int i;
327   char *mime;
328   const char *ext;
329   
330   ext = "";
331   mime = NULL;
332   // FIXME: get mime from meta data
333   if (mime != NULL)
334     {
335       i = 0;
336       while ( (mimeMap[i][0] != NULL) && 
337               (0 != strcmp (mime, mimeMap[i][0])))
338         i++;
339       if (mimeMap[i][1] == NULL)
340         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | 
341                     GNUNET_ERROR_TYPE_BULK,
342                     _("Did not find mime type `%s' in extension list.\n"),
343                     mime);
344       else
345         ext = mimeMap[i][1];
346     }
347   // FIXME: try to get some base name...
348 #if 0
349   const char *key;
350   const char *mime;
351   char *path;
352   unsigned int j;
353   char *renameTo;
354   char *ret;
355   size_t max;
356   struct stat filestat;
357
358   key = EXTRACTOR_extractLast (EXTRACTOR_TITLE, list);
359   if (key == NULL)
360     key = EXTRACTOR_extractLast (EXTRACTOR_SOFTWARE, list);
361   if (key == NULL)
362     key = EXTRACTOR_extractLast (EXTRACTOR_DESCRIPTION, list);
363   if (key == NULL)
364     key = EXTRACTOR_extractLast (EXTRACTOR_COMMENT, list);
365   if (key == NULL)
366     key = EXTRACTOR_extractLast (EXTRACTOR_SUBJECT, list);
367   if (key == NULL)
368     key = EXTRACTOR_extractLast (EXTRACTOR_ALBUM, list);
369   if (key == NULL)
370     key = EXTRACTOR_extractLast (EXTRACTOR_UNKNOWN, list);
371   mime = EXTRACTOR_extractLast (EXTRACTOR_MIMETYPE, list);
372   if (mime != NULL)
373     {
374     }
375   if (key == NULL)
376     {
377       key = &filename[strlen (filename) - 1];
378       while ((key != filename) && (key[0] != DIR_SEPARATOR))
379         key--;
380       if (key[0] == DIR_SEPARATOR)
381         key++;
382     }
383       GNUNET_snprintf (renameTo,
384                        max,
385                        "%s%s%.*s%s",
386                        path,
387                        (path[strlen (path) - 1] !=
388                         DIR_SEPARATOR) ? DIR_SEPARATOR_STR : "",
389                        GNUNET_MIN (255 - strlen (mime),
390                                    PATH_MAX - strlen (path) - 64), key,
391                        (strcasecmp
392                         (renameTo + strlen (renameTo) - strlen (mime),
393                          mime) != 0) ? mime : "");
394
395
396     }
397   for (i = strlen (renameTo) - 1; i >= 0; i--)
398     if (!isprint (renameTo[i]))
399       renameTo[i] = '_';
400     else if (renameTo[i] == '.' && i > 0 && renameTo[i - 1] == '.')
401       {
402         /* remove .. to avoid directory traversal */
403         renameTo[i - 1] = renameTo[i] = '_';
404         i--;
405       }
406 #endif
407
408   GNUNET_break (0); // FIXME: not implemented
409   return NULL;
410 }
411
412
413 /**
414  * We've lost our connection with the FS service.
415  * Re-establish it and re-transmit all of our
416  * pending requests.
417  *
418  * @param dc download context that is having trouble
419  */
420 static void
421 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
422
423
424 /**
425  * Compute how many bytes of data should be stored in
426  * the specified node.
427  *
428  * @param fsize overall file size
429  * @param totaldepth depth of the entire tree
430  * @param offset offset of the node
431  * @param depth depth of the node
432  * @return number of bytes stored in this node
433  */
434 static size_t
435 calculate_block_size (uint64_t fsize,
436                       unsigned int totaldepth,
437                       uint64_t offset,
438                       unsigned int depth)
439 {
440   unsigned int i;
441   size_t ret;
442   uint64_t rsize;
443   uint64_t epos;
444   unsigned int chks;
445
446   GNUNET_assert (offset < fsize);
447   if (depth == totaldepth)
448     {
449       ret = DBLOCK_SIZE;
450       if (offset + ret > fsize)
451         ret = (size_t) (fsize - offset);
452       return ret;
453     }
454
455   rsize = DBLOCK_SIZE;
456   for (i = totaldepth-1; i > depth; i--)
457     rsize *= CHK_PER_INODE;
458   epos = offset + rsize * CHK_PER_INODE;
459   GNUNET_assert (epos > offset);
460   if (epos > fsize)
461     epos = fsize;
462   /* round up when computing #CHKs in our IBlock */
463   chks = (epos - offset + rsize - 1) / rsize;
464   GNUNET_assert (chks <= CHK_PER_INODE);
465   return chks * sizeof (struct ContentHashKey);
466 }
467
468
469 /**
470  * Closure for iterator processing results.
471  */
472 struct ProcessResultClosure
473 {
474   
475   /**
476    * Hash of data.
477    */
478   GNUNET_HashCode query;
479
480   /**
481    * Data found in P2P network.
482    */ 
483   const void *data;
484
485   /**
486    * Our download context.
487    */
488   struct GNUNET_FS_DownloadContext *dc;
489                 
490   /**
491    * Number of bytes in data.
492    */
493   size_t size;
494
495   /**
496    * Type of data.
497    */
498   uint32_t type;
499   
500 };
501
502
503 /**
504  * We found an entry in a directory.  Check if the respective child
505  * already exists and if not create the respective child download.
506  *
507  * @param cls the parent download
508  * @param filename name of the file in the directory
509  * @param uri URI of the file (CHK or LOC)
510  * @param meta meta data of the file
511  * @param length number of bytes in data
512  * @param data contents of the file (or NULL if they were not inlined)
513  */
514 static void 
515 trigger_recursive_download (void *cls,
516                             const char *filename,
517                             const struct GNUNET_FS_Uri *uri,
518                             const struct GNUNET_CONTAINER_MetaData *meta,
519                             size_t length,
520                             const void *data)
521 {
522   struct GNUNET_FS_DownloadContext *dc = cls;  
523   struct GNUNET_FS_DownloadContext *cpos;
524   char *fn;
525   char *us;
526   char *ext;
527   char *dn;
528   char *full_name;
529
530   if (NULL == uri)
531     return; /* entry for the directory itself */
532   cpos = dc->child_head;
533   while (cpos != NULL)
534     {
535       if ( (GNUNET_FS_uri_test_equal (uri,
536                                       cpos->uri)) ||
537            ( (filename != NULL) &&
538              (0 == strcmp (cpos->filename,
539                            filename)) ) )
540         break;  
541       cpos = cpos->next;
542     }
543   if (cpos != NULL)
544     return; /* already exists */
545   fn = NULL;
546   if (NULL == filename)
547     {
548       fn = GNUNET_FS_meta_data_suggest_filename (meta);      
549       if (fn == NULL)
550         {
551           us = GNUNET_FS_uri_to_string (uri);
552           fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX 
553                                            GNUNET_FS_URI_CHK_INFIX)]);
554           GNUNET_free (us);
555         }
556       else if (fn[0] == '.')
557         {
558           ext = fn;
559           us = GNUNET_FS_uri_to_string (uri);
560           GNUNET_asprintf (&fn,
561                            "%s%s",
562                            &us[strlen (GNUNET_FS_URI_PREFIX 
563                                        GNUNET_FS_URI_CHK_INFIX)], ext);
564           GNUNET_free (ext);
565           GNUNET_free (us);
566         }
567       filename = fn;
568     }
569   if (dc->filename == NULL)
570     {
571       full_name = NULL;
572     }
573   else
574     {
575       dn = GNUNET_strdup (dc->filename);
576       GNUNET_break ( (strlen (dn) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
577                      (NULL ==
578                       strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
579                               GNUNET_FS_DIRECTORY_EXT)) );
580       dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';      
581       if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
582            ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
583              (NULL ==
584               strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
585                       GNUNET_FS_DIRECTORY_EXT)) ) )
586         {
587           GNUNET_asprintf (&full_name,
588                            "%s%s%s%s",
589                            dn,
590                            DIR_SEPARATOR_STR,
591                            filename,
592                            GNUNET_FS_DIRECTORY_EXT);
593         }
594       else
595         {
596           GNUNET_asprintf (&full_name,
597                            "%s%s%s",
598                            dn,
599                            DIR_SEPARATOR_STR,
600                            filename);
601         }
602       GNUNET_free (dn);
603     }
604   if ( (full_name != NULL) &&
605        (GNUNET_OK !=
606         GNUNET_DISK_directory_create_for_file (full_name)) )
607     {
608       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
609                   _("Failed to create directory for recursive download of `%s'\n"),
610                   full_name);
611       GNUNET_free (full_name);
612       GNUNET_free_non_null (fn);
613       return;
614     }
615     
616   if (data != NULL) 
617     {
618       if (full_name != NULL)
619         {
620           /* determine on-disk filename, write data! */
621           GNUNET_break (0); // FIXME: not implemented
622         }
623       else
624         {
625           /* FIXME: generate 'progress' events and move to
626              instant completion! */
627           GNUNET_break (0); // FIXME: not implemented
628         }
629     }
630   GNUNET_FS_download_start (dc->h,
631                             uri,
632                             meta,
633                             full_name,
634                             0,
635                             GNUNET_FS_uri_chk_get_file_size (uri),
636                             dc->anonymity,
637                             dc->options,
638                             NULL,
639                             dc);
640   GNUNET_free_non_null (full_name);
641   GNUNET_free_non_null (fn);
642 }
643
644
645 /**
646  * We're done downloading a directory.  Open the file and
647  * trigger all of the (remaining) child downloads.
648  *
649  * @param dc context of download that just completed
650  */
651 static void
652 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
653 {
654   size_t size;
655   uint64_t size64;
656   void *data;
657   struct GNUNET_DISK_FileHandle *h;
658   struct GNUNET_DISK_MapHandle *m;
659   
660   size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
661   size = (size_t) size64;
662   if (size64 != (uint64_t) size)
663     {
664       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
665                   _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
666       return;
667     }
668   if (dc->filename != NULL)
669     {
670       h = GNUNET_DISK_file_open (dc->filename,
671                                  GNUNET_DISK_OPEN_READ,
672                                  GNUNET_DISK_PERM_NONE);
673     }
674   else
675     {
676       /* FIXME: need to initialize (and use) temp_filename
677          in various places in order for this assertion to
678          not fail; right now, it will always fail! */
679       GNUNET_assert (dc->temp_filename != NULL);
680       h = GNUNET_DISK_file_open (dc->temp_filename,
681                                  GNUNET_DISK_OPEN_READ,
682                                  GNUNET_DISK_PERM_NONE);
683     }
684   if (h == NULL)
685     return; /* oops */
686   data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
687   if (data == NULL)
688     {
689       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
690                   _("Directory too large for system address space\n"));
691     }
692   else
693     {
694       GNUNET_FS_directory_list_contents (size,
695                                          data,
696                                          0,
697                                          &trigger_recursive_download,
698                                          dc);         
699       GNUNET_DISK_file_unmap (m);
700     }
701   GNUNET_DISK_file_close (h);
702   if (dc->filename == NULL)
703     {
704       if (0 != UNLINK (dc->temp_filename))
705         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
706                                   "unlink",
707                                   dc->temp_filename);
708       GNUNET_free (dc->temp_filename);
709       dc->temp_filename = NULL;
710     }
711 }
712
713
714 /**
715  * Iterator over entries in the pending requests in the 'active' map for the
716  * reply that we just got.
717  *
718  * @param cls closure (our 'struct ProcessResultClosure')
719  * @param key query for the given value / request
720  * @param value value in the hash map (a 'struct DownloadRequest')
721  * @return GNUNET_YES (we should continue to iterate); unless serious error
722  */
723 static int
724 process_result_with_request (void *cls,
725                              const GNUNET_HashCode * key,
726                              void *value)
727 {
728   struct ProcessResultClosure *prc = cls;
729   struct DownloadRequest *sm = value;
730   struct GNUNET_FS_DownloadContext *dc = prc->dc;
731   struct GNUNET_CRYPTO_AesSessionKey skey;
732   struct GNUNET_CRYPTO_AesInitializationVector iv;
733   char pt[prc->size];
734   struct GNUNET_FS_ProgressInfo pi;
735   uint64_t off;
736   size_t app;
737   int i;
738   struct ContentHashKey *chk;
739   char *emsg;
740
741   if (prc->size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
742                                          dc->treedepth,
743                                          sm->offset,
744                                          sm->depth))
745     {
746 #if DEBUG_DOWNLOAD
747       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
749                   calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
750                                         dc->treedepth,
751                                         sm->offset,
752                                         sm->depth),
753                   prc->size);
754 #endif
755       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
756       /* signal error */
757       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
758       make_download_status (&pi, dc);
759       pi.value.download.specifics.error.message = dc->emsg;
760       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
761                                      &pi);
762       /* abort all pending requests */
763       if (NULL != dc->th)
764         {
765           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
766           dc->th = NULL;
767         }
768       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
769       dc->client = NULL;
770       return GNUNET_NO;
771     }
772   GNUNET_assert (GNUNET_YES ==
773                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
774                                                        &prc->query,
775                                                        sm));
776   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
777   GNUNET_CRYPTO_aes_decrypt (prc->data,
778                              prc->size,
779                              &skey,
780                              &iv,
781                              pt);
782   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
783                              sm->offset,
784                              sm->depth,
785                              dc->treedepth);
786   /* save to disk */
787   if ( (NULL != dc->handle) &&
788        ( (sm->depth == dc->treedepth) ||
789          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
790     {
791       emsg = NULL;
792 #if DEBUG_DOWNLOAD
793       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
794                   "Saving decrypted block to disk at offset %llu\n",
795                   (unsigned long long) off);
796 #endif
797       if ( (off  != 
798             GNUNET_DISK_file_seek (dc->handle,
799                                    off,
800                                    GNUNET_DISK_SEEK_SET) ) )
801         GNUNET_asprintf (&emsg,
802                          _("Failed to seek to offset %llu in file `%s': %s\n"),
803                          (unsigned long long) off,
804                          dc->filename,
805                          STRERROR (errno));
806       else if (prc->size !=
807                GNUNET_DISK_file_write (dc->handle,
808                                        pt,
809                                        prc->size))
810         GNUNET_asprintf (&emsg,
811                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
812                          (unsigned int) prc->size,
813                          (unsigned long long) off,
814                          dc->filename,
815                          STRERROR (errno));
816       if (NULL != emsg)
817         {
818           dc->emsg = emsg;
819           // FIXME: make persistent
820
821           /* signal error */
822           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
823           make_download_status (&pi, dc);
824           pi.value.download.specifics.error.message = emsg;
825           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
826                                          &pi);
827
828           /* abort all pending requests */
829           if (NULL != dc->th)
830             {
831               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
832               dc->th = NULL;
833             }
834           GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
835           dc->client = NULL;
836           GNUNET_free (sm);
837           return GNUNET_NO;
838         }
839     }
840   if (sm->depth == dc->treedepth) 
841     {
842       app = prc->size;
843       if (sm->offset < dc->offset)
844         {
845           /* starting offset begins in the middle of pt,
846              do not count first bytes as progress */
847           GNUNET_assert (app > (dc->offset - sm->offset));
848           app -= (dc->offset - sm->offset);       
849         }
850       if (sm->offset + prc->size > dc->offset + dc->length)
851         {
852           /* end of block is after relevant range,
853              do not count last bytes as progress */
854           GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
855           app -= (sm->offset + prc->size) - (dc->offset + dc->length);
856         }
857       dc->completed += app;
858
859       /* do recursive download if option is set and either meta data
860          says it is a directory or if no meta data is given AND filename 
861          ends in '.gnd' (top-level case) */
862       if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
863            ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
864              ( (dc->meta == NULL) &&
865                ( (NULL == dc->filename) ||             
866                  ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
867                    (NULL !=
868                     strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
869                             GNUNET_FS_DIRECTORY_EXT)) ) ) ) ) )
870         {
871           GNUNET_FS_directory_list_contents (prc->size,
872                                              pt,
873                                              off,
874                                              &trigger_recursive_download,
875                                              dc);         
876         }
877
878     }
879
880   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
881   make_download_status (&pi, dc);
882   pi.value.download.specifics.progress.data = pt;
883   pi.value.download.specifics.progress.offset = sm->offset;
884   pi.value.download.specifics.progress.data_len = prc->size;
885   pi.value.download.specifics.progress.depth = sm->depth;
886   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
887                                  &pi);
888   GNUNET_assert (dc->completed <= dc->length);
889   if (dc->completed == dc->length)
890     {
891 #if DEBUG_DOWNLOAD
892       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
893                   "Download completed, truncating file to desired length %llu\n",
894                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
895 #endif
896       /* truncate file to size (since we store IBlocks at the end) */
897       if (dc->handle != NULL)
898         {
899           GNUNET_DISK_file_close (dc->handle);
900           dc->handle = NULL;
901           if (0 != truncate (dc->filename,
902                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
903             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
904                                       "truncate",
905                                       dc->filename);
906         }
907
908       if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
909            (GNUNET_NO != GNUNET_FS_meta_data_test_for_directory (dc->meta)) )
910         full_recursive_download (dc);
911       if (dc->child_head == NULL)
912         {
913           /* signal completion */
914           pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
915           make_download_status (&pi, dc);
916           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
917                                          &pi);
918         }
919       GNUNET_assert (sm->depth == dc->treedepth);
920     }
921   // FIXME: make persistent
922   if (sm->depth == dc->treedepth) 
923     {
924       GNUNET_free (sm);      
925       return GNUNET_YES;
926     }
927 #if DEBUG_DOWNLOAD
928   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
929               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
930               sm->depth,
931               (unsigned long long) sm->offset);
932 #endif
933   GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
934   chk = (struct ContentHashKey*) pt;
935   for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
936     {
937       off = compute_dblock_offset (sm->offset,
938                                    sm->depth,
939                                    dc->treedepth,
940                                    i);
941       if ( (off + DBLOCK_SIZE >= dc->offset) &&
942            (off < dc->offset + dc->length) ) 
943         schedule_block_download (dc,
944                                  &chk[i],
945                                  off,
946                                  sm->depth + 1);
947     }
948   GNUNET_free (sm);
949   return GNUNET_YES;
950 }
951
952
953 /**
954  * Process a download result.
955  *
956  * @param dc our download context
957  * @param type type of the result
958  * @param data the (encrypted) response
959  * @param size size of data
960  */
961 static void
962 process_result (struct GNUNET_FS_DownloadContext *dc,
963                 uint32_t type,
964                 const void *data,
965                 size_t size)
966 {
967   struct ProcessResultClosure prc;
968
969   prc.dc = dc;
970   prc.data = data;
971   prc.size = size;
972   prc.type = type;
973   GNUNET_CRYPTO_hash (data, size, &prc.query);
974 #if DEBUG_DOWNLOAD
975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
976               "Received result for query `%s' from `%s'-service\n",
977               GNUNET_h2s (&prc.query),
978               "FS");
979 #endif
980   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
981                                               &prc.query,
982                                               &process_result_with_request,
983                                               &prc);
984 }
985
986
987 /**
988  * Type of a function to call when we receive a message
989  * from the service.
990  *
991  * @param cls closure
992  * @param msg message received, NULL on timeout or fatal error
993  */
994 static void 
995 receive_results (void *cls,
996                  const struct GNUNET_MessageHeader * msg)
997 {
998   struct GNUNET_FS_DownloadContext *dc = cls;
999   const struct PutMessage *cm;
1000   uint16_t msize;
1001
1002   if ( (NULL == msg) ||
1003        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1004        (sizeof (struct PutMessage) > ntohs(msg->size)) )
1005     {
1006       GNUNET_break (msg == NULL);       
1007       try_reconnect (dc);
1008       return;
1009     }
1010   msize = ntohs(msg->size);
1011   cm = (const struct PutMessage*) msg;
1012   process_result (dc, 
1013                   ntohl (cm->type),
1014                   &cm[1],
1015                   msize - sizeof (struct PutMessage));
1016   if (dc->client == NULL)
1017     return; /* fatal error */
1018   /* continue receiving */
1019   GNUNET_CLIENT_receive (dc->client,
1020                          &receive_results,
1021                          dc,
1022                          GNUNET_TIME_UNIT_FOREVER_REL);
1023 }
1024
1025
1026
1027 /**
1028  * We're ready to transmit a search request to the
1029  * file-sharing service.  Do it.  If there is 
1030  * more than one request pending, try to send 
1031  * multiple or request another transmission.
1032  *
1033  * @param cls closure
1034  * @param size number of bytes available in buf
1035  * @param buf where the callee should write the message
1036  * @return number of bytes written to buf
1037  */
1038 static size_t
1039 transmit_download_request (void *cls,
1040                            size_t size, 
1041                            void *buf)
1042 {
1043   struct GNUNET_FS_DownloadContext *dc = cls;
1044   size_t msize;
1045   struct SearchMessage *sm;
1046
1047   dc->th = NULL;
1048   if (NULL == buf)
1049     {
1050       try_reconnect (dc);
1051       return 0;
1052     }
1053   GNUNET_assert (size >= sizeof (struct SearchMessage));
1054   msize = 0;
1055   sm = buf;
1056   while ( (dc->pending != NULL) &&
1057           (size > msize + sizeof (struct SearchMessage)) )
1058     {
1059 #if DEBUG_DOWNLOAD
1060       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061                   "Transmitting download request for `%s' to `%s'-service\n",
1062                   GNUNET_h2s (&dc->pending->chk.query),
1063                   "FS");
1064 #endif
1065       memset (sm, 0, sizeof (struct SearchMessage));
1066       sm->header.size = htons (sizeof (struct SearchMessage));
1067       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1068       if (dc->pending->depth == dc->treedepth)
1069         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
1070       else
1071         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
1072       sm->anonymity_level = htonl (dc->anonymity);
1073       sm->target = dc->target.hashPubKey;
1074       sm->query = dc->pending->chk.query;
1075       dc->pending->is_pending = GNUNET_NO;
1076       dc->pending = dc->pending->next;
1077       msize += sizeof (struct SearchMessage);
1078       sm++;
1079     }
1080   if (dc->pending != NULL)
1081     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1082                                                   sizeof (struct SearchMessage),
1083                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1084                                                   GNUNET_NO,
1085                                                   &transmit_download_request,
1086                                                   dc); 
1087   return msize;
1088 }
1089
1090
1091 /**
1092  * Reconnect to the FS service and transmit our queries NOW.
1093  *
1094  * @param cls our download context
1095  * @param tc unused
1096  */
1097 static void
1098 do_reconnect (void *cls,
1099               const struct GNUNET_SCHEDULER_TaskContext *tc)
1100 {
1101   struct GNUNET_FS_DownloadContext *dc = cls;
1102   struct GNUNET_CLIENT_Connection *client;
1103   
1104   dc->task = GNUNET_SCHEDULER_NO_TASK;
1105   client = GNUNET_CLIENT_connect (dc->h->sched,
1106                                   "fs",
1107                                   dc->h->cfg);
1108   if (NULL == client)
1109     {
1110       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1111                   "Connecting to `%s'-service failed, will try again.\n",
1112                   "FS");
1113       try_reconnect (dc);
1114       return;
1115     }
1116   dc->client = client;
1117   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1118                                                 sizeof (struct SearchMessage),
1119                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1120                                                 GNUNET_NO,
1121                                                 &transmit_download_request,
1122                                                 dc);  
1123   GNUNET_CLIENT_receive (client,
1124                          &receive_results,
1125                          dc,
1126                          GNUNET_TIME_UNIT_FOREVER_REL);
1127 }
1128
1129
1130 /**
1131  * Add entries that are not yet pending back to the pending list.
1132  *
1133  * @param cls our download context
1134  * @param key unused
1135  * @param entry entry of type "struct DownloadRequest"
1136  * @return GNUNET_OK
1137  */
1138 static int
1139 retry_entry (void *cls,
1140              const GNUNET_HashCode *key,
1141              void *entry)
1142 {
1143   struct GNUNET_FS_DownloadContext *dc = cls;
1144   struct DownloadRequest *dr = entry;
1145
1146   if (! dr->is_pending)
1147     {
1148       dr->next = dc->pending;
1149       dr->is_pending = GNUNET_YES;
1150       dc->pending = entry;
1151     }
1152   return GNUNET_OK;
1153 }
1154
1155
1156 /**
1157  * We've lost our connection with the FS service.
1158  * Re-establish it and re-transmit all of our
1159  * pending requests.
1160  *
1161  * @param dc download context that is having trouble
1162  */
1163 static void
1164 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1165 {
1166   
1167   if (NULL != dc->client)
1168     {
1169       if (NULL != dc->th)
1170         {
1171           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1172           dc->th = NULL;
1173         }
1174       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1175                                              &retry_entry,
1176                                              dc);
1177       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1178       dc->client = NULL;
1179     }
1180   dc->task
1181     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1182                                     GNUNET_TIME_UNIT_SECONDS,
1183                                     &do_reconnect,
1184                                     dc);
1185 }
1186
1187
1188 /**
1189  * Download parts of a file.  Note that this will store
1190  * the blocks at the respective offset in the given file.  Also, the
1191  * download is still using the blocking of the underlying FS
1192  * encoding.  As a result, the download may *write* outside of the
1193  * given boundaries (if offset and length do not match the 32k FS
1194  * block boundaries). <p>
1195  *
1196  * This function should be used to focus a download towards a
1197  * particular portion of the file (optimization), not to strictly
1198  * limit the download to exactly those bytes.
1199  *
1200  * @param h handle to the file sharing subsystem
1201  * @param uri the URI of the file (determines what to download); CHK or LOC URI
1202  * @param meta known metadata for the file (can be NULL)
1203  * @param filename where to store the file, maybe NULL (then no file is
1204  *        created on disk and data must be grabbed from the callbacks)
1205  * @param offset at what offset should we start the download (typically 0)
1206  * @param length how many bytes should be downloaded starting at offset
1207  * @param anonymity anonymity level to use for the download
1208  * @param options various options
1209  * @param cctx initial value for the client context for this download
1210  * @param parent parent download to associate this download with (use NULL
1211  *        for top-level downloads; useful for manually-triggered recursive downloads)
1212  * @return context that can be used to control this download
1213  */
1214 struct GNUNET_FS_DownloadContext *
1215 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1216                           const struct GNUNET_FS_Uri *uri,
1217                           const struct GNUNET_CONTAINER_MetaData *meta,
1218                           const char *filename,
1219                           uint64_t offset,
1220                           uint64_t length,
1221                           uint32_t anonymity,
1222                           enum GNUNET_FS_DownloadOptions options,
1223                           void *cctx,
1224                           struct GNUNET_FS_DownloadContext *parent)
1225 {
1226   struct GNUNET_FS_ProgressInfo pi;
1227   struct GNUNET_FS_DownloadContext *dc;
1228   struct GNUNET_CLIENT_Connection *client;
1229
1230   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1231   if ( (offset + length < offset) ||
1232        (offset + length > uri->data.chk.file_length) )
1233     {      
1234       GNUNET_break (0);
1235       return NULL;
1236     }
1237   // FIXME: add support for "loc" URIs!
1238 #if DEBUG_DOWNLOAD
1239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1240               "Starting download `%s' of %llu bytes\n",
1241               filename,
1242               (unsigned long long) length);
1243 #endif
1244   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1245   dc->h = h;
1246   dc->parent = parent;
1247   if (parent != NULL)
1248     {
1249       GNUNET_CONTAINER_DLL_insert (parent->child_head,
1250                                    parent->child_tail,
1251                                    dc);
1252     }
1253   dc->uri = GNUNET_FS_uri_dup (uri);
1254   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1255   dc->client_info = cctx;
1256   dc->start_time = GNUNET_TIME_absolute_get ();
1257   if (NULL != filename)
1258     {
1259       dc->filename = GNUNET_strdup (filename);
1260       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1261         GNUNET_DISK_file_size (filename,
1262                                &dc->old_file_size,
1263                                GNUNET_YES);
1264       dc->handle = GNUNET_DISK_file_open (filename, 
1265                                           GNUNET_DISK_OPEN_READWRITE | 
1266                                           GNUNET_DISK_OPEN_CREATE,
1267                                           GNUNET_DISK_PERM_USER_READ |
1268                                           GNUNET_DISK_PERM_USER_WRITE |
1269                                           GNUNET_DISK_PERM_GROUP_READ |
1270                                           GNUNET_DISK_PERM_OTHER_READ);
1271       if (dc->handle == NULL)
1272         {
1273           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1274                       _("Download failed: could not open file `%s': %s\n"),
1275                       dc->filename,
1276                       STRERROR (errno));
1277           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1278           GNUNET_FS_uri_destroy (dc->uri);
1279           GNUNET_free (dc->filename);
1280           GNUNET_free (dc);
1281           return NULL;
1282         }
1283     }
1284   // FIXME: set "dc->target" for LOC uris!
1285   dc->offset = offset;
1286   dc->length = length;
1287   dc->anonymity = anonymity;
1288   dc->options = options;
1289   dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
1290   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1291 #if DEBUG_DOWNLOAD
1292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1293               "Download tree has depth %u\n",
1294               dc->treedepth);
1295 #endif
1296   // FIXME: make persistent
1297   
1298   // FIXME: bound parallelism here!
1299   client = GNUNET_CLIENT_connect (h->sched,
1300                                   "fs",
1301                                   h->cfg);
1302   dc->client = client;
1303   schedule_block_download (dc, 
1304                            &dc->uri->data.chk.chk,
1305                            0, 
1306                            1 /* 0 == CHK, 1 == top */);
1307   GNUNET_CLIENT_receive (client,
1308                          &receive_results,
1309                          dc,
1310                          GNUNET_TIME_UNIT_FOREVER_REL);
1311   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1312   make_download_status (&pi, dc);
1313   pi.value.download.specifics.start.meta = meta;
1314   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1315                                  &pi);
1316
1317   return dc;
1318 }
1319
1320
1321 /**
1322  * Free entries in the map.
1323  *
1324  * @param cls unused (NULL)
1325  * @param key unused
1326  * @param entry entry of type "struct DownloadRequest" which is freed
1327  * @return GNUNET_OK
1328  */
1329 static int
1330 free_entry (void *cls,
1331             const GNUNET_HashCode *key,
1332             void *entry)
1333 {
1334   GNUNET_free (entry);
1335   return GNUNET_OK;
1336 }
1337
1338
1339 /**
1340  * Stop a download (aborts if download is incomplete).
1341  *
1342  * @param dc handle for the download
1343  * @param do_delete delete files of incomplete downloads
1344  */
1345 void
1346 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1347                          int do_delete)
1348 {
1349   struct GNUNET_FS_ProgressInfo pi;
1350
1351   while (NULL != dc->child_head)
1352     GNUNET_FS_download_stop (dc->child_head, 
1353                              do_delete);
1354   // FIXME: make unpersistent  
1355   if (dc->parent != NULL)
1356     GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1357                                  dc->parent->child_tail,
1358                                  dc);
1359   
1360   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1361   make_download_status (&pi, dc);
1362   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1363                                  &pi);
1364
1365   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1366     GNUNET_SCHEDULER_cancel (dc->h->sched,
1367                              dc->task);
1368   if (NULL != dc->th)
1369     {
1370       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1371       dc->th = NULL;
1372     }
1373   if (NULL != dc->client)
1374     GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1375   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1376                                          &free_entry,
1377                                          NULL);
1378   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1379   if (dc->filename != NULL)
1380     {
1381       if (NULL != dc->handle)
1382         GNUNET_DISK_file_close (dc->handle);
1383       if ( (dc->completed != dc->length) &&
1384            (GNUNET_YES == do_delete) )
1385         {
1386           if (0 != UNLINK (dc->filename))
1387             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1388                                       "unlink",
1389                                       dc->filename);
1390         }
1391       GNUNET_free (dc->filename);
1392     }
1393   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1394   GNUNET_FS_uri_destroy (dc->uri);
1395   GNUNET_free (dc);
1396 }
1397
1398 /* end of fs_download.c */