added option to restrict search to local-only
[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       if (0 == memcmp (&key,
317                        &chk->key,
318                        sizeof (GNUNET_HashCode)))
319         {
320           char enc[len];
321           struct GNUNET_CRYPTO_AesSessionKey sk;
322           struct GNUNET_CRYPTO_AesInitializationVector iv;
323           GNUNET_HashCode query;
324
325           GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
326           GNUNET_CRYPTO_aes_encrypt (block, len,
327                                      &sk,
328                                      &iv,
329                                      enc);
330           GNUNET_CRYPTO_hash (enc, len, &query);
331           if (0 == memcmp (&query,
332                            &chk->query,
333                            sizeof (GNUNET_HashCode)))
334             {
335               /* already got it! */
336               prc.dc = dc;
337               prc.data = enc;
338               prc.size = len;
339               prc.type = (dc->treedepth == depth) 
340                 ? GNUNET_BLOCK_TYPE_DBLOCK 
341                 : GNUNET_BLOCK_TYPE_IBLOCK;
342               prc.query = chk->query;
343               prc.do_store = GNUNET_NO; /* useless */
344               process_result_with_request (&prc,
345                                            &key,
346                                            sm);
347             }
348           else
349             {
350               GNUNET_break_op (0);
351             }
352           return;
353         }
354     }
355   if (depth < dc->treedepth)
356     {
357       // FIXME: try if we could
358       // reconstitute this IBLOCK
359       // from the existing blocks on disk (can wait)
360       // (read block(s), encode, compare with
361       // query; if matches, simply return)
362     }
363
364   if ( (dc->th == NULL) &&
365        (dc->client != NULL) )
366     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
367                                                   sizeof (struct SearchMessage),
368                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
369                                                   GNUNET_NO,
370                                                   &transmit_download_request,
371                                                   dc);
372 }
373
374
375
376 /**
377  * Suggest a filename based on given metadata.
378  * 
379  * @param md given meta data
380  * @return NULL if meta data is useless for suggesting a filename
381  */
382 char *
383 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
384 {
385   static const char *mimeMap[][2] = {
386     {"application/bz2", ".bz2"},
387     {"application/gnunet-directory", ".gnd"},
388     {"application/java", ".class"},
389     {"application/msword", ".doc"},
390     {"application/ogg", ".ogg"},
391     {"application/pdf", ".pdf"},
392     {"application/pgp-keys", ".key"},
393     {"application/pgp-signature", ".pgp"},
394     {"application/postscript", ".ps"},
395     {"application/rar", ".rar"},
396     {"application/rtf", ".rtf"},
397     {"application/xml", ".xml"},
398     {"application/x-debian-package", ".deb"},
399     {"application/x-dvi", ".dvi"},
400     {"applixation/x-flac", ".flac"},
401     {"applixation/x-gzip", ".gz"},
402     {"application/x-java-archive", ".jar"},
403     {"application/x-java-vm", ".class"},
404     {"application/x-python-code", ".pyc"},
405     {"application/x-redhat-package-manager", ".rpm"},
406     {"application/x-rpm", ".rpm"},
407     {"application/x-tar", ".tar"},
408     {"application/x-tex-pk", ".pk"},
409     {"application/x-texinfo", ".texinfo"},
410     {"application/x-xcf", ".xcf"},
411     {"application/x-xfig", ".xfig"},
412     {"application/zip", ".zip"},
413     
414     {"audio/midi", ".midi"},
415     {"audio/mpeg", ".mp3"},
416     {"audio/real", ".rm"},
417     {"audio/x-wav", ".wav"},
418     
419     {"image/gif", ".gif"},
420     {"image/jpeg", ".jpg"},
421     {"image/pcx", ".pcx"},
422     {"image/png", ".png"},
423     {"image/tiff", ".tiff"},
424     {"image/x-ms-bmp", ".bmp"},
425     {"image/x-xpixmap", ".xpm"},
426     
427     {"text/css", ".css"},
428     {"text/html", ".html"},
429     {"text/plain", ".txt"},
430     {"text/rtf", ".rtf"},
431     {"text/x-c++hdr", ".h++"},
432     {"text/x-c++src", ".c++"},
433     {"text/x-chdr", ".h"},
434     {"text/x-csrc", ".c"},
435     {"text/x-java", ".java"},
436     {"text/x-moc", ".moc"},
437     {"text/x-pascal", ".pas"},
438     {"text/x-perl", ".pl"},
439     {"text/x-python", ".py"},
440     {"text/x-tex", ".tex"},
441     
442     {"video/avi", ".avi"},
443     {"video/mpeg", ".mpeg"},
444     {"video/quicktime", ".qt"},
445     {"video/real", ".rm"},
446     {"video/x-msvideo", ".avi"},
447     {NULL, NULL},
448   };
449   char *ret;
450   unsigned int i;
451   char *mime;
452   char *base;
453   const char *ext;
454
455   ret = GNUNET_CONTAINER_meta_data_get_by_type (md,
456                                                 EXTRACTOR_METATYPE_FILENAME);
457   if (ret != NULL)
458     return ret;  
459   ext = NULL;
460   mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
461                                                  EXTRACTOR_METATYPE_MIMETYPE);
462   if (mime != NULL)
463     {
464       i = 0;
465       while ( (mimeMap[i][0] != NULL) && 
466               (0 != strcmp (mime, mimeMap[i][0])))
467         i++;
468       if (mimeMap[i][1] == NULL)
469         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | 
470                     GNUNET_ERROR_TYPE_BULK,
471                     _("Did not find mime type `%s' in extension list.\n"),
472                     mime);
473       else
474         ext = mimeMap[i][1];
475       GNUNET_free (mime);
476     }
477   base = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
478                                                         EXTRACTOR_METATYPE_TITLE,
479                                                         EXTRACTOR_METATYPE_BOOK_TITLE,
480                                                         EXTRACTOR_METATYPE_ORIGINAL_TITLE,
481                                                         EXTRACTOR_METATYPE_PACKAGE_NAME,
482                                                         EXTRACTOR_METATYPE_URL,
483                                                         EXTRACTOR_METATYPE_URI, 
484                                                         EXTRACTOR_METATYPE_DESCRIPTION,
485                                                         EXTRACTOR_METATYPE_ISRC,
486                                                         EXTRACTOR_METATYPE_JOURNAL_NAME,
487                                                         EXTRACTOR_METATYPE_AUTHOR_NAME,
488                                                         EXTRACTOR_METATYPE_SUBJECT,
489                                                         EXTRACTOR_METATYPE_ALBUM,
490                                                         EXTRACTOR_METATYPE_ARTIST,
491                                                         EXTRACTOR_METATYPE_KEYWORDS,
492                                                         EXTRACTOR_METATYPE_COMMENT,
493                                                         EXTRACTOR_METATYPE_UNKNOWN,
494                                                         -1);
495   if ( (base == NULL) &&
496        (ext == NULL) )
497     return NULL;
498   if (base == NULL)
499     return GNUNET_strdup (ext);
500   if (ext == NULL)
501     return base;
502   GNUNET_asprintf (&ret,
503                    "%s%s",
504                    base,
505                    ext);
506   GNUNET_free (base);
507   return ret;
508 }
509
510
511 /**
512  * We've lost our connection with the FS service.
513  * Re-establish it and re-transmit all of our
514  * pending requests.
515  *
516  * @param dc download context that is having trouble
517  */
518 static void
519 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
520
521
522 /**
523  * We found an entry in a directory.  Check if the respective child
524  * already exists and if not create the respective child download.
525  *
526  * @param cls the parent download
527  * @param filename name of the file in the directory
528  * @param uri URI of the file (CHK or LOC)
529  * @param meta meta data of the file
530  * @param length number of bytes in data
531  * @param data contents of the file (or NULL if they were not inlined)
532  */
533 static void 
534 trigger_recursive_download (void *cls,
535                             const char *filename,
536                             const struct GNUNET_FS_Uri *uri,
537                             const struct GNUNET_CONTAINER_MetaData *meta,
538                             size_t length,
539                             const void *data);
540
541
542 /**
543  * We're done downloading a directory.  Open the file and
544  * trigger all of the (remaining) child downloads.
545  *
546  * @param dc context of download that just completed
547  */
548 static void
549 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
550 {
551   size_t size;
552   uint64_t size64;
553   void *data;
554   struct GNUNET_DISK_FileHandle *h;
555   struct GNUNET_DISK_MapHandle *m;
556   
557   size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
558   size = (size_t) size64;
559   if (size64 != (uint64_t) size)
560     {
561       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
562                   _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
563       return;
564     }
565   if (dc->filename != NULL)
566     {
567       h = GNUNET_DISK_file_open (dc->filename,
568                                  GNUNET_DISK_OPEN_READ,
569                                  GNUNET_DISK_PERM_NONE);
570     }
571   else
572     {
573       GNUNET_assert (dc->temp_filename != NULL);
574       h = GNUNET_DISK_file_open (dc->temp_filename,
575                                  GNUNET_DISK_OPEN_READ,
576                                  GNUNET_DISK_PERM_NONE);
577     }
578   if (h == NULL)
579     return; /* oops */
580   data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
581   if (data == NULL)
582     {
583       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
584                   _("Directory too large for system address space\n"));
585     }
586   else
587     {
588       GNUNET_FS_directory_list_contents (size,
589                                          data,
590                                          0,
591                                          &trigger_recursive_download,
592                                          dc);         
593       GNUNET_DISK_file_unmap (m);
594     }
595   GNUNET_DISK_file_close (h);
596   if (dc->filename == NULL)
597     {
598       if (0 != UNLINK (dc->temp_filename))
599         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
600                                   "unlink",
601                                   dc->temp_filename);
602       GNUNET_free (dc->temp_filename);
603       dc->temp_filename = NULL;
604     }
605 }
606
607
608 /**
609  * Check if all child-downloads have completed and
610  * if so, signal completion (and possibly recurse to
611  * parent).
612  */
613 static void
614 check_completed (struct GNUNET_FS_DownloadContext *dc)
615 {
616   struct GNUNET_FS_ProgressInfo pi;
617   struct GNUNET_FS_DownloadContext *pos;
618
619   pos = dc->child_head;
620   while (pos != NULL)
621     {
622       if ( (pos->emsg == NULL) &&
623            (pos->completed < pos->length) )
624         return; /* not done yet */
625       if ( (pos->child_head != NULL) &&
626            (pos->has_finished != GNUNET_YES) )
627         return; /* not transitively done yet */
628       pos = pos->next;
629     }
630   dc->has_finished = GNUNET_YES;
631   /* signal completion */
632   pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
633   make_download_status (&pi, dc);
634   if (dc->parent != NULL)
635     check_completed (dc->parent);  
636 }
637
638
639 /**
640  * We found an entry in a directory.  Check if the respective child
641  * already exists and if not create the respective child download.
642  *
643  * @param cls the parent download
644  * @param filename name of the file in the directory
645  * @param uri URI of the file (CHK or LOC)
646  * @param meta meta data of the file
647  * @param length number of bytes in data
648  * @param data contents of the file (or NULL if they were not inlined)
649  */
650 static void 
651 trigger_recursive_download (void *cls,
652                             const char *filename,
653                             const struct GNUNET_FS_Uri *uri,
654                             const struct GNUNET_CONTAINER_MetaData *meta,
655                             size_t length,
656                             const void *data)
657 {
658   struct GNUNET_FS_DownloadContext *dc = cls;  
659   struct GNUNET_FS_DownloadContext *cpos;
660   struct GNUNET_DISK_FileHandle *fh;
661   char *temp_name;
662   const char *real_name;
663   char *fn;
664   char *us;
665   char *ext;
666   char *dn;
667   char *full_name;
668
669   if (NULL == uri)
670     return; /* entry for the directory itself */
671   cpos = dc->child_head;
672   while (cpos != NULL)
673     {
674       if ( (GNUNET_FS_uri_test_equal (uri,
675                                       cpos->uri)) ||
676            ( (filename != NULL) &&
677              (0 == strcmp (cpos->filename,
678                            filename)) ) )
679         break;  
680       cpos = cpos->next;
681     }
682   if (cpos != NULL)
683     return; /* already exists */
684   fn = NULL;
685   if (NULL == filename)
686     {
687       fn = GNUNET_FS_meta_data_suggest_filename (meta);      
688       if (fn == NULL)
689         {
690           us = GNUNET_FS_uri_to_string (uri);
691           fn = GNUNET_strdup (&us [strlen (GNUNET_FS_URI_PREFIX 
692                                            GNUNET_FS_URI_CHK_INFIX)]);
693           GNUNET_free (us);
694         }
695       else if (fn[0] == '.')
696         {
697           ext = fn;
698           us = GNUNET_FS_uri_to_string (uri);
699           GNUNET_asprintf (&fn,
700                            "%s%s",
701                            &us[strlen (GNUNET_FS_URI_PREFIX 
702                                        GNUNET_FS_URI_CHK_INFIX)], ext);
703           GNUNET_free (ext);
704           GNUNET_free (us);
705         }
706       filename = fn;
707     }
708   if (dc->filename == NULL)
709     {
710       full_name = NULL;
711     }
712   else
713     {
714       dn = GNUNET_strdup (dc->filename);
715       GNUNET_break ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
716                      (NULL !=
717                       strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
718                               GNUNET_FS_DIRECTORY_EXT)) );
719       if ( (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
720            (NULL !=
721             strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
722                     GNUNET_FS_DIRECTORY_EXT)) )      
723         dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';      
724       if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
725            ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
726              (NULL ==
727               strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
728                       GNUNET_FS_DIRECTORY_EXT)) ) )
729         {
730           GNUNET_asprintf (&full_name,
731                            "%s%s%s%s",
732                            dn,
733                            DIR_SEPARATOR_STR,
734                            filename,
735                            GNUNET_FS_DIRECTORY_EXT);
736         }
737       else
738         {
739           GNUNET_asprintf (&full_name,
740                            "%s%s%s",
741                            dn,
742                            DIR_SEPARATOR_STR,
743                            filename);
744         }
745       GNUNET_free (dn);
746     }
747   if ( (full_name != NULL) &&
748        (GNUNET_OK !=
749         GNUNET_DISK_directory_create_for_file (full_name)) )
750     {
751       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
752                   _("Failed to create directory for recursive download of `%s'\n"),
753                   full_name);
754       GNUNET_free (full_name);
755       GNUNET_free_non_null (fn);
756       return;
757     }
758
759   temp_name = NULL;
760   if ( (data != NULL) &&
761        (GNUNET_FS_uri_chk_get_file_size (uri) == length) )
762     {
763       if (full_name == NULL)
764         {
765           temp_name = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp");
766           real_name = temp_name;
767         }
768       else
769         {
770           real_name = full_name;
771         }
772       /* write to disk, then trigger normal download which will instantly progress to completion */
773       fh = GNUNET_DISK_file_open (real_name,
774                                   GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE,
775                                   GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
776       if (fh == NULL)
777         {
778           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
779                                     "open",
780                                     real_name);       
781           GNUNET_free (full_name);
782           GNUNET_free_non_null (fn);
783           return;
784         }
785       if (length != 
786           GNUNET_DISK_file_write (fh,
787                                   data,
788                                   length))
789         {
790           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
791                                     "write",
792                                     full_name);       
793         }
794       GNUNET_DISK_file_close (fh);
795     }
796   GNUNET_FS_download_start (dc->h,
797                             uri,
798                             meta,
799                             full_name, temp_name,
800                             0,
801                             GNUNET_FS_uri_chk_get_file_size (uri),
802                             dc->anonymity,
803                             dc->options,
804                             NULL,
805                             dc);
806   GNUNET_free_non_null (full_name);
807   GNUNET_free_non_null (temp_name);
808   GNUNET_free_non_null (fn);
809 }
810
811
812 /**
813  * Iterator over entries in the pending requests in the 'active' map for the
814  * reply that we just got.
815  *
816  * @param cls closure (our 'struct ProcessResultClosure')
817  * @param key query for the given value / request
818  * @param value value in the hash map (a 'struct DownloadRequest')
819  * @return GNUNET_YES (we should continue to iterate); unless serious error
820  */
821 static int
822 process_result_with_request (void *cls,
823                              const GNUNET_HashCode * key,
824                              void *value)
825 {
826   struct ProcessResultClosure *prc = cls;
827   struct DownloadRequest *sm = value;
828   struct GNUNET_FS_DownloadContext *dc = prc->dc;
829   struct GNUNET_CRYPTO_AesSessionKey skey;
830   struct GNUNET_CRYPTO_AesInitializationVector iv;
831   char pt[prc->size];
832   struct GNUNET_FS_ProgressInfo pi;
833   uint64_t off;
834   size_t bs;
835   size_t app;
836   int i;
837   struct ContentHashKey *chk;
838   char *emsg;
839
840   bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
841                                             dc->treedepth,
842                                             sm->offset,
843                                             sm->depth);
844     if (prc->size != bs)
845     {
846 #if DEBUG_DOWNLOAD
847       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
848                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
849                   bs,
850                   prc->size);
851 #endif
852       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
853       /* signal error */
854       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
855       pi.value.download.specifics.error.message = dc->emsg;
856       make_download_status (&pi, dc);
857       /* abort all pending requests */
858       if (NULL != dc->th)
859         {
860           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
861           dc->th = NULL;
862         }
863       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
864       dc->client = NULL;
865       return GNUNET_NO;
866     }
867   GNUNET_assert (GNUNET_YES ==
868                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
869                                                        &prc->query,
870                                                        sm));
871   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
872   GNUNET_CRYPTO_aes_decrypt (prc->data,
873                              prc->size,
874                              &skey,
875                              &iv,
876                              pt);
877   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
878                              sm->offset,
879                              sm->depth,
880                              dc->treedepth);
881   /* save to disk */
882   if ( ( GNUNET_YES == prc->do_store) &&
883        (NULL != dc->handle) &&
884        ( (sm->depth == dc->treedepth) ||
885          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
886     {
887       emsg = NULL;
888 #if DEBUG_DOWNLOAD
889       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890                   "Saving decrypted block to disk at offset %llu\n",
891                   (unsigned long long) off);
892 #endif
893       if ( (off  != 
894             GNUNET_DISK_file_seek (dc->handle,
895                                    off,
896                                    GNUNET_DISK_SEEK_SET) ) )
897         GNUNET_asprintf (&emsg,
898                          _("Failed to seek to offset %llu in file `%s': %s\n"),
899                          (unsigned long long) off,
900                          dc->filename,
901                          STRERROR (errno));
902       else if (prc->size !=
903                GNUNET_DISK_file_write (dc->handle,
904                                        pt,
905                                        prc->size))
906         GNUNET_asprintf (&emsg,
907                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
908                          (unsigned int) prc->size,
909                          (unsigned long long) off,
910                          dc->filename,
911                          STRERROR (errno));
912       if (NULL != emsg)
913         {
914           dc->emsg = emsg;
915           // FIXME: make persistent
916
917           /* signal error */
918           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
919           pi.value.download.specifics.error.message = emsg;
920           make_download_status (&pi, dc);
921           /* abort all pending requests */
922           if (NULL != dc->th)
923             {
924               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
925               dc->th = NULL;
926             }
927           GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
928           dc->client = NULL;
929           GNUNET_free (sm);
930           return GNUNET_NO;
931         }
932     }
933   if (sm->depth == dc->treedepth) 
934     {
935       app = prc->size;
936       if (sm->offset < dc->offset)
937         {
938           /* starting offset begins in the middle of pt,
939              do not count first bytes as progress */
940           GNUNET_assert (app > (dc->offset - sm->offset));
941           app -= (dc->offset - sm->offset);       
942         }
943       if (sm->offset + prc->size > dc->offset + dc->length)
944         {
945           /* end of block is after relevant range,
946              do not count last bytes as progress */
947           GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
948           app -= (sm->offset + prc->size) - (dc->offset + dc->length);
949         }
950       dc->completed += app;
951
952       /* do recursive download if option is set and either meta data
953          says it is a directory or if no meta data is given AND filename 
954          ends in '.gnd' (top-level case) */
955       if (is_recursive_download (dc))
956         GNUNET_FS_directory_list_contents (prc->size,
957                                            pt,
958                                            off,
959                                            &trigger_recursive_download,
960                                            dc);         
961             
962     }
963   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
964   pi.value.download.specifics.progress.data = pt;
965   pi.value.download.specifics.progress.offset = sm->offset;
966   pi.value.download.specifics.progress.data_len = prc->size;
967   pi.value.download.specifics.progress.depth = sm->depth;
968   make_download_status (&pi, dc);
969   GNUNET_assert (dc->completed <= dc->length);
970   if (dc->completed == dc->length)
971     {
972 #if DEBUG_DOWNLOAD
973       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974                   "Download completed, truncating file to desired length %llu\n",
975                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
976 #endif
977       /* truncate file to size (since we store IBlocks at the end) */
978       if (dc->handle != NULL)
979         {
980           GNUNET_DISK_file_close (dc->handle);
981           dc->handle = NULL;
982           if (0 != truncate (dc->filename,
983                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
984             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
985                                       "truncate",
986                                       dc->filename);
987         }
988       if (dc->job_queue != NULL)
989         {
990           GNUNET_FS_dequeue_ (dc->job_queue);
991           dc->job_queue = NULL;
992         }
993       if (is_recursive_download (dc))
994         full_recursive_download (dc);
995       if (dc->child_head == NULL)
996         {
997           /* signal completion */
998           pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
999           make_download_status (&pi, dc);
1000           if (dc->parent != NULL)
1001             check_completed (dc->parent);
1002         }
1003       GNUNET_assert (sm->depth == dc->treedepth);
1004     }
1005   // FIXME: make persistent
1006   if (sm->depth == dc->treedepth) 
1007     {
1008       GNUNET_free (sm);      
1009       return GNUNET_YES;
1010     }
1011 #if DEBUG_DOWNLOAD
1012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1013               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
1014               sm->depth,
1015               (unsigned long long) sm->offset);
1016 #endif
1017   GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
1018   chk = (struct ContentHashKey*) pt;
1019   for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
1020     {
1021       off = compute_dblock_offset (sm->offset,
1022                                    sm->depth,
1023                                    dc->treedepth,
1024                                    i);
1025       if ( (off + DBLOCK_SIZE >= dc->offset) &&
1026            (off < dc->offset + dc->length) ) 
1027         schedule_block_download (dc,
1028                                  &chk[i],
1029                                  off,
1030                                  sm->depth + 1);
1031     }
1032   GNUNET_free (sm);
1033   return GNUNET_YES;
1034 }
1035
1036
1037 /**
1038  * Process a download result.
1039  *
1040  * @param dc our download context
1041  * @param type type of the result
1042  * @param data the (encrypted) response
1043  * @param size size of data
1044  */
1045 static void
1046 process_result (struct GNUNET_FS_DownloadContext *dc,
1047                 enum GNUNET_BLOCK_Type type,
1048                 const void *data,
1049                 size_t size)
1050 {
1051   struct ProcessResultClosure prc;
1052
1053   prc.dc = dc;
1054   prc.data = data;
1055   prc.size = size;
1056   prc.type = type;
1057   prc.do_store = GNUNET_YES;
1058   GNUNET_CRYPTO_hash (data, size, &prc.query);
1059 #if DEBUG_DOWNLOAD
1060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061               "Received result for query `%s' from `%s'-service\n",
1062               GNUNET_h2s (&prc.query),
1063               "FS");
1064 #endif
1065   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
1066                                               &prc.query,
1067                                               &process_result_with_request,
1068                                               &prc);
1069 }
1070
1071
1072 /**
1073  * Type of a function to call when we receive a message
1074  * from the service.
1075  *
1076  * @param cls closure
1077  * @param msg message received, NULL on timeout or fatal error
1078  */
1079 static void 
1080 receive_results (void *cls,
1081                  const struct GNUNET_MessageHeader * msg)
1082 {
1083   struct GNUNET_FS_DownloadContext *dc = cls;
1084   const struct PutMessage *cm;
1085   uint16_t msize;
1086
1087   if ( (NULL == msg) ||
1088        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
1089        (sizeof (struct PutMessage) > ntohs(msg->size)) )
1090     {
1091       GNUNET_break (msg == NULL);       
1092       try_reconnect (dc);
1093       return;
1094     }
1095   msize = ntohs(msg->size);
1096   cm = (const struct PutMessage*) msg;
1097   process_result (dc, 
1098                   ntohl (cm->type),
1099                   &cm[1],
1100                   msize - sizeof (struct PutMessage));
1101   if (dc->client == NULL)
1102     return; /* fatal error */
1103   /* continue receiving */
1104   GNUNET_CLIENT_receive (dc->client,
1105                          &receive_results,
1106                          dc,
1107                          GNUNET_TIME_UNIT_FOREVER_REL);
1108 }
1109
1110
1111
1112 /**
1113  * We're ready to transmit a search request to the
1114  * file-sharing service.  Do it.  If there is 
1115  * more than one request pending, try to send 
1116  * multiple or request another transmission.
1117  *
1118  * @param cls closure
1119  * @param size number of bytes available in buf
1120  * @param buf where the callee should write the message
1121  * @return number of bytes written to buf
1122  */
1123 static size_t
1124 transmit_download_request (void *cls,
1125                            size_t size, 
1126                            void *buf)
1127 {
1128   struct GNUNET_FS_DownloadContext *dc = cls;
1129   size_t msize;
1130   struct SearchMessage *sm;
1131
1132   dc->th = NULL;
1133   if (NULL == buf)
1134     {
1135       try_reconnect (dc);
1136       return 0;
1137     }
1138   GNUNET_assert (size >= sizeof (struct SearchMessage));
1139   msize = 0;
1140   sm = buf;
1141   while ( (dc->pending != NULL) &&
1142           (size > msize + sizeof (struct SearchMessage)) )
1143     {
1144 #if DEBUG_DOWNLOAD
1145       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1146                   "Transmitting download request for `%s' to `%s'-service\n",
1147                   GNUNET_h2s (&dc->pending->chk.query),
1148                   "FS");
1149 #endif
1150       memset (sm, 0, sizeof (struct SearchMessage));
1151       sm->header.size = htons (sizeof (struct SearchMessage));
1152       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1153       if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY))
1154         sm->options = htonl (1);
1155       else
1156         sm->options = htonl (0);      
1157       if (dc->pending->depth == dc->treedepth)
1158         sm->type = htonl (GNUNET_BLOCK_TYPE_DBLOCK);
1159       else
1160         sm->type = htonl (GNUNET_BLOCK_TYPE_IBLOCK);
1161       sm->anonymity_level = htonl (dc->anonymity);
1162       sm->target = dc->target.hashPubKey;
1163       sm->query = dc->pending->chk.query;
1164       dc->pending->is_pending = GNUNET_NO;
1165       dc->pending = dc->pending->next;
1166       msize += sizeof (struct SearchMessage);
1167       sm++;
1168     }
1169   if (dc->pending != NULL)
1170     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1171                                                   sizeof (struct SearchMessage),
1172                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1173                                                   GNUNET_NO,
1174                                                   &transmit_download_request,
1175                                                   dc); 
1176   return msize;
1177 }
1178
1179
1180 /**
1181  * Reconnect to the FS service and transmit our queries NOW.
1182  *
1183  * @param cls our download context
1184  * @param tc unused
1185  */
1186 static void
1187 do_reconnect (void *cls,
1188               const struct GNUNET_SCHEDULER_TaskContext *tc)
1189 {
1190   struct GNUNET_FS_DownloadContext *dc = cls;
1191   struct GNUNET_CLIENT_Connection *client;
1192   
1193   dc->task = GNUNET_SCHEDULER_NO_TASK;
1194   client = GNUNET_CLIENT_connect (dc->h->sched,
1195                                   "fs",
1196                                   dc->h->cfg);
1197   if (NULL == client)
1198     {
1199       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1200                   "Connecting to `%s'-service failed, will try again.\n",
1201                   "FS");
1202       try_reconnect (dc);
1203       return;
1204     }
1205   dc->client = client;
1206   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
1207                                                 sizeof (struct SearchMessage),
1208                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1209                                                 GNUNET_NO,
1210                                                 &transmit_download_request,
1211                                                 dc);  
1212   GNUNET_CLIENT_receive (client,
1213                          &receive_results,
1214                          dc,
1215                          GNUNET_TIME_UNIT_FOREVER_REL);
1216 }
1217
1218
1219 /**
1220  * Add entries that are not yet pending back to the pending list.
1221  *
1222  * @param cls our download context
1223  * @param key unused
1224  * @param entry entry of type "struct DownloadRequest"
1225  * @return GNUNET_OK
1226  */
1227 static int
1228 retry_entry (void *cls,
1229              const GNUNET_HashCode *key,
1230              void *entry)
1231 {
1232   struct GNUNET_FS_DownloadContext *dc = cls;
1233   struct DownloadRequest *dr = entry;
1234
1235   if (! dr->is_pending)
1236     {
1237       dr->next = dc->pending;
1238       dr->is_pending = GNUNET_YES;
1239       dc->pending = entry;
1240     }
1241   return GNUNET_OK;
1242 }
1243
1244
1245 /**
1246  * We've lost our connection with the FS service.
1247  * Re-establish it and re-transmit all of our
1248  * pending requests.
1249  *
1250  * @param dc download context that is having trouble
1251  */
1252 static void
1253 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1254 {
1255   
1256   if (NULL != dc->client)
1257     {
1258       if (NULL != dc->th)
1259         {
1260           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1261           dc->th = NULL;
1262         }
1263       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1264                                              &retry_entry,
1265                                              dc);
1266       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1267       dc->client = NULL;
1268     }
1269   dc->task
1270     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1271                                     GNUNET_TIME_UNIT_SECONDS,
1272                                     &do_reconnect,
1273                                     dc);
1274 }
1275
1276
1277
1278 /**
1279  * We're allowed to ask the FS service for our blocks.  Start the download.
1280  *
1281  * @param cls the 'struct GNUNET_FS_DownloadContext'
1282  * @param client handle to use for communcation with FS (we must destroy it!)
1283  */
1284 static void
1285 activate_fs_download (void *cls,
1286                       struct GNUNET_CLIENT_Connection *client)
1287 {
1288   struct GNUNET_FS_DownloadContext *dc = cls;
1289   struct GNUNET_FS_ProgressInfo pi;
1290
1291   GNUNET_assert (NULL != client);
1292   dc->client = client;
1293   GNUNET_CLIENT_receive (client,
1294                          &receive_results,
1295                          dc,
1296                          GNUNET_TIME_UNIT_FOREVER_REL);
1297   pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE;
1298   make_download_status (&pi, dc);
1299   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1300                                          &retry_entry,
1301                                          dc);
1302   if ( (dc->th == NULL) &&
1303        (dc->client != NULL) )
1304     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
1305                                                   sizeof (struct SearchMessage),
1306                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1307                                                   GNUNET_NO,
1308                                                   &transmit_download_request,
1309                                                   dc);
1310 }
1311
1312
1313 /**
1314  * We must stop to ask the FS service for our blocks.  Pause the download.
1315  *
1316  * @param cls the 'struct GNUNET_FS_DownloadContext'
1317  * @param client handle to use for communcation with FS (we must destroy it!)
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 */