fixing drq code
[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_NO
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 level "i"? */
69   uint64_t loff; /* where do IBlocks for level "i" start? */
70   unsigned int ioff; /* which IBlock corresponds to "off" at level "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 level 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  * Process a download result.
307  *
308  * @param dc our download context
309  * @param type type of the result
310  * @param data the (encrypted) response
311  * @param size size of data
312  */
313 static void
314 process_result (struct GNUNET_FS_DownloadContext *dc,
315                 uint32_t type,
316                 const void *data,
317                 size_t size)
318 {
319   struct GNUNET_FS_ProgressInfo pi;
320   GNUNET_HashCode query;
321   struct DownloadRequest *sm;
322   struct GNUNET_CRYPTO_AesSessionKey skey;
323   struct GNUNET_CRYPTO_AesInitializationVector iv;
324   char pt[size];
325   uint64_t off;
326   size_t app;
327   int i;
328   struct ContentHashKey *chk;
329   char *emsg;
330
331
332   GNUNET_CRYPTO_hash (data, size, &query);
333 #if DEBUG_DOWNLOAD
334   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
335               "Received result for query `%s' from `%s'-service\n",
336               GNUNET_h2s (&query),
337               "FS");
338 #endif
339   sm = GNUNET_CONTAINER_multihashmap_get (dc->active,
340                                           &query);
341   if (NULL == sm)
342     {
343       GNUNET_break (0);
344       return;
345     }
346   if (size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
347                                     dc->treedepth,
348                                     sm->offset,
349                                     sm->depth))
350     {
351 #if DEBUG_DOWNLOAD
352       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
353                   "Internal error or bogus download URI (expected %u bytes, got %u)\n",
354                   calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
355                                         dc->treedepth,
356                                         sm->offset,
357                                         sm->depth),
358                   size);
359 #endif
360       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
361       /* signal error */
362       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
363       make_download_status (&pi, dc);
364       pi.value.download.specifics.error.message = dc->emsg;
365       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
366                                      &pi);
367       /* abort all pending requests */
368       if (NULL != dc->th)
369         {
370           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
371           dc->th = NULL;
372         }
373       GNUNET_CLIENT_disconnect (dc->client);
374       dc->client = NULL;
375       return;
376     }
377   GNUNET_assert (GNUNET_YES ==
378                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
379                                                        &query,
380                                                        sm));
381   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
382   GNUNET_CRYPTO_aes_decrypt (data,
383                              size,
384                              &skey,
385                              &iv,
386                              pt);
387   /* save to disk */
388   if ( (NULL != dc->handle) &&
389        ( (sm->depth == dc->treedepth) ||
390          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
391     {
392       off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
393                                  sm->offset,
394                                  sm->depth,
395                                  dc->treedepth);
396       emsg = NULL;
397 #if DEBUG_DOWNLOAD
398       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
399                   "Saving decrypted block to disk at offset %llu\n",
400                   (unsigned long long) off);
401 #endif
402       if ( (off  != 
403             GNUNET_DISK_file_seek (dc->handle,
404                                    off,
405                                    GNUNET_DISK_SEEK_SET) ) )
406         GNUNET_asprintf (&emsg,
407                          _("Failed to seek to offset %llu in file `%s': %s\n"),
408                          (unsigned long long) off,
409                          dc->filename,
410                          STRERROR (errno));
411       else if (size !=
412                GNUNET_DISK_file_write (dc->handle,
413                                        pt,
414                                        size))
415         GNUNET_asprintf (&emsg,
416                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
417                          (unsigned int) size,
418                          (unsigned long long) off,
419                          dc->filename,
420                          STRERROR (errno));
421       if (NULL != emsg)
422         {
423           dc->emsg = emsg;
424           // FIXME: make persistent
425
426           /* signal error */
427           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
428           make_download_status (&pi, dc);
429           pi.value.download.specifics.error.message = emsg;
430           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
431                                          &pi);
432
433           /* abort all pending requests */
434           if (NULL != dc->th)
435             {
436               GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
437               dc->th = NULL;
438             }
439           GNUNET_CLIENT_disconnect (dc->client);
440           dc->client = NULL;
441           GNUNET_free (sm);
442           return;
443         }
444     }
445   if (sm->depth == dc->treedepth) 
446     {
447       app = size;
448       if (sm->offset < dc->offset)
449         {
450           /* starting offset begins in the middle of pt,
451              do not count first bytes as progress */
452           GNUNET_assert (app > (dc->offset - sm->offset));
453           app -= (dc->offset - sm->offset);       
454         }
455       if (sm->offset + size > dc->offset + dc->length)
456         {
457           /* end of block is after relevant range,
458              do not count last bytes as progress */
459           GNUNET_assert (app > (sm->offset + size) - (dc->offset + dc->length));
460           app -= (sm->offset + size) - (dc->offset + dc->length);
461         }
462       dc->completed += app;
463     }
464
465   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
466   make_download_status (&pi, dc);
467   pi.value.download.specifics.progress.data = pt;
468   pi.value.download.specifics.progress.offset = sm->offset;
469   pi.value.download.specifics.progress.data_len = size;
470   pi.value.download.specifics.progress.depth = sm->depth;
471   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
472                                  &pi);
473   GNUNET_assert (dc->completed <= dc->length);
474   if (dc->completed == dc->length)
475     {
476 #if DEBUG_DOWNLOAD
477       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
478                   "Download completed, truncating file to desired length %llu\n",
479                   (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
480 #endif
481       /* truncate file to size (since we store IBlocks at the end) */
482       if (dc->handle != NULL)
483         {
484           GNUNET_DISK_file_close (dc->handle);
485           dc->handle = NULL;
486           if (0 != truncate (dc->filename,
487                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
488             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
489                                       "truncate",
490                                       dc->filename);
491         }
492       /* signal completion */
493       pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
494       make_download_status (&pi, dc);
495       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
496                                      &pi);
497       GNUNET_assert (sm->depth == dc->treedepth);
498     }
499   // FIXME: make persistent
500   if (sm->depth == dc->treedepth) 
501     {
502       GNUNET_free (sm);      
503       return;
504     }
505 #if DEBUG_DOWNLOAD
506   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
507               "Triggering downloads of children (this block was at level %u and offset %llu)\n",
508               sm->depth,
509               (unsigned long long) sm->offset);
510 #endif
511   GNUNET_assert (0 == (size % sizeof(struct ContentHashKey)));
512   chk = (struct ContentHashKey*) pt;
513   for (i=(size / sizeof(struct ContentHashKey))-1;i>=0;i--)
514     {
515       off = compute_dblock_offset (sm->offset,
516                                    sm->depth,
517                                    dc->treedepth,
518                                    i);
519       if ( (off + DBLOCK_SIZE >= dc->offset) &&
520            (off < dc->offset + dc->length) ) 
521         schedule_block_download (dc,
522                                  &chk[i],
523                                  off,
524                                  sm->depth + 1);
525     }
526   GNUNET_free (sm);
527 }
528
529
530 /**
531  * Type of a function to call when we receive a message
532  * from the service.
533  *
534  * @param cls closure
535  * @param msg message received, NULL on timeout or fatal error
536  */
537 static void 
538 receive_results (void *cls,
539                  const struct GNUNET_MessageHeader * msg)
540 {
541   struct GNUNET_FS_DownloadContext *dc = cls;
542   const struct ContentMessage *cm;
543   uint16_t msize;
544
545   if ( (NULL == msg) ||
546        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_CONTENT) ||
547        (ntohs (msg->size) <= sizeof (struct ContentMessage)) )
548     {
549       try_reconnect (dc);
550       return;
551     }
552   msize = ntohs (msg->size);
553   cm = (const struct ContentMessage*) msg;
554   process_result (dc, 
555                   ntohl (cm->type),
556                   &cm[1],
557                   msize - sizeof (struct ContentMessage));
558   if (dc->client == NULL)
559     return; /* fatal error */
560   /* continue receiving */
561   GNUNET_CLIENT_receive (dc->client,
562                          &receive_results,
563                          dc,
564                          GNUNET_TIME_UNIT_FOREVER_REL);
565 }
566
567
568
569 /**
570  * We're ready to transmit a search request to the
571  * file-sharing service.  Do it.  If there is 
572  * more than one request pending, try to send 
573  * multiple or request another transmission.
574  *
575  * @param cls closure
576  * @param size number of bytes available in buf
577  * @param buf where the callee should write the message
578  * @return number of bytes written to buf
579  */
580 static size_t
581 transmit_download_request (void *cls,
582                            size_t size, 
583                            void *buf)
584 {
585   struct GNUNET_FS_DownloadContext *dc = cls;
586   size_t msize;
587   struct SearchMessage *sm;
588
589   dc->th = NULL;
590   if (NULL == buf)
591     {
592       try_reconnect (dc);
593       return 0;
594     }
595   GNUNET_assert (size >= sizeof (struct SearchMessage));
596   msize = 0;
597   sm = buf;
598   while ( (dc->pending != NULL) &&
599           (size > msize + sizeof (struct SearchMessage)) )
600     {
601 #if DEBUG_DOWNLOAD
602       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
603                   "Transmitting download request for `%s' to `%s'-service\n",
604                   GNUNET_h2s (&dc->pending->chk.query),
605                   "FS");
606 #endif
607       memset (sm, 0, sizeof (struct SearchMessage));
608       sm->header.size = htons (sizeof (struct SearchMessage));
609       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
610       sm->anonymity_level = htonl (dc->anonymity);
611       sm->target = dc->target.hashPubKey;
612       sm->query = dc->pending->chk.query;
613       dc->pending->is_pending = GNUNET_NO;
614       dc->pending = dc->pending->next;
615       msize += sizeof (struct SearchMessage);
616       sm++;
617     }
618   if (dc->pending != NULL)
619     dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
620                                                   sizeof (struct SearchMessage),
621                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT,
622                                                   GNUNET_NO,
623                                                   &transmit_download_request,
624                                                   dc); 
625   return msize;
626 }
627
628
629 /**
630  * Reconnect to the FS service and transmit
631  * our queries NOW.
632  *
633  * @param cls our download context
634  * @param tc unused
635  */
636 static void
637 do_reconnect (void *cls,
638               const struct GNUNET_SCHEDULER_TaskContext *tc)
639 {
640   struct GNUNET_FS_DownloadContext *dc = cls;
641   struct GNUNET_CLIENT_Connection *client;
642   
643   dc->task = GNUNET_SCHEDULER_NO_TASK;
644   client = GNUNET_CLIENT_connect (dc->h->sched,
645                                   "fs",
646                                   dc->h->cfg);
647   if (NULL == client)
648     {
649       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
650                   "Connecting to `%s'-service failed, will try again.\n",
651                   "FS");
652       try_reconnect (dc);
653       return;
654     }
655   dc->client = client;
656   dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
657                                                 sizeof (struct SearchMessage),
658                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
659                                                 GNUNET_NO,
660                                                 &transmit_download_request,
661                                                 dc);  
662   GNUNET_CLIENT_receive (client,
663                          &receive_results,
664                          dc,
665                          GNUNET_TIME_UNIT_FOREVER_REL);
666 }
667
668
669 /**
670  * Add entries that are not yet pending back to the pending list.
671  *
672  * @param cls our download context
673  * @param key unused
674  * @param entry entry of type "struct DownloadRequest"
675  * @return GNUNET_OK
676  */
677 static int
678 retry_entry (void *cls,
679              const GNUNET_HashCode *key,
680              void *entry)
681 {
682   struct GNUNET_FS_DownloadContext *dc = cls;
683   struct DownloadRequest *dr = entry;
684
685   if (! dr->is_pending)
686     {
687       dr->next = dc->pending;
688       dr->is_pending = GNUNET_YES;
689       dc->pending = entry;
690     }
691   return GNUNET_OK;
692 }
693
694
695 /**
696  * We've lost our connection with the FS service.
697  * Re-establish it and re-transmit all of our
698  * pending requests.
699  *
700  * @param dc download context that is having trouble
701  */
702 static void
703 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
704 {
705   
706   if (NULL != dc->client)
707     {
708       if (NULL != dc->th)
709         {
710           GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
711           dc->th = NULL;
712         }
713       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
714                                              &retry_entry,
715                                              dc);
716       GNUNET_CLIENT_disconnect (dc->client);
717       dc->client = NULL;
718     }
719   dc->task
720     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
721                                     GNUNET_TIME_UNIT_SECONDS,
722                                     &do_reconnect,
723                                     dc);
724 }
725
726
727 /**
728  * Download parts of a file.  Note that this will store
729  * the blocks at the respective offset in the given file.  Also, the
730  * download is still using the blocking of the underlying FS
731  * encoding.  As a result, the download may *write* outside of the
732  * given boundaries (if offset and length do not match the 32k FS
733  * block boundaries). <p>
734  *
735  * This function should be used to focus a download towards a
736  * particular portion of the file (optimization), not to strictly
737  * limit the download to exactly those bytes.
738  *
739  * @param h handle to the file sharing subsystem
740  * @param uri the URI of the file (determines what to download); CHK or LOC URI
741  * @param meta known metadata for the file (can be NULL)
742  * @param filename where to store the file, maybe NULL (then no file is
743  *        created on disk and data must be grabbed from the callbacks)
744  * @param offset at what offset should we start the download (typically 0)
745  * @param length how many bytes should be downloaded starting at offset
746  * @param anonymity anonymity level to use for the download
747  * @param options various options
748  * @param cctx initial value for the client context for this download
749  * @param parent parent download to associate this download with (use NULL
750  *        for top-level downloads; useful for manually-triggered recursive downloads)
751  * @return context that can be used to control this download
752  */
753 struct GNUNET_FS_DownloadContext *
754 GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
755                           const struct GNUNET_FS_Uri *uri,
756                           const struct GNUNET_CONTAINER_MetaData *meta,
757                           const char *filename,
758                           uint64_t offset,
759                           uint64_t length,
760                           uint32_t anonymity,
761                           enum GNUNET_FS_DownloadOptions options,
762                           void *cctx,
763                           struct GNUNET_FS_DownloadContext *parent)
764 {
765   struct GNUNET_FS_ProgressInfo pi;
766   struct GNUNET_FS_DownloadContext *dc;
767   struct GNUNET_CLIENT_Connection *client;
768
769   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
770   if ( (offset + length < offset) ||
771        (offset + length > uri->data.chk.file_length) )
772     {      
773       GNUNET_break (0);
774       return NULL;
775     }
776   client = GNUNET_CLIENT_connect (h->sched,
777                                   "fs",
778                                   h->cfg);
779   if (NULL == client)
780     return NULL;
781   // FIXME: add support for "loc" URIs!
782 #if DEBUG_DOWNLOAD
783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
784               "Starting download `%s' of %llu bytes\n",
785               filename,
786               (unsigned long long) length);
787 #endif
788   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
789   dc->h = h;
790   dc->client = client;
791   dc->parent = parent;
792   dc->uri = GNUNET_FS_uri_dup (uri);
793   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
794   dc->client_info = cctx;
795   if (NULL != filename)
796     {
797       dc->filename = GNUNET_strdup (filename);
798       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
799         GNUNET_DISK_file_size (filename,
800                                &dc->old_file_size,
801                                GNUNET_YES);
802       dc->handle = GNUNET_DISK_file_open (filename, 
803                                           GNUNET_DISK_OPEN_READWRITE | 
804                                           GNUNET_DISK_OPEN_CREATE,
805                                           GNUNET_DISK_PERM_USER_READ |
806                                           GNUNET_DISK_PERM_USER_WRITE |
807                                           GNUNET_DISK_PERM_GROUP_READ |
808                                           GNUNET_DISK_PERM_OTHER_READ);
809       if (dc->handle == NULL)
810         {
811           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
812                       _("Download failed: could not open file `%s': %s\n"),
813                       dc->filename,
814                       STRERROR (errno));
815           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
816           GNUNET_FS_uri_destroy (dc->uri);
817           GNUNET_free (dc->filename);
818           GNUNET_CLIENT_disconnect (dc->client);
819           GNUNET_free (dc);
820           return NULL;
821         }
822     }
823   // FIXME: set "dc->target" for LOC uris!
824   dc->offset = offset;
825   dc->length = length;
826   dc->anonymity = anonymity;
827   dc->options = options;
828   dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
829   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
830 #if DEBUG_DOWNLOAD
831   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832               "Download tree has depth %u\n",
833               dc->treedepth);
834 #endif
835   // FIXME: make persistent
836   schedule_block_download (dc, 
837                            &dc->uri->data.chk.chk,
838                            0, 
839                            1 /* 0 == CHK, 1 == top */);
840   GNUNET_CLIENT_receive (client,
841                          &receive_results,
842                          dc,
843                          GNUNET_TIME_UNIT_FOREVER_REL);
844   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
845   make_download_status (&pi, dc);
846   pi.value.download.specifics.start.meta = meta;
847   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
848                                  &pi);
849
850   return dc;
851 }
852
853
854 /**
855  * Free entries in the map.
856  *
857  * @param cls unused (NULL)
858  * @param key unused
859  * @param entry entry of type "struct DownloadRequest" which is freed
860  * @return GNUNET_OK
861  */
862 static int
863 free_entry (void *cls,
864             const GNUNET_HashCode *key,
865             void *entry)
866 {
867   GNUNET_free (entry);
868   return GNUNET_OK;
869 }
870
871
872 /**
873  * Stop a download (aborts if download is incomplete).
874  *
875  * @param dc handle for the download
876  * @param do_delete delete files of incomplete downloads
877  */
878 void
879 GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
880                          int do_delete)
881 {
882   struct GNUNET_FS_ProgressInfo pi;
883
884   // FIXME: make unpersistent  
885   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
886   make_download_status (&pi, dc);
887   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
888                                  &pi);
889
890   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
891     GNUNET_SCHEDULER_cancel (dc->h->sched,
892                              dc->task);
893   if (NULL != dc->th)
894     {
895       GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
896       dc->th = NULL;
897     }
898   if (NULL != dc->client)
899     GNUNET_CLIENT_disconnect (dc->client);
900   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
901                                          &free_entry,
902                                          NULL);
903   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
904   if (dc->filename != NULL)
905     {
906       if (NULL != dc->handle)
907         GNUNET_DISK_file_close (dc->handle);
908       if ( (dc->completed != dc->length) &&
909            (GNUNET_YES == do_delete) )
910         {
911           if (0 != UNLINK (dc->filename))
912             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
913                                       "unlink",
914                                       dc->filename);
915         }
916       GNUNET_free (dc->filename);
917     }
918   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
919   GNUNET_FS_uri_destroy (dc->uri);
920   GNUNET_free (dc);
921 }
922
923
924
925 #if 0
926
927
928 /**
929  * Check if self block is already present on the drive.  If the block
930  * is a dblock and present, the ProgressModel is notified. If the
931  * block is present and it is an iblock, downloading the children is
932  * triggered.
933  *
934  * Also checks if the block is within the range of blocks
935  * that we are supposed to download.  If not, the method
936  * returns as if the block is present but does NOT signal
937  * progress.
938  *
939  * @param node that is checked for presence
940  * @return GNUNET_YES if present, GNUNET_NO if not.
941  */
942 static int
943 check_node_present (const struct Node *node)
944 {
945   int res;
946   int ret;
947   char *data;
948   unsigned int size;
949   GNUNET_HashCode hc;
950
951   size = get_node_size (node);
952   /* first check if node is within range.
953      For now, keeping it simple, we only do
954      this for level-0 nodes */
955   if ((node->level == 0) &&
956       ((node->offset + size < node->ctx->offset) ||
957        (node->offset >= node->ctx->offset + node->ctx->length)))
958     return GNUNET_YES;
959   data = GNUNET_malloc (size);
960   ret = GNUNET_NO;
961   res = read_from_files (node->ctx, node->level, node->offset, data, size);
962   if (res == size)
963     {
964       GNUNET_hash (data, size, &hc);
965       if (0 == memcmp (&hc, &node->chk.key, sizeof (GNUNET_HashCode)))
966         {
967           notify_client_about_progress (node, data, size);
968           if (node->level > 0)
969             iblock_download_children (node, data, size);
970           ret = GNUNET_YES;
971         }
972     }
973   GNUNET_free (data);
974   return ret;
975 }
976
977 #endif
978
979
980 /* end of fs_download.c */