Search in sources :

Example 1 with PRUDPPacketHandler

use of com.biglybt.net.udp.uc.PRUDPPacketHandler in project BiglyBT by BiglySoftware.

the class DHTUDPPacketHandlerFactory method getHandlerSupport.

protected DHTUDPPacketHandler getHandlerSupport(DHTTransportUDPImpl transport, DHTUDPRequestHandler request_handler) throws DHTUDPPacketHandlerException {
    try {
        this_mon.enter();
        int port = transport.getPort();
        int network = transport.getNetwork();
        Object[] port_details = (Object[]) port_map.get(new Integer(port));
        if (port_details == null) {
            PRUDPPacketHandler packet_handler = PRUDPPacketHandlerFactory.getHandler(port, new DHTUDPPacketNetworkHandler(this, port));
            port_details = new Object[] { packet_handler, new HashMap() };
            port_map.put(new Integer(port), port_details);
        }
        Map network_map = (Map) port_details[1];
        Object[] network_details = (Object[]) network_map.get(new Integer(network));
        if (network_details != null) {
            throw (new DHTUDPPacketHandlerException("Network already added"));
        }
        DHTUDPPacketHandler ph = new DHTUDPPacketHandler(this, network, (PRUDPPacketHandler) port_details[0], request_handler);
        network_map.put(new Integer(network), new Object[] { transport, ph });
        return (ph);
    } finally {
        this_mon.exit();
    }
}
Also used : PRUDPPacketHandler(com.biglybt.net.udp.uc.PRUDPPacketHandler) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with PRUDPPacketHandler

use of com.biglybt.net.udp.uc.PRUDPPacketHandler in project BiglyBT by BiglySoftware.

the class VersionCheckClient method executeUDP.

