org.jivesoftware.util.JiveGlobals Java Examples

The following examples show how to use org.jivesoftware.util.JiveGlobals. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoteServerManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the remote server with the specified domain can connect to the
 * local server.
 *
 * @param domain the domain of the remote server.
 * @return true if the remote server with the specified domain can connect to the
 *         local server.
 */
public static boolean canAccess(String domain) {
    // If s2s is disabled then it is not possible to send packets to remote servers or
    // receive packets from remote servers
    if (!JiveGlobals.getBooleanProperty(ConnectionSettings.Server.SOCKET_ACTIVE, true)) {
        return false;
    }

    // By default there is no permission defined for the XMPP entity
    Permission permission = null;

    RemoteServerConfiguration config = getConfiguration(domain);
    if (config != null) {
        permission = config.getPermission();
    }

    if (PermissionPolicy.blacklist == getPermissionPolicy()) {
        // Anyone can access except those entities listed in the blacklist
        return Permission.blocked != permission;
    }
    else {
        // Access is limited to those present in the whitelist
        return Permission.allowed == permission;
    }
}
 
Example #2
Source File: ConnectionListener.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Configuresif self-signed peer certificates can be used to establish an encrypted connection.
 *
 * @param accept true when self-signed certificates are accepted, otherwise false.
 */
public void setAcceptSelfSignedCertificates( boolean accept )
{
    final boolean oldValue = verifyCertificateValidity();

    // Always set the property explicitly even if it appears the equal to the old value (the old value might be a fallback value).
    JiveGlobals.setProperty( type.getPrefix() + "certificate.accept-selfsigned", Boolean.toString( accept ) );

    if ( oldValue == accept )
    {
        Log.debug( "Ignoring self-signed certificate acceptance policy change request (to '{}'): listener already in this state.", accept );
        return;
    }

    Log.debug( "Changing self-signed certificate acceptance policy from '{}' to '{}'.", oldValue, accept );
    restart();
}
 
Example #3
Source File: PluginManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the first few bytes of the input stream correspond to any of the known 'magic numbers' that
 * are known to represent a JAR archive.
 *
 * This method uses the mark/reset functionality of InputStream. This ensures that the input stream is reset
 * back to its original position after execution of this method.
 *
 * @param bin The input to read (cannot be null).
 * @return true if the stream first few bytes are equal to any of the known magic number sequences, otherwise false.
 */
public static boolean validMagicNumbers( final BufferedInputStream bin ) throws IOException
{
    final List<String> validMagicBytesCollection = JiveGlobals.getListProperty( "plugins.upload.magic-number.values.expected-value", Arrays.asList( "504B0304", "504B0506", "504B0708" ) );
    for ( final String entry : validMagicBytesCollection )
    {
        final byte[] validMagicBytes = StringUtils.decodeHex( entry );
        bin.mark( validMagicBytes.length );
        try
        {
            final byte[] magicBytes = new byte[validMagicBytes.length];
            final int bytesRead = IOUtils.read( bin, magicBytes );
            if ( bytesRead == validMagicBytes.length && Arrays.equals( validMagicBytes, magicBytes ) )
            {
                return true;
            }
        }
        finally
        {
            bin.reset();
        }
    }

    return false;
}
 
