Ejemplo n.º 1
0
  protected ServerSocket createSocket(URI uri)
      throws IOException, NoSuchAlgorithmException, KeyManagementException {
    SslConnector cnn = null;
    ServerSocketFactory ssf = null;
    cnn = (SslConnector) connector;
    // An SSLContext is an environment for implementing JSSE
    // It is used to create a ServerSocketFactory
    SSLContext sslc = SSLContext.getInstance(cnn.getProtocol().toLowerCase());

    // Initialize the SSLContext to work with our key managers
    sslc.init(cnn.getKeyManagerFactory().getKeyManagers(), null, null);

    ssf = sslc.getServerSocketFactory();

    String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost");
    int backlog = cnn.getBacklog();
    SSLServerSocket serverSocket = null;

    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost())
        || inetAddress.isLoopbackAddress()
        || host.trim().equals("localhost")) {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog);
    } else {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog, inetAddress);
    }
    // Authenticate the client?
    serverSocket.setNeedClientAuth(cnn.isRequireClientAuthentication());
    return serverSocket;
  }
Ejemplo n.º 2
0
  protected void bind() throws IOException {
    URI bind = getBindLocation();

    String host = bind.getHost();
    host = (host == null || host.length() == 0) ? "localhost" : host;
    InetAddress addr = InetAddress.getByName(host);

    try {
      if (host.trim().equals("localhost") || addr.equals(InetAddress.getLocalHost())) {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog);
      } else {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr);
      }
      this.serverSocket.setSoTimeout(2000);
    } catch (IOException e) {
      throw IOExceptionSupport.create(
          "Failed to bind to server socket: " + bind + " due to: " + e, e);
    }
    try {
      setConnectURI(
          new URI(
              bind.getScheme(),
              bind.getUserInfo(),
              resolveHostName(bind.getHost()),
              serverSocket.getLocalPort(),
              bind.getPath(),
              bind.getQuery(),
              bind.getFragment()));
    } catch (URISyntaxException e) {
      throw IOExceptionSupport.create(e);
    }
  }
    @Override
    public void run() {

      List<Socket> inProgress = new ArrayList<>();
      ServerSocketFactory factory = ServerSocketFactory.getDefault();

      try {
        ss = factory.createServerSocket(0);
        ss.setSoTimeout(5000);

        socketReadyLatch.countDown();
        while (!interrupted()) {
          inProgress.add(ss.accept()); // eat socket
        }
      } catch (java.net.SocketTimeoutException expected) {
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          ss.close();
        } catch (IOException ignored) {
        }
        for (Socket s : inProgress) {
          try {
            s.close();
          } catch (IOException ignored) {
          }
        }
      }
    }
Ejemplo n.º 4
0
  public FileSender(File file, InetAddress client) throws IOException {
    ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
    ssocket = ssocketFactory.createServerSocket();
    ssocket.bind(null);
    ssocket.setSoTimeout(timeout);

    this.file = file;
    this.client = client;
  }
