LocalComponentSession.java 17 KB
Newer Older
1
/*
2
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
Gaston Dombiak's avatar
Gaston Dombiak committed
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.
Gaston Dombiak's avatar
Gaston Dombiak committed
15 16 17
 */
package org.jivesoftware.openfire.session;

18 19 20 21
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
22
import java.util.Locale;
23 24
import java.util.Map;

Gaston Dombiak's avatar
Gaston Dombiak committed
25 26 27 28 29 30 31 32
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.component.ExternalComponentManager;
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.util.LocaleUtils;
33 34
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Gaston Dombiak's avatar
Gaston Dombiak committed
35 36
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
37
import org.xmpp.component.ComponentException;
Gaston Dombiak's avatar
Gaston Dombiak committed
38
import org.xmpp.component.ComponentManager;
39
import org.xmpp.packet.IQ;
Gaston Dombiak's avatar
Gaston Dombiak committed
40 41 42 43 44 45 46 47 48
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.StreamError;

/**
 * Represents a session between the server and a component.
 *
 * @author Gaston Dombiak
 */
49
// TODO implement TLS and observe org.jivesoftware.openfire.session.ConnectionSettings.Component.TLS_POLICY
Gaston Dombiak's avatar
Gaston Dombiak committed
50 51
public class LocalComponentSession extends LocalSession implements ComponentSession {

52 53
	private static final Logger Log = LoggerFactory.getLogger(LocalComponentSession.class);

54
    private LocalExternalComponent component;
55 56 57 58 59 60 61
    /**
     * When using XEP-114 (the old spec) components will include in the TO attribute
     * of the intial stream header the domain they would like to have. The requested
     * domain is used only after the authentication was successful so we need keep track
     * of this information until the handshake is done.  
     */
    private String defaultSubdomain;
Gaston Dombiak's avatar
Gaston Dombiak committed
62 63 64 65 66 67 68 69 70

