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