ClearspaceManager.java 46.1 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
7 8
 *
 * This software is published under the terms of the GNU Public License (GPL),
9 10
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
11 12 13 14
 */

package org.jivesoftware.openfire.clearspace;

15
import org.apache.commons.httpclient.*;
16 17
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.*;
18
import org.dom4j.*;
19
import org.dom4j.io.XMPPPacketReader;
20 21
import org.jivesoftware.openfire.IQResultListener;
import org.jivesoftware.openfire.IQRouter;
22 23
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.XMPPServerInfo;
24
import org.jivesoftware.openfire.auth.AuthFactory;
25 26
import org.jivesoftware.openfire.auth.UnauthorizedException;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
27
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.POST;
28
import org.jivesoftware.openfire.component.*;
29
import org.jivesoftware.openfire.container.BasicModule;
30
import org.jivesoftware.openfire.group.GroupNotFoundException;
31
import org.jivesoftware.openfire.muc.spi.MultiUserChatServiceImpl;
32
import org.jivesoftware.openfire.net.MXParser;
33
import org.jivesoftware.openfire.session.ComponentSession;
34 35
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.util.*;
36 37
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;
38
import org.jivesoftware.util.cache.DefaultCache;
39 40
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
41
import org.xmpp.packet.IQ;
42 43 44 45 46 47
import org.xmpp.packet.JID;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.*;
import java.util.*;
48 49
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
50

51

52 53
/**
 * Centralized administration of Clearspace connections. The {@link #getInstance()} method
54 55
 * should be used to get an instance. The following properties configure this manager:
 * <p/>
56
 * <ul>
57 58
 * <li>clearspace.uri</li>
 * <li>clearspace.sharedSecret</li>
59 60 61 62
 * </ul>
 *
 * @author Daniel Henninger
 */
63
public class ClearspaceManager extends BasicModule implements ExternalComponentManagerListener, ComponentEventListener {
64 65 66 67 68 69 70
    /**
     * This is the username of the user that Openfires uses to connect
     * to Clearspace. It is fixed a well known by Openfire and Clearspace.
     */
    private static final String OPENFIRE_USERNAME = "openfire_SHRJKZCNU53";
    private static final String WEBSERVICES_PATH = "rpc/rest/";
    protected static final String IM_URL_PREFIX = "imService/";
71 72
    public  static final String MUC_SUBDOMAIN = "clearspace-conference";
    private static final String MUC_DESCRIPTION = "Clearspace Conference Services";
73
    public  static final String CLEARSPACE_COMPONENT = "clearspace";
74

75 76
    private static ThreadLocal<XMPPPacketReader> localParser = null;
    private static XmlPullParserFactory factory = null;
77 78 79 80 81
    /**
     * This map is used to transale exceptions from CS to OF
     */
    private static final Map<String, String> exceptionMap;

82
    private static ClearspaceManager instance;
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

    static {
        try {
            factory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null);
            factory.setNamespaceAware(true);
        }
        catch (XmlPullParserException e) {
            Log.error("Error creating a parser factory", e);
        }
        // Create xmpp parser to keep in each thread
        localParser = new ThreadLocal<XMPPPacketReader>() {
            protected XMPPPacketReader initialValue() {
                XMPPPacketReader parser = new XMPPPacketReader();
                factory.setNamespaceAware(true);
                parser.setXPPFactory(factory);
                return parser;
            }
        };
101 102

        // Add a new exception map from CS to OF and it will be automatically translated.
103 104 105 106 107
        exceptionMap = new HashMap<String, String>();
        exceptionMap.put("com.jivesoftware.base.UserNotFoundException", "org.jivesoftware.openfire.user.UserNotFoundException");
        exceptionMap.put("com.jivesoftware.base.UserAlreadyExistsException", "org.jivesoftware.openfire.user.UserAlreadyExistsException");
        exceptionMap.put("com.jivesoftware.base.GroupNotFoundException", "org.jivesoftware.openfire.group.GroupNotFoundException");
        exceptionMap.put("com.jivesoftware.base.GroupAlreadyExistsException", "org.jivesoftware.openfire.group.GroupAlreadyExistsException");
108
        exceptionMap.put("org.acegisecurity.BadCredentialsException", "org.jivesoftware.openfire.auth.UnauthorizedException");
109 110
        exceptionMap.put("com.jivesoftware.base.UnauthorizedException", "org.jivesoftware.openfire.auth.UnauthorizedException");
        exceptionMap.put("com.jivesoftware.community.NotFoundException", "org.jivesoftware.util.NotFoundException");
111
    }
112

113
    private ConfigClearspaceTask configClearspaceTask;
114
    private Map<String, String> properties;
115
    private String uri;
116 117
    private String host;
    private int port;
118
    private String sharedSecret;
119
    private Map<String, Long> userIDCache;
120
    private Map<Long, String> usernameCache;
121
    private Map<String, Long> groupIDCache;
122 123 124 125 126

    // Current nonce storage
    private Cache<String, Long> nonceCache;
    // Nonce generator
    private Random nonceGenerator;
127 128 129 130
    /**
     * Records transcripts for group chat rooms in Clearspace.
     */
    private ClearspaceMUCTranscriptManager mucTranscriptManager = new ClearspaceMUCTranscriptManager(TaskEngine.getInstance());
