ComponentSession.java 11 KB
Newer Older
Gaston Dombiak's avatar
Gaston Dombiak committed
1
/**
2
 * $RCSfile: ComponentSession.java,v $
Gaston Dombiak's avatar
Gaston Dombiak committed
3 4 5 6 7 8 9 10
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2004 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.
 */
Gaston Dombiak's avatar
Gaston Dombiak committed
11
package org.jivesoftware.messenger.component;
Gaston Dombiak's avatar
Gaston Dombiak committed
12

Gaston Dombiak's avatar
Gaston Dombiak committed
13 14 15
import org.dom4j.Element;
import org.dom4j.io.XPPPacketReader;
import org.jivesoftware.messenger.*;
Gaston Dombiak's avatar
Gaston Dombiak committed
16
import org.jivesoftware.messenger.auth.AuthFactory;
Gaston Dombiak's avatar
Gaston Dombiak committed
17
import org.jivesoftware.messenger.auth.UnauthorizedException;
Gaston Dombiak's avatar
Gaston Dombiak committed
18
import org.jivesoftware.util.LocaleUtils;
Gaston Dombiak's avatar
Gaston Dombiak committed
19
import org.jivesoftware.util.Log;
Gaston Dombiak's avatar
Gaston Dombiak committed
20 21
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
Gaston Dombiak's avatar
Gaston Dombiak committed
22 23 24 25 26
import org.xmpp.component.Component;
import org.xmpp.component.ComponentManager;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.StreamError;
Gaston Dombiak's avatar
Gaston Dombiak committed
27 28

import java.io.IOException;
Gaston Dombiak's avatar
Gaston Dombiak committed
29
import java.io.Writer;
Gaston Dombiak's avatar
Gaston Dombiak committed
30 31 32 33 34 35 36 37 38 39 40 41

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

    private ExternalComponent component = new ExternalComponent();

    /**
     * Returns a newly created session between the server and a component. The session will be
42
     * created and returned only if all the checkings were correct.<p>
Gaston Dombiak's avatar
Gaston Dombiak committed
43 44
     *
     * A domain will be binded for the new connecting component. This method is following
45
     * the JEP-114 where the domain to bind is sent in the TO attribute of the stream header.
Gaston Dombiak's avatar
Gaston Dombiak committed
46 47
     *
     * @param serverName the name of the server where the session is connecting to.
48
     * @param reader     the reader that is reading the provided XML through the connection.
Gaston Dombiak's avatar
Gaston Dombiak committed
49 50 51 52 53
     * @param connection the connection with the component.
     * @return a newly created session between the server and a component.
     */
    public static Session createSession(String serverName, XPPPacketReader reader,
            Connection connection) throws UnauthorizedException, IOException,
