StanzaHandler.java 31.5 KB
Newer Older
1
/**
2
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
3
 *
4 5 6 7 8 9 10 11 12 13 14
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
15 16
 */

17
package org.jivesoftware.openfire.net;
18 19 20

import org.dom4j.Element;
import org.dom4j.io.XMPPPacketReader;
21 22
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.PacketRouter;
23
import org.jivesoftware.openfire.StreamIDFactory;
24
import org.jivesoftware.openfire.XMPPServer;
25
import org.jivesoftware.openfire.auth.UnauthorizedException;
26
import org.jivesoftware.openfire.http.FlashCrossDomainServlet;
27
import org.jivesoftware.openfire.session.LocalSession;
28
import org.jivesoftware.openfire.session.Session;
29
import org.jivesoftware.openfire.spi.BasicStreamIDFactory;
30
import org.jivesoftware.openfire.streammanagement.StreamManager;
31
import org.jivesoftware.util.JiveGlobals;
32
import org.jivesoftware.util.LocaleUtils;
33 34
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
35 36
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
37 38 39 40
import org.xmpp.packet.*;

import java.io.IOException;
import java.io.StringReader;
41 42 43 44 45 46 47 48

/**
 * A StanzaHandler is the main responsible for handling incoming stanzas. Some stanzas like startTLS
 * are totally managed by this class. The rest of the stanzas are just forwarded to the router.
 *
 * @author Gaston Dombiak
 */
public abstract class StanzaHandler {
49

50 51
	private static final Logger Log = LoggerFactory.getLogger(StanzaHandler.class);

52 53 54 55 56
    /**
     * A factory that generates random stream IDs
     */
    private static final StreamIDFactory STREAM_ID_FACTORY = new BasicStreamIDFactory();

57 58 59 60
    /**
     * The utf-8 charset for decoding and encoding Jabber packet streams.
     */
    protected static String CHARSET = "UTF-8";
61
    protected Connection connection;
62 63 64 65

    // DANIELE: Indicate if a session is already created
    private boolean sessionCreated = false;

66 67 68
    // 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.
    private boolean startedTLS = false;
69 70 71
    // Flag that indicates that the client requested to be authenticated. Once the
    // authentication process is over the value will return to false.
    private boolean startedSASL = false;
72 73 74 75
    /**
     * SASL status based on the last SASL interaction
     */
    private SASLAuthentication.Status saslStatus;
76 77 78 79 80 81 82

    // DANIELE: Indicate if a stream:stream is arrived to complete compression
    private boolean waitingCompressionACK = false;

    /**
     * Session associated with the socket reader.
     */
83
    protected LocalSession session;
84 85 86 87 88 89 90 91 92

    /**
     * Router used to route incoming packets to the correct channels.
     */
    private PacketRouter router;

    /**
     * Creates a dedicated reader for a socket.
     *
93
     * @param router     the router for sending packets that were read.
94 95
     * @param connection the connection being read.
     */
96 97 98 99 100 101
    public StanzaHandler(PacketRouter router, Connection connection) {
        this.router = router;
        this.connection = connection;
    }

