Esempio n. 1
0
  /** Loads the provider names from the jive properties config file. */
  private static void loadProviders() {
    if (factory == null) {
      // Use className as a convenient object to get a lock on.
      synchronized (classNames) {
        if (factory == null) {
          try {
            Class[] providers = new Class[classNames.length];
            for (int i = 0; i < classNames.length; i++) {
              // Convert XML based provider setup to Database based
              JiveGlobals.migrateProperty(propNames[i]);

              String className = classNames[i];
              // See if the classname has been set as a Jive property.
              String classNameProp = JiveGlobals.getProperty(propNames[i]);
              if (classNameProp != null) {
                className = classNameProp;
              }
              try {
                providers[i] = ClassUtils.forName(className);
              } catch (Exception e) {
                Log.error("Exception loading class: " + className, e);
              }
            }
            setProviders(providers);
          } catch (Exception e) {
            Log.error("Exception loading class: " + classNames, e);
          }
        }
      }
    }
  }
Esempio n. 2
0
 public static synchronized void addAgentSelectorClass(Class newClass)
     throws IllegalArgumentException {
   try {
     AgentSelector newAlgorithm = (AgentSelector) newClass.newInstance();
     // Make sure the interceptor isn't already in the list.
     List<AgentSelector> availableAgentSelectors = getAvailableAgentSelectors();
     for (AgentSelector algorithm : availableAgentSelectors) {
       if (newAlgorithm.getClass().equals(algorithm.getClass())) {
         return;
       }
     }
     // Add in the new algorithm
     availableAgentSelectors.add(newAlgorithm);
     // Write out new class names.
     JiveGlobals.deleteProperty("agentSelector.classes");
     for (int i = 0; i < availableAgentSelectors.size(); i++) {
       String cName = availableAgentSelectors.get(i).getClass().getName();
       JiveGlobals.setProperty("agentSelector.classes." + i, cName);
     }
   } catch (IllegalAccessException e) {
     throw new IllegalArgumentException(e.getMessage());
   } catch (InstantiationException e2) {
     throw new IllegalArgumentException(e2.getMessage());
   } catch (ClassCastException e5) {
     throw new IllegalArgumentException("Class is not a AgentSelector");
   }
 }
  static {
    String propertyValue = JiveGlobals.getProperty(JIVE_CROWD_GROUPS_CACHE_TTL_SECS);
    int ttl =
        (propertyValue == null || propertyValue.trim().length() == 0)
            ? CACHE_TTL
            : Integer.parseInt(propertyValue);

    crowdGroupSync.scheduleAtFixedRate(new GroupSynch(), 0, ttl, TimeUnit.SECONDS);

    JiveGlobals.setProperty(JIVE_CROWD_GROUPS_CACHE_TTL_SECS, String.valueOf(ttl));
  }
 /**
  * Returns <tt>null</tt> if the admin console will be available in all network interfaces of this
  * machine or a String representing the only interface where the admin console will be available.
  *
  * @return String representing the only interface where the admin console will be available or
  *     null if it will be available in all interfaces.
  */
 public String getBindInterface() {
   String adminInterfaceName = JiveGlobals.getXMLProperty("adminConsole.interface");
   String globalInterfaceName = JiveGlobals.getXMLProperty("network.interface");
   String bindInterface = null;
   if (adminInterfaceName != null && adminInterfaceName.trim().length() > 0) {
     bindInterface = adminInterfaceName;
   } else if (globalInterfaceName != null && globalInterfaceName.trim().length() > 0) {
     bindInterface = globalInterfaceName;
   }
   return bindInterface;
 }
