/* * 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(); }
public static String httsRequest(String url, String contentdata) { String str_return = ""; SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { sc.init( null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom()); } catch (KeyManagementException e) { e.printStackTrace(); } URL console = null; try { console = new URL(url); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpsURLConnection conn; try { conn = (HttpsURLConnection) console.openConnection(); conn.setRequestMethod("POST"); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json" String inpputs = contentdata; OutputStream os = conn.getOutputStream(); os.write(inpputs.getBytes()); os.close(); conn.connect(); InputStream is = conn.getInputStream(); // // DataInputStream indata = new DataInputStream(is); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String ret = ""; while (ret != null) { ret = reader.readLine(); if (ret != null && !ret.trim().equals("")) { str_return = str_return + ret; } } is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str_return; }
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(); }
/** Creates an XMLRPC call from the given method name and parameters and sends it */ protected void writeCall(String methodName, Object[] args) throws Exception { huc = u.openConnection(); huc.setDoOutput(true); huc.setDoInput(true); huc.setUseCaches(false); huc.setRequestProperty("Content-Type", "binary/message-pack"); huc.setReadTimeout(0); OutputStream os = huc.getOutputStream(); Packer pk = new Packer(os); pk.packArray(args.length + 1); pk.pack(methodName); for (Object o : args) pk.pack(o); os.close(); }
private static void putVMFiles(String remoteFilePath, String localFilePath) throws Exception { String serviceUrl = url.substring(0, url.lastIndexOf("sdk") - 1); String httpUrl = serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + datacenter + "&dsName=" + datastore; httpUrl = httpUrl.replaceAll("\\ ", "%20"); System.out.println("Putting VM File " + httpUrl); URL fileURL = new URL(httpUrl); HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); // Maintain session List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; // set the cookie in the new request header Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Length", "1024"); long fileLen = new File(localFilePath).length(); System.out.println("File size is: " + fileLen); conn.setChunkedStreamingMode((int) fileLen); OutputStream out = conn.getOutputStream(); InputStream in = new BufferedInputStream(new FileInputStream(localFilePath)); int bufLen = 9 * 1024; byte[] buf = new byte[bufLen]; byte[] tmp = null; int len = 0; while ((len = in.read(buf, 0, bufLen)) != -1) { tmp = new byte[len]; System.arraycopy(buf, 0, tmp, 0, len); out.write(tmp, 0, len); } in.close(); out.close(); conn.getResponseMessage(); conn.disconnect(); }
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); } }
void handleRequest(InputStream in, OutputStream out) throws IOException { boolean newline = false; StringBuilder sb = new StringBuilder(); while (true) { int ch = in.read(); if (ch < 0) { throw new EOFException(); } sb.append((char) ch); if (ch == '\r') { // empty } else if (ch == '\n') { if (newline) { // 2nd newline in a row, end of request break; } newline = true; } else { newline = false; } } String request = sb.toString(); if (request.startsWith("GET / HTTP/1.") == false) { throw new IOException("Invalid request: " + request); } out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes()); }
public void close() { if (closed) { return; } closed = true; /* close the underlying connection if, * a) the streams not set up yet, no response can be sent, or * b) if the wrapper output stream is not set up, or * c) if the close of the input/outpu stream fails */ try { if (uis_orig == null || uos == null) { connection.close(); return; } if (!uos_orig.isWrapped()) { connection.close(); return; } if (!uis_orig.isClosed()) { uis_orig.close(); } uos.close(); } catch (IOException e) { connection.close(); } }
private byte[] sendHttpMessage(byte[] body) throws IOException { HttpMessageContext context = HttpMessageContext.getInstance(); context.Debug("GNHttpConnection [sendHttpMessage] starts"); if (context.getLogheader()) { context.Info(logMessageSetting()); } connection.setDoInput(true); if (body != null) { connection.setDoOutput(true); OutputStream os = TimedURLConnection.getOutputStream(connection, timeout * 1000); context.Debug("GNHttpConnection [sendHttpMessage] sending message ..."); os.write(body); context.Debug("GNHttpConnection [sendHttpMessage] message sent"); } context.Debug( "GNHttpConnection [sendHttpMessage] TimedURLConnection.getInputStream timeout[" + timeout + " S]"); InputStream is = TimedURLConnection.getInputStream(connection, timeout * 1000); responseCode = connection.getResponseCode(); context.Debug("GNHttpConnection [sendHttpMessage] responseCode[" + responseCode + "]"); responseMessage = HttpMessageContext.getMessage(is); responseheaders = new Hashtable<String, String>(); int no = 0; while (true) { String headerName = connection.getHeaderFieldKey(no); String headerValue = connection.getHeaderField(no); if (headerName != null && headerName.length() > 0) { responseheaders.put(headerName, headerValue); } else { if (headerValue == null || headerValue.length() <= 0) break; } no++; } if (context.getLogheader()) { GTConfigFile head = new GTConfigFile(responseheaders); context.Debug("GNHttpConnection [sendHttpMessage] responseHeader\r\n" + head); context.Debug( "GNHttpConnection [sendHttpMessage] responseMessage\r\n" + new String(getResponseMessage())); context.Info("GNHttpConnection [sendHttpMessage] success for " + url); } else context.Info("GNHttpConnection [sendHttpMessage] success for " + url); return responseMessage; }
public void sendResponseHeaders(int rCode, long contentLen) throws IOException { if (sentHeaders) { throw new IOException("headers already sent"); } this.rcode = rCode; String statusLine = "HTTP/1.1 " + rCode + Code.msg(rCode) + "\r\n"; OutputStream tmpout = new BufferedOutputStream(ros); PlaceholderOutputStream o = getPlaceholderResponseBody(); tmpout.write(bytes(statusLine, 0), 0, statusLine.length()); boolean noContentToSend = false; // assume there is content rspHdrs.set("Date", df.format(new Date())); if (contentLen == 0) { if (http10) { o.setWrappedStream(new UndefLengthOutputStream(this, ros)); close = true; } else { rspHdrs.set("Transfer-encoding", "chunked"); o.setWrappedStream(new ChunkedOutputStream(this, ros)); } } else { if (contentLen == -1) { noContentToSend = true; contentLen = 0; } /* content len might already be set, eg to implement HEAD resp */ if (rspHdrs.getFirst("Content-length") == null) { rspHdrs.set("Content-length", Long.toString(contentLen)); } o.setWrappedStream(new FixedLengthOutputStream(this, ros, contentLen)); } write(rspHdrs, tmpout); this.rspContentLen = contentLen; tmpout.flush(); tmpout = null; sentHeaders = true; if (noContentToSend) { WriteFinishedEvent e = new WriteFinishedEvent(this); server.addEvent(e); closed = true; } server.logReply(rCode, req.requestLine(), null); }
public void run() { try { URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); if (urlc instanceof HttpsURLConnection) { HttpsURLConnection urlcs = (HttpsURLConnection) urlc; urlcs.setHostnameVerifier( new HostnameVerifier() { public boolean verify(String s, SSLSession s1) { return true; } }); urlcs.setSSLSocketFactory(ctx.getSocketFactory()); } byte[] buf = new byte[4096]; if (fixedLen) { urlc.setRequestProperty("XFixed", "yes"); } InputStream is = urlc.getInputStream(); File temp = File.createTempFile("Test1", null); temp.deleteOnExit(); OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp)); int c, count = 0; while ((c = is.read(buf)) != -1) { count += c; fout.write(buf, 0, c); } is.close(); fout.close(); if (count != size) { throw new RuntimeException("wrong amount of data returned"); } String orig = root + "/" + f; compare(new File(orig), temp); temp.delete(); } catch (Exception e) { e.printStackTrace(); fail = true; } }
void write(Headers map, OutputStream os) throws IOException { Set<Map.Entry<String, List<String>>> entries = map.entrySet(); for (Map.Entry<String, List<String>> entry : entries) { String key = entry.getKey(); byte[] buf; List<String> values = entry.getValue(); for (String val : values) { int i = key.length(); buf = bytes(key, 2); buf[i++] = ':'; buf[i++] = ' '; os.write(buf, 0, i); buf = bytes(val, 2); i = val.length(); buf[i++] = '\r'; buf[i++] = '\n'; os.write(buf, 0, i); } } os.write('\r'); os.write('\n'); }
/* * 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(); }
public static void main(String[] args) throws Exception { String host; int port; char[] passphrase; if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { System.out.println("Usage: java InstallCert <host>[:port] [passphrase]"); return; } File file = new File("jssecacerts"); if (file.isFile() == false) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } System.out.println("Loading KeyStore " + file + "..."); KeyStore ks; InputStream in = new FileInputStream(file); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); String line = reader.readLine().trim(); int k; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { System.out.println("KeyStore not changed"); return; } X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'"); }
/* * 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(); }
public void close() throws IOException { checkWrap(); wrapped.close(); }
public void flush() throws IOException { checkWrap(); wrapped.flush(); }
public void write(byte b[], int off, int len) throws IOException { checkWrap(); wrapped.write(b, off, len); }
public void write(byte b[]) throws IOException { checkWrap(); wrapped.write(b); }