RTorrent (Русский) - ArchWiki

# RTorrent (Русский)

Эта страница нуждается в сопроводителе

Статья не гарантирует актуальность информации. Помогите русскоязычному сообществу поддержкой подобных страниц. См. Команда переводчиков ArchWiki

Информация в этой статье или разделе устарела

Причина: rc.d references. Needs update, see Systemd (Русский). (Обсудить)

rTorrent - это быстрый и эффективный клиент BitTorrent использующий библиотеку libtorrent. rTorrent написан на C++ и использует программную библиотеку ncurses, которая означает, что он использует текстовый интерфейс. В сочетании с GNU Screen и Secure Shell, он становится удобным удаленным клиентом BitTorrent.

## Установка

Установите пакет rtorrent, доступный в официальном репозитории.

Кроме того rtorrent-svn[broken link: package not found] или rtorrent-extended можно установить из AUR.

## Конфигурация

Обратите внимание: Смотрите статью rTorrent для получения дополнительной информации: Common Tasks in rTorrent for Dummies

До запуска rTorrent, найдите пример конфигурационного файла `/usr/share/doc/rtorrent/rtorrent.rc` и скопируйте его в `~/.rtorrent.rc`:

    $ cp /usr/share/doc/rtorrent/rtorrent.rc ~/.rtorrent.rc

### Производительность

Обратите внимание: Смотрите статью rTorrent для получения дополнительной информации: Performance Tuning

Значения следующих параметров зависят от аппаратной части системы и скорости интернет-соединения. Чтобы найти оптимальные значения, читайте статью: Optimize Your BitTorrent Download Speed

    min_peers = 40
    max_peers = 52

    min_peers_seed = 10
    max_peers_seed = 52

    max_uploads = 8

    download_rate = 200
    upload_rate = 28

Опция `check_hash` выполняет проверку хэш-кода, когда загрузка завершена или запущен rTorrent. При запуске, она проверяет на наличие ошибок завершенные (загруженные) файлы.

    check_hash = yes

### Создание и управление файлами

Опция `directory` будет определять место, где ваши данные будут сохраняться. Обязательно указывайте абсолютный путь, так как rTorrent не поддерживает относительные пути:

    directory = /home/[пользователь]/torrents/

Опция `session` позволяет rTorrent сохранять текущее состояние (прогресс) ваших загрузок. Рекомендуется создать директорию с названием `.session` (например: `$ mkdir ~/.session`).

    session = /home/[пользователь]/.session/