Esempio n. 5
0
  static {
    String algorithm = JiveGlobals.getProperty("xmpp.socket.ssl.algorithm", "TLS");
    String storeType = JiveGlobals.getProperty("xmpp.socket.ssl.storeType", "jks");

    // Get the keystore location. The default location is security/keystore
    keyStoreLocation =
        JiveGlobals.getProperty(
            "xmpp.socket.ssl.keystore",
            "resources" + File.separator + "security" + File.separator + "keystore");
    keyStoreLocation = JiveGlobals.getHomeDirectory() + File.separator + keyStoreLocation;

    // Get the keystore password. The default password is "changeit".
    keypass = JiveGlobals.getProperty("xmpp.socket.ssl.keypass", "changeit");
    keypass = keypass.trim();

    // Get the truststore location; default at security/truststore
    trustStoreLocation =
        JiveGlobals.getProperty(
            "xmpp.socket.ssl.truststore",
            "resources" + File.separator + "security" + File.separator + "truststore");
    trustStoreLocation = JiveGlobals.getHomeDirectory() + File.separator + trustStoreLocation;

    // Get the truststore passwprd; default is "changeit".
    trustpass = JiveGlobals.getProperty("xmpp.socket.ssl.trustpass", "changeit");
    trustpass = trustpass.trim();

    try {
      keyStore = KeyStore.getInstance(storeType);
      keyStore.load(new FileInputStream(keyStoreLocation), keypass.toCharArray());

      trustStore = KeyStore.getInstance(storeType);
      trustStore.load(new FileInputStream(trustStoreLocation), trustpass.toCharArray());

      sslFactory =
          (SSLJiveServerSocketFactory)
              SSLJiveServerSocketFactory.getInstance(algorithm, keyStore, trustStore);
    } catch (Exception e) {
      Log.error(
          "SSLConfig startup problem.\n"
              + "  storeType: ["
              + storeType
              + "]\n"
              + "  keyStoreLocation: ["
              + keyStoreLocation
              + "]\n"
              + "  keypass: ["
              + keypass
              + "]\n"
              + "  trustStoreLocation: ["
              + trustStoreLocation
              + "]\n"
              + "  trustpass: ["
              + trustpass
              + "]",
          e);
      keyStore = null;
      trustStore = null;
      sslFactory = null;
    }
  }
  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 {
        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
            }
          }
        }
      } catch (SocketException e) {
        // We failed to discover a valid IP address where the admin console is running
        return null;
      }
    } else {
      bindInterfaces.add(bindInterface);
    }

    return bindInterfaces;
  }
 static {
   // Fill out the allowedIPs with the system property
   String allowed = JiveGlobals.getProperty("xmpp.client.login.allowed", "");
   StringTokenizer tokens = new StringTokenizer(allowed, ", ");
   while (tokens.hasMoreTokens()) {
     String address = tokens.nextToken().trim();
     allowedIPs.put(address, "");
   }
   String allowedAnonym = JiveGlobals.getProperty("xmpp.client.login.allowedAnonym", "");
   tokens = new StringTokenizer(allowedAnonym, ", ");
   while (tokens.hasMoreTokens()) {
     String address = tokens.nextToken().trim();
     allowedAnonymIPs.put(address, "");
   }
 }
Esempio n. 8
0
 void checkHealth() {
   // Check that the sending operation is still active
   if (writeStarted > -1
       && System.currentTimeMillis() - writeStarted
           > 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(writeStarted));
     }
     forceClose();
   } 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();
     }
   }
 }
Esempio n. 9
0
 /**
  * Forwards the received message to the list of users defined in the property
  * <b>xmpp.forward.admins</b>. The property may include bare JIDs or just usernames separated by
  * commas or white spaces. When using bare JIDs the target user may belong to a remote server.
  *
  * <p>If the property <b>xmpp.forward.admins</b> was not defined then the message will be sent to
  * all the users allowed to enter the admin console.
  *
  * @param packet the message to forward.
  */
 private void sendMessageToAdmins(Message packet) {
   String jids = JiveGlobals.getProperty("xmpp.forward.admins");
   if (jids != null && jids.trim().length() > 0) {
     // Forward the message to the users specified in the "xmpp.forward.admins" property
     StringTokenizer tokenizer = new StringTokenizer(jids, ", ");
     while (tokenizer.hasMoreTokens()) {
       String username = tokenizer.nextToken();
       Message forward = packet.createCopy();
       if (username.contains("@")) {
         // Use the specified bare JID address as the target address
         forward.setTo(username);
       } else {
         forward.setTo(username + "@" + serverName);
       }
       route(forward);
     }
   } else {
     // Forward the message to the users allowed to log into the admin console
     for (JID jid : XMPPServer.getInstance().getAdmins()) {
       Message forward = packet.createCopy();
       forward.setTo(jid);
       route(forward);
     }
   }
 }