    @Deprecated
102 103 104 105 106
    public StanzaHandler(PacketRouter router, String serverName, Connection connection) {
        this.router = router;
        this.connection = connection;
    }

107
    public void process(String stanza, XMPPPacketReader reader) throws Exception {
108

109
        boolean initialStream = stanza.startsWith("<stream:stream") || stanza.startsWith("<flash:stream");
110 111
        if (!sessionCreated || initialStream) {
            if (!initialStream) {
112 113
                // Allow requests for flash socket policy files directly on the client listener port
                if (stanza.startsWith("<policy-file-request/>")) {
114
                    String crossDomainText = FlashCrossDomainServlet.CROSS_DOMAIN_TEXT +
115
                            XMPPServer.getInstance().getConnectionManager().getClientListenerPort() +
116
                            FlashCrossDomainServlet.CROSS_DOMAIN_END_TEXT + '\0';
117 118 119 120 121 122 123
                    connection.deliverRawText(crossDomainText);
                    return;
                }
                else {
                    // Ignore <?xml version="1.0"?>
                    return;
                }
124 125 126 127
            }
            // Found an stream:stream tag...
            if (!sessionCreated) {
                sessionCreated = true;
128
                MXParser parser = reader.getXPPParser();
129 130
                parser.setInput(new StringReader(stanza));
                createSession(parser);
131 132
            }
            else if (startedTLS) {
133 134
                startedTLS = false;
                tlsNegotiated();
135 136
            }
            else if (startedSASL && saslStatus == SASLAuthentication.Status.authenticated) {
137 138
                startedSASL = false;
                saslSuccessful();
139 140
            }
            else if (waitingCompressionACK) {
141 142 143 144 145 146
                waitingCompressionACK = false;
                compressionSuccessful();
            }
            return;
        }

147 148
        // Verify if end of stream was requested
        if (stanza.equals("</stream:stream>")) {
149 150 151
            if (session != null) {
                session.close();
            }
152 153
            return;
        }
154 155 156 157
        // Ignore <?xml version="1.0"?> stanzas sent by clients
        if (stanza.startsWith("<?xml")) {
            return;
        }
158
        // Create DOM object from received stanza
159
        Element doc = reader.read(new StringReader(stanza)).getRootElement();
160 161 162 163 164 165 166 167
        if (doc == null) {
            // No document found.
            return;
        }
        String tag = doc.getName();
        if ("starttls".equals(tag)) {
            // Negotiate TLS
            if (negotiateTLS()) {
168 169 170
                startedTLS = true;
            }
            else {
171 172 173
                connection.close();
                session = null;
            }
174 175
        }
        else if ("auth".equals(tag)) {
176 177
            // User is trying to authenticate using SASL
            startedSASL = true;
178 179
            // Process authentication stanza
            saslStatus = SASLAuthentication.handle(session, doc);
180
        } else if (startedSASL && "response".equals(tag) || "abort".equals(tag)) {
181 182
            // User is responding to SASL challenge. Process response
            saslStatus = SASLAuthentication.handle(session, doc);
183 184
        }
        else if ("compress".equals(tag)) {
185 186 187 188 189 190
            // Client is trying to initiate compression
            if (compressClient(doc)) {
                // Compression was successful so open a new stream and offer
                // resource binding and session establishment (to client sessions only)
                waitingCompressionACK = true;
            }
191 192
        } else if (isStreamManagementStanza(doc)) {
            session.getStreamManager().process( doc, session.getAddress() );
193 194
        }
        else {
195 196 197 198
            process(doc);
        }
    }

199
	private void process(Element doc) throws UnauthorizedException {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        if (doc == null) {
            return;
        }

        // Ensure that connection was secured if TLS was required
        if (connection.getTlsPolicy() == Connection.TLSPolicy.required &&
                !connection.isSecure()) {
            closeNeverSecuredConnection();
            return;
        }

        String tag = doc.getName();
        if ("message".equals(tag)) {
            Message packet;
            try {
215
                packet = new Message(doc, !validateJIDs());
216
            }
217
            catch (IllegalArgumentException e) {
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
                Log.debug("Rejecting packet. JID malformed", e);
                // The original packet contains a malformed JID so answer with an error.
                Message reply = new Message();
                reply.setID(doc.attributeValue("id"));
                reply.setTo(session.getAddress());
                reply.getElement().addAttribute("from", doc.attributeValue("to"));
                reply.setError(PacketError.Condition.jid_malformed);
                session.process(reply);
                return;
            }
            processMessage(packet);
        }
        else if ("presence".equals(tag)) {
            Presence packet;
            try {
233
                packet = new Presence(doc, !validateJIDs());
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
            }
            catch (IllegalArgumentException e) {
                Log.debug("Rejecting packet. JID malformed", e);
                // The original packet contains a malformed JID so answer an error
                Presence reply = new Presence();
                reply.setID(doc.attributeValue("id"));
                reply.setTo(session.getAddress());
                reply.getElement().addAttribute("from", doc.attributeValue("to"));
                reply.setError(PacketError.Condition.jid_malformed);
                session.process(reply);
                return;
            }
            // Check that the presence type is valid. If not then assume available type
            try {
                packet.getType();
            }
            catch (IllegalArgumentException e) {
                Log.warn("Invalid presence type", e);
                // The presence packet contains an invalid presence type so replace it with
                // an available presence type
                packet.setType(null);
            }
            // Check that the presence show is valid. If not then assume available show value
            try {
                packet.getShow();
            }
            catch (IllegalArgumentException e) {
261
                Log.debug("Invalid presence show for -" + packet.toXML(), e);
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
                // The presence packet contains an invalid presence show so replace it with
                // an available presence show
                packet.setShow(null);
            }
            if (session.getStatus() == Session.STATUS_CLOSED && packet.isAvailable()) {
                // Ignore available presence packets sent from a closed session. A closed
                // session may have buffered data pending to be processes so we want to ignore
                // just Presences of type available
                Log.warn("Ignoring available presence packet of closed session: " + packet);
                return;
            }
            processPresence(packet);
        }
        else if ("iq".equals(tag)) {
            IQ packet;
            try {
                packet = getIQ(doc);
            }
280
            catch (IllegalArgumentException e) {
281 282 283 284
                Log.debug("Rejecting packet. JID malformed", e);
                // The original packet contains a malformed JID so answer an error
                IQ reply = new IQ();
                if (!doc.elements().isEmpty()) {
285
                    reply.setChildElement(((Element)doc.elements().get(0)).createCopy());
286 287 288 289 290 291 292 293 294 295
                }
                reply.setID(doc.attributeValue("id"));
                reply.setTo(session.getAddress());
                if (doc.attributeValue("to") != null) {
                    reply.getElement().addAttribute("from", doc.attributeValue("to"));
                }
                reply.setError(PacketError.Condition.jid_malformed);
                session.process(reply);
                return;
            }
296 297 298 299 300 301 302
            if (packet.getID() == null && JiveGlobals.getBooleanProperty("xmpp.server.validation.enabled", false)) {
                // IQ packets MUST have an 'id' attribute so close the connection
                StreamError error = new StreamError(StreamError.Condition.invalid_xml);
                session.deliverRawText(error.toXML());
                session.close();
                return;
            }
303 304
            processIQ(packet);
        }
305
        else {
306 307 308
            if (!processUnknowPacket(doc)) {
                Log.warn(LocaleUtils.getLocalizedString("admin.error.packet.tag") +
                        doc.asXML());
309
                session.close();
310 311 312 313 314 315 316 317 318 319
            }
        }
    }

