Example usage for java.net Socket connect

List of usage examples for java.net Socket connect

Introduction

In this page you can find the example usage for java.net Socket connect.

Prototype

public void connect(SocketAddress endpoint, int timeout) throws IOException 

Source Link

Document

Connects this socket to the server with a specified timeout value.

Usage

From source file:monasca.api.integration.docker.ITInfluxDBTest.java

private void waitForPortReady(String host, int port) {

    System.out.println("waiting to connect to host [" + host + "] on port [" + port + "]");

    Socket s = null;
    boolean isPortReady = false;
    int tryCount = 0;
    while (!isPortReady) {

        if (tryCount >= MAX_CONNECT_PORT_TRIES) {
            System.err.println("Failed to connect to host [" + host + "] on port [" + port + "] in " + "["
                    + tryCount + "] tries");
            tearDown();/*from  w w w.  jav a  2 s.c o  m*/
            System.exit(-1);
        }

        try {
            s = new Socket();
            s.setReuseAddress(true);
            SocketAddress sa = new InetSocketAddress(host, port);
            s.connect(sa, 50000);
            isPortReady = true;
            System.out.println(
                    "Took " + tryCount + " tries to connect to host [" + host + "] on port" + "[" + port + "]");
        } catch (Exception e) {
            tryCount++;
        }
    }

    if (s != null) {
        try {
            s.close();
        } catch (Exception e) {
            System.err.print(e);
        }
    }
}

From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java

public HttpResponse(HttpBase http, URL url, WebPage page) throws ProtocolException, IOException {
    conf = http.getConf();/*from   w  w w  .  j a  v a 2s.c  o  m*/
    this.http = http;
    this.url = url;
    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new HttpException("Unknown scheme (not http/https) for url:" + url);
    }

    if (Http.LOG.isTraceEnabled()) {
        Http.LOG.trace("fetching " + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        if (sockAddr != null && conf.getBoolean("store.ip.address", false) == true) {
            String ipString = sockAddr.getAddress().getHostAddress(); // get the ip
                                                                      // address
            page.getMetadata().put(new Utf8("_ip_"), ByteBuffer.wrap(ipString.getBytes()));
        }

        Http.LOG.debug("HTTP fetching: " + url);
        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (Http.LOG.isErrorEnabled()) {
                Http.LOG.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        // if (page.isReadable(WebPage.Field.MODIFIED_TIME.getIndex())) {
        reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(page.getModifiedTime()));
        reqStr.append("\r\n");
        // }
        reqStr.append("\r\n");

        byte[] reqBytes = reqStr.toString().getBytes();

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE),
                        Http.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is "Continue"
        }

        if (!url.toString().endsWith("robots.txt")) {
            if (readPlainContent(url.toString(), in)) {
            } else if (readPlainContentByHtmlunit(url)) {
            } else {
                readPlainContentByWebDriver(url);
            }
        }

        if (content != null && content.length > 0) {
            String html = charset == null ? new String(content) : new String(content, charset);
            //System.out.println("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
            Http.LOG_HTML.trace("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
        }

        // add headers in metadata to row
        if (page.getHeaders() != null) {
            page.getHeaders().clear();
        }
        for (String key : headers.names()) {
            page.getHeaders().put(new Utf8(key), new Utf8(headers.get(key)));
        }

    } catch (Exception e) {
        Http.LOG.error(e.getMessage(), e);
    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java

/**
 * Builds a SSL Socket Factory for the Apache HTTP Client.
 *///www. ja va 2  s .  com
private SchemeLayeredSocketFactory getSSLSocketFactory(final UrlBuilder url, final BindingSession session) {
    // get authentication provider
    AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);

    // check SSL Socket Factory
    final SSLSocketFactory sf = authProvider.getSSLSocketFactory();
    if (sf == null) {
        // no custom factory -> return default factory
        return org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    }

    // check hostame verifier and use default if not set
    final HostnameVerifier hv = (authProvider.getHostnameVerifier() == null
            ? new BrowserCompatHostnameVerifier()
            : authProvider.getHostnameVerifier());

    if (hv instanceof X509HostnameVerifier) {
        return new org.apache.http.conn.ssl.SSLSocketFactory(sf, (X509HostnameVerifier) hv);
    }

    // build new socket factory
    return new SchemeLayeredSocketFactory() {

        @Override
        public boolean isSecure(Socket sock) {
            return true;
        }

        @Override
        public Socket createSocket(HttpParams params) throws IOException {
            return sf.createSocket();
        }

        @Override
        public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
                final InetSocketAddress localAddress, final HttpParams params) throws IOException {

            Socket sock = socket != null ? socket : createSocket(params);
            if (localAddress != null) {
                sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
                sock.bind(localAddress);
            }

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

            try {
                sock.setSoTimeout(soTimeout);
                sock.connect(remoteAddress, connTimeout);
            } catch (SocketTimeoutException ex) {
                closeSocket(sock);
                throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out!");
            }

            String host;
            if (remoteAddress instanceof HttpInetSocketAddress) {
                host = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
            } else {
                host = remoteAddress.getHostName();
            }

            SSLSocket sslSocket;
            if (sock instanceof SSLSocket) {
                sslSocket = (SSLSocket) sock;
            } else {
                int port = remoteAddress.getPort();
                sslSocket = (SSLSocket) sf.createSocket(sock, host, port, true);
            }
            verify(hv, host, sslSocket);

            return sslSocket;
        }

        @Override
        public Socket createLayeredSocket(final Socket socket, final String host, final int port,
                final HttpParams params) throws IOException {
            SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, true);
            verify(hv, host, sslSocket);

            return sslSocket;
        }
    };
}

