qBittorrent
torrentinfo.cpp
Go to the documentation of this file.
1 /*
2  * Bittorrent Client using Qt and libtorrent.
3  * Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * In addition, as a special exception, the copyright holders give permission to
20  * link this program with the OpenSSL project's "OpenSSL" library (or with
21  * modified versions of it that use the same license as the "OpenSSL" library),
22  * and distribute the linked executables. You must obey the GNU General Public
23  * License in all respects for all of the code used other than "OpenSSL". If you
24  * modify file(s), you may extend this exception to your version of the file(s),
25  * but you are not obligated to do so. If you do not wish to do so, delete this
26  * exception statement from your version.
27  */
28 
29 #include "torrentinfo.h"
30 
31 #include <libtorrent/create_torrent.hpp>
32 #include <libtorrent/error_code.hpp>
33 
34 #include <QByteArray>
35 #include <QDateTime>
36 #include <QDebug>
37 #include <QDir>
38 #include <QString>
39 #include <QStringList>
40 #include <QUrl>
41 #include <QVector>
42 
43 #include "base/global.h"
44 #include "base/utils/fs.h"
45 #include "base/utils/io.h"
46 #include "base/utils/misc.h"
47 #include "infohash.h"
48 #include "trackerentry.h"
49 
50 using namespace BitTorrent;
51 
52 const int torrentInfoId = qRegisterMetaType<TorrentInfo>();
53 
54 TorrentInfo::TorrentInfo(const lt::torrent_info &nativeInfo)
55  : m_nativeInfo {std::make_shared<const lt::torrent_info>(nativeInfo)}
56 {
57  Q_ASSERT(m_nativeInfo->is_valid() && (m_nativeInfo->num_files() > 0));
58 
59  const lt::file_storage &fileStorage = m_nativeInfo->orig_files();
60  m_nativeIndexes.reserve(fileStorage.num_files());
61  for (const lt::file_index_t nativeIndex : fileStorage.file_range())
62  {
63  if (!fileStorage.pad_file_at(nativeIndex))
64  m_nativeIndexes.append(nativeIndex);
65  }
66 }
67 
69  : m_nativeInfo {other.m_nativeInfo}
70  , m_nativeIndexes {other.m_nativeIndexes}
71 {
72 }
73 
75 {
76  if (this != &other)
77  {
78  m_nativeInfo = other.m_nativeInfo;
80  }
81  return *this;
82 }
83 
85 {
86  return (m_nativeInfo != nullptr);
87 }
88 
89 nonstd::expected<TorrentInfo, QString> TorrentInfo::load(const QByteArray &data) noexcept
90 {
91  // 2-step construction to overcome default limits of `depth_limit` & `token_limit` which are
92  // used in `torrent_info()` constructor
93  const int depthLimit = 100;
94  const int tokenLimit = 10000000;
95 
96  lt::error_code ec;
97  const lt::bdecode_node node = lt::bdecode(data, ec
98  , nullptr, depthLimit, tokenLimit);
99  if (ec)
100  return nonstd::make_unexpected(QString::fromStdString(ec.message()));
101 
102  lt::torrent_info nativeInfo {node, ec};
103  if (ec)
104  return nonstd::make_unexpected(QString::fromStdString(ec.message()));
105 
106  return TorrentInfo(nativeInfo);
107 }
108 
109 nonstd::expected<TorrentInfo, QString> TorrentInfo::loadFromFile(const QString &path) noexcept
110 {
111  QFile file {path};
112  if (!file.open(QIODevice::ReadOnly))
113  return nonstd::make_unexpected(file.errorString());
114 
115  if (file.size() > MAX_TORRENT_SIZE)
116  return nonstd::make_unexpected(tr("File size exceeds max limit %1").arg(Utils::Misc::friendlyUnit(MAX_TORRENT_SIZE)));
117 
118  QByteArray data;
119  try
120  {
121  data = file.readAll();
122  }
123  catch (const std::bad_alloc &e)
124  {
125  return nonstd::make_unexpected(tr("Torrent file read error: %1").arg(e.what()));
126  }
127 
128  if (data.size() != file.size())
129  return nonstd::make_unexpected(tr("Torrent file read error: size mismatch"));
130 
131  file.close();
132 
133  return load(data);
134 }
135 
136 nonstd::expected<void, QString> TorrentInfo::saveToFile(const QString &path) const
137 {
138  if (!isValid())
139  return nonstd::make_unexpected(tr("Invalid metadata"));
140 
141  try
142  {
143  const auto torrentCreator = lt::create_torrent(*nativeInfo());
144  const lt::entry torrentEntry = torrentCreator.generate();
145  const nonstd::expected<void, QString> result = Utils::IO::saveToFile(path, torrentEntry);
146  if (!result)
147  return result.get_unexpected();
148  }
149  catch (const lt::system_error &err)
150  {
151  return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
152  }
153 
154  return {};
155 }
156 
158 {
159  if (!isValid()) return {};
160 
161 #ifdef QBT_USES_LIBTORRENT2
162  return m_nativeInfo->info_hashes();
163 #else
164  return m_nativeInfo->info_hash();
165 #endif
166 }
167 
168 QString TorrentInfo::name() const
169 {
170  if (!isValid()) return {};
171 
172  return QString::fromStdString(m_nativeInfo->orig_files().name());
173 }
174 
175 QDateTime TorrentInfo::creationDate() const
176 {
177  if (!isValid()) return {};
178 
179  const std::time_t date = m_nativeInfo->creation_date();
180  return ((date != 0) ? QDateTime::fromSecsSinceEpoch(date) : QDateTime());
181 }
182 
183 QString TorrentInfo::creator() const
184 {
185  if (!isValid()) return {};
186 
187  return QString::fromStdString(m_nativeInfo->creator());
188 }
189 
190 QString TorrentInfo::comment() const
191 {
192  if (!isValid()) return {};
193 
194  return QString::fromStdString(m_nativeInfo->comment());
195 }
196 
198 {
199  if (!isValid()) return false;
200 
201  return m_nativeInfo->priv();
202 }
203 
204 qlonglong TorrentInfo::totalSize() const
205 {
206  if (!isValid()) return -1;
207 
208  return m_nativeInfo->total_size();
209 }
210 
212 {
213  if (!isValid()) return -1;
214 
215  return m_nativeIndexes.size();
216 }
217 
219 {
220  if (!isValid()) return -1;
221 
222  return m_nativeInfo->piece_length();
223 }
224 
225 int TorrentInfo::pieceLength(const int index) const
226 {
227  if (!isValid()) return -1;
228 
229  return m_nativeInfo->piece_size(lt::piece_index_t {index});
230 }
231 
233 {
234  if (!isValid()) return -1;
235 
236  return m_nativeInfo->num_pieces();
237 }
238 
239 QString TorrentInfo::filePath(const int index) const
240 {
241  if (!isValid()) return {};
242 
244  QString::fromStdString(m_nativeInfo->orig_files().file_path(m_nativeIndexes[index])));
245 }
246 
247 QStringList TorrentInfo::filePaths() const
248 {
249  QStringList list;
250  list.reserve(filesCount());
251  for (int i = 0; i < filesCount(); ++i)
252  list << filePath(i);
253 
254  return list;
255 }
256 
257 qlonglong TorrentInfo::fileSize(const int index) const
258 {
259  if (!isValid()) return -1;
260 
261  return m_nativeInfo->orig_files().file_size(m_nativeIndexes[index]);
262 }
263 
264 qlonglong TorrentInfo::fileOffset(const int index) const
265 {
266  if (!isValid()) return -1;
267 
268  return m_nativeInfo->orig_files().file_offset(m_nativeIndexes[index]);
269 }
270 
271 QVector<TrackerEntry> TorrentInfo::trackers() const
272 {
273  if (!isValid()) return {};
274 
275  const std::vector<lt::announce_entry> trackers = m_nativeInfo->trackers();
276 
277  QVector<TrackerEntry> ret;
278  ret.reserve(static_cast<decltype(ret)::size_type>(trackers.size()));
279 
280  for (const lt::announce_entry &tracker : trackers)
281  ret.append({QString::fromStdString(tracker.url)});
282 
283  return ret;
284 }
285 
286 QVector<QUrl> TorrentInfo::urlSeeds() const
287 {
288  if (!isValid()) return {};
289 
290  const std::vector<lt::web_seed_entry> &nativeWebSeeds = m_nativeInfo->web_seeds();
291 
292  QVector<QUrl> urlSeeds;
293  urlSeeds.reserve(static_cast<decltype(urlSeeds)::size_type>(nativeWebSeeds.size()));
294 
295  for (const lt::web_seed_entry &webSeed : nativeWebSeeds)
296  {
297  if (webSeed.type == lt::web_seed_entry::url_seed)
298  urlSeeds.append(QUrl(webSeed.url.c_str()));
299  }
300 
301  return urlSeeds;
302 }
303 
304 QByteArray TorrentInfo::metadata() const
305 {
306  if (!isValid()) return {};
307 #ifdef QBT_USES_LIBTORRENT2
308  const lt::span<const char> infoSection {m_nativeInfo->info_section()};
309  return {infoSection.data(), static_cast<int>(infoSection.size())};
310 #else
311  return {m_nativeInfo->metadata().get(), m_nativeInfo->metadata_size()};
312 #endif
313 }
314 
315 QStringList TorrentInfo::filesForPiece(const int pieceIndex) const
316 {
317  // no checks here because fileIndicesForPiece() will return an empty list
318  const QVector<int> fileIndices = fileIndicesForPiece(pieceIndex);
319 
320  QStringList res;
321  res.reserve(fileIndices.size());
322  std::transform(fileIndices.begin(), fileIndices.end(), std::back_inserter(res),
323  [this](int i) { return filePath(i); });
324 
325  return res;
326 }
327 
328 QVector<int> TorrentInfo::fileIndicesForPiece(const int pieceIndex) const
329 {
330  if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount()))
331  return {};
332 
333  const std::vector<lt::file_slice> files = m_nativeInfo->map_block(
334  lt::piece_index_t {pieceIndex}, 0, m_nativeInfo->piece_size(lt::piece_index_t {pieceIndex}));
335  QVector<int> res;
336  res.reserve(static_cast<decltype(res)::size_type>(files.size()));
337  for (const lt::file_slice &fileSlice : files)
338  {
339  const int index = m_nativeIndexes.indexOf(fileSlice.file_index);
340  if (index >= 0)
341  res.append(index);
342  }
343 
344  return res;
345 }
346 
347 QVector<QByteArray> TorrentInfo::pieceHashes() const
348 {
349  if (!isValid())
350  return {};
351 
352  const int count = piecesCount();
353  QVector<QByteArray> hashes;
354  hashes.reserve(count);
355 
356  for (int i = 0; i < count; ++i)
357  hashes += {m_nativeInfo->hash_for_piece_ptr(lt::piece_index_t {i}), SHA1Hash::length()};
358 
359  return hashes;
360 }
361 
363 {
364  if (!isValid()) // if we do not check here the debug message will be printed, which would be not correct
365  return {};
366 
367  const int index = fileIndex(file);
368  if (index == -1)
369  {
370  qDebug() << "Filename" << file << "was not found in torrent" << name();
371  return {};
372  }
373  return filePieces(index);
374 }
375 
377 {
378  if (!isValid())
379  return {};
380 
381  if ((fileIndex < 0) || (fileIndex >= filesCount()))
382  {
383  qDebug() << "File index (" << fileIndex << ") is out of range for torrent" << name();
384  return {};
385  }
386 
387  const lt::file_storage &files = m_nativeInfo->orig_files();
388  const auto fileSize = files.file_size(m_nativeIndexes[fileIndex]);
389  const auto fileOffset = files.file_offset(m_nativeIndexes[fileIndex]);
390 
391  const int beginIdx = (fileOffset / pieceLength());
392  const int endIdx = ((fileOffset + fileSize - 1) / pieceLength());
393 
394  if (fileSize <= 0)
395  return {beginIdx, 0};
396  return makeInterval(beginIdx, endIdx);
397 }
398 
399 int TorrentInfo::fileIndex(const QString &fileName) const
400 {
401  // the check whether the object is valid is not needed here
402  // because if filesCount() returns -1 the loop exits immediately
403  for (int i = 0; i < filesCount(); ++i)
404  {
405  if (fileName == filePath(i))
406  return i;
407  }
408 
409  return -1;
410 }
411 
412 QString TorrentInfo::rootFolder() const
413 {
414  if (!isValid())
415  return {};
416 
418 }
419 
421 {
422  return !rootFolder().isEmpty();
423 }
424 
426 {
427  if (!isValid())
428  return TorrentContentLayout::Original;
429 
430  return detectContentLayout(filePaths());
431 }
432 
433 std::shared_ptr<lt::torrent_info> TorrentInfo::nativeInfo() const
434 {
435  if (!isValid())
436  return nullptr;
437 
438  return std::make_shared<lt::torrent_info>(*m_nativeInfo);
439 }
440 
441 QVector<lt::file_index_t> TorrentInfo::nativeIndexes() const
442 {
443  return m_nativeIndexes;
444 }
QVector< QUrl > urlSeeds() const
static nonstd::expected< TorrentInfo, QString > load(const QByteArray &data) noexcept
Definition: torrentinfo.cpp:89
QStringList filesForPiece(int pieceIndex) const
qlonglong totalSize() const
QVector< lt::file_index_t > nativeIndexes() const
QVector< TrackerEntry > trackers() const
QString comment() const
qlonglong fileOffset(int index) const
QString filePath(int index) const
InfoHash infoHash() const
int fileIndex(const QString &fileName) const
QVector< lt::file_index_t > m_nativeIndexes
Definition: torrentinfo.h:110
TorrentInfo & operator=(const TorrentInfo &other)
Definition: torrentinfo.cpp:74
TorrentContentLayout contentLayout() const
PieceRange filePieces(const QString &file) const
std::shared_ptr< lt::torrent_info > nativeInfo() const
QStringList filePaths() const
QDateTime creationDate() const
QByteArray metadata() const
std::shared_ptr< const lt::torrent_info > m_nativeInfo
Definition: torrentinfo.h:106
bool hasRootFolder() const
QString name() const
QString rootFolder() const
QVector< QByteArray > pieceHashes() const
QString creator() const
qlonglong fileSize(int index) const
QVector< int > fileIndicesForPiece(int pieceIndex) const
nonstd::expected< void, QString > saveToFile(const QString &path) const
static nonstd::expected< TorrentInfo, QString > loadFromFile(const QString &path) noexcept
static constexpr int length()
Definition: digest32.h:53
const int MAX_TORRENT_SIZE
Definition: global.h:39
flag icons free of to any person obtaining a copy of this software and associated documentation files(the "Software")
constexpr IndexInterval< T > makeInterval(const T first, const T last)
Definition: indexrange.h:63
TorrentContentLayout detectContentLayout(const QStringList &filePaths)
QString fileName(const QString &filePath)
Definition: fs.cpp:87
QString findRootFolder(const QStringList &filePaths)
Definition: fs.cpp:403
QString toUniformPath(const QString &path)
Definition: fs.cpp:69
nonstd::expected< void, QString > saveToFile(const QString &path, const QByteArray &data)
Definition: io.cpp:69
QString friendlyUnit(qint64 bytes, bool isSpeed=false)
Definition: misc.cpp:261
file(GLOB QBT_TS_FILES "${qBittorrent_SOURCE_DIR}/src/lang/*.ts") set_source_files_properties($
Definition: CMakeLists.txt:5
const int torrentInfoId
Definition: torrentinfo.cpp:52