RequestGroup.cc 42.8 KB
Newer Older
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
/* <!-- 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 "RequestGroup.h"

#include <cassert>
#include <algorithm>

#include "PostDownloadHandler.h"
#include "DownloadEngine.h"
#include "SegmentMan.h"
#include "NullProgressInfoFile.h"
#include "Dependency.h"
#include "prefs.h"
#include "CreateRequestCommand.h"
#include "File.h"
#include "message.h"
#include "util.h"
#include "LogFactory.h"
#include "Logger.h"
#include "DiskAdaptor.h"
#include "DiskWriterFactory.h"
#include "RecoverableException.h"
#include "StreamCheckIntegrityEntry.h"
#include "CheckIntegrityCommand.h"
#include "UnknownLengthPieceStorage.h"
#include "DownloadContext.h"
#include "DlAbortEx.h"
#include "DownloadFailureException.h"
#include "RequestGroupMan.h"
#include "DefaultBtProgressInfoFile.h"
#include "DefaultPieceStorage.h"
64
#include "download_handlers.h"
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
#include "MemoryBufferPreDownloadHandler.h"
#include "DownloadHandlerConstants.h"
#include "Option.h"
#include "FileEntry.h"
#include "Request.h"
#include "FileAllocationIterator.h"
#include "fmt.h"
#include "A2STR.h"
#include "URISelector.h"
#include "InorderURISelector.h"
#include "PieceSelector.h"
#include "a2functional.h"
#include "SocketCore.h"
#include "SimpleRandomizer.h"
#include "Segment.h"
#include "SocketRecvBuffer.h"
81
#include "RequestGroupCriteria.h"
82 83
#include "CheckIntegrityCommand.h"
#include "ChecksumCheckIntegrityEntry.h"
84
#ifdef ENABLE_BITTORRENT
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
#include "bittorrent_helper.h"
#include "BtRegistry.h"
#include "BtCheckIntegrityEntry.h"
#include "DefaultPeerStorage.h"
#include "DefaultBtAnnounce.h"
#include "BtRuntime.h"
#include "BtSetup.h"
#include "BtPostDownloadHandler.h"
#include "DHTSetup.h"
#include "DHTRegistry.h"
#include "DHTNode.h"
#include "DHTRoutingTable.h"
#include "DHTTaskQueue.h"
#include "DHTTaskFactory.h"
#include "DHTTokenTracker.h"
#include "DHTMessageDispatcher.h"
#include "DHTMessageReceiver.h"
#include "DHTMessageFactory.h"
#include "DHTMessageCallback.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "BtMessageDispatcher.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
#include "DHTPeerAnnounceStorage.h"
#include "DHTEntryPointNameResolveCommand.h"
#include "LongestSequencePieceSelector.h"
#include "PriorityPieceSelector.h"
#include "bittorrent_helper.h"
115 116
#endif // ENABLE_BITTORRENT
#ifdef ENABLE_METALINK
117
#include "MetalinkPostDownloadHandler.h"
118 119 120 121
#endif // ENABLE_METALINK

namespace aria2 {

122 123
RequestGroup::RequestGroup(const std::shared_ptr<GroupId>& gid,
                           const std::shared_ptr<Option>& option)
124 125 126 127 128 129
    : belongsToGID_(0),
      gid_(gid),
      option_(option),
      progressInfoFile_(std::make_shared<NullProgressInfoFile>()),
      uriSelector_(make_unique<InorderURISelector>()),
      requestGroupMan_(nullptr),
130
#ifdef ENABLE_BITTORRENT
131 132
      btRuntime_(nullptr),
      peerStorage_(nullptr),
133
#endif // ENABLE_BITTORRENT
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
      followingGID_(0),
      lastModifiedTime_(Time::null()),
      timeout_(option->getAsInt(PREF_TIMEOUT)),
      state_(STATE_WAITING),
      numConcurrentCommand_(option->getAsInt(PREF_SPLIT)),
      numStreamConnection_(0),
      numStreamCommand_(0),
      numCommand_(0),
      fileNotFoundCount_(0),
      maxDownloadSpeedLimit_(option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT)),
      maxUploadSpeedLimit_(option->getAsInt(PREF_MAX_UPLOAD_LIMIT)),
      resumeFailureCount_(0),
      haltReason_(RequestGroup::NONE),
      lastErrorCode_(error_code::UNDEFINED),
      saveControlFile_(true),
      preLocalFileCheckEnabled_(true),
      haltRequested_(false),
      forceHaltRequested_(false),
      pauseRequested_(false),
153
      restartRequested_(false),
154 155
      inMemoryDownload_(false),
      seedOnly_(false)
156 157
{
  fileAllocationEnabled_ = option_->get(PREF_FILE_ALLOCATION) != V_NONE;
158
  if (!option_->getAsBool(PREF_DRY_RUN)) {
159 160 161 162 163
    initializePreDownloadHandler();
    initializePostDownloadHandler();
  }
}

164
RequestGroup::~RequestGroup() = default;
165 166 167 168

bool RequestGroup::isCheckIntegrityReady()
{
  return option_->getAsBool(PREF_CHECK_INTEGRITY) &&
169 170 171
         ((downloadContext_->isChecksumVerificationAvailable() &&
           downloadFinishedByFileLength()) ||
          downloadContext_->isPieceHashVerificationAvailable());
172 173 174 175
}

bool RequestGroup::downloadFinished() const
{
176
  if (!pieceStorage_) {
177 178
    return false;
  }
179
  return pieceStorage_->downloadFinished();
180 181 182 183
}

bool RequestGroup::allDownloadFinished() const
{
184
  if (!pieceStorage_) {
185 186
    return false;
  }
187
  return pieceStorage_->allDownloadFinished();
188 189
}

190
std::pair<error_code::Value, std::string> RequestGroup::downloadResult() const
191
{
192 193
  if (downloadFinished() && !downloadContext_->isChecksumVerificationNeeded()) {
    return std::make_pair(error_code::FINISHED, "");
194 195
  }

196 197
  if (haltReason_ == RequestGroup::USER_REQUEST) {
    return std::make_pair(error_code::REMOVED, "");
198 199
  }

200 201 202
  if (lastErrorCode_ == error_code::UNDEFINED) {
    if (haltReason_ == RequestGroup::SHUTDOWN_SIGNAL) {
      return std::make_pair(error_code::IN_PROGRESS, "");
203
    }
204
    return std::make_pair(error_code::UNKNOWN_ERROR, "");
205
  }
206

207
  return std::make_pair(lastErrorCode_, lastErrorMessage_);
208 209 210 211
}

void RequestGroup::closeFile()
{
212
  if (pieceStorage_) {
213
    pieceStorage_->flushWrDiskCacheEntry();
214 215 216 217 218 219
    pieceStorage_->getDiskAdaptor()->closeFile();
  }
}

// TODO The function name is not intuitive at all.. it does not convey
// that this function open file.
220
std::unique_ptr<CheckIntegrityEntry> RequestGroup::createCheckIntegrityEntry()
221
{
222 223
  auto infoFile = std::make_shared<DefaultBtProgressInfoFile>(
      downloadContext_, pieceStorage_, option_.get());
224

225 226
  if (option_->getAsBool(PREF_CHECK_INTEGRITY) &&
      downloadContext_->isPieceHashVerificationAvailable()) {
227 228 229
    // When checking piece hash, we don't care file is downloaded and
    // infoFile exists.
    loadAndOpenFile(infoFile);
230
    return make_unique<StreamCheckIntegrityEntry>(this);
231 232 233
  }

  if (isPreLocalFileCheckEnabled() &&
234 235
      (infoFile->exists() || (File(getFirstFilePath()).exists() &&
                              option_->getAsBool(PREF_CONTINUE)))) {
236 237 238 239 240
    // If infoFile exists or -c option is given, we need to check
    // download has been completed (which is determined after
    // loadAndOpenFile()). If so, use ChecksumCheckIntegrityEntry when
    // verification is enabled, because CreateRequestCommand does not
    // issue checksum verification and download fails without it.
241
    loadAndOpenFile(infoFile);
242 243
    if (downloadFinished()) {
      if (downloadContext_->isChecksumVerificationNeeded()) {
244
        A2_LOG_INFO(MSG_HASH_CHECK_NOT_DONE);
245
        auto tempEntry = make_unique<ChecksumCheckIntegrityEntry>(this);
246
        tempEntry->setRedownload(true);
247
        return std::move(tempEntry);
248 249
      }
      downloadContext_->setChecksumVerified(true);
250
      A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, gid_->toHex().c_str(),
251 252
                        downloadContext_->getBasePath().c_str()));
      return nullptr;
253
    }
254 255 256 257 258 259 260 261 262 263
    return make_unique<StreamCheckIntegrityEntry>(this);
  }

  if (downloadFinishedByFileLength() &&
      downloadContext_->isChecksumVerificationAvailable()) {
    pieceStorage_->markAllPiecesDone();
    loadAndOpenFile(infoFile);
    auto tempEntry = make_unique<ChecksumCheckIntegrityEntry>(this);
    tempEntry->setRedownload(true);
    return std::move(tempEntry);
264
  }
265 266 267

  loadAndOpenFile(infoFile);
  return make_unique<StreamCheckIntegrityEntry>(this);
268 269
}

270 271
void RequestGroup::createInitialCommand(
    std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e)
272 273 274 275 276 277 278
{
  // Start session timer here.  When file size becomes known, it will
  // be reset again in *FileAllocationEntry, because hash check and
  // file allocation takes a time.  For downloads in which file size
  // is unknown, session timer will not be reset.
  downloadContext_->resetDownloadStartTime();
#ifdef ENABLE_BITTORRENT
279 280 281 282
  if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
    auto torrentAttrs = bittorrent::getTorrentAttrs(downloadContext_);
    bool metadataGetMode = torrentAttrs->metadata.empty();
    if (option_->getAsBool(PREF_DRY_RUN)) {
283 284
      throw DOWNLOAD_FAILURE_EXCEPTION(
          "Cancel BitTorrent download in dry-run context.");
285 286 287 288 289
    }
    auto& btRegistry = e->getBtRegistry();
    if (btRegistry->getDownloadContext(torrentAttrs->infoHash)) {
      // TODO If metadataGetMode == false and each FileEntry has
      // URI, then go without BT.
290 291 292 293
      throw DOWNLOAD_FAILURE_EXCEPTION2(
          fmt("InfoHash %s is already registered.",
              bittorrent::getInfoHashString(downloadContext_).c_str()),
          error_code::DUPLICATE_INFO_HASH);
294 295 296 297 298
    }
    if (metadataGetMode) {
      // Use UnknownLengthPieceStorage.
      initPieceStorage();
    }
299 300 301 302 303
    else if (e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
      throw DOWNLOAD_FAILURE_EXCEPTION2(
          fmt(EX_DUPLICATE_FILE_DOWNLOAD,
              downloadContext_->getBasePath().c_str()),
          error_code::DUPLICATE_DOWNLOAD);
304 305 306
    }
    else {
      initPieceStorage();
307
      if (downloadContext_->getFileEntries().size() > 1) {
308
        pieceStorage_->setupFileFilter();
309
      }
310 311 312
    }

    std::shared_ptr<DefaultBtProgressInfoFile> progressInfoFile;
313 314 315
    if (!metadataGetMode) {
      progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>(
          downloadContext_, pieceStorage_, option_.get());
316 317 318 319 320
    }

    auto btRuntime = std::make_shared<BtRuntime>();
    btRuntime->setMaxPeers(option_->getAsInt(PREF_BT_MAX_PEERS));
    btRuntime_ = btRuntime.get();
321
    if (progressInfoFile) {
322 323 324 325 326 327 328
      progressInfoFile->setBtRuntime(btRuntime);
    }

    auto peerStorage = std::make_shared<DefaultPeerStorage>();
    peerStorage->setBtRuntime(btRuntime);
    peerStorage->setPieceStorage(pieceStorage_);
    peerStorage_ = peerStorage.get();
329
    if (progressInfoFile) {
330 331 332
      progressInfoFile->setPeerStorage(peerStorage);
    }

333 334
    auto btAnnounce = std::make_shared<DefaultBtAnnounce>(
        downloadContext_.get(), option_.get());
335 336 337
    btAnnounce->setBtRuntime(btRuntime);
    btAnnounce->setPieceStorage(pieceStorage_);
    btAnnounce->setPeerStorage(peerStorage);
338 339
    btAnnounce->setUserDefinedInterval(
        std::chrono::seconds(option_->getAsInt(PREF_BT_TRACKER_INTERVAL)));
340 341 342
    btAnnounce->shuffleAnnounce();

    assert(!btRegistry->get(gid_->getNumericId()));
343 344 345 346 347
    btRegistry->put(
        gid_->getNumericId(),
        make_unique<BtObject>(
            downloadContext_, pieceStorage_, peerStorage, btAnnounce, btRuntime,
            (progressInfoFile ? progressInfoFile : progressInfoFile_)));
348

349 350 351
    if (option_->getAsBool(PREF_ENABLE_DHT) ||
        (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
         option_->getAsBool(PREF_ENABLE_DHT6))) {
352

353
      if (option_->getAsBool(PREF_ENABLE_DHT)) {
354 355 356 357 358 359 360
        std::vector<std::unique_ptr<Command>> c, rc;
        std::tie(c, rc) = DHTSetup().setup(e, AF_INET);

        e->addCommand(std::move(c));
        for (auto& a : rc) {
          e->addRoutineCommand(std::move(a));
        }
361
      }
362

363 364
      if (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
          option_->getAsBool(PREF_ENABLE_DHT6)) {
365 366 367 368 369 370 371
        std::vector<std::unique_ptr<Command>> c, rc;
        std::tie(c, rc) = DHTSetup().setup(e, AF_INET6);

        e->addCommand(std::move(c));
        for (auto& a : rc) {
          e->addRoutineCommand(std::move(a));
        }
372
      }
373
      const auto& nodes = torrentAttrs->nodes;
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
      if (!torrentAttrs->privateTorrent && !nodes.empty()) {
        if (DHTRegistry::isInitialized()) {
          auto command = make_unique<DHTEntryPointNameResolveCommand>(
              e->newCUID(), e, AF_INET, nodes);
          const auto& data = DHTRegistry::getData();
          command->setTaskQueue(data.taskQueue.get());
          command->setTaskFactory(data.taskFactory.get());
          command->setRoutingTable(data.routingTable.get());
          command->setLocalNode(data.localNode);
          e->addCommand(std::move(command));
        }

        if (DHTRegistry::isInitialized6()) {
          auto command = make_unique<DHTEntryPointNameResolveCommand>(
              e->newCUID(), e, AF_INET6, nodes);
          const auto& data = DHTRegistry::getData6();
          command->setTaskQueue(data.taskQueue.get());
          command->setTaskFactory(data.taskFactory.get());
          command->setRoutingTable(data.routingTable.get());
          command->setLocalNode(data.localNode);
          e->addCommand(std::move(command));
        }
396
      }
397 398
    }
    else if (metadataGetMode) {
399 400 401 402 403
      A2_LOG_NOTICE(_("For BitTorrent Magnet URI, enabling DHT is strongly"
                      " recommended. See --enable-dht option."));
    }

    if (metadataGetMode) {
404 405 406
      BtCheckIntegrityEntry{this}.onDownloadIncomplete(commands, e);
      return;
    }
407

408 409 410 411 412 413 414
    removeDefunctControlFile(progressInfoFile);
    {
      int64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
      if (actualFileSize == downloadContext_->getTotalLength()) {
        // First, make DiskAdaptor read-only mode to allow the
        // program to seed file in read-only media.
        pieceStorage_->getDiskAdaptor()->enableReadOnly();
415
      }
416 417 418 419 420
      else {
        // Open file in writable mode to allow the program
        // truncate the file to downloadContext_->getTotalLength()
        A2_LOG_DEBUG(fmt("File size not match. File is opened in writable"
                         " mode. Expected:%" PRId64 " Actual:%" PRId64 "",
421
                         downloadContext_->getTotalLength(), actualFileSize));
422
      }
423 424
    }
    // Call Load, Save and file allocation command here
425
    if (progressInfoFile->exists()) {
426 427 428 429
      // load .aria2 file if it exists.
      progressInfoFile->load();
      pieceStorage_->getDiskAdaptor()->openFile();
    }
430 431 432 433
    else if (pieceStorage_->getDiskAdaptor()->fileExists()) {
      if (!option_->getAsBool(PREF_CHECK_INTEGRITY) &&
          !option_->getAsBool(PREF_ALLOW_OVERWRITE) &&
          !option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
434
        // TODO we need this->haltRequested = true?
435 436 437 438
        throw DOWNLOAD_FAILURE_EXCEPTION2(
            fmt(MSG_FILE_ALREADY_EXISTS,
                downloadContext_->getBasePath().c_str()),
            error_code::FILE_ALREADY_EXISTS);
439
      }
440
      pieceStorage_->getDiskAdaptor()->openFile();
441
      if (option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
442
        pieceStorage_->markAllPiecesDone();
443
      }
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    }
    else {
      pieceStorage_->getDiskAdaptor()->openFile();
    }
    progressInfoFile_ = progressInfoFile;

    auto entry = make_unique<BtCheckIntegrityEntry>(this);
    // --bt-seed-unverified=true is given and download has completed, skip
    // validation for piece hashes.
    if (option_->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
        pieceStorage_->downloadFinished()) {
      entry->onDownloadFinished(commands, e);
    }
    else {
      processCheckIntegrityEntry(commands, std::move(entry), e);
    }
    return;
461 462
  }
#endif // ENABLE_BITTORRENT
463 464

  if (downloadContext_->getFileEntries().size() == 1) {
465 466
    // TODO I assume here when totallength is set to DownloadContext and it is
    // not 0, then filepath is also set DownloadContext correctly....
467
    if (option_->getAsBool(PREF_DRY_RUN) ||
468
        downloadContext_->getTotalLength() == 0) {
469
      createNextCommand(commands, e, 1);
470
      return;
471
    }
472 473
    auto progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>(
        downloadContext_, nullptr, option_.get());
474
    adjustFilename(progressInfoFile);
475
    initPieceStorage();
476
    auto checkEntry = createCheckIntegrityEntry();
477
    if (checkEntry) {
478
      processCheckIntegrityEntry(commands, std::move(checkEntry), e);
479
    }
480 481 482 483 484
    return;
  }

  // TODO --dry-run is not supported for multifile download for now.
  if (option_->getAsBool(PREF_DRY_RUN)) {
485 486
    throw DOWNLOAD_FAILURE_EXCEPTION(
        "--dry-run in multi-file download is not supported yet.");
487 488 489 490 491 492
  }
  // TODO file size is known in this context?

  // In this context, multiple FileEntry objects are in
  // DownloadContext.
  if (e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
493 494 495 496
    throw DOWNLOAD_FAILURE_EXCEPTION2(
        fmt(EX_DUPLICATE_FILE_DOWNLOAD,
            downloadContext_->getBasePath().c_str()),
        error_code::DUPLICATE_DOWNLOAD);
497 498 499 500 501
  }
  initPieceStorage();
  if (downloadContext_->getFileEntries().size() > 1) {
    pieceStorage_->setupFileFilter();
  }
502 503
  auto progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>(
      downloadContext_, pieceStorage_, option_.get());
504 505 506 507 508 509 510 511
  removeDefunctControlFile(progressInfoFile);
  // Call Load, Save and file allocation command here
  if (progressInfoFile->exists()) {
    // load .aria2 file if it exists.
    progressInfoFile->load();
    pieceStorage_->getDiskAdaptor()->openFile();
  }
  else if (pieceStorage_->getDiskAdaptor()->fileExists()) {
512
    if (!isCheckIntegrityReady() && !option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
513
      // TODO we need this->haltRequested = true?
514 515 516
      throw DOWNLOAD_FAILURE_EXCEPTION2(
          fmt(MSG_FILE_ALREADY_EXISTS, downloadContext_->getBasePath().c_str()),
          error_code::FILE_ALREADY_EXISTS);
517
    }
518
    pieceStorage_->getDiskAdaptor()->openFile();
519 520
  }
  else {
521
    pieceStorage_->getDiskAdaptor()->openFile();
522
  }
523 524
  progressInfoFile_ = progressInfoFile;
  processCheckIntegrityEntry(commands,
525
                             make_unique<StreamCheckIntegrityEntry>(this), e);
526 527
}

528 529 530
void RequestGroup::processCheckIntegrityEntry(
    std::vector<std::unique_ptr<Command>>& commands,
    std::unique_ptr<CheckIntegrityEntry> entry, DownloadEngine* e)
531
{
532
  int64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
533
  if (actualFileSize > downloadContext_->getTotalLength()) {
534 535
    entry->cutTrailingGarbage();
  }
536 537 538
  if ((option_->getAsBool(PREF_CHECK_INTEGRITY) ||
       downloadContext_->isChecksumVerificationNeeded()) &&
      entry->isValidationReady()) {
539 540 541 542 543 544 545 546
    entry->initValidator();
    // Don't save control file(.aria2 file) when user presses
    // control-c key while aria2 is checking hashes. If control file
    // doesn't exist when aria2 launched, the completed length in
    // saved control file will be 0 byte and this confuses user.
    // enableSaveControlFile() will be called after hash checking is
    // done. See CheckIntegrityCommand.
    disableSaveControlFile();
547
    e->getCheckIntegrityMan()->pushEntry(std::move(entry));
548 549 550 551
    return;
  }

  entry->onDownloadIncomplete(commands, e);
552 553 554 555
}

void RequestGroup::initPieceStorage()
{
556
  std::shared_ptr<PieceStorage> tempPieceStorage;
557 558 559 560
  if (downloadContext_->knowsTotalLength() &&
      // Following conditions are needed for chunked encoding with
      // content-length = 0. Google's dl server used this before.
      (downloadContext_->getTotalLength() > 0
561
#ifdef ENABLE_BITTORRENT
562
       || downloadContext_->hasAttribute(CTX_ATTR_BT)
563
#endif // ENABLE_BITTORRENT
564
           )) {
565
#ifdef ENABLE_BITTORRENT
566 567
    auto ps =
        std::make_shared<DefaultPieceStorage>(downloadContext_, option_.get());
568
    if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
569 570 571
      if (isUriSuppliedForRequsetFileEntry(
              downloadContext_->getFileEntries().begin(),
              downloadContext_->getFileEntries().end())) {
572
        // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent
573
        // integrated downloads.
574
        A2_LOG_DEBUG("Using LongestSequencePieceSelector");
575
        ps->setPieceSelector(make_unique<LongestSequencePieceSelector>());
576
      }
577
      if (option_->defined(PREF_BT_PRIORITIZE_PIECE)) {
578
        std::vector<size_t> result;
579 580 581 582 583
        util::parsePrioritizePieceRange(result,
                                        option_->get(PREF_BT_PRIORITIZE_PIECE),
                                        downloadContext_->getFileEntries(),
                                        downloadContext_->getPieceLength());
        if (!result.empty()) {
584 585 586 587
          std::shuffle(std::begin(result), std::end(result),
                       *SimpleRandomizer::getInstance());
          auto priSelector =
              make_unique<PriorityPieceSelector>(ps->popPieceSelector());
588 589
          priSelector->setPriorityPiece(std::begin(result), std::end(result));
          ps->setPieceSelector(std::move(priSelector));
590 591 592
        }
      }
    }
593 594 595
#else  // !ENABLE_BITTORRENT
    auto ps =
        std::make_shared<DefaultPieceStorage>(downloadContext_, option_.get());
596
#endif // !ENABLE_BITTORRENT
597
    if (requestGroupMan_) {
598 599
      ps->setWrDiskCache(requestGroupMan_->getWrDiskCache());
    }
600
    if (diskWriterFactory_) {
601 602
      ps->setDiskWriterFactory(diskWriterFactory_);
    }
603 604 605 606 607
    tempPieceStorage = ps;
  }
  else {
    auto ps = std::make_shared<UnknownLengthPieceStorage>(downloadContext_);
    if (diskWriterFactory_) {
608 609
      ps->setDiskWriterFactory(diskWriterFactory_);
    }
610
    tempPieceStorage = ps;
611 612
  }
  tempPieceStorage->initStorage();
613 614 615
  if (requestGroupMan_) {
    tempPieceStorage->getDiskAdaptor()->setOpenedFileCounter(
        requestGroupMan_->getOpenedFileCounter());
616
  }
617 618
  segmentMan_ =
      std::make_shared<SegmentMan>(downloadContext_, tempPieceStorage);
619
  pieceStorage_ = tempPieceStorage;
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

#ifdef __MINGW32__
  // Windows build: --file-allocation=falloc uses SetFileValidData
  // which requires SE_MANAGE_VOLUME_NAME privilege.  SetFileValidData
  // has security implications (see
  // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365544%28v=vs.85%29.aspx).
  static auto gainPrivilegeAttempted = false;

  if (!gainPrivilegeAttempted &&
      pieceStorage_->getDiskAdaptor()->getFileAllocationMethod() ==
          DiskAdaptor::FILE_ALLOC_FALLOC &&
      isFileAllocationEnabled()) {
    if (!util::gainPrivilege(SE_MANAGE_VOLUME_NAME)) {
      A2_LOG_WARN("--file-allocation=falloc will not work properly.");
    }
    else {
      A2_LOG_DEBUG("SE_MANAGE_VOLUME_NAME privilege acquired");

      A2_LOG_WARN(
          "--file-allocation=falloc will use SetFileValidData() API, and "
          "aria2 uses uninitialized disk space which may contain "
          "confidential data as the download file space. If it is "
          "undesirable, --file-allocation=prealloc is slower, but safer "
          "option.");
    }

    gainPrivilegeAttempted = true;
  }
#endif // __MINGW32__
649 650 651 652 653 654 655 656 657 658 659
}

void RequestGroup::dropPieceStorage()
{
  segmentMan_.reset();
  pieceStorage_.reset();
}

bool RequestGroup::downloadFinishedByFileLength()
{
  // assuming that a control file doesn't exist.
660 661
  if (!isPreLocalFileCheckEnabled() ||
      option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
662 663
    return false;
  }
664
  if (!downloadContext_->knowsTotalLength()) {
665 666 667
    return false;
  }
  File outfile(getFirstFilePath());
668 669
  if (outfile.exists() &&
      downloadContext_->getTotalLength() == outfile.size()) {
670 671
    return true;
  }
672
  return false;
673 674
}

675 676
void RequestGroup::adjustFilename(
    const std::shared_ptr<BtProgressInfoFile>& infoFile)
677
{
678
  if (!isPreLocalFileCheckEnabled()) {
679 680 681
    // OK, no need to care about filename.
    return;
  }
682
  // TODO need this?
683 684
  if (requestGroupMan_) {
    if (requestGroupMan_->isSameFileBeingDownloaded(this)) {
685 686 687 688 689 690
      // The file name must be renamed
      tryAutoFileRenaming();
      A2_LOG_NOTICE(fmt(MSG_FILE_RENAMED, getFirstFilePath().c_str()));
      return;
    }
  }
691
  if (!option_->getAsBool(PREF_DRY_RUN) &&
692
      option_->getAsBool(PREF_REMOVE_CONTROL_FILE) && infoFile->exists()) {
693 694 695 696 697
    infoFile->removeFile();
    A2_LOG_NOTICE(fmt(_("Removed control file for %s because it is requested by"
                        " user."),
                      infoFile->getFilename().c_str()));
  }
698 699

  if (infoFile->exists()) {
700
    // Use current filename
701 702 703 704
    return;
  }

  File outfile(getFirstFilePath());
705 706
  if (outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
      outfile.size() <= downloadContext_->getTotalLength()) {
707 708
    // File exists but user decided to resume it.
  }
709
  else if (outfile.exists() && isCheckIntegrityReady()) {
710
    // check-integrity existing file
711 712 713
  }
  else {
    shouldCancelDownloadForSafety();
714 715 716
  }
}

717 718
void RequestGroup::removeDefunctControlFile(
    const std::shared_ptr<BtProgressInfoFile>& progressInfoFile)
719 720
{
  // Remove the control file if download file doesn't exist
721 722
  if (progressInfoFile->exists() &&
      !pieceStorage_->getDiskAdaptor()->fileExists()) {
723 724 725 726 727 728 729
    progressInfoFile->removeFile();
    A2_LOG_NOTICE(fmt(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
                      progressInfoFile->getFilename().c_str(),
                      downloadContext_->getBasePath().c_str()));
  }
}

730 731
void RequestGroup::loadAndOpenFile(
    const std::shared_ptr<BtProgressInfoFile>& progressInfoFile)
732 733
{
  try {
734
    if (!isPreLocalFileCheckEnabled()) {
735 736 737 738
      pieceStorage_->getDiskAdaptor()->initAndOpenFile();
      return;
    }
    removeDefunctControlFile(progressInfoFile);
739
    if (progressInfoFile->exists()) {
740 741
      progressInfoFile->load();
      pieceStorage_->getDiskAdaptor()->openExistingFile();
742 743
    }
    else {
744
      File outfile(getFirstFilePath());
745
      if (outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
746
          outfile.size() <= getTotalLength()) {
747 748
        pieceStorage_->getDiskAdaptor()->openExistingFile();
        pieceStorage_->markPiecesDone(outfile.size());
749 750 751 752 753 754
      }
      else if (outfile.exists() && isCheckIntegrityReady()) {
        pieceStorage_->getDiskAdaptor()->openExistingFile();
      }
      else {
        pieceStorage_->getDiskAdaptor()->initAndOpenFile();
755 756 757
      }
    }
    setProgressInfoFile(progressInfoFile);
758
  }
759 760
  catch (RecoverableException& e) {
    throw DOWNLOAD_FAILURE_EXCEPTION2(EX_DOWNLOAD_ABORTED, e);
761 762 763 764 765 766
  }
}

// assuming that a control file does not exist
void RequestGroup::shouldCancelDownloadForSafety()
{
767
  if (option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
768 769 770
    return;
  }
  File outfile(getFirstFilePath());
771 772 773 774
  if (!outfile.exists()) {
    return;
  }

775 776 777 778 779 780
  tryAutoFileRenaming();
  A2_LOG_NOTICE(fmt(MSG_FILE_RENAMED, getFirstFilePath().c_str()));
}

void RequestGroup::tryAutoFileRenaming()
{
781
  if (!option_->getAsBool(PREF_AUTO_FILE_RENAMING)) {
782 783 784
    throw DOWNLOAD_FAILURE_EXCEPTION2(
        fmt(MSG_FILE_ALREADY_EXISTS, getFirstFilePath().c_str()),
        error_code::FILE_ALREADY_EXISTS);
785 786
  }

787
  std::string filepath = getFirstFilePath();
788 789 790 791
  if (filepath.empty()) {
    throw DOWNLOAD_FAILURE_EXCEPTION2(
        fmt("File renaming failed: %s", getFirstFilePath().c_str()),
        error_code::FILE_RENAMING_FAILED);
792
  }
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  auto fn = filepath;
  std::string ext;
  const auto idx = fn.find_last_of(".");
  const auto slash = fn.find_last_of("\\/");
  // Do extract the extension, as in "file.ext" = "file" and ".ext",
  // but do not consider ".file" to be a file name without extension instead
  // of a blank file name and an extension of ".file"
  if (idx != std::string::npos &&
      // fn has no path component and starts with a dot, but has no extension
      // otherwise
      idx != 0 &&
      // has a file path component if we found a slash.
      // if slash == idx - 1 this means a form of "*/.*", so the file name
      // starts with a dot, has no extension otherwise, and therefore do not
      // extract an extension either
      (slash == std::string::npos || slash < idx - 1)) {
    ext = fn.substr(idx);
    fn = fn.substr(0, idx);
  }
