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