Esempio n. 10
0
  /**
   * Returns a full JID based off of a username passed in.
   *
   * <p>If it already looks like a JID, returns what was passed in.
   *
   * @param username Username to turn into a JID.
   * @return Converted username.
   */
  public String generateFullJID(String username) {
    if (username.indexOf("@") > -1) {
      return username;
    }

    if (getTransport().getType().equals(TransportType.gtalk)) {
      return username + "@" + "gmail.com";
    } else if (getTransport().getType().equals(TransportType.facebook)) {
      return username + "@" + "chat.facebook.com";
    } else if (getTransport().getType().equals(TransportType.renren)) {
      return username + "@" + "renren.com";
    } else if (getTransport().getType().equals(TransportType.livejournal)) {
      return username + "@" + "livejournal.com";
    } else {
      String connecthost =
          JiveGlobals.getProperty(
              "plugin.gateway." + getTransport().getType() + ".connecthost",
              (getTransport().getType().equals(TransportType.gtalk)
                  ? "talk.google.com"
                  : getTransport().getType().equals(TransportType.facebook)
                      ? "chat.facebook.com"
                      : "jabber.org"));
      return username + "@" + connecthost;
    }
  }
Esempio n. 11
0
  public void initializePlugin(PluginManager manager, File pluginDirectory) {
    System.out.println("Starting Client Control Plugin");

    // Check if we Enterprise is installed and stop loading this plugin if found
    File pluginDir = new File(JiveGlobals.getHomeDirectory(), "plugins");
    File[] jars =
        pluginDir.listFiles(
            new FileFilter() {
              public boolean accept(File pathname) {
                String fileName = pathname.getName().toLowerCase();
                return (fileName.equalsIgnoreCase("enterprise.jar"));
              }
            });
    if (jars.length > 0) {
      // Do not load this plugin since Enterprise is still installed
      System.out.println("Enterprise plugin found. Stopping Client Control Plugin");
      throw new IllegalStateException("This plugin cannot run next to the Enterprise plugin");
    }

    taskEngine = TaskEngine.getInstance();
    sparkManager = new SparkManager(taskEngine);
    sparkManager.start();

    // Create and start the Spark version manager
    sparkVersionManager = new SparkVersionManager();
    sparkVersionManager.start();

    fileTransferFilterManager = new FileTransferFilterManager();
    fileTransferFilterManager.start();
  }
