NonBlockingReadingMode.java 10.5 KB
Newer Older
Gaston Dombiak's avatar
Gaston Dombiak committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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 86 87 88 89 90 91 92 93 94 95 96 97 98 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
/**
 * $RCSfile$
 * $Revision: $
 * $Date: $
 *
 * Copyright (C) 2006 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

package org.jivesoftware.wildfire.net;

import com.jcraft.jzlib.JZlib;
import com.jcraft.jzlib.ZInputStream;
import org.dom4j.Element;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.wildfire.SessionManager;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.SocketChannel;

/**
 * Process incoming packets using a non-blocking model.
 *
 * @author Daniele Piras
 */
class NonBlockingReadingMode extends SocketReadingMode {

    // DANIELE: Socket read timeout in milliseconds
    private static int READ_TIMEOUT = 0;

    private static String STREAM_START = "<stream:stream";

    // DANIELE: Semaphore to avoid concurrent reading operation from different thread
    private boolean isReading;

    // DANIELE: lightweight xml parser.
    private XMLLightweightParser xmlLightWeightParser;

    // DANIELE: Channel for socket connection
    private SocketChannel socketChannel;

    // DANIELE: Indicate if the reading operations has been scheduled into the executor.
    // this is very important because if all reading thread are busy is used to avoid
    // to reinsert into the queue the reading operation.
    private boolean isScheduled = false;

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

    // DANIELE: Indicate if a stream:stream is arrived to complete a sals authentication
    private boolean awaytingSasl = false;

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

    private StreamReader streamReader;

    public NonBlockingReadingMode(Socket socket, SocketReader socketReader) {
        super(socket, socketReader);
        // DANIELE: Initialization
        // Setting timeout for reading operations.
        try {
            socket.setSoTimeout(READ_TIMEOUT);
        }
        catch (SocketException e) {
            // There is an exception...
            Log.warn(e);
        }

        socketChannel = socket.getChannel();

        // Initialize XML light weight parser
        xmlLightWeightParser = new XMLLightweightParser(socketChannel, CHARSET);


        isReading = false;
        socketReader.open = true;

        streamReader = new StreamReader();
    }

