aboutsummaryrefslogtreecommitdiff
path: root/src/fs/fs_download.c
blob: 3de192e12eb4eaa96a6e741db4f342072487d169 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
/*
     This file is part of GNUnet.
     (C) 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009 Christian Grothoff (and other contributing authors)

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 2, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/
/**
 * @file fs/fs_download.c
 * @brief download methods
 * @author Christian Grothoff
 *
 * TODO:
 * - handle recursive downloads (need directory & 
 *   fs-level download-parallelism management)
 * - location URI suppport (can wait, easy)
 * - check if blocks exist already (can wait, easy)
 * - check if iblocks can be computed from existing blocks (can wait, hard)
 * - persistence (can wait)
 */
#include "platform.h"
#include "gnunet_constants.h"
#include "gnunet_fs_service.h"
#include "fs.h"
#include "fs_tree.h"

#define DEBUG_DOWNLOAD GNUNET_NO

/**
 * We're storing the IBLOCKS after the
 * DBLOCKS on disk (so that we only have
 * to truncate the file once we're done).
 *
 * Given the offset of a block (with respect
 * to the DBLOCKS) and its depth, return the
 * offset where we would store this block
 * in the file.

 * 
 * @param fsize overall file size
 * @param off offset of the block in the file
 * @param depth depth of the block in the tree
 * @param treedepth maximum depth of the tree
 * @return off for DBLOCKS (depth == treedepth),
 *         otherwise an offset past the end
 *         of the file that does not overlap
 *         with the range for any other block
 */
