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