812
  for (int i = 1; i < 10000; ++i) {
813
    auto newfilename = fmt("%s.%d%s", fn.c_str(), i, ext.c_str());
814
    File newfile(newfilename);
815 816
    File ctrlfile(newfile.getPath() + DefaultBtProgressInfoFile::getSuffix());
    if (!newfile.exists() || (newfile.exists() && ctrlfile.exists())) {
817
      downloadContext_->getFirstFileEntry()->setPath(newfile.getPath());
818
      return;
819 820
    }
  }
821 822 823
  throw DOWNLOAD_FAILURE_EXCEPTION2(
      fmt("File renaming failed: %s", getFirstFilePath().c_str()),
      error_code::FILE_RENAMING_FAILED);
824 825
}

826 827 828
void RequestGroup::createNextCommandWithAdj(
    std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e,
    int numAdj)
829 830
{
  int numCommand;
831
  if (getTotalLength() == 0) {
832
    numCommand = 1 + numAdj;
833 834
  }
  else {
835 836 837 838
    numCommand = std::min(downloadContext_->getNumPieces(),
                          static_cast<size_t>(numConcurrentCommand_));
    numCommand += numAdj;
  }
839 840

  if (numCommand > 0) {
841 842 843 844
    createNextCommand(commands, e, numCommand);
  }
}

