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