Example #4
Source File: LocalClientSession.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the list of IP address that are allowed to connect to the server. If the list is empty then anyone not on
 * {@link #getBlacklistedIPs()} is  allowed to connect to the server except for anonymous users that are subject to
 * {@link #getWhitelistedAnonymousIPs()}. This list is used for both anonymous and non-anonymous users.
 *
 * Note that blacklisting takes precedence over whitelisting: if an address is matched by both, access is denied.
 *
 * @param allowed the list of IP address that are allowed to connect to the server. Can be empty, but not null.
 */
public static void setWhitelistedIPs(Set<String> allowed) {
    if (allowed == null) {
        throw new NullPointerException();
    }
    allowedIPs = allowed;
    if (allowedIPs.isEmpty()) {
        JiveGlobals.deleteProperty(ConnectionSettings.Client.LOGIN_ALLOWED);
    }
    else {
        // Iterate through the elements in the map.
        StringBuilder buf = new StringBuilder();
        Iterator<String> iter = allowedIPs.iterator();
        if (iter.hasNext()) {
            buf.append(iter.next());
        }
        while (iter.hasNext()) {
            buf.append(", ").append(iter.next());
        }
        JiveGlobals.setProperty(ConnectionSettings.Client.LOGIN_ALLOWED, buf.toString());
    }
}
 
Example #5
Source File: CrowdProperties.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public CrowdProperties() throws IOException {
    props = new Properties();
    
    File file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf" + File.separator + "crowd.properties");
    if (!file.exists()) {
        throw new IOException("The file crowd.properties is missing from Openfire conf folder");
    } else {
        try {
            props.load(new FileInputStream(file));
        } catch (IOException ioe) {
            throw new IOException("Unable to load crowd.properties file");
        }
    }
    
    // checking for required info in file
    if (StringUtils.isBlank(props.getProperty(APPLICATION_NAME))
            || StringUtils.isBlank(props.getProperty(APPLICATION_PASSWORD))
            || StringUtils.isBlank(props.getProperty(CROWD_SERVER_URL))) {
        
        throw new IOException("crowd.properties is missing required information (app name, app passwd, crowd url)");
    }
}
 
Example #6
Source File: SessionManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void stop() {
    Log.debug("SessionManager: Stopping server");
    // Stop threads that are sending packets to remote servers
    OutgoingSessionPromise.getInstance().shutdown();
    if (JiveGlobals.getBooleanProperty("shutdownMessage.enabled")) {
        sendServerMessage(null, LocaleUtils.getLocalizedString("admin.shutdown.now"));
    }
    localSessionManager.stop();
    serverName = null;

    try
    {
        // Purge our own components from the cache for the benefit of other cluster nodes.
        CacheUtil.removeValueFromMultiValuedCache( componentSessionsCache, XMPPServer.getInstance().getNodeID() );
    }
    catch ( Exception e )
    {
        Log.warn( "An exception occurred while trying to remove locally connected external components from the clustered cache. Other cluster nodes might continue to see our external components, even though we this instance is stopping.", e );
    }
}
 
Example #7
Source File: HttpSessionManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Starts the services used by the HttpSessionManager.
 *
 * (Re)creates and configures a pooled executor to handle async routing for incoming packets with a configurable
 * (through property "xmpp.httpbind.worker.threads") amount of threads; also uses an unbounded task queue and
 * configurable ("xmpp.httpbind.worker.timeout") keep-alive.
 *
 * Note: Apart from the processing threads configured in this class, the server also uses a threadpool to perform
 * the network IO (as configured in ({@link HttpBindManager}). BOSH installations expecting heavy loads may want to
 * allocate additional threads to this worker pool to ensure timely delivery of inbound packets
 */
public void start() {
    Log.info( "Starting instance" );

    this.sessionManager = SessionManager.getInstance();

    final int maxClientPoolSize = JiveGlobals.getIntProperty( "xmpp.client.processing.threads", 8 );
    final int maxPoolSize = JiveGlobals.getIntProperty("xmpp.httpbind.worker.threads", maxClientPoolSize );
    final int keepAlive = JiveGlobals.getIntProperty( "xmpp.httpbind.worker.timeout", 60 );
    final int sessionCleanupCheck = JiveGlobals.getIntProperty("xmpp.httpbind.worker.cleanupcheck", 30);

    sendPacketPool = new ThreadPoolExecutor(getCorePoolSize(maxPoolSize), maxPoolSize, keepAlive, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), // unbounded task queue
            new NamedThreadFactory( "httpbind-worker-", true, null, Thread.currentThread().getThreadGroup(), null )
    );

    sendPacketPool.prestartCoreThread();

    // Periodically check for Sessions that need a cleanup.
    inactivityTask = new HttpSessionReaper();
    TaskEngine.getInstance().schedule( inactivityTask, 30 * JiveConstants.SECOND, sessionCleanupCheck * JiveConstants.SECOND);
}
 
Example #8
Source File: PropertyBasedUserProviderMapper.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public UserProvider getUserProvider( String username )
{
    for ( final Map.Entry<String, UserProvider> entry : providersByPrefix.entrySet() )
    {
        final String usersProperty = JiveGlobals.getProperty( entry.getKey() + ".members.propertyName" );
        if ( usersProperty != null )
        {
            final List<String> usersInSet = JiveGlobals.getListProperty( usersProperty, Collections.<String>emptyList() );
            if ( usersInSet.contains( username ) )
            {
                return entry.getValue();
            }
        }
    }

    return fallbackProvider;
}
 
Example #9
Source File: UserMultiProvider.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a UserProvider based on a property value (that is expected to be a class name). When the property
 * is not set, this method returns null. When the property is set, but an exception occurs while instantiating
 * the class, this method logs the error and returns null.
 *
 * UserProvider classes are required to have a public, no-argument constructor.
 *
 * @param propertyName A property name (cannot ben ull).
 * @return A user provider (can be null).
 */
public static UserProvider instantiate( String propertyName )
{
    final String className = JiveGlobals.getProperty( propertyName );
    if ( className == null )
    {
        Log.debug( "Property '{}' is undefined. Skipping.", propertyName );
        return null;
    }
    Log.debug( "About to to instantiate an UserProvider '{}' based on the value of property '{}'.", className, propertyName );
    try
    {
        final Class c = ClassUtils.forName( className );
        final UserProvider provider = (UserProvider) c.newInstance();
        Log.debug( "Instantiated UserProvider '{}'", className );
        return provider;
    }
    catch ( Exception e )
    {
        Log.error( "Unable to load UserProvider '{}'. Users in this provider will be disabled.", className, e );
        return null;
    }
}
 
Example #10
Source File: PropertyBasedAuthProviderMapper.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public PropertyBasedAuthProviderMapper()
{
    // Migrate properties.
    JiveGlobals.migratePropertyTree( "propertyBasedAuthMapper" );

    // Instantiate the fallback provider
    fallbackProvider = instantiateProvider( "propertyBasedAuthMapper.fallbackProvider.className" );
    if ( fallbackProvider == null )
    {
        throw new IllegalStateException( "Expected a AuthProvider class name in property 'propertyBasedAuthMapper.fallbackProvider.className'" );
    }
    // Instantiate all sets
    final List<String> setProperties = JiveGlobals.getPropertyNames( "propertyBasedAuthMapper.set" );
    for ( final String setProperty : setProperties )
    {
        final AuthProvider provider = instantiateProvider( setProperty + ".provider.className" );
        if ( provider == null )
        {
            throw new IllegalStateException( "Expected a AuthProvider class name in property '" + setProperty + ".provider.className'" );
        }

        providersByPrefix.put( setProperty, provider );
    }
}
 
Example #11
Source File: HttpBindServlet.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void handleSessionRequest(AsyncContext context, HttpBindBody body)
        throws IOException
{
    final String sid = body.getSid();
    if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
        Log.info("HTTP RECV(" + sid + "): " + body.asXML());
    }

    HttpSession session = sessionManager.getSession(sid);
    if (session == null) {
        if (Log.isDebugEnabled()) {
            Log.debug("Client provided invalid session: " + sid + ". [" +
                context.getRequest().getRemoteAddr() + "]");
        }
        sendLegacyError(context, BoshBindingError.itemNotFound, "Invalid SID value.");
        return;
    }

    synchronized (session) {
        try {
            session.forwardRequest(body, context);
        }
        catch (HttpBindException e) {
            sendError(session, context, e.getBindingError());
        }
        catch (HttpConnectionClosedException nc) {
            Log.error("Error sending packet to client.", nc);
            context.complete();
        }
    }
}
 
Example #12
Source File: SessionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(XMPPServer server) {
    super.initialize(server);
    this.server = server;
    router = server.getPacketRouter();
    userManager = server.getUserManager();
    routingTable = server.getRoutingTable();
    serverName = server.getServerInfo().getXMPPDomain();
    serverAddress = new JID(serverName);

    if (JiveGlobals.getBooleanProperty("xmpp.audit.active")) {
        streamIDFactory = new AuditStreamIDFactory();
    }
    else {
        streamIDFactory = new BasicStreamIDFactory();
    }

    // Initialize caches.
    componentSessionsCache = CacheFactory.createCache(COMPONENT_SESSION_CACHE_NAME);
    multiplexerSessionsCache = CacheFactory.createCache(CM_CACHE_NAME);
    incomingServerSessionsCache = CacheFactory.createCache(ISS_CACHE_NAME);
    hostnameSessionsCache = CacheFactory.createCache(HOSTNAME_SESSIONS_CACHE_NAME);
    validatedDomainsCache = CacheFactory.createCache(VALIDATED_DOMAINS_CACHE_NAME);
    sessionInfoCache = CacheFactory.createCache(C2S_INFO_CACHE_NAME);

    // Listen to cluster events
    ClusterManager.addListener(this);
}
 
Example #13
Source File: XMPPServer.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void finalSetupSteps() {
    for (String propName : JiveGlobals.getXMLPropertyNames()) {
        if (!XML_ONLY_PROPERTIES.contains(propName)) {
            if (JiveGlobals.getProperty(propName) == null) {
                JiveGlobals.setProperty(propName, JiveGlobals.getXMLProperty(propName));
            }
            JiveGlobals.setPropertyEncrypted(propName, JiveGlobals.isXMLPropertyEncrypted(propName));
        }
    }

    // Check if keystore (that out-of-the-box is a fallback for all keystores) already has certificates for current domain.
    CertificateStoreManager certificateStoreManager = null; // Will be a module after finishing setup.
    try {
        certificateStoreManager = new CertificateStoreManager();
        certificateStoreManager.initialize( this );
        certificateStoreManager.start();
        final IdentityStore identityStore = certificateStoreManager.getIdentityStore( ConnectionType.SOCKET_C2S );
        identityStore.ensureDomainCertificate();

    } catch (Exception e) {
        logger.error("Error generating self-signed certificates", e);
    } finally {
        if (certificateStoreManager != null)
        {
            certificateStoreManager.stop();
            certificateStoreManager.destroy();
        }
    }

    // Initialize list of admins now (before we restart Jetty)
    AdminManager.getInstance().getAdminAccounts();
}
 
Example #14
Source File: GcmPlugin.java    From Openfire-GCM with Apache License 2.0 5 votes vote down vote up
public boolean getDebug() {
	if(JiveGlobals.getProperty(DEBUG, GcmPlugin.DEBUG_OFF).equalsIgnoreCase(GcmPlugin.DEBUG_ON)){
		return true;
	} else {
		return false;
	}
}
 
Example #15
Source File: HttpSession.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public HttpSession(PacketDeliverer backupDeliverer, String serverName,
                   StreamID streamID, HttpConnection connection, Locale language) throws UnknownHostException
{
    super(serverName, new HttpVirtualConnection(connection.getRemoteAddr(), ConnectionType.SOCKET_C2S), streamID, language);
    this.isClosed = false;
    this.lastActivity = System.currentTimeMillis();
    this.lastRequestID = connection.getRequestId();
    this.backupDeliverer = backupDeliverer;
    this.sslCertificates = connection.getPeerCertificates();
    if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
        Log.info("Session " + getStreamID() + " being opened with initial connection " +
                connection.toString());
    }
}
 