845 846
void RequestGroup::createNextCommand(
    std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e)
847 848
{
  int numCommand;
849 850
  if (getTotalLength() == 0) {
    if (numStreamCommand_ > 0) {
851
      numCommand = 0;
852 853
    }
    else {
854 855 856
      numCommand = 1;
    }
  }
857 858 859 860
  else if (numStreamCommand_ >= numConcurrentCommand_) {
    numCommand = 0;
  }
  else {
861 862 863
    numCommand = std::min(
        downloadContext_->getNumPieces(),
        static_cast<size_t>(numConcurrentCommand_ - numStreamCommand_));
864 865 866
  }

  if (numCommand > 0) {
867 868 869 870
    createNextCommand(commands, e, numCommand);
  }
}

871 872 873
void RequestGroup::createNextCommand(
    std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e,
    int numCommand)
874
{
875
  for (; numCommand > 0; --numCommand) {
876 877
    commands.push_back(
        make_unique<CreateRequestCommand>(e->newCUID(), this, e));
878
  }
879
  if (!commands.empty()) {
880 881 882 883 884 885 886
    e->setNoWait(true);
  }
}

std::string RequestGroup::getFirstFilePath() const
{
  assert(downloadContext_);
887
  if (inMemoryDownload()) {
888 889
    return "[MEMORY]" +
           File(downloadContext_->getFirstFileEntry()->getPath()).getBasename();
890
  }
891
  return downloadContext_->getFirstFileEntry()->getPath();
892 893
}