From source file:orca.ektorp.client.ContextualSSLSocketFactory.java

/**
 * @since 4.1//from  ww w. j  av a  2  s . c o  m
 * @param socket socket
 * @param remoteAddress remote address
 * @param localAddress local address
 * @param params HTTP params
 * @throws IOException in case of IO error
 * @throws UnknownHostException in case of unknonwn host
 * @throws ConnectTimeoutException in case of connect timeout
 * @return returns the socket
 */
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    //Here!
    Socket sock = socket != null ? socket : this.socketfactory.createSocket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

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

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }

    String hostname;
    if (remoteAddress instanceof HttpInetSocketAddress) {
        hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
    } else {
        hostname = remoteAddress.getHostName();
    }

    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        int port = remoteAddress.getPort();
        sslsock = (SSLSocket) this.socketfactory.createSocket(sock, hostname, port, true);
        prepareSocket(sslsock);
    }
    if (this.hostnameVerifier != null) {
        try {
            this.hostnameVerifier.verify(hostname, 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;
}

From source file:org.apache.hadoop.hdfs.server.namenode.NamenodeFsck.java

private void copyBlock(final DFSClient dfs, LocatedBlock lblock, OutputStream fos) throws Exception {
    int failures = 0;
    InetSocketAddress targetAddr = null;
    TreeSet<DatanodeInfo> deadNodes = new TreeSet<DatanodeInfo>();
    BlockReader blockReader = null;/* ww w  . jav a 2  s.  co  m*/
    ExtendedBlock block = lblock.getBlock();

    while (blockReader == null) {
        DatanodeInfo chosenNode;

        try {
            chosenNode = bestNode(dfs, lblock.getLocations(), deadNodes);
            targetAddr = NetUtils.createSocketAddr(chosenNode.getXferAddr());
        } catch (IOException ie) {
            if (failures >= DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT) {
                throw new IOException("Could not obtain block " + lblock, ie);
            }
            LOG.info("Could not obtain block from any node:  " + ie);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException iex) {
            }
            deadNodes.clear();
            failures++;
            continue;
        }
        try {
            String file = BlockReaderFactory.getFileName(targetAddr, block.getBlockPoolId(),
                    block.getBlockId());
            blockReader = new BlockReaderFactory(dfs.getConf()).setFileName(file).setBlock(block)
                    .setBlockToken(lblock.getBlockToken()).setStartOffset(0).setLength(-1)
                    .setVerifyChecksum(true).setClientName("fsck").setDatanodeInfo(chosenNode)
                    .setInetSocketAddress(targetAddr).setCachingStrategy(CachingStrategy.newDropBehind())
                    .setClientCacheContext(dfs.getClientContext()).setConfiguration(namenode.conf)
                    .setRemotePeerFactory(new RemotePeerFactory() {
                        @Override
                        public Peer newConnectedPeer(InetSocketAddress addr,
                                Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId)
                                throws IOException {
                            Peer peer = null;
                            Socket s = NetUtils.getDefaultSocketFactory(conf).createSocket();
                            try {
                                s.connect(addr, HdfsServerConstants.READ_TIMEOUT);
                                s.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);
                                peer = TcpPeerServer.peerFromSocketAndKey(dfs.getSaslDataTransferClient(), s,
                                        NamenodeFsck.this, blockToken, datanodeId);
                            } finally {
                                if (peer == null) {
                                    IOUtils.closeQuietly(s);
                                }
                            }
                            return peer;
                        }
                    }).build();
        } catch (IOException ex) {
            // Put chosen node into dead list, continue
            LOG.info("Failed to connect to " + targetAddr + ":" + ex);
            deadNodes.add(chosenNode);
        }
    }
    byte[] buf = new byte[1024];
    int cnt = 0;
    boolean success = true;
    long bytesRead = 0;
    try {
        while ((cnt = blockReader.read(buf, 0, buf.length)) > 0) {
            fos.write(buf, 0, cnt);
            bytesRead += cnt;
        }
        if (bytesRead != block.getNumBytes()) {
            throw new IOException("Recorded block size is " + block.getNumBytes() + ", but datanode returned "
                    + bytesRead + " bytes");
        }
    } catch (Exception e) {
        LOG.error("Error reading block", e);
        success = false;
    } finally {
        blockReader.close();
    }
    if (!success) {
        throw new Exception("Could not copy block data for " + lblock.getBlock());
    }
}

