avoid tracking requests twice if multiple blocks in the same file are identical
[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 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @file fs/fs_download.c
22  * @brief download methods
23  * @author Christian Grothoff
24  *
25  * TODO:
26  * - location URI suppport (can wait, easy)
27  * - check if blocks exist already (can wait, easy)
28  * - handle recursive downloads (need directory & 
29  *   fs-level download-parallelism management, can wait)
30  * - check if iblocks can be computed from existing blocks (can wait, hard)
31  * - persistence (can wait)
32  */
33 #include "platform.h"
34 #include "gnunet_constants.h"
35 #include "gnunet_fs_service.h"
36 #include "fs.h"
37 #include "fs_tree.h"
38
39 #define DEBUG_DOWNLOAD GNUNET_YES
40
41 /**
42  * We're storing the IBLOCKS after the
43  * DBLOCKS on disk (so that we only have
44  * to truncate the file once we're done).
45  *
46  * Given the offset of a block (with respect
47  * to the DBLOCKS) and its depth, return the
48  * offset where we would store this block
49  * in the file.
50
51  * 
52  * @param fsize overall file size
53  * @param off offset of the block in the file
54  * @param depth depth of the block in the tree
55  * @param treedepth maximum depth of the tree
56  * @return off for DBLOCKS (depth == treedepth),
57  *         otherwise an offset past the end
58  *         of the file that does not overlap
59  *         with the range for any other block
60  */
61 static uint64_t
62 compute_disk_offset (uint64_t fsize,
63                      uint64_t off,
64                      unsigned int depth,
65                      unsigned int treedepth)
66 {
67   unsigned int i;
68   uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
69   uint64_t loff; /* where do IBlocks for depth "i" start? */
70   unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
71   
72   if (depth == treedepth)
73     return off;
74   /* first IBlocks start at the end of file, rounded up
75      to full DBLOCK_SIZE */
76   loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
77   lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
78   GNUNET_assert (0 == (off % DBLOCK_SIZE));
79   ioff = (off / DBLOCK_SIZE);
80   for (i=treedepth-1;i>depth;i--)
81     {
82       loff += lsize;
83       lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
84       GNUNET_assert (lsize > 0);
85       GNUNET_assert (0 == (ioff % CHK_PER_INODE));
86       ioff /= CHK_PER_INODE;
87     }
88   return loff + ioff * sizeof (struct ContentHashKey);
89 }
90
91
92 /**
93  * Given a file of the specified treedepth and a block at the given
94  * offset and depth, calculate the offset for the CHK at the given
95  * index.
96  *
97  * @param offset the offset of the first
98  *        DBLOCK in the subtree of the 
99  *        identified IBLOCK
100  * @param depth the depth of the IBLOCK in the tree
101  * @param treedepth overall depth of the tree
102  * @param k which CHK in the IBLOCK are we 
103  *        talking about
104  * @return offset if k=0, otherwise an appropriately
105  *         larger value (i.e., if depth = treedepth-1,
106  *         the returned value should be offset+DBLOCK_SIZE)
107  */
108 static uint64_t
109 compute_dblock_offset (uint64_t offset,
110                        unsigned int depth,
111                        unsigned int treedepth,
112                        unsigned int k)
113 {
114   unsigned int i;
115   uint64_t lsize; /* what is the size of the sum of all DBlocks 
116                      that a CHK at depth i corresponds to? */
117
118   if (depth == treedepth)
119     return offset;
120   lsize = DBLOCK_SIZE;
121   for (i=treedepth-1;i>depth;i--)
122     lsize *= CHK_PER_INODE;
123   return offset + k * lsize;
124 }
125
126
127 /**
128  * Fill in all of the generic fields for 
129  * a download event.
130  *
131  * @param pi structure to fill in
132  * @param dc overall download context
133  */
134 static void
135 make_download_status (struct GNUNET_FS_ProgressInfo *pi,
136                       struct GNUNET_FS_DownloadContext *dc)
137 {
138   pi->value.download.dc = dc;
139   pi->value.download.cctx
140     = dc->client_info;
141   pi->value.download.pctx
142     = (dc->parent == NULL) ? NULL : dc->parent->client_info;
143   pi->value.download.uri 
144     = dc->uri;
145   pi->value.download.filename
146     = dc->filename;
147   pi->value.download.size
148     = dc->length;
149   pi->value.download.duration
150     = GNUNET_TIME_absolute_get_duration (dc->start_time);
151   pi->value.download.completed
152     = dc->completed;
153   pi->value.download.anonymity
154     = dc->anonymity;
155 }
156
157 /**
158  * We're ready to transmit a search request to the
159  * file-sharing service.  Do it.  If there is 
160  * more than one request pending, try to send 
161  * multiple or request another transmission.
162  *
163  * @param cls closure
164  * @param size number of bytes available in buf
165  * @param buf where the callee should write the message
166  * @return number of bytes written to buf
167  */
168 static size_t
169 transmit_download_request (void *cls,
170                            size_t size, 
171                            void *buf);
172
173
174 /**
175  * Schedule the download of the specified
176  * block in the tree.
177  *
178  * @param dc overall download this block belongs to
179  * @param chk content-hash-key of the block
180  * @param offset offset of the block in the file
181  *         (for IBlocks, the offset is the lowest
182  *          offset of any DBlock in the subtree under
183  *          the IBlock)
184  * @param depth depth of the block, 0 is the root of the tree
185  */
186 static void
187 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
188                          const struct ContentHashKey *chk,
189                          uint64_t offset,
190                          unsigned int depth)
191 {
192   struct DownloadRequest *sm;
193   uint64_t off;
194
195 #if DEBUG_DOWNLOAD
196   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
197               "Scheduling download at offset %llu and depth %u for `%s'\n",
198               (unsigned long long) offset,
199               depth,
200               GNUNET_h2s (&chk->query));
201 #endif
202   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
203                              offset,
204                              depth,
205                              dc->treedepth);
206   if ( (dc->old_file_size > off) &&
207        (dc->handle != NULL) &&
208        (off  == 
209         GNUNET_DISK_file_seek (dc->handle,
210                                off,
211                                GNUNET_DISK_SEEK_SET) ) )
212     {
213       // FIXME: check if block exists on disk!
214       // (read block, encode, compare with
215       // query; if matches, simply return)
216     }
217   if (depth < dc->treedepth)
218     {
219       // FIXME: try if we could
220       // reconstitute this IBLOCK
221       // from the existing blocks on disk (can wait)
222       // (read block(s), encode, compare with
223       // query; if matches, simply return)
224     }
225   sm = GNUNET_malloc (sizeof (struct DownloadRequest));
226   sm->chk = *chk;
227   sm->offset = offset;
228   sm->depth = depth;
229   sm->is_pending = GNUNET_YES;
230   sm->next = dc->pending;
231   dc->pending = sm;
232   GNUNET_CONTAINER_multihashmap_put (dc->active,
233                                      &chk->query,
234                                      sm,
235                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
236
237   if ( (dc->th == NULL) &&
238        (dc->client != NULL) )
239     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
240                                                   sizeof (struct SearchMessage),
241                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
242                                                   GNUNET_NO,
243                                                   &transmit_download_request,
244                                                   dc); 
245
246 }
247
248
249 /**
250  * We've lost our connection with the FS service.
251  * Re-establish it and re-transmit all of our
252  * pending requests.
253  *
254  * @param dc download context that is having trouble
255  */
256 static void
257 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
258
259
260 /**
261  * Compute how many bytes of data should be stored in
262  * the specified node.
263  *
264  * @param fsize overall file size
265  * @param totaldepth depth of the entire tree
266  * @param offset offset of the node
267  * @param depth depth of the node
268  * @return number of bytes stored in this node
269  */
270 static size_t
271 calculate_block_size (uint64_t fsize,
272                       unsigned int totaldepth,
273                       uint64_t offset,
274                       unsigned int depth)
275 {
276   unsigned int i;
277   size_t ret;
278   uint64_t rsize;
279   uint64_t epos;
280   unsigned int chks;
281
282   GNUNET_assert (offset < fsize);
283   if (depth == totaldepth)
284     {
285       ret = DBLOCK_SIZE;
286       if (offset + ret > fsize)
287         ret = (size_t) (fsize - offset);
288       return ret;
289     }
290
291   rsize = DBLOCK_SIZE;
292   for (i = totaldepth-1; i > depth; i--)
293     rsize *= CHK_PER_INODE;
294   epos = offset + rsize * CHK_PER_INODE;
295   GNUNET_assert (epos > offset);
296   if (epos > fsize)
297     epos = fsize;
298   /* round up when computing #CHKs in our IBlock */
299   chks = (epos - offset + rsize - 1) / rsize;
300   GNUNET_assert (chks <= CHK_PER_INODE);
301   return chks * sizeof (struct ContentHashKey);
302 }
303
304
305 /**
306  * Closure for iterator processing results.
307  */
308 struct ProcessResultClosure
309 {
310   
311   /**
312    * Hash of data.
313    */
314   GNUNET_HashCode query;
315
316   /**
317    * Data found in P2P network.
318    */ 
319   const void *data;
320
321   /**
322    * Our download context.
323    */
324   struct GNUNET_FS_DownloadContext *dc;
325                 
326   /**
327    * Number of bytes in data.
328    */
329   size_t size;
330
331   /**
332    * Type of data.
333    */
334   uint32_t type;
335   
336 };
337
338
339 /**
340  * Iterator over entries in the pending requests in the 'active' map for the
341  * reply that we just got.
342  *
343  * @param cls closure (our 'struct ProcessResultClosure')
344  * @param value value in the hash map (a 'struct DownloadRequest')
345  * @return GNUNET_YES (we should continue to iterate); unless serious error
346  */
347 static int
348 process_result_with_request (void *cls,
349                              const GNUNET_HashCode * key,
350                              void *value)
351 {
352   struct ProcessResultClosure *prc = cls;
353   struct DownloadRequest *sm = value;
354   struct GNUNET_FS_DownloadContext *dc = prc->dc;
355   struct GNUNET_CRYPTO_AesSessionKey skey;
356   struct GNUNET_CRYPTO_AesInitializationVector iv;
357   char pt[prc->size];
358   struct GNUNET_FS_ProgressInfo pi;
359   uint64_t off;
360   size_t app;
361   int i;
362   struct ContentHashKey *chk;
363   char *emsg;
364
365   if (prc->size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
366                                          dc->treedepth,
367                                          sm->offset,
368                                          sm->depth))
369     {
370 #if DEBUG_DOWNLOAD
371       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
372                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
373                   calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
374                                         dc->treedepth,
375                                         sm->offset,
376                                         sm->depth),
377                   prc->size);
378 #endif
379       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
380       /* signal error */
381       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
382       make_download_status (&pi, dc);
383       pi.value.download.specifics.error.message = dc->emsg;
384       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
385                                      &pi);
386       /* abort all pending requests */
387       if (NULL != dc->th)
388         {
389           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
390           dc->th = NULL;
391         }
392       GNUNET_CLIENT_disconnect (dc->client);
393       dc->client = NULL;
394       return GNUNET_NO;
395     }
396   GNUNET_assert (GNUNET_YES ==
397                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
398                                                        &prc->query,
399                                                        sm));
400   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
401   GNUNET_CRYPTO_aes_decrypt (prc->data,
402                              prc->size,
403                              &skey,
404                              &iv,
405                              pt);
406   /* save to disk */
407   if ( (NULL != dc->handle) &&
408        ( (sm->depth == dc->treedepth) ||
409          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
410     {
411       off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
412                                  sm->offset,
413                                  sm->depth,
414                                  dc->treedepth);
415       emsg = NULL;
416 #if DEBUG_DOWNLOAD
417       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
418                   "Saving decrypted block to disk at offset %llu\n",
419                   (unsigned long long) off);
420 #endif
421       if ( (off  != 
422             GNUNET_DISK_file_seek (dc->handle,
423                                    off,
424                                    GNUNET_DISK_SEEK_SET) ) )
425         GNUNET_asprintf (&emsg,
426                          _("Failed to seek to offset %llu in file `%s': %s\n"),
427                          (unsigned long long) off,
428                          dc->filename,
429                          STRERROR (errno));
430       else if (prc->size !=
431                GNUNET_DISK_file_write (dc->handle,
432                                        pt,
433                                        prc->size))
434         GNUNET_asprintf (&emsg,
435                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
436                          (unsigned int) prc->size,
437                          (unsigned long long) off,
438                          dc->filename,
439                          STRERROR (errno));
440       if (NULL != emsg)
441         {
442           dc->emsg = emsg;
443           // FIXME: make persistent
444
445           /* signal error */
446           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
447           make_download_status (&pi, dc);
448           pi.value.download.specifics.error.message = emsg;
449           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
450                                          &pi);
451
452           /* abort all pending requests */
453           if (NULL != dc->th)
454             {
455               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
456               dc->th = NULL;
457             }
458           GNUNET_CLIENT_disconnect (dc->client);
459           dc->client = NULL;
460           GNUNET_free (sm);
461           return GNUNET_NO;
462         }
463     }
464   if (sm->depth == dc->treedepth) 
465     {
466       app = prc->size;
467       if (sm->offset < dc->offset)
468         {
469           /* starting offset begins in the middle of pt,
470              do not count first bytes as progress */
471           GNUNET_assert (app > (dc->offset - sm->offset));
472           app -= (dc->offset - sm->offset);       
473         }
474       if (sm->offset + prc->size > dc->offset + dc->length)
475         {
476           /* end of block is after relevant range,
477              do not count last bytes as progress */
478           GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
479           app -= (sm->offset + prc->size) - (dc->offset + dc->length);
480         }
481       dc->completed += app;
482     }
483
484   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
485   make_download_status (&pi, dc);
486   pi.value.download.specifics.progress.data = pt;
487   pi.value.download.specifics.progress.offset = sm->offset;
488   pi.value.download.specifics.progress.data_len = prc->size;
489   pi.value.download.specifics.progress.depth = sm->depth;
490   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
491                                  &pi);
492   GNUNET_assert (dc->completed <= dc->length);
493   if (dc->completed == dc->length)
494     {
495 #if DEBUG_DOWNLOAD
496       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497                   "Download completed, truncating file to desired length %llu\n",
498                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
499 #endif
500       /* truncate file to size (since we store IBlocks at the end) */
501       if (dc->handle != NULL)
502         {
503           GNUNET_DISK_file_close (dc->handle);
504           dc->handle = NULL;
505           if (0 != truncate (dc->filename,
506                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
507             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
508                                       "truncate",
509                                       dc->filename);
510         }
511       /* signal completion */
512       pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
513       make_download_status (&pi, dc);
514       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
515                                      &pi);
516       GNUNET_assert (sm->depth == dc->treedepth);
517     }
518   // FIXME: make persistent
519   if (sm->depth == dc->treedepth) 
520     {
521       GNUNET_free (sm);      
522       return GNUNET_YES;
523     }
524 #if DEBUG_DOWNLOAD
525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
526               "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
527               sm->depth,
528               (unsigned long long) sm->offset);
529 #endif
530   GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
531   chk = (struct ContentHashKey*) pt;
532   for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
533     {
534       off = compute_dblock_offset (sm->offset,
535                                    sm->depth,
536                                    dc->treedepth,
537                                    i);
538       if ( (off + DBLOCK_SIZE >= dc->offset) &&
539            (off < dc->offset + dc->length) ) 
540         schedule_block_download (dc,
541                                  &chk[i],
542                                  off,
543                                  sm->depth + 1);
544     }
545   GNUNET_free (sm);
546   return GNUNET_YES;
547 }
548
549
550 /**
551  * Process a download result.
552  *
553  * @param dc our download context
554  * @param type type of the result
555  * @param data the (encrypted) response
556  * @param size size of data
557  */
558 static void
559 process_result (struct GNUNET_FS_DownloadContext *dc,
560                 uint32_t type,
561                 const void *data,
562                 size_t size)
563 {
564   struct ProcessResultClosure prc;
565
566   prc.dc = dc;
567   prc.data = data;
568   prc.size = size;
569   prc.type = type;
570   GNUNET_CRYPTO_hash (data, size, &prc.query);
571 #if DEBUG_DOWNLOAD
572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
573               "Received result for query `%s' from `%s'-service\n",
574               GNUNET_h2s (&prc.query),
575               "FS");
576 #endif
577   GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
578                                               &prc.query,
579                                               &process_result_with_request,
580                                               &prc);
581 }
582
583
584 /**
585  * Type of a function to call when we receive a message
586  * from the service.
587  *
588  * @param cls closure
589  * @param msg message received, NULL on timeout or fatal error
590  */
591 static void 
592 receive_results (void *cls,
593                  const struct GNUNET_MessageHeader * msg)
594 {
595   struct GNUNET_FS_DownloadContext *dc = cls;
596   const struct PutMessage *cm;
597   uint16_t msize;
598
599   if ( (NULL == msg) ||
600        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
601        (sizeof (struct PutMessage) > ntohs(msg->size)) )
602     {
603       GNUNET_break (msg == NULL);       
604       try_reconnect (dc);
605       return;
606     }
607   msize = ntohs(msg->size);
608   cm = (const struct PutMessage*) msg;
609   process_result (dc, 
610                   ntohl (cm->type),
611                   &cm[1],
612                   msize - sizeof (struct PutMessage));
613   if (dc->client == NULL)
614     return; /* fatal error */
615   /* continue receiving */
616   GNUNET_CLIENT_receive (dc->client,
617                          &receive_results,
618                          dc,
619                          GNUNET_TIME_UNIT_FOREVER_REL);
620 }
621
622
623
624 /**
625  * We're ready to transmit a search request to the
626  * file-sharing service.  Do it.  If there is 
627  * more than one request pending, try to send 
628  * multiple or request another transmission.
629  *
630  * @param cls closure
631  * @param size number of bytes available in buf
632  * @param buf where the callee should write the message
633  * @return number of bytes written to buf
634  */
635 static size_t
636 transmit_download_request (void *cls,
637                            size_t size, 
638                            void *buf)
639 {
640   struct GNUNET_FS_DownloadContext *dc = cls;
641   size_t msize;
642   struct SearchMessage *sm;
643
644   dc->th = NULL;
645   if (NULL == buf)
646     {
647       try_reconnect (dc);
648       return 0;
649     }
650   GNUNET_assert (size >= sizeof (struct SearchMessage));
651   msize = 0;
652   sm = buf;
653   while ( (dc->pending != NULL) &&
654           (size > msize + sizeof (struct SearchMessage)) )
655     {
656 #if DEBUG_DOWNLOAD
657       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
658                   "Transmitting download request for `%s' to `%s'-service\n",
659                   GNUNET_h2s (&dc->pending->chk.query),
660                   "FS");
661 #endif
662       memset (sm, 0, sizeof (struct SearchMessage));
663       sm->header.size = htons (sizeof (struct SearchMessage));
664       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
665       if (dc->pending->depth == dc->treedepth)
666         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
667       else
668         sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
669       sm->anonymity_level = htonl (dc->anonymity);
670       sm->target = dc->target.hashPubKey;
671       sm->query = dc->pending->chk.query;
672       dc->pending->is_pending = GNUNET_NO;
673       dc->pending = dc->pending->next;
674       msize += sizeof (struct SearchMessage);
675       sm++;
676     }
677   if (dc->pending != NULL)
678     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
679                                                   sizeof (struct SearchMessage),
680                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
681                                                   GNUNET_NO,
682                                                   &transmit_download_request,
683                                                   dc); 
684   return msize;
685 }
686
687
688 /**
689  * Reconnect to the FS service and transmit our queries NOW.
690  *
691  * @param cls our download context
692  * @param tc unused
693  */
694 static void
695 do_reconnect (void *cls,
696               const struct GNUNET_SCHEDULER_TaskContext *tc)
697 {
698   struct GNUNET_FS_DownloadContext *dc = cls;
699   struct GNUNET_CLIENT_Connection *client;
700   
701   dc->task = GNUNET_SCHEDULER_NO_TASK;
702   client = GNUNET_CLIENT_connect (dc->h->sched,
703                                   "fs",
704                                   dc->h->cfg);
705   if (NULL == client)
706     {
707       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
708                   "Connecting to `%s'-service failed, will try again.\n",
709                   "FS");
710       try_reconnect (dc);
711       return;
712     }
713   dc->client = client;
714   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
715                                                 sizeof (struct SearchMessage),
716                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
717                                                 GNUNET_NO,
718                                                 &transmit_download_request,
719                                                 dc);  
720   GNUNET_CLIENT_receive (client,
721                          &receive_results,
722                          dc,
723                          GNUNET_TIME_UNIT_FOREVER_REL);
724 }
725
726
727 /**
728  * Add entries that are not yet pending back to the pending list.
729  *
730  * @param cls our download context
731  * @param key unused
732  * @param entry entry of type "struct DownloadRequest"
733  * @return GNUNET_OK
734  */
735 static int
736 retry_entry (void *cls,
737              const GNUNET_HashCode *key,
738              void *entry)
739 {
740   struct GNUNET_FS_DownloadContext *dc = cls;
741   struct DownloadRequest *dr = entry;
742
743   if (! dr->is_pending)
744     {
745       dr->next = dc->pending;
746       dr->is_pending = GNUNET_YES;
747       dc->pending = entry;
748     }
749   return GNUNET_OK;
750 }
751
752
753 /**
754  * We've lost our connection with the FS service.
755  * Re-establish it and re-transmit all of our
756  * pending requests.
757  *
758  * @param dc download context that is having trouble
759  */
760 static void
761 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
762 {
763   
764   if (NULL != dc->client)
765     {
766       if (NULL != dc->th)
767         {
768           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
769           dc->th = NULL;
770         }
771       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
772                                              &retry_entry,
773                                              dc);
774       GNUNET_CLIENT_disconnect (dc->client);
775       dc->client = NULL;
776     }
777   dc->task
778     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
779                                     GNUNET_TIME_UNIT_SECONDS,
780                                     &do_reconnect,
781                                     dc);
782 }
783
784
785 /**
786  * Download parts of a file.  Note that this will store
787  * the blocks at the respective offset in the given file.  Also, the
788  * download is still using the blocking of the underlying FS
789  * encoding.  As a result, the download may *write* outside of the
790  * given boundaries (if offset and length do not match the 32k FS
791  * block boundaries). <p>
792  *
793  * This function should be used to focus a download towards a
794  * particular portion of the file (optimization), not to strictly
795  * limit the download to exactly those bytes.
796  *
797  * @param h handle to the file sharing subsystem
798  * @param uri the URI of the file (determines what to download); CHK or LOC URI
799  * @param meta known metadata for the file (can be NULL)
800  * @param filename where to store the file, maybe NULL (then no file is
801  *        created on disk and data must be grabbed from the callbacks)
802  * @param offset at what offset should we start the download (typically 0)
803  * @param length how many bytes should be downloaded starting at offset
804  * @param anonymity anonymity level to use for the download
805  * @param options various options
806  * @param cctx initial value for the client context for this download
807  * @param parent parent download to associate this download with (use NULL
808  *        for top-level downloads; useful for manually-triggered recursive downloads)
809  * @return context that can be used to control this download
810  */
811 struct GNUNET_FS_DownloadContext *
812 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
813                           const struct GNUNET_FS_Uri *uri,
814                           const struct GNUNET_CONTAINER_MetaData *meta,
815                           const char *filename,
816                           uint64_t offset,
817                           uint64_t length,
818                           uint32_t anonymity,
819                           enum GNUNET_FS_DownloadOptions options,
820                           void *cctx,
821                           struct GNUNET_FS_DownloadContext *parent)
822 {
823   struct GNUNET_FS_ProgressInfo pi;
824   struct GNUNET_FS_DownloadContext *dc;
825   struct GNUNET_CLIENT_Connection *client;
826
827   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
828   if ( (offset + length < offset) ||
829        (offset + length > uri->data.chk.file_length) )
830     {      
831       GNUNET_break (0);
832       return NULL;
833     }
834   client = GNUNET_CLIENT_connect (h->sched,
835                                   "fs",
836                                   h->cfg);
837   if (NULL == client)
838     return NULL;
839   // FIXME: add support for "loc" URIs!
840 #if DEBUG_DOWNLOAD
841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
842               "Starting download `%s' of %llu bytes\n",
843               filename,
844               (unsigned long long) length);
845 #endif
846   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
847   dc->h = h;
848   dc->client = client;
849   dc->parent = parent;
850   dc->uri = GNUNET_FS_uri_dup (uri);
851   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
852   dc->client_info = cctx;
853   if (NULL != filename)
854     {
855       dc->filename = GNUNET_strdup (filename);
856       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
857         GNUNET_DISK_file_size (filename,
858                                &dc->old_file_size,
859                                GNUNET_YES);
860       dc->handle = GNUNET_DISK_file_open (filename, 
861                                           GNUNET_DISK_OPEN_READWRITE | 
862                                           GNUNET_DISK_OPEN_CREATE,
863                                           GNUNET_DISK_PERM_USER_READ |
864                                           GNUNET_DISK_PERM_USER_WRITE |
865                                           GNUNET_DISK_PERM_GROUP_READ |
866                                           GNUNET_DISK_PERM_OTHER_READ);
867       if (dc->handle == NULL)
868         {
869           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
870                       _("Download failed: could not open file `%s': %s\n"),
871                       dc->filename,
872                       STRERROR (errno));
873           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
874           GNUNET_FS_uri_destroy (dc->uri);
875           GNUNET_free (dc->filename);
876           GNUNET_CLIENT_disconnect (dc->client);
877           GNUNET_free (dc);
878           return NULL;
879         }
880     }
881   // FIXME: set "dc->target" for LOC uris!
882   dc->offset = offset;
883   dc->length = length;
884   dc->anonymity = anonymity;
885   dc->options = options;
886   dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
887   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
888 #if DEBUG_DOWNLOAD
889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
890               "Download tree has depth %u\n",
891               dc->treedepth);
892 #endif
893   // FIXME: make persistent
894   schedule_block_download (dc, 
895                            &dc->uri->data.chk.chk,
896                            0, 
897                            1 /* 0 == CHK, 1 == top */);
898   GNUNET_CLIENT_receive (client,
899                          &receive_results,
900                          dc,
901                          GNUNET_TIME_UNIT_FOREVER_REL);
902   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
903   make_download_status (&pi, dc);
904   pi.value.download.specifics.start.meta = meta;
905   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
906                                  &pi);
907
908   return dc;
909 }
910
911
912 /**
913  * Free entries in the map.
914  *
915  * @param cls unused (NULL)
916  * @param key unused
917  * @param entry entry of type "struct DownloadRequest" which is freed
918  * @return GNUNET_OK
919  */
920 static int
921 free_entry (void *cls,
922             const GNUNET_HashCode *key,
923             void *entry)
924 {
925   GNUNET_free (entry);
926   return GNUNET_OK;
927 }
928
929
930 /**
931  * Stop a download (aborts if download is incomplete).
932  *
933  * @param dc handle for the download
934  * @param do_delete delete files of incomplete downloads
935  */
936 void
937 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
938                          int do_delete)
939 {
940   struct GNUNET_FS_ProgressInfo pi;
941
942   // FIXME: make unpersistent  
943   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
944   make_download_status (&pi, dc);
945   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
946                                  &pi);
947
948   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
949     GNUNET_SCHEDULER_cancel (dc->h->sched,
950                              dc->task);
951   if (NULL != dc->th)
952     {
953       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
954       dc->th = NULL;
955     }
956   if (NULL != dc->client)
957     GNUNET_CLIENT_disconnect (dc->client);
958   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
959                                          &free_entry,
960                                          NULL);
961   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
962   if (dc->filename != NULL)
963     {
964       if (NULL != dc->handle)
965         GNUNET_DISK_file_close (dc->handle);
966       if ( (dc->completed != dc->length) &&
967            (GNUNET_YES == do_delete) )
968         {
969           if (0 != UNLINK (dc->filename))
970             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
971                                       "unlink",
972                                       dc->filename);
973         }
974       GNUNET_free (dc->filename);
975     }
976   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
977   GNUNET_FS_uri_destroy (dc->uri);
978   GNUNET_free (dc);
979 }
980
981 /* end of fs_download.c */