Example #16
Source File: LdapAuthProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public LdapAuthProvider() {
    // Convert XML based provider setup to Database based
    JiveGlobals.migrateProperty("ldap.authCache.enabled");

    manager = LdapManager.getInstance();
    if (JiveGlobals.getBooleanProperty("ldap.authCache.enabled", false)) {
        String cacheName = "LDAP Authentication";
        authCache = CacheFactory.createCache(cacheName);
    }
}
 
Example #17
Source File: ConnectionManagerImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the specific network interface on which Openfire is configured to listen, or null when no such preference
 * has been configured.
 *
 * @return A network interface or null.
 * @throws UnknownHostException When the configured network name cannot be resolved.
 */
public InetAddress getListenAddress() throws UnknownHostException
{
    String interfaceName = JiveGlobals.getXMLProperty( "network.interface" );
    InetAddress bindInterface = null;
    if (interfaceName != null) {
        if (interfaceName.trim().length() > 0) {
            bindInterface = InetAddress.getByName(interfaceName);
        }
    }
    return bindInterface;
}
 
Example #18
Source File: OFMeetConfig.java    From openfire-ofmeet-plugin with Apache License 2.0 5 votes vote down vote up
public void setStunMappingHarversterAddresses( List<String> addresses )
{
    if (addresses == null || addresses.isEmpty() )
    {
        JiveGlobals.deleteProperty( "org.ice4j.ice.harvest.STUN_MAPPING_HARVESTER_ADDRESSES" );
    }
    else
    {
        JiveGlobals.setProperty( "org.ice4j.ice.harvest.STUN_MAPPING_HARVESTER_ADDRESSES", addresses );
    }
}
 
