summaryrefslogtreecommitdiffstats
path: root/libktorrent/torrent/multifilecache.cpp
blob: c6cd8b7c518d907da1e0f55152360d16e13fdba1 (plain)
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
/***************************************************************************
 *   Copyright (C) 2005 by Joris Guisson                                   *
 *   joris.guisson@gmail.com                                               *
 *                                                                         *
 *   This program 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 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.             *
 ***************************************************************************/
#include <errno.h>
#include <tqdir.h>
#include <tqstringlist.h>
#include <tqfileinfo.h>
#include <klocale.h>
#include <kio/netaccess.h>
#include <util/file.h>
#include <util/fileops.h>
#include <util/functions.h>
#include <util/error.h>
#include <util/log.h>
#include "torrent.h"
#include "cache.h"
#include "multifilecache.h"
#include "globals.h"
#include "chunk.h"
#include "cachefile.h"
#include "dndfile.h"
#include "preallocationthread.h"
#include "movedatafilesjob.h"



namespace bt
{
	static Uint64 FileOffset(Chunk* c,const TorrentFile & f,Uint64 chunk_size);
	static Uint64 FileOffset(Uint32 cindex,const TorrentFile & f,Uint64 chunk_size);
	static void DeleteEmptyDirs(const TQString & output_dir,const TQString & fpath);


	MultiFileCache::MultiFileCache(Torrent& tor,const TQString & tmpdir,const TQString & datadir,bool custom_output_name) : Cache(tor, tmpdir,datadir)
	{
		cache_dir = tmpdir + "cache" + bt::DirSeparator();
		if (datadir.length() == 0)
			this->datadir = guessDataDir();
		if (!custom_output_name)
			output_dir = this->datadir + tor.getNameSuggestion() + bt::DirSeparator();
		else
			output_dir = this->datadir;
		files.setAutoDelete(true);
	}


	MultiFileCache::~MultiFileCache()
	{}
	
	TQString MultiFileCache::guessDataDir()
	{
		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{
			TorrentFile & tf = tor.getFile(i);
			if (tf.doNotDownload())
				continue;
			
			TQString p = cache_dir + tf.getPath();
			TQFileInfo fi(p);
			if (!fi.isSymLink())
				continue;
			
			TQString dst = fi.readLink();
			TQString tmp = tor.getNameSuggestion() + bt::DirSeparator() + tf.getPath();
			dst = dst.left(dst.length() - tmp.length());
			if (dst.length() == 0)
				continue;
			
			if (!dst.endsWith(bt::DirSeparator()))
				dst += bt::DirSeparator();
			Out() << "Guessed outputdir to be " << dst << endl;
			return dst;
		}
		
		return TQString();
	}
	
	TQString MultiFileCache::getOutputPath() const
	{
		return output_dir;
	}

	void MultiFileCache::close()
	{
		files.clear();
	}
	
	void MultiFileCache::open()
	{
		TQString dnd_dir = tmpdir + "dnd" + bt::DirSeparator();
		// open all files
		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{
			TorrentFile & tf = tor.getFile(i);
			CacheFile* fd = 0;
			DNDFile* dfd = 0;
			try
			{
				if (!tf.doNotDownload())
				{
					if (files.contains(i))
						files.erase(i);
					
					fd = new CacheFile();
					fd->open(cache_dir + tf.getPath(),tf.getSize());
					files.insert(i,fd);
				}
				else
				{
					if (dnd_files.contains(i))
						dnd_files.erase(i);
					
					dfd = new DNDFile(dnd_dir + tf.getPath() + ".dnd");
					dfd->checkIntegrity();
					dnd_files.insert(i,dfd);
				}
			}
			catch (...)
			{
				delete fd;
				fd = 0;
				delete dfd;
				dfd = 0;
				throw;
			}
		}
	}

	void MultiFileCache::changeTmpDir(const TQString& ndir)
	{
		Cache::changeTmpDir(ndir);
		cache_dir = tmpdir + "cache/";
		TQString dnd_dir = tmpdir + "dnd" + bt::DirSeparator();
		
		// change paths for individual files, it should not
		// be a problem to move these files when they are open
		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{
			TorrentFile & tf = tor.getFile(i);
			if (tf.doNotDownload())
			{
				DNDFile* dfd = dnd_files.find(i);
				if (dfd)
					dfd->changePath(dnd_dir + tf.getPath() + ".dnd");
			}
			else
			{
				CacheFile* fd = files.find(i);
				if (fd)
					fd->changePath(cache_dir + tf.getPath());
			}
		}
	}
	
