/**
  * Send a message to a specified address.
  *
  * @param message Pre-formatted message to send.
  * @param receiverAddress Address to send it to.
  * @param receiverPort Receiver port.
  * @throws IOException If there is a problem connecting or sending.
  */
 public void sendMessage(
     byte message[], InetAddress receiverAddress, int receiverPort, boolean retry)
     throws IOException {
   if (message == null || receiverAddress == null)
     throw new IllegalArgumentException("Null argument");
   SSLSocket sock =
       (SSLSocket)
           this.stack.ioHandler.sendBytes(receiverAddress, receiverPort, "TLS", message, retry);
   //
   // Created a new socket so close the old one and s
   // Check for null (bug fix sent in by Christophe)
   if (sock != mySock && sock != null) {
     try {
       if (mySock != null) mySock.close();
     } catch (IOException ex) {
       /* ignore */
     }
     mySock = sock;
     this.myClientInputStream = mySock.getInputStream();
     this.myClientOutputStream = mySock.getOutputStream();
     // start a new reader on this end of the pipe.
     Thread mythread = new Thread(this);
     mythread.setDaemon(true);
     mythread.setName("TLSMessageChannelThread");
     mythread.start();
   }
 }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    sslSocket.close();
  }
Esempio n. 3
0
    @Override
    public void run() {
      SSLSocketFactory socFac = _sslCtx.getSocketFactory();
      SSLSocket socket = null;
      try {
        socket = (SSLSocket) socFac.createSocket(_targetAddr.getAddress(), _targetAddr.getPort());
        Utility.logOutConnection(socket, _selfId); // log connection
        BufferedWriter out =
            new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Utility.ENCODING));
        Utility.XMLDocToWriter(_doc, out);
        if (_bExpectACK) {
          BufferedReader in =
              new BufferedReader(new InputStreamReader(socket.getInputStream(), Utility.ENCODING));
          Document doc = Utility.ReaderToXMLDoc(in);
          if (!doc.getRootElement().getName().equals(ACK)) { // if not ACK
            _log.error("The Peer didn't send ACK back");
          }
        }

      } catch (Exception e) {
        _log.error("SendJob failed", e);
      } finally {
        try {
          if (null != socket) socket.close();
        } catch (IOException e) {
          _log.error("close sendjob socket failed", e);
        }
      }
    }
