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