static uint64_t
compute_disk_offset (uint64_t fsize,
		     uint64_t off,
		     unsigned int depth,
		     unsigned int treedepth)
{
  unsigned int i;
  uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */
  uint64_t loff; /* where do IBlocks for depth "i" start? */
  unsigned int ioff; /* which IBlock corresponds to "off" at depth "i"? */
  
  if (depth == treedepth)
    return off;
  /* first IBlocks start at the end of file, rounded up
     to full DBLOCK_SIZE */
  loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE;
  lsize = ( (fsize + DBLOCK_SIZE-1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey);
  GNUNET_assert (0 == (off % DBLOCK_SIZE));
  ioff = (off / DBLOCK_SIZE);
  for (i=treedepth-1;i>depth;i--)
    {
      loff += lsize;
      lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE;
      GNUNET_assert (lsize > 0);
      GNUNET_assert (0 == (ioff % CHK_PER_INODE));
      ioff /= CHK_PER_INODE;
    }
  return loff + ioff * sizeof (struct ContentHashKey);
}


/**
 * Given a file of the specified treedepth and a block at the given
 * offset and depth, calculate the offset for the CHK at the given
 * index.
 *
 * @param offset the offset of the first
 *        DBLOCK in the subtree of the 
 *        identified IBLOCK
 * @param depth the depth of the IBLOCK in the tree
 * @param treedepth overall depth of the tree
 * @param k which CHK in the IBLOCK are we 
 *        talking about
 * @return offset if k=0, otherwise an appropriately
 *         larger value (i.e., if depth = treedepth-1,
 *         the returned value should be offset+DBLOCK_SIZE)
 */
static uint64_t
compute_dblock_offset (uint64_t offset,
		       unsigned int depth,
		       unsigned int treedepth,
		       unsigned int k)
{
  unsigned int i;
  uint64_t lsize; /* what is the size of the sum of all DBlocks 
		     that a CHK at depth i corresponds to? */

  if (depth == treedepth)
    return offset;
  lsize = DBLOCK_SIZE;
  for (i=treedepth-1;i>depth;i--)
    lsize *= CHK_PER_INODE;
  return offset + k * lsize;
}


/**
 * Fill in all of the generic fields for 
 * a download event.
 *
 * @param pi structure to fill in
 * @param dc overall download context
 */
static void
make_download_status (struct GNUNET_FS_ProgressInfo *pi,
		      struct GNUNET_FS_DownloadContext *dc)
{
  pi->value.download.dc = dc;
  pi->value.download.cctx
    = dc->client_info;
  pi->value.download.pctx
    = (dc->parent == NULL) ? NULL : dc->parent->client_info;
  pi->value.download.uri 
    = dc->uri;
  pi->value.download.filename
    = dc->filename;
  pi->value.download.size
    = dc->length;
  pi->value.download.duration
    = GNUNET_TIME_absolute_get_duration (dc->start_time);
  pi->value.download.completed
    = dc->completed;
  pi->value.download.anonymity
    = dc->anonymity;
  pi->value.download.eta
    = GNUNET_TIME_calculate_eta (dc->start_time,
				 dc->completed,
				 dc->length);
}

/**
 * We're ready to transmit a search request to the
 * file-sharing service.  Do it.  If there is 
 * more than one request pending, try to send 
 * multiple or request another transmission.
 *
 * @param cls closure
 * @param size number of bytes available in buf
 * @param buf where the callee should write the message
 * @return number of bytes written to buf
 */
static size_t
transmit_download_request (void *cls,
			   size_t size, 
			   void *buf);


/**
 * Schedule the download of the specified
 * block in the tree.
 *
 * @param dc overall download this block belongs to
 * @param chk content-hash-key of the block
 * @param offset offset of the block in the file
 *         (for IBlocks, the offset is the lowest
 *          offset of any DBlock in the subtree under
 *          the IBlock)
 * @param depth depth of the block, 0 is the root of the tree
 */
static void
schedule_block_download (struct GNUNET_FS_DownloadContext *dc,
			 const struct ContentHashKey *chk,
			 uint64_t offset,
			 unsigned int depth)
{
  struct DownloadRequest *sm;
  uint64_t off;

#if DEBUG_DOWNLOAD
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Scheduling download at offset %llu and depth %u for `%s'\n",
	      (unsigned long long) offset,
	      depth,
	      GNUNET_h2s (&chk->query));
#endif
  off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
			     offset,
			     depth,
			     dc->treedepth);
  if ( (dc->old_file_size > off) &&
       (dc->handle != NULL) &&
       (off  == 
	GNUNET_DISK_file_seek (dc->handle,
			       off,
			       GNUNET_DISK_SEEK_SET) ) )
    {
      // FIXME: check if block exists on disk!
      // (read block, encode, compare with
      // query; if matches, simply return)
    }
  if (depth < dc->treedepth)
    {
      // FIXME: try if we could
      // reconstitute this IBLOCK
      // from the existing blocks on disk (can wait)
      // (read block(s), encode, compare with
      // query; if matches, simply return)
    }
  sm = GNUNET_malloc (sizeof (struct DownloadRequest));
  sm->chk = *chk;
  sm->offset = offset;
  sm->depth = depth;
  sm->is_pending = GNUNET_YES;
  sm->next = dc->pending;
  dc->pending = sm;
  GNUNET_CONTAINER_multihashmap_put (dc->active,
				     &chk->query,
				     sm,
				     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);

  if ( (dc->th == NULL) &&
       (dc->client != NULL) )
    dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
						  sizeof (struct SearchMessage),
						  GNUNET_CONSTANTS_SERVICE_TIMEOUT,
						  GNUNET_NO,
						  &transmit_download_request,
						  dc); 

}


/**
 * We've lost our connection with the FS service.
 * Re-establish it and re-transmit all of our
 * pending requests.
 *
 * @param dc download context that is having trouble
 */
static void
try_reconnect (struct GNUNET_FS_DownloadContext *dc);


/**
 * Compute how many bytes of data should be stored in
 * the specified node.
 *
 * @param fsize overall file size
 * @param totaldepth depth of the entire tree
 * @param offset offset of the node
 * @param depth depth of the node
 * @return number of bytes stored in this node
 */
static size_t
calculate_block_size (uint64_t fsize,
		      unsigned int totaldepth,
		      uint64_t offset,
		      unsigned int depth)
{
  unsigned int i;
  size_t ret;
  uint64_t rsize;
  uint64_t epos;
  unsigned int chks;

  GNUNET_assert (offset < fsize);
  if (depth == totaldepth)
    {
      ret = DBLOCK_SIZE;
      if (offset + ret > fsize)
        ret = (size_t) (fsize - offset);
      return ret;
    }

  rsize = DBLOCK_SIZE;
  for (i = totaldepth-1; i > depth; i--)
    rsize *= CHK_PER_INODE;
  epos = offset + rsize * CHK_PER_INODE;
  GNUNET_assert (epos > offset);
  if (epos > fsize)
    epos = fsize;
  /* round up when computing #CHKs in our IBlock */
  chks = (epos - offset + rsize - 1) / rsize;
  GNUNET_assert (chks <= CHK_PER_INODE);
  return chks * sizeof (struct ContentHashKey);
}


/**
 * Closure for iterator processing results.
 */
struct ProcessResultClosure
{
  
  /**
   * Hash of data.
   */
  GNUNET_HashCode query;

  /**
   * Data found in P2P network.
   */ 
  const void *data;

  /**
   * Our download context.
   */
  struct GNUNET_FS_DownloadContext *dc;
		
  /**
   * Number of bytes in data.
   */
  size_t size;

  /**
   * Type of data.
   */
  uint32_t type;
  
};


/**
 * Iterator over entries in the pending requests in the 'active' map for the
 * reply that we just got.
 *
 * @param cls closure (our 'struct ProcessResultClosure')
 * @param key query for the given value / request
 * @param value value in the hash map (a 'struct DownloadRequest')
 * @return GNUNET_YES (we should continue to iterate); unless serious error
 */
static int
process_result_with_request (void *cls,
			     const GNUNET_HashCode * key,
			     void *value)
{
  struct ProcessResultClosure *prc = cls;
  struct DownloadRequest *sm = value;
  struct GNUNET_FS_DownloadContext *dc = prc->dc;
  struct GNUNET_CRYPTO_AesSessionKey skey;
  struct GNUNET_CRYPTO_AesInitializationVector iv;
  char pt[prc->size];
  struct GNUNET_FS_ProgressInfo pi;
  uint64_t off;
  size_t app;
  int i;
  struct ContentHashKey *chk;
  char *emsg;

  if (prc->size != calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
					 dc->treedepth,
					 sm->offset,
					 sm->depth))
    {
#if DEBUG_DOWNLOAD
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Internal error or bogus download URI (expected %u bytes, got %u)\n",
		  calculate_block_size (GNUNET_ntohll (dc->uri->data.chk.file_length),
					dc->treedepth,
					sm->offset,
					sm->depth),
		  prc->size);
#endif
      dc->emsg = GNUNET_strdup ("Internal error or bogus download URI");
      /* signal error */
      pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
      make_download_status (&pi, dc);
      pi.value.download.specifics.error.message = dc->emsg;
      dc->client_info = dc->h->upcb (dc->h->upcb_cls,
				     &pi);
      /* abort all pending requests */
      if (NULL != dc->th)
	{
	  GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
	  dc->th = NULL;
	}
      GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
      dc->client = NULL;
      return GNUNET_NO;
    }
  GNUNET_assert (GNUNET_YES ==
		 GNUNET_CONTAINER_multihashmap_remove (dc->active,
						       &prc->query,
						       sm));
  GNUNET_CRYPTO_hash_to_aes_key (&sm->chk.key, &skey, &iv);
  GNUNET_CRYPTO_aes_decrypt (prc->data,
			     prc->size,
			     &skey,
			     &iv,
			     pt);
  /* save to disk */
  if ( (NULL != dc->handle) &&
       ( (sm->depth == dc->treedepth) ||
	 (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)) ) )
    {
      off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length),
				 sm->offset,
				 sm->depth,
				 dc->treedepth);
      emsg = NULL;
#if DEBUG_DOWNLOAD
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Saving decrypted block to disk at offset %llu\n",
		  (unsigned long long) off);
#endif
      if ( (off  != 
	    GNUNET_DISK_file_seek (dc->handle,
				   off,
				   GNUNET_DISK_SEEK_SET) ) )
	GNUNET_asprintf (&emsg,
			 _("Failed to seek to offset %llu in file `%s': %s\n"),
			 (unsigned long long) off,
			 dc->filename,
			 STRERROR (errno));
      else if (prc->size !=
	       GNUNET_DISK_file_write (dc->handle,
				       pt,
				       prc->size))
	GNUNET_asprintf (&emsg,
			 _("Failed to write block of %u bytes at offset %llu in file `%s': %s\n"),
			 (unsigned int) prc->size,
			 (unsigned long long) off,
			 dc->filename,
			 STRERROR (errno));
      if (NULL != emsg)
	{
	  dc->emsg = emsg;
	  // FIXME: make persistent

	  /* signal error */
	  pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR;
	  make_download_status (&pi, dc);
	  pi.value.download.specifics.error.message = emsg;
	  dc->client_info = dc->h->upcb (dc->h->upcb_cls,
					 &pi);

	  /* abort all pending requests */
	  if (NULL != dc->th)
	    {
	      GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
	      dc->th = NULL;
	    }
	  GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
	  dc->client = NULL;
	  GNUNET_free (sm);
	  return GNUNET_NO;
	}
    }
  if (sm->depth == dc->treedepth) 
    {
      app = prc->size;
      if (sm->offset < dc->offset)
	{
	  /* starting offset begins in the middle of pt,
	     do not count first bytes as progress */
	  GNUNET_assert (app > (dc->offset - sm->offset));
	  app -= (dc->offset - sm->offset);	  
	}
      if (sm->offset + prc->size > dc->offset + dc->length)
	{
	  /* end of block is after relevant range,
	     do not count last bytes as progress */
	  GNUNET_assert (app > (sm->offset + prc->size) - (dc->offset + dc->length));
	  app -= (sm->offset + prc->size) - (dc->offset + dc->length);
	}
      dc->completed += app;
    }

  pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS;
  make_download_status (&pi, dc);
  pi.value.download.specifics.progress.data = pt;
  pi.value.download.specifics.progress.offset = sm->offset;
  pi.value.download.specifics.progress.data_len = prc->size;
  pi.value.download.specifics.progress.depth = sm->depth;
  dc->client_info = dc->h->upcb (dc->h->upcb_cls,
				 &pi);
  GNUNET_assert (dc->completed <= dc->length);
  if (dc->completed == dc->length)
    {
#if DEBUG_DOWNLOAD
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Download completed, truncating file to desired length %llu\n",
		  (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length));