131 132 133
    /**
     * Keep the domains of Clearspace components
     */
134
    private final List<String> clearspaces = new ArrayList<String>();
135 136

    /**
137
     * Provides singleton access to an instance of the ClearspaceManager class.
138 139 140 141 142 143 144
     *
     * @return an ClearspaceManager instance.
     */
    public static ClearspaceManager getInstance() {
        return instance;
    }

145 146 147 148 149 150
    /**
     * Constructs a new ClearspaceManager instance. Typically, {@link #getInstance()} should be
     * called instead of this method. ClearspaceManager instances should only be created directly
     * for testing purposes.
     *
     * @param properties the Map that contains properties used by the Clearspace manager, such as
151
     *                   Clearspace host and shared secret.
152 153 154 155 156
     */
    public ClearspaceManager(Map<String, String> properties) {
        super("Clearspace integration module for testing only");
        this.properties = properties;

157
        init();
158 159
    }

160 161 162 163 164
    /**
     * Constructs a new ClearspaceManager instance. Typically, {@link #getInstance()} should be
     * called instead of this method. ClearspaceManager instances should only be created directly
     * for testing purposes.
     */
165 166
    public ClearspaceManager() {
        super("Clearspace integration module");
167 168 169 170 171 172
        // Create a special Map implementation to wrap XMLProperties. We only implement
        // the get, put, and remove operations, since those are the only ones used. Using a Map
        // makes it easier to perform LdapManager testing.
        this.properties = new Map<String, String>() {

            public String get(Object key) {
173
                return JiveGlobals.getProperty((String) key);
174 175 176
            }

            public String put(String key, String value) {
177
                JiveGlobals.setProperty(key, value);
178 179 180 181 182
                // Always return null since XMLProperties doesn't support the normal semantics.
                return null;
            }

            public String remove(Object key) {
183
                JiveGlobals.deleteProperty((String) key);
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
                // Always return null since XMLProperties doesn't support the normal semantics.
                return null;
            }


            public int size() {
                return 0;
            }

            public boolean isEmpty() {
                return false;
            }

            public boolean containsKey(Object key) {
                return false;
            }

            public boolean containsValue(Object value) {
                return false;
            }

            public void putAll(Map<? extends String, ? extends String> t) {
            }

            public void clear() {
            }

            public Set<String> keySet() {
                return null;
            }

            public Collection<String> values() {
                return null;
            }

            public Set<Entry<String, String>> entrySet() {
                return null;
            }
        };

224
        init();
225
        instance = this;
226
    }
227

228
    private void init() {
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
        // Convert XML based provider setup to Database based
        JiveGlobals.migrateProperty("clearspace.uri");
        JiveGlobals.migrateProperty("clearspace.sharedSecret");

        // Make sure that all Clearspace components are set up, unless they were overridden
        // Note that the auth provider is our way of knowing that we are set up with Clearspace,
        // so don't bother checking to set it.
        if (isEnabled()) {
            if (JiveGlobals.getProperty("provider.user.className") == null) {
                JiveGlobals.setProperty("provider.user.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceUserProvider");
            }
            if (JiveGlobals.getProperty("provider.group.className") == null) {
                JiveGlobals.setProperty("provider.group.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceGroupProvider");
            }
            if (JiveGlobals.getProperty("provider.vcard.className") == null) {
                JiveGlobals.setProperty("provider.vcard.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceVCardProvider");
            }
            if (JiveGlobals.getProperty("provider.lockout.className") == null) {
                JiveGlobals.setProperty("provider.lockout.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceLockOutProvider");
            }
            if (JiveGlobals.getProperty("provider.securityAudit.className") == null) {
                JiveGlobals.setProperty("provider.securityAudit.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceSecurityAuditProvider");
            }
            if (JiveGlobals.getProperty("provider.admin.className") == null) {
                JiveGlobals.setProperty("provider.admin.className",
                        "org.jivesoftware.openfire.clearspace.ClearspaceAdminProvider");
            }
        }

263 264 265 266 267 268 269 270 271 272 273
        this.uri = properties.get("clearspace.uri");
        if (uri != null) {
            if (!this.uri.endsWith("/")) {
                this.uri = this.uri + "/";
            }
            // Updates the host/port attributes based on the uri
            updateHostPort();
        }
        sharedSecret = properties.get("clearspace.sharedSecret");

        // Creates the cache maps
274 275
        userIDCache = new DefaultCache<String, Long>("clearspace.userid", 1000, JiveConstants.DAY);
        groupIDCache = new DefaultCache<String, Long>("clearspace.groupid", 1000, JiveConstants.DAY);
276
        usernameCache = new DefaultCache<Long, String>("clearspace.username", 1000, JiveConstants.DAY);
277

278

279
        if (Log.isDebugEnabled()) {
280 281 282 283 284 285
            StringBuilder buf = new StringBuilder();
            buf.append("Created new ClearspaceManager() instance, fields:\n");
            buf.append("\t URI: ").append(uri).append("\n");
            buf.append("\t sharedSecret: ").append(sharedSecret).append("\n");

            Log.debug("ClearspaceManager: " + buf.toString());
286
        }
287 288

        // Init nonce cache
289
        nonceCache = CacheFactory.createCache("Clearspace SSO Nonce");
290 291
        // Init nonce generator
        nonceGenerator = new Random();
292 293
    }

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    /**
     * Updates the host port attributes based on the URI.
     */
    private void updateHostPort() {
        if (uri != null && !"".equals(uri.trim())) {
            try {
                URL url = new URL(uri);
                host = url.getHost();
                port = url.getPort();
            } catch (MalformedURLException e) {
                // this won't happen
            }
        }
    }