894
int64_t RequestGroup::getTotalLength() const
895
{
896
  if (!pieceStorage_) {
897 898
    return 0;
  }
899 900 901 902 903 904

  if (pieceStorage_->isSelectiveDownloadingMode()) {
    return pieceStorage_->getFilteredTotalLength();
  }

  return pieceStorage_->getTotalLength();
905 906
}

907
int64_t RequestGroup::getCompletedLength() const
908
{
909
  if (!pieceStorage_) {
910 911
    return 0;
  }
912 913 914 915 916 917

  if (pieceStorage_->isSelectiveDownloadingMode()) {
    return pieceStorage_->getFilteredCompletedLength();
  }

  return pieceStorage_->getCompletedLength();
918 919 920 921 922
}

void RequestGroup::validateFilename(const std::string& expectedFilename,
                                    const std::string& actualFilename) const
{
923
  if (expectedFilename.empty()) {
924 925
    return;
  }
926

927 928
  if (expectedFilename != actualFilename) {
    throw DL_ABORT_EX(fmt(EX_FILENAME_MISMATCH, expectedFilename.c_str(),
929 930 931 932
                          actualFilename.c_str()));
  }
}

933 934
void RequestGroup::validateTotalLength(int64_t expectedTotalLength,
                                       int64_t actualTotalLength) const
