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

📄 ipfilterimpl.java

📁 这是一个基于java编写的torrent的P2P源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * File    : IpFilterImpl.java
 * Created : 16-Oct-2003
 * By      : Olivier
 * 
 * Azureus - a Java Bittorrent client
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details ( see the LICENSE file ).
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.gudy.azureus2.core3.ipfilter.impl;

/**
 * @author Olivier
 *
 */

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.util.*;

import org.gudy.azureus2.core3.config.COConfigurationManager;
import org.gudy.azureus2.core3.ipfilter.*;
import org.gudy.azureus2.core3.logging.*;
import org.gudy.azureus2.core3.tracker.protocol.PRHelpers;
import org.gudy.azureus2.core3.util.*;

public class 
IpFilterImpl 
	implements IpFilter
{
	private static final LogIDs LOGID = LogIDs.CORE;

	private final static long BAN_IP_PERSIST_TIME	= 7*24*60*60*1000L;
	
	private final static int MAX_BLOCKS_TO_REMEMBER = 500;
  
	private static IpFilterImpl ipFilter;
	private static AEMonitor	class_mon	= new AEMonitor( "IpFilter:class" );
 
	private IPAddressRangeManager	range_manager = new IPAddressRangeManager();
	
	private Map			bannedIps;
	 
    //Map ip blocked -> matching range
	
	private LinkedList		ipsBlocked;
	
	private int num_ips_blocked 			= 0;
	private int num_ips_blocked_loggable	= 0;

	private long	last_update_time;
    
  
	private List	listeners = new ArrayList();
	
	
	private IpFilterImpl() 
	{
	  ipFilter = this;
	  
	  bannedIps = new HashMap();
	  
	  ipsBlocked = new LinkedList();
	  
	  try{
		  loadBannedIPs();
		  
	  }catch( Throwable e ){
		  
		  Debug.printStackTrace(e);
	  }
	  try{
	  	
	  	loadFilters();
	  	
	  }catch( Exception e ){
	  	
	  	Debug.printStackTrace( e );
	  }
	}
  
	public static IpFilter getInstance() {
		try{
			class_mon.enter();
		
			  if(ipFilter == null) {
				ipFilter = new IpFilterImpl();
			  }
			  return ipFilter;
		}finally{
			
			class_mon.exit();
		}
	}
  
	public File
	getFile()
	{
		return( FileUtil.getUserFile("filters.config"));
	}
	
	public void
	reload()
		throws Exception
	{
		loadFilters();
	}
	
	public void 
	save() 
	
		throws Exception
	{
		try{
			class_mon.enter();
		
			Map map = new HashMap();
		 
	
			List filters = new ArrayList();
			map.put("ranges",filters);
			List entries = range_manager.getEntries();
			Iterator iter = entries.iterator();
			while(iter.hasNext()) {
			  IpRange range = (IpRange) iter.next();
			  if(range.isValid() && ! range.isSessionOnly()) {
				String description =  range.getDescription();
				String startIp = range.getStartIp();
				String endIp = range.getEndIp();
				Map mapRange = new HashMap();
				mapRange.put("description",description.getBytes( "UTF-8" ));
				mapRange.put("start",startIp);
				mapRange.put("end",endIp);
				filters.add(mapRange);
			  }
			}
		  
		  	FileOutputStream fos  = null;
	    
	    	try {
	      	
	    		//  Open the file
	    		
	    		File filtersFile = FileUtil.getUserFile("filters.config");
	        
	    		fos = new FileOutputStream(filtersFile);
	    		
	    		fos.write(BEncoder.encode(map));
	    		
	    	}finally{
		  	
		  		if ( fos != null ){
		  			
		  			fos.close();
		  		}
	    	}
		}finally{
			
			class_mon.exit();
		}
	}
  
	private void 
	loadFilters() 
		throws Exception
	{
		try{
			class_mon.enter();
		
		  List new_ipRanges = new ArrayList(1024);
	
		  FileInputStream fin = null;
		  BufferedInputStream bin = null;
		  try {
			//open the file
			File filtersFile = FileUtil.getUserFile("filters.config");
			if (filtersFile.exists()) {
				fin = new FileInputStream(filtersFile);
				bin = new BufferedInputStream(fin, 16384);
				Map map = BDecoder.decode(bin);
				List list = (List) map.get("ranges");
				Iterator iter = list.listIterator();
				while(iter.hasNext()) {
				  Map range = (Map) iter.next();
				  String description =  new String((byte[])range.get("description"), "UTF-8");
				  String startIp =  new String((byte[])range.get("start"));
				  String endIp = new String((byte[])range.get("end"));
		        
				  IpRangeImpl ipRange = new IpRangeImpl(description,startIp,endIp,false);

				  ipRange.setAddedToRangeList(true);
				  
				  new_ipRanges.add( ipRange );
				}
			}		
		  }finally{
		  
			if ( bin != null ){
				try{
				    bin.close();
				}catch( Throwable e ){
				}
			}
			if ( fin != null ){
				try{
					fin.close();
				}catch( Throwable e ){
				}
			}
			
		  	
		  	Iterator	it = new_ipRanges.iterator();
		  	
		  	while( it.hasNext()){
		  		  		
		  		((IpRange)it.next()).checkValid();
		  	}
		  	
		  	markAsUpToDate();
		  }
		}finally{
			
			class_mon.exit();
		}
	}
  
	protected void
	loadBannedIPs()
	{
		if ( !COConfigurationManager.getBooleanParameter("Ip Filter Banning Persistent" )){
			
			return;
		}
		
		try{
			class_mon.enter();
			
			Map	map = FileUtil.readResilientConfigFile( "banips.config" );
		
			List	ips = (List)map.get( "ips" );
			
			if ( ips != null ){
				
				long	now = SystemTime.getCurrentTime();
				
				for (int i=0;i<ips.size();i++){
					
					Map	entry = (Map)ips.get(i);
					
					String	ip 		= new String((byte[])entry.get("ip"));
					String	desc 	= new String((byte[])entry.get("desc"), "UTF-8");
					Long	ltime	= (Long)entry.get("time");
					
					long	time = ltime.longValue();
					
					boolean	drop	= false;
					
					if ( time > now ){
						
						time	= now;
						
					}else if ( now - time >= BAN_IP_PERSIST_TIME ){
						
						drop	= true;
						
					    if (Logger.isEnabled()){
					    	
								Logger.log(
									new LogEvent(
										LOGID, LogEvent.LT_INFORMATION, 
										"Persistent ban dropped as too old : "
											+ ip + ", " + desc));
					      }
					}
					
					if ( !drop ){
						
						int	int_ip = range_manager.addressToInt( ip );
						
						bannedIps.put( new Integer( int_ip ), new BannedIpImpl(ip, desc, time ));
					}
				}
			}
		}catch( Throwable e ){
			
			Debug.printStackTrace(e);
			
		}finally{
			
			class_mon.exit();
		}
	}
	
	protected void
	saveBannedIPs()
	{
		if ( !COConfigurationManager.getBooleanParameter("Ip Filter Banning Persistent" )){
			
			return;
		}
		
		try{
			class_mon.enter();
			
			Map	map = new HashMap();
			
			List	ips = new ArrayList();
			
			Iterator	it = bannedIps.values().iterator();
			
			while( it.hasNext()){
				
				BannedIpImpl	bip = (BannedIpImpl)it.next();
				
				Map	entry = new HashMap();
				
				entry.put( "ip", bip.getIp());
				entry.put( "desc", bip.getTorrentName().getBytes( "UTF-8" ));
				entry.put( "time", new Long( bip.getBanningTime()));
				
				ips.add( entry );
			}
			
			map.put( "ips", ips );
			
			FileUtil.writeResilientConfigFile( "banips.config", map );
		
		}catch( Throwable e ){
			
			Debug.printStackTrace(e);
			
		}finally{
			
			class_mon.exit();
		}
	}
	protected boolean
	isInRange(
		IpRangeImpl	range,
		String		address )
	{
		return( range_manager.isInRange( range, address ));
	}
  
  public boolean isInRange(String ipAddress) {
    return isInRange( ipAddress, "" );
  }
  
  
	public boolean 
	isInRange(
		String ipAddress, 
		String torrent_name) 
	{
		return( isInRange( ipAddress, torrent_name, true ));
	}
	
	public boolean 
	isInRange(
		String ipAddress, 
		String torrent_name,
		boolean	loggable ) 
	{
		if ( !isEnabled()){
			
			return( false );
		}
		
		//In all cases, block banned ip addresses
		
	  if(isBanned(ipAddress)){
	  
		  return true;
	  }
	  
	  	// never bounce the local machine (peer guardian has a range that includes it!)
	  
	  if ( ipAddress.equals("127.0.0.1")){
	  	
		  return( false );
	  }
	  
	  //never block lan local addresses
	  if( AddressUtils.isLANLocalAddress( ipAddress ) != AddressUtils.LAN_LOCAL_NO ) {
	  	return false;
	  }
	  
	  
	  if(!COConfigurationManager.getBooleanParameter("Ip Filter Enabled",true)){
		  
	    return false;
	  }
	  
	  boolean allow = COConfigurationManager.getBooleanParameter("Ip Filter Allow");
	  
	  IpRange	match = (IpRange)range_manager.isInRange( ipAddress );

	  if(match != null) {
	    if(!allow) {
	    	
	      	// don't bounce non-public addresses (we can ban them but not filter them as they have no sensible
		  	// real filter address
		  
		  if ( AENetworkClassifier.categoriseAddress( ipAddress ) != AENetworkClassifier.AT_PUBLIC ){
			  
			  return( false );
		  }
		  
	      addBlockedIP( new BlockedIpImpl(ipAddress,match, torrent_name, loggable), loggable );
	      
	      if (Logger.isEnabled())
					Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Ip Blocked : "
							+ ipAddress + ", in range : " + match));
	      
	      return true;
	    }
      
	    return false;  
	  }

	
	  if( allow ){  
		  
		if ( AENetworkClassifier.categoriseAddress( ipAddress ) != AENetworkClassifier.AT_PUBLIC ){
			  
		  return( false );
		}
		  
	    addBlockedIP( new BlockedIpImpl(ipAddress,null, torrent_name, loggable), loggable );
	    
	    if (Logger.isEnabled())
				Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Ip Blocked : "
						+ ipAddress + ", not in any range"));
	    
	    return true;
	  }
	  
	  return false;
	}
	
  
	public boolean 
	isInRange(
		InetAddress ipAddress, 
		String 		torrent_name,
		boolean		loggable ) 
	{
		if ( !isEnabled()){
			
			return( false );
		}
		
		//In all cases, block banned ip addresses
		
	  if(isBanned(ipAddress)){
	  
		  return true;
	  }
	  
	  	// never bounce the local machine (peer guardian has a range that includes it!)
	  
	  if ( ipAddress.isLoopbackAddress() || ipAddress.isLinkLocalAddress() || ipAddress.isSiteLocalAddress()){
	  	
		  return( false );
	  }
	  
	  //never block lan local addresses
	  if( AddressUtils.isLANLocalAddress( ipAddress ) != AddressUtils.LAN_LOCAL_NO ) {
	  	return false;
	  }
	  
	  
	  if(!COConfigurationManager.getBooleanParameter("Ip Filter Enabled",true)){
		  
	    return false;
	  }
	  
	  boolean allow = COConfigurationManager.getBooleanParameter("Ip Filter Allow");
	  
	  IpRange	match = (IpRange)range_manager.isInRange( ipAddress );

	  if(match != null) {
		  
	    if(!allow) {
	    			  
	      addBlockedIP( new BlockedIpImpl(ipAddress.getHostAddress(),match, torrent_name, loggable), loggable );
	      
	      if (Logger.isEnabled())
					Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Ip Blocked : "
							+ ipAddress + ", in range : " + match));
	      
	      return true;
	    }
      
	    return false;  
	  }

⌨️ 快捷键说明

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