    private IQ getIQ(Element doc) {
        Element query = doc.element("query");
        if (query != null && "jabber:iq:roster".equals(query.getNamespaceURI())) {
            return new Roster(doc);
        }
        else {
320
            return new IQ(doc, !validateJIDs());
321 322 323 324 325
        }
    }

    /**
     * Process the received IQ packet. Registered
326
     * {@link org.jivesoftware.openfire.interceptor.PacketInterceptor} will be invoked before
327 328
     * and after the packet was routed.
     * <p>
329 330
     * Subclasses may redefine this method for different reasons such as modifying the sender
     * of the packet to avoid spoofing, rejecting the packet or even process the packet in
331
     * another thread.</p>
332 333
     *
     * @param packet the received packet.
334 335
     * @throws org.jivesoftware.openfire.auth.UnauthorizedException
     *          if service is not available to sender.
336 337 338 339 340 341 342 343
     */
    protected void processIQ(IQ packet) throws UnauthorizedException {
        router.route(packet);
        session.incrementClientPacketCount();
    }

    /**
     * Process the received Presence packet. Registered
344
     * {@link org.jivesoftware.openfire.interceptor.PacketInterceptor} will be invoked before
345 346
     * and after the packet was routed.
     * <p>
347 348
     * Subclasses may redefine this method for different reasons such as modifying the sender
     * of the packet to avoid spoofing, rejecting the packet or even process the packet in
349
     * another thread.</p>
350 351
     *
     * @param packet the received packet.
352 353
     * @throws org.jivesoftware.openfire.auth.UnauthorizedException
     *          if service is not available to sender.
354 355 356 357 358 359 360 361
     */
    protected void processPresence(Presence packet) throws UnauthorizedException {
        router.route(packet);
        session.incrementClientPacketCount();
    }