	void MultiFileCache::changeOutputPath(const TQString & outputpath)
	{
		output_dir = outputpath;
		if (!output_dir.endsWith(bt::DirSeparator()))
			output_dir += bt::DirSeparator();
		
		datadir = output_dir;
		
		if (!bt::Exists(cache_dir))
			MakeDir(cache_dir);
		
		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{
			TorrentFile & tf = tor.getFile(i);
			if (!tf.doNotDownload())
			{
				TQString fpath = tf.getPath();
				if (bt::Exists(output_dir + fpath))
				{
					bt::Delete(cache_dir + fpath,true); // delete any existing symlinks
					// create new one
					bt::SymLink(output_dir + fpath,cache_dir + fpath,true); 
				}
			}
		}
	}
	
	TDEIO::Job* MultiFileCache::moveDataFiles(const TQString & ndir)
	{
		if (!bt::Exists(ndir))
			bt::MakeDir(ndir);
		
		TQString nd = ndir;
		if (!nd.endsWith(bt::DirSeparator()))
			nd += bt::DirSeparator();
		
		try
		{
			MoveDataFilesJob* mvd = new MoveDataFilesJob();
			for (Uint32 i = 0;i < tor.getNumFiles();i++)
			{			
				TorrentFile & tf = tor.getFile(i);
				if (tf.doNotDownload())
					continue;
				
				// check if every directory along the path exists, and if it doesn't
				// create it
				TQStringList sl = TQStringList::split(bt::DirSeparator(),nd + tf.getPath());
				TQString odir = bt::DirSeparator();
				for (Uint32 i = 0;i < sl.count() - 1;i++)
				{
					odir += sl[i] + bt::DirSeparator();
					if (!bt::Exists(odir))
					{
						bt::MakeDir(odir);
					}
				}
				
				mvd->addMove(output_dir + tf.getPath(),nd + tf.getPath());
			}
			
			mvd->startMoving();
			return mvd;
		}
		catch (bt::Error & err)
		{
			throw; // rethrow error
		}
		return 0;
	}
	
	void MultiFileCache::moveDataFilesCompleted(TDEIO::Job* job)
	{
		if (!job->error())
		{
			for (Uint32 i = 0;i < tor.getNumFiles();i++)
			{
				TorrentFile & tf = tor.getFile(i);
					// check for empty directories and delete them 
				DeleteEmptyDirs(output_dir,tf.getPath());
			}
		}
	}

	void MultiFileCache::create()
	{
		if (!bt::Exists(cache_dir))
			MakeDir(cache_dir);
		if (!bt::Exists(output_dir))
			MakeDir(output_dir);
		if (!bt::Exists(tmpdir + "dnd"))
			bt::MakeDir(tmpdir + "dnd");

		// update symlinks
		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{			
			TorrentFile & tf = tor.getFile(i);
			touch(tf);
		}
	}

	void MultiFileCache::touch(TorrentFile & tf)
	{
		TQString fpath = tf.getPath();
		bool dnd = tf.doNotDownload();
		// first split fpath by / separator 
		TQStringList sl = TQStringList::split(bt::DirSeparator(),fpath);
		// create all necessary subdirs
		TQString ctmp = cache_dir;
		TQString otmp = output_dir;
		TQString dtmp = tmpdir + "dnd" + bt::DirSeparator();
		for (Uint32 i = 0;i < sl.count() - 1;i++)
		{
			otmp += sl[i];
			ctmp += sl[i];
			dtmp += sl[i];
			// we need to make the same directory structure in the cache,
			// the output_dir and the dnd directory
			if (!bt::Exists(ctmp))
				MakeDir(ctmp);
			if (!bt::Exists(otmp))
				MakeDir(otmp);
			if (!bt::Exists(dtmp))
				MakeDir(dtmp);
			otmp += bt::DirSeparator();
			ctmp += bt::DirSeparator();
			dtmp += bt::DirSeparator();
		}
		
		
		bt::Delete(cache_dir + fpath,true); // delete any existing symlinks

		// then make the file
		TQString tmp = dnd ? tmpdir + "dnd" + bt::DirSeparator() : output_dir;
		if (dnd)
		{
			// only symlink, when we open the files a default dnd file will be made if the file is corrupt or doesn't exist
			bt::SymLink(tmp + fpath + ".dnd",cache_dir + fpath);
		}
		else
		{
			if (!bt::Exists(tmp + fpath))
			{
				bt::Touch(tmp + fpath);
			}
			else
			{
				preexisting_files = true;
				tf.setPreExisting(true); // mark the file as preexisting
			}
			
			bt::SymLink(tmp + fpath,cache_dir + fpath);
		}
	}

