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