Установка Prosody и миграция с ejabberd

Решил систематизировать все сакральные знания по установке этого неплохого Jabber-сервера. Настройка велась не с нуля, а выполнялся переезд с ejabberd, который в принципе неплох, но для небольшой организации немного тяжёлый, а также плохо себя вёл на Ubuntu 14.04.

Я ставил самую свежую версию (читай — версию в разработке), которая на данный момент 0.10. Адрес сервера будет 192.168.0.2, все операции от рута.

Установка и начальная настройка Prosody

Вначале добавим репозиторий и ключ:

wget https://prosody.im/files/prosody-debian-packages.key -O- | apt-key add -
echo "deb http://packages.prosody.im/debian trusty main" >> /etc/apt/sources.list.d/prosody.list

и ставим:

aptitude update
aptitude upgrade
aptitude install prosody-trunk lua-dbi-mysql

Генерируем ключи:

root@mail:/etc/prosody/certs# openssl req -new -x509 -days 365 -nodes -out "example.com.crt" -keyout "example.com.key"
Generating a 2048 bit RSA private key
.+++
.............................+++
writing new private key to 'example.com.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:RU
State or Province Name (full name) [Some-State]:Saint Petersburg
Locality Name (eg, city) []:Saint Petersburg
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example LLC
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:example.com
Email Address []:it@example.com

Теперь редактируем конфиг. Prosody написан на Lua, который гораздо более читабелен, чем старый формат Erlang (с переходом на YAML это исправили)

vim /etc/prosody/prosody.cfg.lua

Вот пример моего конфига на 2 домена:

admins = {"andrusha@example.com", "admin@example.org"}
use_libevent = true
modules_enabled = {
        -- Generally required
                "roster"; -- Allow users to have a roster. Recommended ;)
                "saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
                "tls"; -- Add support for secure TLS on c2s/s2s connections
                "dialback"; -- s2s dialback support
                "disco"; -- Service discovery
        -- Not essential, but recommended
                "private"; -- Private XML storage (for room bookmarks, etc.)
                "vcard"; -- Allow users to set vCards
        -- These are commented by default as they have a performance impact
                --"blocklist"; -- Allow users to block communications with other users
                --"compression"; -- Stream compression (requires the lua-zlib package installed)
        -- Nice to have
                "version"; -- Replies to server version requests
                "uptime"; -- Report how long server has been running
                "time"; -- Let others know the time here on this server
                "ping"; -- Replies to XMPP pings with pongs
                "pep"; -- Enables users to publish their mood, activity, playing music and more
                "register"; -- Allow users to register on this server using a client and change passwords

        -- Admin interfaces
                "admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
                --"admin_telnet"; -- Opens telnet console interface on localhost port 5582

        -- HTTP modules
                "bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
                "http_files"; -- Serve static files from a directory over HTTP

        -- Other specific functionality
                "groups"; -- Shared roster support
                "announce"; -- Send announcement to all online users
                --"welcome"; -- Welcome users who register accounts
                --"watchregistrations"; -- Alert admins of registrations
                --"motd"; -- Send a message to users when they log in
                "legacyauth"; -- Legacy authentication. Only used by some old clients and bots.
}

-- These modules are auto-loaded, but should you want
-- to disable them then uncomment them here:
modules_disabled = {
        -- "offline"; -- Store offline messages
        -- "c2s"; -- Handle client connections
        -- "s2s"; -- Handle server-to-server connections
        -- "posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
}

allow_registration = false

ssl = {
        key = "/etc/prosody/certs/localhost.key";
        certificate = "/etc/prosody/certs/localhost.crt";
}

c2s_require_encryption = false
s2s_secure_auth = false
allow_unencrypted_plain_auth = true
--s2s_insecure_domains = { "gmail.com" }
--s2s_secure_domains = { "jabber.org" }
pidfile = "/var/run/prosody/prosody.pid"
authentication = "internal_plain"
storage = "sql" -- Default is "internal"
-- For the "sql" backend, you can uncomment *one* of the below to configure:
--sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename.
sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "$ecretpa$$word", host = "localhost" }
--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
log = {
        info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
        error = "/var/log/prosody/prosody.err";
        "*syslog";
}
groups_file = "/var/lib/prosody/sharedgroups.txt"
----------- Virtual hosts -----------
VirtualHost "localhost"
        modules_enabled = {
                "admin_web";
        }

VirtualHost "192.168.0.2"
        modules_enabled = {
                "admin_web";
        }

VirtualHost "example.com"
        enabled = true
        modules_enabled = {
                "admin_web";
        }
        ssl = {
                key = "/etc/prosody/certs/example.com.key";
                certificate = "/etc/prosody/certs/example.com.crt";
        }

