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/bencode.hpp>
32 #include <libtorrent/create_torrent.hpp>
33 #include <libtorrent/error_code.hpp>
34 #include <libtorrent/version.hpp>
35 
36 #include <QByteArray>
37 #include <QDateTime>
38 #include <QDebug>
39 #include <QDir>
40 #include <QString>
41 #include <QStringList>
42 #include <QUrl>
43 #include <QVector>
44 
45 #include "base/exceptions.h"
46 #include "base/global.h"
47 #include "base/utils/fs.h"
48 #include "base/utils/io.h"
49 #include "base/utils/misc.h"
50 #include "infohash.h"
51 #include "trackerentry.h"
52 
53 using namespace BitTorrent;
54 
55 namespace
56 {
getRootFolder(const QStringList & filePaths)57     QString getRootFolder(const QStringList &filePaths)
58     {
59         QString rootFolder;
60         for (const QString &filePath : filePaths)
61         {
62             if (QDir::isAbsolutePath(filePath)) continue;
63 
64             const auto filePathElements = filePath.splitRef('/');
65             // if at least one file has no root folder, no common root folder exists
66             if (filePathElements.count() <= 1) return {};
67 
68             if (rootFolder.isEmpty())
69                 rootFolder = filePathElements.at(0).toString();
70             else if (rootFolder != filePathElements.at(0))
71                 return {};
72         }
73 
74         return rootFolder;
75     }
76 }
77 
78 const int torrentInfoId = qRegisterMetaType<TorrentInfo>();
79 
TorrentInfo(std::shared_ptr<const lt::torrent_info> nativeInfo)80 TorrentInfo::TorrentInfo(std::shared_ptr<const lt::torrent_info> nativeInfo)
81 {
82     m_nativeInfo = std::const_pointer_cast<lt::torrent_info>(nativeInfo);
83 }
84 
TorrentInfo(const TorrentInfo & other)85 TorrentInfo::TorrentInfo(const TorrentInfo &other)
86     : m_nativeInfo(other.m_nativeInfo)
87 {
88 }
89 
operator =(const TorrentInfo & other)90 TorrentInfo &TorrentInfo::operator=(const TorrentInfo &other)
91 {
92     if (this != &other)
93     {
94         m_nativeInfo = other.m_nativeInfo;
95     }
96     return *this;
97 }
98 
load(const QByteArray & data,QString * error)99 TorrentInfo TorrentInfo::load(const QByteArray &data, QString *error) noexcept
100 {
101     // 2-step construction to overcome default limits of `depth_limit` & `token_limit` which are
102     // used in `torrent_info()` constructor
103     const int depthLimit = 100;
104     const int tokenLimit = 10000000;
105 
106     lt::error_code ec;
107     const lt::bdecode_node node = lt::bdecode(data, ec
108         , nullptr, depthLimit, tokenLimit);
109     if (ec)
110     {
111         if (error)
112             *error = QString::fromStdString(ec.message());
113         return TorrentInfo();
114     }
115 
116     TorrentInfo info {std::shared_ptr<lt::torrent_info>(new lt::torrent_info(node, ec))};
117     if (ec)
118     {
119         if (error)
120             *error = QString::fromStdString(ec.message());
121         return TorrentInfo();
122     }
123 
124     return info;
125 }
126 
loadFromFile(const QString & path,QString * error)127 TorrentInfo TorrentInfo::loadFromFile(const QString &path, QString *error) noexcept
128 {
129     if (error)
130         error->clear();
131 
132     QFile file {path};
133     if (!file.open(QIODevice::ReadOnly))
134     {
135         if (error)
136             *error = file.errorString();
137         return TorrentInfo();
138     }
139 
140     if (file.size() > MAX_TORRENT_SIZE)
141     {
142         if (error)
143             *error = tr("File size exceeds max limit %1").arg(Utils::Misc::friendlyUnit(MAX_TORRENT_SIZE));
144         return TorrentInfo();
145     }
146 
147     QByteArray data;
148     try
149     {
150         data = file.readAll();
151     }
152     catch (const std::bad_alloc &e)
153     {
154         if (error)
155             *error = tr("Torrent file read error: %1").arg(e.what());
156         return TorrentInfo();
157     }
158     if (data.size() != file.size())
159     {
160         if (error)
161             *error = tr("Torrent file read error: size mismatch");
162         return TorrentInfo();
163     }
164 
165     file.close();
166 
167     return load(data, error);
168 }
169 
saveToFile(const QString & path) const170 void TorrentInfo::saveToFile(const QString &path) const
171 {
172     if (!isValid())
173         throw RuntimeError {tr("Invalid metadata.")};
174 
175     const lt::create_torrent torrentCreator = lt::create_torrent(*(nativeInfo()));
176     const lt::entry torrentEntry = torrentCreator.generate();
177 
178     QFile torrentFile {path};
179     if (!torrentFile.open(QIODevice::WriteOnly))
180         throw RuntimeError {torrentFile.errorString()};
181 
182     lt::bencode(Utils::IO::FileDeviceOutputIterator {torrentFile}, torrentEntry);
183     if (torrentFile.error() != QFileDevice::NoError)
184         throw RuntimeError {torrentFile.errorString()};
185 }
186 
isValid() const187 bool TorrentInfo::isValid() const
188 {
189     return (m_nativeInfo && m_nativeInfo->is_valid() && (m_nativeInfo->num_files() > 0));
190 }
191 
infoHash() const192 InfoHash TorrentInfo::infoHash() const
193 {
194     if (!isValid()) return {};
195 
196 #if (LIBTORRENT_VERSION_NUM >= 20000)
197     return m_nativeInfo->info_hashes();
198 #else
199     return m_nativeInfo->info_hash();
200 #endif
201 }
202 
name() const203 QString TorrentInfo::name() const
204 {
205     if (!isValid()) return {};
206     return QString::fromStdString(m_nativeInfo->orig_files().name());
207 }
208 
creationDate() const209 QDateTime TorrentInfo::creationDate() const
210 {
211     if (!isValid()) return {};
212 
213     const std::time_t date = m_nativeInfo->creation_date();
214     return ((date != 0) ? QDateTime::fromSecsSinceEpoch(date) : QDateTime());
215 }
216 
creator() const217 QString TorrentInfo::creator() const
218 {
219     if (!isValid()) return {};
220     return QString::fromStdString(m_nativeInfo->creator());
221 }
222 
comment() const223 QString TorrentInfo::comment() const
224 {
225     if (!isValid()) return {};
226     return QString::fromStdString(m_nativeInfo->comment());
227 }
228 
isPrivate() const229 bool TorrentInfo::isPrivate() const
230 {
231     if (!isValid()) return false;
232     return m_nativeInfo->priv();
233 }
234 
totalSize() const235 qlonglong TorrentInfo::totalSize() const
236 {
237     if (!isValid()) return -1;
238     return m_nativeInfo->total_size();
239 }
240 
filesCount() const241 int TorrentInfo::filesCount() const
242 {
243     if (!isValid()) return -1;
244     return m_nativeInfo->num_files();
245 }
246 
pieceLength() const247 int TorrentInfo::pieceLength() const
248 {
249     if (!isValid()) return -1;
250     return m_nativeInfo->piece_length();
251 }
252 
pieceLength(const int index) const253 int TorrentInfo::pieceLength(const int index) const
254 {
255     if (!isValid()) return -1;
256     return m_nativeInfo->piece_size(lt::piece_index_t {index});
257 }
258 
piecesCount() const259 int TorrentInfo::piecesCount() const
260 {
261     if (!isValid()) return -1;
262     return m_nativeInfo->num_pieces();
263 }
264 
filePath(const int index) const265 QString TorrentInfo::filePath(const int index) const
266 {
267     if (!isValid()) return {};
268     return Utils::Fs::toUniformPath(
269                 QString::fromStdString(m_nativeInfo->files().file_path(lt::file_index_t {index})));
270 }
271 
filePaths() const272 QStringList TorrentInfo::filePaths() const
273 {
274     QStringList list;
275     for (int i = 0; i < filesCount(); ++i)
276         list << filePath(i);
277 
278     return list;
279 }
280 
fileName(const int index) const281 QString TorrentInfo::fileName(const int index) const
282 {
283     return Utils::Fs::fileName(filePath(index));
284 }
285 
origFilePath(const int index) const286 QString TorrentInfo::origFilePath(const int index) const
287 {
288     if (!isValid()) return {};
289     return Utils::Fs::toUniformPath(
290                 QString::fromStdString(m_nativeInfo->orig_files().file_path(lt::file_index_t {index})));
291 }
292 
fileSize(const int index) const293 qlonglong TorrentInfo::fileSize(const int index) const
294 {
295     if (!isValid()) return -1;
296     return m_nativeInfo->files().file_size(lt::file_index_t {index});
297 }
298 
fileOffset(const int index) const299 qlonglong TorrentInfo::fileOffset(const int index) const
300 {
301     if (!isValid()) return -1;
302     return m_nativeInfo->files().file_offset(lt::file_index_t {index});
303 }
304 
trackers() const305 QVector<TrackerEntry> TorrentInfo::trackers() const
306 {
307     if (!isValid()) return {};
308 
309     const std::vector<lt::announce_entry> trackers = m_nativeInfo->trackers();
310 
311     QVector<TrackerEntry> ret;
312     ret.reserve(static_cast<decltype(ret)::size_type>(trackers.size()));
313 
314     for (const lt::announce_entry &tracker : trackers)
315         ret.append({QString::fromStdString(tracker.url)});
316 
317     return ret;
318 }
319 
urlSeeds() const320 QVector<QUrl> TorrentInfo::urlSeeds() const
321 {
322     if (!isValid()) return {};
323 
324     const std::vector<lt::web_seed_entry> &nativeWebSeeds = m_nativeInfo->web_seeds();
325 
326     QVector<QUrl> urlSeeds;
327     urlSeeds.reserve(static_cast<decltype(urlSeeds)::size_type>(nativeWebSeeds.size()));
328 
329     for (const lt::web_seed_entry &webSeed : nativeWebSeeds)
330     {
331         if (webSeed.type == lt::web_seed_entry::url_seed)
332             urlSeeds.append(QUrl(webSeed.url.c_str()));
333     }
334 
335     return urlSeeds;
336 }
337 
metadata() const338 QByteArray TorrentInfo::metadata() const
339 {
340     if (!isValid()) return {};
341 #if (LIBTORRENT_VERSION_NUM >= 20000)
342     const lt::span<const char> infoSection {m_nativeInfo->info_section()};
343     return {infoSection.data(), static_cast<int>(infoSection.size())};
344 #else
345     return {m_nativeInfo->metadata().get(), m_nativeInfo->metadata_size()};
346 #endif
347 }
348 
filesForPiece(const int pieceIndex) const349 QStringList TorrentInfo::filesForPiece(const int pieceIndex) const
350 {
351     // no checks here because fileIndicesForPiece() will return an empty list
352     const QVector<int> fileIndices = fileIndicesForPiece(pieceIndex);
353 
354     QStringList res;
355     res.reserve(fileIndices.size());
356     std::transform(fileIndices.begin(), fileIndices.end(), std::back_inserter(res),
357         [this](int i) { return filePath(i); });
358 
359     return res;
360 }
361 
fileIndicesForPiece(const int pieceIndex) const362 QVector<int> TorrentInfo::fileIndicesForPiece(const int pieceIndex) const
363 {
364     if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount()))
365         return {};
366 
367     const std::vector<lt::file_slice> files = nativeInfo()->map_block(
368                 lt::piece_index_t {pieceIndex}, 0, nativeInfo()->piece_size(lt::piece_index_t {pieceIndex}));
369     QVector<int> res;
370     res.reserve(static_cast<decltype(res)::size_type>(files.size()));
371     std::transform(files.begin(), files.end(), std::back_inserter(res),
372         [](const lt::file_slice &s) { return static_cast<int>(s.file_index); });
373 
374     return res;
375 }
376 
pieceHashes() const377 QVector<QByteArray> TorrentInfo::pieceHashes() const
378 {
379     if (!isValid())
380         return {};
381 
382     const int count = piecesCount();
383     QVector<QByteArray> hashes;
384     hashes.reserve(count);
385 
386     for (int i = 0; i < count; ++i)
387         hashes += {m_nativeInfo->hash_for_piece_ptr(lt::piece_index_t {i}), SHA1Hash::length()};
388 
389     return hashes;
390 }
391 
filePieces(const QString & file) const392 TorrentInfo::PieceRange TorrentInfo::filePieces(const QString &file) const
393 {
394     if (!isValid()) // if we do not check here the debug message will be printed, which would be not correct
395         return {};
396 
397     const int index = fileIndex(file);
398     if (index == -1)
399     {
400         qDebug() << "Filename" << file << "was not found in torrent" << name();
401         return {};
402     }
403     return filePieces(index);
404 }
405 
filePieces(const int fileIndex) const406 TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const
407 {
408     if (!isValid())
409         return {};
410 
411     if ((fileIndex < 0) || (fileIndex >= filesCount()))
412     {
413         qDebug() << "File index (" << fileIndex << ") is out of range for torrent" << name();
414         return {};
415     }
416 
417     const lt::file_storage &files = nativeInfo()->files();
418     const auto fileSize = files.file_size(lt::file_index_t {fileIndex});
419     const auto fileOffset = files.file_offset(lt::file_index_t {fileIndex});
420 
421     const int beginIdx = (fileOffset / pieceLength());
422     const int endIdx = ((fileOffset + fileSize - 1) / pieceLength());
423 
424     if (fileSize <= 0)
425         return {beginIdx, 0};
426     return makeInterval(beginIdx, endIdx);
427 }
428 
renameFile(const int index,const QString & newPath)429 void TorrentInfo::renameFile(const int index, const QString &newPath)
430 {
431     if (!isValid()) return;
432     nativeInfo()->rename_file(lt::file_index_t {index}, Utils::Fs::toNativePath(newPath).toStdString());
433 }
434 
fileIndex(const QString & fileName) const435 int TorrentInfo::fileIndex(const QString &fileName) const
436 {
437     // the check whether the object is valid is not needed here
438     // because if filesCount() returns -1 the loop exits immediately
439     for (int i = 0; i < filesCount(); ++i)
440         if (fileName == filePath(i))
441             return i;
442 
443     return -1;
444 }
445 
rootFolder() const446 QString TorrentInfo::rootFolder() const
447 {
448     return getRootFolder(filePaths());
449 }
450 
hasRootFolder() const451 bool TorrentInfo::hasRootFolder() const
452 {
453     return !rootFolder().isEmpty();
454 }
455 
setContentLayout(const TorrentContentLayout layout)456 void TorrentInfo::setContentLayout(const TorrentContentLayout layout)
457 {
458     switch (layout)
459     {
460     case TorrentContentLayout::Original:
461         setContentLayout(defaultContentLayout());
462         break;
463     case TorrentContentLayout::Subfolder:
464         if (rootFolder().isEmpty())
465             addRootFolder();
466         break;
467     case TorrentContentLayout::NoSubfolder:
468         if (!rootFolder().isEmpty())
469             stripRootFolder();
470         break;
471     }
472 }
473 
stripRootFolder()474 void TorrentInfo::stripRootFolder()
475 {
476     lt::file_storage files = m_nativeInfo->files();
477 
478     // Solution for case of renamed root folder
479     const QString path = filePath(0);
480     const std::string newName = path.left(path.indexOf('/')).toStdString();
481     if (files.name() != newName)
482     {
483         files.set_name(newName);
484         for (int i = 0; i < files.num_files(); ++i)
485             files.rename_file(lt::file_index_t {i}, files.file_path(lt::file_index_t {i}));
486     }
487 
488     files.set_name("");
489     m_nativeInfo->remap_files(files);
490 }
491 
addRootFolder()492 void TorrentInfo::addRootFolder()
493 {
494     const QString originalName = name();
495     Q_ASSERT(!originalName.isEmpty());
496 
497     const QString extension = Utils::Fs::fileExtension(originalName);
498     const QString rootFolder = extension.isEmpty()
499             ? originalName
500             : originalName.chopped(extension.size() + 1);
501     const std::string rootPrefix = Utils::Fs::toNativePath(rootFolder + QLatin1Char {'/'}).toStdString();
502     lt::file_storage files = m_nativeInfo->files();
503     files.set_name(rootFolder.toStdString());
504     for (int i = 0; i < files.num_files(); ++i)
505         files.rename_file(lt::file_index_t {i}, rootPrefix + files.file_path(lt::file_index_t {i}));
506     m_nativeInfo->remap_files(files);
507 }
508 
defaultContentLayout() const509 TorrentContentLayout TorrentInfo::defaultContentLayout() const
510 {
511     QStringList origFilePaths;
512     origFilePaths.reserve(filesCount());
513     for (int i = 0; i < filesCount(); ++i)
514         origFilePaths << origFilePath(i);
515 
516     const QString origRootFolder = getRootFolder(origFilePaths);
517     return (origRootFolder.isEmpty()
518             ? TorrentContentLayout::NoSubfolder
519             : TorrentContentLayout::Subfolder);
520 }
521 
nativeInfo() const522 std::shared_ptr<lt::torrent_info> TorrentInfo::nativeInfo() const
523 {
524     return m_nativeInfo;
525 }
526