	void MultiFileCache::load(Chunk* c)
	{
		TQValueList<Uint32> tflist;
		tor.calcChunkPos(c->getIndex(),tflist);
		
		// one file is simple, just mmap it
		if (tflist.count() == 1)
		{
			const TorrentFile & f = tor.getFile(tflist.first());
			CacheFile* fd = files.find(tflist.first());
			if (!fd)
				return;
			
			if (Cache::mappedModeAllowed() && mmap_failures < 3)
			{
				Uint64 off = FileOffset(c,f,tor.getChunkSize());
				Uint8* buf = (Uint8*)fd->map(c,off,c->getSize(),CacheFile::READ);
				if (buf)
				{
					c->setData(buf,Chunk::MMAPPED);
					// only return when the mapping is OK
					// if mmap fails we will just load it buffered
					return;
				}
				else
					mmap_failures++;
			}
		}
		
		Uint8* data = new Uint8[c->getSize()];
		Uint64 read = 0; // number of bytes read
		for (Uint32 i = 0;i < tflist.count();i++)
		{
			const TorrentFile & f = tor.getFile(tflist[i]);
			CacheFile* fd = files.find(tflist[i]);
			DNDFile* dfd = dnd_files.find(tflist[i]);
				
			// first calculate offset into file
			// only the first file can have an offset
			// the following files will start at the beginning
			Uint64 off = 0;
			if (i == 0)
				off = FileOffset(c,f,tor.getChunkSize());
			
			Uint32 to_read = 0;
			// then the amount of data we can read from this file
			if (tflist.count() == 1)
				to_read = c->getSize();
			else if (i == 0)
				to_read = f.getLastChunkSize();
			else if (i == tflist.count() - 1)
				to_read = c->getSize() - read;
			else
				to_read = f.getSize();
			
		
			// read part of data
			if (fd)
				fd->read(data + read,to_read,off);
			else if (dfd)
			{
				Uint32 ret = 0;
				if (i == 0)
					ret = dfd->readLastChunk(data,read,c->getSize());
				else if (i == tflist.count() - 1)
					ret = dfd->readFirstChunk(data,read,c->getSize());
				else
					ret = dfd->readFirstChunk(data,read,c->getSize());
				
				if (ret > 0 && ret != to_read)
					Out() << "Warning : MultiFileCache::load ret != to_read" << endl;
			}
			read += to_read;
		}
		c->setData(data,Chunk::BUFFERED);
	}

	
	bool MultiFileCache::prep(Chunk* c)
	{
		// find out in which files a chunk lies
		TQValueList<Uint32> tflist;
		tor.calcChunkPos(c->getIndex(),tflist);
		
//		Out() << "Prep " << c->getIndex() << endl;
		if (tflist.count() == 1)
		{
			// in one so just mmap it
			Uint64 off = FileOffset(c,tor.getFile(tflist.first()),tor.getChunkSize());
			CacheFile* fd = files.find(tflist.first());
			Uint8* buf = 0;
			if (fd && Cache::mappedModeAllowed() && mmap_failures < 3)
			{
				buf = (Uint8*)fd->map(c,off,c->getSize(),CacheFile::RW);
				if (!buf)
					mmap_failures++;
			}
			
			if (!buf)
			{
				// if mmap fails or is not possible use buffered mode
				c->allocate();
				c->setStatus(Chunk::BUFFERED);
			}
			else
			{
				c->setData(buf,Chunk::MMAPPED);
			}
		}
		else
		{
			// just allocate it
			c->allocate();
			c->setStatus(Chunk::BUFFERED);
		}
		return true;
	}