Example #19
Source File: OfflineMessageStrategy.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void setType(OfflineMessageStrategy.Type type) {
    if (type == null) {
        throw new IllegalArgumentException();
    }
    OfflineMessageStrategy.type = type;
    JiveGlobals.setProperty("xmpp.offline.type", type.toString());
}
 
Example #20
Source File: CrowdUserProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public CrowdUserProvider() {
    String propertyValue = JiveGlobals.getProperty(JIVE_CROWD_USERS_CACHE_TTL_SECS);
    int ttl = (propertyValue == null || propertyValue.trim().length() == 0) ? CACHE_TTL : Integer.parseInt(propertyValue);
    
    crowdUserSync.scheduleAtFixedRate(new UserSynch(this), 0, ttl, TimeUnit.SECONDS);
    
    JiveGlobals.setProperty(JIVE_CROWD_USERS_CACHE_TTL_SECS, String.valueOf(ttl));
    
    // workaround to load the sync of groups with crowd
    new CrowdGroupProvider();
}
 
Example #21
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private HttpBindManager() {
    JiveGlobals.migrateProperty(HTTP_BIND_ENABLED);
    JiveGlobals.migrateProperty(HTTP_BIND_PORT);
    JiveGlobals.migrateProperty(HTTP_BIND_SECURE_PORT);
    JiveGlobals.migrateProperty(HTTP_BIND_THREADS);
    JiveGlobals.migrateProperty(HTTP_BIND_FORWARDED);
    JiveGlobals.migrateProperty(HTTP_BIND_FORWARDED_FOR);
    JiveGlobals.migrateProperty(HTTP_BIND_FORWARDED_SERVER);
    JiveGlobals.migrateProperty(HTTP_BIND_FORWARDED_HOST);
    JiveGlobals.migrateProperty(HTTP_BIND_FORWARDED_HOST_NAME);
    JiveGlobals.migrateProperty(HTTP_BIND_CORS_ENABLED);
    JiveGlobals.migrateProperty(HTTP_BIND_CORS_ALLOW_ORIGIN);
    JiveGlobals.migrateProperty(HTTP_BIND_REQUEST_HEADER_SIZE);

    PropertyEventDispatcher.addListener( this );
    this.httpSessionManager = new HttpSessionManager();

    // setup the cache for the allowed origins
    this.setupAllowedOriginsMap();

    // Setup the default handlers. Order is important here. First, evaluate if the 'standard' handlers can be used to fulfill requests.
    this.handlerList.addHandler( createBoshHandler() );
    this.handlerList.addHandler( createWebsocketHandler() );
    this.handlerList.addHandler( createCrossDomainHandler() );

    // When standard handling does not apply, see if any of the handlers in the extension pool of handlers applies to the request.
    this.handlerList.addHandler( this.extensionHandlers );

    // When everything else fails, use the static content handler. This one should be last, as it is mapping to the root context.
    // This means that it will catch everything and prevent the invocation of later handlers.
    final Handler staticContentHandler = createStaticContentHandler();
    if ( staticContentHandler != null )
    {
        this.handlerList.addHandler( staticContentHandler );
    }
}
 
