Conversations не коннектится к OpenFire на кириллический домен

0 0
Conversations не коннектится к OpenFire на кириллический домен.
Думаю, начнёт ли, если я пропатчу OpenFire?

Суть такова:
Conversations самовольно преобразует punicode-запись в кириллицу.
затем по всей видимости кириллицу и отсылает. А OpenFire преобразовывает обратно в punicode,
и потом эти строки не совпадают при возврате в Conversations.

Если я в OpenFire сделаю возврат в том виде, в каком присылали (при сохранении семантики проверок),
то по идее должно заработать, не так ли?

0 1
План работ примерно такой:

1) установить эмулятор Android
2) настроить сборку (то ли внутри эмулятора, то ли снаружи кросс-компиляцией)
3) научиться устанавливать в эмуляторе
4) запустить
5) попробовать сконнектиться и убедиться, что ошибка воспроизводится
(по HEAD и по версии, скачиваемой из Store, если внезапно HEAD окажется работающим)
6) выяснить, что именно и как проверяется в клиенте Conversations
7) подумать, можно ли этому удовлетворить, меняя только сервер, и не меняя клиента


0 2
Алиса:
Поле SAN типа dNSName по RFC 5280 имеет формат IA5String, то есть хранит только ASCII-символы. U-label (запись домена в юникоде, например пример.рф) туда физически не влезает — это не ограничение Let's Encrypt, а ограничение самого формата сертификата. IDN-домены всегда записываются в A-label, то есть в punycode с префиксом xn-- (например, пример.рф → xn--e1afmkfd.xn--p1ai). Let's Encrypt и протокол ACME принимают IDN только в таком виде.
Это значит, что невозможно сделать сертификат, в котором будет написано имя домена как в punicode, так и в Unicode.



0 3
Алиса:
Это верно для старого RFC 6120 (2011), но более новый RFC 7622 (2015) прямо говорит другое: доменная часть JID должна состоять из U-label (юникод), а A-labels должны быть конвертированы в U-label перед отправкой.
Ну вот теперь ещё стандарты надо сверять с бредом Алисы...

RFC 7622: Extensible Messaging and Presence Protocol (XMPP): Address Format
    This RFC was updated, see RFC 9844. (это про ipv6, не к месту)
Алиса:
«Not responsible for domain» — это не сетевая ошибка клиента.  Так Conversations переводит ситуацию, когда соединение установлено, TLS пройден, клиент открыл XMPP-поток

```bash
2026-11-24T08:09:43.013985306Z - C2S-STARTTLS /172.31.4.1:34860 - RECV - (rawDebugger): <?xml version='1.0'?><stream:stream xmlns="jabber:client" to="опенсорс.рус" version="1.0" xml:lang="en" xmlns:stream="http://etherx.jabber.org/streams">
2026-11-24T08:09:43.020107261Z - C2S-STARTTLS /172.31.4.1:34860 - SENT - (rawDebugger): <?xml version="1.0" encoding="UTF-8"?><stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" from="xn--e1aqbccjfc.xn--p1acf" id="293f2ketow" xml:lang="en" version="1.0"><stream:features><starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/><limits xmlns="urn:xmpp:stream-limits:0"><max-bytes>1048576</max-bytes><idle-seconds>360</idle-seconds></limits><compression xmlns="http://jabber.org/features/compress"><method>zlib</method></compression><ver xmlns="urn:xmpp:features:rosterver"/><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>SCRAM-SHA-512</mechanism><mechanism>PLAIN</mechanism><mechanism>SCRAM-SHA-1</mechanism><mechanism>SCRAM-SHA-256</mechanism></mechanisms><register xmlns="http://jabber.org/features/iq-register"/><c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="https://www.igniterealtime.org/projects/openfire/" ver="EkCX3P5jPLO5vmH++kU2s3dXp0o="/><limits xmlns="urn:xmpp:stream-limits:0"><max-bytes>1048576</max-bytes><idle-seconds>360</idle-seconds></limits></stream:features>
2026-11-24T08:09:43.030362359Z - C2S-STARTTLS /172.31.4.1:34860 - CLSD - (rawDebugger)
```

to="опенсорс.рус"
from="xn--e1aqbccjfc.xn--p1acf"
не совпадают, что и требовалось показать