	void MultiFileCache::save(Chunk* c)
	{
		TQValueList<Uint32> tflist;
		tor.calcChunkPos(c->getIndex(),tflist);
		
		if (c->getStatus() == Chunk::MMAPPED)
		{
			// mapped chunks are easy
			CacheFile* fd = files.find(tflist[0]);
			if (!fd)
				return;
			
			fd->unmap(c->getData(),c->getSize());
			c->clear();
			c->setStatus(Chunk::ON_DISK);
			return;
		}
	
	//	Out() << "Writing to " << tflist.count() << " files " << endl;
		Uint64 written = 0; // number of bytes written
		for (Uint32 i = 0;i < tflist.count();i++)
		{
			const TorrentFile & f = tor.getFile(tflist[i]);
			CacheFile* fd = files.find(tflist[i]);
			DNDFile* dfd = dnd_files.find(tflist[i]);

			// first calculate offset into file
			// only the first file can have an offset
			// the following files will start at the beginning
			Uint64 off = 0;
			Uint32 to_write = 0;
			if (i == 0)
			{
				off = FileOffset(c,f,tor.getChunkSize());
			}

			// the amount of data we can write to this file
			if (tflist.count() == 1)
				to_write = c->getSize();
			else if (i == 0)
				to_write = f.getLastChunkSize();
			else if (i == tflist.count() - 1)
				to_write = c->getSize() - written;
			else
				to_write = f.getSize();
			
		//	Out() << "to_write " << to_write << endl;
			// write the data
			if (fd)
				fd->write(c->getData() + written,to_write,off);
			else if (dfd)
			{
				if (i == 0)
					dfd->writeLastChunk(c->getData() + written,to_write);
				else if (i == tflist.count() - 1)
					dfd->writeFirstChunk(c->getData() + written,to_write);
				else
					dfd->writeFirstChunk(c->getData() + written,to_write);
			}
			
			written += to_write;
		}
		
		// set the chunk to on disk and clear it
		c->clear();
		c->setStatus(Chunk::ON_DISK);
	}
	
	void MultiFileCache::downloadStatusChanged(TorrentFile* tf, bool download)
	{	
		bool dnd = !download;
		TQString dnd_dir = tmpdir + "dnd" + bt::DirSeparator();
		// if it is dnd and it is already in the dnd tree do nothing
		if (dnd && bt::Exists(dnd_dir + tf->getPath() + ".dnd"))
			return;
		
		// if it is !dnd and it is already in the output_dir tree do nothing
		if (!dnd && bt::Exists(output_dir + tf->getPath()))
			return;
		
		
		DNDFile* dfd = 0;
		CacheFile* fd = 0;
		try
		{
			
			if (dnd && bt::Exists(dnd_dir + tf->getPath()))
			{
				// old download, we need to convert it
				// save first and last chunk of the file
				saveFirstAndLastChunk(tf,dnd_dir + tf->getPath(),dnd_dir + tf->getPath() + ".dnd");
				// delete symlink
				bt::Delete(cache_dir + tf->getPath());
				bt::Delete(dnd_dir + tf->getPath()); // delete old dnd file
				// recreate it
				bt::SymLink(dnd_dir + tf->getPath() + ".dnd",cache_dir + tf->getPath());
				
				files.erase(tf->getIndex());
				dfd = new DNDFile(dnd_dir + tf->getPath() + ".dnd");
				dfd->checkIntegrity();
				dnd_files.insert(tf->getIndex(),dfd);
			}
			else if (dnd)
			{
				// save first and last chunk of the file
				if (bt::Exists(output_dir + tf->getPath()))
					saveFirstAndLastChunk(tf,output_dir + tf->getPath(),dnd_dir + tf->getPath() + ".dnd");
				
				// delete symlink
				bt::Delete(cache_dir + tf->getPath());
				// delete data file
				bt::Delete(output_dir + tf->getPath(),true);
				// recreate it
				bt::SymLink(dnd_dir + tf->getPath() + ".dnd",cache_dir + tf->getPath());
				
				files.erase(tf->getIndex());
				dfd = new DNDFile(dnd_dir + tf->getPath() + ".dnd");
				dfd->checkIntegrity();
				dnd_files.insert(tf->getIndex(),dfd);
			}
			else
			{
				// recreate the file
				recreateFile(tf,dnd_dir + tf->getPath() + ".dnd",output_dir + tf->getPath());
				// delete symlink and dnd file
				bt::Delete(cache_dir + tf->getPath());
				bt::Delete(dnd_dir + tf->getPath() + ".dnd");
				// recreate it
				bt::SymLink(output_dir + tf->getPath(),cache_dir + tf->getPath());
				dnd_files.erase(tf->getIndex());
				
				fd = new CacheFile();
				fd->open(output_dir + tf->getPath(),tf->getSize());
				files.insert(tf->getIndex(),fd);
			}
		}
		catch (bt::Error & err)
		{
			delete fd;
			delete dfd;
			Out() << err.toString() << endl;
		}
	}
	

	
	void MultiFileCache::saveFirstAndLastChunk(TorrentFile* tf,const TQString & src_file,const TQString & dst_file)
	{
		DNDFile out(dst_file);
		File fptr;
		if (!fptr.open(src_file,"rb"))
			throw Error(i18n("Cannot open file %1 : %2").arg(src_file).arg(fptr.errorString()));
		
		Uint32 cs = 0;
		if (tf->getFirstChunk() == tor.getNumChunks() - 1)
		{
			cs = tor.getFileLength() % tor.getChunkSize();
			if (cs == 0)
				cs = tor.getChunkSize();
		}
		else
			cs = tor.getChunkSize();
		
		Uint8* tmp = new Uint8[tor.getChunkSize()];
		try
		{
			fptr.read(tmp,cs - tf->getFirstChunkOffset());
			out.writeFirstChunk(tmp,cs - tf->getFirstChunkOffset());
			
			if (tf->getFirstChunk() != tf->getLastChunk())
			{
				Uint64 off = FileOffset(tf->getLastChunk(),*tf,tor.getChunkSize());
				fptr.seek(File::BEGIN,off);
				fptr.read(tmp,tf->getLastChunkSize());
				out.writeLastChunk(tmp,tf->getLastChunkSize());
			}
			delete [] tmp;
		}
		catch (...)
		{
			delete [] tmp;
			throw;
		}
	}
	