935
{
936
  if (expectedTotalLength <= 0) {
937 938
    return;
  }
939

940 941 942
  if (expectedTotalLength != actualTotalLength) {
    throw DL_ABORT_EX(
        fmt(EX_SIZE_MISMATCH, expectedTotalLength, actualTotalLength));
943 944 945 946 947
  }
}

void RequestGroup::validateFilename(const std::string& actualFilename) const
{
948 949
  validateFilename(downloadContext_->getFileEntries().front()->getBasename(),
                   actualFilename);
950 951
}

952
void RequestGroup::validateTotalLength(int64_t actualTotalLength) const
953 954 955 956
{
  validateTotalLength(getTotalLength(), actualTotalLength);
}

957
void RequestGroup::increaseStreamCommand() { ++numStreamCommand_; }
958

959
void RequestGroup::decreaseStreamCommand() { --numStreamCommand_; }
960

961
void RequestGroup::increaseStreamConnection() { ++numStreamConnection_; }
962

963
void RequestGroup::decreaseStreamConnection() { --numStreamConnection_; }
964 965 966 967 968

int RequestGroup::getNumConnection() const
{
  int numConnection = numStreamConnection_;
#ifdef ENABLE_BITTORRENT
969
  if (btRuntime_) {
970 971 972 973 974 975
    numConnection += btRuntime_->getConnections();
  }
#endif // ENABLE_BITTORRENT
  return numConnection;
}