309
    /**
310
     * Check a username/password pair for valid authentication.
311
     *
312 313 314
     * @param username Username to authenticate against.
     * @param password Password to use for authentication.
     * @return True or false of the authentication succeeded.
315
     */
316
    public Boolean checkAuthentication(String username, String password) {
317 318 319 320
        try {
            String path = ClearspaceAuthProvider.URL_PREFIX + "authenticate/" + username + "/" + password;
            executeRequest(GET, path);
            return true;
321 322 323
        } catch (Exception e) {
            // Nothing to do.
        }
324 325

        return false;
326 327
    }

328
    /**
329
     * Tests the web services connection with Clearspace given the manager's current configuration.
330
     *
331
     * @return True if connection test was successful.
332
     */
333
    public Boolean testConnection() {
334 335
        // Test invoking a simple method
        try {
336 337 338 339
            // If there is a problem with the URL or the user/password this service throws an exception
            String path = IM_URL_PREFIX + "testCredentials";
            executeRequest(GET, path);

340
            return true;
341
        } catch (Exception e) {
342
            // It is not ok, return false.
343
        }
344 345

        return false;
346 347
    }

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    /**
     * Returns true if Openfire is connected to Clearspace.
     * This method may delay some time since it has to ping Clearspace to know if
     * Openfire is able to connect to it.
     *
     * @return true if Openfire is connected to Clearspace.
     */
    public Boolean isOpenfireConnected() {
        return testConnection();
    }

    /**
     * Returns true if Clearspce is connected to Openfire.
     *
     * @return true if Clearspce is connected to Openfire.
     */
    public Boolean isClearspaceConnected() {
        XMPPServer server = XMPPServer.getInstance();
        if (server == null) {
            return false;
        }
        
        Collection<ComponentSession> componentSessions = server.getSessionManager().getComponentSessions();
        for (ComponentSession cs : componentSessions) {
            // All Clearspace sessions start with "clearspace"
            if (cs.getAddress().getDomain().startsWith("clearspace")) {
                return true;
            }
        }
        return false;
    }
379
    /**
380 381
     * Returns the Clearspace service URI; e.g. <tt>https://localhost:80/clearspace</tt>.
     * This value is stored as the Jive Property <tt>clearspace.uri</tt>.
382
     *
383
     * @return the Clearspace service URI.
384
     */
385 386
    public String getConnectionURI() {
        return uri;
387 388 389
    }

    /**
390 391
     * Sets the URI of the Clearspace service; e.g., <tt>https://localhost:80/clearspace</tt>.
     * This value is stored as the Jive Property <tt>clearspace.uri</tt>.
392
     *
393
     * @param uri the Clearspace service URI.
394
     */
395
    public void setConnectionURI(String uri) {
396 397 398
        if (!uri.endsWith("/")) {
            uri = uri + "/";
        }
399
        this.uri = uri;
400
        properties.put("clearspace.uri", uri);
401 402 403 404

        //Updates the host/port attributes
        updateHostPort();

405
        if (isEnabled()) {
406
            startClearspaceConfig();
407
        }
408 409
    }

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    /**
     * Returns the password, configured in Clearspace, that Openfire will use to authenticate
     * with Clearspace to perform it's integration.
     *
     * @return the password Openfire will use to authenticate with Clearspace.
     */
    public String getSharedSecret() {
        return sharedSecret;
    }

    /**
     * Sets the shared secret for the Clearspace service we're connecting to.
     *
     * @param sharedSecret the password configured in Clearspace to authenticate Openfire.
     */
    public void setSharedSecret(String sharedSecret) {
426
        // Set new password for external component
427
        ExternalComponentConfiguration configuration = new ExternalComponentConfiguration("clearspace", true,
428 429 430 431 432 433 434
                ExternalComponentConfiguration.Permission.allowed, sharedSecret);
        try {
            ExternalComponentManager.allowAccess(configuration);
        }
        catch (ModificationNotAllowedException e) {
            Log.warn("Failed to configure password for Clearspace", e);
        }
435 436 437 438 439 440

        // After updating the component information we can update the field, but not before.
        // If it is done before, OF won't be able to execute the updateSharedsecret webservice
        // since it would try with the new password.
        this.sharedSecret = sharedSecret;
        properties.put("clearspace.sharedSecret", sharedSecret);
441 442 443 444 445 446 447 448 449
    }

    /**
     * Returns true if Clearspace is being used as the backend of Openfire. When
     * integrated with Clearspace then users and groups will be pulled out from
     * Clearspace. User authentication will also rely on Clearspace.
     *
     * @return true if Clearspace is being used as the backend of Openfire.
     */