Ejemplo n.º 5
0
  public static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

      SSLContext sslContext = SSLContext.getInstance("TLS");

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
 public void waitForConnection() {
   try (ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(PORT)) {
     networkManager.startCommunication(serverSocket.accept());
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 7
0
 @Override
 protected boolean isPortAvailable(int port) {
   try {
     ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(port);
     serverSocket.close();
     return true;
   } catch (Exception ex) {
     return false;
   }
 }
  public JDSimpleWebserver() {
    SubConfiguration subConfig = SubConfiguration.getConfig("WEBINTERFACE");
    Boolean https = subConfig.getBooleanProperty(JDWebinterface.PROPERTY_HTTPS, false);
    AuthUser =
        "******"
            + Encoding.Base64Encode(
                subConfig.getStringProperty(JDWebinterface.PROPERTY_USER, "JD")
                    + ":"
                    + subConfig.getStringProperty(JDWebinterface.PROPERTY_PASS, "JD"));
    NeedAuth = subConfig.getBooleanProperty(JDWebinterface.PROPERTY_LOGIN, true);
    boolean localhostonly =
        subConfig.getBooleanProperty(JDWebinterface.PROPERTY_LOCALHOST_ONLY, false);
    int port = subConfig.getIntegerProperty(JDWebinterface.PROPERTY_PORT, 8765);
    try {
      if (!https) {
        if (localhostonly) {
          Server_Socket = new ServerSocket(port, -1, HttpServer.getLocalHost());
        } else {
          Server_Socket = new ServerSocket(port);
        }
      } else {
        try {
          ServerSocketFactory ssocketFactory = setupSSL();

          if (localhostonly) {
            Server_Socket = ssocketFactory.createServerSocket(port, -1, HttpServer.getLocalHost());
          } else {
            Server_Socket = ssocketFactory.createServerSocket(port);
          }
        } catch (Exception e) {
          logger.severe("WebInterface: Server failed to start (SSL Setup Failed)!");
          return;
        }
      }
      logger.info("Webinterface: Server started");
      start();
    } catch (IOException e) {
      logger.severe("WebInterface: Server failed to start!");
    }
  }
Ejemplo n.º 9
0
 @Override
 public ServerSocket createServerSocket(int port) throws IOException {
   log.info(
       "Starting repository on host: "
           + this.host
           + ":"
           + port
           + ":m("
           + this.maxConnections
           + ")");
   InetAddress address = InetAddress.getByName(this.host);
   return ServerSocketFactory.getDefault().createServerSocket(port, this.maxConnections, address);
 }
 public TestTCPServer() {
   ServerSocket serverSocket = null;
   ExecutorService executor = null;
   try {
     serverSocket = ServerSocketFactory.getDefault().createServerSocket(0);
     System.setProperty("tcp.sink.test.port", Integer.toString(serverSocket.getLocalPort()));
     executor = Executors.newSingleThreadExecutor();
   } catch (IOException e) {
     e.printStackTrace();
   }
   this.serverSocket = serverSocket;
   this.executor = executor;
   this.decoder = new ByteArrayCrLfSerializer();
   executor.execute(this);
 }
Ejemplo n.º 11
0
  public static void main(String[] args) {
    //		GatewayServer.turnAllLoggingOn();
    Logger logger = Logger.getLogger("py4j");
    logger.setLevel(Level.ALL);
    ConsoleHandler handler = new ConsoleHandler();
    handler.setLevel(Level.FINEST);
    logger.addHandler(handler);
    System.out.println("Starting");

    SharedRunnable sharedRunnable = new SharedRunnable();
    Thread thread = new Thread(sharedRunnable, "SharedRunnable");
    thread.setDaemon(true);
    thread.start();

    EntryPoint entryPoint0 = new EntryPoint(0, sharedRunnable);
    ClientServer clientServer0 = new ClientServer(entryPoint0);
    // Wait for Python side to shut down Java side
    clientServer0.startServer(true);

    // TODO: Refactor with Py4J Pull 204
    // Start the second client server on default + 10 port, the rest of the
    // arguments are the same
    EntryPoint entryPoint1 = new EntryPoint(1, sharedRunnable);
    ClientServer clientServer1 =
        new ClientServer(
            GatewayServer.DEFAULT_PORT + 2,
            GatewayServer.defaultAddress(),
            GatewayServer.DEFAULT_PYTHON_PORT + 2,
            GatewayServer.defaultAddress(),
            GatewayServer.DEFAULT_CONNECT_TIMEOUT,
            GatewayServer.DEFAULT_READ_TIMEOUT,
            ServerSocketFactory.getDefault(),
            SocketFactory.getDefault(),
            entryPoint1);
    // Wait for Python side to shut down Java side
    clientServer1.startServer(true);

    // Shut down after 5 seconds
    // clientServer.startServer(true);
    // try {
    // Thread.currentThread().sleep(5000);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // clientServer.shutdown();
    //
    // System.out.println("Stopping");
  }
  /**
   * Starts the service. Will start a socket listener to listen for management operation requests.
   *
   * @param context The start context
   * @throws StartException If any errors occur
   */
  public synchronized void start(StartContext context) throws StartException {
    System.out.println("Installing 2");
    final ExecutorService executorService = executorServiceValue.getValue();
    final ThreadFactory threadFactory = threadFactoryValue.getValue();
    final NetworkInterfaceBinding interfaceBinding = interfaceBindingValue.getValue();
    final Integer port = portValue.getValue();
    try {
      final ProtocolServer.Configuration config = new ProtocolServer.Configuration();
      config.setBindAddress(new InetSocketAddress(interfaceBinding.getAddress(), port));
      config.setThreadFactory(threadFactory);
      config.setReadExecutor(executorService);
      config.setSocketFactory(ServerSocketFactory.getDefault());
      config.setBacklog(50);
      config.setConnectionHandler(this);

      server = new ProtocolServer(config);
      server.start();
    } catch (Exception e) {
      throw new StartException("Failed to start server socket", e);
    }
  }
 @Override
 public ServerSocket createServerSocket(int port) throws IOException {
   ServerSocket serverSocket = delegate.createServerSocket(port);
   return configureServerSocket(serverSocket);
 }
Ejemplo n.º 14
0
 /**
  * Use this constructor to create a server ACSE SAP that listens on a fixed port.
  *
  * @param port the local port listen on
  * @param backlog the backlog
  * @param bindAddr the InetAddress to bind to
  * @param associationListener the AssociationListener that will be notified when remote clients
  *     have associated. Once constructed the AcseSAP contains a public TSAP that can be accessed
  *     to set its configuration.
  */
 public ServerAcseSap(
     int port, int backlog, InetAddress bindAddr, AcseAssociationListener associationListener) {
   this(port, backlog, bindAddr, associationListener, ServerSocketFactory.getDefault());
 }
Ejemplo n.º 15
0
  public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
      throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
          UnrecoverableKeyException, KeyManagementException, IOException {
    keepAlive = !noKeepAlive;
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null) port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null) backlog = new Integer(s).intValue();

    if (keepAlive) {
      s = (String) props.get("keepAlive");
      if (s != null) keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
      KeyManager[] keyManagers = null;
      TrustManager[] trustManagers = null;

      String keyManager = (String) props.get("keyManager");

      if (keyManager != null && keyManager.length() > 0) {
        try {
          KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
          keyManagers = new KeyManager[] {manager};
        } catch (Exception e) {
          e.printStackTrace();
        }
      } else {
        String keystore = (String) props.get("keyStore");
        String keystoreType = (String) props.get("keyStoreType");
        String keystorePassword = (String) props.get("keyStorePassword");
        String keyPassword = (String) props.get("keyPassword");

        if (keystore != null) {
          if (keystoreType == null) keystoreType = "pkcs12";

          KeyStore ks = KeyStore.getInstance(keystoreType);
          ks.load(
              new FileInputStream(keystore),
              keystorePassword == null ? null : keystorePassword.toCharArray());

          KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
          kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
          keyManagers = kmf.getKeyManagers();
        }
      }

      String trustManager = (String) props.get("trustManager");

      if (trustManager != null && trustManager.length() > 0) {
        try {
          TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
          trustManagers = new TrustManager[] {manager};
        } catch (Exception e) {
          e.printStackTrace();
        }
      } else if ("true".equalsIgnoreCase(trustAll)) {
        trustManagers =
            new TrustManager[] {
              new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {}

                public void checkServerTrusted(X509Certificate[] chain, String authType) {}

                public X509Certificate[] getAcceptedIssuers() {
                  return new X509Certificate[0];
                }
              }
            };
      } else {
        String keystore = (String) props.get("caStore");
        String keystoreType = (String) props.get("caStoreType");
        String keystorePassword = (String) props.get("caStorePassword");

        if (keystore != null) {
          if (keystoreType == null) keystoreType = "pkcs12";

          KeyStore caKeys = KeyStore.getInstance(keystoreType);
          caKeys.load(
              new FileInputStream(keystore),
              keystorePassword == null ? null : keystorePassword.toCharArray());
          TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
          tmf.init(caKeys);
          trustManagers = tmf.getTrustManagers();
        }
      }

      SSLContext sslContext = SSLContext.getInstance("SSLv3");
      sslContext.init(keyManagers, trustManagers, null);

      ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
      SSLServerSocket sslServerSocket =
          (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
      serverSocket = sslServerSocket;

      if (sslWantClientAuth) sslServerSocket.setWantClientAuth(true);

      if (sslNeedClientAuth) sslServerSocket.setNeedClientAuth(true);

      if (sslEnabledProtocols != null) sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

      if (sslEnabledCiphers != null) sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

      usingSSL = true;
    } else {
      serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
  }
Ejemplo n.º 16
0
 public ServerSocketFactory getServerSocketFactory() {
   if (serverSocketFactory == null) {
     serverSocketFactory = ServerSocketFactory.getDefault();
   }
   return serverSocketFactory;
 }
Ejemplo n.º 17
0
  public UnicomSPMonitor() {
    try {
      SAXBuilder builder = new SAXBuilder();
      Document doc = null;
      String osname = System.getProperty("os.name");
      Pattern ospn = Pattern.compile("^windows.*$", Pattern.CASE_INSENSITIVE); // 大小写不敏感

      // String confpath =
      // Thread.currentThread().getContextClassLoader().getResource(".").getPath();
      String confpath = FileHelper.getClassesPath();
      if (ospn.matcher(osname).matches()) { // windows操作系统
        log.info(
            "操作系统名称:"
                + osname
                + ",配置文件路径:"
                + System.getProperty("user.dir")
                + "\\productionConf.xml");
        doc = builder.build(confpath + "\\productionConf.xml");
      } else { // Linux系统
        log.info(
            "操作系统名称:"
                + osname
                + ",配置文件路径:"
                + System.getProperty("user.dir")
                + "/productionConf.xml");
        doc = builder.build(confpath + "/productionConf.xml");
      }
      // 判断操作系统
      // 根目录
      Element productionConf = doc.getRootElement();
      Element uncomConf = productionConf.getChild("unicomconf");
      // 获取联通短信网关ip及port
      SPSender.unicomIp = uncomConf.getChildText("ipaddr");
      SPSender.unicomPort = Integer.valueOf(uncomConf.getChildText("addrport"));
      String srcNodeId = uncomConf.getChildText("spNodeid");
      SGIPHeader.setSrcNodeId(srcNodeId);
      SPSender.spCorpId = srcNodeId.substring(5, 10);
      SPSender.spLoginName = uncomConf.getChildText("spUserName");
      SPSender.spLogPassword = uncomConf.getChildText("spPassword");
      UnicomSPMonitor.spListenPort = Integer.parseInt(uncomConf.getChildText("spListenPort"));
      UnicomSPMonitor.smgLoginUserName = uncomConf.getChildText("smgUserName");
      UnicomSPMonitor.smgLoginPassword = uncomConf.getChildText("smgPassword");
      // 配置实例
      log.info("***************** 加载网关配置  ********************");
      log.info("联通SMG地址:" + SPSender.unicomIp);
      log.info("联通SMG端口:" + SPSender.unicomPort);
      log.info("源节点编号:" + SGIPHeader.getSrcNodeId());
      log.info("SMG连接SP端口:" + UnicomSPMonitor.spListenPort);
      log.info("SP登陆SMG用户名:" + SPSender.spLoginName);
      log.info("SP登陆SMG密码:" + SPSender.spLogPassword);
      log.info("SMG登陆SP用户名:" + UnicomSPMonitor.smgLoginUserName);
      log.info("SMG登陆SP密码:" + UnicomSPMonitor.smgLoginPassword);

      try {
        spsvrSocket = ServerSocketFactory.getDefault().createServerSocket(spListenPort);
        log.info("短消息上行(MO))接收端启动,监听端口:" + spListenPort);
      } catch (IOException e) {
        log.error("launch local server error!", e);
        throw new ExceptionInInitializerError(e);
      }
      new Thread(new JFThread()).start();
      log.info("***************** 网关配置完成  ********************\n");
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
 @Override
 public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress)
     throws IOException {
   ServerSocket serverSocket = delegate.createServerSocket(port, backlog, ifAddress);
   return configureServerSocket(serverSocket);
 }