private Map executeUDP(Map data_to_send, InetAddress bind_ip, int bind_port, boolean v6) throws Exception {
    if (COConfigurationManager.getBooleanParameter("update.anonymous")) {
        throw (new Exception("UDP disabled for anonymous updates"));
    }
    if (v6 && !enable_v6) {
        throw (new Exception("IPv6 is disabled"));
    }
    String host = getHost(v6, UDP_SERVER_ADDRESS_V6, UDP_SERVER_ADDRESS_V4);
    PRUDPReleasablePacketHandler handler = PRUDPPacketHandlerFactory.getReleasableHandler(bind_port);
    PRUDPPacketHandler packet_handler = handler.getHandler();
    long timeout = 5;
    Random random = new Random();
    try {
        Exception last_error = null;
        packet_handler.setExplicitBindAddress(bind_ip);
        for (int i = 0; i < 3; 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();
                VersionCheckClientUDPRequest request_packet = new VersionCheckClientUDPRequest(connection_id);
                request_packet.setPayload(data_to_send);
                VersionCheckClientUDPReply reply_packet = (VersionCheckClientUDPReply) packet_handler.sendAndReceive(null, request_packet, new InetSocketAddress(host, UDP_SERVER_PORT), timeout);
                Map reply = reply_packet.getPayload();
                preProcessReply(reply, v6);
                return (reply);
            } catch (Exception e) {
                last_error = e;
                timeout = timeout * 2;
            }
        }
        if (last_error != null) {
            throw (last_error);
        }
        throw (new Exception("Timeout"));
    } finally {
        packet_handler.setExplicitBindAddress(null);
        handler.release();
    }
}
Also used : PRUDPReleasablePacketHandler(com.biglybt.net.udp.uc.PRUDPReleasablePacketHandler) PRUDPPacketHandler(com.biglybt.net.udp.uc.PRUDPPacketHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 3 with PRUDPPacketHandler

use of com.biglybt.net.udp.uc.PRUDPPacketHandler in project BiglyBT by BiglySoftware.

the class TrackerStatus method scrapeUDP.

protected boolean scrapeUDP(URL reqUrl, ByteArrayOutputStream message, List hashes, boolean do_auth_test) throws Exception {
    Map rootMap = new HashMap();
    Map files = new ByteEncodedKeyHashMap();
    rootMap.put("files", files);
    /*
		 * reduce network traffic by only scraping UDP when the torrent isn't
		 * running as UDP version 2 contains scrape data in the announce
		 * response
		 */
    /* removed implementation for the time being

		for (Iterator it = hashes.iterator(); it.hasNext();)
		{
			HashWrapper hash = (HashWrapper) it.next();
			if (PRUDPPacketTracker.VERSION == 2 && scraper.isTorrentDownloading(hash))
			{
				if (Logger.isEnabled())
					Logger.log(new LogEvent(TorrentUtils.getDownloadManager(hash), LOGID, LogEvent.LT_WARNING, "Scrape of " + reqUrl + " skipped as torrent running and " + "therefore scrape data available in " + "announce replies"));
				// easiest approach here is to brew up a response that looks like the current one
				Map file = new HashMap();
				byte[] resp_hash = hash.getBytes();
				// System.out.println("got hash:" + ByteFormatter.nicePrint( resp_hash, true ));
				files.put(new String(resp_hash, Constants.BYTE_ENCODING), file);
				file.put("complete", new Long(current_response.getSeeds()));
				file.put("downloaded", new Long(-1)); // unknown
				file.put("incomplete", new Long(current_response.getPeers()));
				byte[] data = BEncoder.encode(rootMap);
				message.write(data);
				return true;
			}
		}

		*/
    reqUrl = TRTrackerUtils.adjustURLForHosting(reqUrl);
    PasswordAuthentication auth = null;
    boolean auth_ok = false;
    try {
        if (do_auth_test && UrlUtils.queryHasParameter(reqUrl.getQuery(), "auth", false)) {
            auth = SESecurityManager.getPasswordAuthentication("UDP Tracker", reqUrl);
        }
        int port = UDPNetworkManager.getSingleton().getUDPNonDataListeningPortNumber();
        PRUDPPacketHandler handler = PRUDPPacketHandlerFactory.getHandler(port);
        InetSocketAddress destination = new InetSocketAddress(reqUrl.getHost(), reqUrl.getPort() == -1 ? 80 : reqUrl.getPort());
        handler = handler.openSession(destination);
        try {
            String failure_reason = null;
            for (int retry_loop = 0; retry_loop < PRUDPPacketTracker.DEFAULT_RETRY_COUNT; retry_loop++) {
                try {
                    PRUDPPacket connect_request = new PRUDPPacketRequestConnect();
                    PRUDPPacket reply = handler.sendAndReceive(auth, connect_request, destination);
                    if (reply.getAction() == PRUDPPacketTracker.ACT_REPLY_CONNECT) {
                        PRUDPPacketReplyConnect connect_reply = (PRUDPPacketReplyConnect) reply;
                        long my_connection = connect_reply.getConnectionId();
                        PRUDPPacketRequestScrape scrape_request = new PRUDPPacketRequestScrape(my_connection, hashes);
                        reply = handler.sendAndReceive(auth, scrape_request, destination);
                        if (reply.getAction() == PRUDPPacketTracker.ACT_REPLY_SCRAPE) {
                            auth_ok = true;
                            if (PRUDPPacketTracker.VERSION == 1) {
                                PRUDPPacketReplyScrape scrape_reply = (PRUDPPacketReplyScrape) reply;
                                /*
								int	interval = scrape_reply.getInterval();

								if ( interval != 0 ){

									map.put( "interval", new Long(interval ));
								}
								*/
                                byte[][] reply_hashes = scrape_reply.getHashes();
                                int[] complete = scrape_reply.getComplete();
                                int[] downloaded = scrape_reply.getDownloaded();
                                int[] incomplete = scrape_reply.getIncomplete();
                                for (int i = 0; i < reply_hashes.length; i++) {
                                    Map file = new HashMap();
                                    byte[] resp_hash = reply_hashes[i];
                                    // System.out.println("got hash:" + ByteFormatter.nicePrint( resp_hash, true ));
                                    files.put(new String(resp_hash, Constants.BYTE_ENCODING), file);
                                    file.put("complete", new Long(complete[i]));
                                    file.put("downloaded", new Long(downloaded[i]));
                                    file.put("incomplete", new Long(incomplete[i]));
                                }
                                byte[] data = BEncoder.encode(rootMap);
                                message.write(data);
                                return true;
                            } else {
                                PRUDPPacketReplyScrape2 scrape_reply = (PRUDPPacketReplyScrape2) reply;
                                /*
								int	interval = scrape_reply.getInterval();

								if ( interval != 0 ){

									map.put( "interval", new Long(interval ));
								}
								*/
                                int[] complete = scrape_reply.getComplete();
                                int[] downloaded = scrape_reply.getDownloaded();
                                int[] incomplete = scrape_reply.getIncomplete();
                                int i = 0;
                                for (Iterator it = hashes.iterator(); it.hasNext() && i < complete.length; i++) {
                                    HashWrapper hash = (HashWrapper) it.next();
                                    Map file = new HashMap();
                                    file.put("complete", new Long(complete[i]));
                                    file.put("downloaded", new Long(downloaded[i]));
                                    file.put("incomplete", new Long(incomplete[i]));
                                    files.put(new String(hash.getBytes(), Constants.BYTE_ENCODING), file);
                                }
                                // System.out.println("got hash:" + ByteFormatter.nicePrint( resp_hash, true ));
                                byte[] data = BEncoder.encode(rootMap);
                                message.write(data);
                                return true;
                            }
                        } else {
                            failure_reason = ((PRUDPPacketReplyError) reply).getMessage();
                            if (Logger.isEnabled())
                                Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "Response from scrape interface " + reqUrl + " : " + failure_reason));
                            break;
                        }
                    } else {
                        failure_reason = ((PRUDPPacketReplyError) reply).getMessage();
                        if (Logger.isEnabled())
                            Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "Response from scrape interface " + reqUrl + " : " + ((PRUDPPacketReplyError) reply).getMessage()));
                        break;
                    }
                } catch (PRUDPPacketHandlerException e) {
                    if (e.getMessage() == null || !e.getMessage().contains("timed out")) {
                        throw (e);
                    }
                    failure_reason = "Timeout";
                }
            }
            if (failure_reason != null) {
                rootMap.put("failure reason", failure_reason.getBytes());
                rootMap.remove("files");
                byte[] data = BEncoder.encode(rootMap);
                message.write(data);
            }
        } finally {
            handler.closeSession();
        }
        return false;
    } finally {
        if (auth != null) {
            SESecurityManager.setPasswordAuthenticationOutcome(TRTrackerBTAnnouncerImpl.UDP_REALM, reqUrl, auth_ok);
        }
    }
}
Also used : PRUDPPacket(com.biglybt.net.udp.uc.PRUDPPacket) LogEvent(com.biglybt.core.logging.LogEvent) PRUDPPacketHandlerException(com.biglybt.net.udp.uc.PRUDPPacketHandlerException) PRUDPPacketHandler(com.biglybt.net.udp.uc.PRUDPPacketHandler)