450
    public static boolean isEnabled() {
451 452 453 454 455 456
        return AuthFactory.getAuthProvider() instanceof ClearspaceAuthProvider;
    }

    public void start() throws IllegalStateException {
        super.start();
        if (isEnabled()) {
457 458 459 460 461 462 463 464 465 466
            // Before starting up service make sure there is a default secret
            if (ExternalComponentManager.getDefaultSecret() == null ||
                    "".equals(ExternalComponentManager.getDefaultSecret())) {
                try {
                    ExternalComponentManager.setDefaultSecret(StringUtils.randomString(10));
                }
                catch (ModificationNotAllowedException e) {
                    Log.warn("Failed to set a default secret to external component service", e);
                }
            }
467 468 469 470 471 472 473 474 475 476 477
            // Make sure that external component service is enabled
            if (!ExternalComponentManager.isServiceEnabled()) {
                try {
                    ExternalComponentManager.setServiceEnabled(true);
                }
                catch (ModificationNotAllowedException e) {
                    Log.warn("Failed to start external component service", e);
                }
            }
            // Listen for changes to external component settings
            ExternalComponentManager.addListener(this);
478 479
            // List for registration of new components
            InternalComponentManager.getInstance().addListener(this);
480
            // Set up custom clearspace MUC service
481 482 483 484 485 486 487 488 489 490
            // Create service if it doesn't exist, load if it does.
            MultiUserChatServiceImpl muc = (MultiUserChatServiceImpl)XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(MUC_SUBDOMAIN);
            if (muc == null) {
                try {
                    muc = XMPPServer.getInstance().getMultiUserChatManager().createMultiUserChatService(MUC_SUBDOMAIN, MUC_DESCRIPTION, true);
                }
                catch (AlreadyExistsException e) {
                    Log.error("ClearspaceManager: Found no "+MUC_SUBDOMAIN+" service, but got already exists when creation attempted?  Service probably not started!");
                }
            }
491 492 493 494 495
            if (muc != null) {
                // Set up special delegate for Clearspace MUC service
                muc.setMUCDelegate(new ClearspaceMUCEventDelegate());
                // Set up additional features for Clearspace MUC service
                muc.addExtraFeature("clearspace:service");
496 497
                // Set up additional identity of conference service to Clearspace MUC service
                muc.addExtraIdentity("conference", "Clearspace Chat Service", "text");
498
            }
499 500 501

            // Starts the clearspace configuration task
            startClearspaceConfig();
502 503

            // Starts the Clearspace MUC transcript manager
504
            mucTranscriptManager.start();
505 506 507
        }
    }

508 509 510
    public void stop() {
        super.stop();

511
        // Stops the Clearspace MUC transcript manager
512
        mucTranscriptManager.stop();
513

514 515 516 517
        // Unregister/shut down custom MUC service
        XMPPServer.getInstance().getMultiUserChatManager().unregisterMultiUserChatService(MUC_SUBDOMAIN);
    }

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    public synchronized boolean configClearspace() {
        // If the task is running, stop it
        if (configClearspaceTask != null) {
            configClearspaceTask.cancel();
            Log.debug("Stopping previous configuration Clearspace task.");
        }

        boolean configured = false;
        try {
            doConfigClearspace();
            configured = true;
        } catch (UnauthorizedException e) {
            Log.info("Unauthorized to configure Clearspace.", e);
        } catch (UnsupportedOperationException e) {
            Log.info("Error configuring Clearspace.", e);
        }

        if (!configured) {
            startClearspaceConfig();
        }
        return configured;
    }

541 542 543
    /**
     *
     */
544 545 546 547 548
    private synchronized void startClearspaceConfig() {
        // If the task is running, stop it
        if (configClearspaceTask != null) {
            configClearspaceTask.cancel();
            Log.debug("Stopping previous configuration Clearspace task.");
549
        }
550 551 552

        // Create and schedule a confi task every minute
        configClearspaceTask = new ConfigClearspaceTask();
553
        // Wait some time to start the task until Openfire has binding address
554 555
        TaskEngine.getInstance().schedule(configClearspaceTask, JiveConstants.SECOND * 10, JiveConstants.MINUTE);
        Log.debug("Starting configuration Clearspace task in 10 seconds.");
556 557
    }