	void MultiFileCache::recreateFile(TorrentFile* tf,const TQString & dnd_file,const TQString & output_file)
	{
		DNDFile dnd(dnd_file);
		
		// create the output file
		bt::Touch(output_file);
		// truncate it
		try
		{
			bool res = false;
			
			#ifdef HAVE_XFS_XFS_H
				if( (! res) && (Settings::fullDiskPreallocMethod() == 1) )
				{
					res = XfsPreallocate(output_file, tf->getSize());
				}
			#endif
			
			if(! res)
			{
				bt::TruncateFile(output_file,tf->getSize());
			}
		}
		catch (bt::Error & e)
		{
			// first attempt failed, must be fat so try that
			if (!FatPreallocate(output_file,tf->getSize()))
			{	
				throw Error(i18n("Cannot preallocate diskspace : %1").arg(strerror(errno)));
			}
		}
		
		Uint32 cs = 0;
		if (tf->getFirstChunk() == tor.getNumChunks() - 1)
		{
			cs = tor.getFileLength() % tor.getChunkSize();
			if (cs == 0)
				cs = tor.getChunkSize();
		}
		else
			cs = tor.getChunkSize();
		
		File fptr;
		if (!fptr.open(output_file,"r+b"))
			throw Error(i18n("Cannot open file %1 : %2").arg(output_file).arg(fptr.errorString()));
			
		
		Uint32 ts = cs - tf->getFirstChunkOffset() > tf->getLastChunkSize() ? 
				cs - tf->getFirstChunkOffset() : tf->getLastChunkSize();
		Uint8* tmp = new Uint8[ts];
		
		try
		{
			dnd.readFirstChunk(tmp,0,cs - tf->getFirstChunkOffset());
			fptr.write(tmp,cs - tf->getFirstChunkOffset());
			
			if (tf->getFirstChunk() != tf->getLastChunk())
			{
				Uint64 off = FileOffset(tf->getLastChunk(),*tf,tor.getChunkSize());
				fptr.seek(File::BEGIN,off);
				dnd.readLastChunk(tmp,0,tf->getLastChunkSize());
				fptr.write(tmp,tf->getLastChunkSize());
			}
			delete [] tmp;
		}
		catch (...)
		{
			delete [] tmp;
			throw;
		}
	}
	
