fix
[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  * - handle recursive downloads (need directory & 
27  *   fs-level download-parallelism management)
28  * - handle recursive downloads where directory file is
29  *   NOT saved on disk (need temporary file instead then!)
30  * - location URI suppport (can wait, easy)
31  * - check if blocks exist already (can wait, easy)
32  * - check if iblocks can be computed from existing blocks (can wait, hard)
33  * - persistence (can wait)
34  */
35 #include "platform.h"
36 #include "gnunet_constants.h"
37 #include "gnunet_fs_service.h"
38 #include "fs.h"
39 #include "fs_tree.h"
40
41 #define DEBUG_DOWNLOAD GNUNET_NO
42
43 /**
44  * We're storing the IBLOCKS after the DBLOCKS on disk (so that we
45  * only have to truncate the file once we're done).
46  *
47  * Given the offset of a block (with respect to the DBLOCKS) and its
48  * depth, return the offset where we would store this block in the
49  * file.
50  * 
51  * @param fsize overall file size
52  * @param off offset of the block in the file
53  * @param depth depth of the block in the tree
54  * @param treedepth maximum depth of the tree
55  * @return off for DBLOCKS (depth == treedepth),
56  *         otherwise an offset past the end
57  *         of the file that does not overlap
58  *         with the range for any other block
59  */
60 static uint64_t
61 compute_disk_offset (uint64_t fsize,
62                      uint64_t off,
63                      unsigned int depth,
64                      unsigned int treedepth)
65 {
66   unsigned int i;
67   uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
68   uint64_t loff; /* where do IBlocks for depth "i" start? */
69   unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
70   
71   if (depth == treedepth)
72     return off;
73   /* first IBlocks start at the end of file, rounded up
74      to full DBLOCK_SIZE */
75   loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
76   lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
77   GNUNET_assert (0 == (off % DBLOCK_SIZE));
78   ioff = (off / DBLOCK_SIZE);
79   for (i=treedepth-1;i>depth;i--)
80     {
81       loff += lsize;
82       lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
83       GNUNET_assert (lsize > 0);
84       GNUNET_assert (0 == (ioff % CHK_PER_INODE));
85       ioff /= CHK_PER_INODE;
86     }
87   return loff + ioff * sizeof (struct ContentHashKey);
88 }
89
90
91 /**
92  * Given a file of the specified treedepth and a block at the given
93  * offset and depth, calculate the offset for the CHK at the given
94  * index.
95  *
96  * @param offset the offset of the first
97  *        DBLOCK in the subtree of the 
98  *        identified IBLOCK
99  * @param depth the depth of the IBLOCK in the tree
100  * @param treedepth overall depth of the tree
101  * @param k which CHK in the IBLOCK are we 
102  *        talking about
103  * @return offset if k=0, otherwise an appropriately
104  *         larger value (i.e., if depth = treedepth-1,
105  *         the returned value should be offset+DBLOCK_SIZE)
106  */
107 static uint64_t
108 compute_dblock_offset (uint64_t offset,
109                        unsigned int depth,
110                        unsigned int treedepth,
111                        unsigned int k)
112 {
113   unsigned int i;
114   uint64_t lsize; /* what is the size of the sum of all DBlocks 
115                      that a CHK at depth i corresponds to? */
116
117   if (depth == treedepth)
118     return offset;
119   lsize = DBLOCK_SIZE;
120   for (i=treedepth-1;i>depth;i--)
121     lsize *= CHK_PER_INODE;
122   return offset + k * lsize;
123 }
124
125
126 /**
127  * Fill in all of the generic fields for 
128  * a download event.
129  *
130  * @param pi structure to fill in
131  * @param dc overall download context
132  */
133 static void
134 make_download_status (struct GNUNET_FS_ProgressInfo *pi,
135                       struct GNUNET_FS_DownloadContext *dc)
136 {
137   pi->value.download.dc = dc;
138   pi->value.download.cctx
139     = dc->client_info;
140   pi->value.download.pctx
141     = (dc->parent == NULL) ? NULL : dc->parent->client_info;
142   pi->value.download.uri 
143     = dc->uri;
144   pi->value.download.filename
145     = dc->filename;
146   pi->value.download.size
147     = dc->length;
148   pi->value.download.duration
149     = GNUNET_TIME_absolute_get_duration (dc->start_time);
150   pi->value.download.completed
151     = dc->completed;
152   pi->value.download.anonymity
153     = dc->anonymity;
154   pi->value.download.eta
155     = GNUNET_TIME_calculate_eta (dc->start_time,
156                                  dc->completed,
157                                  dc->length);
158 }
159
160 /**
161  * We're ready to transmit a search request to the
162  * file-sharing service.  Do it.  If there is 
163  * more than one request pending, try to send 
164  * multiple or request another transmission.
165  *
166  * @param cls closure
167  * @param size number of bytes available in buf
168  * @param buf where the callee should write the message
169  * @return number of bytes written to buf
170  */
171 static size_t
172 transmit_download_request (void *cls,
173                            size_t size, 
174                            void *buf);
175
176
177 /**
178  * Schedule the download of the specified
179  * block in the tree.
180  *
181  * @param dc overall download this block belongs to
182  * @param chk content-hash-key of the block
183  * @param offset offset of the block in the file
184  *         (for IBlocks, the offset is the lowest
185  *          offset of any DBlock in the subtree under
186  *          the IBlock)
187  * @param depth depth of the block, 0 is the root of the tree
188  */
189 static void
190 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
191                          const struct ContentHashKey *chk,
192                          uint64_t offset,
193                          unsigned int depth)
194 {
195   struct DownloadRequest *sm;
196   uint64_t off;
197
198 #if DEBUG_DOWNLOAD
199   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
200               "Scheduling download at offset %llu and depth %u for `%s'\n",
201               (unsigned long long) offset,
202               depth,
203               GNUNET_h2s (&chk->query));
204 #endif
205   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
206                              offset,
207                              depth,
208                              dc->treedepth);
209   if ( (dc->old_file_size > off) &&
210        (dc->handle != NULL) &&
211        (off  == 
212         GNUNET_DISK_file_seek (dc->handle,
213                                off,
214                                GNUNET_DISK_SEEK_SET) ) )
215     {
216       // FIXME: check if block exists on disk!
217       // (read block, encode, compare with
218       // query; if matches, simply return)
219     }
220   if (depth < dc->treedepth)
221     {
222       // FIXME: try if we could
223       // reconstitute this IBLOCK
224       // from the existing blocks on disk (can wait)
225       // (read block(s), encode, compare with
226       // query; if matches, simply return)
227     }
228   sm = GNUNET_malloc (sizeof (struct DownloadRequest));
229   sm->chk = *chk;
230   sm->offset = offset;
231   sm->depth = depth;
232   sm->is_pending = GNUNET_YES;
233   sm->next = dc->pending;
234   dc->pending = sm;
235   GNUNET_CONTAINER_multihashmap_put (dc->active,
236                                      &chk->query,
237                                      sm,
238                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
239
240   if ( (dc->th == NULL) &&
241        (dc->client != NULL) )
242     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
243                                                   sizeof (struct SearchMessage),
244                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
245                                                   GNUNET_NO,
246                                                   &transmit_download_request,
247                                                   dc);
248 }
249
250
251
252 /**
253  * Suggest a filename based on given metadata.
254  * 
255  * @param md given meta data
256  * @return NULL if meta data is useless for suggesting a filename
257  */
258 char *
259 GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md)
260 {
261   return NULL;
262 }
263
264
265 /**
266  * We've lost our connection with the FS service.
267  * Re-establish it and re-transmit all of our
268  * pending requests.
269  *
270  * @param dc download context that is having trouble
271  */
272 static void
273 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
274
275
276 /**
277  * Compute how many bytes of data should be stored in
278  * the specified node.
279  *
280  * @param fsize overall file size
281  * @param totaldepth depth of the entire tree
282  * @param offset offset of the node
283  * @param depth depth of the node
284  * @return number of bytes stored in this node
285  */
286 static size_t
287 calculate_block_size (uint64_t fsize,
288                       unsigned int totaldepth,
289                       uint64_t offset,
290                       unsigned int depth)
291 {
292   unsigned int i;
293   size_t ret;
294   uint64_t rsize;
295   uint64_t epos;
296   unsigned int chks;
297
298   GNUNET_assert (offset < fsize);
299   if (depth == totaldepth)
300     {
301       ret = DBLOCK_SIZE;
302       if (offset + ret > fsize)
303         ret = (size_t) (fsize - offset);
304       return ret;
305     }
306
307   rsize = DBLOCK_SIZE;
308   for (i = totaldepth-1; i > depth; i--)
309     rsize *= CHK_PER_INODE;
310   epos = offset + rsize * CHK_PER_INODE;
311   GNUNET_assert (epos > offset);
312   if (epos > fsize)
313     epos = fsize;
314   /* round up when computing #CHKs in our IBlock */
315   chks = (epos - offset + rsize - 1) / rsize;
316   GNUNET_assert (chks <= CHK_PER_INODE);
317   return chks * sizeof (struct ContentHashKey);
318 }
319
320
321 /**
322  * Closure for iterator processing results.
323  */
324 struct ProcessResultClosure
325 {
326   
327   /**
328    * Hash of data.
329    */
330   GNUNET_HashCode query;
331
332   /**
333    * Data found in P2P network.
334    */ 
335   const void *data;
336
337   /**
338    * Our download context.
339    */
340   struct GNUNET_FS_DownloadContext *dc;
341                 
342   /**
343    * Number of bytes in data.
344    */
345   size_t size;
346
347   /**
348    * Type of data.
349    */
350   uint32_t type;
351   
352 };
353
354
355 /**
356  * We found an entry in a directory.  Check if the respective child
357  * already exists and if not create the respective child download.
358  *
359  * @param cls the parent download
360  * @param filename name of the file in the directory
361  * @param uri URI of the file (CHK or LOC)
362  * @param meta meta data of the file
363  * @param length number of bytes in data
364  * @param data contents of the file (or NULL if they were not inlined)
365  */
366 static void 
367 trigger_recursive_download (void *cls,
368                             const char *filename,
369                             const struct GNUNET_FS_Uri *uri,
370                             const struct GNUNET_CONTAINER_MetaData *meta,
371                             size_t length,
372                             const void *data)
373 {
374   struct GNUNET_FS_DownloadContext *dc = cls;  
375   struct GNUNET_FS_DownloadContext *cpos;
376   char *fn;
377   char *us;
378   char *ext;
379   char *dn;
380   char *full_name;
381
382   if (NULL == uri)
383     return; /* entry for the directory itself */
384   cpos = dc->child_head;
385   while (cpos != NULL)
386     {
387       if ( (GNUNET_FS_uri_test_equal (uri,
388                                       cpos->uri)) ||
389            ( (filename != NULL) &&
390              (0 == strcmp (cpos->filename,
391                            filename)) ) )
392         break;  
393       cpos = cpos->next;
394     }
395   if (cpos != NULL)
396     return; /* already exists */
397   fn = NULL;
398   if (NULL == filename)
399     {
400       fn = GNUNET_FS_meta_data_suggest_filename (meta);      
401       if (fn == NULL)
402         {
403           fn = GNUNET_FS_uri_to_string (uri);
404           
405         }
406       else if (fn[0] == '.')
407         {
408           ext = fn;
409           us = GNUNET_FS_uri_to_string (uri);
410           GNUNET_asprintf (&fn,
411                            "%s%s",
412                            &us[strlen (GNUNET_FS_URI_PREFIX 
413                                        GNUNET_FS_URI_CHK_INFIX)], ext);
414           GNUNET_free (ext);
415           GNUNET_free (us);
416         }
417       filename = fn;
418     }
419   if (dc->filename == NULL)
420     {
421       full_name = NULL;
422     }
423   else
424     {
425       dn = GNUNET_strdup (dc->filename);
426       GNUNET_break ( (strlen (dn) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
427                      (NULL ==
428                       strstr (dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT),
429                               GNUNET_FS_DIRECTORY_EXT)) );
430       dn[strlen(dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0';      
431       if ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) &&
432            ( (strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) ||
433              (NULL ==
434               strstr (filename + strlen(filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
435                       GNUNET_FS_DIRECTORY_EXT)) ) )
436         {
437           GNUNET_asprintf (&full_name,
438                            "%s%s%s%s",
439                            dn,
440                            DIR_SEPARATOR_STR,
441                            filename,
442                            GNUNET_FS_DIRECTORY_EXT);
443         }
444       else
445         {
446           GNUNET_asprintf (&full_name,
447                            "%s%s%s",
448                            dn,
449                            DIR_SEPARATOR_STR,
450                            filename);
451         }
452       GNUNET_free (dn);
453     }
454   if (data != NULL) 
455     {
456       if (full_name != NULL)
457         {
458           /* determine on-disk filename, write data! */
459           GNUNET_break (0); // FIXME: not implemented
460         }
461       else
462         {
463           /* FIXME: generate 'progress' events and move to
464              instant completion! */
465           GNUNET_break (0); // FIXME: not implemented
466         }
467     }
468   GNUNET_FS_download_start (dc->h,
469                             uri,
470                             meta,
471                             full_name,
472                             0,
473                             GNUNET_FS_uri_chk_get_file_size (uri),
474                             dc->anonymity,
475                             dc->options,
476                             NULL,
477                             dc);
478   GNUNET_free_non_null (full_name);
479   GNUNET_free_non_null (fn);
480 }
481
482
483 /**
484  * We're done downloading a directory.  Open the file and
485  * trigger all of the (remaining) child downloads.
486  *
487  * @param dc context of download that just completed
488  */
489 static void
490 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
491 {
492   size_t size;
493   uint64_t size64;
494   void *data;
495   struct GNUNET_DISK_FileHandle *h;
496   struct GNUNET_DISK_MapHandle *m;
497   
498   size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
499   size = (size_t) size64;
500   if (size64 != (uint64_t) size)
501     {
502       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
503                   _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
504       return;
505     }
506   if (dc->filename != NULL)
507     {
508       h = GNUNET_DISK_file_open (dc->filename,
509                                  GNUNET_DISK_OPEN_READ,
510                                  GNUNET_DISK_PERM_NONE);
511     }
512   else
513     {
514       /* FIXME: need to initialize (and use) temp_filename
515          in various places in order for this assertion to
516          not fail; right now, it will always fail! */
517       GNUNET_assert (dc->temp_filename != NULL);
518       h = GNUNET_DISK_file_open (dc->temp_filename,
519                                  GNUNET_DISK_OPEN_READ,
520                                  GNUNET_DISK_PERM_NONE);
521     }
522   if (h == NULL)
523     return; /* oops */
524   data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
525   if (data == NULL)
526     {
527       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
528                   _("Directory too large for system address space\n"));
529     }
530   else
531     {
532       GNUNET_FS_directory_list_contents (size,
533                                          data,
534                                          0,
535                                          &trigger_recursive_download,
536                                          dc);         
537       GNUNET_DISK_file_unmap (m);
538     }
539   GNUNET_DISK_file_close (h);
540   if (dc->filename == NULL)
541     {
542       if (0 != UNLINK (dc->temp_filename))
543         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
544                                   "unlink",
545                                   dc->temp_filename);
546       GNUNET_free (dc->temp_filename);
547       dc->temp_filename = NULL;
548     }
549 }
550
551
552 /**
553  * Iterator over entries in the pending requests in the 'active' map for the
554  * reply that we just got.
555  *
556  * @param cls closure (our 'struct ProcessResultClosure')
557  * @param key query for the given value / request
558  * @param value value in the hash map (a 'struct DownloadRequest')
559  * @return GNUNET_YES (we should continue to iterate); unless serious error
560  */
561 static int
562 process_result_with_request (void *cls,
563                              const GNUNET_HashCode * key,
564                              void *value)
565 {
566   struct ProcessResultClosure *prc = cls;
567   struct DownloadRequest *sm = value;
568   struct GNUNET_FS_DownloadContext *dc = prc->dc;
569   struct GNUNET_CRYPTO_AesSessionKey skey;
570   struct GNUNET_CRYPTO_AesInitializationVector iv;
571   char pt[prc->size];
572   struct GNUNET_FS_ProgressInfo pi;
573   uint64_t off;
574   size_t app;
575   int i;
576   struct ContentHashKey *chk;
577   char *emsg;
578
579   if (prc->size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
580                                          dc->treedepth,
581                                          sm->offset,
582                                          sm->depth))
583     {
584 #if DEBUG_DOWNLOAD
585       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
586                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
587                   calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
588                                         dc->treedepth,
589                                         sm->offset,
590                                         sm->depth),
591                   prc->size);
592 #endif
593       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
594       /* signal error */
595       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
596       make_download_status (&pi, dc);
597       pi.value.download.specifics.error.message = dc->emsg;
598       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
599                                      &pi);
600       /* abort all pending requests */
601       if (NULL != dc->th)
602         {
603           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
604           dc->th = NULL;
605         }
606       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
607       dc->client = NULL;
608       return GNUNET_NO;
609     }
610   GNUNET_assert (GNUNET_YES ==
611                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
612                                                        &prc->query,
613                                                        sm));
614   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
615   GNUNET_CRYPTO_aes_decrypt (prc->data,
616                              prc->size,
617                              &skey,
618                              &iv,
619                              pt);
620   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
621                              sm->offset,
622                              sm->depth,
623                              dc->treedepth);
624   /* save to disk */
625   if ( (NULL != dc->handle) &&
626        ( (sm->depth == dc->treedepth) ||
627          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
628     {
629       emsg = NULL;
630 #if DEBUG_DOWNLOAD
631       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
632                   "Saving decrypted block to disk at offset %llu\n",
633                   (unsigned long long) off);
634 #endif
635       if ( (off  != 
636             GNUNET_DISK_file_seek (dc->handle,
637                                    off,
638                                    GNUNET_DISK_SEEK_SET) ) )
639         GNUNET_asprintf (&emsg,
640                          _("Failed to seek to offset %llu in file `%s': %s\n"),
641                          (unsigned long long) off,
642                          dc->filename,
643                          STRERROR (errno));
644       else if (prc->size !=
645                GNUNET_DISK_file_write (dc->handle,
646                                        pt,
647                                        prc->size))
648         GNUNET_asprintf (&emsg,
649                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
650                          (unsigned int) prc->size,
651                          (unsigned long long) off,
652                          dc->filename,
653                          STRERROR (errno));
654       if (NULL != emsg)
655         {
656           dc->emsg = emsg;
657           // FIXME: make persistent
658
659           /* signal error */
660           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
661           make_download_status (&pi, dc);
662           pi.value.download.specifics.error.message = emsg;
663           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
664                                          &pi);
665
666           /* abort all pending requests */
667           if (NULL != dc->th)
668             {
669               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
670               dc->th = NULL;
671             }
672           GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
673           dc->client = NULL;
674           GNUNET_free (sm);
675           return GNUNET_NO;
676         }
677     }
678   if (sm->depth == dc->treedepth) 
679     {
680       app = prc->size;
681       if (sm->offset < dc->offset)
682         {
683           /* starting offset begins in the middle of pt,
684              do not count first bytes as progress */
685           GNUNET_assert (app > (dc->offset - sm->offset));
686           app -= (dc->offset - sm->offset);       
687         }
688       if (sm->offset + prc->size > dc->offset + dc->length)
689         {
690           /* end of block is after relevant range,
691              do not count last bytes as progress */
692           GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
693           app -= (sm->offset + prc->size) - (dc->offset + dc->length);
694         }
695       dc->completed += app;
696
697       /* do recursive download if option is set and either meta data
698          says it is a directory or if no meta data is given AND filename 
699          ends in '.gnd' (top-level case) */
700       if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
701            ( (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) ||
702              ( (dc->meta == NULL) &&
703                ( (NULL == dc->filename) ||             
704                  ( (strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) &&
705                    (NULL !=
706                     strstr (dc->filename + strlen(dc->filename) - strlen(GNUNET_FS_DIRECTORY_EXT),
707                             GNUNET_FS_DIRECTORY_EXT)) ) ) ) ) )
708         {
709           GNUNET_FS_directory_list_contents (prc->size,
710                                              pt,
711                                              off,
712                                              &trigger_recursive_download,
713                                              dc);         
714         }
715
716     }
717
718   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
719   make_download_status (&pi, dc);
720   pi.value.download.specifics.progress.data = pt;
721   pi.value.download.specifics.progress.offset = sm->offset;
722   pi.value.download.specifics.progress.data_len = prc->size;
723   pi.value.download.specifics.progress.depth = sm->depth;
724   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
725                                  &pi);
726   GNUNET_assert (dc->completed <= dc->length);
727   if (dc->completed == dc->length)
728     {
729 #if DEBUG_DOWNLOAD
730       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
731                   "Download completed, truncating file to desired length %llu\n",
732                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
733 #endif
734       /* truncate file to size (since we store IBlocks at the end) */
735       if (dc->handle != NULL)
736         {
737           GNUNET_DISK_file_close (dc->handle);
738           dc->handle = NULL;
739           if (0 != truncate (dc->filename,
740                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
741             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
742                                       "truncate",
743                                       dc->filename);
744         }
745
746       if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
747            (GNUNET_NO != GNUNET_FS_meta_data_test_for_directory (dc->meta)) )
748         full_recursive_download (dc);
749       if (dc->child_head == NULL)
750         {
751           /* signal completion */
752           pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
753           make_download_status (&pi, dc);
754           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
755                                          &pi);
756         }
757       GNUNET_assert (sm->depth == dc->treedepth);
758     }
759   // FIXME: make persistent
760   if (sm->depth == dc->treedepth) 
761     {
762       GNUNET_free (sm);      
763       return GNUNET_YES;
764     }
765 #if DEBUG_DOWNLOAD
766   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
767               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
768               sm->depth,
769               (unsigned long long) sm->offset);
770 #endif
771   GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
772   chk = (struct ContentHashKey*) pt;
773   for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
774     {
775       off = compute_dblock_offset (sm->offset,
776                                    sm->depth,
777                                    dc->treedepth,
778                                    i);
779       if ( (off + DBLOCK_SIZE >= dc->offset) &&
780            (off < dc->offset + dc->length) ) 
781         schedule_block_download (dc,
782                                  &chk[i],
783                                  off,
784                                  sm->depth + 1);
785     }
786   GNUNET_free (sm);
787   return GNUNET_YES;
788 }
789
790
791 /**
792  * Process a download result.
793  *
794  * @param dc our download context
795  * @param type type of the result
796  * @param data the (encrypted) response
797  * @param size size of data
798  */
799 static void
800 process_result (struct GNUNET_FS_DownloadContext *dc,
801                 uint32_t type,
802                 const void *data,
803                 size_t size)
804 {
805   struct ProcessResultClosure prc;
806
807   prc.dc = dc;
808   prc.data = data;
809   prc.size = size;
810   prc.type = type;
811   GNUNET_CRYPTO_hash (data, size, &prc.query);
812 #if DEBUG_DOWNLOAD
813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
814               "Received result for query `%s' from `%s'-service\n",
815               GNUNET_h2s (&prc.query),
816               "FS");
817 #endif
818   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
819                                               &prc.query,
820                                               &process_result_with_request,
821                                               &prc);
822 }
823
824
825 /**
826  * Type of a function to call when we receive a message
827  * from the service.
828  *
829  * @param cls closure
830  * @param msg message received, NULL on timeout or fatal error
831  */
832 static void 
833 receive_results (void *cls,
834                  const struct GNUNET_MessageHeader * msg)
835 {
836   struct GNUNET_FS_DownloadContext *dc = cls;
837   const struct PutMessage *cm;
838   uint16_t msize;
839
840   if ( (NULL == msg) ||
841        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
842        (sizeof (struct PutMessage) > ntohs(msg->size)) )
843     {
844       GNUNET_break (msg == NULL);       
845       try_reconnect (dc);
846       return;
847     }
848   msize = ntohs(msg->size);
849   cm = (const struct PutMessage*) msg;
850   process_result (dc, 
851                   ntohl (cm->type),
852                   &cm[1],
853                   msize - sizeof (struct PutMessage));
854   if (dc->client == NULL)
855     return; /* fatal error */
856   /* continue receiving */
857   GNUNET_CLIENT_receive (dc->client,
858                          &receive_results,
859                          dc,
860                          GNUNET_TIME_UNIT_FOREVER_REL);
861 }
862
863
864
865 /**
866  * We're ready to transmit a search request to the
867  * file-sharing service.  Do it.  If there is 
868  * more than one request pending, try to send 
869  * multiple or request another transmission.
870  *
871  * @param cls closure
872  * @param size number of bytes available in buf
873  * @param buf where the callee should write the message
874  * @return number of bytes written to buf
875  */
876 static size_t
877 transmit_download_request (void *cls,
878                            size_t size, 
879                            void *buf)
880 {
881   struct GNUNET_FS_DownloadContext *dc = cls;
882   size_t msize;
883   struct SearchMessage *sm;
884
885   dc->th = NULL;
886   if (NULL == buf)
887     {
888       try_reconnect (dc);
889       return 0;
890     }
891   GNUNET_assert (size >= sizeof (struct SearchMessage));
892   msize = 0;
893   sm = buf;
894   while ( (dc->pending != NULL) &&
895           (size > msize + sizeof (struct SearchMessage)) )
896     {
897 #if DEBUG_DOWNLOAD
898       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
899                   "Transmitting download request for `%s' to `%s'-service\n",
900                   GNUNET_h2s (&dc->pending->chk.query),
901                   "FS");
902 #endif
903       memset (sm, 0, sizeof (struct SearchMessage));
904       sm->header.size = htons (sizeof (struct SearchMessage));
905       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
906       if (dc->pending->depth == dc->treedepth)
907         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
908       else
909         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
910       sm->anonymity_level = htonl (dc->anonymity);
911       sm->target = dc->target.hashPubKey;
912       sm->query = dc->pending->chk.query;
913       dc->pending->is_pending = GNUNET_NO;
914       dc->pending = dc->pending->next;
915       msize += sizeof (struct SearchMessage);
916       sm++;
917     }
918   if (dc->pending != NULL)
919     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
920                                                   sizeof (struct SearchMessage),
921                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
922                                                   GNUNET_NO,
923                                                   &transmit_download_request,
924                                                   dc); 
925   return msize;
926 }
927
928
929 /**
930  * Reconnect to the FS service and transmit our queries NOW.
931  *
932  * @param cls our download context
933  * @param tc unused
934  */
935 static void
936 do_reconnect (void *cls,
937               const struct GNUNET_SCHEDULER_TaskContext *tc)
938 {
939   struct GNUNET_FS_DownloadContext *dc = cls;
940   struct GNUNET_CLIENT_Connection *client;
941   
942   dc->task = GNUNET_SCHEDULER_NO_TASK;
943   client = GNUNET_CLIENT_connect (dc->h->sched,
944                                   "fs",
945                                   dc->h->cfg);
946   if (NULL == client)
947     {
948       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
949                   "Connecting to `%s'-service failed, will try again.\n",
950                   "FS");
951       try_reconnect (dc);
952       return;
953     }
954   dc->client = client;
955   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
956                                                 sizeof (struct SearchMessage),
957                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
958                                                 GNUNET_NO,
959                                                 &transmit_download_request,
960                                                 dc);  
961   GNUNET_CLIENT_receive (client,
962                          &receive_results,
963                          dc,
964                          GNUNET_TIME_UNIT_FOREVER_REL);
965 }
966
967
968 /**
969  * Add entries that are not yet pending back to the pending list.
970  *
971  * @param cls our download context
972  * @param key unused
973  * @param entry entry of type "struct DownloadRequest"
974  * @return GNUNET_OK
975  */
976 static int
977 retry_entry (void *cls,
978              const GNUNET_HashCode *key,
979              void *entry)
980 {
981   struct GNUNET_FS_DownloadContext *dc = cls;
982   struct DownloadRequest *dr = entry;
983
984   if (! dr->is_pending)
985     {
986       dr->next = dc->pending;
987       dr->is_pending = GNUNET_YES;
988       dc->pending = entry;
989     }
990   return GNUNET_OK;
991 }
992
993
994 /**
995  * We've lost our connection with the FS service.
996  * Re-establish it and re-transmit all of our
997  * pending requests.
998  *
999  * @param dc download context that is having trouble
1000  */
1001 static void
1002 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
1003 {
1004   
1005   if (NULL != dc->client)
1006     {
1007       if (NULL != dc->th)
1008         {
1009           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1010           dc->th = NULL;
1011         }
1012       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1013                                              &retry_entry,
1014                                              dc);
1015       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1016       dc->client = NULL;
1017     }
1018   dc->task
1019     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
1020                                     GNUNET_TIME_UNIT_SECONDS,
1021                                     &do_reconnect,
1022                                     dc);
1023 }
1024
1025
1026 /**
1027  * Download parts of a file.  Note that this will store
1028  * the blocks at the respective offset in the given file.  Also, the
1029  * download is still using the blocking of the underlying FS
1030  * encoding.  As a result, the download may *write* outside of the
1031  * given boundaries (if offset and length do not match the 32k FS
1032  * block boundaries). <p>
1033  *
1034  * This function should be used to focus a download towards a
1035  * particular portion of the file (optimization), not to strictly
1036  * limit the download to exactly those bytes.
1037  *
1038  * @param h handle to the file sharing subsystem
1039  * @param uri the URI of the file (determines what to download); CHK or LOC URI
1040  * @param meta known metadata for the file (can be NULL)
1041  * @param filename where to store the file, maybe NULL (then no file is
1042  *        created on disk and data must be grabbed from the callbacks)
1043  * @param offset at what offset should we start the download (typically 0)
1044  * @param length how many bytes should be downloaded starting at offset
1045  * @param anonymity anonymity level to use for the download
1046  * @param options various options
1047  * @param cctx initial value for the client context for this download
1048  * @param parent parent download to associate this download with (use NULL
1049  *        for top-level downloads; useful for manually-triggered recursive downloads)
1050  * @return context that can be used to control this download
1051  */
1052 struct GNUNET_FS_DownloadContext *
1053 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
1054                           const struct GNUNET_FS_Uri *uri,
1055                           const struct GNUNET_CONTAINER_MetaData *meta,
1056                           const char *filename,
1057                           uint64_t offset,
1058                           uint64_t length,
1059                           uint32_t anonymity,
1060                           enum GNUNET_FS_DownloadOptions options,
1061                           void *cctx,
1062                           struct GNUNET_FS_DownloadContext *parent)
1063 {
1064   struct GNUNET_FS_ProgressInfo pi;
1065   struct GNUNET_FS_DownloadContext *dc;
1066   struct GNUNET_CLIENT_Connection *client;
1067
1068   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
1069   if ( (offset + length < offset) ||
1070        (offset + length > uri->data.chk.file_length) )
1071     {      
1072       GNUNET_break (0);
1073       return NULL;
1074     }
1075   // FIXME: add support for "loc" URIs!
1076 #if DEBUG_DOWNLOAD
1077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1078               "Starting download `%s' of %llu bytes\n",
1079               filename,
1080               (unsigned long long) length);
1081 #endif
1082   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
1083   dc->h = h;
1084   dc->parent = parent;
1085   if (parent != NULL)
1086     {
1087       GNUNET_CONTAINER_DLL_insert (parent->child_head,
1088                                    parent->child_tail,
1089                                    dc);
1090     }
1091   dc->uri = GNUNET_FS_uri_dup (uri);
1092   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
1093   dc->client_info = cctx;
1094   dc->start_time = GNUNET_TIME_absolute_get ();
1095   if (NULL != filename)
1096     {
1097       dc->filename = GNUNET_strdup (filename);
1098       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1099         GNUNET_DISK_file_size (filename,
1100                                &dc->old_file_size,
1101                                GNUNET_YES);
1102       dc->handle = GNUNET_DISK_file_open (filename, 
1103                                           GNUNET_DISK_OPEN_READWRITE | 
1104                                           GNUNET_DISK_OPEN_CREATE,
1105                                           GNUNET_DISK_PERM_USER_READ |
1106                                           GNUNET_DISK_PERM_USER_WRITE |
1107                                           GNUNET_DISK_PERM_GROUP_READ |
1108                                           GNUNET_DISK_PERM_OTHER_READ);
1109       if (dc->handle == NULL)
1110         {
1111           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1112                       _("Download failed: could not open file `%s': %s\n"),
1113                       dc->filename,
1114                       STRERROR (errno));
1115           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1116           GNUNET_FS_uri_destroy (dc->uri);
1117           GNUNET_free (dc->filename);
1118           GNUNET_free (dc);
1119           return NULL;
1120         }
1121     }
1122   // FIXME: set "dc->target" for LOC uris!
1123   dc->offset = offset;
1124   dc->length = length;
1125   dc->anonymity = anonymity;
1126   dc->options = options;
1127   dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
1128   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1129 #if DEBUG_DOWNLOAD
1130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1131               "Download tree has depth %u\n",
1132               dc->treedepth);
1133 #endif
1134   // FIXME: make persistent
1135   
1136   // FIXME: bound parallelism here!
1137   client = GNUNET_CLIENT_connect (h->sched,
1138                                   "fs",
1139                                   h->cfg);
1140   dc->client = client;
1141   schedule_block_download (dc, 
1142                            &dc->uri->data.chk.chk,
1143                            0, 
1144                            1 /* 0 == CHK, 1 == top */);
1145   GNUNET_CLIENT_receive (client,
1146                          &receive_results,
1147                          dc,
1148                          GNUNET_TIME_UNIT_FOREVER_REL);
1149   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1150   make_download_status (&pi, dc);
1151   pi.value.download.specifics.start.meta = meta;
1152   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1153                                  &pi);
1154
1155   return dc;
1156 }
1157
1158
1159 /**
1160  * Free entries in the map.
1161  *
1162  * @param cls unused (NULL)
1163  * @param key unused
1164  * @param entry entry of type "struct DownloadRequest" which is freed
1165  * @return GNUNET_OK
1166  */
1167 static int
1168 free_entry (void *cls,
1169             const GNUNET_HashCode *key,
1170             void *entry)
1171 {
1172   GNUNET_free (entry);
1173   return GNUNET_OK;
1174 }
1175
1176
1177 /**
1178  * Stop a download (aborts if download is incomplete).
1179  *
1180  * @param dc handle for the download
1181  * @param do_delete delete files of incomplete downloads
1182  */
1183 void
1184 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1185                          int do_delete)
1186 {
1187   struct GNUNET_FS_ProgressInfo pi;
1188
1189   while (NULL != dc->child_head)
1190     GNUNET_FS_download_stop (dc->child_head, 
1191                              do_delete);
1192   // FIXME: make unpersistent  
1193   if (dc->parent != NULL)
1194     GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1195                                  dc->parent->child_tail,
1196                                  dc);
1197   
1198   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1199   make_download_status (&pi, dc);
1200   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1201                                  &pi);
1202
1203   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1204     GNUNET_SCHEDULER_cancel (dc->h->sched,
1205                              dc->task);
1206   if (NULL != dc->th)
1207     {
1208       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1209       dc->th = NULL;
1210     }
1211   if (NULL != dc->client)
1212     GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1213   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1214                                          &free_entry,
1215                                          NULL);
1216   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1217   if (dc->filename != NULL)
1218     {
1219       if (NULL != dc->handle)
1220         GNUNET_DISK_file_close (dc->handle);
1221       if ( (dc->completed != dc->length) &&
1222            (GNUNET_YES == do_delete) )
1223         {
1224           if (0 != UNLINK (dc->filename))
1225             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1226                                       "unlink",
1227                                       dc->filename);
1228         }
1229       GNUNET_free (dc->filename);
1230     }
1231   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1232   GNUNET_FS_uri_destroy (dc->uri);
1233   GNUNET_free (dc);
1234 }
1235
1236 /* end of fs_download.c */