Esempio n. 12
0
  public static synchronized List<AgentSelector> getAvailableAgentSelectors() {
    List<AgentSelector> answer = new ArrayList<AgentSelector>();
    // First, add in built-in list of algorithms.
    for (Class newClass : getBuiltInAgentSelectorClasses()) {
      try {
        AgentSelector algorithm = (AgentSelector) newClass.newInstance();
        answer.add(algorithm);
      } catch (Exception e) {
        Log.error(e.getMessage(), e);
      }
    }

    // Now get custom algorithms.
    List<String> classNames = JiveGlobals.getProperties("agentSelector.classes");
    for (String className : classNames) {
      install_algorithm:
      try {
        Class algorithmClass = loadClass(className);
        // Make sure that the intercepter isn't already installed.
        for (AgentSelector agentSelector : answer) {
          if (algorithmClass.equals(agentSelector.getClass())) {
            break install_algorithm;
          }
        }
        AgentSelector algorithm = (AgentSelector) algorithmClass.newInstance();
        answer.add(algorithm);
      } catch (Exception e) {
        Log.error(e.getMessage(), e);
      }
    }
    return answer;
  }
  public NativeAuthProvider() {
    // Convert XML based provider setup to Database based
    JiveGlobals.migrateProperty("nativeAuth.domain");

    this.domain = JiveGlobals.getProperty("nativeAuth.domain");

    // Configure the library path so that we can load the shaj native library
    // from the Openfire lib directory.
    // Find the root path of this class.
    try {
      String binaryPath =
          (new URL(Shaj.class.getProtectionDomain().getCodeSource().getLocation(), "."))
              .openConnection()
              .getPermission()
              .getName();
      binaryPath = (new File(binaryPath)).getCanonicalPath();

      // Add the binary path to "java.library.path".
      String newLibPath = binaryPath + File.pathSeparator + System.getProperty("java.library.path");
      System.setProperty("java.library.path", newLibPath);
      Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
      fieldSysPath.setAccessible(true);
      fieldSysPath.set(System.class.getClassLoader(), null);
    } catch (Exception e) {
      Log.error(e);
    }

    // Configure Shaj to log output to the Openfire logger.
    com.cenqua.shaj.log.Log.Factory.setInstance(
        new com.cenqua.shaj.log.Log() {
          public boolean isDebug() {
            return Log.isDebugEnabled();
          }

          public void error(String string) {
            Log.error(string);
          }

          public void error(String string, Throwable throwable) {
            Log.error(string, throwable);
          }

          public void debug(String string) {
            Log.debug("NativeAuthProvider: " + string);
          }
        });
  }
  /** Save properties as Jive properties. */
  private void saveProperties() {

    JiveGlobals.setXMLProperty("database.defaultProvider.driver", driver);
    JiveGlobals.setXMLProperty("database.defaultProvider.serverURL", serverURL);
    JiveGlobals.setXMLProperty("database.defaultProvider.username", username);
    JiveGlobals.setXMLProperty("database.defaultProvider.password", password);
    JiveGlobals.setXMLProperty("database.defaultProvider.testSQL", testSQL);
    JiveGlobals.setXMLProperty("database.defaultProvider.testBeforeUse", testBeforeUse.toString());
    JiveGlobals.setXMLProperty("database.defaultProvider.testAfterUse", testAfterUse.toString());

    JiveGlobals.setXMLProperty(
        "database.defaultProvider.minConnections", Integer.toString(minConnections));
    JiveGlobals.setXMLProperty(
        "database.defaultProvider.maxConnections", Integer.toString(maxConnections));
    JiveGlobals.setXMLProperty(
        "database.defaultProvider.connectionTimeout", Double.toString(connectionTimeout));
  }
 /**
  * Sets the list of IP address that are allowed to connect to the server for anonymous users. If
  * the list is empty then anonymous will be only restricted by {@link #getAllowedIPs()}.
  *
  * @param allowed the list of IP address that are allowed to connect to the server.
  */
 public static void setAllowedAnonymIPs(Map<String, String> allowed) {
   allowedAnonymIPs = allowed;
   if (allowedAnonymIPs.isEmpty()) {
     JiveGlobals.deleteProperty("xmpp.client.login.allowedAnonym");
   } else {
     // Iterate through the elements in the map.
     StringBuilder buf = new StringBuilder();
     Iterator<String> iter = allowedAnonymIPs.keySet().iterator();
     if (iter.hasNext()) {
       buf.append(iter.next());
     }
     while (iter.hasNext()) {
       buf.append(", ").append(iter.next());
     }
     JiveGlobals.setProperty("xmpp.client.login.allowedAnonym", buf.toString());
   }
 }
Esempio n. 16
0
  /**
   * Initializes the server's security audit provider, based on configuration and defaults to
   * DefaultSecurityAuditProvider if the specified provider is not valid or not specified.
   */
  private void initProvider() {
    // Convert XML based provider setup to Database based
    JiveGlobals.migrateProperty("provider.securityAudit.className");

    String className =
        JiveGlobals.getProperty(
            "provider.securityAudit.className",
            "org.jivesoftware.openfire.security.DefaultSecurityAuditProvider");
    // Check if we need to reset the provider class
    if (provider == null || !className.equals(provider.getClass().getName())) {
      try {
        Class c = ClassUtils.forName(className);
        provider = (SecurityAuditProvider) c.newInstance();
      } catch (Exception e) {
        Log.error("Error loading security audit provider: " + className, e);
        provider = new DefaultSecurityAuditProvider();
      }
    }
  }
