Search in sources :

Example 11 with LogEvent

use of com.biglybt.core.logging.LogEvent in project BiglyBT by BiglySoftware.

the class TCPConnectionManager method addNewRequest.

private void addNewRequest(final ConnectionRequest request) {
    request.setConnectTimeout(request.listener.connectAttemptStarted(request.getConnectTimeout()));
    boolean ipv6problem = false;
    boolean bind_failed = false;
    try {
        request.channel = SocketChannel.open();
        InetAddress bindIP = null;
        try {
            // advanced socket options
            if (rcv_size > 0) {
                if (Logger.isEnabled())
                    Logger.log(new LogEvent(LOGID, "Setting socket receive buffer size" + " for outgoing connection [" + request.address + "] to: " + rcv_size));
                request.channel.socket().setReceiveBufferSize(rcv_size);
            }
            if (snd_size > 0) {
                if (Logger.isEnabled())
                    Logger.log(new LogEvent(LOGID, "Setting socket send buffer size " + "for outgoing connection [" + request.address + "] to: " + snd_size));
                request.channel.socket().setSendBufferSize(snd_size);
            }
            if (ip_tos.length() > 0) {
                if (Logger.isEnabled())
                    Logger.log(new LogEvent(LOGID, "Setting socket TOS field " + "for outgoing connection [" + request.address + "] to: " + ip_tos));
                request.channel.socket().setTrafficClass(Integer.decode(ip_tos).intValue());
            }
            if (local_bind_port > 0) {
                request.channel.socket().setReuseAddress(true);
            }
            try {
                bindIP = NetworkAdmin.getSingleton().getMultiHomedOutgoingRoundRobinBindAddress(request.address.getAddress());
                if (bindIP != null) {
                    if (bindIP.isAnyLocalAddress() || !AEProxyFactory.isPluginProxy(request.address)) {
                        if (Logger.isEnabled())
                            Logger.log(new LogEvent(LOGID, "Binding outgoing connection [" + request.address + "] to local IP address: " + bindIP + ":" + local_bind_port));
                        request.channel.socket().bind(new InetSocketAddress(bindIP, local_bind_port));
                    }
                } else if (local_bind_port > 0) {
                    if (Logger.isEnabled())
                        Logger.log(new LogEvent(LOGID, "Binding outgoing connection [" + request.address + "] to local port #: " + local_bind_port));
                    request.channel.socket().bind(new InetSocketAddress(local_bind_port));
                }
            } catch (SocketException e) {
                bind_failed = true;
                String msg = e.getMessage().toLowerCase();
                if ((msg.contains("address family not supported by protocol family") || msg.contains("protocol family unavailable")) && !NetworkAdmin.getSingleton().hasIPV6Potential(true)) {
                    ipv6problem = true;
                }
                throw e;
            }
        } catch (Throwable t) {
            if (bind_failed && NetworkAdmin.getSingleton().mustBind()) {
                throw (t);
            } else if (!ipv6problem) {
                // dont pass the exception outwards, so we will continue processing connection without advanced options set
                String msg = "Error while processing advanced socket options (rcv=" + rcv_size + ", snd=" + snd_size + ", tos=" + ip_tos + ", port=" + local_bind_port + ", bind=" + bindIP + ")";
                // Debug.out( msg, t );
                Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, t));
            } else {
                throw (t);
            }
        }
        request.channel.configureBlocking(false);
        request.connect_start_time = SystemTime.getMonotonousTime();
        if (request.channel.connect(request.address)) {
            // already connected
            finishConnect(request);
        } else {
            try {
                new_canceled_mon.enter();
                pending_attempts.put(request, null);
            } finally {
                new_canceled_mon.exit();
            }
            connect_selector.register(request.channel, new VirtualChannelSelector.VirtualSelectorListener() {

                @Override
                public boolean selectSuccess(VirtualChannelSelector selector, SocketChannel sc, Object attachment) {
                    try {
                        new_canceled_mon.enter();
                        pending_attempts.remove(request);
                    } finally {
                        new_canceled_mon.exit();
                    }
                    finishConnect(request);
                    return true;
                }

                @Override
                public void selectFailure(VirtualChannelSelector selector, SocketChannel sc, Object attachment, Throwable msg) {
                    try {
                        new_canceled_mon.enter();
                        pending_attempts.remove(request);
                    } finally {
                        new_canceled_mon.exit();
                    }
                    closeConnection(request.channel);
                    request.listener.connectFailure(msg);
                }
            }, null);
        }
    } catch (Throwable t) {
        String full = request.address.toString();
        String hostname = request.address.getHostName();
        int port = request.address.getPort();
        boolean unresolved = request.address.isUnresolved();
        InetAddress inet_address = request.address.getAddress();
        String full_sub = inet_address == null ? request.address.toString() : inet_address.toString();
        String host_address = inet_address == null ? request.address.toString() : inet_address.getHostAddress();
        String msg = "ConnectDisconnectManager::address exception: full=" + full + ", hostname=" + hostname + ", port=" + port + ", unresolved=" + unresolved + ", full_sub=" + full_sub + ", host_address=" + host_address;
        if (request.channel != null) {
            String channel = request.channel.toString();
            Socket socket = request.channel.socket();
            String socket_string = socket.toString();
            InetAddress local_address = socket.getLocalAddress();
            String local_address_string = local_address == null ? "<null>" : local_address.toString();
            int local_port = socket.getLocalPort();
            SocketAddress ra = socket.getRemoteSocketAddress();
            String remote_address;
            if (ra != null)
                remote_address = ra.toString();
            else
                remote_address = "<null>";
            int remote_port = socket.getPort();
            msg += "\n channel=" + channel + ", socket=" + socket_string + ", local_address=" + local_address_string + ", local_port=" + local_port + ", remote_address=" + remote_address + ", remote_port=" + remote_port;
        } else {
            msg += "\n channel=<null>";
        }
        if (ipv6problem || t instanceof UnresolvedAddressException || t instanceof NoRouteToHostException) {
            Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, msg));
        } else {
            Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, msg, t));
        }
        if (request.channel != null) {
            closeConnection(request.channel);
        }
        request.listener.connectFailure(t);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) LogEvent(com.biglybt.core.logging.LogEvent) LogAlert(com.biglybt.core.logging.LogAlert) VirtualChannelSelector(com.biglybt.core.networkmanager.VirtualChannelSelector) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException)