976
void RequestGroup::increaseNumCommand() { ++numCommand_; }
977 978 979 980

void RequestGroup::decreaseNumCommand()
{
  --numCommand_;
981
  if (!numCommand_ && requestGroupMan_) {
982
    A2_LOG_DEBUG(fmt("GID#%s - Request queue check", gid_->toHex().c_str()));
983 984 985 986 987 988
    requestGroupMan_->requestQueueCheck();
  }
}

TransferStat RequestGroup::calculateStat() const
{
989
  TransferStat stat = downloadContext_->getNetStat().toTransferStat();
990
#ifdef ENABLE_BITTORRENT
991 992 993
  if (btRuntime_) {
    stat.allTimeUploadLength =
        btRuntime_->getUploadLengthAtStartup() + stat.sessionUploadLength;
994 995 996 997 998 999 1000 1001
  }
#endif // ENABLE_BITTORRENT
  return stat;
}

void RequestGroup::setHaltRequested(bool f, HaltReason haltReason)
{
  haltRequested_ = f;
1002
  if (haltRequested_) {
1003 1004 1005 1006
    pauseRequested_ = false;
    haltReason_ = haltReason;
  }
#ifdef ENABLE_BITTORRENT
1007
  if (btRuntime_) {
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    btRuntime_->setHalt(f);
  }
#endif // ENABLE_BITTORRENT
}

void RequestGroup::setForceHaltRequested(bool f, HaltReason haltReason)
{
  setHaltRequested(f, haltReason);
  forceHaltRequested_ = f;
}

1019
void RequestGroup::setPauseRequested(bool f) { pauseRequested_ = f; }
1020

1021 1022
void RequestGroup::setRestartRequested(bool f) { restartRequested_ = f; }