#endif
      /* truncate file to size (since we store IBlocks at the end) */
      if (dc->handle != NULL)
	{
	  GNUNET_DISK_file_close (dc->handle);
	  dc->handle = NULL;
	  if (0 != truncate (dc->filename,
			     GNUNET_ntohll (dc->uri->data.chk.file_length)))
	    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
				      "truncate",
				      dc->filename);
	}
      /* signal completion */
      pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED;
      make_download_status (&pi, dc);
      dc->client_info = dc->h->upcb (dc->h->upcb_cls,
				     &pi);
      GNUNET_assert (sm->depth == dc->treedepth);
    }
  // FIXME: make persistent
  if (sm->depth == dc->treedepth) 
    {
      GNUNET_free (sm);      
      return GNUNET_YES;
    }
#if DEBUG_DOWNLOAD
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Triggering downloads of children (this block was at depth %u and offset %llu)\n",
	      sm->depth,
	      (unsigned long long) sm->offset);
#endif
  GNUNET_assert (0 == (prc->size % sizeof(struct ContentHashKey)));
  chk = (struct ContentHashKey*) pt;
  for (i=(prc->size / sizeof(struct ContentHashKey))-1;i>=0;i--)
    {
      off = compute_dblock_offset (sm->offset,
				   sm->depth,
				   dc->treedepth,
				   i);
      if ( (off + DBLOCK_SIZE >= dc->offset) &&
	   (off < dc->offset + dc->length) ) 
	schedule_block_download (dc,
				 &chk[i],
				 off,
				 sm->depth + 1);
    }
  GNUNET_free (sm);
  return GNUNET_YES;
}


