Search in sources :

Example 1 with NetworkConnection

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

the class MessageManagerImpl method registerGenericMessageType.

@Override
public GenericMessageRegistration registerGenericMessageType(final String _type, final String description, final int stream_crypto, final GenericMessageHandler handler) throws MessageException {
    final String type = "AEGEN:" + _type;
    final byte[] type_bytes = type.getBytes();
    final byte[][] shared_secrets = new byte[][] { new SHA1Simple().calculateHash(type_bytes) };
    synchronized (message_handlers) {
        message_handlers.put(type, handler);
    }
    final NetworkManager.ByteMatcher matcher = new NetworkManager.ByteMatcher() {

        @Override
        public int matchThisSizeOrBigger() {
            return (maxSize());
        }

        @Override
        public int maxSize() {
            return type_bytes.length;
        }

        @Override
        public int minSize() {
            return maxSize();
        }

        @Override
        public Object matches(TransportHelper transport, ByteBuffer to_compare, int port) {
            int old_limit = to_compare.limit();
            to_compare.limit(to_compare.position() + maxSize());
            boolean matches = to_compare.equals(ByteBuffer.wrap(type_bytes));
            // restore buffer structure
            to_compare.limit(old_limit);
            return matches ? "" : null;
        }

        @Override
        public Object minMatches(TransportHelper transport, ByteBuffer to_compare, int port) {
            return (matches(transport, to_compare, port));
        }

        @Override
        public byte[][] getSharedSecrets() {
            return (shared_secrets);
        }

        @Override
        public int getSpecificPort() {
            return (-1);
        }
    };
    NetworkManager.getSingleton().requestIncomingConnectionRouting(matcher, new NetworkManager.RoutingListener() {

        @Override
        public void connectionRouted(final NetworkConnection connection, Object routing_data) {
            try {
                ByteBuffer[] skip_buffer = { ByteBuffer.allocate(type_bytes.length) };
                connection.getTransport().read(skip_buffer, 0, 1);
                if (skip_buffer[0].remaining() != 0) {
                    Debug.out("incomplete read");
                }
                GenericMessageEndpointImpl endpoint = new GenericMessageEndpointImpl(connection.getEndpoint());
                GenericMessageConnectionDirect direct_connection = GenericMessageConnectionDirect.receive(endpoint, type, description, stream_crypto, shared_secrets);
                GenericMessageConnectionImpl new_connection = new GenericMessageConnectionImpl(MessageManagerImpl.this, direct_connection);
                direct_connection.connect(connection);
                if (handler.accept(new_connection)) {
                    new_connection.accepted();
                } else {
                    connection.close("connection not accepted");
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
                connection.close(e == null ? null : Debug.getNestedExceptionMessage(e));
            }
        }

        @Override
        public boolean autoCryptoFallback() {
            return (stream_crypto != MessageManager.STREAM_ENCRYPTION_RC4_REQUIRED);
        }
    }, new MessageStreamFactory() {

        @Override
        public MessageStreamEncoder createEncoder() {
            return new GenericMessageEncoder();
        }

        @Override
        public MessageStreamDecoder createDecoder() {
            return new GenericMessageDecoder(type, description);
        }
    });
    return (new GenericMessageRegistration() {

        @Override
        public GenericMessageEndpoint createEndpoint(InetSocketAddress notional_target) {
            return (new GenericMessageEndpointImpl(notional_target));
        }

        @Override
        public GenericMessageConnection createConnection(GenericMessageEndpoint endpoint) throws MessageException {
            return (new GenericMessageConnectionImpl(MessageManagerImpl.this, type, description, (GenericMessageEndpointImpl) endpoint, stream_crypto, shared_secrets));
        }

        @Override
        public void cancel() {
            NetworkManager.getSingleton().cancelIncomingConnectionRouting(matcher);
            synchronized (message_handlers) {
                message_handlers.remove(type);
            }
        }
    });
}
Also used : MessageStreamFactory(com.biglybt.core.peermanager.messaging.MessageStreamFactory) InetSocketAddress(java.net.InetSocketAddress) MessageException(com.biglybt.pif.messaging.MessageException) MessageStreamEncoder(com.biglybt.core.peermanager.messaging.MessageStreamEncoder) GenericMessageRegistration(com.biglybt.pif.messaging.generic.GenericMessageRegistration) SHA1Simple(com.biglybt.core.util.SHA1Simple) NetworkConnection(com.biglybt.core.networkmanager.NetworkConnection) TransportHelper(com.biglybt.core.networkmanager.impl.TransportHelper) ByteBuffer(java.nio.ByteBuffer) GenericMessageEndpoint(com.biglybt.pif.messaging.generic.GenericMessageEndpoint) MessageStreamDecoder(com.biglybt.core.peermanager.messaging.MessageStreamDecoder) GenericMessageEndpoint(com.biglybt.pif.messaging.generic.GenericMessageEndpoint) NetworkManager(com.biglybt.core.networkmanager.NetworkManager) GenericMessageConnection(com.biglybt.pif.messaging.generic.GenericMessageConnection)

Example 2 with NetworkConnection

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

the class HTTPNetworkManager method reRoute.

protected void reRoute(final HTTPNetworkConnection old_http_connection, final byte[] old_hash, final byte[] new_hash, final String header) {
    final NetworkConnection old_connection = old_http_connection.getConnection();
    PeerManagerRegistration reg_data = PeerManager.getSingleton().manualMatchHash(old_connection.getEndpoint().getNotionalAddress(), new_hash);
    if (reg_data == null) {
        old_http_connection.close("Re-routing failed - registration not found");
        return;
    }
    final Transport transport = old_connection.detachTransport();
    old_http_connection.close("Switching torrents");
    final NetworkConnection new_connection = NetworkManager.getSingleton().bindTransport(transport, new HTTPMessageEncoder(), new HTTPMessageDecoder(header));
    PeerManager.getSingleton().manualRoute(reg_data, new_connection, new PeerManagerRoutingListener() {

        @Override
        public boolean routed(PEPeerTransport peer) {
            HTTPNetworkConnection new_http_connection;
            if (header.contains("/webseed")) {
                new_http_connection = new HTTPNetworkConnectionWebSeed(HTTPNetworkManager.this, new_connection, peer);
            } else if (header.contains("/files/")) {
                new_http_connection = new HTTPNetworkConnectionFile(HTTPNetworkManager.this, new_connection, peer);
            } else {
                return (false);
            }
            // fake a wakeup so pre-read header is processed
            new_http_connection.readWakeup();
            return (true);
        }
    });
}
Also used : PeerManagerRegistration(com.biglybt.core.peermanager.PeerManagerRegistration) PeerManagerRoutingListener(com.biglybt.core.peermanager.PeerManagerRoutingListener) PEPeerTransport(com.biglybt.core.peer.impl.PEPeerTransport) NetworkConnection(com.biglybt.core.networkmanager.NetworkConnection) Transport(com.biglybt.core.networkmanager.Transport) PEPeerTransport(com.biglybt.core.peer.impl.PEPeerTransport)

Example 3 with NetworkConnection

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

the class PeerManager method init.

protected void init() {
    // ensure it gets initialized
    MessageManager.getSingleton().initialize();
    NetworkManager.ByteMatcher matcher = new NetworkManager.ByteMatcher() {

        @Override
        public int matchThisSizeOrBigger() {
            return (48);
        }

        @Override
        public int maxSize() {
            return 48;
        }

        @Override
        public int minSize() {
            return 20;
        }

        @Override
        public Object matches(TransportHelper transport, ByteBuffer to_compare, int port) {
            InetSocketAddress address = transport.getAddress();
            int old_limit = to_compare.limit();
            int old_position = to_compare.position();
            to_compare.limit(old_position + 20);
            PeerManagerRegistrationImpl routing_data = null;
            if (to_compare.equals(legacy_handshake_header)) {
                // compare header
                to_compare.limit(old_position + 48);
                to_compare.position(old_position + 28);
                byte[] hash = new byte[to_compare.remaining()];
                to_compare.get(hash);
                try {
                    managers_mon.enter();
                    List<PeerManagerRegistrationImpl> registrations = registered_legacy_managers.get(new HashWrapper(hash));
                    if (registrations != null) {
                        routing_data = registrations.get(0);
                    }
                } finally {
                    managers_mon.exit();
                }
            }
            // restore buffer structure
            to_compare.limit(old_limit);
            to_compare.position(old_position);
            if (routing_data != null) {
                if (!routing_data.isActive()) {
                    if (routing_data.isKnownSeed(address)) {
                        String reason = "Activation request from " + address + " denied as known seed";
                        if (Logger.isEnabled()) {
                            Logger.log(new LogEvent(LOGID, reason));
                        }
                        transport.close(reason);
                        routing_data = null;
                    } else {
                        if (!routing_data.getAdapter().activateRequest(address)) {
                            String reason = "Activation request from " + address + " denied by rules";
                            if (Logger.isEnabled()) {
                                Logger.log(new LogEvent(LOGID, reason));
                            }
                            transport.close(reason);
                            routing_data = null;
                        }
                    }
                }
            }
            return routing_data;
        }

        @Override
        public Object minMatches(TransportHelper transport, ByteBuffer to_compare, int port) {
            boolean matches = false;
            int old_limit = to_compare.limit();
            int old_position = to_compare.position();
            to_compare.limit(old_position + 20);
            if (to_compare.equals(legacy_handshake_header)) {
                matches = true;
            }
            // restore buffer structure
            to_compare.limit(old_limit);
            to_compare.position(old_position);
            return matches ? "" : null;
        }

        @Override
        public byte[][] getSharedSecrets() {
            // registered manually above
            return (null);
        }

        @Override
        public int getSpecificPort() {
            return (-1);
        }
    };
    // register for incoming connection routing
    NetworkManager.getSingleton().requestIncomingConnectionRouting(matcher, new NetworkManager.RoutingListener() {

        @Override
        public void connectionRouted(NetworkConnection connection, Object routing_data) {
            PeerManagerRegistrationImpl registration = (PeerManagerRegistrationImpl) routing_data;
            registration.route(connection, null);
        }

        @Override
        public boolean autoCryptoFallback() {
            return (false);
        }
    }, new MessageStreamFactory() {

        @Override
        public MessageStreamEncoder createEncoder() {
            return new BTMessageEncoder();
        }

        @Override
        public MessageStreamDecoder createDecoder() {
            return new BTMessageDecoder();
        }
    });
}
Also used : MessageStreamFactory(com.biglybt.core.peermanager.messaging.MessageStreamFactory) LogEvent(com.biglybt.core.logging.LogEvent) InetSocketAddress(java.net.InetSocketAddress) NetworkConnection(com.biglybt.core.networkmanager.NetworkConnection) TransportHelper(com.biglybt.core.networkmanager.impl.TransportHelper) BTMessageDecoder(com.biglybt.core.peermanager.messaging.bittorrent.BTMessageDecoder) ByteBuffer(java.nio.ByteBuffer) ProtocolEndpoint(com.biglybt.core.networkmanager.ProtocolEndpoint) ConnectionEndpoint(com.biglybt.core.networkmanager.ConnectionEndpoint) BTMessageEncoder(com.biglybt.core.peermanager.messaging.bittorrent.BTMessageEncoder) MessageStreamDecoder(com.biglybt.core.peermanager.messaging.MessageStreamDecoder) MessageStreamEncoder(com.biglybt.core.peermanager.messaging.MessageStreamEncoder) NetworkManager(com.biglybt.core.networkmanager.NetworkManager)

Example 4 with NetworkConnection

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

the class TransferStatsView method refreshConnectionPanel.

private void refreshConnectionPanel() {
    if (global_manager == null) {
        return;
    }
    int total_connections = 0;
    int total_con_queued = 0;
    int total_con_blocked = 0;
    int total_con_unchoked = 0;
    int total_data_queued = 0;
    int total_in = 0;
    List<DownloadManager> dms = global_manager.getDownloadManagers();
    for (DownloadManager dm : dms) {
        PEPeerManager pm = dm.getPeerManager();
        if (pm != null) {
            total_data_queued += pm.getBytesQueuedForUpload();
            total_connections += pm.getNbPeers() + pm.getNbSeeds();
            total_con_queued += pm.getNbPeersWithUploadQueued();
            total_con_blocked += pm.getNbPeersWithUploadBlocked();
            total_con_unchoked += pm.getNbPeersUnchoked();
            total_in += pm.getNbRemoteTCPConnections() + pm.getNbRemoteUDPConnections() + pm.getNbRemoteUTPConnections();
        }
    }
    connection_label.setText(MessageText.getString("SpeedView.stats.con_details", new String[] { String.valueOf(total_connections) + "[" + MessageText.getString("label.in").toLowerCase() + ":" + total_in + "]", String.valueOf(total_con_unchoked), String.valueOf(total_con_queued), String.valueOf(total_con_blocked) }));
    connection_graphic.addIntsValue(new int[] { total_connections, total_con_unchoked, total_con_queued, total_con_blocked });
    upload_label.setText(MessageText.getString("SpeedView.stats.upload_details", new String[] { DisplayFormatters.formatByteCountToKiBEtc(total_data_queued) }));
    upload_graphic.addIntValue(total_data_queued);
    upload_graphic.refresh(false);
    connection_graphic.refresh(false);
    if (con_folder.getSelectionIndex() == 1) {
        long now = SystemTime.getMonotonousTime();
        if (now - last_route_update >= 2 * 1000) {
            last_route_update = now;
            NetworkAdmin na = NetworkAdmin.getSingleton();
            Map<InetAddress, String> ip_to_name_map = new HashMap<>();
            Map<String, RouteInfo> name_to_route_map = new HashMap<>();
            RouteInfo udp_info = null;
            RouteInfo unknown_info = null;
            List<PRUDPPacketHandler> udp_handlers = PRUDPPacketHandlerFactory.getHandlers();
            InetAddress udp_bind_ip = null;
            for (PRUDPPacketHandler handler : udp_handlers) {
                if (handler.hasPrimordialHandler()) {
                    udp_bind_ip = handler.getBindIP();
                    if (udp_bind_ip != null) {
                        if (udp_bind_ip.isAnyLocalAddress()) {
                            udp_bind_ip = null;
                        }
                    }
                }
            }
            for (DownloadManager dm : dms) {
                PEPeerManager pm = dm.getPeerManager();
                if (pm != null) {
                    List<PEPeer> peers = pm.getPeers();
                    for (PEPeer p : peers) {
                        NetworkConnection nc = PluginCoreUtils.unwrap(p.getPluginConnection());
                        boolean done = false;
                        if (nc != null) {
                            Transport transport = nc.getTransport();
                            if (transport != null) {
                                InetSocketAddress notional_address = nc.getEndpoint().getNotionalAddress();
                                String ip = AddressUtils.getHostAddress(notional_address);
                                String network = AENetworkClassifier.categoriseAddress(ip);
                                if (network == AENetworkClassifier.AT_PUBLIC) {
                                    if (transport.isTCP()) {
                                        TransportStartpoint start = transport.getTransportStartpoint();
                                        if (start != null) {
                                            InetSocketAddress socket_address = start.getProtocolStartpoint().getAddress();
                                            if (socket_address != null) {
                                                InetAddress address = socket_address.getAddress();
                                                String name;
                                                if (address.isAnyLocalAddress()) {
                                                    name = "* (TCP)";
                                                } else {
                                                    name = ip_to_name_map.get(address);
                                                }
                                                if (name == null) {
                                                    name = na.classifyRoute(address);
                                                    ip_to_name_map.put(address, name);
                                                }
                                                if (transport.isSOCKS()) {
                                                    name += " (SOCKS)";
                                                }
                                                RouteInfo info = name_to_route_map.get(name);
                                                if (info == null) {
                                                    info = new RouteInfo(name);
                                                    name_to_route_map.put(name, info);
                                                    route_last_seen.put(name, now);
                                                }
                                                info.update(p);
                                                done = true;
                                            }
                                        }
                                    } else {
                                        if (udp_bind_ip != null) {
                                            RouteInfo info;
                                            String name = ip_to_name_map.get(udp_bind_ip);
                                            if (name == null) {
                                                name = na.classifyRoute(udp_bind_ip);
                                                ip_to_name_map.put(udp_bind_ip, name);
                                                info = name_to_route_map.get(name);
                                                route_last_seen.put(name, now);
                                                if (info == null) {
                                                    info = new RouteInfo(name);
                                                    name_to_route_map.put(name, info);
                                                }
                                            } else {
                                                info = name_to_route_map.get(name);
                                            }
                                            info.update(p);
                                            done = true;
                                        } else {
                                            if (udp_info == null) {
                                                udp_info = new RouteInfo("* (UDP)");
                                                name_to_route_map.put(udp_info.getName(), udp_info);
                                                route_last_seen.put(udp_info.getName(), now);
                                            }
                                            udp_info.update(p);
                                            done = true;
                                        }
                                    }
                                } else {
                                    RouteInfo info = name_to_route_map.get(network);
                                    if (info == null) {
                                        info = new RouteInfo(network);
                                        name_to_route_map.put(network, info);
                                        route_last_seen.put(network, now);
                                    }
                                    info.update(p);
                                    done = true;
                                }
                            }
                        }
                        if (!done) {
                            if (unknown_info == null) {
                                unknown_info = new RouteInfo("Pending");
                                name_to_route_map.put(unknown_info.getName(), unknown_info);
                                route_last_seen.put(unknown_info.getName(), now);
                            }
                            unknown_info.update(p);
                        }
                    }
                }
            }
            List<RouteInfo> rows = new ArrayList<>();
            Iterator<Map.Entry<String, Long>> it = route_last_seen.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Long> entry = it.next();
                long when = entry.getValue();
                if (now - when > 60 * 1000) {
                    it.remove();
                } else if (when != now) {
                    rows.add(new RouteInfo(entry.getKey()));
                }
            }
            rows.addAll(name_to_route_map.values());
            Collections.sort(rows, new Comparator<RouteInfo>() {

                @Override
                public int compare(RouteInfo o1, RouteInfo o2) {
                    String n1 = o1.getName();
                    String n2 = o2.getName();
                    // wildcard and pending to the bottom
                    if (n1.startsWith("*") || n1.equals("Pending")) {
                        n1 = "zzzz" + n1;
                    }
                    if (n2.startsWith("*") || n2.equals("Pending")) {
                        n2 = "zzzz" + n2;
                    }
                    return (n1.compareTo(n2));
                }
            });
            buildRouteComponent(rows.size());
            for (int i = 0; i < rows.size(); i++) {
                RouteInfo info = rows.get(i);
                route_labels[i][0].setText(info.getName());
                route_labels[i][1].setText(info.getIncomingString());
                route_labels[i][2].setText(info.getOutgoingString());
            }
            buildRouteComponent(rows.size());
        }
    }
}
Also used : PEPeer(com.biglybt.core.peer.PEPeer) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) DownloadManager(com.biglybt.core.download.DownloadManager) NetworkAdmin(com.biglybt.core.networkmanager.admin.NetworkAdmin) TransportStartpoint(com.biglybt.core.networkmanager.TransportStartpoint) NetworkConnection(com.biglybt.core.networkmanager.NetworkConnection) Point(org.eclipse.swt.graphics.Point) TransportStartpoint(com.biglybt.core.networkmanager.TransportStartpoint) PRUDPPacketHandler(com.biglybt.net.udp.uc.PRUDPPacketHandler) PEPeerManager(com.biglybt.core.peer.PEPeerManager) Transport(com.biglybt.core.networkmanager.Transport) InetAddress(java.net.InetAddress) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

