summaryrefslogtreecommitdiff
path: root/src/TrackerWatcherCommand.cc
blob: 06d7fc3e327909711691932bab1822fec31c6655 (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
/* <!-- copyright */
/*
 * aria2 - The high speed download utility
 *
 * Copyright (C) 2006 Tatsuhiro Tsujikawa
 *
 * 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
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
/* copyright --> */
#include "TrackerWatcherCommand.h"

#include <sstream>

#include "DownloadEngine.h"
#include "BtAnnounce.h"
#include "BtRuntime.h"
#include "PieceStorage.h"
#include "PeerStorage.h"
#include "Peer.h"
#include "prefs.h"
#include "message.h"
#include "ByteArrayDiskWriterFactory.h"
#include "RecoverableException.h"
#include "PeerInitiateConnectionCommand.h"
#include "DiskAdaptor.h"
#include "FileEntry.h"
#include "RequestGroup.h"
#include "Option.h"
#include "DlAbortEx.h"
#include "Logger.h"
#include "LogFactory.h"
#include "A2STR.h"
#include "SocketCore.h"
#include "Request.h"
#include "AnnounceTier.h"
#include "DownloadContext.h"
#include "bittorrent_helper.h"
#include "a2functional.h"
#include "util.h"
#include "fmt.h"
#include "UDPTrackerRequest.h"
#include "UDPTrackerClient.h"
#include "BtRegistry.h"
#include "NameResolveCommand.h"

namespace aria2 {

HTTPAnnRequest::HTTPAnnRequest(const SharedHandle<RequestGroup>& rg)
  : rg_(rg)
{}

HTTPAnnRequest::~HTTPAnnRequest()
{}

bool HTTPAnnRequest::stopped() const
{
  return rg_->getNumCommand() == 0;
}

bool HTTPAnnRequest::success() const
{
  return rg_->downloadFinished();
}

void HTTPAnnRequest::stop(DownloadEngine* e)
{
  rg_->setForceHaltRequested(true);
}

bool HTTPAnnRequest::issue(DownloadEngine* e)
{
  try {
    std::vector<Command*>* commands = new std::vector<Command*>();
    auto_delete_container<std::vector<Command*> > commandsDel(commands);
    rg_->createInitialCommand(*commands, e);
    e->addCommand(*commands);
    e->setNoWait(true);
    commands->clear();
    A2_LOG_DEBUG("added tracker request command");
    return true;
  } catch(RecoverableException& ex) {
    A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
    return false;
  }
}

bool HTTPAnnRequest::processResponse
(const SharedHandle<BtAnnounce>& btAnnounce)
{
  try {
    std::stringstream strm;
    unsigned char data[2048];
    rg_->getPieceStorage()->getDiskAdaptor()->openFile();
    while(1) {
      ssize_t dataLength = rg_->getPieceStorage()->
        getDiskAdaptor()->readData(data, sizeof(data), strm.tellp());
      if(dataLength == 0) {
        break;
      }
      strm.write(reinterpret_cast<const char*>(data), dataLength);
    }
    std::string res = strm.str();
    btAnnounce->processAnnounceResponse
      (reinterpret_cast<const unsigned char*>(res.c_str()), res.size());
    return true;
  } catch(RecoverableException& e) {
    A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
    return false;
  }
}

UDPAnnRequest::UDPAnnRequest(const SharedHandle<UDPTrackerRequest>& req)
  : req_(req)
{}

UDPAnnRequest::~UDPAnnRequest()
{}

bool UDPAnnRequest::stopped() const
{
  return !req_ || req_->state == UDPT_STA_COMPLETE;
}

bool UDPAnnRequest::success() const
{
  return req_ && req_->state == UDPT_STA_COMPLETE &&
    req_->error == UDPT_ERR_SUCCESS;
}

void UDPAnnRequest::stop(DownloadEngine* e)
{
  if(req_) {
    req_.reset();
  }
}

bool UDPAnnRequest::issue(DownloadEngine* e)
{
  if(req_) {
    NameResolveCommand* command = new NameResolveCommand
      (e->newCUID(), e, req_);
    e->addCommand(command);
    e->setNoWait(true);
    return true;
  } else {
    return false;
  }
}

bool UDPAnnRequest::processResponse
(const SharedHandle<BtAnnounce>& btAnnounce)
{
  if(req_) {
    btAnnounce->processUDPTrackerResponse(req_);
    return true;
  } else {
    return false;
  }
}

TrackerWatcherCommand::TrackerWatcherCommand
(cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e)
  : Command(cuid),
    requestGroup_(requestGroup),
    e_(e),
    udpTrackerClient_(e_->getBtRegistry()->getUDPTrackerClient())
{
  requestGroup_->increaseNumCommand();
  if(udpTrackerClient_) {
    udpTrackerClient_->increaseWatchers();
  }
}

TrackerWatcherCommand::~TrackerWatcherCommand()
{
  requestGroup_->decreaseNumCommand();
  if(udpTrackerClient_) {
    udpTrackerClient_->decreaseWatchers();
  }
}

bool TrackerWatcherCommand::execute() {
  if(requestGroup_->isForceHaltRequested()) {
    if(!trackerRequest_) {
      return true;
    } else if(trackerRequest_->stopped() ||
              trackerRequest_->success()) {
      return true;
    } else {
      trackerRequest_->stop(e_);
      e_->setRefreshInterval(0);
      e_->addCommand(this);
      return false;
    }
  }
  if(btAnnounce_->noMoreAnnounce()) {
    A2_LOG_DEBUG("no more announce");
    return true;
  }
  if(!trackerRequest_) {
    trackerRequest_ = createAnnounce(e_);
    if(trackerRequest_) {
      trackerRequest_->issue(e_);
    }
  } else if(trackerRequest_->stopped()) {
    // We really want to make sure that tracker request has finished
    // by checking getNumCommand() == 0. Because we reset
    // trackerRequestGroup_, if it is still used in other Command, we
    // will get Segmentation fault.
    if(trackerRequest_->success()) {
      if(trackerRequest_->processResponse(btAnnounce_)) {
        btAnnounce_->announceSuccess();
        btAnnounce_->resetAnnounce();
        addConnection();
      } else {
        btAnnounce_->announceFailure();
        if(btAnnounce_->isAllAnnounceFailed()) {
          btAnnounce_->resetAnnounce();
        }
      }
      trackerRequest_.reset();
    } else {
      // handle errors here
      btAnnounce_->announceFailure(); // inside it, trackers = 0.
      trackerRequest_.reset();
      if(btAnnounce_->isAllAnnounceFailed()) {
        btAnnounce_->resetAnnounce();
      }
    }
  }
  e_->addCommand(this);
  return false;
}

void TrackerWatcherCommand::addConnection()
{
  while(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) {
    if(!peerStorage_->isPeerAvailable()) {
      break;
    }
    cuid_t ncuid = e_->newCUID();
    SharedHandle<Peer> peer = peerStorage_->checkoutPeer(ncuid);
    // sanity check
    if(!peer) {
      break;
    }
    PeerInitiateConnectionCommand* command;
    command = new PeerInitiateConnectionCommand(ncuid, requestGroup_, peer,
                                                e_, btRuntime_);
    command->setPeerStorage(peerStorage_);
    command->setPieceStorage(pieceStorage_);
    e_->addCommand(command);
    A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Adding new command CUID#%" PRId64 "",
                     getCuid(), peer->usedBy()));
  }
}

