libtorrentはBitTorrentプロトコルを実装したライブラリ。qBittorrentのような有名なBitTorrentソフトでも使われている。
※ちなみに「libtorrent」という名前のライブラリは二種類あるので注意が必要(もうひとつの「libtorrent」はrTorrentというBitTorrentクライアントで使われている)。ここで取り上げる「libtorrent」は、多くのLinuxのパッケージでは「libtorrent-rasterbar」という名前になっているはず。
公式サイトのチュートリアル(https://libtorrent.org/tutorial-ref.html)やoverview(https://libtorrent.org/manual-ref.html)、リファレンス(https://libtorrent.org/reference.html)には詳しい説明がある。
1.インストール
Ubuntuなどの場合、以下のコマンドでインストールできる。(
コンパイルするのでdev付きのパッケージを選ぶ)
$ sudo apt install libtorrent-rasterbar-dev
2.基本的な概念
torrent_handle
一つの
トレントファイルやマグネットリンクにつき、一つのハンドルを持つ。
後述のsessionが自動で管理する。
session
sessionは複数のtorrent_handleを管理し、通信やデータの書き込みなど、
トレントに必要な操作をほとんど自動で行ってくれる。
一つのプログラムにつき、基本的にsessionは一つでよい。
settings_pack
sessionの設定を格納し、sessionに渡すためのクラス。設定はsession内のすべてのtorrent_handleに影響する。
add_torrent_params
個々のtorrent_handleの設定を格納するためのクラス。
これを設定し、sessionに渡すことで、sessionがtorrent_handleを生成し、ファイル共有が開始される。
alert
sessionは別スレッドで通信を行うので、実行中のsessionから現在の状態を取得する方法が必要になる。libtorrentでは、alertを使ってsessionの様々な情報を取得できる。
BitTorrentの通信部分は、基本的にsessionが別スレッドですべて行ってくれるので、ループを回してsessionの状態確認・ダウンロード完了待機をするだけでよい。
#include <iostream>
#include <thread>
#include <chrono>
#include <filesystem>
#include <libtorrent/session.hpp>
#include <libtorrent/session_params.hpp>
#include <libtorrent/add_torrent_params.hpp>
#include <libtorrent/torrent_handle.hpp>
#include <libtorrent/alert_types.hpp>
#include <libtorrent/magnet_uri.hpp>
#include <libtorrent/load_torrent.hpp>
#include <libtorrent/alert.hpp>
int main(int argc, char const* argv[]) try
{
if (argc < 2) {
return 1;
}
lt::settings_pack p;
p.set_int(lt::settings_pack::alert_mask
, lt::alert_category::error
| lt::alert_category::storage
| lt::alert_category::status
| lt::alert_category::peer
| lt::alert_category::dht
| lt::alert_category::file_progress
| lt::alert_category::piece_progress
| lt::alert_category::upload
| lt::alert_category::incoming_request
);
lt::session ses(p);
lt::add_torrent_params atp;
if(std::filesystem::exists(argv[1])){
atp = lt::load_torrent_file(argv[1]);
}
else{
atp = lt::parse_magnet_uri(argv[1]);
}
atp.save_path = ".";
ses.async_add_torrent(std::move(atp));
for (;;) {
std::vector<lt::alert*> alerts;
ses.pop_alerts(&alerts);
for (lt::alert const* a : alerts) {
std::cout << a->message() << "\n";
if (lt::alert_cast<lt::torrent_finished_alert>(a)) {
goto done;
}
if (lt::alert_cast<lt::torrent_error_alert>(a)) {
throw std::runtime_error(a->message());
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
done:
std::cout << "ダウンロードが完了しました" << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
}
上のコードは、
$ g++ -o simple_torrent_client simple_torrent_client.cpp `pkg-config --cflags --libs libtorrent-rasterbar`
このようなコマンドでコンパイルして、
$ ./simple_torrent_client [マグネットリンク]
もしくは
$ ./simple_torrent_client [トレントファイル]
でトレントのダウンロードができるはず。
100行以下のコードだが、これでも十分に実用的なBitTorrentクライアントになる。
参考リンク
https://libtorrent.org/tutorial-ref.html
https://libtorrent.org/manual-ref.html
https://libtorrent.org/reference.htmlライセンス
記事内の
BitTorrentクライアントのサンプルプログラムは、libtorrentのドキュメント(
https://libtorrent.org/tutorial-ref.html、
https://github.com/arvidn/libtorrent/blob/RC_2_0/docs/tutorial.rst)内のコードの改変なので、以下にライセンスを明示する。
Copyright (c) 2003-2020, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.