54 55
            XmlPullParserException
    {
Gaston Dombiak's avatar
Gaston Dombiak committed
56 57 58 59
        XmlPullParser xpp = reader.getXPPParser();
        Session session;
        String domain = xpp.getAttributeValue("", "to");

Gaston Dombiak's avatar
Gaston Dombiak committed
60 61
        Log.debug("[ExComp] Starting registration of new external component for domain: " + domain);

62 63 64 65 66 67 68
        // Get the requested subdomain
        String subdomain = domain;
        int index = domain.indexOf(serverName);
        if (index > -1) {
            subdomain = domain.substring(0, index -1);
        }

Gaston Dombiak's avatar
Gaston Dombiak committed
69 70
        Writer writer = connection.getWriter();
        // Default answer header in case of an error
71
        StringBuilder sb = new StringBuilder();
Gaston Dombiak's avatar
Gaston Dombiak committed
72 73 74 75 76 77 78 79 80 81 82
        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) {
Gaston Dombiak's avatar
Gaston Dombiak committed
83
            Log.debug("[ExComp] Domain not specified in stanza: " + xpp.getText());
Gaston Dombiak's avatar
Gaston Dombiak committed
84
            // Include the bad-format in the response
85 86
            StreamError error = new StreamError(StreamError.Condition.bad_format);
            sb.append(error.toXML());
Gaston Dombiak's avatar
Gaston Dombiak committed
87 88 89 90 91 92
            writer.write(sb.toString());
            writer.flush();
            // Close the underlying connection
            connection.close();
            return null;
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
93 94 95 96 97 98 99 100 101 102 103
        // Check that an external component for the specified subdomain may connect to this server
        if (!ExternalComponentManager.canAccess(subdomain)) {
            Log.debug("[ExComp] Component is not allowed to connect with subdomain: " + subdomain);
            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;
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
104
        // Check that a secret key was configured in the server
Gaston Dombiak's avatar
Gaston Dombiak committed
105
        String secretKey = ExternalComponentManager.getSecretForComponent(subdomain);
Gaston Dombiak's avatar
Gaston Dombiak committed
106
        if (secretKey == null) {
Gaston Dombiak's avatar
Gaston Dombiak committed
107
            Log.debug("[ExComp] A shared secret for the component was not found.");
Gaston Dombiak's avatar
Gaston Dombiak committed
108
            // Include the internal-server-error in the response
109 110
            StreamError error = new StreamError(StreamError.Condition.internal_server_error);
            sb.append(error.toXML());
Gaston Dombiak's avatar
Gaston Dombiak committed
111 112 113 114 115 116
            writer.write(sb.toString());
            writer.flush();
            // Close the underlying connection
            connection.close();
            return null;
        }
117 118
        // Check that the requested subdomain is not already in use
        if (InternalComponentManager.getInstance().getComponent(subdomain) != null) {
Gaston Dombiak's avatar
Gaston Dombiak committed
119
            Log.debug("[ExComp] Another component is already using domain: " + domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
120 121
            // Domain already occupied so return a conflict error and close the connection
            // Include the conflict error in the response
122 123
            StreamError error = new StreamError(StreamError.Condition.conflict);
            sb.append(error.toXML());
Gaston Dombiak's avatar
Gaston Dombiak committed
124 125 126 127 128 129 130 131 132 133
            writer.write(sb.toString());
            writer.flush();
            // Close the underlying connection
            connection.close();
            return null;
        }

        // Create a ComponentSession for the external component
        session = SessionManager.getInstance().createComponentSession(connection);
        // Set the bind address as the address of the session
134
        session.setAddress(new JID(null, domain , null));
Gaston Dombiak's avatar
Gaston Dombiak committed
135 136

        try {
Gaston Dombiak's avatar
Gaston Dombiak committed
137 138 139
            Log.debug("[ExComp] Send stream header with ID: " + session.getStreamID() +
                    " for component with domain: " +
                    domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
140
            // Build the start packet response
141
            sb = new StringBuilder();
Gaston Dombiak's avatar
Gaston Dombiak committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
            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);
160
            // Check that the provided handshake (secret key + sessionID) is correct
Gaston Dombiak's avatar
Gaston Dombiak committed
161
            if (!anticipatedDigest.equalsIgnoreCase(digest)) {
Gaston Dombiak's avatar
Gaston Dombiak committed
162
                Log.debug("[ExComp] Incorrect handshake for component with domain: " + domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
163 164
                //  The credentials supplied by the initiator are not valid (answer an error
                // and close the connection)
165
                sb = new StringBuilder();
Gaston Dombiak's avatar
Gaston Dombiak committed
166
                // Include the conflict error in the response
167 168
                StreamError error = new StreamError(StreamError.Condition.not_authorized);
                sb.append(error.toXML());
Gaston Dombiak's avatar
Gaston Dombiak committed
169 170 171 172 173 174 175 176 177 178 179 180
                writer.write(sb.toString());
                writer.flush();
                // Close the underlying connection
                connection.close();
                return null;
            }
            else {
                // Component has authenticated fine
                session.setStatus(Session.STATUS_AUTHENTICATED);
                // Send empty handshake element to acknowledge success
                writer.write("<handshake></handshake>");
                writer.flush();
181 182
                // Bind the domain to this component
                ExternalComponent component = ((ComponentSession) session).getExternalComponent();
Gaston Dombiak's avatar
Gaston Dombiak committed
183
                component.setSubdomain(subdomain);
184
                InternalComponentManager.getInstance().addComponent(subdomain, component);
Gaston Dombiak's avatar
Gaston Dombiak committed
185 186
                Log.debug("[ExComp] External component was registered SUCCESSFULLY with domain: " +
                        domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
                return session;
            }
        }
        catch (Exception e) {
            Log.error("An error occured while creating a ComponentSession", e);
            // Close the underlying connection
            connection.close();
            return null;
        }
    }

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

202
    public void process(Packet packet) throws PacketException {
Gaston Dombiak's avatar
Gaston Dombiak committed
203 204
        // Since ComponentSessions are not being stored in the RoutingTable this messages is very
        // unlikely to be sent
205
        component.processPacket(packet);
Gaston Dombiak's avatar
Gaston Dombiak committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    }

    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.
     */
    public class ExternalComponent implements Component {

224 225 226
        private String name = "";
        private String type = "";
        private String category = "";
Gaston Dombiak's avatar
Gaston Dombiak committed
227 228
        private String subdomain;

229
        public void processPacket(Packet packet) {
Gaston Dombiak's avatar
Gaston Dombiak committed
230 231 232 233 234
            if (conn != null && !conn.isClosed()) {
                try {
                    conn.deliver(packet);
                }
                catch (Exception e) {
235
                    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
236
                    conn.close();
Gaston Dombiak's avatar
Gaston Dombiak committed
237 238 239 240
                }
            }
        }

241
        public String getName() {
Gaston Dombiak's avatar
Gaston Dombiak committed
242
            return name;
243 244 245
        }

        public String getDescription() {
Gaston Dombiak's avatar
Gaston Dombiak committed
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
            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 getSubdomain() {
            return subdomain;
        }

        public void setSubdomain(String subdomain) {
            this.subdomain = subdomain;
275 276 277 278 279
        }

        public void initialize(JID jid, ComponentManager componentManager) {
        }

280 281 282
        public void start() {
        }

283 284
        public void shutdown() {
        }
285
    }
286
}