SharedHandle<AnnRequest>
TrackerWatcherCommand::createAnnounce(DownloadEngine* e)
{
  SharedHandle<AnnRequest> treq;
  while(!btAnnounce_->isAllAnnounceFailed() &&
        btAnnounce_->isAnnounceReady()) {
    std::string uri = btAnnounce_->getAnnounceUrl();
    uri_split_result res;
    memset(&res, 0, sizeof(res));
    if(uri_split(&res, uri.c_str()) == 0) {
      // Without UDP tracker support, send it to normal tracker flow
      // and make it fail.
      if(udpTrackerClient_ &&
         uri::getFieldString(res, USR_SCHEME, uri.c_str()) == "udp") {
        uint16_t localPort;
        localPort = e->getBtRegistry()->getUdpPort();
        treq = createUDPAnnRequest
          (uri::getFieldString(res, USR_HOST, uri.c_str()), res.port,
           localPort);
      } else {
        treq = createHTTPAnnRequest(btAnnounce_->getAnnounceUrl());
      }
      btAnnounce_->announceStart(); // inside it, trackers++.
      break;
    } else {
      btAnnounce_->announceFailure();
    }
  }
  if(btAnnounce_->isAllAnnounceFailed()) {
    btAnnounce_->resetAnnounce();
  }
  return treq;
}

