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