Example 4 with PRUDPPacketHandler

use of com.biglybt.net.udp.uc.PRUDPPacketHandler 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)

Example 5 with PRUDPPacketHandler

use of com.biglybt.net.udp.uc.PRUDPPacketHandler in project BiglyBT by BiglySoftware.

the class DHTUDPPacketHandlerFactory method destroy.

protected void destroy(DHTUDPPacketHandler handler) {
    PRUDPPacketHandler packet_handler = handler.getPacketHandler();
    int port = packet_handler.getPort();
    int network = handler.getNetwork();
    try {
        this_mon.enter();
        Object[] port_details = (Object[]) port_map.get(new Integer(port));
        if (port_details == null) {
            return;
        }
        Map network_map = (Map) port_details[1];
        network_map.remove(new Integer(network));
        if (network_map.size() == 0) {
            port_map.remove(new Integer(port));
            try {
                packet_handler.setRequestHandler(null);
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
    } finally {
        this_mon.exit();
    }
}
Also used : PRUDPPacketHandler(com.biglybt.net.udp.uc.PRUDPPacketHandler) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

PRUDPPacketHandler (com.biglybt.net.udp.uc.PRUDPPacketHandler)6 HashMap (java.util.HashMap)4 Map (java.util.Map)4 PRUDPReleasablePacketHandler (com.biglybt.net.udp.uc.PRUDPReleasablePacketHandler)2 InetSocketAddress (java.net.InetSocketAddress)2 DownloadManager (com.biglybt.core.download.DownloadManager)1 LogEvent (com.biglybt.core.logging.LogEvent)1 NetworkConnection (com.biglybt.core.networkmanager.NetworkConnection)1 Transport (com.biglybt.core.networkmanager.Transport)1 TransportStartpoint (com.biglybt.core.networkmanager.TransportStartpoint)1 NetworkAdmin (com.biglybt.core.networkmanager.admin.NetworkAdmin)1 NetworkAdminASN (com.biglybt.core.networkmanager.admin.NetworkAdminASN)1 NetworkAdminException (com.biglybt.core.networkmanager.admin.NetworkAdminException)1 PEPeer (com.biglybt.core.peer.PEPeer)1 PEPeerManager (com.biglybt.core.peer.PEPeerManager)1 PRUDPPacket (com.biglybt.net.udp.uc.PRUDPPacket)1 PRUDPPacketHandlerException (com.biglybt.net.udp.uc.PRUDPPacketHandlerException)1 PluginInterface (com.biglybt.pif.PluginInterface)1 UPnPPlugin (com.biglybt.plugin.upnp.UPnPPlugin)1 UPnPPluginService (com.biglybt.plugin.upnp.UPnPPluginService)1