Нельзя в Conversations задать имя пользователя (JID): `юзер@xn--e1aqbccjfc.xn--p1acf` (строго A-label).
Заставить Conversations отправить A-label в JID невозможно — клиент принудительно нормализует его в U-label (Unicode) на уровне интерфейса и логики.

0 4
https://www.rfc-editor.org/info/rfc7622/#section-5
5.  Internationalization Considerations

   XMPP applications MUST support IDNA2008 for domainparts as described
   under Section 3.2, the UsernameCaseMapped profile for localparts as
   described under Section 3.3, and the OpaqueString profile for
   resourceparts as described under Section 3.4.  This enables XMPP
   addresses to include a wide variety of characters outside the ASCII
   range.  Rules for enforcement of the XMPP address format are provided
   in [RFC6120] and specifications for various XMPP extensions.

      Interoperability Note: For backward compatibility, many existing
      XMPP implementations and deployments support IDNA2003 [RFC3490]
      for domainparts, and the stringprep [RFC3454] profiles Nodeprep
      and Resourceprep [RFC3920] for localparts and resourceparts.

0 5
...

3.2.1.  Preparation

   An entity that prepares a string for inclusion in an XMPP domainpart
   slot MUST ensure that the string consists only of Unicode code points
   that are allowed in NR-LDH labels or U-labels as defined in
   [RFC5890].  This implies that the string MUST NOT include A-labels as
   defined in [RFC5890]; each A-label MUST be converted to a U-label
   during preparation of a string for inclusion in a domainpart slot.
   In addition, the string MUST be encoded as UTF-8 [RFC3629].

...

Звучит так, будто бы Unicode-символы передавать можно. Но это же только про подготовку? Или про отправку тоже?


Правильно ли, что оба правы - и Conversations и OpenFire? Conversation имел право передавать Unicode, OpenFire имел право возвращать punicode, Проблема на стороне Conversation (нарушает RFC), но патчить мы его не можем, потому что он в сторе. Патчить можем только OpenFire, потому что админим сервер.


0 6
Я попробовал установить xmpp.domain в U-строку (оставив при этом сертификат с A-строкой),
OpenFire выдал предупреждение, что сертификат перестал совпадать.
Conversations начал коннектиться (но не регистрироваться - где-то дальше что-то не срабатывает)
к конференции существующей подключиться не удалось, видимо создалась отдельная, не знаю точно, что с ней не так.

У меня есть возможнось смотреть (грепать) код в директориях ~/Java/Conversations/iNPUTmice/ и ~/Java/openfire/igniterealtime Нужно разобраться, как сделать так, чтобы OpenFire запоминал в сессии как запросил домен клиент (в U-строке или в A-строке), и отдавал свой домен так же. А хранил у себя в A-строке (в xmpp.domain)

# 1. Правите код в ~/Java/Conversations/iNPUTmice
# 2. Пересобираете
./gradlew assembleConversationsFreeDebug
# 3. Переустанавливаете (подпись та же — удаление не нужно)
waydroid app install build/outputs/apk/conversationsFree/debug/eu.siacs.conversations-2.21.4+free-x86_64.apk
# 4. Запускаете
waydroid app launch eu.siacs.conversations
# 5. Смотрите логи
adb logcat | grep -iE "AndroidRuntime|siacs"