/**
 * Process a download result.
 *
 * @param dc our download context
 * @param type type of the result
 * @param data the (encrypted) response
 * @param size size of data
 */
static void
process_result (struct GNUNET_FS_DownloadContext *dc,
		uint32_t type,
		const void *data,
		size_t size)
{
  struct ProcessResultClosure prc;

  prc.dc = dc;
  prc.data = data;
  prc.size = size;
  prc.type = type;
  GNUNET_CRYPTO_hash (data, size, &prc.query);
#if DEBUG_DOWNLOAD
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received result for query `%s' from `%s'-service\n",
	      GNUNET_h2s (&prc.query),
	      "FS");
#endif
  GNUNET_CONTAINER_multihashmap_get_multiple (dc->active,
					      &prc.query,
					      &process_result_with_request,
					      &prc);
}


/**
 * Type of a function to call when we receive a message
 * from the service.
 *
 * @param cls closure
 * @param msg message received, NULL on timeout or fatal error
 */
static void 
receive_results (void *cls,
		 const struct GNUNET_MessageHeader * msg)
{
  struct GNUNET_FS_DownloadContext *dc = cls;
  const struct PutMessage *cm;
  uint16_t msize;

  if ( (NULL == msg) ||
       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
       (sizeof (struct PutMessage) > ntohs(msg->size)) )
    {
      GNUNET_break (msg == NULL);	
      try_reconnect (dc);
      return;
    }
  msize = ntohs(msg->size);
  cm = (const struct PutMessage*) msg;
  process_result (dc, 
		  ntohl (cm->type),
		  &cm[1],
		  msize - sizeof (struct PutMessage));
  if (dc->client == NULL)
    return; /* fatal error */
  /* continue receiving */
  GNUNET_CLIENT_receive (dc->client,
			 &receive_results,
			 dc,
			 GNUNET_TIME_UNIT_FOREVER_REL);
}