Example #22
Source File: FileTransferProxy.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize( XMPPServer server )
{
    super.initialize(server);

    proxyServiceName = JiveGlobals.getProperty("xmpp.proxy.service", "proxy");
    routingTable = server.getRoutingTable();
    router = server.getPacketRouter();

    connectionManager = new ProxyConnectionManager(getFileTransferManager(server));
}
 
Example #23
Source File: ConnectionManagerImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the specific network interface on which the Openfire administration
 * console should be configured to listen, or null when no such preference
 * has been configured.
 *
 * @return A network interface or null.
 * @throws UnknownHostException When the configured network name cannot be resolved.
 */
public InetAddress getAdminConsoleListenAddress() throws UnknownHostException
{
    String acInterfaceName = JiveGlobals.getXMLProperty( "adminConsole.interface" );
    InetAddress acBindInterface = null;
    if (acInterfaceName != null) {
        if (acInterfaceName.trim().length() > 0) {
            acBindInterface = InetAddress.getByName(acInterfaceName);
        }
    }
    return acBindInterface;
}
 
Example #24
Source File: ConnectionListener.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Defines the collection of cipher suite (by name) that can be used for encryption of connections.
 *
 * When non-empty, the list is intended to specify those cipher suites (from a larger collection of implementation-
 * supported cipher suites) that can be used to establish encryption. An empty list will cause an implementation
 * default to be used.
 *
 * The order over which values are presented can, but is not guaranteed to, indicate preference.
 *
 * @param cipherSuites An array of cipher suite names, can be null.
 */
