LocalComponentSession.java 13.3 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
/**
 * $RCSfile: $
 * $Revision: $
 * $Date: $
 *
 * Copyright (C) 2007 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.openfire.session;

import org.dom4j.Element;
import org.dom4j.io.XMPPPacketReader;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.StreamID;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.component.ExternalComponentManager;
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.openfire.net.SocketConnection;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmpp.component.ComponentManager;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.StreamError;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Represents a session between the server and a component.
 *
 * @author Gaston Dombiak
 */
public class LocalComponentSession extends LocalSession implements ComponentSession {

46
    private LocalExternalComponent component;
Gaston Dombiak's avatar
Gaston Dombiak committed
47 48 49 50 51 52 53 54 55 56 57 58

    /**
     * Returns a newly created session between the server and a component. The session will be
     * created and returned only if all the checkings were correct.<p>
     *
     * A domain will be binded for the new connecting component. This method is following
     * the JEP-114 where the domain to bind is sent in the TO attribute of the stream header.
     *
     * @param serverName the name of the server where the session is connecting to.
     * @param reader     the reader that is reading the provided XML through the connection.
     * @param connection the connection with the component.
     * @return a newly created session between the server and a component.
59 60 61
     * @throws UnauthorizedException if the connection required security but was not secured.
     * @throws XmlPullParserException if there was an XML error while creating the session.
     * @throws IOException if an IO error occured while creating the session.
Gaston Dombiak's avatar
Gaston Dombiak committed
62 63
     */
    public static LocalComponentSession createSession(String serverName, XMPPPacketReader reader,
64
            SocketConnection connection) throws UnauthorizedException, IOException,
Gaston Dombiak's avatar
Gaston Dombiak committed
65 66 67 68
            XmlPullParserException
    {
        XmlPullParser xpp = reader.getXPPParser();
        String domain = xpp.getAttributeValue("", "to");
69
        Boolean allowMultiple = reader.getXPPParser().getAttributeValue("", "allowMultiple") != null;
Gaston Dombiak's avatar
Gaston Dombiak committed
70

71
        Log.debug("LocalComponentSession: [ExComp] Starting registration of new external component for domain: " + domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

        Writer writer = connection.getWriter();
        // Default answer header in case of an error
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version='1.0' encoding='");
        sb.append(CHARSET);
        sb.append("'?>");
        sb.append("<stream:stream ");
        sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
        sb.append("xmlns=\"jabber:component:accept\" from=\"");
        sb.append(domain);
        sb.append("\">");

        // Check that a domain was provided in the stream header
        if (domain == null) {
87
            Log.debug("LocalComponentSession: [ExComp] Domain not specified in stanza: " + xpp.getText());
Gaston Dombiak's avatar
Gaston Dombiak committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
            // Include the bad-format in the response
            StreamError error = new StreamError(StreamError.Condition.bad_format);
            sb.append(error.toXML());
            writer.write(sb.toString());
            writer.flush();
            // Close the underlying connection
            connection.close();
            return null;
        }

        // Get the requested subdomain
        String subdomain = domain;
        int index = domain.indexOf(serverName);
        if (index > -1) {
            subdomain = domain.substring(0, index -1);
        }
104 105
        domain = subdomain + "." + serverName;
        JID componentJID = new JID(domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
106 107
        // Check that an external component for the specified subdomain may connect to this server
        if (!ExternalComponentManager.canAccess(subdomain)) {
108
            Log.debug("LocalComponentSession: [ExComp] Component is not allowed to connect with subdomain: " + subdomain);
Gaston Dombiak's avatar
Gaston Dombiak committed
109 110 111 112 113 114 115 116 117 118 119
            StreamError error = new StreamError(StreamError.Condition.host_unknown);
            sb.append(error.toXML());
            writer.write(sb.toString());
            writer.flush();
            // Close the underlying connection
            connection.close();
            return null;
        }
        // Check that a secret key was configured in the server
        String secretKey = ExternalComponentManager.getSecretForComponent(subdomain);
        if (secretKey == null) {
120
            Log.debug("LocalComponentSession: [ExComp] A shared secret for the component was not found.");
Gaston Dombiak's avatar
Gaston Dombiak committed
121 122 123 124 125 126 127 128 129 130
            // Include the internal-server-error in the response
            StreamError error = new StreamError(StreamError.Condition.internal_server_error);
            sb.append(error.toXML());
            writer.write(sb.toString());
            writer.flush();
            // Close the underlying connection
            connection.close();
            return null;
        }
        // Check that the requested subdomain is not already in use
131
        if (!allowMultiple && InternalComponentManager.getInstance().hasComponent(componentJID)) {
132
            Log.debug("LocalComponentSession: [ExComp] Another component is already using domain: " + domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
133 134 135 136 137 138 139 140 141 142 143 144
            // Domain already occupied so return a conflict error and close the connection
            // Include the conflict error in the response
            StreamError error = new StreamError(StreamError.Condition.conflict);
            sb.append(error.toXML());
            writer.write(sb.toString());
            writer.flush();
            // Close the underlying connection
            connection.close();
            return null;
        }

        // Create a ComponentSession for the external component
145 146
        LocalComponentSession session = SessionManager.getInstance().createComponentSession(componentJID, connection);
        session.component = new LocalExternalComponent(session, connection);
Gaston Dombiak's avatar
Gaston Dombiak committed
147 148

        try {
149
            Log.debug("LocalComponentSession: [ExComp] Send stream header with ID: " + session.getStreamID() +
Gaston Dombiak's avatar
Gaston Dombiak committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
                    " for component with domain: " +
                    domain);
            // Build the start packet response
            sb = new StringBuilder();
            sb.append("<?xml version='1.0' encoding='");
            sb.append(CHARSET);
            sb.append("'?>");
            sb.append("<stream:stream ");
            sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
            sb.append("xmlns=\"jabber:component:accept\" from=\"");
            sb.append(domain);
            sb.append("\" id=\"");
            sb.append(session.getStreamID().toString());
            sb.append("\">");
            writer.write(sb.toString());
            writer.flush();

            // Perform authentication. Wait for the handshake (with the secret key)
            Element doc = reader.parseDocument().getRootElement();
            String digest = "handshake".equals(doc.getName()) ? doc.getStringValue() : "";
            String anticipatedDigest = AuthFactory.createDigest(session.getStreamID().getID(), secretKey);
            // Check that the provided handshake (secret key + sessionID) is correct
            if (!anticipatedDigest.equalsIgnoreCase(digest)) {
173
                Log.debug("LocalComponentSession: [ExComp] Incorrect handshake for component with domain: " + domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
                //  The credentials supplied by the initiator are not valid (answer an error
                // and close the connection)
                writer.write(new StreamError(StreamError.Condition.not_authorized).toXML());
                writer.flush();
                // Close the underlying connection
                connection.close();
                return null;
            }
            else {
                // Component has authenticated fine
                session.setStatus(STATUS_AUTHENTICATED);
                // Send empty handshake element to acknowledge success
                writer.write("<handshake></handshake>");
                writer.flush();
                // Bind the domain to this component
                ExternalComponent component = session.getExternalComponent();
                InternalComponentManager.getInstance().addComponent(subdomain, component);
191
                Log.debug("LocalComponentSession: [ExComp] External component was registered SUCCESSFULLY with domain: " + domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
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
                return session;
            }
        }
        catch (Exception e) {
            Log.error("An error occured while creating a ComponentSession", e);
            // Close the underlying connection
            connection.close();
            return null;
        }
    }

    public LocalComponentSession(String serverName, Connection conn, StreamID id) {
        super(serverName, conn, id);
    }

    public String getAvailableStreamFeatures() {
        // Nothing special to add
        return null;
    }

    boolean canProcess(Packet packet) {
        return true;
    }

    void deliver(Packet packet) throws PacketException {
217
        component.deliver(packet);
Gaston Dombiak's avatar
Gaston Dombiak committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    }

    public ExternalComponent getExternalComponent() {
        return component;
    }

    /**
     * The ExternalComponent acts as a proxy of the remote connected component. Any Packet that is
     * sent to this component will be delivered to the real component on the other side of the
     * connection.<p>
     *
     * An ExternalComponent will be added as a route in the RoutingTable for each connected
     * external component. This implies that when the server receives a packet whose domain matches
     * the external component services address then a route to the external component will be used
     * and the packet will be forwarded to the component on the other side of the connection.
     *
     * @author Gaston Dombiak
     */
    public static class LocalExternalComponent implements ComponentSession.ExternalComponent {
237
        private LocalComponentSession session;
Gaston Dombiak's avatar
Gaston Dombiak committed
238 239 240 241 242 243 244 245 246 247 248
        private Connection connection;
        private String name = "";
        private String type = "";
        private String category = "";
        /**
         * List of subdomains that were binded for this component. The list will include
         * the initial subdomain.
         */
        private List<String> subdomains = new ArrayList<String>();


249 250
        public LocalExternalComponent(LocalComponentSession session, Connection connection) {
            this.session = session;
Gaston Dombiak's avatar
Gaston Dombiak committed
251 252 253 254
            this.connection = connection;
        }

        public void processPacket(Packet packet) {
255 256 257 258 259 260 261 262 263 264 265
            // Ask the session to process the outgoing packet. This will
            // give us the chance to apply PacketInterceptors
            session.process(packet);
        }

        /**
         * Delivers the packet to the external component.
         *
         * @param packet the packet to deliver.
         */
        void deliver(Packet packet) {
Gaston Dombiak's avatar
Gaston Dombiak committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
            if (connection != null && !connection.isClosed()) {
                try {
                    connection.deliver(packet);
                }
                catch (Exception e) {
                    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                    connection.close();
                }
            }
        }

        public String getName() {
            return name;
        }

        public String getDescription() {
            return category + " - " + type;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public String getInitialSubdomain() {
            if (subdomains.isEmpty()) {
                return null;
            }
            return subdomains.get(0);
        }

        private void addSubdomain(String subdomain) {
            subdomains.add(subdomain);
        }

        public Collection<String> getSubdomains() {
            return subdomains;
        }

        public void initialize(JID jid, ComponentManager componentManager) {
            addSubdomain(jid.toString());
        }

        public void start() {
        }

        public void shutdown() {
        }

        public String toString() {
            return super.toString() + " - subdomains: " + subdomains;
        }
    }
}