Search in sources :

Example 1 with NetworkAdminException

use of com.biglybt.core.networkmanager.admin.NetworkAdminException in project BiglyBT by BiglySoftware.

the class NetworkAdminHTTPProxyImpl method getDetails.

@Override
public Details getDetails() throws NetworkAdminException {
    final int RES_CONNECT_FAILED = 0;
    final int RES_PROXY_FAILED = 1;
    final int RES_OK = 3;
    final AESemaphore sem = new AESemaphore("NetworkAdminSocksProxy:test");
    final int[] result = { RES_CONNECT_FAILED };
    final NetworkAdminException[] error = { null };
    final ProxyDetails[] details = { null };
    try {
        InetSocketAddress socks_address = new InetSocketAddress(InetAddress.getByName(http_host), Integer.parseInt(http_port));
        final InetSocketAddress target_address = new InetSocketAddress(TARGET_HOST, TARGET_PORT);
        TCPConnectionManager.ConnectListener connect_listener = new TCPConnectionManager.ConnectListener() {

            @Override
            public int connectAttemptStarted(int default_connect_timeout) {
                return (default_connect_timeout);
            }

            @Override
            public void connectSuccess(SocketChannel channel) {
                final TCPTransportImpl transport = new TCPTransportImpl((ProtocolEndpointTCP) ProtocolEndpointFactory.createEndpoint(ProtocolEndpoint.PROTOCOL_TCP, target_address), false, false, null);
                transport.setFilter(TCPTransportHelperFilterFactory.createTransparentFilter(channel));
                final long start_time = SystemTime.getCurrentTime();
                try {
                    String get_str = VersionCheckClient.getSingleton().getHTTPGetString(true, false);
                    ByteBuffer request = ByteBuffer.wrap(get_str.getBytes());
                    while (request.hasRemaining()) {
                        if (transport.write(new ByteBuffer[] { request }, 0, 1) < 1) {
                            if (SystemTime.getCurrentTime() - start_time > 30 * 1000) {
                                String error = "proxy handshake message send timed out after 30sec";
                                Debug.out(error);
                                throw new IOException(error);
                            }
                            try {
                                Thread.sleep(50);
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                        }
                    }
                    TCPNetworkManager.getSingleton().getReadSelector().register(transport.getSocketChannel(), new VirtualChannelSelector.VirtualSelectorListener() {

                        private final byte[] reply_buffer = new byte[8192];

                        private final ByteBuffer reply = ByteBuffer.wrap(reply_buffer);

                        @Override
                        public boolean selectSuccess(VirtualChannelSelector selector, SocketChannel sc, Object attachment) {
                            try {
                                if (SystemTime.getCurrentTime() - start_time > 30 * 1000) {
                                    throw (new Exception("Timeout"));
                                }
                                long len = transport.read(new ByteBuffer[] { reply }, 0, 1);
                                if (len <= 0) {
                                    return (false);
                                }
                                String str = new String(reply_buffer, 0, reply.position());
                                if (str.contains(NL + NL)) {
                                    System.out.println(str);
                                    String server_name = "unknown";
                                    String auth = "none";
                                    String response = "unknown";
                                    StringTokenizer tok = new StringTokenizer(str, "\n");
                                    int line_num = 0;
                                    while (tok.hasMoreTokens()) {
                                        String token = tok.nextToken().trim();
                                        if (token.length() == 0) {
                                            continue;
                                        }
                                        line_num++;
                                        if (line_num == 1) {
                                            int pos = token.indexOf(' ');
                                            if (pos != -1) {
                                                response = token.substring(pos + 1).trim();
                                            }
                                        } else {
                                            int pos = token.indexOf(':');
                                            if (pos != -1) {
                                                String lhs = token.substring(0, pos).trim().toLowerCase(MessageText.LOCALE_ENGLISH);
                                                String rhs = token.substring(pos + 1).trim();
                                                if (lhs.equals("server")) {
                                                    if (!response.startsWith("200")) {
                                                        server_name = rhs;
                                                    }
                                                } else if (lhs.equals("via")) {
                                                    server_name = rhs;
                                                    int p = server_name.indexOf(' ');
                                                    if (p != -1) {
                                                        server_name = server_name.substring(p + 1).trim();
                                                    }
                                                } else if (lhs.equals("proxy-authenticate")) {
                                                    auth = rhs;
                                                }
                                            }
                                        }
                                    }
                                    details[0] = new ProxyDetails(server_name, response, auth);
                                    transport.close("Done");
                                    result[0] = RES_OK;
                                    sem.release();
                                } else {
                                    TCPNetworkManager.getSingleton().getReadSelector().resumeSelects(transport.getSocketChannel());
                                }
                                return (true);
                            } catch (Throwable t) {
                                return false;
                            }
                        }

                        @Override
                        public void selectFailure(VirtualChannelSelector selector, SocketChannel sc, Object attachment, Throwable msg) {
                            result[0] = RES_PROXY_FAILED;
                            error[0] = new NetworkAdminException("Proxy error", msg);
                            transport.close("Proxy error");
                            sem.release();
                        }
                    }, null);
                } catch (Throwable t) {
                    result[0] = RES_PROXY_FAILED;
                    error[0] = new NetworkAdminException("Proxy connect failed", t);
                    sem.release();
                }
            }

            @Override
            public void connectFailure(Throwable failure_msg) {
                result[0] = RES_CONNECT_FAILED;
                error[0] = new NetworkAdminException("Connect failed", failure_msg);
                sem.release();
            }
        };
        TCPNetworkManager.getSingleton().getConnectDisconnectManager().requestNewConnection(socks_address, connect_listener, ProtocolEndpoint.CONNECT_PRIORITY_MEDIUM);
    } catch (Throwable e) {
        result[0] = RES_CONNECT_FAILED;
        error[0] = new NetworkAdminException("Connect failed", e);
        sem.release();
    }
    if (!sem.reserve(10000)) {
        result[0] = RES_CONNECT_FAILED;
        error[0] = new NetworkAdminException("Connect timeout");
    }
    if (result[0] == RES_OK) {
        return (details[0]);
    }
    throw (error[0]);
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) AESemaphore(com.biglybt.core.util.AESemaphore) VirtualChannelSelector(com.biglybt.core.networkmanager.VirtualChannelSelector) NetworkAdminException(com.biglybt.core.networkmanager.admin.NetworkAdminException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ProtocolEndpoint(com.biglybt.core.networkmanager.ProtocolEndpoint) NetworkAdminException(com.biglybt.core.networkmanager.admin.NetworkAdminException) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer)

Example 2 with NetworkAdminException

use of com.biglybt.core.networkmanager.admin.NetworkAdminException in project BiglyBT by BiglySoftware.

the class NetworkAdminSocksProxyImpl method testVersion.

protected void testVersion(final String version) throws NetworkAdminException {
    final int RES_CONNECT_FAILED = 0;
    final int RES_SOCKS_FAILED = 1;
    final int RES_OK = 3;
    final AESemaphore sem = new AESemaphore("NetworkAdminSocksProxy:test");
    final int[] result = { RES_CONNECT_FAILED };
    final NetworkAdminException[] error = { null };
    try {
        InetSocketAddress socks_address = new InetSocketAddress(InetAddress.getByName(host), Integer.parseInt(port));
        final InetSocketAddress target_address = new InetSocketAddress(TARGET_HOST, TARGET_PORT);
        TCPConnectionManager.ConnectListener connect_listener = new TCPConnectionManager.ConnectListener() {

            @Override
            public int connectAttemptStarted(int default_connect_timeout) {
                return (default_connect_timeout);
            }

            @Override
            public void connectSuccess(SocketChannel channel) {
                final TCPTransportImpl transport = new TCPTransportImpl((ProtocolEndpointTCP) ProtocolEndpointFactory.createEndpoint(ProtocolEndpoint.PROTOCOL_TCP, target_address), false, false, null);
                transport.setFilter(TCPTransportHelperFilterFactory.createTransparentFilter(channel));
                new ProxyLoginHandler(transport, target_address, new ProxyLoginHandler.ProxyListener() {

                    @Override
                    public void connectSuccess() {
                        transport.close("Done");
                        result[0] = RES_OK;
                        sem.release();
                    }

                    @Override
                    public void connectFailure(Throwable failure_msg) {
                        transport.close("Proxy login failed");
                        result[0] = RES_SOCKS_FAILED;
                        error[0] = new NetworkAdminException("Proxy connect failed", failure_msg);
                        sem.release();
                    }
                }, version, user, password);
            }

            @Override
            public void connectFailure(Throwable failure_msg) {
                result[0] = RES_CONNECT_FAILED;
                error[0] = new NetworkAdminException("Connect failed", failure_msg);
                sem.release();
            }
        };
        TCPNetworkManager.getSingleton().getConnectDisconnectManager().requestNewConnection(socks_address, connect_listener, ProtocolEndpoint.CONNECT_PRIORITY_MEDIUM);
    } catch (Throwable e) {
        result[0] = RES_CONNECT_FAILED;
        error[0] = new NetworkAdminException("Connect failed", e);
        sem.release();
    }
    if (!sem.reserve(10000)) {
        result[0] = RES_CONNECT_FAILED;
        error[0] = new NetworkAdminException("Connect timeout");
    }
    if (result[0] != RES_OK) {
        throw (error[0]);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) NetworkAdminException(com.biglybt.core.networkmanager.admin.NetworkAdminException) InetSocketAddress(java.net.InetSocketAddress) AESemaphore(com.biglybt.core.util.AESemaphore) ProtocolEndpoint(com.biglybt.core.networkmanager.ProtocolEndpoint)

Example 3 with NetworkAdminException

use of com.biglybt.core.networkmanager.admin.NetworkAdminException in project BiglyBT by BiglySoftware.

the class NetworkAdminSocksProxyImpl method getVersionsSupported.

@Override
public String[] getVersionsSupported() throws NetworkAdminException {
    NetworkAdminException failure = null;
    List versions = new ArrayList();
    try {
        testVersion("V4");
        versions.add("4");
    } catch (NetworkAdminException e) {
        failure = e;
    }
    try {
        testVersion("V4a");
        versions.add("4a");
    } catch (NetworkAdminException e) {
        failure = e;
    }
    try {
        testVersion("V5");
        versions.add("5");
    } catch (NetworkAdminException e) {
        failure = e;
    }
    if (versions.size() > 0) {
        return ((String[]) versions.toArray(new String[versions.size()]));
    }
    throw (failure);
}
Also used : NetworkAdminException(com.biglybt.core.networkmanager.admin.NetworkAdminException) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList)

Example 4 with NetworkAdminException

use of com.biglybt.core.networkmanager.admin.NetworkAdminException in project BiglyBT by BiglySoftware.

the class NetworkAdminSocksProxyImpl method getString.

@Override
public String getString() {
    String res = getName();
    if (user.length() > 0) {
        res += " [auth=" + user + "]";
    }
    res += ", versions=";
    try {
        String[] versions = getVersionsSupported();
        for (int j = 0; j < versions.length; j++) {
            res += (j == 0 ? "" : ",") + versions[j];
        }
    } catch (NetworkAdminException e) {
        res += "unknown (" + e.getLocalizedMessage() + ")";
    }
    return (res);
}
Also used : NetworkAdminException(com.biglybt.core.networkmanager.admin.NetworkAdminException) ProtocolEndpoint(com.biglybt.core.networkmanager.ProtocolEndpoint)

Example 5 with NetworkAdminException

use of com.biglybt.core.networkmanager.admin.NetworkAdminException in project BiglyBT by BiglySoftware.

the class NetworkAdminUDPTester method testInbound.

@Override
public InetAddress testInbound(InetAddress bind_ip, int bind_port) throws NetworkAdminException {
    PRUDPReleasablePacketHandler handler = PRUDPPacketHandlerFactory.getReleasableHandler(bind_port);
    PRUDPPacketHandler packet_handler = handler.getHandler();
    HashMap data_to_send = new HashMap();
    PluginInterface pi_upnp = core.getPluginManager().getPluginInterfaceByClass(UPnPPlugin.class);
    String upnp_str = null;
    if (pi_upnp != null) {
        UPnPPlugin upnp = (UPnPPlugin) pi_upnp.getPlugin();
        /*
			UPnPMapping mapping = upnp.getMapping( true, port );

			if ( mapping == null ) {

				new_mapping = mapping = upnp.addMapping( "NAT Tester", true, port, true );

				// give UPnP a chance to work

				try {
					Thread.sleep( 500 );

				}
				catch (Throwable e) {

					Debug.printStackTrace( e );
				}
			}
			*/
        UPnPPluginService[] services = upnp.getServices();
        if (services.length > 0) {
            upnp_str = "";
            for (int i = 0; i < services.length; i++) {
                UPnPPluginService service = services[i];
                upnp_str += (i == 0 ? "" : ",") + service.getInfo();
            }
        }
    }
    if (upnp_str != null) {
        data_to_send.put("upnp", upnp_str);
    }
    NetworkAdminASN net_asn = NetworkAdmin.getSingleton().getCurrentASN();
    String as = net_asn.getAS();
    String asn = net_asn.getASName();
    if (as.length() > 0) {
        data_to_send.put("as", as);
    }
    if (asn.length() > 0) {
        data_to_send.put("asn", asn);
    }
    data_to_send.put("locale", MessageText.getCurrentLocale().toString());
    Random random = new Random();
    data_to_send.put("id", new Long(random.nextLong()));
    try {
        packet_handler.setExplicitBindAddress(bind_ip);
        Throwable last_error = null;
        long timeout = 5000;
        long timeout_inc = 5000;
        try {
            for (int i = 0; i < 3; i++) {
                data_to_send.put("seq", new Long(i));
                try {
                    // connection ids for requests must always have their msb set...
                    // apart from the original darn udp tracker spec....
                    long connection_id = 0x8000000000000000L | random.nextLong();
                    NetworkAdminNATUDPRequest request_packet = new NetworkAdminNATUDPRequest(connection_id);
                    request_packet.setPayload(data_to_send);
                    if (listener != null) {
                        listener.reportProgress("Sending outbound packet and waiting for reply probe (timeout=" + timeout + ")");
                    }
                    NetworkAdminNATUDPReply reply_packet = (NetworkAdminNATUDPReply) packet_handler.sendAndReceive(null, request_packet, new InetSocketAddress(UDP_SERVER_ADDRESS, UDP_SERVER_PORT), timeout, PRUDPPacketHandler.PRIORITY_IMMEDIATE);
                    Map reply = reply_packet.getPayload();
                    byte[] ip_bytes = (byte[]) reply.get("ip_address");
                    if (ip_bytes == null) {
                        throw (new NetworkAdminException("IP address missing in reply"));
                    }
                    byte[] reason = (byte[]) reply.get("reason");
                    if (reason != null) {
                        throw (new NetworkAdminException(new String(reason, "UTF8")));
                    }
                    return (InetAddress.getByAddress(ip_bytes));
                } catch (Throwable e) {
                    last_error = e;
                    timeout += timeout_inc;
                }
            }
            if (last_error != null) {
                throw (last_error);
            }
            throw (new NetworkAdminException("Timeout"));
        } finally {
            try {
                data_to_send.put("seq", new Long(99));
                long connection_id = 0x8000000000000000L | random.nextLong();
                NetworkAdminNATUDPRequest request_packet = new NetworkAdminNATUDPRequest(connection_id);
                request_packet.setPayload(data_to_send);
                if (listener != null) {
                    listener.reportProgress("Sending completion event");
                }
                packet_handler.send(request_packet, new InetSocketAddress(UDP_SERVER_ADDRESS, UDP_SERVER_PORT));
            } catch (Throwable e) {
            }
        }
    } catch (NetworkAdminException e) {
        throw (e);
    } catch (Throwable e) {
        throw (new NetworkAdminException("Inbound test failed", e));
    } finally {
        packet_handler.setExplicitBindAddress(null);
        handler.release();
    }
}
Also used : NetworkAdminException(com.biglybt.core.networkmanager.admin.NetworkAdminException) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) PluginInterface(com.biglybt.pif.PluginInterface) NetworkAdminASN(com.biglybt.core.networkmanager.admin.NetworkAdminASN) UPnPPluginService(com.biglybt.plugin.upnp.UPnPPluginService) PRUDPReleasablePacketHandler(com.biglybt.net.udp.uc.PRUDPReleasablePacketHandler) Random(java.util.Random) PRUDPPacketHandler(com.biglybt.net.udp.uc.PRUDPPacketHandler) UPnPPlugin(com.biglybt.plugin.upnp.UPnPPlugin) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

NetworkAdminException (com.biglybt.core.networkmanager.admin.NetworkAdminException)7 InetSocketAddress (java.net.InetSocketAddress)4 ProtocolEndpoint (com.biglybt.core.networkmanager.ProtocolEndpoint)3 AESemaphore (com.biglybt.core.util.AESemaphore)2 SocketChannel (java.nio.channels.SocketChannel)2 VirtualChannelSelector (com.biglybt.core.networkmanager.VirtualChannelSelector)1 NetworkAdminASN (com.biglybt.core.networkmanager.admin.NetworkAdminASN)1 PRUDPPacketHandler (com.biglybt.net.udp.uc.PRUDPPacketHandler)1 PRUDPReleasablePacketHandler (com.biglybt.net.udp.uc.PRUDPReleasablePacketHandler)1 PluginInterface (com.biglybt.pif.PluginInterface)1 UPnPPlugin (com.biglybt.plugin.upnp.UPnPPlugin)1 UPnPPluginService (com.biglybt.plugin.upnp.UPnPPluginService)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 InetAddress (java.net.InetAddress)1 Socket (java.net.Socket)1 ByteBuffer (java.nio.ByteBuffer)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1