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();
  }
示例#2
0
 public static void close(Object o) {
   try {
     if (o == null) return;
     if (o instanceof InputStream) {
       ((InputStream) o).close();
     } else if (o instanceof OutputStream) {
       ((OutputStream) o).flush();
       ((OutputStream) o).close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#3
0
 void sendRequest(InputStream in, OutputStream out) throws IOException {
   out.write("GET / HTTP/1.0\r\n\r\n".getBytes());
   out.flush();
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       break;
     }
     sb.append((char) ch);
   }
   String response = sb.toString();
   if (response.startsWith("HTTP/1.0 200 ") == false) {
     throw new IOException("Invalid response: " + response);
   }
 }
 @Override
 protected void engineSetSeed(byte[] bytes) {
   try {
     OutputStream out;
     synchronized (sLock) {
       out = getUrandomOutputStream();
     }
     out.write(bytes);
     out.flush();
   } catch (IOException e) {
     // On a small fraction of devices /dev/urandom is not writable.
     // Log and ignore.
     Log.w(PRNGFixes.class.getSimpleName(), "Failed to mix seed into " + URANDOM_FILE);
   } finally {
     mSeeded = true;
   }
 }
示例#5
0
 /**
  * Watches an event.
  *
  * @param name event name
  * @param notifier event notification
  * @throws IOException I/O exception
  */
 public void watch(final String name, final EventNotifier notifier) throws IOException {
   out.write(10);
   if (esocket == null) {
     final int eport = Integer.parseInt(receive());
     // initialize event socket
     esocket = new Socket();
     esocket.connect(new InetSocketAddress(ehost, eport), 5000);
     final OutputStream os = esocket.getOutputStream();
     receive(in, os);
     os.write(0);
     os.flush();
     final InputStream is = esocket.getInputStream();
     is.read();
     listen(is);
   }
   send(name);
   info = receive();
   if (!ok()) throw new IOException(info);
   notifiers.put(name, notifier);
 }
  /*
   * 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 {
    KeyStore ks = KeyStore.getInstance("JKS");
    com.sun.net.ssl.SSLContext ctx = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");

    ks.load(new FileInputStream(keyFilename), cpasswd);
    kmf.init(ks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) ctx.getServerSocketFactory();

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

    sslServerSocket.setNeedClientAuth(true);

    /*
     * Create using the other type.
     */
    SSLContext ctx1 = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf1 = KeyManagerFactory.getInstance("SunX509");

    TrustManager[] tms1 = new TrustManager[] {new MyJavaxX509TrustManager()};

    kmf1.init(ks, cpasswd);

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory();

    SSLServerSocket sslServerSocket1 = (SSLServerSocket) sslssf.createServerSocket(serverPort1);
    serverPort1 = sslServerSocket1.getLocalPort();
    sslServerSocket1.setNeedClientAuth(true);

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

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslServerSocket.close();
    serverReady = false;

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

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    sslSocket = (SSLSocket) sslServerSocket1.accept();
    sslIS = sslSocket.getInputStream();
    sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    System.out.println("Server exiting!");
    System.out.flush();
  }
  SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      if (endPoint.getProtocol().equals("https"))
        // if(!setHttps)
        initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("POST");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setInstanceFollowRedirects(true);

      if (message.saveRequired()) message.saveChanges();

      MimeHeaders headers = message.getMimeHeaders();

      Iterator it = headers.getAllHeaders();
      boolean hasAuth = false; // true if we find explicit Auth header
      while (it.hasNext()) {
        MimeHeader header = (MimeHeader) it.next();

        String[] values = headers.getHeader(header.getName());
        if (values.length == 1)
          httpConnection.setRequestProperty(header.getName(), header.getValue());
        else {
          StringBuffer concat = new StringBuffer();
          int i = 0;
          while (i < values.length) {
            if (i != 0) concat.append(',');
            concat.append(values[i]);
            i++;
          }

          httpConnection.setRequestProperty(header.getName(), concat.toString());
        }

        if ("Authorization".equals(header.getName())) {
          hasAuth = true;
          log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
        }
      }

      if (!hasAuth && userInfo != null) {
        initAuthUserInfo(httpConnection, userInfo);
      }

      OutputStream out = httpConnection.getOutputStream();
      message.writeTo(out);

      out.flush();
      out.close();

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        }
        // else if (responseCode != HttpURLConnection.HTTP_OK)
        // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
        else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0009.p2p.msg.send.failed");
      throw new SOAPExceptionImpl("Message send failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());

        byte[] bytes = readFully(httpIn);

        int length =
            httpConnection.getContentLength() == -1
                ? bytes.length
                : httpConnection.getContentLength();

        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        if (length == 0) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          ByteInputStream in = new ByteInputStream(bytes, length);
          response = messageFactory.createMessage(headers, in);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
  private byte[] transform(Data dereferencedData, XMLCryptoContext context)
      throws XMLSignatureException {

    if (md == null) {
      try {
        md =
            MessageDigest.getInstance(((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm());
      } catch (NoSuchAlgorithmException nsae) {
        throw new XMLSignatureException(nsae);
      }
    }
    md.reset();
    DigesterOutputStream dos;
    Boolean cache = (Boolean) context.getProperty("javax.xml.crypto.dsig.cacheReference");
    if (cache != null && cache.booleanValue() == true) {
      this.derefData = copyDerefData(dereferencedData);
      dos = new DigesterOutputStream(md, true);
    } else {
      dos = new DigesterOutputStream(md);
    }
    OutputStream os = new UnsyncBufferedOutputStream(dos);
    Data data = dereferencedData;
    for (int i = 0, size = transforms.size(); i < size; i++) {
      DOMTransform transform = (DOMTransform) transforms.get(i);
      try {
        if (i < size - 1) {
          data = transform.transform(data, context);
        } else {
          data = transform.transform(data, context, os);
        }
      } catch (TransformException te) {
        throw new XMLSignatureException(te);
      }
    }

    try {
      if (data != null) {
        XMLSignatureInput xi;
        if (data instanceof ApacheData) {
          xi = ((ApacheData) data).getXMLSignatureInput();
        } else if (data instanceof OctetStreamData) {
          xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
        } else if (data instanceof NodeSetData) {
          TransformService spi =
              TransformService.getInstance(CanonicalizationMethod.INCLUSIVE, "DOM");
          data = spi.transform(data, context);
          xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
        } else {
          throw new XMLSignatureException("unrecognized Data type");
        }
        xi.updateOutputStream(os);
      }
      os.flush();
      if (cache != null && cache.booleanValue() == true) {
        this.dis = dos.getInputStream();
      }
      return dos.getDigestValue();
    } catch (Exception e) {
      throw new XMLSignatureException(e);
    }
  }
示例#9
0
 /**
  * Checks the next success flag.
  *
  * @return value of check
  * @throws IOException Exception
  */
 boolean ok() throws IOException {
   out.flush();
   return in.read() == 0;
 }
示例#10
0
 /**
  * Closes the session.
  *
  * @throws IOException Exception
  */
 public void close() throws IOException {
   send("exit");
   out.flush();
   if (esocket != null) esocket.close();
   socket.close();
 }