0 7
~/Java/openfire/igniterealtime$ grep -B 13 -A 21 -n "protected void refuseStream" ./xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java
945-    /**
946-     * Responds to a stream header that cannot be accepted by opening a stream that carries the provided stream error,
947-     * and then closes the underlying connection.
948-     *
949-     * The stream is opened from the host that the peer addressed, unless that host is missing or is not serviced (as
950-     * determined by {@link #isHostUnknown(String)}), whatever the reason for the refusal: then it is opened from the XMPP
951-     * domain of the local XMPP service. In that case, RFC 6120 section 4.9.1.3 allows either an authoritative name for
952-     * the receiving entity or the empty string; the XMPP domain is such an authoritative name.
953-     *
954-     * @param xpp a parser positioned on the stream header that is refused.
955-     * @param host the value of the 'to' attribute of the refused stream header (can be null).
956-     * @param error the stream error to send to the peer.
957-     */
958:    protected void refuseStream(XmlPullParser xpp, String host, StreamError error) {
959-        final String from = host == null || isHostUnknown(host)
960-            ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
961-            : host;
962-        final Element stream = DocumentHelper.createElement(QName.get("stream", "stream", "http://etherx.jabber.org/streams"));
963-        final Document document = DocumentHelper.createDocument(stream);
964-        document.setXMLEncoding(StandardCharsets.UTF_8.toString());
965-        // The refused header need not declare a content namespace. When it does not, the error is answered in the
966-        // namespace of this handler, rather than copying the absent namespace (which would fail to build the error).
967-        final String contentNamespace = xpp.getNamespace(null);
968-        stream.add(Namespace.get(contentNamespace != null ? contentNamespace : getNamespace().getURI()));
969-        stream.addAttribute("from", from);
970-        stream.addAttribute("id", STREAM_ID_FACTORY.createStreamID().getID());
971-        stream.addAttribute("version", "1.0");
972-        stream.add(error.getElement());
973-
974-        // Deliver stanza
975-        connection.deliverRawText(StringUtils.asUnclosedStream(document));
976-
977-        // Close the underlying connection
978-        connection.close();
979-    }
~/Java/openfire/igniterealtime$

В этом куске кода from устанавливается из конфига, если host неизвестен (null, или чужой).
А если известен, то оставляется какой был. И, наверное, это хорошо. Хорошо, если бы так же было и в других местах.

Другие места, это:

LocalClientSession.createSession
(создание сессии)
cd ~/Java/openfire/igniterealtime
grep -n -B 11 -A 108  "public static LocalClientSession createSession" ./xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java

StanzaHandler.getStreamHeader
(последующие сообщения внутри начатой сессии)
cd ~/Java/openfire/igniterealtime
grep -n -B 0 -A 12  "protected Document getStreamHeader" ./xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java

добавил:

