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