    /* DANIELE:
     * Method that verify if the client has data in the channel and in this case
     * call an executor to perform reading operations.
     */
    void run() {
        try {
            // Check if the socket is open
            if (socketReader.open) {
                // Verify semaphore and if there are data into the socket.
                if (!isReading && !isScheduled) {
                    try {
                        // Semaphore to avoid concurrent schedule of the same read operation.
                        isScheduled = true;
                        // Schedule execution with executor
                        IOExecutor.execute(streamReader);
                    }
                    catch (Exception e) {
                        if (socketReader.session != null) {
                            Log.warn(LocaleUtils.getLocalizedString("admin.error.stream") +
                                    ". Session: " +
                                    socketReader.session, e);
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            socketReader.shutdown();
            // There is an exception...
            Log.error(e);
        }
        if (!socketReader.open) {
            socketReader.shutdown();
        }
    }

    protected void tlsNegotiated() throws XmlPullParserException, IOException {
        XmlPullParser xpp = socketReader.reader.getXPPParser();
        InputStream is = socketReader.connection.getTLSStreamHandler().getInputStream();
        xpp.setInput(new InputStreamReader(is, CHARSET));
        xmlLightWeightParser.setInput( is, CHARSET );
        super.tlsNegotiated();
    }

    protected boolean compressClient(Element doc) throws IOException, XmlPullParserException {
        boolean answer = super.compressClient(doc);
        if (answer) {
            XmlPullParser xpp = socketReader.reader.getXPPParser();
            // Reset the parser since a new stream header has been sent from the client
            if (socketReader.connection.getTLSStreamHandler() == null) {
                InputStream is;
                if (socketChannel != null) {
                    // DANIELE: Create an inputstream using the utility class ChannelInputStream.
                    is = new ChannelInputStream(socketChannel);
                }
                else {
                    is = socket.getInputStream();
                }
150
                is = ServerTrafficCounter.wrapInputStream(is);
Gaston Dombiak's avatar
Gaston Dombiak committed
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 221 222 223 224 225 226 227 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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

                ZInputStream in = new ZInputStream(is);
                in.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
                xpp.setInput(new InputStreamReader(in, CHARSET));
            }
            else {
                ZInputStream in = new ZInputStream(
                        socketReader.connection.getTLSStreamHandler().getInputStream());
                in.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
                xpp.setInput(new InputStreamReader(in, CHARSET));
                xmlLightWeightParser.setInput( in, CHARSET );
            }
        }
        return answer;
    }

    class StreamReader implements Runnable {

        /*
         * This method is invoked when client send data to the channel.
         *
         */
        public void run() {
            try {
                // If no other reading operations are perform
                if (!isReading) {
                    // Change the semaphore status
                    isReading = true;
                    // Call the XML light-wieght parser to read data...
                    xmlLightWeightParser.read();
                    // Check if the parser has found a complete message...
                    if (xmlLightWeightParser.areThereMsgs()) {
                        // Process every message found
                        String[] msgs = xmlLightWeightParser.getMsgs();
                        for (int i = 0; i < msgs.length; i++) {
                            //System.out.println( "Processing " + msgs[ i ] );
                            readStream(msgs[i]);
                        }
                    }
                }
            }
            catch (IOException e) {
                if (socketReader.session != null) {
                    // DANIELE: Remove session from SessionManager. I don't know if
                    // this is the easy way.
                    // TODO Review this. Closing the connection should be used???
                    SessionManager.getInstance().removeSession(
                            SessionManager.getInstance().getSession(
                                    socketReader.session.getAddress()));
                }
                try {
                    xmlLightWeightParser.getChannel().close();
                }
                catch (IOException e1) {
                }
                // System.out.println( "Client disconnecting" );
            }
            catch (Exception e) {
                if (socketReader.session != null) {
                    Log.warn(LocaleUtils.getLocalizedString("admin.error.stream") + ". Session: " +
                            socketReader.session, e);
                }
                e.printStackTrace();
            }
            finally {
                isReading = false;
                isScheduled = false;
            }
        }

        /**
         * Process a single message
         */
        private void readStream(String msg) throws Exception {

            if (msg.trim().startsWith(STREAM_START)) {
                // Found an stream:stream tag...
                if (!sessionCreated) {
                    sessionCreated = true;
                    socketReader.reader.getXPPParser().setInput(new StringReader(
                            msg + ((msg.indexOf("</stream:stream") == -1) ? "</stream:stream>" :
                                    "")));
                    socketReader.createSession();
                }
                else if (awaytingSasl) {
                    awaytingSasl = false;
                    saslSuccessful();
                }
                else if (awaitingForCompleteCompression) {
                    awaitingForCompleteCompression = false;
                    compressionSuccessful();
                }
                return;
            }

            // Create dom in base on the string.
            Element doc = socketReader.reader.parseDocument(msg).getRootElement();
            if (doc == null) {
                // No document found.
                return;
            }
            String tag = doc.getName();
            if ("starttls".equals(tag)) {
                // Negotiate TLS
                if (negotiateTLS()) {
                    tlsNegotiated();
                }
                else {
                    socketReader.open = false;
                    socketReader.session = null;
                }
            }
            else if ("auth".equals(tag)) {
                // User is trying to authenticate using SASL
                if (authenticateClient(doc)) {
                    // SASL authentication was successful so open a new stream and offer
                    // resource binding and session establishment (to client sessions only)
                    awaytingSasl = true;
                }
                else if (socketReader.connection.isClosed()) {
                    socketReader.open = false;
                    socketReader.session = null;
                }
            }
            else if ("compress".equals(tag))
            {
                // 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)
                    awaitingForCompleteCompression = true;
                }
            }
            else {
                socketReader.process(doc);
            }
        }
    }
}