types
[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 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 + i * lsize;
124 }
125
126
127 /**
128  * Fill in all of the generic fields for 
129  * a download event.
130  *
131  * @param pc 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.length
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 /**
159  * Schedule the download of the specified
160  * block in the tree.
161  *
162  * @param dc overall download this block belongs to
163  * @param chk content-hash-key of the block
164  * @param offset offset of the block in the file
165  *         (for IBlocks, the offset is the lowest
166  *          offset of any DBlock in the subtree under
167  *          the IBlock)
168  * @param depth depth of the block, 0 is the root of the tree
169  */
170 static void
171 schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
172                          const struct ContentHashKey *chk,
173                          uint64_t offset,
174                          unsigned int depth)
175 {
176   struct DownloadRequest *sm;
177   uint64_t off;
178
179   off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
180                              offset,
181                              depth,
182                              dc->treedepth);
183   if ( (dc->old_file_size > off) &&
184        (dc->handle != NULL) &&
185        (off  == 
186         GNUNET_DISK_file_seek (dc->handle,
187                                off,
188                                GNUNET_DISK_SEEK_SET) ) )
189     {
190       // FIXME: check if block exists on disk!
191       // (read block, encode, compare with
192       // query; if matches, simply return)
193     }
194   if (depth < dc->treedepth)
195     {
196       // FIXME: try if we could
197       // reconstitute this IBLOCK
198       // from the existing blocks on disk (can wait)
199       // (read block(s), encode, compare with
200       // query; if matches, simply return)
201     }
202   sm = GNUNET_malloc (sizeof (struct DownloadRequest));
203   sm->chk = *chk;
204   sm->offset = offset;
205   sm->depth = depth;
206   sm->is_pending = GNUNET_YES;
207   sm->next = dc->pending;
208   dc->pending = sm;
209   GNUNET_CONTAINER_multihashmap_put (dc->active,
210                                      &chk->query,
211                                      sm,
212                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
213 }
214
215
216 /**
217  * We've lost our connection with the FS service.
218  * Re-establish it and re-transmit all of our
219  * pending requests.
220  *
221  * @param dc download context that is having trouble
222  */
223 static void
224 try_reconnect (struct GNUNET_FS_DownloadContext *dc);
225
226
227 /**
228  * Compute how many bytes of data should be stored in
229  * the specified node.
230  *
231  * @param fsize overall file size
232  * @param off offset of the node
233  * @param depth depth of the node
234  * @return number of bytes stored in this node
235  */
236 static size_t
237 calculate_block_size (uint64_t fsize,
238                       unsigned int totaldepth,
239                       uint64_t offset,
240                       unsigned int depth)
241 {
242   unsigned int i;
243   size_t ret;
244   uint64_t rsize;
245   uint64_t epos;
246   unsigned int chks;
247
248   GNUNET_assert (offset < fsize);
249   if (depth == totaldepth)
250     {
251       ret = DBLOCK_SIZE;
252       if (offset + ret > fsize)
253         ret = (size_t) (fsize - offset);
254       return ret;
255     }
256
257   rsize = DBLOCK_SIZE;
258   for (i = totaldepth-1; i > depth; i--)
259     rsize *= CHK_PER_INODE;
260   epos = offset + rsize * CHK_PER_INODE;
261   GNUNET_assert (epos > offset);
262   if (epos > fsize)
263     epos = fsize;
264   /* round up when computing #CHKs in our IBlock */
265   chks = (epos - offset + rsize - 1) / rsize;
266   GNUNET_assert (chks <= CHK_PER_INODE);
267   return chks * sizeof (struct ContentHashKey);
268 }
269
270
271 /**
272  * Process a search result.
273  *
274  * @param sc our search context
275  * @param type type of the result
276  * @param data the (encrypted) response
277  * @param size size of data
278  */
279 static void
280 process_result (struct GNUNET_FS_DownloadContext *dc,
281                 uint32_t type,
282                 const void *data,
283                 size_t size)
284 {
285   struct GNUNET_FS_ProgressInfo pi;
286   GNUNET_HashCode query;
287   struct DownloadRequest *sm;
288   struct GNUNET_CRYPTO_AesSessionKey skey;
289   struct GNUNET_CRYPTO_AesInitializationVector iv;
290   char pt[size];
291   uint64_t off;
292   size_t app;
293   unsigned int i;
294   struct ContentHashKey *chk;
295   char *emsg;
296
297   GNUNET_CRYPTO_hash (data, size, &query);
298   sm = GNUNET_CONTAINER_multihashmap_get (dc->active,
299                                           &query);
300   if (NULL == sm)
301     {
302       GNUNET_break (0);
303       return;
304     }
305   if (size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
306                                     dc->treedepth,
307                                     sm->offset,
308                                     sm->depth))
309     {
310       dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
311       /* signal error */
312       pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
313       make_download_status (&pi, dc);
314       pi.value.download.specifics.error.message = dc->emsg;
315       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
316                                      &pi);
317       /* abort all pending requests */
318       GNUNET_CLIENT_disconnect (dc->client);
319       dc->client = NULL;
320       return;
321     }
322   GNUNET_assert (GNUNET_YES ==
323                  GNUNET_CONTAINER_multihashmap_remove (dc->active,
324                                                        &query,
325                                                        sm));
326   GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
327   GNUNET_CRYPTO_aes_decrypt (data,
328                              size,
329                              &skey,
330                              &iv,
331                              pt);
332   /* save to disk */
333   if ( (NULL != dc->handle) &&
334        ( (sm->depth == dc->treedepth) ||
335          (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
336     {
337       off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
338                                  sm->offset,
339                                  sm->depth,
340                                  dc->treedepth);
341       emsg = NULL;
342       if ( (off  != 
343             GNUNET_DISK_file_seek (dc->handle,
344                                    off,
345                                    GNUNET_DISK_SEEK_SET) ) )
346         GNUNET_asprintf (&emsg,
347                          _("Failed to seek to offset %llu in file `%s': %s\n"),
348                          (unsigned long long) off,
349                          dc->filename,
350                          STRERROR (errno));
351       else if (size !=
352                GNUNET_DISK_file_write (dc->handle,
353                                        pt,
354                                        size))
355         GNUNET_asprintf (&emsg,
356                          _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
357                          (unsigned int) size,
358                          (unsigned long long) off,
359                          dc->filename,
360                          STRERROR (errno));
361       if (NULL != emsg)
362         {
363           dc->emsg = emsg;
364           // FIXME: make persistent
365
366           /* signal error */
367           pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
368           make_download_status (&pi, dc);
369           pi.value.download.specifics.error.message = emsg;
370           dc->client_info = dc->h->upcb (dc->h->upcb_cls,
371                                          &pi);
372
373           /* abort all pending requests */
374           GNUNET_CLIENT_disconnect (dc->client);
375           dc->client = NULL;
376           return;
377         }
378     }
379   if (sm->depth == dc->treedepth) 
380     {
381       app = size;
382       if (sm->offset < dc->offset)
383         {
384           /* starting offset begins in the middle of pt,
385              do not count first bytes as progress */
386           GNUNET_assert (app > (dc->offset - sm->offset));
387           app -= (dc->offset - sm->offset);       
388         }
389       if (sm->offset + size > dc->offset + dc->length)
390         {
391           /* end of block is after relevant range,
392              do not count last bytes as progress */
393           GNUNET_assert (app > (sm->offset + size) - (dc->offset + dc->length));
394           app -= (sm->offset + size) - (dc->offset + dc->length);
395         }
396       dc->completed += app;
397     }
398
399   pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
400   make_download_status (&pi, dc);
401   pi.value.download.specifics.progress.data = pt;
402   pi.value.download.specifics.progress.offset = sm->offset;
403   pi.value.download.specifics.progress.data_len = size;
404   pi.value.download.specifics.progress.depth = sm->depth;
405   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
406                                  &pi);
407   GNUNET_assert (dc->completed <= dc->length);
408   if (dc->completed == dc->length)
409     {
410       /* truncate file to size (since we store IBlocks at the end) */
411       if (dc->handle != NULL)
412         {
413           GNUNET_DISK_file_close (dc->handle);
414           dc->handle = NULL;
415           if (0 != truncate (dc->filename,
416                              GNUNET_ntohll (dc->uri->data.chk.file_length)))
417             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
418                                       "truncate",
419                                       dc->filename);
420         }
421       /* signal completion */
422       pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
423       make_download_status (&pi, dc);
424       dc->client_info = dc->h->upcb (dc->h->upcb_cls,
425                                      &pi);
426       GNUNET_assert (sm->depth == dc->treedepth);
427     }
428   // FIXME: make persistent
429   if (sm->depth == dc->treedepth) 
430     return;
431   GNUNET_assert (0 == (size % sizeof(struct ContentHashKey)));
432   chk = (struct ContentHashKey*) pt;
433   for (i=0;i<(size / sizeof(struct ContentHashKey));i++)
434     {
435       off = compute_dblock_offset (sm->offset,
436                                    sm->depth,
437                                    dc->treedepth,
438                                    i);
439       if ( (off + DBLOCK_SIZE >= dc->offset) &&
440            (off < dc->offset + dc->length) ) 
441         schedule_block_download (dc,
442                                  &chk[i],
443                                  off,
444                                  sm->depth + 1);
445     }
446 }
447
448
449 /**
450  * Type of a function to call when we receive a message
451  * from the service.
452  *
453  * @param cls closure
454  * @param msg message received, NULL on timeout or fatal error
455  */
456 static void 
457 receive_results (void *cls,
458                  const struct GNUNET_MessageHeader * msg)
459 {
460   struct GNUNET_FS_DownloadContext *dc = cls;
461   const struct ContentMessage *cm;
462   uint16_t msize;
463
464   if ( (NULL == msg) ||
465        (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_CONTENT) ||
466        (ntohs (msg->size) <= sizeof (struct ContentMessage)) )
467     {
468       try_reconnect (dc);
469       return;
470     }
471   msize = ntohs (msg->size);
472   cm = (const struct ContentMessage*) msg;
473   process_result (dc, 
474                   ntohl (cm->type),
475                   &cm[1],
476                   msize - sizeof (struct ContentMessage));
477   /* continue receiving */
478   GNUNET_CLIENT_receive (dc->client,
479                          &receive_results,
480                          dc,
481                          GNUNET_TIME_UNIT_FOREVER_REL);
482 }
483
484
485
486 /**
487  * We're ready to transmit a search request to the
488  * file-sharing service.  Do it.  If there is 
489  * more than one request pending, try to send 
490  * multiple or request another transmission.
491  *
492  * @param cls closure
493  * @param size number of bytes available in buf
494  * @param buf where the callee should write the message
495  * @return number of bytes written to buf
496  */
497 static size_t
498 transmit_download_request (void *cls,
499                            size_t size, 
500                            void *buf)
501 {
502   struct GNUNET_FS_DownloadContext *dc = cls;
503   size_t msize;
504   struct SearchMessage *sm;
505
506   if (NULL == buf)
507     {
508       try_reconnect (dc);
509       return 0;
510     }
511   GNUNET_assert (size >= sizeof (struct SearchMessage));
512   msize = 0;
513   sm = buf;
514   while ( (dc->pending == NULL) &&
515           (size > msize + sizeof (struct SearchMessage)) )
516     {
517       memset (sm, 0, sizeof (struct SearchMessage));
518       sm->header.size = htons (sizeof (struct SearchMessage));
519       sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
520       sm->anonymity_level = htonl (dc->anonymity);
521       sm->target = dc->target.hashPubKey;
522       sm->query = dc->pending->chk.query;
523       dc->pending->is_pending = GNUNET_NO;
524       dc->pending = dc->pending->next;
525       msize += sizeof (struct SearchMessage);
526       sm++;
527     }
528   return msize;
529 }
530
531
532 /**
533  * Reconnect to the FS service and transmit
534  * our queries NOW.
535  *
536  * @param cls our download context
537  * @param tc unused
538  */
539 static void
540 do_reconnect (void *cls,
541               const struct GNUNET_SCHEDULER_TaskContext *tc)
542 {
543   struct GNUNET_FS_DownloadContext *dc = cls;
544   struct GNUNET_CLIENT_Connection *client;
545   
546   dc->task = GNUNET_SCHEDULER_NO_TASK;
547   client = GNUNET_CLIENT_connect (dc->h->sched,
548                                   "fs",
549                                   dc->h->cfg);
550   if (NULL == client)
551     {
552       try_reconnect (dc);
553       return;
554     }
555   dc->client = client;
556   GNUNET_CLIENT_notify_transmit_ready (client,
557                                        sizeof (struct SearchMessage),
558                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT,
559                                        &transmit_download_request,
560                                        dc);  
561   GNUNET_CLIENT_receive (client,
562                          &receive_results,
563                          dc,
564                          GNUNET_TIME_UNIT_FOREVER_REL);
565 }
566
567
568 /**
569  * Add entries that are not yet pending back to
570  * the pending list.
571  *
572  * @param cls our download context
573  * @param key unused
574  * @param entry entry of type "struct DownloadRequest"
575  * @return GNUNET_OK
576  */
577 static int
578 retry_entry (void *cls,
579              const GNUNET_HashCode *key,
580              void *entry)
581 {
582   struct GNUNET_FS_DownloadContext *dc = cls;
583   struct DownloadRequest *dr = entry;
584
585   if (! dr->is_pending)
586     {
587       dr->next = dc->pending;
588       dr->is_pending = GNUNET_YES;
589       dc->pending = entry;
590     }
591   return GNUNET_OK;
592 }
593
594
595 /**
596  * We've lost our connection with the FS service.
597  * Re-establish it and re-transmit all of our
598  * pending requests.
599  *
600  * @param dc download context that is having trouble
601  */
602 static void
603 try_reconnect (struct GNUNET_FS_DownloadContext *dc)
604 {
605   
606   if (NULL != dc->client)
607     {
608       GNUNET_CONTAINER_multihashmap_iterate (dc->active,
609                                              &retry_entry,
610                                              dc);
611       GNUNET_CLIENT_disconnect (dc->client);
612       dc->client = NULL;
613     }
614   dc->task
615     = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
616                                     GNUNET_NO,
617                                     GNUNET_SCHEDULER_PRIORITY_IDLE,
618                                     GNUNET_SCHEDULER_NO_TASK,
619                                     GNUNET_TIME_UNIT_SECONDS,
620                                     &do_reconnect,
621                                     dc);
622 }
623
624
625 /**
626  * Download parts of a file.  Note that this will store
627  * the blocks at the respective offset in the given file.  Also, the
628  * download is still using the blocking of the underlying FS
629  * encoding.  As a result, the download may *write* outside of the
630  * given boundaries (if offset and length do not match the 32k FS
631  * block boundaries). <p>
632  *
633  * This function should be used to focus a download towards a
634  * particular portion of the file (optimization), not to strictly
635  * limit the download to exactly those bytes.
636  *
637  * @param h handle to the file sharing subsystem
638  * @param uri the URI of the file (determines what to download); CHK or LOC URI
639  * @param meta known metadata for the file (can be NULL)
640  * @param filename where to store the file, maybe NULL (then no file is
641  *        created on disk and data must be grabbed from the callbacks)
642  * @param offset at what offset should we start the download (typically 0)
643  * @param length how many bytes should be downloaded starting at offset
644  * @param anonymity anonymity level to use for the download
645  * @param options various options
646  * @param parent parent download to associate this download with (use NULL
647  *        for top-level downloads; useful for manually-triggered recursive downloads)
648  * @return context that can be used to control this download
649  */
650 struct GNUNET_FS_DownloadContext *
651 GNUNET_FS_file_download_start (struct GNUNET_FS_Handle *h,
652                                const struct GNUNET_FS_Uri *uri,
653                                const struct GNUNET_CONTAINER_MetaData *meta,
654                                const char *filename,
655                                uint64_t offset,
656                                uint64_t length,
657                                uint32_t anonymity,
658                                enum GNUNET_FS_DownloadOptions options,
659                                struct GNUNET_FS_DownloadContext *parent)
660 {
661   struct GNUNET_FS_ProgressInfo pi;
662   struct GNUNET_FS_DownloadContext *dc;
663   struct GNUNET_CLIENT_Connection *client;
664
665   client = GNUNET_CLIENT_connect (h->sched,
666                                   "fs",
667                                   h->cfg);
668   if (NULL == client)
669     return NULL;
670   // FIXME: add support for "loc" URIs!
671   GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
672   if ( (offset + length < offset) ||
673        (offset + length > uri->data.chk.file_length) )
674     {
675       GNUNET_break (0);
676       return NULL;
677     }
678   dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
679   dc->h = h;
680   dc->client = client;
681   dc->parent = parent;
682   dc->uri = GNUNET_FS_uri_dup (uri);
683   dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
684   if (NULL != filename)
685     {
686       dc->filename = GNUNET_strdup (filename);
687       if (GNUNET_YES == GNUNET_DISK_file_test (filename))
688         GNUNET_DISK_file_size (filename,
689                                &dc->old_file_size,
690                                GNUNET_YES);
691       dc->handle = GNUNET_DISK_file_open (filename, 
692                                           GNUNET_DISK_OPEN_READWRITE | 
693                                           GNUNET_DISK_OPEN_CREATE,
694                                           GNUNET_DISK_PERM_USER_READ |
695                                           GNUNET_DISK_PERM_USER_WRITE |
696                                           GNUNET_DISK_PERM_GROUP_READ |
697                                           GNUNET_DISK_PERM_OTHER_READ);
698       if (dc->handle == NULL)
699         {
700           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
701                       _("Download failed: could not open file `%s': %s\n"),
702                       dc->filename,
703                       STRERROR (errno));
704           GNUNET_CONTAINER_meta_data_destroy (dc->meta);
705           GNUNET_FS_uri_destroy (dc->uri);
706           GNUNET_free (dc->filename);
707           GNUNET_CLIENT_disconnect (dc->client);
708           GNUNET_free (dc);
709           return NULL;
710         }
711     }
712   // FIXME: set "dc->target" for LOC uris!
713   dc->offset = offset;
714   dc->length = length;
715   dc->anonymity = anonymity;
716   dc->options = options;
717   dc->active = GNUNET_CONTAINER_multihashmap_create (1 + (length / DBLOCK_SIZE));
718   dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
719   // FIXME: make persistent
720   schedule_block_download (dc, 
721                            &dc->uri->data.chk.chk,
722                            0, 
723                            0);
724   GNUNET_CLIENT_notify_transmit_ready (client,
725                                        sizeof (struct SearchMessage),
726                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT,
727                                        &transmit_download_request,
728                                        dc);  
729   GNUNET_CLIENT_receive (client,
730                          &receive_results,
731                          dc,
732                          GNUNET_TIME_UNIT_FOREVER_REL);
733   pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
734   make_download_status (&pi, dc);
735   pi.value.download.specifics.start.meta = meta;
736   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
737                                  &pi);
738
739   return dc;
740 }
741
742
743 /**
744  * Free entries in the map.
745  *
746  * @param cls unused (NULL)
747  * @param key unused
748  * @param entry entry of type "struct DownloadRequest" which is freed
749  * @return GNUNET_OK
750  */
751 static int
752 free_entry (void *cls,
753             const GNUNET_HashCode *key,
754             void *entry)
755 {
756   GNUNET_free (entry);
757   return GNUNET_OK;
758 }
759
760
761 /**
762  * Stop a download (aborts if download is incomplete).
763  *
764  * @param dc handle for the download
765  * @param do_delete delete files of incomplete downloads
766  */
767 void
768 GNUNET_FS_file_download_stop (struct GNUNET_FS_DownloadContext *dc,
769                               int do_delete)
770 {
771   struct GNUNET_FS_ProgressInfo pi;
772
773   // FIXME: make unpersistent  
774   pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
775   make_download_status (&pi, dc);
776   dc->client_info = dc->h->upcb (dc->h->upcb_cls,
777                                  &pi);
778
779   if (GNUNET_SCHEDULER_NO_TASK != dc->task)
780     GNUNET_SCHEDULER_cancel (dc->h->sched,
781                              dc->task);
782   if (NULL != dc->client)
783     GNUNET_CLIENT_disconnect (dc->client);
784   GNUNET_CONTAINER_multihashmap_iterate (dc->active,
785                                          &free_entry,
786                                          NULL);
787   GNUNET_CONTAINER_multihashmap_destroy (dc->active);
788   if (dc->filename != NULL)
789     {
790       if (NULL != dc->handle)
791         GNUNET_DISK_file_close (dc->handle);
792       if ( (dc->completed != dc->length) &&
793            (GNUNET_YES == do_delete) )
794         {
795           if (0 != UNLINK (dc->filename))
796             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
797                                       "unlink",
798                                       dc->filename);
799         }
800       GNUNET_free (dc->filename);
801     }
802   GNUNET_CONTAINER_meta_data_destroy (dc->meta);
803   GNUNET_FS_uri_destroy (dc->uri);
804   GNUNET_free (dc);
805 }
806
807
808
809 #if 0
810
811
812 /**
813  * Check if self block is already present on the drive.  If the block
814  * is a dblock and present, the ProgressModel is notified. If the
815  * block is present and it is an iblock, downloading the children is
816  * triggered.
817  *
818  * Also checks if the block is within the range of blocks
819  * that we are supposed to download.  If not, the method
820  * returns as if the block is present but does NOT signal
821  * progress.
822  *
823  * @param node that is checked for presence
824  * @return GNUNET_YES if present, GNUNET_NO if not.
825  */
826 static int
827 check_node_present (const struct Node *node)
828 {
829   int res;
830   int ret;
831   char *data;
832   unsigned int size;
833   GNUNET_HashCode hc;
834
835   size = get_node_size (node);
836   /* first check if node is within range.
837      For now, keeping it simple, we only do
838      this for level-0 nodes */
839   if ((node->level == 0) &&
840       ((node->offset + size < node->ctx->offset) ||
841        (node->offset >= node->ctx->offset + node->ctx->length)))
842     return GNUNET_YES;
843   data = GNUNET_malloc (size);
844   ret = GNUNET_NO;
845   res = read_from_files (node->ctx, node->level, node->offset, data, size);
846   if (res == size)
847     {
848       GNUNET_hash (data, size, &hc);
849       if (0 == memcmp (&hc, &node->chk.key, sizeof (GNUNET_HashCode)))
850         {
851           notify_client_about_progress (node, data, size);
852           if (node->level > 0)
853             iblock_download_children (node, data, size);
854           ret = GNUNET_YES;
855         }
856     }
857   GNUNET_free (data);
858   return ret;
859 }
860
861 #endif
862
863
864 /* end of fs_download.c */