VirtualHost "example.org"
        enabled = true
        modules_enabled = {
                "admin_web";
        }
        ssl = {
                key = "/etc/prosody/certs/example.org.key";
                certificate = "/etc/prosody/certs/example.org.crt";
        }

------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see http://prosody.im/doc/components

---Set up a MUC (multi-user chat) room server on conference.example.com:
Component "conference.example.com" "muc"
        name = "example.com chatrooms server"
        restrict_room_creation = true
Component "conference.example.org" "muc"
        name = "example.org chatrooms server"
        restrict_room_creation = true

Движок базы. Я выбрал MySQL, хотя встроенный файловый формат тоже хорош и удобочитаем. Создаём базу:

mysql> create database prosody character set utf8 collate utf8_general_ci;
mysql> grant usage on *.* to prosody@localhost identified by '$ecretpa$$word';
mysql> grant all privileges on prosody.* to prosody@localhost;
mysql> flush privileges;

Важные моменты

c2s_require_encryption = false — в Miranda NG в Windows XP не работает TLS, поэтому я разрешил соединяться без шифрования. Внутри корпоративной сети это некритично. Также добавил параметр legacyauth

groups_file должен обязательно идти до VirtualHost. Это единственная настройка модуля groups, который нужен для загрузки общего ростера. Сам формат файла такой:

[+Бухгалтерия]
ivanova@example.com=Главбух
sidorova@examle.org
[+Продажи]
petrov@example.com
pupkin@example.org
[IT]
admin@example.com=Super Admin
coder@example.org=1С погромист

Плюсик означает публичную группу, то есть группы «Бухгалтерия» и «Продажи» будут у всех в списках, а «IT» только у членов группы «IT». Через веб-интерфейс управлять ими нельзя (я редактирую через Webmin). Через равно задаётся имя в списке. Кириллица работает (разумеется, UTF-8)

mod_admin_web — плагин веб-интерфейса. Он ещё менее функциональный, чем у ejabberd, и из него не отредактировать общий ростер, но лучшего пока нет. И его нужно ставить отдельно.
Инструкция по установке модулей
Инструкция к самому модулю
Ставим Mercurial, скачиваем репозиторий с плагинами, копируем и добавляем в конфиг (у меня уже добавлено). В Ubuntu плагины лежат в /usr/lib/prosody/modules/, узнать свой путь можно запустив prosodyctl about

apt-get install mercurial
cd /tmp
hg clone http://prosody-modules.googlecode.com/hg/ prosody-modules
cd prosody-modules/mod_admin_web
cp -r admin_web /usr/lib/prosody/modules/
chmod +x /usr/lib/prosody/modules/admin_web/get_deps.sh

Обычно в локальной сети Jabber-сервер не резольвится по своему полному доменному имени, поэтому нужно добавить VirtualHost для IP-адреса или внутреннего доменного имени.  Пример:
http://192.168.0.2:5280/admin/
https://192.168.0.2:5281/admin/

LuaExpat. prosodyctl может ругаться (без потери функционала, но сервер уязвим к DoS-атакам) на устаревший или отсутствующий luaexpat, который должен быть версии 1.3.0 или новее. В репозиториях текущего LTS Ubuntu Server 14.04 есть только 1.2.0, варианты решения — либо прикрутить из этого репозитория, либо отключить mod_compression, либо не заморачиваться :)

Миграция пользователей с ejabberd

1. Экспортируем дамп базы ejabberd

Может понадобиться пакет exmpp. Файл окажется в /var/lib/ejabberd, потом можно будет его перенести.

apt-get install exmpp
ejabberdctl dump ejabberd_dump
mv /var/lib/ejabberd/ejabber_dump /tmp

2. Импортируем дамп базы ejabberd в prosody

Инструкция по импорту здесь. Нужно поставить Mercurial (если ещё не установлен), скачать репозиторий с исходниками и отредактироватьь конфиг.

apt-get install mercurial
cd /tmp
hg clone hg clone http://hg.prosody.im/trunk prosody-hg
cd prosody-hg/tools/
./prosody-hg/tools/ejabberd2prosody.lua /tmp/ejabberd_dump

3. Конвертируем файловую базу Prosody в MySQL

Необязательно если мы не используем MySQL. Инструкция к мигратору.

cd migration
vim migrator.cfg.lua

По умолчанию этот файл есть в папке /etc/prosody, можно отредактировать либо его, либо этот и запускать с опцией —config=./migrator.cfg.lua

local data_path = '/var/lib/prosody';

input {
        type = "prosody_files";
        path = data_path;
}

output {
        type = "prosody_sql";
        driver = "MySQL";
        database = "prosody";
        username = "prosody";
        password = "$ecretpa$$word";
        host = "localhost";
}

И запускаем импорт

prosody-migrator input output

Добавить комментарий