1023 1024 1025
void RequestGroup::releaseRuntimeResource(DownloadEngine* e)
{
#ifdef ENABLE_BITTORRENT
1026
  e->getBtRegistry()->remove(gid_->getNumericId());
1027 1028
  btRuntime_ = nullptr;
  peerStorage_ = nullptr;
1029
#endif // ENABLE_BITTORRENT
1030
  if (pieceStorage_) {
1031
    pieceStorage_->removeAdvertisedPiece(Timer::zero());
1032 1033 1034
  }
  // Don't reset segmentMan_ and pieceStorage_ here to provide
  // progress information via RPC
1035
  progressInfoFile_ = std::make_shared<NullProgressInfoFile>();
1036
  downloadContext_->releaseRuntimeResource();
1037 1038 1039
  // Reset seedOnly_, so that we can handle pause/unpause-ing seeding
  // torrent with --bt-detach-seed-only.
  seedOnly_ = false;
1040 1041 1042 1043 1044 1045 1046
}

void RequestGroup::preDownloadProcessing()
{
  A2_LOG_DEBUG(fmt("Finding PreDownloadHandler for path %s.",
                   getFirstFilePath().c_str()));
  try {
1047 1048
    for (const auto& pdh : preDownloadHandlers_) {
      if (pdh->canHandle(this)) {
1049
        pdh->execute(this);
1050 1051 1052
        return;
      }
    }
1053 1054
  }
  catch (RecoverableException& ex) {
1055 1056 1057
    A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
    return;
  }
1058

1059 1060 1061 1062
  A2_LOG_DEBUG("No PreDownloadHandler found.");
  return;
}

1063 1064
void RequestGroup::postDownloadProcessing(
    std::vector<std::shared_ptr<RequestGroup>>& groups)
1065 1066 1067 1068
{
  A2_LOG_DEBUG(fmt("Finding PostDownloadHandler for path %s.",
                   getFirstFilePath().c_str()));
  try {
1069
    for (const auto& pdh : postDownloadHandlers_) {
1070 1071
      if (pdh->canHandle(this)) {
        pdh->getNextRequestGroups(groups, this);
1072 1073 1074
        return;
      }
    }
1075
  }
1076
  catch (RecoverableException& ex) {
1077 1078
    A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  }
1079

1080 1081 1082 1083 1084 1085
  A2_LOG_DEBUG("No PostDownloadHandler found.");
}

void RequestGroup::initializePreDownloadHandler()
{
#ifdef ENABLE_BITTORRENT
1086 1087 1088
  if (option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
    preDownloadHandlers_.push_back(
        download_handlers::getBtPreDownloadHandler());
1089 1090 1091
  }
#endif // ENABLE_BITTORRENT
#ifdef ENABLE_METALINK
1092 1093 1094
  if (option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
    preDownloadHandlers_.push_back(
        download_handlers::getMetalinkPreDownloadHandler());
1095 1096 1097 1098 1099 1100 1101
  }
#endif // ENABLE_METALINK
}

void RequestGroup::initializePostDownloadHandler()
{
#ifdef ENABLE_BITTORRENT
1102 1103 1104 1105
  if (option_->getAsBool(PREF_FOLLOW_TORRENT) ||
      option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
    postDownloadHandlers_.push_back(
        download_handlers::getBtPostDownloadHandler());
1106 1107 1108
  }
#endif // ENABLE_BITTORRENT
#ifdef ENABLE_METALINK
1109 1110 1111 1112
  if (option_->getAsBool(PREF_FOLLOW_METALINK) ||
      option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
    postDownloadHandlers_.push_back(
        download_handlers::getMetalinkPostDownloadHandler());
1113 1114 1115 1116 1117 1118
  }
#endif // ENABLE_METALINK
}

bool RequestGroup::isDependencyResolved()
{
1119
  if (!dependency_) {
1120 1121 1122 1123 1124
    return true;
  }
  return dependency_->resolve();
}

1125
void RequestGroup::dependsOn(const std::shared_ptr<Dependency>& dep)
1126 1127 1128 1129
{
  dependency_ = dep;
}

1130 1131
void RequestGroup::setDiskWriterFactory(
    const std::shared_ptr<DiskWriterFactory>& diskWriterFactory)
1132 1133 1134 1135
{
  diskWriterFactory_ = diskWriterFactory;
}

1136
void RequestGroup::addPostDownloadHandler(const PostDownloadHandler* handler)
1137 1138 1139 1140
{
  postDownloadHandlers_.push_back(handler);
}

1141
void RequestGroup::addPreDownloadHandler(const PreDownloadHandler* handler)
1142 1143 1144 1145
{
  preDownloadHandlers_.push_back(handler);
}

1146
void RequestGroup::clearPostDownloadHandler() { postDownloadHandlers_.clear(); }
1147

1148
void RequestGroup::clearPreDownloadHandler() { preDownloadHandlers_.clear(); }
1149

1150 1151
void RequestGroup::setPieceStorage(
    const std::shared_ptr<PieceStorage>& pieceStorage)
1152 1153 1154 1155
{
  pieceStorage_ = pieceStorage;
}

1156 1157
void RequestGroup::setProgressInfoFile(
    const std::shared_ptr<BtProgressInfoFile>& progressInfoFile)
1158 1159 1160 1161 1162 1163 1164
{
  progressInfoFile_ = progressInfoFile;
}

bool RequestGroup::needsFileAllocation() const
{
  return isFileAllocationEnabled() &&
1165 1166 1167
         option_->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <=
             getTotalLength() &&
         !pieceStorage_->getDiskAdaptor()->fileAllocationIterator()->finished();
1168 1169
}

1170
std::shared_ptr<DownloadResult> RequestGroup::createDownloadResult() const
1171
{
1172
  A2_LOG_DEBUG(fmt("GID#%s - Creating DownloadResult.", gid_->toHex().c_str()));
1173
  TransferStat st = calculateStat();
1174
  auto res = std::make_shared<DownloadResult>();
1175
  res->gid = gid_;
1176
  res->attrs = downloadContext_->getAttributes();
1177 1178
  res->fileEntries = downloadContext_->getFileEntries();
  res->inMemoryDownload = inMemoryDownload_;
1179
  res->sessionDownloadLength = st.sessionDownloadLength;
1180 1181 1182 1183 1184 1185
  res->sessionTime = std::chrono::duration_cast<std::chrono::milliseconds>(
      downloadContext_->calculateSessionTime());

  auto result = downloadResult();
  res->result = result.first;
  res->resultMessage = result.second;
1186
  res->followedBy = followedByGIDs_;
1187
  res->following = followingGID_;
1188 1189 1190 1191 1192
  res->belongsTo = belongsToGID_;
  res->option = option_;
  res->metadataInfo = metadataInfo_;
  res->totalLength = getTotalLength();
  res->completedLength = getCompletedLength();
1193
  res->uploadLength = st.allTimeUploadLength;
1194
  if (pieceStorage_ && pieceStorage_->getBitfieldLength() > 0) {
1195 1196
    res->bitfield.assign(pieceStorage_->getBitfield(),
                         pieceStorage_->getBitfield() +
1197
                             pieceStorage_->getBitfieldLength());
1198 1199
  }
#ifdef ENABLE_BITTORRENT
1200
  if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
1201
    const unsigned char* p = bittorrent::getInfoHash(downloadContext_);
1202
    res->infoHash.assign(p, p + INFO_HASH_LENGTH);
1203 1204 1205 1206 1207 1208 1209
  }