SharedHandle<AnnRequest>
TrackerWatcherCommand::createUDPAnnRequest(const std::string& host,
                                           uint16_t port,
                                           uint16_t localPort)
{
  SharedHandle<UDPTrackerRequest> req =
    btAnnounce_->createUDPTrackerRequest(host, port, localPort);
  return SharedHandle<AnnRequest>(new UDPAnnRequest(req));
}

namespace {
bool backupTrackerIsAvailable
(const SharedHandle<DownloadContext>& context)
{
  SharedHandle<TorrentAttribute> torrentAttrs =
    bittorrent::getTorrentAttrs(context);
  if(torrentAttrs->announceList.size() >= 2) {
    return true;
  }
  if(torrentAttrs->announceList.empty()) {
    return false;
  }
  if(torrentAttrs->announceList[0].size() >= 2) {
    return true;
  } else {
    return false;
  }
}
} // namespace

SharedHandle<AnnRequest>
TrackerWatcherCommand::createHTTPAnnRequest(const std::string& uri)
{
  std::vector<std::string> uris;
  uris.push_back(uri);
  SharedHandle<Option> option = util::copy(getOption());
  SharedHandle<RequestGroup> rg(new RequestGroup(GroupId::create(), option));
  if(backupTrackerIsAvailable(requestGroup_->getDownloadContext())) {
    A2_LOG_DEBUG("This is multi-tracker announce.");
  } else {
    A2_LOG_DEBUG("This is single-tracker announce.");
  }
  rg->setNumConcurrentCommand(1);
  // If backup tracker is available, try 2 times for each tracker
  // and if they all fails, then try next one.
  option->put(PREF_MAX_TRIES, "2");
  // TODO When dry-run mode becomes available in BitTorrent, set
  // PREF_DRY_RUN=false too.
  option->put(PREF_USE_HEAD, A2_V_FALSE);
  // Setting tracker timeouts
  rg->setTimeout(option->getAsInt(PREF_BT_TRACKER_TIMEOUT));
  option->put(PREF_CONNECT_TIMEOUT,
              option->get(PREF_BT_TRACKER_CONNECT_TIMEOUT));
  option->put(PREF_REUSE_URI, A2_V_FALSE);
  option->put(PREF_SELECT_LEAST_USED_HOST, A2_V_FALSE);
  SharedHandle<DownloadContext> dctx
    (new DownloadContext(option->getAsInt(PREF_PIECE_LENGTH),
                         0,
                         "[tracker.announce]"));
  dctx->getFileEntries().front()->setUris(uris);
  rg->setDownloadContext(dctx);
  SharedHandle<DiskWriterFactory> dwf(new ByteArrayDiskWriterFactory());
  rg->setDiskWriterFactory(dwf);
  rg->setFileAllocationEnabled(false);
  rg->setPreLocalFileCheckEnabled(false);
  // Clearing pre- and post handler is not needed because the
  // RequestGroup is not handled by RequestGroupMan.
  rg->clearPreDownloadHandler();
  rg->clearPostDownloadHandler();
  dctx->setAcceptMetalink(false);
  A2_LOG_INFO(fmt("Creating tracker request group GID#%s",
                  GroupId::toHex(rg->getGID()).c_str()));
  return SharedHandle<AnnRequest>(new HTTPAnnRequest(rg));
}

void TrackerWatcherCommand::setBtRuntime
(const SharedHandle<BtRuntime>& btRuntime)
{
  btRuntime_ = btRuntime;
}

void TrackerWatcherCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
  peerStorage_ = peerStorage;
}

void TrackerWatcherCommand::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
  pieceStorage_ = pieceStorage;
}

void TrackerWatcherCommand::setBtAnnounce
(const SharedHandle<BtAnnounce>& btAnnounce)
{
  btAnnounce_ = btAnnounce;
}

const SharedHandle<Option>& TrackerWatcherCommand::getOption() const
{
  return requestGroup_->getOption();
}

} // namespace aria2