Користувальницькі налаштування

Налаштування сайту


jabber

Розбіжності

Тут показані розбіжності між вибраною ревізією та поточною версією сторінки.

Посилання на цей список змін

Порівняння попередніх версійПопередня ревізія
Наступна ревізія
Попередня ревізія
jabber [2013/10/22 16:46] – [Подключение к серверам Google] wombatjabber [2016/02/28 10:15] (поточний) – [Модули] wombat
Рядок 1: Рядок 1:
 +====== Сервер ======
  
 +===== Выбор =====
 +
 +[[http://prosody.im/ | Prosody]]
 +
 +===== Установка =====
 +
 +Рассмотрим процесс установки Prosody в операционной системе Debian GNU/Linux.
 +
 +Как описано на [[http://prosody.im/download/package_repository | этой странице]], добавляем репозиторий пакетов для Дебиан:
 +
 +  deb http://packages.prosody.im/debian wheezy main
 +
 +Для этой цели может понадобиться добавить ключ их репозитория:
 +
 +  wget https://prosody.im/files/prosody-debian-packages.key -O- | sudo apt-key add -
 +
 +Если wget выдаёт ошибку
 +
 +  ERROR: The certificate of `prosody.im' is not trusted.
 +  ERROR: The certificate of `prosody.im' hasn't got a known issuer.
 +
 +тогда его следует запускать с ключом --no-check-certificate . Тогда вся строка целиком будет выглядеть так:
 +
 +  wget --no-check-certificate https://prosody.im/files/prosody-debian-packages.key -O- | sudo apt-key add -
 +
 +После того, как добавлен ключ, обновляем списки доступных пакетов:
 +
 +  apt-get update
 +
 +И устанавливаем Prosody:
 +
 +  apt-get install prosody
 +
 +===== Настройка =====
 +
 +На [[http://prosody.im/doc/configure | сайте Prosody]] имеется понятная инструкция по первичной настройке сервера. Базовая настройка чрезвычайно проста и состоит из следующих шагов:
 +
 +
 +**1.** Указание **домена** (или нескольких доменов), на котором наш Jabber-сервер будет работать. Для этого в файле ''/etc/prosody/prosody.cfg.lua'' Находим строку
 +
 +    VirtualHost "example.org"
 +
 +и изменяем её так, как нам нужно. Если наш домен "wombat.org.ua", то строка будет выглядеть так:
 +
 +    VirtualHost "wombat.org.ua"
 +
 +Если далее в описании данного домена имеется строка
 +
 +    enabled = false
 +
 +её следует закомментировать следующим образом:
 +
 +  
 +  -- enabled = false
 +
 +**2.** Выбор **модулей**, загружаемых при запуске сервера. Предлагаемый разработчиками набор модулей по умолчанию, указанный в файле конфигурации, для старта подойдёт. Позже можно будет легко изменить этот список.
 +
 +После этого Jabber-сервер готов к запуску. Однако, такой сервер работает только по незащищённому соединению, и большинство современных jabber-клиентов будут сообщать пользователю об этом. Чтобы использовать защищённое соединение, нужно [[http://prosody.im/doc/certificates | создать и настроить SSL-сертификат]] для нашего сервера.
 +
 +**3.** Создать свой **SSL-сертификат**((Самоподписанный сертификат по умолчанию не считается доверенным большинством программ, поэтому они будут выдавать запрос на его подтверждение. Можно получить доверенный SSL-сертификат для своего домена бесплатно -- см. [[https://letsencrypt.readthedocs.org/en/latest/intro.html | Let’s Encrypt ]])) можно (независимо от версии Prosody) следующим образом:
 +
 +  openssl req -new -x509 -days 365 -nodes -out "wombat.org.ua.crt" -keyout "wombat.org.ua.key"
 +
 +После этого перемещаем полученные файлы, например, в каталог ''/etc/prosody/certs/'' и указываем пути к ним в файле конфигурации:
 +
 +  ssl = {
 +         key = "/etc/prosody/certs/wombat.org.ua.key";
 +         certificate = "/etc/prosody/certs/wombat.org.ua.crt";
 +  }
 +
 +для глобальных настроек, а также в разделе соответствующего домена:
 +
 +  VirtualHost "wombat.org.ua"
 +     -- enabled = false -- Remove this line to enable this host
 +               
 +     -- Assign this host a certificate for TLS, otherwise it would use the one
 +     -- set in the global section (if any).
 +     -- Note that old-style SSL on port 5223 only supports one certificate, and will always
 +     -- use the global one.
 +     ssl = {
 + key = "/etc/prosody/certs/wombat.org.ua.key";
 +                certificate = "/etc/prosody/certs/wombat.org.ua.crt";
 +     }
 +
 +**4.** Если сервер не предназначен для публичного использования, свободную регистрацию новых учётных записей следует отключить:
 +
 +  allow_registration = false;
 +
 +**5.** Полезной возможностью также является создание чат-комнат. Следующая строка включает такую возможность:
 +
 +  Component "conference.example.com" "muc"
 +
 +Таким образом, полный файл конфигурации (с комментариями от разработчиков Prosody) может выглядеть примерно так:
 +
 +<file lua /etc/prosody/prosody.cfg.lua>
 +-- Prosody XMPP Server Configuration
 +--
 +-- Information on configuring Prosody can be found on our
 +-- website at http://prosody.im/doc/configure
 +--
 +-- Tip: You can check that the syntax of this file is correct
 +-- when you have finished by running: luac -p prosody.cfg.lua
 +-- If there are any errors, it will let you know what and where
 +-- they are, otherwise it will keep quiet.
 +--
 +-- Good luck, and happy Jabbering!
 +
 +
 +---------- Server-wide settings ----------
 +-- Settings in this section apply to the whole server and are the default settings
 +-- for any virtual hosts
 +
 +-- This is a (by default, empty) list of accounts that are admins
 +-- for the server. Note that you must create the accounts separately
 +-- (see http://prosody.im/doc/creating_accounts for info)
 +-- Example: admins = { "user1@example.com", "user2@example.net" }
 +admins = { "vasiliy@wombat.org.ua" }
 +
 +-- Enable use of libevent for better performance under high load
 +-- For more information see: http://prosody.im/doc/libevent
 +--use_libevent = true;
 +
 +-- This is the list of modules Prosody will load on startup.
 +-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
 +-- Documentation on modules can be found at: http://prosody.im/doc/modules
 +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
 + "posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
 +
 + -- 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
 + --"privacy"; -- Support privacy lists
 + "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
 +};
 +
 +-- Disable account creation by default, for security
 +-- For more information see http://prosody.im/doc/creating_accounts
 +allow_registration = false;
 +
 +-- These are the SSL/TLS-related settings. If you don't want
 +-- to use SSL/TLS, you may comment or remove this
 +ssl = {
 + key = "/etc/prosody/certs/wombat.org.ua.key";
 + certificate = "/etc/prosody/certs/wombat.org.ua.crt";
 +}
 +
 +-- Force clients to use encrypted connections? This option will
 +-- prevent clients from authenticating unless they are using encryption.
 +
 +c2s_require_encryption = false
 +
 +-- Force certificate authentication for server-to-server connections?
 +-- This provides ideal security, but requires servers you communicate
 +-- with to support encryption AND present valid, trusted certificates.
 +-- NOTE: Your version of LuaSec must support certificate verification!
 +-- For more information see http://prosody.im/doc/s2s#security
 +
 +s2s_secure_auth = false
 +
 +-- Many servers don't support encryption or have invalid or self-signed
 +-- certificates. You can list domains here that will not be required to
 +-- authenticate using certificates. They will be authenticated using DNS.
 +
 +-- s2s_insecure_domains = { "gmail.com" }
 +
 +-- Even if you leave s2s_secure_auth disabled, you can still require valid
 +-- certificates for some domains by specifying a list here.
 +
 +--s2s_secure_domains = { "jabber.org" }
 +
 +-- Required for init scripts and prosodyctl
 +pidfile = "/var/run/prosody/prosody.pid"
 +
 +-- Select the authentication backend to use. The 'internal' providers
 +-- use Prosody's configured data storage to store the authentication data.
 +-- To allow Prosody to offer secure authentication mechanisms to clients, the
 +-- default provider stores passwords in plaintext. If you do not trust your
 +-- server please see http://prosody.im/doc/modules/mod_auth_internal_hashed
 +-- for information about using the hashed backend.
 +
 +authentication = "internal_plain"
 +
 +-- Select the storage backend to use. By default Prosody uses flat files
 +-- in its configured data directory, but it also supports more backends
 +-- through modules. An "sql" backend is included by default, but requires
 +-- additional dependencies. See http://prosody.im/doc/storage for more info.
 +
 +--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 = "secret", host = "localhost" }
 +--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
 +
 +-- Logging configuration
 +-- For advanced logging see http://prosody.im/doc/logging
 +log = {
 + info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
 + error = "/var/log/prosody/prosody.err";
 + "*syslog";
 +}
 +
 +----------- Virtual hosts -----------
 +-- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
 +-- Settings under each VirtualHost entry apply *only* to that host.
 +
 +VirtualHost "localhost"
 +
 +VirtualHost "wombat.org.ua"
 + -- enabled = false -- Remove this line to enable this host
 +
 + -- Assign this host a certificate for TLS, otherwise it would use the one
 + -- set in the global section (if any).
 + -- Note that old-style SSL on port 5223 only supports one certificate, and will always
 + -- use the global one.
 + ssl = {
 + key = "/etc/prosody/certs/wombat.org.ua.key";
 + certificate = "/etc/prosody/certs/wombat.org.ua.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.wombat.org.ua" "muc"
 +
 +-- Set up a SOCKS5 bytestream proxy for server-proxied file transfers:
 +--Component "proxy.example.com" "proxy65"
 +
 +---Set up an external component (default component port is 5347)
 +--
 +-- External components allow adding various services, such as gateways/
 +-- transports to other networks like ICQ, MSN and Yahoo. For more info
 +-- see: http://prosody.im/doc/components#adding_an_external_component
 +--
 +--Component "gateway.example.com"
 +-- component_secret = "password"
 +</file>
 +
 +==== Модули ====
 +
 +Чтобы включить использование какого-либо дополнительного модуля Prosody, нужно в файле конфигурации указать его:
 +
 +<code>
 +modules_enabled = {
 +    "announce";
 +    "motd";
 +    "carbons";
 +};
 +</code>
 +
 +
 +=== Встроенные ===
 +
 +== announce ==
 +
 +Модуль "announce" позволяет отправлять сообщение всем подключённым пользователям от имени администратора сервера. Для этого администратор должен отправить сообщение по адресу ''host/announce/online''.
 +
 +Например, 
 +
 +  wombat.org.ua/announce/online
 +
 +==  motd ==
 +
 +Модуль "motd" (от "**M**essage **O**f **T**he **D**ay") позволяет автоматически отсылать сообщение сервера пользователю, когда тот входит в сеть.
 +
 +Для того, чтобы такое сообщение отправлялось, нужно **ДО** секций "VirtualHost" вставить следующий параметр:
 +
 +<code>
 +    -- Использование [[ .. ]] вместо " .. "
 +    -- позволяет вставлять несколько строк текста
 +    motd_text = [[Добро пожаловть на сервер!
 +    Покупайте наших слонов!]]
 +</code>
 +
 +=== Сторонние ===
 +
 +Сущствует много сторонних модулей для Prosody. Посмотреть список можно по адресу: http://modules.prosody.im
 +
 +Чтобы [[https://prosody.im/doc/installing_modules#prosody-modules | установить]] какой-либо из них, нужно скачать архив с модулями, распаковать его, а затем скопировать нужный модуль в каталог ''/usr/lib/prosody/modules/''.
 +
 +В официальной документации предлагается для скачивания папки с модулями воспользоваться командой
 +
 +  hg clone https://hg.prosody.im/prosody-modules/ prosody-modules
 +
 +но если у вас не установлен клиент Mercurial (команда ''hg'') и вам неохота его устанавливать, то папку можно скачать архивом, зайдя на сайт https://hg.prosody.im/prosody-modules , нажав на ссылку ''files'', а затем на ссылку ''gz''.
 +
 +Например, для модуля ''carbons'' эта последовательность действий может выглядеть так:
 +
 +  wget https://hg.prosody.im/prosody-modules/archive/40056a27f394.tar.gz
 +  tar -xvf 40056a27f394.tar.gz
 +  sudo cp prosody-modules-40056a27f394/mod_carbons/mod_carbons.lua /usr/lib/prosody/modules/
 +
 +  
 +===== Jabber-сервер на 443 порту =====
 +
 +Для того, чтобы принимать соединения в порт 443, не нарушая при этом работы других сервисов (например, HTTPS), можно воспользоваться утилитой ''sslh''. При этом в командной строке параметр ''--xmpp 127.0.0.1 5222'' должен быть расположен после параметр ''--ssh'', но **перед** параметром ''--ssl''. То есть
 +
 +  /usr/sbin/sslh-select -n --user sslh --listen <EXTERNAL_IP> 443 --ssh 127.0.0.1 22 --xmpp 127.0.0.1 5222 --ssl 127.0.0.1 443 --pidfile /var/run/sslh/sslh.pid
 +
 +====== Подключение к серверам Google ======
 +
 +Если пользователю не удаётся добавить в список контактов пользователей сервисов Google (GTalk, Gmail, ...), а Jabber-сервер выдаёт в логи следующие сообщения:
 +
 +  Oct 21 22:57:16 s2sout95897f8   info    Beginning new connection attempt to gmail.com ([173.194.70.125]:5269) 
 +  Oct 21 22:57:16 s2sout95897f8   info    sent dialback key on outgoing s2s stream 
 +  Oct 21 22:57:16 s2sout95897f8   info    Session closed by remote with error: undefined-condition (wombat.org.ua is a Google Apps Domain with Talk service enabled.) 
 +  Oct 21 22:57:16 s2sout95897f8   info    outgoing s2s stream wombat.org.ua->gmail.com closed: undefined-condition (wombat.org.ua is a Google Apps Domain with Talk service enabled.) 
 +  Oct 21 22:57:16 s2sout95897f8   info    sending error replies for 2 queued stanzas because of failed outgoing connection to gmail.com
 +
 +где "wombat.org.ua" - это домен, на котором мы запустили наш Jabber-сервер, вероятнее всего, это означает, что данный домен зарегистрирован в системе Google Apps, и для него активирована служба Googlt Talk. Чтобы всё заработало, её нужно деактивировать. При наличии учётной записи Google сделать это можно, следуя инструкциям на соответствующем сайте. Если учётной записи, к которой приписан данный домен, не существует в Google (например, она была удалена пользователем), то единственным способом исправить ситуацию оказалось обращение в службу техподдержки Google из какой-либо другой учётной записи (например, вновь созданной или просто записи друга). При этом нужно описать ситуацию в деталях, чтобы не заподозрели, что вы пытаетесь присвоить себе управление чужим доменом. Впрочем, служба техподдержки всё равно запрашивает подтверждение владения доменом, например, при помощи добавления указанной ими DNS-записи.
 +
 +Следует отметить, что с поддоменами главного домена такой проблемы нет. Т.е. если у нас имеется поддомен "pechka.wombat.org.ua", то пользователи нашего Jabber-сервера на этом поддомене смогут без проблем связываться с пользователями Jabber-серверов Google. Впрочем, возможно, это справедливо только для поддоменов, не зарегистрированных в вышеупомянутом сервисе Google Apps.
 +
 +http://stackoverflow.com/questions/3866299/xmpp-ejabberd-server-is-not-able-to-connect-gtalk-server
 +
 +http://lists.jabber.ru/pipermail/ejabberd/2009-January/004605.html
 +
 +https://code.google.com/p/jabber-net/wiki/FAQ_GoogleTalk
 +
 +http://productforums.google.com/forum/#!topic/mobile/9Sqpc2Ra43I
 +
 +http://serverfault.com/questions/475005/need-help-understanding-why-gtalk-will-not-talk-to-my-xmpp-server-if-it-serves-r