    /**
     * Process the received Message packet. Registered
362
     * {@link org.jivesoftware.openfire.interceptor.PacketInterceptor} will be invoked before
363 364
     * and after the packet was routed.
     * <p>
365 366
     * Subclasses may redefine this method for different reasons such as modifying the sender
     * of the packet to avoid spoofing, rejecting the packet or even process the packet in
367
     * another thread.</p>
368 369
     *
     * @param packet the received packet.
370 371
     * @throws org.jivesoftware.openfire.auth.UnauthorizedException
     *          if service is not available to sender.
372 373 374 375 376 377 378 379 380 381 382 383
     */
    protected void processMessage(Message packet) throws UnauthorizedException {
        router.route(packet);
        session.incrementClientPacketCount();
    }

    /**
     * Returns true if a received packet of an unkown type (i.e. not a Message, Presence
     * or IQ) has been processed. If the packet was not processed then an exception will
     * be thrown which will make the thread to stop processing further packets.
     *
     * @param doc the DOM element of an unkown type.
384
     * @return true if a received packet has been processed.
385
     * @throws UnauthorizedException if stanza failed to be processed. Connection will be closed.
386
     */
387
    abstract boolean processUnknowPacket(Element doc) throws UnauthorizedException;
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

    /**
     * Tries to secure the connection using TLS. If the connection is secured then reset
     * the parser to use the new secured reader. But if the connection failed to be secured
     * then send a <failure> stanza and close the connection.
     *
     * @return true if the connection was secured.
     */
    private boolean negotiateTLS() {
        if (connection.getTlsPolicy() == Connection.TLSPolicy.disabled) {
            // Set the not_authorized error
            StreamError error = new StreamError(StreamError.Condition.not_authorized);
            // Deliver stanza
            connection.deliverRawText(error.toXML());
            // Close the underlying connection
            connection.close();
            // Log a warning so that admins can track this case from the server side
            Log.warn("TLS requested by initiator when TLS was never offered by server. " +
                    "Closing connection : " + connection);
            return false;
        }
        // Client requested to secure the connection using TLS. Negotiate TLS.
        try {
411
            startTLS();
412 413 414
        }
        catch (Exception e) {
            Log.error("Error while negotiating TLS", e);
415
            connection.deliverRawText("<failure xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
416 417 418 419 420 421
            connection.close();
            return false;
        }
        return true;
    }

422 423
    abstract void startTLS() throws Exception;

424 425 426 427 428 429 430 431 432
    /**
     * TLS negotiation was successful so open a new stream and offer the new stream features.
     * The new stream features will include available SASL mechanisms and specific features
     * depending on the session type such as auth for Non-SASL authentication and register
     * for in-band registration.
     */
    private void tlsNegotiated() {
        // Offer stream features including SASL Mechanisms
        StringBuilder sb = new StringBuilder(620);
433
        sb.append(getStreamHeader());
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
        sb.append("<stream:features>");
        // Include available SASL Mechanisms
        sb.append(SASLAuthentication.getSASLMechanisms(session));
        // Include specific features such as auth and register for client sessions
        String specificFeatures = session.getAvailableStreamFeatures();
        if (specificFeatures != null) {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");
        connection.deliverRawText(sb.toString());
    }

    /**
     * After SASL authentication was successful we should open a new stream and offer
     * new stream features such as resource binding and session establishment. Notice that
     * resource binding and session establishment should only be offered to clients (i.e. not
     * to servers or external components)
     */
    private void saslSuccessful() {
        StringBuilder sb = new StringBuilder(420);
454
        sb.append(getStreamHeader());
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        sb.append("<stream:features>");

        // Include specific features such as resource binding and session establishment
        // for client sessions
        String specificFeatures = session.getAvailableStreamFeatures();
        if (specificFeatures != null) {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");
        connection.deliverRawText(sb.toString());
    }

    /**
     * Start using compression but first check if the connection can and should use compression.
     * The connection will be closed if the requested method is not supported, if the connection
     * is already using compression or if client requested to use compression but this feature
     * is disabled.
     *
     * @param doc the element sent by the client requesting compression. Compression method is
     *            included.
     * @return true if it was possible to use compression.
     */
    private boolean compressClient(Element doc) {
        String error = null;
        if (connection.getCompressionPolicy() == Connection.CompressionPolicy.disabled) {
            // Client requested compression but this feature is disabled
            error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
            // Log a warning so that admins can track this case from the server side
            Log.warn("Client requested compression while compression is disabled. Closing " +
                    "connection : " + connection);
485 486
        }
        else if (connection.isCompressed()) {
487 488 489 490 491
            // Client requested compression but connection is already compressed
            error = "<failure xmlns='http://jabber.org/protocol/compress'><setup-failed/></failure>";
            // Log a warning so that admins can track this case from the server side
            Log.warn("Client requested compression and connection is already compressed. Closing " +
                    "connection : " + connection);
492 493
        }
        else {
494 495 496 497 498 499 500 501 502 503 504 505 506 507
            // Check that the requested method is supported
            String method = doc.elementText("method");
            if (!"zlib".equals(method)) {
                error = "<failure xmlns='http://jabber.org/protocol/compress'><unsupported-method/></failure>";
                // Log a warning so that admins can track this case from the server side
                Log.warn("Requested compression method is not supported: " + method +
                        ". Closing connection : " + connection);
            }
        }

        if (error != null) {
            // Deliver stanza
            connection.deliverRawText(error);
            return false;
508 509
        }
        else {
510 511 512
            // Start using compression for incoming traffic
            connection.addCompression();

513 514 515
            // Indicate client that he can proceed and compress the socket
            connection.deliverRawText("<compressed xmlns='http://jabber.org/protocol/compress'/>");

516
            // Start using compression for outgoing traffic
517 518 519 520 521 522 523 524 525 526 527 528 529
            connection.startCompression();
            return true;
        }
    }

    /**
     * After compression was successful we should open a new stream and offer
     * new stream features such as resource binding and session establishment. Notice that
     * resource binding and session establishment should only be offered to clients (i.e. not
     * to servers or external components)
     */
    private void compressionSuccessful() {
        StringBuilder sb = new StringBuilder(340);
530
        sb.append(getStreamHeader());
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        sb.append("<stream:features>");
        // Include SASL mechanisms only if client has not been authenticated
        if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
            // Include available SASL Mechanisms
            sb.append(SASLAuthentication.getSASLMechanisms(session));
        }
        // Include specific features such as resource binding and session establishment
        // for client sessions
        String specificFeatures = session.getAvailableStreamFeatures();
        if (specificFeatures != null) {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");
        connection.deliverRawText(sb.toString());
    }

547 548 549 550 551 552 553 554 555 556
	/**
	 * Determines whether stanza's namespace matches XEP-0198 namespace
	 * @param stanza Stanza to be checked
	 * @return whether stanza's namespace matches XEP-0198 namespace
	 */
	private boolean isStreamManagementStanza(Element stanza) {
		return StreamManager.NAMESPACE_V2.equals(stanza.getNamespace().getStringValue()) ||
				StreamManager.NAMESPACE_V3.equals(stanza.getNamespace().getStringValue());
	}

557
    private String getStreamHeader() {
558 559 560 561 562 563
        StringBuilder sb = new StringBuilder(200);
        sb.append("<?xml version='1.0' encoding='");
        sb.append(CHARSET);
        sb.append("'?>");
        if (connection.isFlashClient()) {
            sb.append("<flash:stream xmlns:flash=\"http://www.jabber.com/streams/flash\" ");
564 565
        }
        else {
566 567 568 569 570
            sb.append("<stream:stream ");
        }
        sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"");
        sb.append(getNamespace());
        sb.append("\" from=\"");
571
        sb.append(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
572 573 574
        sb.append("\" id=\"");
        sb.append(session.getStreamID());
        sb.append("\" xml:lang=\"");
575
        sb.append(session.getLanguage().toLanguageTag());
576
        sb.append("\" version=\"");
577
        sb.append(Session.MAJOR_VERSION).append('.').append(Session.MINOR_VERSION);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        sb.append("\">");
        return sb.toString();
    }

    /**
     * Close the connection since TLS was mandatory and the entity never negotiated TLS. Before
     * closing the connection a stream error will be sent to the entity.
     */
    void closeNeverSecuredConnection() {
        // Set the not_authorized error
        StreamError error = new StreamError(StreamError.Condition.not_authorized);
        // Deliver stanza
        connection.deliverRawText(error.toXML());
        // Close the underlying connection
        connection.close();
        // Log a warning so that admins can track this case from the server side
        Log.warn("TLS was required by the server and connection was never secured. " +
                "Closing connection : " + connection);
    }

    /**
     * Uses the XPP to grab the opening stream tag and create an active session
     * object. The session to create will depend on the sent namespace. In all
     * cases, the method obtains the opening stream tag, checks for errors, and
     * either creates a session or returns an error and kills the connection.
     * If the connection remains open, the XPP will be set to be ready for the
     * first packet. A call to next() should result in an START_TAG state with
     * the first packet in the stream.
     */
    protected void createSession(XmlPullParser xpp) throws XmlPullParserException, IOException {
        for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) {
            eventType = xpp.next();
        }

612 613
        final String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();

614 615 616 617
        // Check that the TO attribute of the stream header matches the server name or a valid
        // subdomain. If the value of the 'to' attribute is not valid then return a host-unknown
        // error and close the underlying connection.
        String host = xpp.getAttributeValue("", "to");
618
        StreamError streamError = null;
619
        if (validateHost() && isHostUnknown(host)) {
620
            streamError = new StreamError(StreamError.Condition.host_unknown);
621 622 623 624
            // Log a warning so that admins can track this cases from the server side
            Log.warn("Closing session due to incorrect hostname in stream header. Host: " + host +
                    ". Connection: " + connection);
        }
625
        // Validate the stream namespace
626
        else if (!"http://etherx.jabber.org/streams".equals(xpp.getNamespace()) && !"http://www.jabber.com/streams/flash".equals(xpp.getNamespace())) {
627 628 629
            // Include the invalid-namespace in the response
            streamError = new StreamError(StreamError.Condition.invalid_namespace);
            // Log a warning so that admins can track this cases from the server side
630
            Log.warn("Closing session due to invalid namespace in stream header. Namespace: " +
631
                    xpp.getNamespace() + ". Connection: " + connection);
632

633
        }
634 635 636 637
        // Create the correct session based on the sent namespace. At this point the server
        // may offer the client to secure the connection. If the client decides to secure
        // the connection then a <starttls> stanza should be received
        else if (!createSession(xpp.getNamespace(null), serverName, xpp, connection)) {
638 639 640
            // http://xmpp.org/rfcs/rfc6120.html#streams-error-conditions-invalid-namespace
            // "or the content namespace declared as the default namespace is not supported (e.g., something other than "jabber:client" or "jabber:server")."
            streamError = new StreamError(StreamError.Condition.invalid_namespace);
641
            // Log a warning so that admins can track this cases from the server side
642
            Log.warn("Closing session due to invalid namespace in stream header. Prefix: " +
643 644 645 646
                    xpp.getNamespace(null) + ". Connection: " + connection);
        }

        if (streamError != null) {
647
            StringBuilder sb = new StringBuilder(250);
648
            if (host == null) host = serverName;
649 650 651 652 653
            sb.append("<?xml version='1.0' encoding='");
            sb.append(CHARSET);
            sb.append("'?>");
            // Append stream header
            sb.append("<stream:stream ");
654
            sb.append("from=\"").append(host).append("\" ");
655
            sb.append("id=\"").append(STREAM_ID_FACTORY.createStreamID()).append("\" ");
656
            sb.append("xmlns=\"").append(xpp.getNamespace(null)).append("\" ");
657
            sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
658
            sb.append("version=\"1.0\">");
659 660
            sb.append(streamError.toXML());
            // Deliver stanza
661 662 663 664
            connection.deliverRawText(sb.toString());
            // Close the underlying connection
            connection.close();
        }
665

666 667 668 669 670 671 672 673
    }

    private boolean isHostUnknown(String host) {
        if (host == null) {
            // Answer false since when using server dialback the stream header will not
            // have a TO attribute
            return false;
        }
674
        if (XMPPServer.getInstance().getServerInfo().getXMPPDomain().equals( host )) {
675 676 677 678 679 680
            // requested host matched the server name
            return false;
        }
        return true;
    }

681 682 683
    /**
	 * Obtain the address of the XMPP entity for which this StanzaHandler
	 * handles stanzas.
684
	 *
685 686
	 * Note that the value that is returned for this method can
	 * change over time. For example, if no session has been established yet,
687
	 * this method will return <tt>null</tt>, or, if resource binding occurs,
688 689
	 * the returned value might change. Values obtained from this method are
	 * therefore best <em>not</em> cached.
690
	 *
691 692 693 694 695 696
	 * @return The address of the XMPP entity for.
	 */
    public JID getAddress() {
    	if (session == null) {
    		return null;
    	}
697

698 699
    	return session.getAddress();
    }
700

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
    /**
     * Returns the stream namespace. (E.g. jabber:client, jabber:server, etc.).
     *
     * @return the stream namespace.
     */
    abstract String getNamespace();

    /**
     * Returns true if the value of the 'to' attribute in the stream header should be
     * validated. If the value of the 'to' attribute is not valid then a host-unknown error
     * will be returned and the underlying connection will be closed.
     *
     * @return true if the value of the 'to' attribute in the initial stream header should be
     *         validated.
     */
    abstract boolean validateHost();

718 719 720 721 722 723 724 725 726 727
    /**
     * Returns true if the value of the 'to' attribute of {@link IQ}, {@link Presence} and
     * {@link Message} must be validated. Connection Managers perform their own
     * JID validation so there is no need to validate JIDs again but when clients are
     * directly connected to the server then we need to validate JIDs.
     *
     * @return rue if the value of the 'to' attribute of IQ, Presence and Messagemust be validated.
     */
    abstract boolean validateJIDs();

728 729 730 731 732 733
    /**
     * Creates the appropriate {@link Session} subclass based on the specified namespace.
     *
     * @param namespace the namespace sent in the stream element. eg. jabber:client.
     * @return the created session or null.
     * @throws org.xmlpull.v1.XmlPullParserException
734
     *
735 736 737 738
     */
    abstract boolean createSession(String namespace, String serverName, XmlPullParser xpp, Connection connection)
            throws XmlPullParserException;
}