rtorrent + wtorrent на debian
Никого слушать не буду, а просто возьму и напишу как делал, несмотря на то, что подсматривал сюда. Нужно же свое руководство для freebsd (веб-морда) переделать в debian. Также и скрипт запуска возьму нормальный.
Договоримся, что apache2 и php5 у нас работают и установлены. Начнем...
0. В репозиториях squeeze версия rtorrent'а 0.8.5.
apt-cache show rtorrent | grep Vers Version: 0.8.5-2
В lenny из 0.7 ветки. ИМХО, на lenny лучше поставить бекпорт.
1. Устанавливаем rtorrent и сразу же screen. Ну а также необходимые пакетики:
apt-get install php5-xmlrpc rtorrent php5-sqlite sqlite libxmlrpc-c3 libapache2-mod-scgi screen
2. Создаем юзера p2p через adduser. Сделал все по умолчанию:
adduser p2p
3. Подготавливаем папки:
mkdir /var/torrent mkdir /var/torrent/dl mkdir /var/torrent/work mkdir /var/torrent/session chown p2p /home/p2p chown -R p2p /var/torrent/
4. Правим конфиг:
nano /home/p2p/.rtorrent.rc
Конфиг должен быть примерно такой (опции прокомментировал не все, смотрите ман или описание на русском):
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 | #Количество пиров min_peers = 1 max_peers = 100 #Количество пиров для сидирования min_peers_seed = 1 max_peers_seed = 100 #Мне хватало и 1 Мб/с, так и оставлю download_rate = 1024 upload_rate = 1024 #Каталоги directory = /var/torrent/work session = /var/torrent/session #Этот каталог будет просматриваться каждые 5 секунд на наличие #новых торрент файлов. #Расшариваете каталог, кидаете туда торрент и через некоторое #время в work обнаружите закачиваемое schedule = watch_directory,5,5,load_start=/var/torrent/dl/*.torrent schedule = untied_directory,5,5,stop_untied= #Если на харде закончится место schedule = low_diskspace,5,60,close_low_diskspace=1000M #Порты и прочие настройки соединения port_range = 6890-6999 port_random = no use_udp_trackers = no encryption = allow_incoming,enable_retry,prefer_plaintext dht = auto dht_port = 6881 peer_exchange = yes safe_sync = yes encoding_list = UTF-8 #Ну а это наш scgi, которым мы сейчас и займемся scgi_port = localhost:5000 |
Не забываем чоунить, чтобы юзер смог прочесть конфиг:
chown p2p /home/p2p/.rtorrent.rc
5. При установке mod_scgi конфиг отсутствует. Сделаем его так же красиво, как и все настройки в дебиане для апача (первое что меня поразило при переезде с фри — все для людей). Конфиг mod_scgi содержит единственную строку:
nano /etc/apache2/mods-available/scgi.conf
SCGIMount "/RPC2" 127.0.0.1:5000
Добавляем модуль в набор загружаемых:
ln -s /etc/apache2/mods-available/scgi.conf /etc/apache2/mods-enabled/ ln -s /etc/apache2/mods-available/scgi.load /etc/apache2/mods-enabled/
Рестартуем апач:
/etc/init.d/apache2 restart
6. Дальше создаем скрипт запуска. Он скачивается с сайта автора программы и немного правится:
wget http://libtorrent.rakshasa.no/attachment/wiki/RTorrentCommonTasks/rtorrentInit.sh?format=raw -O /etc/init.d/rtorrent
Содержание такое:
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | #!/bin/sh ############# ###<Notes>### ############# # This script depends on screen. # For the stop function to work, you must set an # explicit session directory using ABSOLUTE paths (no, ~ is not absolute) in your rtorrent.rc. # If you typically just start rtorrent with just "rtorrent" on the # command line, all you need to change is the "user" option. # Attach to the screen session as your user with # "screen -dr rtorrent". Change "rtorrent" with srnname option. # Licensed under the GPLv2 by lostnihilist: lostnihilist _at_ gmail _dot_ com ############## ###</Notes>### ############## ####################### ##Start Configuration## ####################### # You can specify your configuration in a different file # (so that it is saved with upgrades, saved in your home directory, # or whateve reason you want to) # by commenting out/deleting the configuration lines and placing them # in a text file (say /home/user/.rtorrent.init.conf) exactly as you would # have written them here (you can leave the comments if you desire # and then uncommenting the following line correcting the path/filename # for the one you used. note the space after the ".". # . /etc/rtorrent.init.conf #Do not put a space on either side of the equal signs e.g. # user = user # will not work # system user to run as user=p2p # the system group to run as, not implemented, see d_start for beginning implementation # group=`id -ng "$user"` # the full path to the filename where you store your rtorrent configuration config="`su -c 'echo $HOME' $user`/.rtorrent.rc" # set of options to run with options="" # default directory for screen, needs to be an absolute path base="`su -c 'echo $HOME' $user`" # name of screen session srnname="rtorrent" # file to log to (makes for easier debugging if something goes wrong) logfile="/var/log/rtorrentInit.log" ####################### ###END CONFIGURATION### ####################### PATH=/usr/bin:/usr/local/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin DESC="rtorrent" NAME=rtorrent DAEMON=$NAME SCRIPTNAME=/etc/init.d/$NAME checkcnfg() { exists=0 for i in `echo "$PATH" | tr ':' '\n'` ; do if [ -f $i/$NAME ] ; then exists=1 break fi done if [ $exists -eq 0 ] ; then echo "cannot find rtorrent binary in PATH $PATH" | tee -a "$logfile" >&2 exit 3 fi if ! [ -r "${config}" ] ; then echo "cannot find readable config ${config}. check that it is there and permissions are appropriate" | tee -a "$logfile" >&2 exit 3 fi session=`getsession "$config"` if ! [ -d "${session}" ] ; then echo "cannot find readable session directory ${session} from config ${config}. check permissions" | tee -a "$logfile" >&2 exit 3 fi } d_start() { [ -d "${base}" ] && cd "${base}" stty stop undef && stty start undef su -c "screen -ls | grep -sq "\.${srnname}[[:space:]]" " ${user} || su -c "screen -dm -S ${srnname} 2>&1 1>/dev/null" ${user} | tee -a "$logfile" >&2 # this works for the screen command, but starting rtorrent below adopts screen session gid # even if it is not the screen session we started (e.g. running under an undesirable gid #su -c "screen -ls | grep -sq "\.${srnname}[[:space:]]" " ${user} || su -c "sg \"$group\" -c \"screen -fn -dm -S ${srnname} 2>&1 1>/dev/null\"" ${user} | tee -a "$logfile" >&2 su -c "screen -S "${srnname}" -X screen rtorrent ${options} 2>&1 1>/dev/null" ${user} | tee -a "$logfile" >&2 } d_stop() { session=`getsession "$config"` if ! [ -s ${session}/rtorrent.lock ] ; then return fi pid=`cat ${session}/rtorrent.lock | awk -F: '{print($2)}' | sed "s/[^0-9]//g"` if ps -A | grep -sq ${pid}.*rtorrent ; then # make sure the pid doesn't belong to another process kill -s INT ${pid} fi } getsession() { session=`cat "$1" | grep "^[[:space:]]*session[[:space:]]*=" | sed "s/^[[:space:]]*session[[:space:]]*=[[:space:]]*//" ` echo $session } checkcnfg case "$1" in start) echo -n "Starting $DESC: $NAME" d_start echo "." ;; stop) echo -n "Stopping $DESC: $NAME" d_stop echo "." ;; restart|force-reload) echo -n "Restarting $DESC: $NAME" d_stop sleep 1 d_start echo "." ;; *) echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2 exit 1 ;; esac exit 0 |
В нем нам надо поставить пользователя, от которого будет запускаться скрипт — строка 35. Главное нигде не наставить пробелов в этой строке.
7. Ставим автоматом на запуск:
chmod +x /etc/init.d/rtorrent update-rc.d rtorrent defaults /etc/init.d/rtorrent start
Запустился — отлично! Нет — ищем ошибки и исправляем. А дальше wtorrent
8. Качаем морду. Распаковываем в папочку wtorrent своего вебсервера.
9. Обязательно даем права 755 нашей папке:
chmod -R 755 wtorrent/
10. Переходим в папку conf и правим конфиг:
cd <путь>/conf/ cp sample.user.conf.php user.conf.php nano user.conf.php
Тут нужно посмотреть корректность относительных путей.
Например в моем случае получилось вот что:
<?php define ('LANGUAGE', 'ru_RU'); define ('DB_FILE', 'db/database.db'); define ('RT_HOST', 'localhost'); define ('RT_PORT', 80); define ('RT_DIR', '/RPC2'); define ('RT_AUTH', false); define ('RT_USER', ''); define ('RT_PASSWD', ''); define ('NO_MULTICALL', true); define ('EFFECTS', true); define ('DIR_TORRENTS', 'torrents'); define ('DIR_EXEC', '/var/www/data_ssl/wtorrent/'); define ('DIR_DOWNLOAD', '/var/www/data_ssl/wtorrent/in'); ?>
11. Ну и запускаем в браузере http://домен/путь/install.php. Если страница пустая — делаем то, что написано в п. 2. Инструкции предельно понятны, если нет — переводим со словарем. После успешной инсталляции и проверки конфига файл install.php нужно удалить.
Вот и все... Добавляем торренты и радуемся:)
Примечание: При добавлении торрента аккуратнее указываем путь к закачке. Директория должна принадлежать юзеру, от которого запущен rtorrent, и сам путь должен заканчиваться «/». Также случайно в конец пути не добавьте пробел.
Также хотелось бы отметить, что ошибки, связанные не с самими торрентами или серверами, не информативны, и приходится залезать через консоль.



*задумавшись* ... интересно ... респект!