558
    private synchronized void doConfigClearspace() throws UnauthorizedException {
559

560 561 562 563 564 565 566 567 568 569
        Log.debug("Starting Clearspace configuration.");

        List<String> bindInterfaces = getServerInterfaces();
        if (bindInterfaces.size() == 0) {
            // We aren't up and running enough to tell Clearspace what interfaces to bind to.
            Log.debug("No bind interfaces found to config Clearspace");
            throw new IllegalStateException("There are no binding interfaces.");
        }

        try {
570

571 572
            XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo();

573
            String path = IM_URL_PREFIX + "configureComponent/";
574

575
            // Creates the XML with the data
576
            Document groupDoc = DocumentHelper.createDocument();
577 578 579 580 581 582 583 584 585 586
            Element rootE = groupDoc.addElement("configureComponent");
            Element domainE = rootE.addElement("domain");
            domainE.setText(serverInfo.getXMPPDomain());
            for (String bindInterface : bindInterfaces) {
                Element hostsE = rootE.addElement("hosts");
                hostsE.setText(bindInterface);
            }
            Element portE = rootE.addElement("port");
            portE.setText(String.valueOf(ExternalComponentManager.getServicePort()));

587 588
            Log.debug("Trying to configure Clearspace with: Domain: " + serverInfo.getXMPPDomain() + ", hosts: " +
                    bindInterfaces.toString() + ", port: " + port);
589

590
            executeRequest(POST, path, rootE.asXML());
591 592

            //Done, Clearspace was configured correctly, clear the task
593
            Log.debug("Clearspace was configured, stopping the task.");
594 595 596 597 598 599 600 601 602 603 604
            TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask);
            configClearspaceTask = null;

        } catch (UnauthorizedException ue) {
            throw ue;
        } catch (Exception e) {
            // It is not supported exception, wrap it into an UnsupportedOperationException
            throw new UnsupportedOperationException("Unexpected error", e);
        }
    }

605 606 607 608 609 610 611 612 613
    /**
     * Returns true if Clerspace was configured at least one time since Openfire startup.
     *
     * @return true if Clerspace was configured at least one time since Openfire startup.
     */
    public boolean isClearspaceConfigured() {
        return configClearspaceTask == null;
    }

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    private List<String> getServerInterfaces() {

        List<String> bindInterfaces = new ArrayList<String>();

        String interfaceName = JiveGlobals.getXMLProperty("network.interface");
        String bindInterface = null;
        if (interfaceName != null) {
            if (interfaceName.trim().length() > 0) {
                bindInterface = interfaceName;
            }
        }

        int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
        int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);

        if (bindInterface == null) {
            try {
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
                Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
                for (NetworkInterface netInterface : Collections.list(nets)) {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    for (InetAddress address : Collections.list(addresses)) {
                        if ("127.0.0.1".equals(address.getHostAddress())) {
                            continue;
                        }
                        if (address.getHostAddress().startsWith("0.")) {
                            continue;
                        }
                        Socket socket = new Socket();
                        InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort);
                        try {
                            socket.connect(remoteAddress);
                            bindInterfaces.add(address.getHostAddress());
                            break;
                        } catch (IOException e) {
                            // Ignore this address. Let's hope there is more addresses to validate
                        }
                    }
                }
652 653 654 655
            } catch (SocketException e) {
                // We failed to discover a valid IP address where the admin console is running
                return null;
            }
656 657
        } else {
            bindInterfaces.add(bindInterface);
658
        }
659

660 661 662 663 664 665
        return bindInterfaces;
    }

    private void updateClearspaceSharedSecret(String newSecret) {

        try {
666 667 668
            String path = IM_URL_PREFIX + "updateSharedSecret/";

            // Creates the XML with the data
669
            Document groupDoc = DocumentHelper.createDocument();
670 671
            Element rootE = groupDoc.addElement("updateSharedSecret");
            rootE.addElement("newSecret").setText(newSecret);
672

673
            executeRequest(POST, path, groupDoc.asXML());
674
        } catch (UnauthorizedException ue) {
675
            Log.error("Error updating the password of Clearspace", ue);
676
        } catch (Exception e) {
677
            Log.error("Error updating the password of Clearspace", e);
678
        }
679

680 681 682 683 684 685 686 687 688 689
    }

    public void serviceEnabled(boolean enabled) throws ModificationNotAllowedException {
        // Do not let admins shutdown the external component service
        if (!enabled) {
            throw new ModificationNotAllowedException("Service cannot be disabled when integrated with Clearspace.");
        }
    }

    public void portChanged(int newPort) throws ModificationNotAllowedException {
690
        startClearspaceConfig();
691
    }
692

693 694 695 696 697 698 699 700 701 702 703 704
    public void defaultSecretChanged(String newSecret) throws ModificationNotAllowedException {
        // Do nothing
    }

    public void permissionPolicyChanged(ExternalComponentManager.PermissionPolicy newPolicy)
            throws ModificationNotAllowedException {
        // Do nothing
    }

    public void componentAllowed(String subdomain, ExternalComponentConfiguration configuration)
            throws ModificationNotAllowedException {
        if (subdomain.startsWith("clearspace")) {
705
            updateClearspaceSharedSecret(configuration.getSecret());
706 707 708 709 710 711 712 713 714 715 716
        }
    }

    public void componentBlocked(String subdomain) throws ModificationNotAllowedException {
        if (subdomain.startsWith("clearspace")) {
            throw new ModificationNotAllowedException("Communication with Clearspace cannot be blocked.");
        }
    }

    public void componentSecretUpdated(String subdomain, String newSecret) throws ModificationNotAllowedException {
        if (subdomain.startsWith("clearspace")) {
717
            updateClearspaceSharedSecret(newSecret);
718 719 720 721 722 723 724 725 726
        }
    }

    public void componentConfigurationDeleted(String subdomain) throws ModificationNotAllowedException {
        // Do not let admins delete configuration of Clearspace component
        if (subdomain.startsWith("clearspace")) {
            throw new ModificationNotAllowedException("Use 'Profile Settings' to change password.");
        }
    }