$ git diff ./xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java b/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
index 1e56967f1..618fe503f 100644
--- a/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
+++ b/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
@@ -200,6 +200,8 @@ public class LocalClientSession extends LocalSession implements ClientSession {
     public static LocalClientSession createSession(String serverName, XmlPullParser xpp, Connection connection)
             throws XmlPullParserException
     {
+        Log.debug("LocalClientSession.java(200): createSession(serverName='{}', xpp, connection)", serverName);
+
         // Conduct error checking, the opening tag should be 'stream' in the 'etherx' namespace
         if (!xpp.getName().equals("stream")) {
             throw new XmlPullParserException(LocaleUtils.getLocalizedString("admin.error.bad-stream"));

и пишет он:

# grep -i "(200)" logs/openfire.log | tail -n 5
2026.11.25 03:39:14.781 DEBUG [socket_c2s-handler-4]: org.jivesoftware.openfire.session.LocalClientSession - LocalClientSession.java(200): createSession(serverName='xn--e1aqbccjfc.xn--p1acf', xpp, connection)
2026.11.25 03:40:04.918 DEBUG [socket_c2s-handler-5]: org.jivesoftware.openfire.session.LocalClientSession - LocalClientSession.java(200): createSession(serverName='xn--e1aqbccjfc.xn--p1acf', xpp, connection)
2026.11.25 03:40:48.430 DEBUG [socket_c2s-handler-6]: org.jivesoftware.openfire.session.LocalClientSession - LocalClientSession.java(200): createSession(serverName='xn--e1aqbccjfc.xn--p1acf', xpp, connection)
2026.11.25 03:41:06.185 DEBUG [socket_c2s-handler-7]: org.jivesoftware.openfire.session.LocalClientSession - LocalClientSession.java(200): createSession(serverName='xn--e1aqbccjfc.xn--p1acf', xpp, connection)
2026.11.25 03:42:24.809 DEBUG [socket_c2s-handler-8]: org.jivesoftware.openfire.session.LocalClientSession - LocalClientSession.java(200): createSession(serverName='xn--e1aqbccjfc.xn--p1acf', xpp, connection)

а берётся эта строка из конфига:

$ grep -n "final String serverName" ./xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java -B 17
888-    /**
889-     * Uses the XPP to grab the opening stream tag and create an active session
890-     * object. The session to create will depend on the sent namespace. In all
891-     * cases, the method obtains the opening stream tag, checks for errors, and
892-     * either creates a session or returns an error and kills the connection.
893-     * If the connection remains open, the XPP will be set to be ready for the
894-     * first packet. A call to next() should result in an START_TAG state with
895-     * the first packet in the stream.
896-     * @param xpp the pull parser
897-     * @throws XmlPullParserException if an exception occurs reading from the pull parser
898-     * @throws IOException if an IO exception occurs reading from the pull parser
899-     */
900-    protected void createSession(XmlPullParser xpp) throws XmlPullParserException, IOException {
901-        for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) {
902-            eventType = xpp.next();
903-        }
904-
905:        final String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();

Сервер объявляет свой домен в ответном stream header как A-label, потому что берёт его из конфига. Conversations (по RFC 7622) ждёт в from тот же U-label, что сам отправил в to, — и отвергает соединение.



0 8
Правильные точки патча - методы, которые строят ответный stream header

  • LocalClientSession.createSession:264 — первая точка, первый ответный stream header.
    Строится сразу после получения входящего header'а, до TLS/SASL.
    Именно в нём сервер объявляет
    <starttls/> в features.

  • StanzaHandler.getStreamHeader:869 — вторая точка, где клиенту отправляется stream header с A-label'ом.
    Она срабатывает при  
     — при всех рестартах стрима (после TLS, после SASL и т.д.).

    Патчить нужно
    обе.

    ~/Java/openfire/igniterealtime$ git diff ./xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java b/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
    index 1e56967f1..a31a9bc78 100644
    @@ -259,7 +261,18 @@ public class LocalClientSession extends LocalSession implements ClientSession {
             final Document document = DocumentHelper.createDocument(stream);
             document.setXMLEncoding(StandardCharsets.UTF_8.toString());
             stream.add(Namespace.get("jabber:client"));
    -        stream.addAttribute("from", serverName);
    +        String fromDomain = serverName;
    +        String toHost = xpp.getAttributeValue("", "to");
    +        if (toHost != null) {
    +            try {
    +                if (JID.domainprep(toHost).equalsIgnoreCase(serverName)) {
    +                    fromDomain = toHost;
    +                }
    +            } catch (IllegalArgumentException e) {
    +                // невалидный 'to' — оставляем serverName
    +            }
    +        }
    +        stream.addAttribute("from", fromDomain);
             stream.addAttribute("id", session.getStreamID().toString());
             stream.addAttribute(QName.get("lang", Namespace.XML_NAMESPACE), language.toLanguageTag());
             // Don't include version info if the version is 0.0.
    ~/Java/openfire/igniterealtime$

    на момент чтения to (строка ~265 после патча) xpp всё ещё стоит на START_TAG элемента stream,
    и вернёт корректное значение. 
    getAttributeValue() не двигает парсер, это чистый read-аксессор.

    ~/Java/openfire/igniterealtime$ git diff ./xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java b/xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java
    index 3332288b9..1bd638a4b 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/net/StanzaHandler.java
    @@ -82,6 +82,13 @@ public abstract class StanzaHandler {
         // DANIELE: Indicate if a session is already created
         protected boolean sessionCreated = false;
     
    +    /**
    +     * Hostname as it was sent from the client.
    +     *
    +     * It can be unicode string or punycode.
    +     */
    +    protected String streamHeaderTo;
    +
         /**
          * Flag that indicates that the client requested to use TLS and TLS has been negotiated. Once the
          * client sent a new initial stream header the value will return to false.
    @@ -202,6 +209,7 @@ public abstract class StanzaHandler {
                 final MXParser parser = reader.getXPPParser();
                 parser.setInput(new StringReader(stanza));
                 recordClaimedIdentity(parser);
    +            this.streamHeaderTo = parser.getAttributeValue("", "to"); // should be after recordClaimedIdentity
     
                 if (startedTLS) {
                     tlsNegotiated(parser);
    @@ -670,6 +678,7 @@ public abstract class StanzaHandler {
          * for in-band registration.
          */
         protected void tlsNegotiated(XmlPullParser xpp) throws XmlPullParserException, IOException {
    +        this.streamHeaderTo = xpp.getAttributeValue("", "to"); // should be before getStreamHeader()
             final Document document = getStreamHeader();
     
             // Offer stream features including SASL Mechanisms
    @@ -866,7 +875,17 @@ public abstract class StanzaHandler {
             final Document document = DocumentHelper.createDocument(stream);
             document.setXMLEncoding(StandardCharsets.UTF_8.toString());
             stream.add(getNamespace());
    -        stream.addAttribute("from", XMPPServer.getInstance().getServerInfo().getXMPPDomain());
    +        String fromDomain = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
    +        if (streamHeaderTo != null) {
    +            try {
    +                if (JID.domainprep(streamHeaderTo).equalsIgnoreCase(fromDomain)) {
    +                    fromDomain = streamHeaderTo;
    +                }
    +            } catch (IllegalArgumentException e) {
    +                // невалидный 'to' — оставляем конфиг
    +            }
    +        }
    +        stream.addAttribute("from", fromDomain);
             stream.addAttribute("id", session.getStreamID().getID());
             stream.addAttribute(QName.get("lang", Namespace.XML_NAMESPACE), session.getLanguage().toLanguageTag());
             stream.addAttribute("version", Session.MAJOR_VERSION + "." + Session.MINOR_VERSION);
    @@ -904,6 +923,7 @@ public abstract class StanzaHandler {
     
             final String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
             String host = xpp.getAttributeValue("", "to");
    +        this.streamHeaderTo = host;
     
             try {
                 // Check that the TO attribute of the stream header names a host that is serviced, as
    ~/Java/openfire/igniterealtime$ 


    0 9
    На этом сказка не заканчивается! Новое сообщение об ошибке: „Bind failure”.

    DeepSeek:
    look at the authorization-identifier: user@xn--e1aqbccjfc.xn--p1acf/Conversations/92ab0f98022e7d28. It's in A-label (punycode)! The client sent its to in U-label (cyrillic), but the SASL2 success response contains the JID in A-label form.

    Здесь два A-label JID'а на проводе:

    1. authorization-identifier — полный JID пользователя;
    2. bound/@location — домен для stream resumption.

    клиент успел послать disco#info (16.747) и получить ответ — то есть SASL2+bind2 его в целом устроили, кроме JID в A-label.

    Клиенту отдаётся JID с доменом в трёх местах:
    SASLAuthentication.java:960 (authorizationIdentity → <authorization-identifier> в SASL2 success)
    SASLAuthentication.java:1102 (bareJid → тот же <authorization-identifier> в SASL2+Bind2)
    IQBindHandler.java:sendBindSuccess (<jid> в ответе на bind (берётся из session.getAddress()))
    ...
    нужно только при формировании ответа клиенту подставлять U-label (или, как сам клиент отправлял)

    ~/Java/openfire/igniterealtime$ git diff
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQBindHandler.java b/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQBindHandler.java
    index 4f2da3084..027750fbb 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQBindHandler.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/handler/IQBindHandler.java
    @@ -139,7 +139,11 @@ public class IQBindHandler extends IQHandler {
             final IQ reply = IQ.createResultIQ(request);
             reply.setFrom((String) null); // OF-2001
             final Element child = reply.setChildElement("bind", "urn:ietf:params:xml:ns:xmpp-bind");
    -        child.addElement("jid").setText(session.getAddress().toString());
    +        final Object _cpdBindJid = session.getSessionData("client-provided-domain");
    +        final String _bindDomain = _cpdBindJid instanceof String ? (String) _cpdBindJid : session.getAddress().getDomain();
    +        final String _displayJid = session.getAddress().getNode() + "@" + _bindDomain
    +            + (session.getAddress().getResource() != null ? "/" + session.getAddress().getResource() : "");
    +        child.addElement("jid").setText(_displayJid);
     
             // Send the response directly since a route does not exist at this point.
             session.process(reply);
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/net/SASLAuthentication.java b/xmppserver/src/main/java/org/jivesoftware/openfire/net/SASLAuthentication.java
    index 88a2d05c1..b36fae188 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/net/SASLAuthentication.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/net/SASLAuthentication.java
    @@ -957,7 +957,10 @@ public class SASLAuthentication {
                     clientAuthToken = AuthToken.generateUserToken(username);
                     node = clientAuthToken.getUsername(); // Normalized: strips any domain-part from the authzid.
                 }
    -            authorizationIdentity = new JID(node, XMPPServer.getInstance().getServerInfo().getXMPPDomain(), null, true).toString();
    +            final Object _cpdAuthzId = session.getSessionData("client-provided-domain");
    +            final String _authzDomain = _cpdAuthzId instanceof String ? (String) _cpdAuthzId
    +                : XMPPServer.getInstance().getServerInfo().getXMPPDomain();
    +            authorizationIdentity = new JID(node, _authzDomain, null, true).toString();
                 // Do not retain an authentication token until all synchronous SASL2 success work,
                 // including requested FAST token persistence, has completed successfully.
                 if (!usingSASL2) {
    @@ -1099,7 +1102,10 @@ public class SASLAuthentication {
                         Log.debug("Bind2 request for anonymous user '{}' processed successfully.", username);
                     } else {
                         // A non-anonymous session performs regular resource binding.
    -                    final String bareJid = new JID(clientAuthToken.getUsername(), XMPPServer.getInstance().getServerInfo().getXMPPDomain(), null, true).toString();
    +                    final Object _cpdBareJid = session.getSessionData("client-provided-domain");
    +                    final String _bareJidDomain = _cpdBareJid instanceof String ? (String) _cpdBareJid
    +                        : XMPPServer.getInstance().getServerInfo().getXMPPDomain();
    +                    final String bareJid = new JID(clientAuthToken.getUsername(), _bareJidDomain, null, true).toString();
                         SessionManager.getInstance().bindResource(clientSession, clientAuthToken, resource)
                             .whenComplete((result, throwable) -> {
                                 if (throwable != null) {
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java b/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
    index a6c0a98b4..dd22648e2 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/session/LocalClientSession.java
    @@ -271,6 +271,10 @@ public class LocalClientSession extends LocalSession implements ClientSession {
                 }
             }
             stream.addAttribute("from", fromDomain);
    +        // Echo back the domain the client used in its stream header (may be U-label).
    +        // Conversations enforces RFC 7622 §3.2.1 (U-label), so substituting the
    +        // server-configured A-label here causes "Bind Failure" in the client.
    +        session.setSessionData("client-provided-domain", fromDomain);
             stream.addAttribute("id", session.getStreamID().toString());
             stream.addAttribute(QName.get("lang", Namespace.XML_NAMESPACE), language.toLanguageTag());
             // Don't include version info if the version is 0.0.
    ~/Java/openfire/igniterealtime$

    Теперь клиент коннектится, но...


    0 10
    Клиент не может зайти в комнату (группой чат). Угадайте почему? Потому что имя комнаты содержит кусок с доменом!

    Правки нужны в
    двух местах:
    нормализация в
    routePacket (с алиасами) и
    нормализация при lookup компонента.

    ~/Java/openfire/igniterealtime$ git diff
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java b/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java
    index 97d447f34..df7925fb3 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java
    @@ -34,6 +34,7 @@ import org.jivesoftware.openfire.server.OutgoingSessionPromise;
     import org.jivesoftware.openfire.server.RemoteServerManager;
     import org.jivesoftware.openfire.session.*;
     import org.jivesoftware.util.JiveGlobals;
    +import org.jivesoftware.util.StringUtils;
     import org.jivesoftware.util.LocaleUtils;
     import org.jivesoftware.util.TaskEngine;
     import org.jivesoftware.util.cache.*;
    @@ -115,6 +116,35 @@ public class RoutingTableImpl extends BasicModule implements RoutingTable, Clust
          */
         private final Cache<String, HashSet<NodeID>> componentsCache;
     
    +    /**
    +     * Normalizes a domain name to its canonical A-label (Punycode) form.
    +     * Returns the input unchanged when it cannot be normalized (e.g., contains invalid characters).
    +     * Makes comparisons robust against mixed U-label / A-label representations of the same IDN.
    +     */
    +    private static String normalizeDomain(@Nonnull final String domain) {
    +        try {
    +            return StringUtils.validateDomainName(domain);
    +        } catch (final IllegalArgumentException e) {
    +            return domain;
    +        }
    +    }
    +
    +    /**
    +     * Returns all domains this server is locally responsible for: the primary XMPP domain
    +     * plus every entry from {@code xmpp.domainAliases}, normalized to A-label form.
    +     */
    +    private Set<String> getLocalDomainsNormalized() {
    +        final Set<String> result = new LinkedHashSet<>();
    +        result.add(normalizeDomain(serverName));
    +        for (final String alias : JiveGlobals.getListProperty("xmpp.domainAliases", Collections.emptyList())) {
    +            if (alias != null && !alias.isBlank()) {
    +                result.add(normalizeDomain(alias));
    +            }
    +        }
    +        return result;
    +    }
    +
    +
         /**
          * A map that, for all nodes in the cluster except for the local one, tracks if a component connection has
          * been established.
    @@ -306,13 +336,33 @@ public class RoutingTableImpl extends BasicModule implements RoutingTable, Clust
         public void routePacket(JID jid, Packet packet) throws PacketException {
             boolean routed = false;
             try {
    -            if (serverName.equals(jid.getDomain())) {
    +            // Normalize the IDN representation (U-label vs A-label) and consider xmpp.domainAliases,
    +            // so that packets addressed to a locally served domain or component are not mistakenly
    +            // routed to a remote server.
    +            final String domain = normalizeDomain(jid.getDomain());
    +            final Set<String> localDomains = getLocalDomainsNormalized();
    +
    +            boolean isLocalComponent = false;
    +            for (final String localDomain : localDomains) {
    +                if (domain.endsWith("." + localDomain)) {
    +                    isLocalComponent = true;
    +                    break;
    +                }
    +            }
    +
    +            // Use the normalized JID for lookups so that components registered under one IDN form
    +            // are found when the client addresses them via the other (U-label vs A-label).
    +            final JID lookupJid = domain.equals(jid.getDomain())
    +                ? jid
    +                : new JID(jid.getNode(), domain, jid.getResource(), true);
    +
    +            if (localDomains.contains(domain)) {
                     // Packet sent to our domain.
    -                routed = routeToLocalDomain(jid, packet);
    +                routed = routeToLocalDomain(lookupJid, packet);
                 }
    -            else if (jid.getDomain().endsWith(serverName) && hasComponentRoute(jid)) {
    +            else if (isLocalComponent && hasComponentRoute(lookupJid)) {
                     // Packet sent to component hosted in this server
    -                routed = routeToComponent(jid, packet);
    +                routed = routeToComponent(lookupJid, packet);
                 }
                 else {
                     // Packet sent to remote server
    @@ -919,7 +969,13 @@ public class RoutingTableImpl extends BasicModule implements RoutingTable, Clust
     
         @Override
         public boolean hasComponentRoute(JID jid) {
    -        return componentsCache.containsKey(jid.getDomain());
    +        if (componentsCache.containsKey(jid.getDomain())) {
    +            return true;
    +        }
    +        // Fall back to the normalized (A-label) representation so that a component registered
    +        // under either IDN form is found via the other (U-label vs A-label mismatch).
    +        final String normalized = normalizeDomain(jid.getDomain());
    +        return !normalized.equals(jid.getDomain()) && componentsCache.containsKey(normalized);
         }
     
         @Override
    ~/Java/openfire/igniterealtime$


    0 11
    Страшно. Очень страшно. Если бы мы понимали, что там написано... Но мы не понимаем.

    ~/Java/openfire/igniterealtime$ export GIT_PAGER=cat
    git diff
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCOccupant.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCOccupant.java
    index 51d6aec85..73353911c 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCOccupant.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCOccupant.java
    @@ -147,7 +147,7 @@ public class MUCOccupant implements Cacheable, Externalizable {
             this.userJid = userJid;
             this.role = role;
             this.affiliation = affiliation;
    -        occupantJID = new JID(roomJid.getNode(), roomJid.getDomain(), nick);
    +        occupantJID = new JID(roomJid.getNode(), roomJid.getDomain(), nick, true);
             this.occupantId = chatroom.generateOccupantId(userJid);
     
             synchronized (this) {
    @@ -185,7 +185,7 @@ public class MUCOccupant implements Cacheable, Externalizable {
             this.role = Role.moderator;
             this.affiliation = Affiliation.owner;
     
    -        occupantJID = new JID(roomJid.getNode(), roomJid.getDomain(), null);
    +        occupantJID = new JID(roomJid.getNode(), roomJid.getDomain(), null, true);
             this.occupantId = room.generateOccupantId(occupantJID);
         }
     
    @@ -317,7 +317,7 @@ public class MUCOccupant implements Cacheable, Externalizable {
          */
         public void changeNickname(String nickname) {
             this.nick = nickname;
    -        setRoleAddress(new JID(roomJid.getNode(), roomJid.getDomain(), nick));
    +        setRoleAddress(new JID(roomJid.getNode(), roomJid.getDomain(), nick, true));
             synchronized (this) {
                 cacheSize = -1;
             }
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
    index b56989048..19390e4dd 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/muc/MUCRoom.java
    @@ -422,7 +422,11 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
          * @return the JID for this room.
          */
         public JID getJID() {
    -        return new JID(getName(), getMUCService().getServiceDomain(), null);
    +        // Preserve the representation of xmpp.domain (U-label vs A-label).
    +        // Clients following RFC 7622 §3.2.1 expect U-label responses when they used a U-label
    +        // room address. Forcing domainprep here caused the room to emit A-label `from`
    +        // attributes, which strict clients (Conversations, Dino) silently drop.
    +        return new JID(getName(), getMUCService().getServiceDomain(), null, true);
         }
     
         /**
    @@ -1338,7 +1342,7 @@ public class MUCRoom implements GroupEventListener, UserEventListener, Externali
                         // Sets the sender of the retraction message to be the chat room itself
                         retractionMsg.setFrom(selfOccupantData.getOccupantJID());
                         // Sets the recipient of the retraction message to be the chat room itself to send to all occupants
    -                    retractionMsg.setTo(new JID(getName(), getMUCService().getServiceDomain(), null).toBareJID());
    +                    retractionMsg.setTo(new JID(getName(), getMUCService().getServiceDomain(), null, true).toBareJID());
                         retractionMsg.setType(Message.Type.groupchat);
                         // An XML element is added to the message to indicate that it is a retraction, with an attribute specifying
                         // the ID of the message being retracted
    diff --git a/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java b/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java
    index df7925fb3..dbfebe435 100644
    --- a/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java
    +++ b/xmppserver/src/main/java/org/jivesoftware/openfire/spi/RoutingTableImpl.java
    @@ -350,19 +350,18 @@ public class RoutingTableImpl extends BasicModule implements RoutingTable, Clust
                     }
                 }
     
    -            // Use the normalized JID for lookups so that components registered under one IDN form
    -            // are found when the client addresses them via the other (U-label vs A-label).
    -            final JID lookupJid = domain.equals(jid.getDomain())
    -                ? jid
    -                : new JID(jid.getNode(), domain, jid.getResource(), true);
    -
                 if (localDomains.contains(domain)) {
                     // Packet sent to our domain.
    -                routed = routeToLocalDomain(lookupJid, packet);
    +                routed = routeToLocalDomain(jid, packet);
                 }
    -            else if (isLocalComponent && hasComponentRoute(lookupJid)) {
    -                // Packet sent to component hosted in this server
    -                routed = routeToComponent(lookupJid, packet);
    +            else if (isLocalComponent && hasComponentRoute(jid)) {
    +                // Packet sent to component hosted in this server. IMPORTANT: pass the ORIGINAL jid,
    +                // not the normalized one. The component will produce responses using IQ.createResultIQ,
    +                // which mirrors request.getTo() into response.getFrom(). Rewriting the 'to' here would
    +                // cause the component to answer with a different IDN representation than the client
    +                // used, and strict clients (Conversations, Dino) silently drop such responses -- the
    +                // client then never reaches the 'join' step.
    +                routed = routeToComponent(jid, packet);
                 }
                 else {
                     // Packet sent to remote server
    @@ -539,9 +538,17 @@ public class RoutingTableImpl extends BasicModule implements RoutingTable, Clust
                 return false;
             }
             
    -        // First check if the component is being hosted in this JVM
    +        // First check if the component is being hosted in this JVM.
    +        // Try the JID's original domain first; if no route is found (component registered under
    +        // the other IDN representation), retry with the normalized A-label form.
             boolean routed = false;
             RoutableChannelHandler route = localComponentRoutingTable.getRoute(new JID(null, jid.getDomain(), null, true));
    +        if (route == null) {
    +            final String normalized = normalizeDomain(jid.getDomain());
    +            if (!normalized.equals(jid.getDomain())) {
    +                route = localComponentRoutingTable.getRoute(new JID(null, normalized, null, true));
    +            }
    +        }
             if (route != null) {
                 try {
                     route.process(packet);
    ~/Java/openfire/igniterealtime$ 

    Хотите присоединиться к обсуждению?

    Войти в аккаунт