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