727 728

    /**
729 730 731 732 733
     * Makes a rest request of either type GET or DELETE at the specified urlSuffix. The
     * urlSuffix should be of the form /userService/users.
     * If CS throws an exception it handled and transalated to a Openfire exception if possible.
     * This is done using the check fault method that has an exception mapping from CS to OF. If
     * no mapping is found then it throws a <code>Exception</code> with the message of the CS exception.
734
     *
735
     * @param type      Must be GET or DELETE
736 737
     * @param urlSuffix The url suffix of the rest request
     * @return The response as a xml doc.
738 739
     * @throws ConnectException Thrown if there are issues perfoming the request.
     * @throws Exception Thrown if the response from Clearspace contains an exception.
740
     */
741
    public Element executeRequest(HttpType type, String urlSuffix) throws ConnectException, Exception {
742 743 744 745
        assert (type == HttpType.GET || type == HttpType.DELETE);
        return executeRequest(type, urlSuffix, null);
    }

746 747 748 749 750 751 752 753 754 755 756 757 758
    /**
     * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
     * form /userService/users.
     * If CS throws an exception it handled and transalated to a Openfire exception if possible.
     * This is done using the check fault method that tries to throw the best maching exception.
     *
     * @param type      Must be GET or DELETE
     * @param urlSuffix The url suffix of the rest request
     * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
     * @return The response as a xml doc.
     * @throws ConnectException Thrown if there are issues perfoming the request.
     * @throws Exception Thrown if the response from Clearspace contains an exception.
     */
759
    public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
760
            throws ConnectException, Exception {
761 762 763 764
        if (Log.isDebugEnabled()) {
            Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
        }

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
        String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

        String secret = getSharedSecret();

        HttpClient client = new HttpClient();
        HttpMethod method;

        // Configures the authentication
        client.getParams().setAuthenticationPreemptive(true);
        Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
        AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
        client.getState().setCredentials(scope, credentials);

        // Creates the method
        switch (type) {
            case GET:
                method = new GetMethod(wsUrl);
                break;
            case POST:
                PostMethod pm = new PostMethod(wsUrl);
                StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
                pm.setRequestEntity(requestEntity);
                method = pm;
                break;
            case PUT:
                PutMethod pm1 = new PutMethod(wsUrl);
                StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
                pm1.setRequestEntity(requestEntity1);
                method = pm1;
                break;
            case DELETE:
                method = new DeleteMethod(wsUrl);
                break;
            default:
                throw new IllegalArgumentException();
        }

        method.setRequestHeader("Accept", "text/xml");
        method.setDoAuthentication(true);

        try {
806
            // Executes the request
807 808 809 810
            client.executeMethod(method);

            // Parses the result
            String body = method.getResponseBodyAsString();
811 812 813
            if (Log.isDebugEnabled()) {
                Log.debug("Outgoing REST call results: " + body);
            }
814 815 816 817 818 819

            // Checks the http status
            if (method.getStatusCode() != 200) {
                throw new ConnectException("Error connecting to Clearspace, http status code: " + method.getStatusCode());
            }

820 821 822 823 824 825 826
            Element response = localParser.get().parseDocument(body).getRootElement();

            // Check for exceptions
            checkFault(response);

            // Since there is no exception, returns the response
            return response;
827 828 829 830 831 832
        } catch (DocumentException e) {
            throw new ConnectException("Error parsing the response of Clearspace.", e);
        } catch (HttpException e) {
            throw new ConnectException("Error peforming http request to Clearspace", e);
        } catch (IOException e) {
            throw new ConnectException("Error peforming http request to Clearspace.", e);
833 834 835 836 837
        } finally {
            method.releaseConnection();
        }
    }

838 839 840 841 842 843 844 845 846
    /**
     * If CS throws an exception it handled and transalated to a Openfire exception if possible.
     * This is done using <code>exceptionMap</code> that has a mapping from CS to OF. If
     * no mapping is found then it tries to instantiete the original exception. If this fails
     * it throws a <code>Exception</code> with the message of the CS exception.
     *
     * @param response the response from CS to check if it is an exception message.
     * @throws Exception if the response is an exception message.
     */