public void setEncryptionCipherSuites( String[] cipherSuites )
{
    if ( cipherSuites == null) {
        cipherSuites = new String[0];
    }
    final String oldValue = getEncryptionCipherSuitesCommaSeparated();

    // Always set the property explicitly even if it appears the equal to the old value (the old value might be a fallback value).
    final StringBuilder csv = new StringBuilder();
    for( String cipherSuite : cipherSuites )
    {
        csv.append( cipherSuite );
        csv.append( ',' );
    }
    final String newValue = csv.length() > 0 ? csv.substring( 0, csv.length() - 1 ) : "";
    JiveGlobals.setProperty( type.getPrefix() + "ciphersuites", newValue );

    if ( oldValue.equals( newValue ) )
    {
        Log.debug( "Ignoring cipher suite configuration change request (to '{}'): listener already in this state.", newValue );
        return;
    }

    Log.debug( "Changing cipher suite configuration from '{}' to '{}'.", oldValue, newValue );
    restart();
}
 
Example #25
Source File: DNSUtil.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a sorted list of host names and ports that the specified XMPP
 * domain can be reached at for server-to-server communication.
 *
 * DNS lookups for a SRV records in the form "_xmpp-server._tcp.example.com"
 * and "_xmpps-server._tcp.example.com" are attempted, in line with section
 * 3.2 of XMPP Core and XEP-0368.
 *
 * If those lookup fail to provide any records, a lookup in the older form
 * of "_jabber._tcp.example.com" is attempted since servers that implement
 * an older version of the protocol may be listed using that notation.
 *
 * If that lookup fails as well, it's assumed that the XMPP server lives at
 * the host resolved by a DNS A lookup at the specified domain on the
 * specified default port.<p>
 *
 * As an example, a lookup for "example.com" may return "im.example.com:5269".
 *
 * @param domain the domain.
 * @param defaultPort default port to return if the DNS look up fails.
 * @return a list of  HostAddresses, which encompasses the hostname and port
 *         that the XMPP server can be reached at for the specified domain.
 * @see <a href="https://tools.ietf.org/html/rfc6120#section-3.2">XMPP CORE</a>
 * @see <a href="https://xmpp.org/extensions/xep-0368.html">XEP-0368</a>
 */
public static List<HostAddress> resolveXMPPDomain(String domain, int defaultPort) {
    // Check if there is an entry in the internal DNS for the specified domain
    List<HostAddress> results = new LinkedList<>();
    if (dnsOverride != null) {
        HostAddress hostAddress = dnsOverride.get(domain);
        if (hostAddress == null) {
            hostAddress = dnsOverride.get("*");
        }
        if (hostAddress != null) {
            results.add(hostAddress);
            return results;
        }
    }

    // Attempt the SRV lookup.
    final List<WeightedHostAddress> srvLookups = new LinkedList<>();
    srvLookups.addAll(srvLookup("xmpp-server", "tcp", domain ) );

    final boolean allowTLS = JiveGlobals.getBooleanProperty(ConnectionSettings.Server.TLS_ENABLED, true);
    if (allowTLS) {
        srvLookups.addAll(srvLookup("xmpps-server", "tcp", domain));
    }
    if (!srvLookups.isEmpty()) {
        // we have to re-prioritize the combination of both lookups.
        results.addAll( prioritize( srvLookups.toArray( new WeightedHostAddress[0] ) ) );
    }

    if (results.isEmpty()) {
        results.addAll(srvLookup( "jabber", "tcp", domain ) );
    }

    // Use domain and default port as fallback.
    if (results.isEmpty()) {
        results.add(new HostAddress(domain, defaultPort, false));
    }
    return results;
}
 
