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