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