#endif // ENABLE_BITTORRENT
  res->pieceLength = downloadContext_->getPieceLength();
  res->numPieces = downloadContext_->getNumPieces();
  res->dir = option_->get(PREF_DIR);
  return res;
}
1210

1211 1212 1213
void RequestGroup::reportDownloadFinished()
{
  A2_LOG_NOTICE(fmt(MSG_FILE_DOWNLOAD_COMPLETED,
1214 1215 1216
                    inMemoryDownload()
                        ? getFirstFilePath().c_str()
                        : downloadContext_->getBasePath().c_str()));
1217 1218
  uriSelector_->resetCounters();
#ifdef ENABLE_BITTORRENT
1219
  if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
1220
    TransferStat stat = calculateStat();
1221
    int64_t completedLength = getCompletedLength();
1222 1223 1224
    double shareRatio = completedLength == 0
                            ? 0.0
                            : 1.0 * stat.allTimeUploadLength / completedLength;
1225
    auto attrs = bittorrent::getTorrentAttrs(downloadContext_);
1226 1227
    if (!attrs->metadata.empty()) {
      A2_LOG_NOTICE(fmt(MSG_SHARE_RATIO_REPORT, shareRatio,
1228
                        util::abbrevSize(stat.allTimeUploadLength).c_str(),
1229 1230 1231 1232 1233 1234
                        util::abbrevSize(completedLength).c_str()));
    }
  }
#endif // ENABLE_BITTORRENT
}

1235
void RequestGroup::setURISelector(std::unique_ptr<URISelector> uriSelector)
1236
{
1237
  uriSelector_ = std::move(uriSelector);
1238 1239 1240 1241
}

void RequestGroup::applyLastModifiedTimeToLocalFiles()
{
1242 1243
  if (!pieceStorage_ || !lastModifiedTime_.good()) {
    return;
1244
  }
1245 1246 1247 1248 1249
  A2_LOG_INFO(fmt("Applying Last-Modified time: %s",
                  lastModifiedTime_.toHTTPDate().c_str()));
  size_t n = pieceStorage_->getDiskAdaptor()->utime(Time(), lastModifiedTime_);
  A2_LOG_INFO(fmt("Last-Modified attrs of %lu files were updated.",
                  static_cast<unsigned long>(n)));
1250 1251 1252 1253
}

void RequestGroup::updateLastModifiedTime(const Time& time)
{
1254
  if (time.good() && lastModifiedTime_ < time) {
1255 1256 1257 1258 1259 1260 1261 1262
    lastModifiedTime_ = time;
  }
}

void RequestGroup::increaseAndValidateFileNotFoundCount()
{
  ++fileNotFoundCount_;
  const int maxCount = option_->getAsInt(PREF_MAX_FILE_NOT_FOUND);
1263
  if (maxCount > 0 && fileNotFoundCount_ >= maxCount &&
1264
      downloadContext_->getNetStat().getSessionDownloadLength() == 0) {
1265 1266 1267
    throw DOWNLOAD_FAILURE_EXCEPTION2(
        fmt("Reached max-file-not-found count=%d", maxCount),
        error_code::MAX_FILE_NOT_FOUND);
1268 1269 1270
  }
}

1271
void RequestGroup::markInMemoryDownload() { inMemoryDownload_ = true; }
1272

1273
void RequestGroup::setTimeout(std::chrono::seconds timeout)
1274
{
1275
  timeout_ = std::move(timeout);
1276 1277 1278 1279
}

bool RequestGroup::doesDownloadSpeedExceed()
{
1280 1281
  int spd = downloadContext_->getNetStat().calculateDownloadSpeed();
  return maxDownloadSpeedLimit_ > 0 && maxDownloadSpeedLimit_ < spd;
1282 1283 1284 1285
}

bool RequestGroup::doesUploadSpeedExceed()
{
1286 1287
  int spd = downloadContext_->getNetStat().calculateUploadSpeed();
  return maxUploadSpeedLimit_ > 0 && maxUploadSpeedLimit_ < spd;
1288 1289 1290 1291
}

void RequestGroup::saveControlFile() const
{
1292
  if (saveControlFile_) {
1293 1294 1295 1296 1297 1298 1299 1300 1301
    progressInfoFile_->save();
  }
}

void RequestGroup::removeControlFile() const
{
  progressInfoFile_->removeFile();
}

1302 1303
void RequestGroup::setDownloadContext(
    const std::shared_ptr<DownloadContext>& downloadContext)
1304 1305
{
  downloadContext_ = downloadContext;
1306
  if (downloadContext_) {
1307 1308 1309 1310 1311 1312 1313
    downloadContext_->setOwnerRequestGroup(this);
  }
}

bool RequestGroup::p2pInvolved() const
{
#ifdef ENABLE_BITTORRENT
1314
  return downloadContext_->hasAttribute(CTX_ATTR_BT);
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
#else  // !ENABLE_BITTORRENT
  return false;
#endif // !ENABLE_BITTORRENT
}

void RequestGroup::enableSeedOnly()
{
  if (seedOnly_ || !option_->getAsBool(PREF_BT_DETACH_SEED_ONLY)) {
    return;
  }

  if (requestGroupMan_) {
    seedOnly_ = true;

    requestGroupMan_->decreaseNumActive();
    requestGroupMan_->requestQueueCheck();
  }
}

bool RequestGroup::isSeeder() const
{
#ifdef ENABLE_BITTORRENT
  return downloadContext_->hasAttribute(CTX_ATTR_BT) &&
         !bittorrent::getTorrentAttrs(downloadContext_)->metadata.empty() &&
         downloadFinished();
#else  // !ENABLE_BITTORRENT
1341 1342 1343 1344
  return false;
#endif // !ENABLE_BITTORRENT
}

1345 1346 1347 1348 1349
void RequestGroup::setPendingOption(std::shared_ptr<Option> option)
{
  pendingOption_ = std::move(option);
}

1350
} // namespace aria2