Example #26
Source File: IQRegisterHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void setInbandRegEnabled(boolean allowed)
{
    if ( allowed && UserManager.getUserProvider().isReadOnly() )
    {
        Log.warn( "Enabling in-band registration has no effect, as the user provider for this system is read-only." );
    }
    registrationEnabled = allowed;
    JiveGlobals.setProperty("register.inband", registrationEnabled ? "true" : "false");
}
 
Example #27
Source File: CertificateStoreManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * The location (relative to OPENFIRE_HOME) of the directory that holds backups for identity stores.
 *
 * @param type the connection type
 * @return a path (never null).
 */
public static String getIdentityStoreBackupDirectory( ConnectionType type )
{
    final String propertyName = type.getPrefix()  + "backup.keystore.location";
    final String defaultValue = "resources" + File.separator + "security" + File.separator + "archive" + File.separator;

    if ( type.getFallback() == null )
    {
        return JiveGlobals.getProperty( propertyName, defaultValue ).trim();
    }
    else
    {
        return JiveGlobals.getProperty( propertyName, getIdentityStoreBackupDirectory( type.getFallback() ) ).trim();
    }
}
 
Example #28
Source File: GroupBasedAdminProviderTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    Fixtures.clearExistingProperties();
    GroupManager.GROUP_PROVIDER.setValue(TestGroupProvider.class);
    mockGroupName = "mock-group-name";
    JiveGlobals.setProperty("provider.group.groupBasedAdminProvider.groupName", mockGroupName);
    mockGroup = mock(Group.class);
    doReturn(ADMINS).when(mockGroup).getMembers();
    adminProvider = new GroupBasedAdminProvider();
}
 
Example #29
Source File: SocketConnection.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the socket was closed due to a bad health. The socket is considered to
 * be in a bad state if a thread has been writing for a while and the write operation has
 * not finished in a long time or when the client has not sent a heartbeat for a long time.
 * In any of both cases the socket will be closed.
 *
 * @return true if the socket was closed due to a bad health.s
 */
boolean checkHealth() {
    // Check that the sending operation is still active
    long writeTimestamp = writeStarted;
    if (writeTimestamp > -1 && System.currentTimeMillis() - writeTimestamp >
            JiveGlobals.getIntProperty("xmpp.session.sending-limit", 60000)) {
        // Close the socket
        if (Log.isDebugEnabled()) {
            Log.debug("Closing connection: " + this + " that started sending data at: " +
                    new Date(writeTimestamp));
        }
        forceClose();
        return true;
    }
    else {
        // Check if the connection has been idle. A connection is considered idle if the client
        // has not been receiving data for a period. Sending data to the client is not
        // considered as activity.
        if (idleTimeout > -1 && socketReader != null &&
                System.currentTimeMillis() - socketReader.getLastActive() > idleTimeout) {
            // Close the socket
            if (Log.isDebugEnabled()) {
                Log.debug("Closing connection that has been idle: " + this);
            }
            forceClose();
            return true;
        }
    }
    return false;
}
 
Example #30
Source File: ConnectionListener.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sets whether compression is optional or disabled for new connections. This configuration change is persisted.
 *
 * If the listener is currently enabled, this configuration change will be applied immediately (which will cause a
 * restart of the underlying connection acceptor).
 *
 * An invocation of this method has no effect if the new policy value is equal to the existing value.
 *
 * @param policy a compression policy (not null).
 */
public void setCompressionPolicy( Connection.CompressionPolicy policy )
{
    final Connection.CompressionPolicy oldPolicy = getCompressionPolicy();
    if ( oldPolicy.equals( policy ) )
    {
        Log.debug( "Ignoring Compression Policy change request (to '{}'): listener already in this state.", policy );
        return;
    }

    Log.debug( "Changing Compression Policy from '{}' to '{}'.", oldPolicy, policy );
    JiveGlobals.setProperty( compressionPolicyPropertyName, policy.toString() );
    restart();
}