/**
 * We're ready to transmit a search request to the
 * file-sharing service.  Do it.  If there is 
 * more than one request pending, try to send 
 * multiple or request another transmission.
 *
 * @param cls closure
 * @param size number of bytes available in buf
 * @param buf where the callee should write the message
 * @return number of bytes written to buf
 */
static size_t
transmit_download_request (void *cls,
			   size_t size, 
			   void *buf)
{
  struct GNUNET_FS_DownloadContext *dc = cls;
  size_t msize;
  struct SearchMessage *sm;

  dc->th = NULL;
  if (NULL == buf)
    {
      try_reconnect (dc);
      return 0;
    }
  GNUNET_assert (size >= sizeof (struct SearchMessage));
  msize = 0;
  sm = buf;
  while ( (dc->pending != NULL) &&
	  (size > msize + sizeof (struct SearchMessage)) )
    {
#if DEBUG_DOWNLOAD
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		  "Transmitting download request for `%s' to `%s'-service\n",
		  GNUNET_h2s (&dc->pending->chk.query),
		  "FS");
#endif
      memset (sm, 0, sizeof (struct SearchMessage));
      sm->header.size = htons (sizeof (struct SearchMessage));
      sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
      if (dc->pending->depth == dc->treedepth)
	sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_DBLOCK);
      else
	sm->type = htonl (GNUNET_DATASTORE_BLOCKTYPE_IBLOCK);
      sm->anonymity_level = htonl (dc->anonymity);
      sm->target = dc->target.hashPubKey;
      sm->query = dc->pending->chk.query;
      dc->pending->is_pending = GNUNET_NO;
      dc->pending = dc->pending->next;
      msize += sizeof (struct SearchMessage);
      sm++;
    }
  if (dc->pending != NULL)
    dc->th = GNUNET_CLIENT_notify_transmit_ready (dc->client,
						  sizeof (struct SearchMessage),
						  GNUNET_CONSTANTS_SERVICE_TIMEOUT,
						  GNUNET_NO,
						  &transmit_download_request,
						  dc); 
  return msize;
}


/**
 * Reconnect to the FS service and transmit our queries NOW.
 *
 * @param cls our download context
 * @param tc unused
 */
static void
do_reconnect (void *cls,
	      const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_FS_DownloadContext *dc = cls;
  struct GNUNET_CLIENT_Connection *client;
  
  dc->task = GNUNET_SCHEDULER_NO_TASK;
  client = GNUNET_CLIENT_connect (dc->h->sched,
				  "fs",
				  dc->h->cfg);
  if (NULL == client)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		  "Connecting to `%s'-service failed, will try again.\n",
		  "FS");
      try_reconnect (dc);
      return;
    }
  dc->client = client;
  dc->th = GNUNET_CLIENT_notify_transmit_ready (client,
						sizeof (struct SearchMessage),
						GNUNET_CONSTANTS_SERVICE_TIMEOUT,
						GNUNET_NO,
						&transmit_download_request,
						dc);  
  GNUNET_CLIENT_receive (client,
			 &receive_results,
			 dc,
			 GNUNET_TIME_UNIT_FOREVER_REL);
}


