SocketReadingMode.java 12.2 KB
Newer Older
Gaston Dombiak's avatar
Gaston Dombiak committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: $
 * $Date: $
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
Gaston Dombiak's avatar
Gaston Dombiak committed
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * 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.
Gaston Dombiak's avatar
Gaston Dombiak committed
19 20
 */

21
package org.jivesoftware.openfire.net;
Gaston Dombiak's avatar
Gaston Dombiak committed
22

23 24 25
import java.io.IOException;
import java.net.Socket;

Gaston Dombiak's avatar
Gaston Dombiak committed
26 27
import org.dom4j.DocumentException;
import org.dom4j.Element;
28 29
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.session.Session;
30 31
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Gaston Dombiak's avatar
Gaston Dombiak committed
32 33 34
import org.xmlpull.v1.XmlPullParserException;
import org.xmpp.packet.StreamError;

35 36
import javax.net.ssl.SSLHandshakeException;

Gaston Dombiak's avatar
Gaston Dombiak committed
37
/**
38
 * Abstract class for {@link BlockingReadingMode}.
Gaston Dombiak's avatar
Gaston Dombiak committed
39 40 41 42 43
 *
 * @author Gaston Dombiak
 */
abstract class SocketReadingMode {

44 45
	private static final Logger Log = LoggerFactory.getLogger(SocketReadingMode.class);

Gaston Dombiak's avatar
Gaston Dombiak committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    /**
     * The utf-8 charset for decoding and encoding Jabber packet streams.
     */
    protected static String CHARSET = "UTF-8";

    protected SocketReader socketReader;
    protected Socket socket;

    protected SocketReadingMode(Socket socket, SocketReader socketReader) {
        this.socket = socket;
        this.socketReader = socketReader;
    }

    /*
    * This method is invoked when client send data to the channel.
    */
    abstract void run();