NetworkConnection (com.biglybt.core.networkmanager.NetworkConnection)4 InetSocketAddress (java.net.InetSocketAddress)3 NetworkManager (com.biglybt.core.networkmanager.NetworkManager)2 Transport (com.biglybt.core.networkmanager.Transport)2 TransportHelper (com.biglybt.core.networkmanager.impl.TransportHelper)2 MessageStreamDecoder (com.biglybt.core.peermanager.messaging.MessageStreamDecoder)2 MessageStreamEncoder (com.biglybt.core.peermanager.messaging.MessageStreamEncoder)2 MessageStreamFactory (com.biglybt.core.peermanager.messaging.MessageStreamFactory)2 ByteBuffer (java.nio.ByteBuffer)2 DownloadManager (com.biglybt.core.download.DownloadManager)1 LogEvent (com.biglybt.core.logging.LogEvent)1 ConnectionEndpoint (com.biglybt.core.networkmanager.ConnectionEndpoint)1 ProtocolEndpoint (com.biglybt.core.networkmanager.ProtocolEndpoint)1 TransportStartpoint (com.biglybt.core.networkmanager.TransportStartpoint)1 NetworkAdmin (com.biglybt.core.networkmanager.admin.NetworkAdmin)1 PEPeer (com.biglybt.core.peer.PEPeer)1 PEPeerManager (com.biglybt.core.peer.PEPeerManager)1 PEPeerTransport (com.biglybt.core.peer.impl.PEPeerTransport)1 PeerManagerRegistration (com.biglybt.core.peermanager.PeerManagerRegistration)1 PeerManagerRoutingListener (com.biglybt.core.peermanager.PeerManagerRoutingListener)1