/**
 * Add entries that are not yet pending back to the pending list.
 *
 * @param cls our download context
 * @param key unused
 * @param entry entry of type "struct DownloadRequest"
 * @return GNUNET_OK
 */
static int
retry_entry (void *cls,
	     const GNUNET_HashCode *key,
	     void *entry)
{
  struct GNUNET_FS_DownloadContext *dc = cls;
  struct DownloadRequest *dr = entry;

  if (! dr->is_pending)
    {
      dr->next = dc->pending;
      dr->is_pending = GNUNET_YES;
      dc->pending = entry;
    }
  return GNUNET_OK;
}


/**
 * We've lost our connection with the FS service.
 * Re-establish it and re-transmit all of our
 * pending requests.
 *
 * @param dc download context that is having trouble
 */
static void
try_reconnect (struct GNUNET_FS_DownloadContext *dc)
{
  
  if (NULL != dc->client)
    {
      if (NULL != dc->th)
	{
	  GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
	  dc->th = NULL;
	}
      GNUNET_CONTAINER_multihashmap_iterate (dc->active,
					     &retry_entry,
					     dc);
      GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
      dc->client = NULL;
    }
  dc->task
    = GNUNET_SCHEDULER_add_delayed (dc->h->sched,
				    GNUNET_TIME_UNIT_SECONDS,
				    &do_reconnect,
				    dc);
}


/**
 * Download parts of a file.  Note that this will store
 * the blocks at the respective offset in the given file.  Also, the
 * download is still using the blocking of the underlying FS
 * encoding.  As a result, the download may *write* outside of the
 * given boundaries (if offset and length do not match the 32k FS
 * block boundaries). <p>
 *
 * This function should be used to focus a download towards a
 * particular portion of the file (optimization), not to strictly
 * limit the download to exactly those bytes.
 *
 * @param h handle to the file sharing subsystem
 * @param uri the URI of the file (determines what to download); CHK or LOC URI
 * @param meta known metadata for the file (can be NULL)
 * @param filename where to store the file, maybe NULL (then no file is
 *        created on disk and data must be grabbed from the callbacks)
 * @param offset at what offset should we start the download (typically 0)
 * @param length how many bytes should be downloaded starting at offset
 * @param anonymity anonymity level to use for the download
 * @param options various options
 * @param cctx initial value for the client context for this download
 * @param parent parent download to associate this download with (use NULL
 *        for top-level downloads; useful for manually-triggered recursive downloads)
 * @return context that can be used to control this download
 */
struct GNUNET_FS_DownloadContext *
GNUNET_FS_download_start (struct GNUNET_FS_Handle *h,
			  const struct GNUNET_FS_Uri *uri,
			  const struct GNUNET_CONTAINER_MetaData *meta,
			  const char *filename,
			  uint64_t offset,
			  uint64_t length,
			  uint32_t anonymity,
			  enum GNUNET_FS_DownloadOptions options,
			  void *cctx,
			  struct GNUNET_FS_DownloadContext *parent)
{
  struct GNUNET_FS_ProgressInfo pi;
  struct GNUNET_FS_DownloadContext *dc;
  struct GNUNET_CLIENT_Connection *client;