	void MultiFileCache::preallocateDiskSpace(PreallocationThread* prealloc)
	{
		Out() << "MultiFileCache::preallocateDiskSpace" << endl;
		PtrMap<Uint32,CacheFile>::iterator i = files.begin();
		while (i != files.end())
		{
			CacheFile* cf = i->second;
			if (!prealloc->isStopped())
			{
				cf->preallocate(prealloc);
			}
			else
			{
				// we got interrupted tell the thread we are not finished and return
				prealloc->setNotFinished();
				return;
			}
			i++;
		}
	}
	
	bool MultiFileCache::hasMissingFiles(TQStringList & sl)
	{
		bool ret = false;
		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{
			TorrentFile & tf = tor.getFile(i);
			if (tf.doNotDownload())
				continue;
			
			TQString p = cache_dir + tf.getPath();
			TQFileInfo fi(p);
			// always use symlink first, file might have been moved
			if (!fi.exists())
			{
				ret = true;
				p = fi.readLink();
				if (p.isNull())
					p = output_dir + tf.getPath();
				sl.append(p);
				tf.setMissing(true);
			}
			else
			{
				p = output_dir + tf.getPath();
				// no symlink so try the actual file
				if (!bt::Exists(p))
				{
					ret = true;
					sl.append(p);
					tf.setMissing(true);
				}
			}
		}
		return ret;
	}
	
	static void DeleteEmptyDirs(const TQString & output_dir,const TQString & fpath)
	{
		TQStringList sl = TQStringList::split(bt::DirSeparator(),fpath);
		// remove the last, which is just the filename
		sl.pop_back();
		
		while (sl.count() > 0)
		{
			TQString path = output_dir;
			// reassemble the full directory path
			for (TQStringList::iterator itr = sl.begin(); itr != sl.end();itr++)
				path += *itr + bt::DirSeparator();
			
			TQDir dir(path);
			TQStringList el = dir.entryList(TQDir::All|TQDir::System|TQDir::Hidden);
			el.remove(".");
			el.remove("..");
			if (el.count() == 0)
			{
				// no childern so delete the directory
				Out(SYS_GEN|LOG_IMPORTANT) << "Deleting empty directory : " << path << endl;
				bt::Delete(path,true);
				sl.pop_back(); // remove the last so we can go one higher
			}
			else
			{
				
				// children, so we cannot delete any more directories higher up
				return;
			}
		}
		
		// now the output_dir itself
		TQDir dir(output_dir);
		TQStringList el = dir.entryList(TQDir::All|TQDir::System|TQDir::Hidden);
		el.remove(".");
		el.remove("..");
		if (el.count() == 0)
		{
			Out(SYS_GEN|LOG_IMPORTANT) << "Deleting empty directory : " << output_dir << endl;
			bt::Delete(output_dir,true);
		}
	}
	
	void MultiFileCache::deleteDataFiles()
	{
		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{
			TorrentFile & tf = tor.getFile(i);
			TQString fpath = tf.getPath();
			if (!tf.doNotDownload())
			{
				// first delete the file
				bt::Delete(output_dir + fpath);
			}
			
			// check for subdirectories
			DeleteEmptyDirs(output_dir,fpath);
		}
	}
	
	Uint64 MultiFileCache::diskUsage()
	{
		Uint64 sum = 0;

		for (Uint32 i = 0;i < tor.getNumFiles();i++)
		{
			TorrentFile & tf = tor.getFile(i);
			if (tf.doNotDownload())
				continue;

			try
			{
				CacheFile* cf = files.find(i);
				if (cf)
				{
					sum += cf->diskUsage();
				}
				else
				{
					// doesn't exist yet, must be before open is called
					// so create one and delete it right after
					cf = new CacheFile();
					cf->open(cache_dir + tf.getPath(),tf.getSize());
					sum += cf->diskUsage();
					delete cf;
				}
			}
			catch (bt::Error & err) // make sure we catch any exceptions
			{
				Out(SYS_DIO|LOG_DEBUG) << "Error: " << err.toString() << endl;
			}
		}

		return sum;
	}

	///////////////////////////////

	Uint64 FileOffset(Chunk* c,const TorrentFile & f,Uint64 chunk_size)
	{
		return FileOffset(c->getIndex(),f,chunk_size);
	}
	
	Uint64 FileOffset(Uint32 cindex,const TorrentFile & f,Uint64 chunk_size)
	{
		return f.fileOffset(cindex,chunk_size);
	}
	
}