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  * - 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  * We've lost our connection with the FS service.
253  * Re-establish it and re-transmit all of our
254  * pending requests.
255  *
256  * @param dc download context that is having trouble
257  */
258 static void
259 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
260
261
262 /**
263  * Compute how many bytes of data should be stored in
264  * the specified node.
265  *
266  * @param fsize overall file size
267  * @param totaldepth depth of the entire tree
268  * @param offset offset of the node
269  * @param depth depth of the node
270  * @return number of bytes stored in this node
271  */
272 static size_t
273 calculate_block_size (uint64_t fsize,
274                       unsigned int totaldepth,
275                       uint64_t offset,
276                       unsigned int depth)
277 {
278   unsigned int i;
279   size_t ret;
280   uint64_t rsize;
281   uint64_t epos;
282   unsigned int chks;
283
284   GNUNET_assert (offset < fsize);
285   if (depth == totaldepth)
286     {
287       ret = DBLOCK_SIZE;
288       if (offset + ret > fsize)
289         ret = (size_t) (fsize - offset);
290       return ret;
291     }
292
293   rsize = DBLOCK_SIZE;
294   for (i = totaldepth-1; i > depth; i--)
295     rsize *= CHK_PER_INODE;
296   epos = offset + rsize * CHK_PER_INODE;
297   GNUNET_assert (epos > offset);
298   if (epos > fsize)
299     epos = fsize;
300   /* round up when computing #CHKs in our IBlock */
301   chks = (epos - offset + rsize - 1) / rsize;
302   GNUNET_assert (chks <= CHK_PER_INODE);
303   return chks * sizeof (struct ContentHashKey);
304 }
305
306
307 /**
308  * Closure for iterator processing results.
309  */
310 struct ProcessResultClosure
311 {
312   
313   /**
314    * Hash of data.
315    */
316   GNUNET_HashCode query;
317
318   /**
319    * Data found in P2P network.
320    */ 
321   const void *data;
322
323   /**
324    * Our download context.
325    */
326   struct GNUNET_FS_DownloadContext *dc;
327                 
328   /**
329    * Number of bytes in data.
330    */
331   size_t size;
332
333   /**
334    * Type of data.
335    */
336   uint32_t type;
337   
338 };
339
340
341 /**
342  * We found an entry in a directory.  Check if the respective child
343  * already exists and if not create the respective child download.
344  *
345  * @param cls the parent download
346  * @param filename name of the file in the directory
347  * @param uri URI of the file (CHK or LOC)
348  * @param meta meta data of the file
349  * @param length number of bytes in data
350  * @param data contents of the file (or NULL if they were not inlined)
351  */
352 static void 
353 trigger_recursive_download (void *cls,
354                             const char *filename,
355                             const struct GNUNET_FS_Uri *uri,
356                             const struct GNUNET_CONTAINER_MetaData *meta,
357                             size_t length,
358                             const void *data)
359 {
360   struct GNUNET_FS_DownloadContext *dc = cls;  
361   struct GNUNET_FS_DownloadContext *cpos;
362
363   cpos = dc->child_head;
364   while (cpos != NULL)
365     {
366       if (0 == strcmp (cpos->filename,
367                        filename))
368         {
369           GNUNET_break_op (GNUNET_FS_uri_test_equal (uri,
370                                                      cpos->uri));
371           break;
372         }
373       cpos = cpos->next;
374     }
375   if (cpos != NULL)
376     return; /* already exists */
377   if (data != NULL)
378     {
379       /* determine on-disk filename, write data! */
380       GNUNET_break (0); // FIXME: not implemented
381     }
382   GNUNET_FS_download_start (dc->h,
383                             uri,
384                             meta,
385                             filename, /* FIXME: prepend directory name! */
386                             0,
387                             GNUNET_FS_uri_chk_get_file_size (uri),
388                             dc->anonymity,
389                             dc->options,
390                             NULL,
391                             dc);
392 }
393
394
395 /**
396  * We're done downloading a directory.  Open the file and
397  * trigger all of the (remaining) child downloads.
398  *
399  * @param dc context of download that just completed
400  */
401 static void
402 full_recursive_download (struct GNUNET_FS_DownloadContext *dc)
403 {
404   size_t size;
405   uint64_t size64;
406   void *data;
407   struct GNUNET_DISK_FileHandle *h;
408   struct GNUNET_DISK_MapHandle *m;
409   
410   size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri);
411   size = (size_t) size64;
412   if (size64 != (uint64_t) size)
413     {
414       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
415                   _("Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n"));
416       return;
417     }
418   if (dc->filename != NULL)
419     {
420       h = GNUNET_DISK_file_open (dc->filename,
421                                  GNUNET_DISK_OPEN_READ,
422                                  GNUNET_DISK_PERM_NONE);
423     }
424   else
425     {
426       /* FIXME: need to initialize (and use) temp_filename
427          in various places in order for this assertion to
428          not fail; right now, it will always fail! */
429       GNUNET_assert (dc->temp_filename != NULL);
430       h = GNUNET_DISK_file_open (dc->temp_filename,
431                                  GNUNET_DISK_OPEN_READ,
432                                  GNUNET_DISK_PERM_NONE);
433     }
434   if (h == NULL)
435     return; /* oops */
436   data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size);
437   if (data == NULL)
438     {
439       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
440                   _("Directory too large for system address space\n"));
441     }
442   else
443     {
444       GNUNET_FS_directory_list_contents (size,
445                                          data,
446                                          0,
447                                          &trigger_recursive_download,
448                                          dc);         
449       GNUNET_DISK_file_unmap (m);
450     }
451   GNUNET_DISK_file_close (h);
452   if (dc->filename == NULL)
453     {
454       if (0 != UNLINK (dc->temp_filename))
455         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
456                                   "unlink",
457                                   dc->temp_filename);
458       GNUNET_free (dc->temp_filename);
459       dc->temp_filename = NULL;
460     }
461 }
462
463
464 /**
465  * Iterator over entries in the pending requests in the 'active' map for the
466  * reply that we just got.
467  *
468  * @param cls closure (our 'struct ProcessResultClosure')
469  * @param key query for the given value / request
470  * @param value value in the hash map (a 'struct DownloadRequest')
471  * @return GNUNET_YES (we should continue to iterate); unless serious error
472  */
473 static int
474 process_result_with_request (void *cls,
475                              const GNUNET_HashCode * key,
476                              void *value)
477 {
478   struct ProcessResultClosure *prc = cls;
479   struct DownloadRequest *sm = value;
480   struct GNUNET_FS_DownloadContext *dc = prc->dc;
481   struct GNUNET_CRYPTO_AesSessionKey skey;
482   struct GNUNET_CRYPTO_AesInitializationVector iv;
483   char pt[prc->size];
484   struct GNUNET_FS_ProgressInfo pi;
485   uint64_t off;
486   size_t app;
487   int i;
488   struct ContentHashKey *chk;
489   char *emsg;
490
491   if (prc->size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
492                                          dc->treedepth,
493                                          sm->offset,
494                                          sm->depth))
495     {
496 #if DEBUG_DOWNLOAD
497       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
498                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
499                   calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
500                                         dc->treedepth,
501                                         sm->offset,
502                                         sm->depth),
503                   prc->size);
504 #endif
505       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
506       /* signal error */
507       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
508       make_download_status (&pi, dc);
509       pi.value.download.specifics.error.message = dc->emsg;
510       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
511                                      &pi);
512       /* abort all pending requests */
513       if (NULL != dc->th)
514         {
515           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
516           dc->th = NULL;
517         }
518       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
519       dc->client = NULL;
520       return GNUNET_NO;
521     }
522   GNUNET_assert (GNUNET_YES ==
523                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
524                                                        &prc->query,
525                                                        sm));
526   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
527   GNUNET_CRYPTO_aes_decrypt (prc->data,
528                              prc->size,
529                              &skey,
530                              &iv,
531                              pt);
532   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
533                              sm->offset,
534                              sm->depth,
535                              dc->treedepth);
536   /* save to disk */
537   if ( (NULL != dc->handle) &&
538        ( (sm->depth == dc->treedepth) ||
539          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
540     {
541       emsg = NULL;
542 #if DEBUG_DOWNLOAD
543       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
544                   "Saving decrypted block to disk at offset %llu\n",
545                   (unsigned long long) off);
546 #endif
547       if ( (off  != 
548             GNUNET_DISK_file_seek (dc->handle,
549                                    off,
550                                    GNUNET_DISK_SEEK_SET) ) )
551         GNUNET_asprintf (&emsg,
552                          _("Failed to seek to offset %llu in file `%s': %s\n"),
553                          (unsigned long long) off,
554                          dc->filename,
555                          STRERROR (errno));
556       else if (prc->size !=
557                GNUNET_DISK_file_write (dc->handle,
558                                        pt,
559                                        prc->size))
560         GNUNET_asprintf (&emsg,
561                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
562                          (unsigned int) prc->size,
563                          (unsigned long long) off,
564                          dc->filename,
565                          STRERROR (errno));
566       if (NULL != emsg)
567         {
568           dc->emsg = emsg;
569           // FIXME: make persistent
570
571           /* signal error */
572           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
573           make_download_status (&pi, dc);
574           pi.value.download.specifics.error.message = emsg;
575           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
576                                          &pi);
577
578           /* abort all pending requests */
579           if (NULL != dc->th)
580             {
581               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
582               dc->th = NULL;
583             }
584           GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
585           dc->client = NULL;
586           GNUNET_free (sm);
587           return GNUNET_NO;
588         }
589     }
590   if (sm->depth == dc->treedepth) 
591     {
592       app = prc->size;
593       if (sm->offset < dc->offset)
594         {
595           /* starting offset begins in the middle of pt,
596              do not count first bytes as progress */
597           GNUNET_assert (app > (dc->offset - sm->offset));
598           app -= (dc->offset - sm->offset);       
599         }
600       if (sm->offset + prc->size > dc->offset + dc->length)
601         {
602           /* end of block is after relevant range,
603              do not count last bytes as progress */
604           GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
605           app -= (sm->offset + prc->size) - (dc->offset + dc->length);
606         }
607       dc->completed += app;
608
609       if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
610            (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) )
611         {
612           GNUNET_FS_directory_list_contents (prc->size,
613                                              pt,
614                                              off,
615                                              &trigger_recursive_download,
616                                              dc);         
617         }
618
619     }
620
621   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
622   make_download_status (&pi, dc);
623   pi.value.download.specifics.progress.data = pt;
624   pi.value.download.specifics.progress.offset = sm->offset;
625   pi.value.download.specifics.progress.data_len = prc->size;
626   pi.value.download.specifics.progress.depth = sm->depth;
627   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
628                                  &pi);
629   GNUNET_assert (dc->completed <= dc->length);
630   if (dc->completed == dc->length)
631     {
632 #if DEBUG_DOWNLOAD
633       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
634                   "Download completed, truncating file to desired length %llu\n",
635                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
636 #endif
637       /* truncate file to size (since we store IBlocks at the end) */
638       if (dc->handle != NULL)
639         {
640           GNUNET_DISK_file_close (dc->handle);
641           dc->handle = NULL;
642           if (0 != truncate (dc->filename,
643                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
644             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
645                                       "truncate",
646                                       dc->filename);
647         }
648
649       if ( (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) &&
650            (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) )
651         full_recursive_download (dc);
652       if (dc->child_head == NULL)
653         {
654           /* signal completion */
655           pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
656           make_download_status (&pi, dc);
657           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
658                                          &pi);
659         }
660       GNUNET_assert (sm->depth == dc->treedepth);
661     }
662   // FIXME: make persistent
663   if (sm->depth == dc->treedepth) 
664     {
665       GNUNET_free (sm);      
666       return GNUNET_YES;
667     }
668 #if DEBUG_DOWNLOAD
669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
670               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
671               sm->depth,
672               (unsigned long long) sm->offset);
673 #endif
674   GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
675   chk = (struct ContentHashKey*) pt;
676   for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
677     {
678       off = compute_dblock_offset (sm->offset,
679                                    sm->depth,
680                                    dc->treedepth,
681                                    i);
682       if ( (off + DBLOCK_SIZE >= dc->offset) &&
683            (off < dc->offset + dc->length) ) 
684         schedule_block_download (dc,
685                                  &chk[i],
686                                  off,
687                                  sm->depth + 1);
688     }
689   GNUNET_free (sm);
690   return GNUNET_YES;
691 }
692
693
694 /**
695  * Process a download result.
696  *
697  * @param dc our download context
698  * @param type type of the result
699  * @param data the (encrypted) response
700  * @param size size of data
701  */
702 static void
703 process_result (struct GNUNET_FS_DownloadContext *dc,
704                 uint32_t type,
705                 const void *data,
706                 size_t size)
707 {
708   struct ProcessResultClosure prc;
709
710   prc.dc = dc;
711   prc.data = data;
712   prc.size = size;
713   prc.type = type;
714   GNUNET_CRYPTO_hash (data, size, &prc.query);
715 #if DEBUG_DOWNLOAD
716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
717               "Received result for query `%s' from `%s'-service\n",
718               GNUNET_h2s (&prc.query),
719               "FS");
720 #endif
721   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
722                                               &prc.query,
723                                               &process_result_with_request,
724                                               &prc);
725 }
726
727
728 /**
729  * Type of a function to call when we receive a message
730  * from the service.
731  *
732  * @param cls closure
733  * @param msg message received, NULL on timeout or fatal error
734  */
735 static void 
736 receive_results (void *cls,
737                  const struct GNUNET_MessageHeader * msg)
738 {
739   struct GNUNET_FS_DownloadContext *dc = cls;
740   const struct PutMessage *cm;
741   uint16_t msize;
742
743   if ( (NULL == msg) ||
744        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
745        (sizeof (struct PutMessage) > ntohs(msg->size)) )
746     {
747       GNUNET_break (msg == NULL);       
748       try_reconnect (dc);
749       return;
750     }
751   msize = ntohs(msg->size);
752   cm = (const struct PutMessage*) msg;
753   process_result (dc, 
754                   ntohl (cm->type),
755                   &cm[1],
756                   msize - sizeof (struct PutMessage));
757   if (dc->client == NULL)
758     return; /* fatal error */
759   /* continue receiving */
760   GNUNET_CLIENT_receive (dc->client,
761                          &receive_results,
762                          dc,
763                          GNUNET_TIME_UNIT_FOREVER_REL);
764 }
765
766
767
768 /**
769  * We're ready to transmit a search request to the
770  * file-sharing service.  Do it.  If there is 
771  * more than one request pending, try to send 
772  * multiple or request another transmission.
773  *
774  * @param cls closure
775  * @param size number of bytes available in buf
776  * @param buf where the callee should write the message
777  * @return number of bytes written to buf
778  */
779 static size_t
780 transmit_download_request (void *cls,
781                            size_t size, 
782                            void *buf)
783 {
784   struct GNUNET_FS_DownloadContext *dc = cls;
785   size_t msize;
786   struct SearchMessage *sm;
787
788   dc->th = NULL;
789   if (NULL == buf)
790     {
791       try_reconnect (dc);
792       return 0;
793     }
794   GNUNET_assert (size >= sizeof (struct SearchMessage));
795   msize = 0;
796   sm = buf;
797   while ( (dc->pending != NULL) &&
798           (size > msize + sizeof (struct SearchMessage)) )
799     {
800 #if DEBUG_DOWNLOAD
801       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
802                   "Transmitting download request for `%s' to `%s'-service\n",
803                   GNUNET_h2s (&dc->pending->chk.query),
804                   "FS");
805 #endif
806       memset (sm, 0, sizeof (struct SearchMessage));
807       sm->header.size = htons (sizeof (struct SearchMessage));
808       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
809       if (dc->pending->depth == dc->treedepth)
810         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
811       else
812         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
813       sm->anonymity_level = htonl (dc->anonymity);
814       sm->target = dc->target.hashPubKey;
815       sm->query = dc->pending->chk.query;
816       dc->pending->is_pending = GNUNET_NO;
817       dc->pending = dc->pending->next;
818       msize += sizeof (struct SearchMessage);
819       sm++;
820     }
821   if (dc->pending != NULL)
822     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
823                                                   sizeof (struct SearchMessage),
824                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
825                                                   GNUNET_NO,
826                                                   &transmit_download_request,
827                                                   dc); 
828   return msize;
829 }
830
831
832 /**
833  * Reconnect to the FS service and transmit our queries NOW.
834  *
835  * @param cls our download context
836  * @param tc unused
837  */
838 static void
839 do_reconnect (void *cls,
840               const struct GNUNET_SCHEDULER_TaskContext *tc)
841 {
842   struct GNUNET_FS_DownloadContext *dc = cls;
843   struct GNUNET_CLIENT_Connection *client;
844   
845   dc->task = GNUNET_SCHEDULER_NO_TASK;
846   client = GNUNET_CLIENT_connect (dc->h->sched,
847                                   "fs",
848                                   dc->h->cfg);
849   if (NULL == client)
850     {
851       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
852                   "Connecting to `%s'-service failed, will try again.\n",
853                   "FS");
854       try_reconnect (dc);
855       return;
856     }
857   dc->client = client;
858   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
859                                                 sizeof (struct SearchMessage),
860                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
861                                                 GNUNET_NO,
862                                                 &transmit_download_request,
863                                                 dc);  
864   GNUNET_CLIENT_receive (client,
865                          &receive_results,
866                          dc,
867                          GNUNET_TIME_UNIT_FOREVER_REL);
868 }
869
870
871 /**
872  * Add entries that are not yet pending back to the pending list.
873  *
874  * @param cls our download context
875  * @param key unused
876  * @param entry entry of type "struct DownloadRequest"
877  * @return GNUNET_OK
878  */
879 static int
880 retry_entry (void *cls,
881              const GNUNET_HashCode *key,
882              void *entry)
883 {
884   struct GNUNET_FS_DownloadContext *dc = cls;
885   struct DownloadRequest *dr = entry;
886
887   if (! dr->is_pending)
888     {
889       dr->next = dc->pending;
890       dr->is_pending = GNUNET_YES;
891       dc->pending = entry;
892     }
893   return GNUNET_OK;
894 }
895
896
897 /**
898  * We've lost our connection with the FS service.
899  * Re-establish it and re-transmit all of our
900  * pending requests.
901  *
902  * @param dc download context that is having trouble
903  */
904 static void
905 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
906 {
907   
908   if (NULL != dc->client)
909     {
910       if (NULL != dc->th)
911         {
912           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
913           dc->th = NULL;
914         }
915       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
916                                              &retry_entry,
917                                              dc);
918       GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
919       dc->client = NULL;
920     }
921   dc->task
922     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
923                                     GNUNET_TIME_UNIT_SECONDS,
924                                     &do_reconnect,
925                                     dc);
926 }
927
928
929 /**
930  * Download parts of a file.  Note that this will store
931  * the blocks at the respective offset in the given file.  Also, the
932  * download is still using the blocking of the underlying FS
933  * encoding.  As a result, the download may *write* outside of the
934  * given boundaries (if offset and length do not match the 32k FS
935  * block boundaries). <p>
936  *
937  * This function should be used to focus a download towards a
938  * particular portion of the file (optimization), not to strictly
939  * limit the download to exactly those bytes.
940  *
941  * @param h handle to the file sharing subsystem
942  * @param uri the URI of the file (determines what to download); CHK or LOC URI
943  * @param meta known metadata for the file (can be NULL)
944  * @param filename where to store the file, maybe NULL (then no file is
945  *        created on disk and data must be grabbed from the callbacks)
946  * @param offset at what offset should we start the download (typically 0)
947  * @param length how many bytes should be downloaded starting at offset
948  * @param anonymity anonymity level to use for the download
949  * @param options various options
950  * @param cctx initial value for the client context for this download
951  * @param parent parent download to associate this download with (use NULL
952  *        for top-level downloads; useful for manually-triggered recursive downloads)
953  * @return context that can be used to control this download
954  */
955 struct GNUNET_FS_DownloadContext *
956 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
957                           const struct GNUNET_FS_Uri *uri,
958                           const struct GNUNET_CONTAINER_MetaData *meta,
959                           const char *filename,
960                           uint64_t offset,
961                           uint64_t length,
962                           uint32_t anonymity,
963                           enum GNUNET_FS_DownloadOptions options,
964                           void *cctx,
965                           struct GNUNET_FS_DownloadContext *parent)
966 {
967   struct GNUNET_FS_ProgressInfo pi;
968   struct GNUNET_FS_DownloadContext *dc;
969   struct GNUNET_CLIENT_Connection *client;
970
971   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
972   if ( (offset + length < offset) ||
973        (offset + length > uri->data.chk.file_length) )
974     {      
975       GNUNET_break (0);
976       return NULL;
977     }
978   // FIXME: add support for "loc" URIs!
979 #if DEBUG_DOWNLOAD
980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
981               "Starting download `%s' of %llu bytes\n",
982               filename,
983               (unsigned long long) length);
984 #endif
985   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
986   dc->h = h;
987   dc->parent = parent;
988   if (parent != NULL)
989     {
990       GNUNET_CONTAINER_DLL_insert (parent->child_head,
991                                    parent->child_tail,
992                                    dc);
993     }
994   dc->uri = GNUNET_FS_uri_dup (uri);
995   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
996   dc->client_info = cctx;
997   dc->start_time = GNUNET_TIME_absolute_get ();
998   if (NULL != filename)
999     {
1000       dc->filename = GNUNET_strdup (filename);
1001       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
1002         GNUNET_DISK_file_size (filename,
1003                                &dc->old_file_size,
1004                                GNUNET_YES);
1005       dc->handle = GNUNET_DISK_file_open (filename, 
1006                                           GNUNET_DISK_OPEN_READWRITE | 
1007                                           GNUNET_DISK_OPEN_CREATE,
1008                                           GNUNET_DISK_PERM_USER_READ |
1009                                           GNUNET_DISK_PERM_USER_WRITE |
1010                                           GNUNET_DISK_PERM_GROUP_READ |
1011                                           GNUNET_DISK_PERM_OTHER_READ);
1012       if (dc->handle == NULL)
1013         {
1014           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1015                       _("Download failed: could not open file `%s': %s\n"),
1016                       dc->filename,
1017                       STRERROR (errno));
1018           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1019           GNUNET_FS_uri_destroy (dc->uri);
1020           GNUNET_free (dc->filename);
1021           GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1022           GNUNET_free (dc);
1023           return NULL;
1024         }
1025     }
1026   // FIXME: set "dc->target" for LOC uris!
1027   dc->offset = offset;
1028   dc->length = length;
1029   dc->anonymity = anonymity;
1030   dc->options = options;
1031   dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
1032   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
1033 #if DEBUG_DOWNLOAD
1034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1035               "Download tree has depth %u\n",
1036               dc->treedepth);
1037 #endif
1038   // FIXME: make persistent
1039   
1040   // FIXME: bound parallelism here!
1041   client = GNUNET_CLIENT_connect (h->sched,
1042                                   "fs",
1043                                   h->cfg);
1044   dc->client = client;
1045   schedule_block_download (dc, 
1046                            &dc->uri->data.chk.chk,
1047                            0, 
1048                            1 /* 0 == CHK, 1 == top */);
1049   GNUNET_CLIENT_receive (client,
1050                          &receive_results,
1051                          dc,
1052                          GNUNET_TIME_UNIT_FOREVER_REL);
1053   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
1054   make_download_status (&pi, dc);
1055   pi.value.download.specifics.start.meta = meta;
1056   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1057                                  &pi);
1058
1059   return dc;
1060 }
1061
1062
1063 /**
1064  * Free entries in the map.
1065  *
1066  * @param cls unused (NULL)
1067  * @param key unused
1068  * @param entry entry of type "struct DownloadRequest" which is freed
1069  * @return GNUNET_OK
1070  */
1071 static int
1072 free_entry (void *cls,
1073             const GNUNET_HashCode *key,
1074             void *entry)
1075 {
1076   GNUNET_free (entry);
1077   return GNUNET_OK;
1078 }
1079
1080
1081 /**
1082  * Stop a download (aborts if download is incomplete).
1083  *
1084  * @param dc handle for the download
1085  * @param do_delete delete files of incomplete downloads
1086  */
1087 void
1088 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
1089                          int do_delete)
1090 {
1091   struct GNUNET_FS_ProgressInfo pi;
1092
1093   while (NULL != dc->child_head)
1094     GNUNET_FS_download_stop (dc->child_head, 
1095                              do_delete);
1096   // FIXME: make unpersistent  
1097   if (dc->parent != NULL)
1098     GNUNET_CONTAINER_DLL_remove (dc->parent->child_head,
1099                                  dc->parent->child_tail,
1100                                  dc);
1101   
1102   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
1103   make_download_status (&pi, dc);
1104   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
1105                                  &pi);
1106
1107   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
1108     GNUNET_SCHEDULER_cancel (dc->h->sched,
1109                              dc->task);
1110   if (NULL != dc->th)
1111     {
1112       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
1113       dc->th = NULL;
1114     }
1115   if (NULL != dc->client)
1116     GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
1117   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
1118                                          &free_entry,
1119                                          NULL);
1120   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
1121   if (dc->filename != NULL)
1122     {
1123       if (NULL != dc->handle)
1124         GNUNET_DISK_file_close (dc->handle);
1125       if ( (dc->completed != dc->length) &&
1126            (GNUNET_YES == do_delete) )
1127         {
1128           if (0 != UNLINK (dc->filename))
1129             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1130                                       "unlink",
1131                                       dc->filename);
1132         }
1133       GNUNET_free (dc->filename);
1134     }
1135   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
1136   GNUNET_FS_uri_destroy (dc->uri);
1137   GNUNET_free (dc);
1138 }
1139
1140 /* end of fs_download.c */