Example 12 with LogEvent

use of com.biglybt.core.logging.LogEvent in project BiglyBT by BiglySoftware.

the class TCPTransportImpl method setTransportBuffersSize.

private void setTransportBuffersSize(int size_in_bytes) {
    if (getFilter() == null) {
        Debug.out("socket_channel == null");
        return;
    }
    try {
        SocketChannel channel = getSocketChannel();
        channel.socket().setSendBufferSize(size_in_bytes);
        channel.socket().setReceiveBufferSize(size_in_bytes);
        int snd_real = channel.socket().getSendBufferSize();
        int rcv_real = channel.socket().getReceiveBufferSize();
        if (Logger.isEnabled())
            Logger.log(new LogEvent(LOGID, "Setting new transport [" + description + "] buffer sizes: SND=" + size_in_bytes + " [" + snd_real + "] , RCV=" + size_in_bytes + " [" + rcv_real + "]"));
    } catch (Throwable t) {
        Debug.out(t);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) LogEvent(com.biglybt.core.logging.LogEvent) TransportStartpoint(com.biglybt.core.networkmanager.TransportStartpoint)

Example 13 with LogEvent

use of com.biglybt.core.logging.LogEvent in project BiglyBT by BiglySoftware.

the class TCPTransportImpl method connectOutbound.

/**
 * Request the transport connection be established.
 * NOTE: Will automatically connect via configured proxy if necessary.
 * @param address remote peer address to connect to
 * @param listener establishment failure/success listener
 */
@Override
public void connectOutbound(final ByteBuffer initial_data, final ConnectListener listener, final int priority) {
    if (!TCPNetworkManager.TCP_OUTGOING_ENABLED) {
        listener.connectFailure(new Throwable("Outbound TCP connections disabled"));
        return;
    }
    if (has_been_closed) {
        listener.connectFailure(new Throwable("Connection already closed"));
        return;
    }
    if (getFilter() != null) {
        // already connected
        Debug.out("socket_channel != null");
        listener.connectSuccess(this, initial_data);
        return;
    }
    final InetSocketAddress address = protocol_endpoint.getAddress();
    if (!address.equals(ProxyLoginHandler.DEFAULT_SOCKS_SERVER_ADDRESS)) {
        if (address.isUnresolved()) {
            String host = address.getHostName();
            if (AENetworkClassifier.categoriseAddress(host) != AENetworkClassifier.AT_PUBLIC) {
                Map<String, Object> opts = new HashMap<>();
                Object peer_nets = listener.getConnectionProperty(AEProxyFactory.PO_PEER_NETWORKS);
                if (peer_nets != null) {
                    opts.put(AEProxyFactory.PO_PEER_NETWORKS, peer_nets);
                }
                PluginProxy pp = plugin_proxy;
                plugin_proxy = null;
                if (pp != null) {
                    // most likely crypto fallback connection so don't assume it is a bad
                    // outcome
                    pp.setOK(true);
                }
                plugin_proxy = AEProxyFactory.getPluginProxy("outbound connection", host, address.getPort(), opts);
            }
        }
        if (plugin_proxy == null) {
            is_socks = COConfigurationManager.getBooleanParameter("Proxy.Data.Enable");
        }
    }
    final TCPTransportImpl transport_instance = this;
    TCPConnectionManager.ConnectListener connect_listener = new TCPConnectionManager.ConnectListener() {

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

        @Override
        public void connectSuccess(final SocketChannel channel) {
            if (channel == null) {
                String msg = "connectSuccess:: given channel == null";
                Debug.out(msg);
                setConnectResult(false);
                listener.connectFailure(new Exception(msg));
                return;
            }
            if (has_been_closed) {
                // closed between select ops
                // just close it
                TCPNetworkManager.getSingleton().getConnectDisconnectManager().closeConnection(channel);
                setConnectResult(false);
                listener.connectFailure(new Throwable("Connection has been closed"));
                return;
            }
            connect_request_key = null;
            description = (is_inbound_connection ? "R" : "L") + ": " + channel.socket().getInetAddress().getHostAddress() + ": " + channel.socket().getPort();
            PluginProxy pp = plugin_proxy;
            if (is_socks) {
                // proxy server connection established, login
                if (Logger.isEnabled())
                    Logger.log(new LogEvent(LOGID, "Socket connection established to proxy server [" + description + "], login initiated..."));
                // set up a transparent filter for socks negotiation
                setFilter(TCPTransportHelperFilterFactory.createTransparentFilter(channel));
                new ProxyLoginHandler(transport_instance, address, new ProxyLoginHandler.ProxyListener() {

                    @Override
                    public void connectSuccess() {
                        if (Logger.isEnabled())
                            Logger.log(new LogEvent(LOGID, "Proxy [" + description + "] login successful."));
                        handleCrypto(address, channel, initial_data, priority, listener);
                    }

                    @Override
                    public void connectFailure(Throwable failure_msg) {
                        close("Proxy login failed");
                        listener.connectFailure(failure_msg);
                    }
                });
            } else if (pp != null) {
                if (Logger.isEnabled()) {
                    Logger.log(new LogEvent(LOGID, "Socket connection established via plugin proxy [" + description + "], login initiated..."));
                }
                // set up a transparent filter for socks negotiation
                setFilter(TCPTransportHelperFilterFactory.createTransparentFilter(channel));
                String pp_host = pp.getHost();
                InetSocketAddress ia_address;
                if (AENetworkClassifier.categoriseAddress(pp_host) == AENetworkClassifier.AT_PUBLIC) {
                    ia_address = new InetSocketAddress(pp.getHost(), pp.getPort());
                } else {
                    ia_address = InetSocketAddress.createUnresolved(pp_host, pp.getPort());
                }
                new ProxyLoginHandler(transport_instance, ia_address, new ProxyLoginHandler.ProxyListener() {

                    @Override
                    public void connectSuccess() {
                        if (Logger.isEnabled()) {
                            Logger.log(new LogEvent(LOGID, "Proxy [" + description + "] login successful."));
                        }
                        setConnectResult(true);
                        handleCrypto(address, channel, initial_data, priority, listener);
                    }

                    @Override
                    public void connectFailure(Throwable failure_msg) {
                        setConnectResult(false);
                        close("Proxy login failed");
                        listener.connectFailure(failure_msg);
                    }
                }, "V4a", "", "");
            } else {
                // direct connection established, notify
                handleCrypto(address, channel, initial_data, priority, listener);
            }
        }

        @Override
        public void connectFailure(Throwable failure_msg) {
            connect_request_key = null;
            setConnectResult(false);
            listener.connectFailure(failure_msg);
        }
    };
    connect_request_key = connect_listener;
    InetSocketAddress to_connect;
    PluginProxy pp = plugin_proxy;
    if (is_socks) {
        to_connect = ProxyLoginHandler.getProxyAddress(address);
    } else if (pp != null) {
        to_connect = (InetSocketAddress) pp.getProxy().address();
    } else {
        to_connect = address;
    }
    TCPNetworkManager.getSingleton().getConnectDisconnectManager().requestNewConnection(to_connect, connect_listener, priority);
}
Also used : SocketChannel(java.nio.channels.SocketChannel) HashMap(java.util.HashMap) LogEvent(com.biglybt.core.logging.LogEvent) InetSocketAddress(java.net.InetSocketAddress) PluginProxy(com.biglybt.core.proxy.AEProxyFactory.PluginProxy)

Example 14 with LogEvent

use of com.biglybt.core.logging.LogEvent in project BiglyBT by BiglySoftware.

the class UDPConnectionManager method accept.

protected void accept(final int local_port, final InetSocketAddress remote_address, final UDPConnection connection) {
    final UDPTransportHelper helper = new UDPTransportHelper(this, remote_address, connection);
    try {
        connection.setTransport(helper);
        TransportCryptoManager.getSingleton().manageCrypto(helper, null, true, null, new TransportCryptoManager.HandshakeListener() {

            @Override
            public void handshakeSuccess(ProtocolDecoder decoder, ByteBuffer remaining_initial_data) {
                TransportHelperFilter filter = decoder.getFilter();
                ConnectionEndpoint co_ep = new ConnectionEndpoint(remote_address);
                ProtocolEndpointUDP pe_udp = (ProtocolEndpointUDP) ProtocolEndpointFactory.createEndpoint(ProtocolEndpoint.PROTOCOL_UDP, co_ep, remote_address);
                UDPTransport transport = new UDPTransport(pe_udp, filter);
                helper.setTransport(transport);
                incoming_manager.addConnection(local_port, filter, transport);
            }

            @Override
            public void handshakeFailure(Throwable failure_msg) {
                if (Logger.isEnabled()) {
                    Logger.log(new LogEvent(LOGID, "incoming crypto handshake failure: " + Debug.getNestedExceptionMessage(failure_msg)));
                }
                connection.close("handshake failure: " + Debug.getNestedExceptionMessage(failure_msg));
            }

            @Override
            public void gotSecret(byte[] session_secret) {
                helper.getConnection().setSecret(session_secret);
            }

            @Override
            public int getMaximumPlainHeaderLength() {
                return (incoming_manager.getMaxMinMatchBufferSize());
            }

            @Override
            public int matchPlainHeader(ByteBuffer buffer) {
                Object[] match_data = incoming_manager.checkForMatch(helper, local_port, buffer, true);
                if (match_data == null) {
                    return (TransportCryptoManager.HandshakeListener.MATCH_NONE);
                } else {
                    return (TransportCryptoManager.HandshakeListener.MATCH_CRYPTO_NO_AUTO_FALLBACK);
                }
            }
        });
    } catch (Throwable e) {
        Debug.printStackTrace(e);
        helper.close(Debug.getNestedExceptionMessage(e));
    }
}
Also used : TransportHelperFilter(com.biglybt.core.networkmanager.impl.TransportHelperFilter) LogEvent(com.biglybt.core.logging.LogEvent) ProtocolDecoder(com.biglybt.core.networkmanager.impl.ProtocolDecoder) ByteBuffer(java.nio.ByteBuffer) ConnectionEndpoint(com.biglybt.core.networkmanager.ConnectionEndpoint) TransportCryptoManager(com.biglybt.core.networkmanager.impl.TransportCryptoManager)

Example 15 with LogEvent

use of com.biglybt.core.logging.LogEvent in project BiglyBT by BiglySoftware.

the class UDPConnectionManager method receive.

@Override
public void receive(int local_port, InetSocketAddress remote_address, byte[] data, int data_length) {
    String key = local_port + ":" + remote_address.getAddress().getHostAddress() + ":" + remote_address.getPort();
    UDPConnectionSet connection_set;
    synchronized (connection_sets) {
        UDPSelector current_selector = checkThreadCreation();
        connection_set = (UDPConnectionSet) connection_sets.get(key);
        if (connection_set == null) {
            timeoutDeadKeys();
            if (data_length >= UDPNetworkManager.MIN_INCOMING_INITIAL_PACKET_SIZE && data_length <= UDPNetworkManager.MAX_INCOMING_INITIAL_PACKET_SIZE) {
                if (!rateLimitIncoming(remote_address)) {
                    rate_limit_discard_packets++;
                    rate_limit_discard_bytes += data_length;
                    return;
                }
                connection_set = new UDPConnectionSet(this, key, current_selector, local_port, remote_address);
                if (Logger.isEnabled()) {
                    Logger.log(new LogEvent(LOGID, "Created new set - " + connection_set.getName() + ", incoming"));
                }
                connection_sets.put(key, connection_set);
            } else {
                if (recently_dead_keys.get(key) == null) {
                // we can get quite a lot of these if things get out of sync
                // Debug.out( "Incoming UDP packet mismatch for connection establishment: " + key );
                }
                setup_discard_packets++;
                setup_discard_bytes += data_length;
                return;
            }
        }
    }
    try {
        // System.out.println( "recv:" + ByteFormatter.encodeString( data, 0, data_length>64?64:data_length ) + (data_length>64?"...":""));
        connection_set.receive(data, data_length);
    } catch (IOException e) {
        connection_set.failed(e);
    } catch (Throwable e) {
        Debug.printStackTrace(e);
        connection_set.failed(e);
    }
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) IOException(java.io.IOException)

Aggregations

LogEvent (com.biglybt.core.logging.LogEvent)172 LogAlert (com.biglybt.core.logging.LogAlert)20 IOException (java.io.IOException)14 File (java.io.File)11 URL (java.net.URL)11 ArrayList (java.util.ArrayList)9 InetSocketAddress (java.net.InetSocketAddress)8 InputStream (java.io.InputStream)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 ZipInputStream (java.util.zip.ZipInputStream)7 CacheFileManagerException (com.biglybt.core.diskmanager.cache.CacheFileManagerException)6 TOTorrent (com.biglybt.core.torrent.TOTorrent)6 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)6 ResourceDownloader (com.biglybt.pif.utils.resourcedownloader.ResourceDownloader)6 UIFunctions (com.biglybt.ui.UIFunctions)6 SocketChannel (java.nio.channels.SocketChannel)6 Iterator (java.util.Iterator)6 ConnectionEndpoint (com.biglybt.core.networkmanager.ConnectionEndpoint)5 ClientIDException (com.biglybt.pif.clientid.ClientIDException)5 ParameterListener (com.biglybt.core.config.ParameterListener)4