summaryrefslogtreecommitdiffstats
path: root/libktorrent/torrent/peersourcemanager.cpp
blob: 80af240a8797c4001242de52bc7abb0a5de9a2b1 (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
/***************************************************************************
 *   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 <tqfile.h>
#include <klocale.h>
#include <functions.h>
#include <util/log.h>
#include <torrent/globals.h>
#include <kademlia/dhtbase.h>
#include <kademlia/dhttrackerbackend.h>
#include "tracker.h"
#include "udptracker.h"
#include "httptracker.h"
#include "torrentcontrol.h"
#include "torrent.h"
#include "peermanager.h"
#include "peersourcemanager.h"

namespace bt
{
	const Uint32 INITIAL_WAIT_TIME = 30; 
	const Uint32 LONGER_WAIT_TIME = 300; 
	const Uint32 FINAL_WAIT_TIME = 1800;

	PeerSourceManager::PeerSourceManager(TorrentControl* tor,PeerManager* pman) 
	: tor(tor),pman(pman),curr(0),m_dht(0),started(false),pending(false)
	{
		failures = 0;
		trackers.setAutoDelete(true);
		no_save_custom_trackers = false;
		
		const TrackerTier* t = tor->getTorrent().getTrackerList();
		int tier = 1;
		while (t)
		{
			// add all standard trackers
			const KURL::List & tr = t->urls;
			KURL::List::const_iterator i = tr.begin();
			while (i != tr.end())
			{
				addTracker(*i,false,tier);
				i++;
			}
			
			tier++;
			t = t->next;
		}
		
		//load custom trackers
		loadCustomURLs();
				
		connect(&timer,TQT_SIGNAL(timeout()),this,TQT_SLOT(updateCurrentManually()));
	}
	
	PeerSourceManager::~PeerSourceManager()
	{
		saveCustomURLs();
		additional.setAutoDelete(true);
		TQPtrList<kt::PeerSource>::iterator itr = additional.begin();
		while (itr != additional.end())
		{
			kt::PeerSource* ps = *itr;
			ps->aboutToBeDestroyed();
			itr++;
		}
		additional.clear();
	}
		
	void PeerSourceManager::addTracker(Tracker* trk)
	{
		trackers.insert(trk->trackerURL(),trk);
		connect(trk,TQT_SIGNAL(peersReady( kt::PeerSource* )),
				 pman,TQT_SLOT(peerSourceReady( kt::PeerSource* )));
	}
		
	void PeerSourceManager::addPeerSource(kt::PeerSource* ps)
	{
		additional.append(ps);
		connect(ps,TQT_SIGNAL(peersReady( kt::PeerSource* )),
						 pman,TQT_SLOT(peerSourceReady( kt::PeerSource* )));
	}
	
	void PeerSourceManager::removePeerSource(kt::PeerSource* ps)
	{
		disconnect(ps,TQT_SIGNAL(peersReady( kt::PeerSource* )),
				pman,TQT_SLOT(peerSourceReady( kt::PeerSource* )));
		additional.remove(ps);
	}

	void PeerSourceManager::start()
	{
		if (started)
			return;
		
		started = true;
		TQPtrList<kt::PeerSource>::iterator i = additional.begin();
		while (i != additional.end())
		{
			(*i)->start();
			i++;
		}
		
		if (!curr)
		{
			if (trackers.count() > 0)
			{
				switchTracker(selectTracker());
				tor->resetTrackerStats();
				curr->start();
			}
		}
		else
		{
			tor->resetTrackerStats();
			curr->start();
		}
	}
		
	void PeerSourceManager::stop(WaitJob* wjob)
	{
		if (!started)
			return;
		
		started = false;
		TQPtrList<kt::PeerSource>::iterator i = additional.begin();
		while (i != additional.end())
		{
			(*i)->stop();
			i++;
		}
		
		if (curr)
			curr->stop(wjob);
		
		timer.stop();
		statusChanged(i18n("Stopped"));
	}
		
	void PeerSourceManager::completed()
	{
		TQPtrList<kt::PeerSource>::iterator i = additional.begin();
		while (i != additional.end())
		{
			(*i)->completed();
			i++;
		}
		
		if (curr)
			curr->completed();
	}
		
	void PeerSourceManager::manualUpdate()
	{
		TQPtrList<kt::PeerSource>::iterator i = additional.begin();
		while (i != additional.end())
		{
			(*i)->manualUpdate();
			i++;
		}
		
		if (curr)
		{
			timer.stop();
			curr->manualUpdate();
		}
	}
		
	
	
	KURL PeerSourceManager::getTrackerURL() const
	{
		if (curr)
			return curr->trackerURL();
		else
			return KURL();
	}
	
	KURL::List PeerSourceManager::getTrackerURLs()
	{
		KURL::List urls;
		const TrackerTier* t = tor->getTorrent().getTrackerList();
		while (t)
		{
			urls += t->urls;
			t = t->next;
		}
		
		urls += custom_trackers; 
		return urls; 
	}
	
	void PeerSourceManager::addTracker(KURL url, bool custom,int tier)
	{
		if (trackers.tqcontains(url))
			return;
		
		Tracker* trk = 0;
		if (url.protocol() == "udp")
			trk = new UDPTracker(url,tor,tor->getTorrent().getPeerID(),tier);
		else
			trk = new HTTPTracker(url,tor,tor->getTorrent().getPeerID(),tier);
		
		addTracker(trk);
		if (custom)
		{
			custom_trackers.append(url);
			if (!no_save_custom_trackers)
				saveCustomURLs();
		}
	}
	
	bool PeerSourceManager::removeTracker(KURL url)
	{
		if (!custom_trackers.tqcontains(url))
			return false;
		
		custom_trackers.remove(url);
		Tracker* trk = trackers.tqfind(url);
		if (curr == trk)
		{
			// do a timed delete on the tracker, so the stop signal
			// has plenty of time to reach it
			trk->stop();
			trk->timedDelete(10 * 1000);
			trackers.setAutoDelete(false);
			trackers.erase(url);
			trackers.setAutoDelete(true);
			
			if (trackers.count() > 0)
			{
				switchTracker(selectTracker());
				tor->resetTrackerStats();
				curr->start();
			}
		}
		else
		{
			// just delete if not the current one
			trackers.erase(url);
		}
		saveCustomURLs();
		return true;
	}
	
	void PeerSourceManager::setTracker(KURL url)
	{
		Tracker* trk = trackers.tqfind(url);
		if (!trk)
			return;
		
		if (curr != trk)
		{
			if (curr)
				curr->stop();
			switchTracker(trk);
			tor->resetTrackerStats();
			trk->start();
		}
	}
	
	void PeerSourceManager::restoreDefault()
	{
		KURL::List::iterator i = custom_trackers.begin();
		while (i != custom_trackers.end())
		{
			Tracker* t = trackers.tqfind(*i);
			if (t)
			{
				if (curr == t)
				{
					if (t->isStarted())
						t->stop();
					
					curr = 0;
					trackers.erase(*i);
					if (trackers.count() > 0)
					{
						switchTracker(trackers.begin()->second);
						if (started)
						{
							tor->resetTrackerStats();
							curr->start();
						}
					}
				}
				else
				{
					trackers.erase(*i);
				}
			}
			i++;
		}
		
		custom_trackers.clear();
		saveCustomURLs();
	}
	
	void PeerSourceManager::saveCustomURLs()
	{
		TQString trackers_file = tor->getTorDir() + "trackers"; 
		TQFile file(trackers_file);
		if(!file.open(IO_WriteOnly))
			return;
		
		TQTextStream stream(&file);
		for (KURL::List::iterator i = custom_trackers.begin();i != custom_trackers.end();i++)
			stream << (*i).prettyURL() << ::endl;
	}
	
	void PeerSourceManager::loadCustomURLs()
	{
		TQString trackers_file = tor->getTorDir() + "trackers";
		TQFile file(trackers_file);
		if(!file.open(IO_ReadOnly))
			return;
		
		no_save_custom_trackers = true;
		TQTextStream stream(&file);
		while (!stream.atEnd())
		{
			KURL url = stream.readLine();
			addTracker(url,true);
		}
		no_save_custom_trackers = false;
	}
	
	Tracker* PeerSourceManager::selectTracker()
	{
		Tracker* n = 0;
		PtrMap<KURL,Tracker>::iterator i = trackers.begin();
		while (i != trackers.end())
		{
			Tracker* t = i->second;
			if (!n)
				n = t;
			else if (t->failureCount() < n->failureCount())
				n = t;
			else if (t->failureCount() == n->failureCount())
				n = t->getTier() < n->getTier() ? t : n;
			i++;
		}
		
		if (n)
		{
			Out(SYS_TRK|LOG_DEBUG) << "Selected tracker " << n->trackerURL().prettyURL() 
					<< " (tier = " << n->getTier() << ")" << endl;
		}
		
		return n;
	}
	
	void PeerSourceManager::onTrackerError(const TQString & err)
	{
		failures++;
		pending = false;
		if (started)
			statusChanged(err);
		
		if (!started)
			return;
		
		// select an other tracker
		Tracker* trk = selectTracker();
		
		if (!trk)
		{
			if (curr->failureCount() > 5)
			{
				// we failed to contact the only tracker 5 times in a row, so try again in 
				// 30 minutes
				curr->setInterval(FINAL_WAIT_TIME);
				timer.start(FINAL_WAIT_TIME * 1000,true);
				request_time = TQDateTime::tqcurrentDateTime();
			}
			else if (curr->failureCount() > 2)
			{
				// we failed to contact the only tracker 3 times in a row, so try again in 
				// a minute or 5, no need for hammering every 30 seconds
				curr->setInterval(LONGER_WAIT_TIME);
				timer.start(LONGER_WAIT_TIME * 1000,true);
				request_time = TQDateTime::tqcurrentDateTime();
			}
			else
			{
				// lets not hammer and wait 30 seconds
				curr->setInterval(INITIAL_WAIT_TIME);
				timer.start(INITIAL_WAIT_TIME * 1000,true);
				request_time = TQDateTime::tqcurrentDateTime();
			}
		}
		else
		{
			curr->stop();
			// switch to another one
			switchTracker(trk);
			if (trk->failureCount() == 0)
			{
				tor->resetTrackerStats();
				curr->start();
			}
			else if (trk->failureCount() > 5)
			{
				curr->setInterval(FINAL_WAIT_TIME);
				timer.start(FINAL_WAIT_TIME * 1000,true);
				request_time = TQDateTime::tqcurrentDateTime();
			}
			else if (trk->failureCount() > 2)
			{
				// we tried everybody 3 times and it didn't work
				// wait 5 minutes and try again
				curr->setInterval(LONGER_WAIT_TIME);
				timer.start(LONGER_WAIT_TIME * 1000,true);
				request_time = TQDateTime::tqcurrentDateTime();
			}
			else
			{
				// wait 30 seconds and try again
				curr->setInterval(INITIAL_WAIT_TIME);
				timer.start(INITIAL_WAIT_TIME * 1000,true);
				request_time = TQDateTime::tqcurrentDateTime();
			}
		}
	}
		
	void PeerSourceManager::onTrackerOK()
	{
		failures = 0;
		if (started)
		{
			timer.start(curr->getInterval() * 1000,true);
			curr->scrape();
		}
		pending = false;
		if (started)
			statusChanged(i18n("OK"));
		request_time = TQDateTime::tqcurrentDateTime();
	}
		
	void PeerSourceManager::onTrackerRequestPending()
	{
		if (started)
			statusChanged(i18n("Announcing"));
		pending = true;
	}
	
	void PeerSourceManager::updateCurrentManually()
	{
		if (!curr)
			return;
		
		if (!curr->isStarted())
			tor->resetTrackerStats();
		
		curr->manualUpdate();
	}
	
	void PeerSourceManager::switchTracker(Tracker* trk)
	{
		if (curr == trk)
			return;
	
		if (curr)
		{
			disconnect(curr,TQT_SIGNAL(requestFailed( const TQString& )),
					   this,TQT_SLOT(onTrackerError( const TQString& )));
			disconnect(curr,TQT_SIGNAL(requestOK()),this,TQT_SLOT(onTrackerOK()));
			disconnect(curr,TQT_SIGNAL(requestPending()),this,TQT_SLOT(onTrackerRequestPending()));
			curr = 0;
		}
		
		curr = trk;
		if (curr)
		{
			Out(SYS_TRK|LOG_NOTICE) << "Switching to tracker " << trk->trackerURL() << endl;
			TQObject::connect(curr,TQT_SIGNAL(requestFailed( const TQString& )),
					this,TQT_SLOT(onTrackerError( const TQString& )));
			
			TQObject::connect(curr,TQT_SIGNAL(requestOK()),
					this,TQT_SLOT(onTrackerOK()));
			
			TQObject::connect(curr,TQT_SIGNAL(requestPending()),
					this,TQT_SLOT(onTrackerRequestPending()));
		}
	}
	
	Uint32 PeerSourceManager::getTimeToNextUpdate() const
	{
		if (pending || !started || !curr)
			return 0;
		
		return curr->getInterval() - request_time.secsTo(TQDateTime::tqcurrentDateTime());
	}
	
	Uint32 PeerSourceManager::getNumSeeders() const
	{
		return curr ? curr->getNumSeeders() : 0;
	}
		
	
	Uint32 PeerSourceManager::getNumLeechers() const
	{
		return curr ? curr->getNumLeechers() : 0;
	}
	
	void PeerSourceManager::addDHT()
	{
		if(m_dht)
		{
			removePeerSource(m_dht);
			delete m_dht;
		}
		
		m_dht = new dht::DHTTrackerBackend(Globals::instance().getDHT(),tor);
		
		// add the DHT source
		addPeerSource(m_dht);
	}

	void PeerSourceManager::removeDHT()
	{
		if(m_dht == 0)
		{
			removePeerSource(m_dht);
			return;
		}
		
		removePeerSource(m_dht);
		delete m_dht;
		m_dht = 0;
	}
	
	bool PeerSourceManager::dhtStarted()
	{
		return m_dht != 0;
	}
	
	
}

#include "peersourcemanager.moc"