Опция `schedule` в rTorrent наблюдает за определенным каталогом на наличие новых торрент-файлов. Сохранение торрент-файла в эту директорию, автоматически начнет загрузку. Не забудьте создать каталог, для автоматической загрузки (например: `$ mkdir ~/obs`). Будьте осторожны, при использовании этой опции так как rTorrent переместит торрент-файл в вашу папку `.session` и переименует его в хэш-значение.

    schedule = watch_directory,5,5,load_start=/home/[user]/watch/*.torrent
    schedule = untied_directory,5,5,stop_untied=
    schedule = tied_directory,5,5,start_tied=

Следующая опция `schedule` предназначена для остановки rTorrent от загрузки данных, когда не хватает дискового пространства.

    schedule = low_diskspace,5,60,close_low_diskspace=100M

### Настройка портов

Параметр `port_range` задает порт(ы) для прослушивания. Рекомендуется использовать порт, который больше чем 49152 (см.: List of port numbers). Несмотря на то, что rTorrent позволяет использовать диапазон портов, рекомендуется использовать один.

    port_range = 49164-49164

Кроме того, убедитесь, что переадресация включена для надлежащих портов (см.: Port Forward Guides).

### Дополнительные настройки

Параметр `encryption` включает или отключает шифрование. Очень важно включить эту опцию, не только для Вас, но так же для Ваших коллег (пиров). Некоторым пользователям нужно скрыть использование своей пропускной способности от их интернет-провайдера.

    encryption = allow_incoming,try_outgoing,enable_retry

Последняя опция `dht` включает поддержку DHT. DHT распространен среди открытых трекеров и позволяет клиенту получить больше пиров.

    dht = auto
    dht_port = 6881
    peer_exchange = yes

Обратите внимание: См. статью rTorrent для получения дополнительной информации: Using DHT

## Привязка клавиш

rTorrent управляется горячими клавишами. Краткий справочник доступен в таблице ниже. Полное руководство доступно в статье rTorrent (см.: rTorrent User Guide).

Обратите внимание: Двойное быстрое нажатие `Ctrl-q` заставит rTorrent завершить работу не дожидаясь отправки сигнала стоп к подключенным трекерам.

Команда | Действие
--- | ---
Ctrl-q | Выход из приложения
Ctrl-s | Начать загрузку. В первую очередь запускает хэширование, если оно еще не было сделано.
Ctrl-d | Остановка активной загрузки или удаление остановленной загрузки.
Ctrl-k | Остановить и закрыть файлы активной загрузки.
Ctrl-r | Инициировать хэш-проверку торрента. Без запуска загрузки/отдачи.
Влево | Возврат к предыдущему экрану.
Вправо | Переход к следующему экрану
Backspace/Return(Enter) | Добавляет указанный *.torrent
a|s|d | Регулировка увеличения глобальной скорости отдачи на 1|5|50 КБ/с
A|S|D | Регулировка увеличения глобальной скорости загрузки на 1|5|50 КБ/с
z|x|c | Регулировка уменьшения глобальной скорости отдачи на 1|5|50 КБ/С
Z|X|C | Регулировка уменьшения глобальной скорости загрузки на 1|5|50 КБ/с

### Redundant mapping

`Ctrl-s` is often used for terminal control to stop screen output while `Ctrl-q` is used to start it. These mappings may interfere with rTorrent. Check to see if these terminal options are bound to a mapping:

    $ stty -a

    ...
    swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V;
    ...

To remove the mappings, change the terminal characteristics to undefine the aforementioned special characters (i.e. `stop` and `start`):

    # stty stop undef
    # stty start undef

To remove these mappings automatically at startup you may add the two preceding commands to your `~/.bashrc` file.

## Additional Tips

### Separate session with Screen

GNU Screen is a wrapper that allows separation between the text program and the shell from which it was launched.

Screen flow-control interferes with the `Ctrl-q` mapping (see: Redundant mapping). To disable it add the following to `~/.screenrc`:

    defflow off

An alternative is to escape the command and send it directly to rTorrent. In other words, use `Ctrl-a` `q` to quit rTorrent within GNU Screen.

To automatically start rTorrent within Screen, add the following to the `~/.screenrc` configuration file:

    screen -t rtorrent rtorrent

#### Run as a daemon

Информация в этой статье или разделе устарела

Причина: update for systemd (Обсудить)

Обратите внимание: See the rTorrent wiki article on this subject for more information: Starting rTorrent on System Startup

Alternatively, GNU Screen and rTorrent can be run together as a daemon (see also: Arch Linux Forums thread, Gentoo Discussion Forums thread).

To use this script with tmux, replace line 9 with `su - USER -c 'tmux new -s rtorrent -d rtorrent' &> /dev/null` (see: rTorrent daemon with tmux).

With root permissions create the following file:

    /etc/rc.d/rtorrent

    #!/bin/bash

    . /etc/rc.conf
    . /etc/rc.d/functions

    case "$1" in
      start)
        stat_busy "Starting rtorrent"
        su - USER -c 'screen -d -m -S rtorrent rtorrent' &> /dev/null
        if [ $? -gt 0 ]; then
          stat_fail
        else
          add_daemon rtorrent
          stat_done
        fi
        ;;
      stop)
        stat_busy "Stopping rtorrent"
        killall -w -s 2 /usr/bin/rtorrent &> /dev/null
        if [ $? -gt 0 ]; then
          stat_fail
        else
          rm_daemon rtorrent
          stat_done
        fi
        ;;
      restart)
        $0 stop
        sleep 1
        $0 start
        ;;
      *)
        echo "usage: $0 {start|stop|restart}"
    esac
    exit 0

Make sure to change USER to the username that will be running rtorrent.

Make the file executable:

    # chmod +x /etc/rc.d/rtorrent

Creating a `.rtorrent.rc` file with relative paths in a user's home directory will break the rc.d script. To run multiple instances of rTorrent with relative paths under different users, replace line 9 in `/etc/rc.d/rtorrent` with the following:

       su username -c 'cd /home/username && screen -d -m -S rtorrent rtorrent' &> /dev/null

Alternatively, you can set absolute paths in the configuration file.

To run the daemon user multiple users create one rc.d script for each user. Then replace line 9 in `/etc/rc.d/rtorrent` with the following:

       su - username -c 'killall -w -s 2 /usr/bin/rtorrent' &> /dev/null

To connect to the daemon process on a remote machine use SSH:

    $ ssh -t rtorrent@192.168.1.10 'screen -r'

Or if you used tmux instead of screen:

    $ ssh -t rtorrent@192.168.1.10 'tmux attach -t rtorrent'

For more information about daemon scripts see: Writing rc.d scripts

This script can be found in rtorrent-daemon-git from AUR.

Alternate scripts can be found on the Gentoo Wiki Archives, Joyent CodeSnippets and ByteTouch.

### Pre-allocation

The rTorrent package in the community repository lacks pre-allocation. Compiling rTorrent with pre-allocation allows files to be allocated before downloading the torrent. The major benefit is that it limits and avoids fragmentation of the filesystem. However, this introduces a delay during the pre-allocation if the filesystem does not support the fallocate syscall natively.

Therefore this switch is recommended for xfs, ext4 and btrfs filesystems, which have native fallocate syscall support. They will see no delay during preallocation and no fragmented filesystem. Pre-allocation on others filesystems will cause a delay but will not fragment the files.

To make pre-allocation available, recompile libtorrent from the ABS tree with the following new switch:

     $ ./configure --prefix=/usr --disable-debug --with-posix-fallocate

To enable it, add the following to your `~/rtorrent.rc`:

    ~/rtorrent.rc

      # Preallocate files; reduces defragmentation on filesystems.
      system.file_allocate.set = yes

### Manage completed files

Обратите внимание: Currently, this part requires either the svn version of rtorrent/libtorrent or having applied the patch to 0.8.6 that adds 'equal'.
Обратите внимание: If you're having trouble with this tip, it's probably easier to follow this

It is possible to have rtorrent sort completed torrent data to specific folders based on which 'watch' folder you drop the *.torrent into while continuing to seed. Many examples show how to do this with torrents downloaded by rtorrent. The problem is when you try to drop in 100% done torrent data and then have rtorrent check the data and resume. It will not be sorted.

As a solution, use the following example in your ~/.rtorrent.rc. Make sure to change the paths.

    # location where new torrent data is placed, and where you should place your
    # 'complete' data before you place your *.torrent file into the watch folder
    directory = /home/user/torrents/incomplete

    # schedule a timer event named 'watch_directory_1':
    # 1) triggers 10 seconds after rtorrent starts
    # 2) triggers at 10 second intervals thereafter
    # 3) Upon trigger, attempt to load (and start) new *.torrent files found in /home/user/torrents/watch/
    # 4) set a variable named 'custom1' with the value "/home/user/torrents/complete"
    # NOTE: if you do not want it to automatically start the torrent, change 'load_start' to 'load'
    schedule = watch_directory_1,10,10,"load_start=/home/user/torrents/watch/*.torrent,d.set_custom1=/home/user/torrents/complete"

    # insert a method with the alias 'checkdirs1'
    # 1) returns true if the current path of the torrent data is not equal to the value of custom1
    # 2) otherwise, returns false
    system.method.insert=checkdirs1,simple,"not=\"$equal={d.get_custom1=,d.get_base_path=}\""

    # insert a method with the alias 'movecheck1'
    # 1) returns true if all 3 commands return true ('result of checkdirs1' && 'torrent is 100% done', 'custom1 variable is set')
    # 2) otherwise, returns false
    system.method.insert=movecheck1,simple,"and={checkdirs1=,d.get_complete=,d.get_custom1=}"

    # insert a method with the alias 'movedir1'
    # (a series of commands, separated by ';')
    # 1) "set path of torrent to equal the value of custom1";
    # 2) "mv -u <current data path> <custom1 path>";
    # 3) "clear custom1", "stop the torrent","resume the torrent"
    # 4) stop the torrent
    # 5) start the torrent (to get the torrent to update the 'base path')
    system.method.insert=movedir1,simple,"d.set_directory=$d.get_custom1=;execute=mv,-u,$d.get_base_path=,$d.get_custom1=;d.set_custom1=;d.stop=;d.start="

    # set a key with the name 'move_hashed1' that is triggered by the hash_done event.
    # 1) When hashing of a torrent completes, this custom key will be triggered.
    # 2) when triggered, execute the 'movecheck1' method and check the return value.
    # 3) if the 'movecheck' method returns 'true', execute the 'movedir1' method we inserted above.
    # NOTE: 'branch' is an 'if' conditional statement: if(movecheck1){movedir1}
    system.method.set_key=event.download.hash_done,move_hashed1,"branch={$movecheck1=,movedir1=}"

You can add additional watch folders and rules should you like to sort your torrents into special folders.

For example, if you would like the torrents to download in:

    /home/user/torrents/incomplete

and then sort the torrent data based on which folder you dropped the *.torrent into:

    /home/user/torrents/watch => /home/user/torrents/complete
    /home/user/torrents/watch/iso => /home/user/torrents/complete/iso
    /home/user/torrents/watch/music => /home/user/torrents/complete/music

You can have the following in your .rtorrent.rc:

    directory = /home/user/torrents/incomplete
    schedule = watch_directory_1,10,10,"load_start=/home/user/torrents/watch/*.torrent,d.set_custom1=/home/user/torrents/complete"

    schedule = watch_directory_2,10,10,"load_start=/home/user/torrents/watch/iso/*.torrent,d.set_custom1=/home/user/torrents/complete/iso"

    schedule = watch_directory_3,10,10,"load_start=/home/user/torrents/watch/music/*.torrent,d.set_custom1=/home/user/torrents/complete/music"

    system.method.insert=checkdirs1,simple,"not=\"$equal={d.get_custom1=,d.get_base_path=}\""
    system.method.insert=movecheck1,simple,"and={checkdirs1=,d.get_complete=,d.get_custom1=}"
    system.method.insert=movedir1,simple,"d.set_directory=$d.get_custom1=;execute=mv,-u,$d.get_base_path=,$d.get_custom1=;d.set_custom1=;d.stop=;d.start="
    system.method.set_key=event.download.hash_done,move_hashed1,"branch={$movecheck1=,movedir1=}"

Also see pyroscope especially the rtcontrol examples. There is an AUR package.

#### Notification with Google Mail

Cell phone providers allow you to "email" your phone:

    Verizon: 10digitphonenumber@vtext.com
    AT&T: 10digitphonenumber@txt.att.net
    Former AT&T customers: 10digitphonenumber@mmode.com
    Sprint: 10digitphonenumber@messaging.sprintpcs.com
    T-Mobile: 10digitphonenumber@tmomail.net
    Nextel: 10digitphonenumber@messaging.nextel.com
    Cingular: 10digitphonenumber@cingularme.com
    Virgin Mobile: 10digitphonenumber@vmobl.com
    Alltel: 10digitphonenumber@alltelmessage.com OR
    10digitphonenumber@message.alltel.com
    CellularOne: 10digitphonenumber@mobile.celloneusa.com
    Omnipoint: 10digitphonenumber@omnipointpcs.com
    Qwest: 10digitphonenumber@qwestmp.com
    Telus: 10digitphonenumber@msg.telus.com
    Rogers Wireless: 10digitphonenumber@pcs.rogers.com
    Fido: 10digitphonenumber@fido.ca
    Bell Mobility: 10digitphonenumber@txt.bell.ca
    Koodo Mobile: 10digitphonenumber@msg.koodomobile.com
    MTS: 10digitphonenumber@text.mtsmobility.com
    President's Choice: 10digitphonenumber@txt.bell.ca
    Sasktel: 10digitphonenumber@sms.sasktel.com
    Solo: 10digitphonenumber@txt.bell.ca

- Install Heirloom's mailx program which is provided by the mailx-heirloom[broken link: replaced by s-nail] package that is found in the Official repositories (Русский).

- Clear the `/etc/mail.rc` file and enter:

Обратите внимание: Older versions of Heirloom's mailx use `/etc/nail.rc`.

    set sendmail="/usr/bin/mailx"
    set smtp=smtp.gmail.com:587
    set smtp-use-starttls
    set ssl-verify=ignore
    set ssl-auth=login
    set smtp-auth-user=USERNAME@gmail.com
    set smtp-auth-password=PASSWORD

Now to send the text, we must pipe a message to the mailx program.

- Make a Bash script:

    /path/to/mail.sh

    echo "$@: Done" | mailx 5551234567@vtext.com

Where the $@ is a variable holding all the arguments passed to our script.

- And finally, add the important `~/.rtorrent.rc` line:

    system.method.set_key = event.download.finished,notify_me,"execute=/path/to/mail.sh,$d.get_name="

Breaking it down:

`notify_me` is the command id, which may be used by other commands, it can be just about anything you like, so long as it is unique.

`execute=` is the rtorrent command, in this case to execute a shell command.

`/path/to/mail.sh` is the name of our script (or whatever command you want to execute) followed by a comma separated list of all the switches/arguments to be passed.

`$d.get_name=` 'd' is an alias to whatever download triggered the command, get_name is a function which returns the name of our download, and the '$' tells rTorrent to replace the command with its output before it calls execute.

The end result? When that torrent, 'All Live Nudibranches', that we started before leaving for work finishes, we will be texted:

    All Live Nudibranches: Done

### Displaying active torrents

The rtorrent doesn't list the active tab properly by default, add this line to your `.rtorrent.rc` to show only active torrents

    schedule = filter_active,30,30,"view_filter = active,\"or={d.get_up_rate=,d.get_down_rate=}\""

Then press `9` in your rTorrent client to see the changes in action.

## Troubleshooting

### CA certificates

To use rTorrent with a tracker that uses HTTPS, do the following as root:

    # cd /etc/ssl/certs

    # wget --no-check-certificate https://www.geotrust.com/resources/root_certificates/certificates/Equifax_Secure_Global_eBusiness_CA-1.cer

    # mv Equifax_Secure_Global_eBusiness_CA-1.cer Equifax_Secure_Global_eBusiness_CA-1.pem

    # c_rehash

And from now on run rTorrent with:

    $ rtorrent -o http_capath=/etc/ssl/certs

If you use GNU Screen, update the `.screenrc` configuration file to reflect this change:

    $ screen -t rtorrent rtorrent -o http_capath=/etc/ssl/certs

In rTorrent 0.8.9, set `network.http.ssl_verify_peer.set=0` to fix the problem.[1]

For more information see: rTorrent Error & CA Certificate and rTorrent Certificates Problem

## Web interface

There are numerous web interfaces and front ends for rTorrent including:

- WTorrent is a web interface to rtorrent programmed in php using Smarty templates and XMLRPC for PHP library.
- nTorrent is a graphical user interface client to rtorrent (a cli torrent client) written in Java.
- rTWi is a simple rTorrent web interface written in PHP.
- Rtgui is a web based front end for rTorrent written in PHP and uses XML-RPC to communicate with the rTorrent client.
- rutorrent and Forum - A web-based front-end with an interface very similar to uTorrent which supports many plugins and advanced features (см. также: RuTorrent и Guide for rTorrent + ruTorrent Installation).

Обратите внимание: rTorrent is currently built using XML-RPC for C/C++, which is required for some web interfaces (e.g. ruTorrent).

### XMLRPC interface

If you want to use rtorrent with some web interfaces (e.g. rutorrent) you need to add the following line to the configuration file:

    scgi_port = localhost:5000

For more information see: Using XMLRPC with rtorrent

## See also

- Screen Tips
- Comparison of BitTorrent clients on Wikipedia
- rTorrent Community Wiki - A public place for information on rTorrent and any project related to rTorrent, regarding setup, configuration, operations, and development.
- PyroScope - A collection of command line tools for rTorrent. It provides commands for creating and modifying torrent files, moving data on completion without having multiple watch folders, and mass-controlling download items via rTorrent's XML-RPC interface: searching, start/stop, deleting items with or without their data, etc. It also offers a documented Python API.
- How-to Install rTorrent and Hellanzb on CentOS 5 64-bit VPS
- Installation Guide for rTorrent and Pryoscope on Debian - A collection of tools for the BitTorrent protocol and especially the rTorrent client
- mktorrent - A command line application used to generate torrent files, which is available as mktorrent in the Official repositories (Русский).

Forum threads

- 2009-03-11 - Arch Linux - HOWTO: rTorrent stats in Conky

Categories:

- Internet applications (Русский)
- Русский