  GNUNET_assert (GNUNET_FS_uri_test_chk (uri));
  if ( (offset + length < offset) ||
       (offset + length > uri->data.chk.file_length) )
    {      
      GNUNET_break (0);
      return NULL;
    }
  client = GNUNET_CLIENT_connect (h->sched,
				  "fs",
				  h->cfg);
  if (NULL == client)
    return NULL;
  // FIXME: add support for "loc" URIs!
#if DEBUG_DOWNLOAD
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Starting download `%s' of %llu bytes\n",
	      filename,
	      (unsigned long long) length);
#endif
  dc = GNUNET_malloc (sizeof(struct GNUNET_FS_DownloadContext));
  dc->h = h;
  dc->client = client;
  dc->parent = parent;
  dc->uri = GNUNET_FS_uri_dup (uri);
  dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
  dc->client_info = cctx;
  dc->start_time = GNUNET_TIME_absolute_get ();
  if (NULL != filename)
    {
      dc->filename = GNUNET_strdup (filename);
      if (GNUNET_YES == GNUNET_DISK_file_test (filename))
	GNUNET_DISK_file_size (filename,
			       &dc->old_file_size,
			       GNUNET_YES);
      dc->handle = GNUNET_DISK_file_open (filename, 
					  GNUNET_DISK_OPEN_READWRITE | 
					  GNUNET_DISK_OPEN_CREATE,
					  GNUNET_DISK_PERM_USER_READ |
					  GNUNET_DISK_PERM_USER_WRITE |
					  GNUNET_DISK_PERM_GROUP_READ |
					  GNUNET_DISK_PERM_OTHER_READ);
      if (dc->handle == NULL)
	{
	  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		      _("Download failed: could not open file `%s': %s\n"),
		      dc->filename,
		      STRERROR (errno));
	  GNUNET_CONTAINER_meta_data_destroy (dc->meta);
	  GNUNET_FS_uri_destroy (dc->uri);
	  GNUNET_free (dc->filename);
	  GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
	  GNUNET_free (dc);
	  return NULL;
	}
    }
  // FIXME: set "dc->target" for LOC uris!
  dc->offset = offset;
  dc->length = length;
  dc->anonymity = anonymity;
  dc->options = options;
  dc->active = GNUNET_CONTAINER_multihashmap_create (2 * (length / DBLOCK_SIZE));
  dc->treedepth = GNUNET_FS_compute_depth (GNUNET_ntohll(dc->uri->data.chk.file_length));
#if DEBUG_DOWNLOAD
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Download tree has depth %u\n",
	      dc->treedepth);
#endif
  // FIXME: make persistent
  schedule_block_download (dc, 
			   &dc->uri->data.chk.chk,
			   0, 
			   1 /* 0 == CHK, 1 == top */);
  GNUNET_CLIENT_receive (client,
			 &receive_results,
			 dc,
			 GNUNET_TIME_UNIT_FOREVER_REL);
  pi.status = GNUNET_FS_STATUS_DOWNLOAD_START;
  make_download_status (&pi, dc);
  pi.value.download.specifics.start.meta = meta;
  dc->client_info = dc->h->upcb (dc->h->upcb_cls,
				 &pi);

  return dc;
}


/**
 * Free entries in the map.
 *
 * @param cls unused (NULL)
 * @param key unused
 * @param entry entry of type "struct DownloadRequest" which is freed
 * @return GNUNET_OK
 */
static int
free_entry (void *cls,
	    const GNUNET_HashCode *key,
	    void *entry)
{
  GNUNET_free (entry);
  return GNUNET_OK;
}


/**
 * Stop a download (aborts if download is incomplete).
 *
 * @param dc handle for the download
 * @param do_delete delete files of incomplete downloads
 */
void
GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc,
			 int do_delete)
{
  struct GNUNET_FS_ProgressInfo pi;

  // FIXME: make unpersistent  
  pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED;
  make_download_status (&pi, dc);
  dc->client_info = dc->h->upcb (dc->h->upcb_cls,
				 &pi);

  if (GNUNET_SCHEDULER_NO_TASK != dc->task)
    GNUNET_SCHEDULER_cancel (dc->h->sched,
			     dc->task);
  if (NULL != dc->th)
    {
      GNUNET_CLIENT_notify_transmit_ready_cancel (dc->th);
      dc->th = NULL;
    }
  if (NULL != dc->client)
    GNUNET_CLIENT_disconnect (dc->client, GNUNET_NO);
  GNUNET_CONTAINER_multihashmap_iterate (dc->active,
					 &free_entry,
					 NULL);
  GNUNET_CONTAINER_multihashmap_destroy (dc->active);
  if (dc->filename != NULL)
    {
      if (NULL != dc->handle)
	GNUNET_DISK_file_close (dc->handle);
      if ( (dc->completed != dc->length) &&
	   (GNUNET_YES == do_delete) )
	{
	  if (0 != UNLINK (dc->filename))
	    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
				      "unlink",
				      dc->filename);
	}
      GNUNET_free (dc->filename);
    }
  GNUNET_CONTAINER_meta_data_destroy (dc->meta);
  GNUNET_FS_uri_destroy (dc->uri);
  GNUNET_free (dc);
}

/* end of fs_download.c */