Esempio n. 17
0
 /**
  * Returns a username based off of a registered name (possible JID) passed in.
  *
  * <p>If it already looks like a username, returns what was passed in.
  *
  * @param regName Registered name to turn into a username.
  * @return Converted registered name.
  */
 public String generateUsername(String regName) {
   if (regName.equals("{PLATFORM}")) {
     return JiveGlobals.getProperty("plugin.gateway.facebook.platform.apikey")
         + "|"
         + JiveGlobals.getProperty("plugin.gateway.facebook.platform.apisecret");
   } else if (regName.indexOf("@") > -1) {
     if (getTransport().getType().equals(TransportType.gtalk)) {
       return regName;
     } else {
       return regName.substring(0, regName.indexOf("@"));
     }
   } else {
     if (getTransport().getType().equals(TransportType.gtalk)) {
       return regName + "@gmail.com";
     } else {
       return regName;
     }
   }
 }
  /**
   * Returns true if the principal is explicity authorized to the JID
   *
   * @param principal The autheticated principal requesting authorization.
   * @return The name of the default username to use.
   */
  @Override
  public String map(String principal) {
    if (principal.contains("@")) {
      String realm = principal.substring(principal.lastIndexOf('@') + 1);
      String username = principal.substring(0, principal.lastIndexOf('@'));

      if (realm.length() > 0) {
        if (realm.equals(JiveGlobals.getProperty("xmpp.domain"))) {
          Log.debug("DefaultAuthorizationMapping: realm = xmpp.domain");
          return username;
        } else if (realm.equals(JiveGlobals.getProperty("sasl.realm"))) {
          Log.debug("DefaultAuthorizationMapping: ream = sasl.realm");
          return username;
        } else {
          for (String approvedRealm : approvedRealms) {
            if (realm.equals(approvedRealm)) {
              Log.debug(
                  "DefaultAuthorizationMapping: realm ("
                      + realm
                      + ") = "
                      + approvedRealm
                      + " which is approved");
              return username;
            } else {
              Log.debug(
                  "DefaultAuthorizationPolicy: realm ("
                      + realm
                      + ") != "
                      + approvedRealm
                      + " which is approved");
            }
          }
        }
        Log.debug("DefaultAuthorizationMapping: No approved mappings found.");
        return principal;
      } else {
        Log.debug("DefaultAuthorizationMapping: Realm has no length");
      }
    } else {
      Log.debug("DefaultAuthorizationMapping: No realm found");
    }
    return principal;
  }
  public DefaultAuthorizationMapping() {
    approvedRealms = new Vector<>();

    String realmList = JiveGlobals.getProperty("sasl.approvedRealms");
    if (realmList != null) {
      StringTokenizer st = new StringTokenizer(realmList, " ,\t\n\r\f");
      while (st.hasMoreTokens()) {
        approvedRealms.add(st.nextToken());
      }
    }
  }
Esempio n. 20
0
 /** Check GMail for new mail. */
 @Override
 public void run() {
   if (getTransport().getType().equals(TransportType.gtalk)
       && JiveGlobals.getBooleanProperty("plugin.gateway.gtalk.mailnotifications", true)) {
     GoogleMailNotifyExtension gmne = new GoogleMailNotifyExtension();
     gmne.setNewerThanTime(listener.getLastGMailThreadDate());
     gmne.setNewerThanTid(listener.getLastGMailThreadId());
     conn.sendPacket(
         new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), gmne));
   }
 }
Esempio n. 21
0
  private DatabaseManager() {

    /*
     * Load time from globals if it is set. It represents the minutes the
     * log entries stay in database until they will get deleted
     */
    // TODO: Use PropertyEventListener to check if cleaner.minutes have
    // changed
    _dbCleanMinutes = JiveGlobals.getIntProperty("plugin.remoteroster.log.cleaner.minutes", 60);

    startDatabaseCleanLoop();
  }
