⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 versioncheckclient.java

📁 这是一个基于java编写的torrent的P2P源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		  byte[]	buffer = new byte[1024];

		  int	total_len = 0;
		  
		  while( true ){
			  
			  int	len = is.read( buffer );
			  
			  if ( len <= 0 ){
				  
				  break;
			  }
			  
			  total_len += len;
			  
			  if ( total_len > 16000 ){
				  
				  throw( new IOException( "reply too large" ));
			  }
			  
			  baos.write( buffer, 0, len );
		  }
		  
		  byte[]	reply_bytes = baos.toByteArray();
		  
		  for (int i=3;i<reply_bytes.length;i++){
			  
			  if ( 		reply_bytes[i-3]== (byte)'\015' &&
					  	reply_bytes[i-2]== (byte)'\012' &&
					  	reply_bytes[i-1]== (byte)'\015' &&
					  	reply_bytes[i-0]== (byte)'\012' ){
			  		  
				  Map reply = BDecoder.decode( new BufferedInputStream( new ByteArrayInputStream( reply_bytes, i+1, reply_bytes.length - (i+1 ))));
				  
				  preProcessReply( reply );

				  return( reply );
			  }
		  }
		  
		  throw( new Exception( "Invalid reply: " + new String( reply_bytes )));
		  
	  }finally{
		  
		  if ( socket != null ){
			  
			  try{
				  socket.close();
				  
			  }catch( Throwable e ){
				  
			  }
		  }
	  }
  }
  
  private Map
  executeUDP(
	Map				data_to_send,
	InetAddress		bind_ip,
	int				bind_port )
  
  	throws Exception
  {
	  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( UDP_SERVER_ADDRESS, UDP_SERVER_PORT ), timeout );
		
				  Map	reply = reply_packet.getPayload();
				  
				  preProcessReply( reply );
				  
				  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();
	  }
  }
  
  protected void
  preProcessReply(
	Map		reply )
  {
	  	// two cases where we automatically attempt to resolve the ASN (to minimise load on ASN
	  	// provider)
	  	// 1) new installs
	  	// 2) where we have an asn and public IP has changed outside of prefix range
	 
	 final long ASN_MIN_CHECK = 7*24*60*60*1000L;
		 
	 boolean	check_asn 	= false;
	 boolean	new_install = COConfigurationManager.isNewInstall();
	 
	 long now = SystemTime.getCurrentTime();
	 
	 String	bgp_prefix = null;
	 
	 if ( new_install ){
		 
		 check_asn	= true;
		 
	 }else{
		 
		 bgp_prefix	= COConfigurationManager.getStringParameter( "ASN BGP", null );
		 
		 long	asn_check_time = COConfigurationManager.getLongParameter( "ASN Autocheck Performed Time" );
		 		 
		 if ( 	bgp_prefix != null && 
				now < asn_check_time || now - asn_check_time > ASN_MIN_CHECK ){
			 			 
			 check_asn = true;
		 }
	 }
	 
	 if ( check_asn ){
		 
		 try{
			 byte[] address = (byte[])reply.get( "source_ip_address" );
			  
			 InetAddress	ip = InetAddress.getByName( new String( address ));
		 		
			 if ( bgp_prefix != null ){
				 
				 	// if we've got a prefix only recheck if outside existing range
				 
				 if ( NetworkAdmin.getSingleton().matchesCIDR( bgp_prefix, ip )){
					 
					 check_asn = false;
				 }
			 }
			 
			 if ( check_asn ){
			 
				 COConfigurationManager.setParameter( "ASN Autocheck Performed Time", now );
	
				 NetworkAdminASNLookup	asn = NetworkAdmin.getSingleton().lookupASN( ip );
				 				 
				 COConfigurationManager.setParameter( "ASN AS", 	asn.getAS());
				 COConfigurationManager.setParameter( "ASN ASN", 	asn.getASName());
				 COConfigurationManager.setParameter( "ASN BGP", 	asn.getBGPPrefix());
				 
				 	// kick off a secondary version check to communicate the new information
				 
				 if ( !secondary_check_done ){
					 
					 secondary_check_done	= true;
					 
					 new AEThread( "Secondary version check", true )
					 {
						 public void
						 runSupport()
						 {
							 getVersionCheckInfoSupport( REASON_SECONDARY_CHECK, false, true );
						 }
					 }.start();
				 }
			 }
			 
		 }catch( Throwable e ){
			 
		 }
	 }
	 
	 Long	as_advice = (Long)reply.get( "as_advice" );
	 
	 if ( as_advice != null ){
		 
	     String	asn = COConfigurationManager.getStringParameter( "ASN ASN", null );

	     if ( asn != null ){
	    	
			 long	advice = as_advice.longValue();
			 
			 if ( advice != 0 ){
			
				 	// require crypto
				 
				 String	done_asn = COConfigurationManager.getStringParameter( "ASN Advice Followed", "" );
				 
				 if ( !done_asn.equals( asn )){
					 
					 COConfigurationManager.setParameter( "ASN Advice Followed", asn );
					 
					 boolean	change 	= advice == 1 || advice == 2;
					 boolean	alert 	= advice == 1 || advice == 3;
					 
					 if ( !COConfigurationManager.getBooleanParameter( "network.transport.encrypted.require" )){
						 
						 if ( change ){
							 
							 COConfigurationManager.setParameter( "network.transport.encrypted.require", true );
						 }
						 
						 if ( alert ){
							 
							 String	msg = 
								 MessageText.getString(
										"crypto.alert.as.warning",
										new String[]{ asn });
							 
							 Logger.log( new LogAlert( false, LogAlert.AT_WARNING, msg ));
						 }
					 }
				 }
			 }
	     }
	 }
  }
  
  public InetAddress
  getExternalIpAddressHTTP()
  
  	throws Exception
  {
	  Map reply = executeHTTP( new HashMap());
	  
	  byte[] address = (byte[])reply.get( "source_ip_address" );
	  
	  return( InetAddress.getByName( new String( address )));
  }
  
  public InetAddress
  getExternalIpAddressTCP(
	InetAddress	 	bind_ip,
	int				bind_port )
  
  	throws Exception
  {
	  Map reply = executeTCP( new HashMap(), bind_ip, bind_port );
	  
	  byte[] address = (byte[])reply.get( "source_ip_address" );
	  
	  return( InetAddress.getByName( new String( address )));
  }
  
  public InetAddress
  getExternalIpAddressUDP(
	InetAddress	 	bind_ip,
	int				bind_port )
  
  	throws Exception
  {
	  Map reply = executeUDP( new HashMap(), bind_ip, bind_port );
	  
	  byte[] address = (byte[])reply.get( "source_ip_address" );
	  
	  return( InetAddress.getByName( new String( address )));
  }
  
  /**
   * Construct the default version check message.
   * @return message to send
   */
  private Map constructVersionCheckMessage( String reason ) {
    Map message = new HashMap();
    
    message.put( "appid", SystemProperties.getApplicationIdentifier());
    message.put( "version", Constants.AZUREUS_VERSION );
    
    String id = COConfigurationManager.getStringParameter( "ID", null );
    boolean send_info = COConfigurationManager.getBooleanParameter( "Send Version Info" );
    
    int last_send_time = COConfigurationManager.getIntParameter( "Send Version Info Last Time", -1 );

    int current_send_time = (int)(SystemTime.getCurrentTime()/1000);
    
    COConfigurationManager.setParameter( "Send Version Info Last Time", current_send_time );
    
    if( id != null && send_info ) {
    	
      message.put( "id", id );
      message.put( "os", Constants.OSName );
      
      message.put( "os_version", System.getProperty( "os.version" ) );
      message.put( "os_arch", System.getProperty( "os.arch" ) );   //see http://lopica.sourceforge.net/os.html
    
      if ( last_send_time != -1 && last_send_time < current_send_time ){
    	  
    	  	// tims since last
    	  
    	  message.put( "tsl", new Long(current_send_time-last_send_time));
      }
      
      message.put( "reason", reason );
      
      String  java_version = System.getProperty( "java.version" );
      if ( java_version == null ){  java_version = "unknown";  }
      message.put( "java", java_version );
      
      
      String  java_vendor = System.getProperty( "java.vm.vendor" );
      if ( java_vendor == null ){   java_vendor = "unknown";  }
      message.put( "javavendor", java_vendor );
      
      
      long  max_mem = Runtime.getRuntime().maxMemory()/(1024*1024);
      message.put( "javamx", new Long( max_mem ) );
      
      OverallStats	stats = StatsFactory.getStats();
      
      if ( stats != null ){
      	
	      long total_bytes_downloaded 	= stats.getDownloadedBytes();
	      long total_bytes_uploaded		= stats.getUploadedBytes();
	      long total_uptime 			= stats.getTotalUpTime();
	
	      message.put( "total_bytes_downloaded", new Long( total_bytes_downloaded ) );
	      message.put( "total_bytes_uploaded", new Long( total_bytes_uploaded ) );
	      message.put( "total_uptime", new Long( total_uptime ) );
	      message.put( "dlstats", stats.getDownloadStats());
      }
      
      String	as = COConfigurationManager.getStringParameter( "ASN AS", null );
      
      if ( as != null ){
    	
    	  message.put( "ip_as", as );
      }
      
      String	asn = COConfigurationManager.getStringParameter( "ASN ASN", null );
      
      if ( asn != null ){
    	
    	  if ( asn.length() > 64 ){
    		  
    		  asn = asn.substring( 0, 64 );
    	  }
    	  
    	  message.put( "ip_asn", asn );
      }
      
      if ( AzureusCoreFactory.isCoreAvailable()){
      	
	      //installed plugin IDs
	      PluginInterface[] plugins = AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaces();
	      List pids = new ArrayList();
	      for (int i=0;i<plugins.length;i++){
	        String  pid = plugins[i].getPluginID();
	        
        	String	info = (String)plugins[i].getPluginconfig().getPluginStringParameter( "plugin.info" );
        	
	          // filter out built-in and core ones
	        if ( 	( info != null && info.length() > 0 ) ||
	        		(	!pid.startsWith( "<" ) && 
		        		!pid.startsWith( "azbp" ) &&
		        		!pid.startsWith( "azupdater" ) &&
	        			!pid.startsWith( "azplatform" ) &&
	        			!pids.contains( pid ))){
	        
	        	if ( info != null && info.length() > 0 ){
	        		
	        		if( info.length() < 256 ){
	        			
	        			pid += ":" + info;
	        			
	        		}else{
	        			
	        			Debug.out( "Plugin '" + pid + "' reported excessive info string '" + info + "'" );
	        		}
	        	}
	        	
	        	pids.add( pid );
	        }
	      }
	      message.put( "plugins", pids );
      }
    }
    
    
    //swt stuff
    try {
      Class c = Class.forName( "org.eclipse.swt.SWT" );
      
      String swt_platform = (String)c.getMethod( "getPlatform", new Class[]{} ).invoke( null, new Object[]{} );
      message.put( "swt_platform", swt_platform );
      
      if( send_info ) {
        Integer swt_version = (Integer)c.getMethod( "getVersion", new Class[]{} ).invoke( null, new Object[]{} );
        message.put( "swt_version", new Long( swt_version.longValue() ) );

        c = Class.forName("org.gudy.azureus2.ui.swt.mainwindow.MainWindow");
				if (c != null) {
					c.getMethod("addToVersionCheckMessage", new Class[] { Map.class }).invoke(
							null, new Object[] { message });
				}
      }
    }
    catch( ClassNotFoundException e ) {  /* ignore */ }
    catch( NoClassDefFoundError er ) {  /* ignore */ }
    catch( InvocationTargetException err ) {  /* ignore */ }
    catch( Throwable t ) {  t.printStackTrace();  }
    
    
    boolean using_phe = COConfigurationManager.getBooleanParameter( "network.transport.encrypted.require" );
    message.put( "using_phe", using_phe ? new Long(1) : new Long(0) );
    
    return message;
  }
  
  public static void
  main(
	String[]	args )
  {
	  try{
		  COConfigurationManager.initialise();
		  
		  System.out.println( "UDP:  " + getSingleton().getExternalIpAddressUDP(null,0));
		  System.out.println( "TCP:  " + getSingleton().getExternalIpAddressTCP(null,0));
		  System.out.println( "HTTP: " + getSingleton().getExternalIpAddressHTTP());
		  
	  }catch( Throwable e){
		  e.printStackTrace();
	  }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -