示例#1
0
  /**
   * Constructor, specifying the server host:port combination, login data and an output stream.
   *
   * @param host server name
   * @param port server port
   * @param user user name
   * @param pass password
   * @param output client output; if set to {@code null}, results will be returned as strings.
   * @throws IOException I/O exception
   */
  public ClientSession(
      final String host,
      final int port,
      final String user,
      final String pass,
      final OutputStream output)
      throws IOException {

    super(output);
    ehost = host;
    socket = new Socket();
    try {
      // limit timeout to five seconds
      socket.connect(new InetSocketAddress(host, port), 5000);
    } catch (final IllegalArgumentException ex) {
      throw new BaseXException(ex);
    }
    sin = socket.getInputStream();

    // receive timestamp
    final BufferInput bi = new BufferInput(sin);
    final String ts = bi.readString();

    // send user name and hashed password/timestamp
    sout = PrintOutput.get(socket.getOutputStream());
    send(user);
    send(Token.md5(Token.md5(pass) + ts));
    sout.flush();

    // receive success flag
    if (!ok(bi)) throw new LoginException();
  }
示例#2
0
  /** Internal method. Connect to searchd and exchange versions. */
  private Socket _Connect() {
    if (_socket != null) return _socket;

    _connerror = false;
    Socket sock = null;
    try {
      sock = new Socket();
      sock.setSoTimeout(_timeout);
      InetSocketAddress addr = new InetSocketAddress(_host, _port);
      sock.connect(addr, _timeout);

      DataInputStream sIn = new DataInputStream(sock.getInputStream());
      int version = sIn.readInt();
      if (version < 1) {
        sock.close();
        _error = "expected searchd protocol version 1+, got version " + version;
        return null;
      }

      DataOutputStream sOut = new DataOutputStream(sock.getOutputStream());
      sOut.writeInt(VER_MAJOR_PROTO);

    } catch (IOException e) {
      _error = "connection to " + _host + ":" + _port + " failed: " + e;
      _connerror = true;

      try {
        if (sock != null) sock.close();
      } catch (IOException e1) {
      }
      return null;
    }

    return sock;
  }
示例#3
0
 private void passTcpFileDescriptor(
     LocalSocket fdSocket,
     OutputStream outputStream,
     String socketId,
     String dstIp,
     int dstPort,
     int connectTimeout)
     throws Exception {
   Socket sock = new Socket();
   sock.setTcpNoDelay(true); // force file descriptor being created
   if (protect(sock)) {
     try {
       sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout);
       ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock);
       tcpSockets.put(socketId, sock);
       fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()});
       outputStream.write('*');
       outputStream.flush();
       fd.detachFd();
     } catch (ConnectException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } catch (SocketTimeoutException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } finally {
       outputStream.flush();
     }
   } else {
     LogUtils.e("protect tcp socket failed");
   }
 }
示例#4
0
  /** Constructor declaration */
  public JICPConnection(TransportAddress ta, int timeout) throws IOException {
    // #MIDP_EXCLUDE_BEGIN
    // For some reason the local address or port may be in use
    while (true) {
      try {
        // #PJAVA_EXCLUDE_BEGIN
        sc = new Socket();
        bindSocket(sc);
        sc.setTcpNoDelay(true);
        sc.connect(new InetSocketAddress(ta.getHost(), Integer.parseInt(ta.getPort())), timeout);
        // #PJAVA_EXCLUDE_END
        /*#PJAVA_INCLUDE_BEGIN
        sc = new Socket(ta.getHost(), Integer.parseInt(ta.getPort()));
        #PJAVA_INCLUDE_END*/
        is = sc.getInputStream();
        os = getOutputStream();
        break;
      } catch (BindException be) {
        // Do nothing and try again
      }
    }
    // #MIDP_EXCLUDE_END

    /*#MIDP_INCLUDE_BEGIN
    String url = "socket://"+ta.getHost()+":"+ta.getPort();
    sc = (StreamConnection) Connector.open(url, Connector.READ_WRITE, false);
    is = sc.openInputStream();
    os = getOutputStream();
    #MIDP_INCLUDE_END*/
  }
示例#5
0
 @Override
 public Socket createSocket(InetAddress host, int port, InetAddress local, int localPort)
     throws IOException {
   Socket s = createSocket();
   s.bind(new InetSocketAddress(local, localPort));
   s.connect(new InetSocketAddress(host, port), SO_CONNECT_TIMEOUT);
   return s;
 }
示例#6
0
 private void setupUserport() {
   userSock = new Socket();
   try {
     userSock.connect(new InetSocketAddress(IP, USERPORT), 10000);
     fromUser = new BufferedReader(new InputStreamReader(userSock.getInputStream()));
     toUser = new PrintStream(new DataOutputStream(userSock.getOutputStream()));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#7
0
 private void setupAltSocket() {
   altSock = new Socket();
   try {
     altSock.connect(new InetSocketAddress(IP, ALTPORT), 10000);
     altSockIn = new BufferedReader(new InputStreamReader(altSock.getInputStream()));
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  /** Attach to the specified address with optional attach and handshake timeout. */
  public Connection attach(String address, long attachTimeout, long handshakeTimeout)
      throws IOException {

    if (address == null) {
      throw new NullPointerException("address is null");
    }
    if (attachTimeout < 0 || handshakeTimeout < 0) {
      throw new IllegalArgumentException("timeout is negative");
    }

    int splitIndex = address.indexOf(':');
    String host;
    String portStr;
    if (splitIndex < 0) {
      host = InetAddress.getLocalHost().getHostName();
      portStr = address;
    } else {
      host = address.substring(0, splitIndex);
      portStr = address.substring(splitIndex + 1);
    }

    int port;
    try {
      port = Integer.decode(portStr).intValue();
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("unable to parse port number in address");
    }

    // open TCP connection to VM

    InetSocketAddress sa = new InetSocketAddress(host, port);
    Socket s = new Socket();
    try {
      s.connect(sa, (int) attachTimeout);
    } catch (SocketTimeoutException exc) {
      try {
        s.close();
      } catch (IOException x) {
      }
      throw new TransportTimeoutException("timed out trying to establish connection");
    }

    // handshake with the target VM
    try {
      handshake(s, handshakeTimeout);
    } catch (IOException exc) {
      try {
        s.close();
      } catch (IOException x) {
      }
      throw exc;
    }

    return new SocketConnection(s);
  }
示例#9
0
    private void doConnect(InetSocketAddress addr) throws IOException {
      dest = new Socket();
      try {
        dest.connect(addr, 10000);
      } catch (SocketTimeoutException ex) {
        sendError(HOST_UNREACHABLE);
        return;
      } catch (ConnectException cex) {
        sendError(CONN_REFUSED);
        return;
      }
      // Success
      InetAddress iadd = addr.getAddress();
      if (iadd instanceof Inet4Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV4);
        out.write(iadd.getAddress());
      } else if (iadd instanceof Inet6Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV6);
        out.write(iadd.getAddress());
      } else {
        sendError(GENERAL_FAILURE);
        return;
      }
      out.write((addr.getPort() >> 8) & 0xff);
      out.write((addr.getPort() >> 0) & 0xff);
      out.flush();

      InputStream in2 = dest.getInputStream();
      OutputStream out2 = dest.getOutputStream();

      Tunnel tunnel = new Tunnel(in2, out);
      tunnel.start();

      int b = 0;
      do {
        // Note that the socket might be closed from another thread (the tunnel)
        try {
          b = in.read();
          if (b == -1) {
            in.close();
            out2.close();
            return;
          }
          out2.write(b);
        } catch (IOException ioe) {
        }
      } while (!client.isClosed());
    }
  /**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy. It issues a
   * CONNECT request and eventually authenticates with the HTTP proxy. Supported authentication
   * methods include: Basic.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws UnknownHostException if the proxy host name cannot be resolved
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket getHttpsTunnelSocket(
      InetSocketAddress address, ConnectivitySettings cs, int timeout) throws IOException {
    Socket proxy = new Socket();
    proxy.connect(new InetSocketAddress(cs.getProxyHost(), cs.getProxyPort()), timeout);
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n\r\n");
    dos.flush();

    String line;
    line = r.readLine();

    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    } else if (sProxyAuthRequiredPattern.matcher(line).find()) {
      boolean authMethodSelected = false;
      String authMethod = AUTH_NONE;
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
        if (line.startsWith("Proxy-Authenticate:") && !authMethodSelected) {
          authMethod = line.substring(19).trim();
          if (authMethod.equals(AUTH_BASIC)) {
            authMethodSelected = true;
          }
        }
      }
      // TODO: need to read full response before closing connection?
      proxy.close();

      if (authMethod.startsWith(AUTH_BASIC)) {
        return authenticateBasic(address, cs);
      } else {
        throw new IOException("Unsupported authentication method: " + authMethod);
      }
    } else {
      proxy.close();
      throw new IOException("HTTP proxy does not support CONNECT command. Received reply: " + line);
    }
  }
  private Socket createSocket(ConnectivitySettings cs, InetSocketAddress address, int timeout)
      throws IOException {
    switch (cs.getConnectionType()) {
      case ConnectivitySettings.CONNECTION_VIA_SOCKS:
      case ConnectivitySettings.CONNECTION_DIRECT:
        Socket s = new Socket();
        s.connect(address, timeout);
        return s;

      case ConnectivitySettings.CONNECTION_VIA_HTTPS:
        return getHttpsTunnelSocket(address, cs, timeout);

      default:
        throw new IllegalArgumentException("Illegal connection type: " + cs.getConnectionType());
    }
  }
示例#12
0
  /**
   * Constructor.
   *
   * @param host server name
   * @param port server port
   * @param user user name
   * @param pass password
   * @throws IOException Exception
   */
  public BaseXClient(final String host, final int port, final String user, final String pass)
      throws IOException {

    socket = new Socket();
    socket.connect(new InetSocketAddress(host, port), 5000);
    in = new BufferedInputStream(socket.getInputStream());
    out = socket.getOutputStream();
    ehost = host;

    // receive timestamp
    final String ts = receive();
    // send {Username}0 and hashed {Password/Timestamp}0
    send(user);
    send(md5(md5(pass) + ts));

    // receive success flag
    if (!ok()) throw new IOException("Access denied.");
  }
示例#13
0
  public void run() {
    try {

      sc = new Socket();
      InetSocketAddress isa = new InetSocketAddress("localhost", 9999);
      sc.connect(isa);
      OutputStream ost = sc.getOutputStream();

      for (int i = 0; i < 10; ++i) {
        String str = "client interation " + (new Integer(i)).toString();
        ost.write(str.getBytes());
        ost.flush();
        System.out.println("Client at " + (new Integer(i)).toString());
        sleep(1000);
      }
    } catch (Exception e) {
    }
  }
示例#14
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);
 }
示例#15
0
  public boolean connect() {
    try {

      // if(hasPass) {
      // password = JOptionPane.showInputDialog("Please enter the password for this server.");
      //	}

      // establishing connection to server

      client = new Socket();
      client.connect(new InetSocketAddress(IP, PORT), 10000);

      setupAltSocket();
      setupUserport();

      toServer = new PrintWriter(new DataOutputStream(client.getOutputStream()));
      // need output stream to server

      inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
      toServer.println(password);

      toServer.flush();

      String temp = inFromServer.readLine();
      // System.out.println(temp + "this is what was read");
      if (temp.equals("BAD_PW")) {
        JOptionPane.showMessageDialog(
            null, "Password to server was rejected, or server is no longer active.");
        client.close();
        return false;
      }

      return startOnServer();

    } catch (Exception e) {

      JOptionPane.showMessageDialog(null, "Error! Cannot connect to specified server.");
      return false;
    }
  }
示例#16
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 {

    sout.write(ServerCmd.WATCH.code);
    if (esocket == null) {
      sout.flush();
      final BufferInput bi = new BufferInput(sin);
      final int eport = Integer.parseInt(bi.readString());
      // initialize event socket
      esocket = new Socket();
      esocket.connect(new InetSocketAddress(ehost, eport), 5000);
      final OutputStream so = esocket.getOutputStream();
      so.write(bi.readBytes());
      so.write(0);
      so.flush();
      final InputStream is = esocket.getInputStream();
      is.read();
      listen(is);
    }
    send(name);
    sout.flush();
    receive(null);
    notifiers.put(name, notifier);
  }
  public Socket createSocket(String host, int port)
      throws IOException, FingerprintException, FingerprintError {

    Socket s = new Socket();
    s.connect(new InetSocketAddress(proxyHost, proxyPort), 1000 * timeout);

    PrintWriter out = new PrintWriter(s.getOutputStream());
    InputStreamReader isr = new InputStreamReader(s.getInputStream());
    BufferedReader in = new BufferedReader(isr);

    String[] connHdr = {
      "CONNECT " + host + ":" + port + " HTTP/1.1",
      "Host: " + host + ":" + port,
      "Proxy-Connection: close"
    };

    String[] connReq = null;

    if (authRequired) {
      connReq = new String[connHdr.length + 1];
      for (int i = 0; i < connHdr.length; i++) {
        connReq[i] = connHdr[i];
      }
      connReq[connHdr.length] = "Proxy-Authorization: " + authenticator;
    } else {
      connReq = new String[connHdr.length];
      for (int i = 0; i < connHdr.length; i++) {
        connReq[i] = connHdr[i];
      }
    }
    sendRequest(out, connReq);

    HttpResponseHeader hdr = new HttpResponseHeader(in);
    int status = hdr.getStatusCode();

    if (Debug.get(Debug.Communication)) {
      System.err.println("Got status " + status);
    }

    /* Now check the status code and act upon it */
    if ((status / 100) == 2) { // Code is 2xx
      return s;
    }

    if (((status / 100) == 4) && (status != 407)) {
      throw new HttpProxyError("Proxy request failed");
    }

    if ((status == 407) && authRequired) {
      /* We already sent authorisation info,
       * but the proxy did not accept it.
       * So we can only stop here, as
       * we do not have the right credentials
       * at hand.
       */
      throw new HttpProxyError("Cannot authenticate " + "to proxy, wrong " + "credentials?");
    }
    if (status == 407) {
      if (Debug.get(Debug.SockInit)) {
        System.err.println("Preparing proxy " + "authenticator for " + hdr.getProxyAuthInfo());
      }
      prepareAuthorisation(hdr.getProxyAuthInfo());
      authRequired = true;
      return createSocket(host, port);
    }
    return s;
  }
示例#18
0
 @Override
 public Socket createSocket(String host, int port) throws IOException {
   Socket s = createSocket();
   s.connect(new InetSocketAddress(host, port), SO_CONNECT_TIMEOUT);
   return s;
 }
    @Override
    public synchronized void open(int mode) throws MessagingException {
      if (isOpen()) {
        return;
      }

      if (!mName.equalsIgnoreCase(mStoreConfig.getInboxFolderName())) {
        throw new MessagingException("Folder does not exist");
      }

      try {
        SocketAddress socketAddress = new InetSocketAddress(mHost, mPort);
        if (mConnectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) {
          mSocket = mTrustedSocketFactory.createSocket(null, mHost, mPort, mClientCertificateAlias);
        } else {
          mSocket = new Socket();
        }

        mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
        mIn = new BufferedInputStream(mSocket.getInputStream(), 1024);
        mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512);

        mSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
        if (!isOpen()) {
          throw new MessagingException("Unable to connect socket");
        }

        String serverGreeting = executeSimpleCommand(null);

        mCapabilities = getCapabilities();
        if (mConnectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) {

          if (mCapabilities.stls) {
            executeSimpleCommand(STLS_COMMAND);

            mSocket =
                mTrustedSocketFactory.createSocket(mSocket, mHost, mPort, mClientCertificateAlias);
            mSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
            mIn = new BufferedInputStream(mSocket.getInputStream(), 1024);
            mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512);
            if (!isOpen()) {
              throw new MessagingException("Unable to connect socket");
            }
            mCapabilities = getCapabilities();
          } else {
            /*
             * This exception triggers a "Certificate error"
             * notification that takes the user to the incoming
             * server settings for review. This might be needed if
             * the account was configured with an obsolete
             * "STARTTLS (if available)" setting.
             */
            throw new CertificateValidationException("STARTTLS connection security not available");
          }
        }

        switch (mAuthType) {
          case PLAIN:
            if (mCapabilities.authPlain) {
              authPlain();
            } else {
              login();
            }
            break;

          case CRAM_MD5:
            if (mCapabilities.cramMD5) {
              authCramMD5();
            } else {
              authAPOP(serverGreeting);
            }
            break;

          case EXTERNAL:
            if (mCapabilities.external) {
              authExternal();
            } else {
              // Provide notification to user of a problem authenticating using client certificates
              throw new CertificateValidationException(MissingCapability);
            }
            break;

          default:
            throw new MessagingException(
                "Unhandled authentication method found in the server settings (bug).");
        }
      } catch (SSLException e) {
        if (e.getCause() instanceof CertificateException) {
          throw new CertificateValidationException(e.getMessage(), e);
        } else {
          throw new MessagingException("Unable to connect", e);
        }
      } catch (GeneralSecurityException gse) {
        throw new MessagingException(
            "Unable to open connection to POP server due to security error.", gse);
      } catch (IOException ioe) {
        throw new MessagingException("Unable to open connection to POP server.", ioe);
      }

      String response = executeSimpleCommand(STAT_COMMAND);
      String[] parts = response.split(" ");
      mMessageCount = Integer.parseInt(parts[1]);

      mUidToMsgMap.clear();
      mMsgNumToMsgMap.clear();
      mUidToMsgNumMap.clear();
    }
示例#20
0
  private byte[] load(String url, int max_millis_to_wait) {
    // limit the subset here as we're looping waiting for something to be alive and we can't afford
    // to take ages getting back to the start

    long start = System.currentTimeMillis();

    while (true) {

      outer:
      for (int i = 45100; i <= 45108; i++) {

        long now = System.currentTimeMillis();

        if (now < start) {

          start = now;
        }

        if (now - start > max_millis_to_wait) {

          return (null);
        }

        Socket sock = null;

        try {
          sock = new Socket();

          sock.connect(new InetSocketAddress("127.0.0.1", i), 500);

          sock.setSoTimeout(5000);

          PrintWriter pw = new PrintWriter(sock.getOutputStream());

          pw.println("GET " + url + " HTTP/1.1" + NL + NL);

          pw.flush();

          InputStream is = sock.getInputStream();

          String header = "";

          byte[] buffer = new byte[1];

          while (true) {

            int len = is.read(buffer);

            if (len <= 0) {

              break outer;
            }

            header += new String(buffer, 0, len);

            if (header.endsWith(NL + NL)) {

              break;
            }
          }

          int pos = header.indexOf(NL);

          String first_line = header.substring(0, pos);

          if (first_line.indexOf("200") == -1) {

            continue;
          }

          ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);

          buffer = new byte[2048];

          while (true) {

            int len = is.read(buffer);

            if (len <= 0) {

              break;
            }

            baos.write(buffer, 0, len);

            if (baos.size() > 512 * 1024) {

              break outer;
            }
          }

          return (baos.toByteArray());

        } catch (Throwable e) {

        } finally {

          if (sock != null) {

            try {
              sock.close();

            } catch (Throwable e) {
            }
          }
        }
      }
    }
  }