Esempio n. 4
0
  /** Disconnects the current session. */
  protected void disconnect() {
    if (tnSocket == null && tnSocketSSL == null) {
      log.warning("socket is null, not connected");

      return;
    }

    try {
      sessionThread.interrupt();
      is.close();
      os.close();
      if (encryption) {
        tnSocketSSL.close();
        tnSocketSSL = null;
      } else {
        tnSocket.close();
        tnSocket = null;
      }
      os = null;
      is = null;
      willHistory = new boolean[3];
      doHistory = new boolean[3];

      log.fine("disconnected");
    } catch (Exception e) {
      e.printStackTrace();
      log.severe(e.getMessage());
    }
  }
 public void close() {
   try {
     socket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 6
0
 public void call() {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   PrintStream out = System.out;
   SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
   try {
     SSLSocket c = (SSLSocket) f.createSocket("localhost", 8888);
     printSocketInfo(c);
     c.startHandshake();
     BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
     BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
     String m = null;
     while ((m = r.readLine()) != null) {
       out.println(m);
       m = in.readLine();
       w.write(m, 0, m.length());
       w.newLine();
       w.flush();
     }
     w.close();
     r.close();
     c.close();
   } catch (IOException e) {
     System.err.println(e.toString());
   }
 }
Esempio n. 7
0
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    // enable TLSv1.1 only
    sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

    // enable a block cipher
    sslSocket.setEnabledCipherSuites(new String[] {"TLS_RSA_WITH_AES_128_CBC_SHA"});

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslOS.write('B');
    sslOS.flush();
    sslIS.read();

    sslSocket.close();
  }
Esempio n. 8
0
  public static void main(String[] args) throws IOException {

    System.out.println("opening a secure socket");

    SSLServerSocketFactory secSocketFactory =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket secSocket = (SSLServerSocket) secSocketFactory.createServerSocket(portNo);

    String[] enabledCipherSuites = {"SSL_DH_anon_WITH_RC4_128_MD5"};
    secSocket.setEnabledCipherSuites(enabledCipherSuites);

    System.out.println("Listening on port no: " + portNo);
    SSLSocket socket = (SSLSocket) secSocket.accept();

    System.out.println("Got a connection from: " + socket.getInetAddress().toString());
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String line = in.readLine();
    while (line != null) {
      System.out.println(line);
      line = in.readLine();
    }

    out.close();
    in.close();
    socket.close();
    secSocket.close();
  }
Esempio n. 9
0
    public void run() {
      try {
        store = provideKeys ? getKeyStore(keys) : null;
        KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
        TrustManager[] trustManagers = new TrustManager[] {trustManager};

        clientSslContext = SSLContext.getInstance("TLS");
        clientSslContext.init(keyManagers, trustManagers, null);

        SSLSocket socket = (SSLSocket) clientSslContext.getSocketFactory().createSocket();

        socket.connect(new InetSocketAddress(port));
        OutputStream ostream = socket.getOutputStream();
        ostream.write(testData.getBytes());
        ostream.flush();

        InputStream istream = socket.getInputStream();
        byte[] buffer = new byte[1024];
        istream.read(buffer);

        clientSession = socket.getSession();
        while (notFinished) {
          Thread.currentThread().sleep(500);
        }
        socket.close();

      } catch (Exception ex) {
        exception = ex;
      }
    }
Esempio n. 10
0
  @Override
  public void run() {
    // TODO Auto-generated method stub

    try {
      this.in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
      JSONObject message;
      int i = 0;
      // receive the first several messages
      while (i < 4) {
        message = (JSONObject) parser.parse(in.readLine());
        MessageReceive(socket, message);
        i++;
      }
      while (run) {
        System.out.print("[" + room_id + "] " + identity + "> ");
        message = (JSONObject) parser.parse(in.readLine());
        MessageReceive(socket, message);
      }
      System.exit(0);
      in.close();
      socket.close();
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws Exception {
    SSLContext sslContext = createSSLContext();
    SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
    SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(Utils.PORT_NO);

    // client authenticate where possible
    sSock.setWantClientAuth(true);

    for (; ; ) {
      SSLSocket sslSock = (SSLSocket) sSock.accept();

      try {
        sslSock.startHandshake();
      } catch (IOException e) {
        continue;
      }

      readRequest(sslSock.getInputStream());

      SSLSession session = sslSock.getSession();

      try {
        Principal clientID = session.getPeerPrincipal();

        System.out.println("client identified as: " + clientID);
      } catch (SSLPeerUnverifiedException e) {
        System.out.println("client not authenticated");
      }

      sendResponse(sslSock.getOutputStream());

      sslSock.close();
    }
  }
 /** Close the message channel. */
 public void close() {
   try {
     if (mySock != null) mySock.close();
     if (LogWriter.needsLogging) stack.logWriter.logMessage("Closing message Channel " + this);
   } catch (IOException ex) {
     if (LogWriter.needsLogging) stack.logWriter.logMessage("Error closing socket " + ex);
   }
 }
Esempio n. 13
0
  @Override
  public Socket connectSocket(
      Socket sock,
      String host,
      int port,
      InetAddress localAddress,
      int localPort,
      HttpParams params)
      throws IOException, UnknownHostException, ConnectTimeoutException {
    if (host == null) {
      throw new IllegalArgumentException("Target host may not be null.");
    }
    if (params == null) {
      throw new IllegalArgumentException("Parameters may not be null.");
    }

    if (App.DEBUG)
      Log.e(
          TAG + "delete",
          "ConnectSocket with "
              + "\n\t host="
              + host
              + "\n\t port="
              + port
              + "\n\t localport="
              + localPort);

    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

    if ((localAddress != null) || (localPort > 0)) {
      if (localPort < 0) localPort = 0;

      InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
      sslsock.bind(isa);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);

    sslsock.connect(remoteAddress, connTimeout);

    sslsock.setSoTimeout(soTimeout);

    try {
      hostnameVerifier.verify(host, sslsock);
    } catch (IOException iox) {
      try {
        sslsock.close();
      } catch (Exception x) {
      }

      throw iox;
    }

    return sslsock;
  }
  // non-javadoc, see interface org.apache.http.conn.SocketFactory
  public Socket connectSocket(
      final Socket sock,
      final String host,
      final int port,
      final InetAddress localAddress,
      int localPort,
      final HttpParams params)
      throws IOException {

    if (host == null) {
      throw new IllegalArgumentException("Target host may not be null.");
    }
    if (params == null) {
      throw new IllegalArgumentException("Parameters may not be null.");
    }

    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

    if ((localAddress != null) || (localPort > 0)) {

      // we need to bind explicitly
      if (localPort < 0) localPort = 0; // indicates "any"

      InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
      sslsock.bind(isa);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    InetSocketAddress remoteAddress;
    if (this.nameResolver != null) {
      remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port);
    } else {
      remoteAddress = new InetSocketAddress(host, port);
    }
    try {
      sslsock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
      throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
    sslsock.setSoTimeout(soTimeout);
    try {
      hostnameVerifier.verify(host, sslsock);
      // verifyHostName() didn't blowup - good!
    } catch (IOException iox) {
      // close the socket before re-throwing the exception
      try {
        sslsock.close();
      } catch (Exception x) {
        /*ignore*/
      }
      throw iox;
    }

    return sslsock;
  }
Esempio n. 15
0
 public void shutdown() {
   try {
     if (sock != null) sock.close();
   } catch (IOException e) {
     Logger.I(TAG, "shutdown fails: IOException: " + e.getMessage());
   } catch (Exception e) {
     reportFail("shutdown", e);
   }
 }
Esempio n. 16
0
 /** Inits supported and enabled protocol versions. */
 private void initSupportedProtocols() {
   try {
     SSLSocket ssl_socket = (SSLSocket) ssl_factory.createSocket();
     if (supported_protocols == null) supported_protocols = ssl_socket.getSupportedProtocols();
     if (enabled_protocols == null) enabled_protocols = ssl_socket.getEnabledProtocols();
     ssl_socket.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  void doTest(SSLSocket sslSocket) throws Exception {
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    System.out.println("  Writing");
    sslOS.write(280);
    sslOS.flush();
    System.out.println("  Reading");
    sslIS.read();

    sslSocket.close();
  }
  public static void main(String[] args) throws Exception {
    String host = "192.168.1.191";

    SocketFactory sf = SSLSocketFactory.getDefault();
    SSLSocket sock = (SSLSocket) sf.createSocket(host, PORT);
    System.out.println("Server connected");

    InputStream rawIn = sock.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(rawIn));
    System.out.println(in.readLine());
    sock.close();
  }
  public void handShake() throws IOException, RemoteException {
    try {
      if (ssl.getWantClientAuth()) {
        log.debug(sm.getString("jsseSupport.noCertWant"));
      } else {
        ssl.setNeedClientAuth(true);
      }

      if (ssl.getEnabledCipherSuites().length == 0) {
        // Handshake is never going to be successful.
        // Assume this is because handshakes are disabled
        log.warn(sm.getString("jsseSupport.serverRenegDisabled"));
        session.invalidate();
        ssl.close();
        return;
      }

      InputStream in = ssl.getInputStream();
      int oldTimeout = ssl.getSoTimeout();
      ssl.setSoTimeout(1000);
      byte[] b = new byte[1];
      listener.reset();
      ssl.startHandshake();
      int maxTries = 60; // 60 * 1000 = example 1 minute time out
      for (int i = 0; i < maxTries; i++) {
        if (log.isTraceEnabled()) log.trace("Reading for try #" + i);
        try {
          int read = in.read(b);
          if (read > 0) {
            // Shouldn't happen as all input should have been swallowed
            // before trying to do the handshake. If it does, something
            // went wrong so lets bomb out now.
            throw new SSLException(sm.getString("jsseSupport.unexpectedData"));
          }
        } catch (SSLException sslex) {
          log.info(sm.getString("jsseSupport.clientCertError"), sslex);
          throw sslex;
        } catch (IOException e) {
          // ignore - presumably the timeout
        }
        if (listener.isCompleted()) {
          break;
        }
      }
      ssl.setSoTimeout(oldTimeout);
      if (listener.isCompleted() == false) {
        throw new SocketException("SSL Cert handshake timeout");
      }

    } catch (Exception excp) {
      excp.printStackTrace();
    }
  }
Esempio n. 20
0
  /**
   * checks if a certificate is installed for given host:port
   *
   * @param context
   * @param host
   * @param port
   * @return
   */
  public IOException checkCertificate() {
    SSLSocketFactory factory = context.getSocketFactory();
    // System.out.println("Opening connection to " + host + ":" + port + "...");

    try {
      SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
      socket.setSoTimeout(10000);
      socket.startHandshake();
      socket.close();
      return null;
    } catch (IOException e) {
      return e;
    }
  }
  private boolean sendLoginRequest(String userName, String password) throws Exception {
    boolean result = false;

    try {
      sslsocket = (SSLSocket) factory.createSocket(BURRITOPOS_SERVER_IP, BURRITOPOS_SERVER_PORT);
      in = new ObjectInputStream(sslsocket.getInputStream());
      out = new ObjectOutputStream(sslsocket.getOutputStream());

      String str = (String) in.readObject();
      dLog.trace("Got : " + str);
      out.writeObject(userName);
      str = (String) in.readObject();
      dLog.trace("Got : " + str);
      out.writeObject(password);
      str = (String) in.readObject();
      dLog.trace("Got : " + str);
      dLog.trace("good? " + str.split(" ")[0]);

      // check our input
      if (str.split(" ")[0].equals("OK")) {
        result = true;
      }

      out.writeObject("exit");
    } catch (Exception e1) {
      dLog.error("Exception in sendLoginRequest", e1);
    } finally {
      try {
        dLog.trace("Trying to close input stream");
        if (in != null) {
          in.close();
        }
        dLog.trace("Trying to close output stream");
        if (out != null) {
          out.close();
        }
        dLog.trace("Trying to close socket");
        if (sslsocket != null) {
          sslsocket.close();
        }
      } catch (Exception e2) {
        dLog.error("Exception closing socket", e2);
        throw (e2);
      }
    }

    dLog.trace("Returning result: " + result);
    return result;
  }
Esempio n. 22
0
 private void processHandshakeFailure(Socket raw) throws Exception {
   SSLContext context = SSLContext.getInstance("TLS");
   context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom());
   SSLSocketFactory sslSocketFactory = context.getSocketFactory();
   SSLSocket socket =
       (SSLSocket)
           sslSocketFactory.createSocket(
               raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
   try {
     socket.startHandshake(); // we're testing a handshake failure
     throw new AssertionError();
   } catch (IOException expected) {
   }
   socket.close();
 }
Esempio n. 23
0
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    DataOutputStream out = new DataOutputStream(sslSocket.getOutputStream());

    try {
      // get path to class file from header
      DataInputStream in = new DataInputStream(sslSocket.getInputStream());
      String path = getPath(in);
      // retrieve bytecodes
      byte[] bytecodes = getBytes(path);
      // send bytecodes in response (assumes HTTP/1.0 or later)
      try {
        out.writeBytes("HTTP/1.0 200 OK\r\n");
        out.writeBytes("Content-Length: " + bytecodes.length + "\r\n");
        out.writeBytes("Content-Type: text/html\r\n\r\n");
        out.write(bytecodes);
        out.flush();
      } catch (IOException ie) {
        ie.printStackTrace();
        return;
      }

    } catch (Exception e) {
      e.printStackTrace();
      // write out error response
      out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
      out.writeBytes("Content-Type: text/html\r\n\r\n");
      out.flush();
    } finally {
      // close the socket
      System.out.println("Server closing socket");
      sslSocket.close();
      serverReady = false;
    }
  }
Esempio n. 24
0
    public void run() {
      try {
        store = provideKeys ? getKeyStore(keys) : null;
        KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
        TrustManager[] trustManagers = new TrustManager[] {trustManager};

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

        SSLServerSocket serverSocket =
            (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();

        if (clientAuth == CLIENT_AUTH_WANTED) {
          serverSocket.setWantClientAuth(true);
        } else if (clientAuth == CLIENT_AUTH_NEEDED) {
          serverSocket.setNeedClientAuth(true);
        } else {
          serverSocket.setWantClientAuth(false);
        }

        serverSocket.bind(new InetSocketAddress(port));

        SSLSocket clientSocket = (SSLSocket) serverSocket.accept();

        InputStream istream = clientSocket.getInputStream();
        byte[] buffer = new byte[1024];
        istream.read(buffer);

        OutputStream ostream = clientSocket.getOutputStream();
        ostream.write(testData.getBytes());
        ostream.flush();

        while (notFinished) {
          Thread.currentThread().sleep(500);
        }

        clientSocket.close();
        serverSocket.close();

      } catch (Exception ex) {
        exception = ex;
      }
    }
Esempio n. 25
0
  public void shutdown() {
    try {
      if (sock != null) {
        synchronized (this) {
          if (sock != null) {
            sock.close();
            sock = null;
            os = null;
            is = null;

            // TODO: check file descriptor is closed gracefully
            sockfd = -1;
          }
        }
      }
    } catch (Exception e) {
      reportFail("shutdown", e);
    }
  }
Esempio n. 26
0
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write('A');
    sslOS.flush();

    sslSocket.close();
  }
Esempio n. 27
0
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    try {
      InputStream sslIS = sslSocket.getInputStream();
      OutputStream sslOS = sslSocket.getOutputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(sslIS));
      PrintStream ps = new PrintStream(sslOS);

      // process HTTP POST request from client
      System.out.println("status line: " + br.readLine());
      String msg = null;
      while ((msg = br.readLine()) != null && msg.length() > 0) ;

      msg = br.readLine();
      if (msg.equals(postMsg)) {
        ps.println("HTTP/1.1 200 OK\n\n");
      } else {
        ps.println("HTTP/1.1 500 Not OK\n\n");
      }
      ps.flush();

      // close the socket
      while (!closeReady) {
        Thread.sleep(50);
      }
    } finally {
      sslSocket.close();
      sslServerSocket.close();
    }
  }
 /**
  * Send message to whoever is connected to us. Uses the topmost via address to send to.
  *
  * @param msg is the message to send.
  * @param retry
  */
 private void sendMessage(byte[] msg, boolean retry) throws IOException {
   SSLSocket sock =
       (SSLSocket)
           this.stack.ioHandler.sendBytes(
               this.peerAddress, this.peerPort, this.peerProtocol, msg, retry);
   // Created a new socket so close the old one and stick the new
   // one in its place but dont do this if it is a datagram socket.
   // (could have replied via udp but received via tcp!).
   if (sock != mySock && sock != null) {
     try {
       if (mySock != null) mySock.close();
     } catch (IOException ex) {
     }
     mySock = sock;
     this.myClientInputStream = mySock.getInputStream();
     this.myClientOutputStream = mySock.getOutputStream();
     Thread thread = new Thread(this);
     thread.setDaemon(true);
     thread.setName("TLSMessageChannelThread");
     thread.start();
   }
 }
Esempio n. 29
0
  public boolean connect() throws IOException, NoSuchAlgorithmException, KeyManagementException {
    // try{
    // Connect
    if (socket == null || socket.isClosed() || !socket.isConnected()) {
      if (socket != null && !socket.isClosed()) socket.close();

      if (sslContext == null) {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, tm, new java.security.SecureRandom());
      }

      SSLSocketFactory socketFactory = sslContext.getSocketFactory();

      socket = (SSLSocket) socketFactory.createSocket(host, 443);
      socket.setSoTimeout(0);
      socket.setUseClientMode(true);
      connected = true;
      Log.i(getClass().toString(), "Connected.");
    }

    // Secure
    if (connected) {
      Log.i(getClass().toString(), "Securing...");
      SSLSession session = socket.getSession();
      secured = session.isValid();

      if (secured) {
        Log.i(getClass().toString(), "Secured.");

        output = new BufferedOutputStream(socket.getOutputStream());
      } else {
        Log.i(getClass().toString(), "Securing failed.");
      }
    }

    return connected;
  }
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslSocket.addHandshakeCompletedListener(this);
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    for (int i = 0; i < 10; i++) {
      sslIS.read();
      sslOS.write(85);
      sslOS.flush();
    }

    System.out.println("invalidating");
    sslSocket.getSession().invalidate();
    System.out.println("starting new handshake");
    sslSocket.startHandshake();

    for (int i = 0; i < 10; i++) {
      System.out.println("sending/receiving data, iteration: " + i);
      sslIS.read();
      sslOS.write(85);
      sslOS.flush();
    }

    sslSocket.close();
  }