Esempio n. 22
0
  public void startTLS(boolean clientMode, String remoteServer, ClientAuth authentication)
      throws Exception {
    boolean c2s = (remoteServer == null);
    KeyStore ksKeys = SSLConfig.getKeyStore();
    String keypass = SSLConfig.getKeyPassword();

    KeyStore ksTrust = (c2s ? SSLConfig.getc2sTrustStore() : SSLConfig.gets2sTrustStore());
    String trustpass = (c2s ? SSLConfig.getc2sTrustPassword() : SSLConfig.gets2sTrustPassword());
    if (c2s) Log.debug("NIOConnection: startTLS: using c2s");
    else Log.debug("NIOConnection: startTLS: using s2s");
    // KeyManager's decide which key material to use.
    KeyManager[] km = SSLJiveKeyManagerFactory.getKeyManagers(ksKeys, keypass);

    // TrustManager's decide whether to allow connections.
    TrustManager[] tm = SSLJiveTrustManagerFactory.getTrustManagers(ksTrust, trustpass);

    if (clientMode || authentication == ClientAuth.needed || authentication == ClientAuth.wanted) {
      // We might need to verify a certificate from our peer, so get different TrustManager[]'s
      if (c2s) {
        // Check if we can trust certificates presented by the client
        tm = new TrustManager[] {new ClientTrustManager(ksTrust)};
      } else {
        // Check if we can trust certificates presented by the server
        tm = new TrustManager[] {new ServerTrustManager(remoteServer, ksTrust, this)};
      }
    }

    String algorithm = JiveGlobals.getProperty(ConnectionSettings.Client.TLS_ALGORITHM, "TLS");
    SSLContext tlsContext = SSLContext.getInstance(algorithm);

    tlsContext.init(km, tm, null);

    SslFilter filter = new SslFilter(tlsContext);
    filter.setUseClientMode(clientMode);
    // Disable SSLv3 due to POODLE vulnerability.
    filter.setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"});
    if (authentication == ClientAuth.needed) {
      filter.setNeedClientAuth(true);
    } else if (authentication == ClientAuth.wanted) {
      // Just indicate that we would like to authenticate the client but if client
      // certificates are self-signed or have no certificate chain then we are still
      // good
      filter.setWantClientAuth(true);
    }
    ioSession.getFilterChain().addAfter(EXECUTOR_FILTER_NAME, TLS_FILTER_NAME, filter);
    ioSession.setAttribute(SslFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE);

    if (!clientMode) {
      // Indicate the client that the server is ready to negotiate TLS
      deliverRawText("<proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
    }
  }
 /**
  * Returns whether TLS is mandatory, optional or is disabled for clients. When TLS is mandatory
  * clients are required to secure their connections or otherwise their connections will be closed.
  * On the other hand, when TLS is disabled clients are not allowed to secure their connections
  * using TLS. Their connections will be closed if they try to secure the connection. in this last
  * case.
  *
  * @return whether TLS is mandatory, optional or is disabled.
  */
 public static SocketConnection.TLSPolicy getTLSPolicy() {
   // Set the TLS policy stored as a system property
   String policyName =
       JiveGlobals.getProperty("xmpp.client.tls.policy", Connection.TLSPolicy.optional.toString());
   SocketConnection.TLSPolicy tlsPolicy;
   try {
     tlsPolicy = Connection.TLSPolicy.valueOf(policyName);
   } catch (IllegalArgumentException e) {
     Log.error("Error parsing xmpp.client.tls.policy: " + policyName, e);
     tlsPolicy = Connection.TLSPolicy.optional;
   }
   return tlsPolicy;
 }
Esempio n. 24
0
  public String getMemoryData() {
    try {
      String port = JiveGlobals.getProperty("httpbind.port.plain", "7070");
      String host = XMPPServer.getInstance().getServerInfo().getHostname();
      String username = JiveGlobals.getProperty("jmxweb.admin.username", "admin");
      String password = JiveGlobals.getProperty("jmxweb.admin.password", "admin");

      URL url =
          new URL(
              "http://"
                  + username
                  + ":"
                  + password
                  + "@"
                  + host
                  + ":"
                  + port
                  + "/jolokia/read/java.lang:type=Memory/HeapMemoryUsage");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "HTTP Call Failed : HTTP error code : " + conn.getResponseCode());
      }
      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
      while ((line = br.readLine()) != null) {
        resultString.append(line);
      }
      Log.info("Memory data: " + resultString.toString());
      conn.disconnect();

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return resultString.toString();
  }