847 848 849 850 851 852 853 854 855 856 857
    private void checkFault(Element response) throws Exception {
        Node node = response.selectSingleNode("ns1:faultstring");
        if (node != null) {
            String exceptionText = node.getText();

            // Text accepted samples:
            // 'java.lang.Exception: Exception message'
            // 'java.lang.Exception'

            // Get the exception class and message if any
            int index = exceptionText.indexOf(":");
858 859
            String className;
            String message;
860
            // If there is no message, save the class only
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
            if (index == -1) {
                className = exceptionText;
                message = null;
            } else {
                // Else save both
                className = exceptionText.substring(0, index);
                message = exceptionText.substring(index + 2);
            }

            // Map the exception to a Openfire one, if possible
            if (exceptionMap.containsKey(className)) {
                className = exceptionMap.get(className);
            }

            //Tries to create an instance with the message
876
            Exception exception;
877 878 879 880 881 882 883 884 885
            try {
                Class exceptionClass = Class.forName(className);
                if (message == null) {
                    exception = (Exception) exceptionClass.newInstance();
                } else {
                    Constructor constructor = exceptionClass.getConstructor(String.class);
                    exception = (Exception) constructor.newInstance(message);
                }
            } catch (Exception e) {
886
                // failed to create an specific exception, creating a standard one.
887 888 889 890 891 892 893 894 895
                exception = new Exception(exceptionText);
            }

            throw exception;
        }

    }

    /**
896
     * Returns the Clearspace user id the user by username.
897
     *
898 899
     * @param username Username to retrieve ID of.
     * @return The ID number of the user in Clearspace.
900 901
     * @throws org.jivesoftware.openfire.user.UserNotFoundException
     *          If the user was not found.
902 903
     */
    protected long getUserID(String username) throws UserNotFoundException {
904 905 906
        // Gets the part before of @ of the username param
        if (username.contains("@")) {
            // User's id are only for local users
907 908 909
            if (!XMPPServer.getInstance().isLocal(new JID(username))) {
                throw new UserNotFoundException("Cannot load user of remote server: " + username);
            }
910
            username = username.substring(0, username.lastIndexOf("@"));
911 912
        }

913 914 915 916 917 918
        // Checks if it is in the cache
        if (userIDCache.containsKey(username)) {
            return userIDCache.get(username);
        }

        // Gets the user's ID from Clearspace
919 920 921 922
        try {
            String path = ClearspaceUserProvider.USER_URL_PREFIX + "users/" + username;
            Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path);

923 924 925 926 927
            Long id = Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID"));

            userIDCache.put(username, id);

            return id;
928 929 930 931
        } catch (UserNotFoundException unfe) {
            // It is a supported exception, throw it again
            throw unfe;
        } catch (Exception e) {
932
            // It is not a supported exception, wrap it into a UserNotFoundException
933 934 935 936
            throw new UserNotFoundException("Unexpected error", e);
        }
    }

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
    /**
     * Returns the Clearspace user id the user by JID.
     *
     * @param user JID of user to retrieve ID of.
     * @return The ID number of the user in Clearspace.
     * @throws org.jivesoftware.openfire.user.UserNotFoundException
     *          If the user was not found.
     */
    protected long getUserID(JID user) throws UserNotFoundException {
        // User's id are only for local users
        XMPPServer server = XMPPServer.getInstance();
        if (!server.isLocal(user)) {
            throw new UserNotFoundException("Cannot load user of remote server: " + user.toString());
        }
        String username = JID.unescapeNode(user.getNode());
        return getUserID(username);
    }

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    /**
     * Returns the Clearspace username of the user by id.
     *
     * @param id ID to retrieve Username of.
     * @return The username of the user in Clearspace.
     * @throws org.jivesoftware.openfire.user.UserNotFoundException
     *          If the user was not found.
     */
    protected String getUsernameByID(Long id) throws UserNotFoundException {
        // Checks if it is in the cache
        if (usernameCache.containsKey(id)) {
            return usernameCache.get(id);
        }

        // Gets the user's ID from Clearspace
        try {
            String path = ClearspaceUserProvider.USER_URL_PREFIX + "usersByID/" + id;
            Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path);

            String username = WSUtils.getElementText(element.selectSingleNode("return"), "username"); // TODO: is this right?

            usernameCache.put(id, username);

            return username;
        } catch (UserNotFoundException unfe) {
            // It is a supported exception, throw it again
            throw unfe;
        } catch (Exception e) {
            // It is not a supported exception, wrap it into a UserNotFoundException
            throw new UserNotFoundException("Unexpected error", e);
        }
    }

988 989
    /**
     * Returns the Clearspace group id of the group.
990
     *
991 992
     * @param groupname Name of the group to retrieve ID of.
     * @return The ID number of the group in Clearspace.
993 994
     * @throws org.jivesoftware.openfire.group.GroupNotFoundException
     *          If the group was not found.
995 996
     */
    protected long getGroupID(String groupname) throws GroupNotFoundException {
997 998 999
        if (groupIDCache.containsKey(groupname)) {
            return groupIDCache.get(groupname);
        }
1000 1001 1002 1003
        try {
            String path = ClearspaceGroupProvider.URL_PREFIX + "groups/" + groupname;
            Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path);

1004 1005 1006 1007 1008
            Long id = Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID"));
            // Saves it into the cache
            groupIDCache.put(groupname, id);

            return id;
1009 1010 1011 1012
        } catch (GroupNotFoundException gnfe) {
            // It is a supported exception, throw it again
            throw gnfe;
        } catch (Exception e) {
1013
            // It is not a supported exception, wrap it into a GroupNotFoundException
1014 1015 1016 1017
            throw new GroupNotFoundException("Unexpected error", e);
        }
    }

1018
    /**
1019
     * Returns true if a given JID belongs to a known Clearspace component domain.
1020 1021
     * @param address Address to check.
     * @return True if the specified address is a Clearspace component.
1022
     */
1023 1024
    public boolean isFromClearspace(JID address) {
        return clearspaces.contains(address.getDomain());
1025 1026
    }