    /**
     * 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.
71
     * @param xpp     the parser that is reading the provided XML through the connection.
Gaston Dombiak's avatar
Gaston Dombiak committed
72 73
     * @param connection the connection with the component.
     * @return a newly created session between the server and a component.
74
     * @throws XmlPullParserException if there was an XML error while creating the session.
Gaston Dombiak's avatar
Gaston Dombiak committed
75
     */
76 77
    public static LocalComponentSession createSession(String serverName, XmlPullParser xpp, Connection connection)
            throws XmlPullParserException {
Gaston Dombiak's avatar
Gaston Dombiak committed
78
        String domain = xpp.getAttributeValue("", "to");
79
        Boolean allowMultiple = xpp.getAttributeValue("", "allowMultiple") != null;
Gaston Dombiak's avatar
Gaston Dombiak committed
80

81 82
        Log.debug("LocalComponentSession: [ExComp] Starting registration of new external component for domain: " +
                domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96

        // 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) {
97
            Log.debug("LocalComponentSession: [ExComp] Domain not specified in stanza: " + xpp.getText());
Gaston Dombiak's avatar
Gaston Dombiak committed
98 99 100
            // Include the bad-format in the response
            StreamError error = new StreamError(StreamError.Condition.bad_format);
            sb.append(error.toXML());
101
            connection.deliverRawText(sb.toString());
Gaston Dombiak's avatar
Gaston Dombiak committed
102 103 104 105 106 107 108 109 110 111 112
            // 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);
        }
113 114
        domain = subdomain + "." + serverName;
        JID componentJID = new JID(domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
115 116
        // Check that an external component for the specified subdomain may connect to this server
        if (!ExternalComponentManager.canAccess(subdomain)) {
117 118
            Log.debug(
                    "LocalComponentSession: [ExComp] Component is not allowed to connect with subdomain: " + subdomain);
Gaston Dombiak's avatar
Gaston Dombiak committed
119 120
            StreamError error = new StreamError(StreamError.Condition.host_unknown);
            sb.append(error.toXML());
121
            connection.deliverRawText(sb.toString());
Gaston Dombiak's avatar
Gaston Dombiak committed
122 123 124 125 126 127 128
            // 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) {
129
            Log.debug("LocalComponentSession: [ExComp] A shared secret for the component was not found.");
Gaston Dombiak's avatar
Gaston Dombiak committed
130 131 132
            // Include the internal-server-error in the response
            StreamError error = new StreamError(StreamError.Condition.internal_server_error);
            sb.append(error.toXML());
133
            connection.deliverRawText(sb.toString());
Gaston Dombiak's avatar
Gaston Dombiak committed
134 135 136 137 138
            // Close the underlying connection
            connection.close();
            return null;
        }
        // Check that the requested subdomain is not already in use
139
        if (!allowMultiple && InternalComponentManager.getInstance().hasComponent(componentJID)) {
140
            Log.debug("LocalComponentSession: [ExComp] Another component is already using domain: " + domain);
Gaston Dombiak's avatar
Gaston Dombiak committed
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());
145
            connection.deliverRawText(sb.toString());
Gaston Dombiak's avatar
Gaston Dombiak committed
146 147 148 149 150 151
            // Close the underlying connection
            connection.close();
            return null;
        }

        // Create a ComponentSession for the external component
152 153
        LocalComponentSession session = SessionManager.getInstance().createComponentSession(componentJID, connection);
        session.component = new LocalExternalComponent(session, connection);
Gaston Dombiak's avatar
Gaston Dombiak committed
154 155

        try {
156
            Log.debug("LocalComponentSession: [ExComp] Send stream header with ID: " + session.getStreamID() +
Gaston Dombiak's avatar
Gaston Dombiak committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170
                    " 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("\">");
171 172 173 174 175 176 177
            connection.deliverRawText(sb.toString());

            // Return session although session has not been authentication yet. Until
            // it is authenticated traffic will be rejected except for authentication
            // requests
            session.defaultSubdomain = subdomain;
            return session;
Gaston Dombiak's avatar
Gaston Dombiak committed
178 179 180 181 182 183 184 185 186 187
        }
        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) {
188
        super(serverName, conn, id, Locale.getDefault());
Gaston Dombiak's avatar
Gaston Dombiak committed
189 190
    }

191 192
    @Override
	public String getAvailableStreamFeatures() {
Gaston Dombiak's avatar
Gaston Dombiak committed
193 194 195 196
        // Nothing special to add
        return null;
    }

197 198
    @Override
	boolean canProcess(Packet packet) {
Gaston Dombiak's avatar
Gaston Dombiak committed
199 200 201
        return true;
    }

202 203
    @Override
	void deliver(Packet packet) throws PacketException {
204
        component.deliver(packet);
Gaston Dombiak's avatar
Gaston Dombiak committed
205 206
    }

207
    @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
208 209 210 211
    public ExternalComponent getExternalComponent() {
        return component;
    }

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
    /**
     * Authenticate the external component using a digest method. The digest includes the
     * stream ID and the secret key of the main domain of the external component. A component
     * needs to authenticate just once but it may bind several domains.
     *
     * @param digest the digest sent in the handshake.
     * @return true if the authentication was successful.
     */
    public boolean authenticate(String digest) {
        // Perform authentication. Wait for the handshake (with the secret key)
        String secretKey = ExternalComponentManager.getSecretForComponent(defaultSubdomain);
        String anticipatedDigest = AuthFactory.createDigest(getStreamID().getID(), secretKey);
        // Check that the provided handshake (secret key + sessionID) is correct
        if (!anticipatedDigest.equalsIgnoreCase(digest)) {
            Log.debug("LocalComponentSession: [ExComp] Incorrect handshake for component with domain: " +
                    defaultSubdomain);
            //  The credentials supplied by the initiator are not valid (answer an error
            // and close the connection)
            conn.deliverRawText(new StreamError(StreamError.Condition.not_authorized).toXML());
            // Close the underlying connection
            conn.close();
            return false;
        }
        else {
            // Component has authenticated fine
            setStatus(STATUS_AUTHENTICATED);
            // Send empty handshake element to acknowledge success
            conn.deliverRawText("<handshake></handshake>");
            // Bind the domain to this component
            ExternalComponent component = getExternalComponent();
            try {
                InternalComponentManager.getInstance().addComponent(defaultSubdomain, component);
                Log.debug(
                        "LocalComponentSession: [ExComp] External component was registered SUCCESSFULLY with domain: " +
                                defaultSubdomain);
                return true;
            }
            catch (ComponentException e) {
                Log.debug("LocalComponentSession: [ExComp] Another component is already using domain: " +
                        defaultSubdomain);
                //  The credentials supplied by the initiator are not valid (answer an error
                // and close the connection)
                conn.deliverRawText(new StreamError(StreamError.Condition.conflict).toXML());
                // Close the underlying connection
                conn.close();
                return false;
            }
        }
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
262 263 264 265 266 267 268 269 270 271 272 273 274
    /**
     * 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 {
275 276 277 278
        /**
         * Keeps track of the IQ (get/set) packets that were sent from a given component's connection. This
         * information will be used to ensure that the IQ reply will be sent to the same component's connection.
         */
279
        private static final Map<String, LocalExternalComponent> iqs = new HashMap<>();
280

281
        private LocalComponentSession session;
Gaston Dombiak's avatar
Gaston Dombiak committed
282 283 284 285 286 287 288 289
        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.
         */
290
        private List<String> subdomains = new ArrayList<>();
Gaston Dombiak's avatar
Gaston Dombiak committed
291 292


293 294
        public LocalExternalComponent(LocalComponentSession session, Connection connection) {
            this.session = session;
Gaston Dombiak's avatar
Gaston Dombiak committed
295 296 297
            this.connection = connection;
        }

298
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
299
        public void processPacket(Packet packet) {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
            if (packet instanceof IQ) {
                IQ iq = (IQ) packet;
                if (iq.getType() == IQ.Type.result || iq.getType() == IQ.Type.error) {
                    // Check if this IQ reply belongs to a specific component and route
                    // reply to that specific component (if it exists)
                    LocalExternalComponent targetComponent;
                    synchronized (iqs) {
                        targetComponent = iqs.remove(packet.getID());
                    }
                    if (targetComponent != null) {
                        targetComponent.processPacket(packet);
                        return;
                    }
                }
            }
315 316 317 318 319 320 321 322 323 324 325
            // 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
326 327 328 329 330 331 332 333 334 335 336
            if (connection != null && !connection.isClosed()) {
                try {
                    connection.deliver(packet);
                }
                catch (Exception e) {
                    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                    connection.close();
                }
            }
        }

337
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
338 339 340 341
        public String getName() {
            return name;
        }

342
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
343 344 345 346
        public String getDescription() {
            return category + " - " + type;
        }

347
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
348 349 350 351
        public void setName(String name) {
            this.name = name;
        }

352
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
353 354 355 356
        public String getType() {
            return type;
        }

357
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
358 359 360 361
        public void setType(String type) {
            this.type = type;
        }

362
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
363 364 365 366
        public String getCategory() {
            return category;
        }

367
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
368 369 370 371
        public void setCategory(String category) {
            this.category = category;
        }

372
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
373 374 375 376 377 378 379 380 381 382 383
        public String getInitialSubdomain() {
            if (subdomains.isEmpty()) {
                return null;
            }
            return subdomains.get(0);
        }

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

384
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
385 386 387 388
        public Collection<String> getSubdomains() {
            return subdomains;
        }

389
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
390 391 392 393
        public void initialize(JID jid, ComponentManager componentManager) {
            addSubdomain(jid.toString());
        }

394
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
395 396 397
        public void start() {
        }

398
        @Override
Gaston Dombiak's avatar
Gaston Dombiak committed
399
        public void shutdown() {
400 401
            // Remove tracking of IQ packets sent from this component
            synchronized (iqs) {
402
                List<String> toRemove = new ArrayList<>();
403 404 405 406 407 408 409 410 411 412
                for (Map.Entry<String,LocalExternalComponent> entry : iqs.entrySet()) {
                    if (entry.getValue() == this) {
                        toRemove.add(entry.getKey());
                    }
                }
                // Remove keys pointing to component being removed
                for (String key : toRemove) {
                    iqs.remove(key);
                }
            }
Gaston Dombiak's avatar
Gaston Dombiak committed
413 414
        }

415 416
        @Override
		public String toString() {
Gaston Dombiak's avatar
Gaston Dombiak committed
417 418
            return super.toString() + " - subdomains: " + subdomains;
        }
419 420 421 422 423 424

        public void track(IQ iq) {
            synchronized (iqs) {
                iqs.put(iq.getID(), this);
            }
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
425 426
    }
}