Esempio n. 25
0
 public ServerSocketReader(
     PacketRouter router,
     RoutingTable routingTable,
     String serverName,
     Socket socket,
     SocketConnection connection,
     boolean useBlockingMode) {
   super(router, routingTable, serverName, socket, connection, useBlockingMode);
   // Create a pool of threads that will process received packets. If more threads are
   // required then the command will be executed on the SocketReader process
   int coreThreads = JiveGlobals.getIntProperty("xmpp.server.processing.core.threads", 2);
   int maxThreads = JiveGlobals.getIntProperty("xmpp.server.processing.max.threads", 50);
   int queueSize = JiveGlobals.getIntProperty("xmpp.server.processing.queue", 50);
   threadPool =
       new ThreadPoolExecutor(
           coreThreads,
           maxThreads,
           60,
           TimeUnit.SECONDS,
           new LinkedBlockingQueue<Runnable>(queueSize),
           new ThreadPoolExecutor.CallerRunsPolicy());
 }
Esempio n. 26
0
  public Packet doAction(Packet packet) throws PacketRejectedException {
    SessionManager sessionManager = SessionManager.getInstance();
    ClientSession clientSession = sessionManager.getSession(packet.getFrom());
    Packet rejectPacket;
    String pfFrom = JiveGlobals.getProperty("pf.From", "packetfilter");

    if (packet instanceof Message) {
      Message in = (Message) packet.createCopy();
      if (clientSession != null && in.getBody() != null) {

        in.setFrom(new JID(pfFrom));
        String rejectMessage =
            JiveGlobals.getProperty(
                "pf.rejectMessage", "Your message was rejected by the packet filter");
        in.setBody(rejectMessage);
        in.setType(Message.Type.error);
        in.setTo(packet.getFrom());
        String rejectSubject = JiveGlobals.getProperty("pf.rejectSubject", "Rejected");
        in.setSubject(rejectSubject);
        clientSession.process(in);
      }

    } else if (packet instanceof Presence) {
      rejectPacket = new Presence();
      rejectPacket.setTo(packet.getFrom());
      rejectPacket.setError(PacketError.Condition.forbidden);

    } else if (packet instanceof IQ) {
      rejectPacket = new IQ();
      rejectPacket.setTo(packet.getFrom());
      rejectPacket.setError(PacketError.Condition.forbidden);
    }
    if (doLog()) {
      Log.info("Rejecting packet from " + packet.getFrom() + " to " + packet.getTo());
    }
    throw new PacketRejectedException();
  }