From source file:com.clavain.munin.MuninNode.java

/**
 * Will load the plugin list from munin-node
 *///from w w w .  j  a va 2s  .  com
public boolean loadPlugins() {
    setLoadedPlugins(new CopyOnWriteArrayList<MuninPlugin>());
    String l_lastProceeded = "";

    try {
        Socket cs = new Socket();
        cs.setKeepAlive(false);
        cs.setSoLinger(true, 0);
        cs.setReuseAddress(true);
        cs.setSoTimeout(com.clavain.muninmxcd.socketTimeout);
        if (!str_via.equals("unset")) {
            cs.connect(new InetSocketAddress(this.getStr_via(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        } else {
            cs.connect(new InetSocketAddress(this.getHostname(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        }

        if (p.getProperty("kill.sockets").equals("true")) {
            SocketCheck sc = new SocketCheck(cs, getUnixtime());
            sc.setHostname(this.getHostname());
            com.clavain.muninmxcd.v_sockets.add(sc);
        }
        PrintStream os = new PrintStream(cs.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));

        String s = in.readLine();

        if (s != null) {
            // Set version
            os.println("version");
            Thread.sleep(150);
            s = in.readLine();

            String version = s.substring(s.indexOf(":") + 1, s.length()).trim();
            this.str_muninVersion = version;

            if (authpw != null) {
                // if authpw is set, verify
                if (!authpw.trim().equals("")) {
                    os.println("config muninmxauth");
                    Thread.sleep(150);
                    String apw = in.readLine();
                    s = in.readLine();
                    if (!apw.trim().equals(this.getAuthpw())) {
                        logger.error("Invalid muninmxauth password for host: " + this.getHostname());
                        cs.close();
                        return false;
                    }
                }
            }
            // check anyway if muninmxauth plugin is present
            else {
                os.println("config muninmxauth");
                Thread.sleep(100);
                String apw = in.readLine();
                if (!apw.trim().equals("# Unknown service")) {
                    logger.error(
                            "no auth password given, but muninmxauth plugin present on " + this.getHostname());
                    cs.close();
                    return false;
                }
                s = in.readLine();
            }

            // get list of available plugins
            if (str_via.equals("unset")) {
                os.println("list");
            } else {
                os.println("list " + str_hostname);
            }

            Thread.sleep(250);
            s = in.readLine();

            // if response is empty and host is not via, do a list $hostname
            if (s.trim().equals("") && str_via.equals("unset")) {
                logger.info("Plugin Response Empty on " + this.getHostname()
                        + " trying to load with list $hostname");
                os.println("list " + this.getHostname());
                Thread.sleep(250);
                s = in.readLine();
            }

            String l_tmp;
            StringTokenizer l_st = new StringTokenizer(s, " ");

            // create plugin
            MuninPlugin l_mp = new MuninPlugin();
            // negative support
            ArrayList<String> tmp_negatives = new ArrayList<String>();

            while (l_st.hasMoreTokens()) {

                String l_strPlugin = l_st.nextToken();

                // check for track_pkg and muninmx essentials
                if (l_strPlugin.equals("muninmx_trackpkg")) {
                    this.setTrack_pkg(true);
                    continue;
                }

                // got essentials?
                if (l_strPlugin.equals("muninmx_essentials")) {
                    this.setEssentials(true);
                    continue;
                }

                if (isPluginIgnored(l_strPlugin.toUpperCase())) {
                    continue;
                }

                l_mp.setPluginName(l_strPlugin);

                os.println("config " + l_strPlugin);

                // create graphs for plugin
                int l_iGraphsFound = 0;
                int l_iTmp = 0;
                MuninGraph l_mg = new MuninGraph();
                l_mg.setQueryInterval(this.getQueryInterval());
                while ((l_tmp = in.readLine()) != null) {
                    if (l_tmp.startsWith(".")) {
                        break;
                    }
                    // collect graphs only for plugin
                    String l_strName;
                    String l_strType;
                    String l_strValue;

                    if (!l_tmp.contains("graph_") && !l_tmp.trim().equals("") && !l_tmp.contains("host_name")
                            && !l_tmp.contains("multigraph") && !l_tmp.trim().equals("graph no")
                            && !l_tmp.trim().equals("# Bad exit")
                            && !l_tmp.trim().contains("info Currently our peer")
                            && !l_tmp.trim().startsWith("#")
                            && !l_tmp.trim().contains("Bonding interface errors")) {
                        l_lastProceeded = l_tmp;
                        l_strName = l_tmp.substring(0, l_tmp.indexOf("."));
                        l_strType = l_tmp.substring(l_tmp.indexOf(".") + 1, l_tmp.indexOf(" "));
                        l_strValue = l_tmp.substring(l_tmp.indexOf(" ") + 1, l_tmp.length());
                        //System.err.println("Name: " + l_strName + " Type: " + l_strType + " Value: " + l_strValue);

                        if (l_strType.equals("label")) {
                            l_iTmp++;

                            if (l_iTmp > 1) {
                                l_mp.addGraph(l_mg);
                                l_mg = new MuninGraph();
                                l_mg.setQueryInterval(this.getQueryInterval());
                            }
                            l_mg.setGraphName(l_strName);
                            l_mg.setGraphLabel(l_strValue);
                        } else if (l_strType.equals("draw")) {
                            l_mg.setGraphDraw(l_strValue);
                        } else if (l_strType.equals("type")) {
                            l_mg.setGraphType(l_strValue);
                        } else if (l_strType.equals("info")) {
                            l_mg.setGraphInfo(l_strValue);
                        } else if (l_strType.equals("negative")) {
                            // add to temporary negative list to set negatives later
                            tmp_negatives.add(l_strValue);
                        }

                        //System.out.println(l_strName); 
                        //System.out.println(l_strType);
                        //System.out.println(l_strValue);
                    } else {
                        // set plugin title
                        if (l_tmp.contains("graph_title")) {
                            l_mp.setPluginTitle(l_tmp.substring(12, l_tmp.length()));
                        }
                        // set plugin info, if any
                        if (l_tmp.contains("graph_info")) {
                            l_mp.setPluginInfo(l_tmp.substring(11, l_tmp.length()));
                        }
                        // set graph category
                        if (l_tmp.contains("graph_category")) {
                            l_mp.setPluginCategory(l_tmp.substring(15, l_tmp.length()));
                        }
                        // set graph vlabel
                        if (l_tmp.contains("graph_vlabel")) {
                            l_mp.setPluginLabel(l_tmp.substring(13, l_tmp.length()));
                        }
                        // set plugin title
                        if (l_tmp.contains("graph_mxdraw")) {
                            l_mp.setStr_LineMode(l_tmp.substring(13, l_tmp.length()));
                        }
                    }

                }

                // add to pluginlist
                l_mp.addGraph(l_mg);

                Iterator it = l_mp.getGraphs().iterator();
                while (it.hasNext()) {
                    MuninGraph l_mpNg = (MuninGraph) it.next();
                    if (tmp_negatives.contains(l_mpNg.getGraphName())) {
                        l_mpNg.setNegative(true);
                    }
                }

                // add plugin if it got valid graphs and add nodeid (req. for alerts)
                if (l_mp.getGraphs().size() > 0) {
                    l_mp.set_NodeId(this.getNode_id());
                    getLoadedPlugins().add(l_mp);
                }
                // flush temporary negatives
                tmp_negatives.clear();
                l_mp = null;
                l_mp = new MuninPlugin();
                //String l_strGraphTitle = s.substring(s.indexOf("graph_title") + 11,s.length());
                //System.out.println(" - " + l_strGraphTitle);
            }
            cs.close();
            in.close();
            os.close();
            last_plugin_load = getUnixtime();
            //System.out.println(s);
        } else {
            cs.close();
            in.close();
            os.close();
            logger.warn("Error loading plugins on " + str_hostname + " (" + this.getNode_id()
                    + "). Check connectivity or munin-node");
        }
        /*
        for (MuninPlugin l_mn : getLoadedPlugins()) {
        i_GraphCount = i_GraphCount + l_mn.getGraphs().size();
        logger.debug(l_mn.getGraphs().size() + " graphs found for plugin: " + l_mn.getPluginName().toUpperCase() + " on node: " + this.getNodename());
        }*/
    } catch (Exception ex) {
        logger.error("Error loading plugins on " + str_hostname + " (" + this.getNode_id() + ") : "
                + ex.getMessage());
        ex.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.apache.jmeter.protocol.tcp.sampler.TCPSampler.java

private Socket getSocket(String socketKey) {
    Map<String, Object> cp = tp.get();
    Socket con = null;
    if (isReUseConnection()) {
        con = (Socket) cp.get(socketKey);
        if (con != null) {
            log.debug(this + " Reusing connection " + con); //$NON-NLS-1$
        }/*w ww  . j a v a  2 s  .  com*/
    }
    if (con == null) {
        // Not in cache, so create new one and cache it
        try {
            closeSocket(socketKey); // Bug 44910 - close previous socket (if any)
            SocketAddress sockaddr = new InetSocketAddress(getServer(), getPort());
            con = new Socket();
            if (getPropertyAsString(SO_LINGER, "").length() > 0) {
                con.setSoLinger(true, getSoLinger());
            }
            con.connect(sockaddr, getConnectTimeout());
            if (log.isDebugEnabled()) {
                log.debug("Created new connection " + con); //$NON-NLS-1$
            }
            cp.put(socketKey, con);
        } catch (UnknownHostException e) {
            log.warn("Unknown host for " + getLabel(), e);//$NON-NLS-1$
            cp.put(ERRKEY, e.toString());
            return null;
        } catch (IOException e) {
            log.warn("Could not create socket for " + getLabel(), e); //$NON-NLS-1$
            cp.put(ERRKEY, e.toString());
            return null;
        }
    }
    // (re-)Define connection params - Bug 50977 
    try {
        con.setSoTimeout(getTimeout());
        con.setTcpNoDelay(getNoDelay());
        if (log.isDebugEnabled()) {
            log.debug(this + "  Timeout " + getTimeout() + " NoDelay " + getNoDelay()); //$NON-NLS-1$
        }
    } catch (SocketException se) {
        log.warn("Could not set timeout or nodelay for " + getLabel(), se); //$NON-NLS-1$
        cp.put(ERRKEY, se.toString());
    }
    return con;
}

From source file:org.zaproxy.zap.extension.ascanrulesAlpha.HeartBleedActiveScanner.java

/**
 * scans the node for the vulnerability   
 *///from  ww  w .j  av  a 2s.c om
@Override
public void scan() {

    try {
        //get the network details for the attack
        String hostname = this.getBaseMsg().getRequestHeader().getURI().getHost();
        int portnumber = this.getBaseMsg().getRequestHeader().getURI().getPort();
        //use the default HTTPS port, if the URI did not contain an explicit port number
        //or if the URL was via HTTP, rather than via HTTPS (yes, we will still check it)
        if (portnumber == -1 || portnumber == 80)
            portnumber = 443;

        if (log.isDebugEnabled())
            log.debug("About to look for HeartBleed on " + hostname + ":" + portnumber);
        for (int tlsIndex = 0; tlsIndex < tlsBuffers.length; tlsIndex++) {
            if (log.isDebugEnabled())
                log.debug("-------------------- Trying " + tlsNames[tlsIndex] + " --------------------");

            Socket socket = null;
            OutputStream os = null;
            InputStream is = null;
            try {
                //establish a raw socket connection, without proxying it (the request will definitely not appear in Zap's history tab)
                socket = new Socket();
                try {
                    socket.connect(new InetSocketAddress(hostname, portnumber), this.timeoutMs);
                    if (log.isDebugEnabled())
                        log.debug("Connected");
                } catch (Exception e) {
                    //we cannot connect at all.. no point in continuing.
                    log.error("Cannot establish a socket connection to " + hostname + ":" + portnumber
                            + " for HeartBleed");
                    return;
                }

                //get the streams
                os = socket.getOutputStream();
                is = socket.getInputStream();

                //send the client Hello
                //prepare some length info - 3 byte message length, and 2 byte record length
                int messagelen = tlsBuffers[tlsIndex].length + helloBuffer.length;
                int recordlen = messagelen + 4;
                byte[] messageLenBytes = new byte[3];
                messageLenBytes[0] = (byte) (messagelen >> 16);
                messageLenBytes[1] = (byte) (messagelen >> 8);
                messageLenBytes[2] = (byte) (messagelen);
                byte[] recordLenBytes = new byte[2];
                recordLenBytes[0] = (byte) (recordlen >> 8);
                recordLenBytes[1] = (byte) (recordlen);

                //now write the Hello message
                os.write(handshakeRecordByte);
                os.write(tlsBuffers[tlsIndex]);
                os.write(recordLenBytes);
                os.write(handShakeClientHello);
                os.write(messageLenBytes);
                os.write(tlsBuffers[tlsIndex]);
                os.write(helloBuffer);
                if (log.isDebugEnabled())
                    log.debug("Wrote the Client Hello");

                //read through messages until we get a handshake message back from the server
                try {
                    while (true) {
                        SSLRecord sslRecord = recvmsg(is, this.timeoutMs);
                        if (sslRecord.typ == handshakeRecordByte && sslRecord.len > 0
                                && sslRecord.pay[0] == 0x0E)
                            break;
                        if (log.isDebugEnabled())
                            log.debug(
                                    "Got a reponse from the server, but it was not a server hello 'Done' message");
                    }
                } catch (IOException e) {
                    //if we do not get back a server hello, it is because
                    //the server does not support the SSL/TLS variant we passed it.
                    throw new IOException(tlsNames[tlsIndex]
                            + " is not supported by the server, or a common cipher suite could not be agreed");
                }

                if (log.isDebugEnabled())
                    log.debug("Got the Server Hello");

                //all the SSL initialisation is complete.  So is the SSL server vulnerable?
                boolean vulnerable = isVulnerable(is, os, this.timeoutMs, tlsBuffers[tlsIndex]); //put a timeout on the check for each of the TLS variants
                if (vulnerable) {
                    if (log.isDebugEnabled())
                        log.debug("Vulnerable");
                    //bingo!
                    String extraInfo = Constant.messages.getString(MESSAGE_PREFIX + "extrainfo",
                            tlsNames[tlsIndex]);
                    bingo(getRisk(), Alert.WARNING, getName(), getDescription(),
                            getBaseMsg().getRequestHeader().getURI().getURI(), "", //param 
                            "", //attack
                            extraInfo, getSolution(), "", //evidence
                            getBaseMsg());
                }
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
                if (socket != null)
                    socket.close();
            } catch (Exception e) {
                //this particular variant is not vulnerable. skip to the next one..
                if (log.isDebugEnabled())
                    log.debug("The SSL server does not appear to be vulnerable, using " + tlsNames[tlsIndex]
                            + ": " + e.getMessage());
            } finally {
                if (log.isDebugEnabled())
                    log.debug("Tidying up");
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
                if (socket != null)
                    socket.close();
            }
        }
    } catch (Exception e) {
        //needed to catch exceptions from the "finally" statement 
        log.error("Error scanning a node for HeartBleed: " + e.getMessage(), e);
    }
}

From source file:org.openqa.selenium.remote.ReusingSocketSocketFactory.java

public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException {

    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }//from   w  w  w . j a v a2  s. c o  m
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    if (sock == null)
        sock = createSocket();

    sock.setReuseAddress(true); // This is the 1 line added by kristian
    if ((localAddress != null) || (localPort > 0)) {

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

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

    int timeout = HttpConnectionParams.getConnectionTimeout(params);

    InetSocketAddress remoteAddress;
    if (this.nameResolver != null) {
        remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port);
    } else {
        remoteAddress = new InetSocketAddress(host, port);
    }
    try {
        sock.connect(remoteAddress, timeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
    return sock;
}

From source file:org.zaproxy.zap.extension.ascanrulesBeta.HeartBleedActiveScanner.java

/** scans the node for the vulnerability */
@Override//  w ww.j  a  va2 s .c  om
public void scan() {

    try {
        // get the network details for the attack
        String hostname = this.getBaseMsg().getRequestHeader().getURI().getHost();
        int portnumber = this.getBaseMsg().getRequestHeader().getURI().getPort();
        // use the default HTTPS port, if the URI did not contain an explicit port number
        // or if the URL was via HTTP, rather than via HTTPS (yes, we will still check it)
        if (portnumber == -1 || portnumber == 80)
            portnumber = 443;

        if (log.isDebugEnabled())
            log.debug("About to look for HeartBleed on " + hostname + ":" + portnumber);
        for (int tlsIndex = 0; tlsIndex < tlsBuffers.length; tlsIndex++) {
            if (log.isDebugEnabled())
                log.debug("-------------------- Trying " + tlsNames[tlsIndex] + " --------------------");

            Socket socket = null;
            OutputStream os = null;
            InputStream is = null;
            try {
                // establish a raw socket connection, without proxying it (the request will
                // definitely not appear in Zap's history tab)
                socket = new Socket();
                try {
                    socket.connect(new InetSocketAddress(hostname, portnumber), this.timeoutMs);
                    if (log.isDebugEnabled())
                        log.debug("Connected");
                    // set a timeout on the socket for reads..
                    socket.setSoTimeout(this.timeoutMs);
                } catch (Exception e) {
                    // we cannot connect at all.. no point in continuing.
                    log.debug("Cannot establish a socket connection to " + hostname + ":" + portnumber
                            + " for HeartBleed");
                    return;
                }

                // get the streams
                os = socket.getOutputStream();
                is = socket.getInputStream();

                // send the client Hello
                // prepare some length info - 3 byte message length, and 2 byte record length
                int messagelen = tlsBuffers[tlsIndex].length + helloBuffer.length;
                int recordlen = messagelen + 4;
                byte[] messageLenBytes = new byte[3];
                messageLenBytes[0] = (byte) (messagelen >> 16);
                messageLenBytes[1] = (byte) (messagelen >> 8);
                messageLenBytes[2] = (byte) (messagelen);
                byte[] recordLenBytes = new byte[2];
                recordLenBytes[0] = (byte) (recordlen >> 8);
                recordLenBytes[1] = (byte) (recordlen);

                // now write the Hello message
                os.write(handshakeRecordByte);
                os.write(tlsBuffers[tlsIndex]);
                os.write(recordLenBytes);
                os.write(handShakeClientHello);
                os.write(messageLenBytes);
                os.write(tlsBuffers[tlsIndex]);
                os.write(helloBuffer);
                if (log.isDebugEnabled())
                    log.debug("Wrote the Client Hello");

                getParent().notifyNewMessage(this);

                // read through messages until we get a handshake message back from the server
                try {
                    while (true) {
                        SSLRecord sslRecord = recvmsg(is, this.timeoutMs);
                        if (sslRecord.typ == handshakeRecordByte && sslRecord.len > 0
                                && sslRecord.pay[0] == 0x0E) {
                            break;
                        }
                        if (log.isDebugEnabled())
                            log.debug(
                                    "Got a reponse from the server, but it was not a server hello 'Done' message");
                    }
                } catch (SocketTimeoutException es) {
                    throw new IOException("The timeout was exceeded while attempting to read the Server Hello");
                } catch (IOException e) {
                    // if we do not get back a server hello, it is because
                    // the server does not support the SSL/TLS variant we passed it.
                    throw new IOException(tlsNames[tlsIndex]
                            + " is not supported by the server, or a common cipher suite could not be agreed");
                }

                if (log.isDebugEnabled())
                    log.debug("Got the Server Hello");

                // all the SSL initialisation is complete.  So is the SSL server vulnerable?
                boolean vulnerable = isVulnerable(is, os, this.timeoutMs, tlsBuffers[tlsIndex]); // put a timeout on the check for each of
                // the TLS variants
                if (vulnerable) {
                    if (log.isDebugEnabled())
                        log.debug("Vulnerable");
                    // bingo!
                    String extraInfo = Constant.messages.getString(MESSAGE_PREFIX + "extrainfo",
                            tlsNames[tlsIndex]);
                    bingo(getRisk(), Alert.CONFIDENCE_MEDIUM, getName(), getDescription(),
                            getBaseMsg().getRequestHeader().getURI().getURI(), "", // param
                            "", // attack
                            extraInfo, getSolution(), "", // evidence
                            getBaseMsg());
                }
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
                if (socket != null)
                    socket.close();
            } catch (Exception e) {
                // this particular variant is not vulnerable. skip to the next one..
                if (log.isDebugEnabled())
                    log.debug("The SSL server does not appear to be vulnerable, using " + tlsNames[tlsIndex]
                            + ": " + e.getMessage());
            } finally {
                if (log.isDebugEnabled())
                    log.debug("Tidying up");
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
                if (socket != null)
                    socket.close();
            }
        }
    } catch (Exception e) {
        // needed to catch exceptions from the "finally" statement
        log.error("Error scanning a node for HeartBleed: " + e.getMessage(), e);
    }
}