    /**
     * 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.
     */
    protected boolean negotiateTLS() {
        if (socketReader.connection.getTlsPolicy() == Connection.TLSPolicy.disabled) {
            // Set the not_authorized error
            StreamError error = new StreamError(StreamError.Condition.not_authorized);
            // Deliver stanza
            socketReader.connection.deliverRawText(error.toXML());
            // Close the underlying connection
            socketReader.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 : " + socketReader.connection);
            return false;
        }
        // Client requested to secure the connection using TLS. Negotiate TLS.
        try {
86
            // This code is only used for s2s
87
            socketReader.connection.startTLS(false);
Gaston Dombiak's avatar
Gaston Dombiak committed
88
        }
89
        catch (SSLHandshakeException e) {
90
            // RFC3620, section 5.4.3.2 "STARTTLS Failure" - close the socket *without* sending any more data (<failure/> nor </stream>).
91
            Log.info( "STARTTLS negotiation (with: {}) failed.", socketReader.connection, e );
92
            socketReader.connection.forceClose();
93 94 95 96 97
            return false;
        }
        catch (IOException | RuntimeException e) {
            // RFC3620, section 5.4.2.2 "Failure case" - Send a <failure/> element, then close the socket.
            Log.warn( "An exception occurred while performing STARTTLS negotiation (with: {})", socketReader.connection, e);
98
            socketReader.connection.deliverRawText("<failure xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
Gaston Dombiak's avatar
Gaston Dombiak committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
            socketReader.connection.close();
            return false;
        }
        return true;
    }

    /**
     * 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.
     */
    protected void tlsNegotiated() throws XmlPullParserException, IOException {
        // Offer stream features including SASL Mechanisms
        StringBuilder sb = new StringBuilder(620);
        sb.append(geStreamHeader());
        sb.append("<stream:features>");
        // Include available SASL Mechanisms
        sb.append(SASLAuthentication.getSASLMechanisms(socketReader.session));
        // Include specific features such as auth and register for client sessions
        String specificFeatures = socketReader.session.getAvailableStreamFeatures();
        if (specificFeatures != null) {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");
        socketReader.connection.deliverRawText(sb.toString());
    }

    protected boolean authenticateClient(Element doc) throws DocumentException, IOException,
            XmlPullParserException {
        // Ensure that connection was secured if TLS was required
        if (socketReader.connection.getTlsPolicy() == Connection.TLSPolicy.required &&
                !socketReader.connection.isSecure()) {
            socketReader.closeNeverSecuredConnection();
            return false;
        }

        boolean isComplete = false;
        boolean success = false;
        while (!isComplete) {
            SASLAuthentication.Status status = SASLAuthentication.handle(socketReader.session, doc);
            if (status == SASLAuthentication.Status.needResponse) {
                // Get the next answer since we are not done yet
                doc = socketReader.reader.parseDocument().getRootElement();
                if (doc == null) {
                    // Nothing was read because the connection was closed or dropped
                    isComplete = true;
                }
            }
            else {
                isComplete = true;
                success = status == SASLAuthentication.Status.authenticated;
            }
        }
        return success;
    }

    /**
     * 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)
     */
    protected void saslSuccessful() throws XmlPullParserException, IOException {
        StringBuilder sb = new StringBuilder(420);
        sb.append(geStreamHeader());
        sb.append("<stream:features>");

        // Include specific features such as resource binding and session establishment
        // for client sessions
        String specificFeatures = socketReader.session.getAvailableStreamFeatures();
        if (specificFeatures != null) {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");
        socketReader.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.
     * @throws IOException if an error occurs while starting using compression.
     */
    protected boolean compressClient(Element doc) throws IOException, XmlPullParserException {
        String error = null;
        if (socketReader.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 : " + socketReader.connection);
        }
        else if (socketReader.connection.isCompressed()) {
            // 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 : " + socketReader.connection);
        }
        else {
            // 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 : " + socketReader.connection);
            }
        }

        if (error != null) {
            // Deliver stanza
            socketReader.connection.deliverRawText(error);
            return false;
        }
        else {
221 222 223
            // Start using compression for incoming traffic
            socketReader.connection.addCompression();

Gaston Dombiak's avatar
Gaston Dombiak committed
224 225 226
            // Indicate client that he can proceed and compress the socket
            socketReader.connection.deliverRawText("<compressed xmlns='http://jabber.org/protocol/compress'/>");

227
            // Start using compression for outgoing traffic
Gaston Dombiak's avatar
Gaston Dombiak committed
228 229 230 231 232 233 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 261 262 263 264 265 266 267 268 269 270
            socketReader.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)
     */
    protected void compressionSuccessful() throws XmlPullParserException, IOException
    {
        StringBuilder sb = new StringBuilder(340);
        sb.append(geStreamHeader());
        sb.append("<stream:features>");
        // Include SASL mechanisms only if client has not been authenticated
        if (socketReader.session.getStatus() != Session.STATUS_AUTHENTICATED) {
            // Include available SASL Mechanisms
            sb.append(SASLAuthentication.getSASLMechanisms(socketReader.session));
        }
        // Include specific features such as resource binding and session establishment
        // for client sessions
        String specificFeatures = socketReader.session.getAvailableStreamFeatures();
        if (specificFeatures != null)
        {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");
        socketReader.connection.deliverRawText(sb.toString());
    }

    private String geStreamHeader() {
        StringBuilder sb = new StringBuilder(200);
        sb.append("<?xml version='1.0' encoding='");
        sb.append(CHARSET);
        sb.append("'?>");
        if (socketReader.connection.isFlashClient()) {
            sb.append("<flash:stream xmlns:flash=\"http://www.jabber.com/streams/flash\" ");
        } else {
            sb.append("<stream:stream ");
        }
        sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"");
271
        sb.append(socketReader.getNamespace()).append('\"');
272
        if (socketReader.getExtraNamespaces() != null) {
273
            sb.append(' ');
274 275 276
            sb.append(socketReader.getExtraNamespaces());
        }
        sb.append(" from=\"");
Gaston Dombiak's avatar
Gaston Dombiak committed
277 278 279 280
        sb.append(socketReader.session.getServerName());
        sb.append("\" id=\"");
        sb.append(socketReader.session.getStreamID().toString());
        sb.append("\" xml:lang=\"");
281
        sb.append(socketReader.session.getLanguage().toLanguageTag());
Gaston Dombiak's avatar
Gaston Dombiak committed
282
        sb.append("\" version=\"");
283
        sb.append(Session.MAJOR_VERSION).append('.').append(Session.MINOR_VERSION);
Gaston Dombiak's avatar
Gaston Dombiak committed
284 285 286 287 288
        sb.append("\">");
        return sb.toString();
    }

}