Esempio n. 27
0
  /** Constructs a new login limit manager. */
  private LoginLimitManager() {
    // Set up initial maps
    attemptsPerIP = new ConcurrentHashMap<String, Long>();
    attemptsPerUsername = new ConcurrentHashMap<String, Long>();

    // Max number of attempts per ip address that can be performed in given time frame (10 attempts
    // default)
    maxAttemptsPerIP = JiveGlobals.getLongProperty("adminConsole.maxAttemptsPerIP", 10);
    // Time frame before attempts per ip addresses are reset (15 minutes default)
    millisecondsBetweenPerIP =
        JiveGlobals.getLongProperty("adminConsole.perIPAttemptResetInterval", 900000);
    // Max number of attempts per username that can be performed in a given time frame (10 attempts
    // default)
    maxAttemptsPerUsername = JiveGlobals.getLongProperty("adminConsole.maxAttemptsPerUsername", 10);
    // Time frame before attempts per ip addresses are reset (15 minutes default)
    millisecondsBetweenPerUsername =
        JiveGlobals.getLongProperty("adminConsole.perUsernameAttemptResetInterval", 900000);
    // Set up per username attempt reset task
    TaskEngine.getInstance()
        .scheduleAtFixedRate(new PerUsernameTask(), 0, millisecondsBetweenPerUsername);
    // Set up per IP attempt reset task
    TaskEngine.getInstance()
        .scheduleAtFixedRate(new PerIPAddressTask(), 0, millisecondsBetweenPerIP);
  }
  private void init() {
    // Create a pool of threads that will process incoming packets.
    int maxThreads = JiveGlobals.getIntProperty("xmpp.manager.incoming.threads", 5);
    if (maxThreads < 1) {
      // Ensure that the max number of threads in the pool is at least 1
      maxThreads = 1;
    }
    threadPool =
        new ThreadPoolExecutor(
            maxThreads,
            maxThreads,
            60,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(),
            new ThreadPoolExecutor.CallerRunsPolicy());

    // Create a thread that will read and store DOM Elements.
    Thread thread =
        new Thread("Server Packet Reader") {
          public void run() {
            while (open) {
              Element doc;
              try {
                doc = reader.parseDocument().getRootElement();

                if (doc == null) {
                  // Stop reading the stream since the remote server has sent an end of
                  // stream element and probably closed the connection.
                  shutdown();
                } else {
                  // Queue task that process incoming stanzas
                  threadPool.execute(new ProcessStanzaTask(packetsHandler, doc));
                }
              } catch (IOException e) {
                Log.debug("Finishing Incoming Server Stanzas Reader.", e);
                shutdown();
              } catch (Exception e) {
                Log.error("Finishing Incoming Server Stanzas Reader.", e);
                shutdown();
              }
            }
          }
        };
    thread.setDaemon(true);
    thread.start();
  }
Esempio n. 29
0
 private GroupManager() {
   // Initialize caches.
   CacheManager.initializeCache("group", 128 * 1024);
   CacheManager.initializeCache("group member", 32 * 1024);
   groupCache = CacheManager.getCache("group");
   // Load a group provider.
   String className =
       JiveGlobals.getXMLProperty(
           "provider.group.className", "org.jivesoftware.wildfire.group.DefaultGroupProvider");
   try {
     Class c = ClassUtils.forName(className);
     provider = (GroupProvider) c.newInstance();
   } catch (Exception e) {
     Log.error("Error loading group provider: " + className, e);
     provider = new DefaultGroupProvider();
   }
 }
Esempio n. 30
0
  private void deliverRawText(String text, boolean asynchronous) {
    if (!isClosed()) {
      boolean errorDelivering = false;
      IoBuffer buffer = IoBuffer.allocate(text.length());
      buffer.setAutoExpand(true);
      try {
        // Charset charset = Charset.forName(CHARSET);
        // buffer.putString(text, charset.newEncoder());
        buffer.put(text.getBytes(CHARSET));
        if (flashClient) {
          buffer.put((byte) '\0');
        }
        buffer.flip();
        ioSessionLock.lock();
        try {
          if (asynchronous) {
            // OF-464: handle dropped connections (no backupDeliverer in this case?)
            if (!ioSession.isConnected()) {
              throw new IOException("Connection reset/closed by peer");
            }
            ioSession.write(buffer);
          } else {
            // Send stanza and wait for ACK (using a 2 seconds default timeout)
            boolean ok =
                ioSession
                    .write(buffer)
                    .awaitUninterruptibly(
                        JiveGlobals.getIntProperty("connection.ack.timeout", 2000));
            if (!ok) {
              Log.warn("No ACK was received when sending stanza to: " + this.toString());
            }
          }
        } finally {
          ioSessionLock.unlock();
        }
      } catch (Exception e) {
        Log.debug("Error delivering raw text:\n" + text, e);
        errorDelivering = true;
      }

      // Close the connection if delivering text fails and we are already not closing the connection
      if (errorDelivering && asynchronous) {
        close();
      }
    }
  }