1027
    /**
1028 1029
     * Sends an IQ packet to the Clearspace external component and returns the IQ packet
     * returned by CS or <tt>null</tt> if no answer was received before the specified
1030
     * timeout.
1031 1032 1033 1034
     *
     * @param packet IQ packet to send.
     * @param timeout milliseconds to wait before timing out.
     * @return IQ packet returned by Clearspace responsing the packet we sent.
1035
     */
1036 1037 1038 1039 1040 1041 1042 1043 1044
    public IQ query(final IQ packet, int timeout) {
        // Complain if FROM is empty
        if (packet.getFrom() == null) {
            throw new IllegalStateException("IQ packets with no FROM cannot be sent to Clearspace");
        }
        // If CS is not connected then return null
        if (clearspaces.isEmpty()) {
            return null;
        }
1045 1046 1047 1048 1049 1050 1051
        // Set the target address to the IQ packet. Roate list so we distribute load
        String component;
        synchronized (clearspaces) {
            component = clearspaces.get(0);
            Collections.rotate(clearspaces, 1);
        }
        packet.setTo(component);
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
        final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8);
        final IQRouter router = XMPPServer.getInstance().getIQRouter();
        router.addIQResultListener(packet.getID(), new IQResultListener() {
            public void receivedAnswer(IQ packet) {
                answer.offer(packet);
            }

            public void answerTimeout(String packetId) {
                Log.warn("No answer from Clearspace was received for IQ stanza: " + packet);
            }
        });
        XMPPServer.getInstance().getIQRouter().route(packet);
        IQ reply = null;
        try {
            reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            // Ignore
        }
        return reply;
    }

    public void componentRegistered(JID componentJID) {
        // Do nothing
    }

    public void componentUnregistered(JID componentJID) {
        // Remove stored information about this component
        clearspaces.remove(componentJID.getDomain());
    }

    public void componentInfoReceived(IQ iq) {
        // Check if it's a Clearspace component
        boolean isClearspace = false;
        Element childElement = iq.getChildElement();
        for (Iterator it = childElement.elementIterator("identity"); it.hasNext();) {
            Element identity = (Element)it.next();
            if ("component".equals(identity.attributeValue("category")) &&
                    "clearspace".equals(identity.attributeValue("type"))) {
                isClearspace = true;
            }
        }
        // If component is Clearspace then keep track of the component
        if (isClearspace) {
            clearspaces.add(iq.getFrom().getDomain());
1096 1097
            // Now send acknowledgement to Clearspace that we received its info
            acknowledgeInfoReceived(iq.getFrom());
1098
        }
1099 1100
    }

1101 1102 1103 1104 1105 1106 1107 1108 1109
    private void acknowledgeInfoReceived(JID infoSender) {
        IQ iq = new IQ();
        iq.setTo(infoSender);
        iq.setFrom(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
        iq.setID("component_info_recvd_" + StringUtils.randomString(3));
        iq.setChildElement("component-info-recvd", "http://jivesoftware.com/clearspace");
        getInstance().query(iq, 30000);
    }

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    /**
     * Returns a nonce generated by Clearspace to be used in a SSO login.
     *
     * @return a unique nonce.
     */
    public String getNonce() {
        try {
            String path = IM_URL_PREFIX + "generateNonce";
            Element element = executeRequest(GET, path);

            return WSUtils.getReturn(element);
        } catch (Exception e) {}

        return null;
    }

    /**
     * Generates a new nonce. The <code>isValidNonce</code> method will return
     * true when using nonces generated by this method.
     *
     * @return a unique nonce
     */
    public String generateNonce() {
        String nonce = String.valueOf(nonceGenerator.nextLong());
        nonceCache.put(nonce, System.currentTimeMillis());
        return nonce;
    }

    /**
     * Returns true if the nonce was generated usig <code>generateNonce</code>
     * and if this is the first check for that nonce.
     *
     * @param nonce the nonce to be checked
     * @return true if the nonce if the nonce was generated and this is the first check for that nonce
     */
    public boolean isValidNonce(String nonce) {
        Long time = nonceCache.remove(nonce);
        if (time == null) {
            return false;
        }
        return System.currentTimeMillis() - time < JiveConstants.MINUTE;
    }

1153 1154 1155 1156
    private class ConfigClearspaceTask extends TimerTask {

        public void run() {
            try {
1157
                Log.debug("Trying to configure Clearspace.");
1158
                doConfigClearspace();
1159
            } catch (UnauthorizedException e) {
1160
                Log.warn("Unauthorization problem trying to configure Clearspace, trying again in 1 minute", e);
1161
                // TODO: Mark that there is an authorization problem
1162
            } catch (Exception e) {
1163
                Log.warn("Unknown problem trying to configure Clearspace, trying again in 1 minute", e);
1164 1165 1166
            }
        }
    }
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192

    /**
     * Different kind of HTTP request types
     */
    public enum HttpType {

        /**
         * Represents an HTTP Get request. And it's equivalent to a SQL SELECTE.
         */
        GET,

        /**
         * Represents an HTTP Post request. And it's equivalent to a SQL UPDATE.
         */
        POST,

        /**
         * Represents an HTTP Delete request. And it's equivalent to a SQL DELETE.
         */
        DELETE,

        /**
         * Represents an HTTP Put requests.And it's equivalent to a SQL CREATE.
         */
        PUT
    }
1193
}