MINA源碼分析----怎麼設置IP限制的(防火牆)



主要涉及到以下兩個類  


一個是IP子網類  (IPV4)

package org.apache.mina.filter.firewall;

import java.net.Inet4Address;
import java.net.InetAddress;

/**
 * A IP subnet using the CIDR notation符號.     無類域內路由選擇(Classless Inter-Domain Routing)
 Currently, only IP version 4
 * address are supported.
 *
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
public class Subnet {
	/**有符號數,這裏最高位爲1,即負數,負數在計算機中是以補碼錶示的!!
	 * 例如    IP_MASK = 0x80000000 ,是以補碼形式表示的負數 ,其原碼爲    0x80000000  減1取反 ,最高位不變
	 *      同理  若  IP_MASK = 0x80000010  ,則其表示的負數  爲   0x80000001 減 1取反,最高位爲1 
	 *      即    0xffffffff  纔是其真正表示的負數,這纔是我們平時做題計算用的形式 ,與計算機中存儲的形式不同!!
	 */
    private static final int IP_MASK = 0x80000000;//凡是在程序中表示的二進制數都表示計算機中的存儲,是補碼
    private static final int BYTE_MASK = 0xFF;

    private InetAddress subnet;//子網IP
    private int subnetInt;//IP的整數表示
    private int subnetMask;//子網掩碼
    private int suffix;//後綴

    /**
     * Creates a subnet from CIDR notation. For example, the subnet
     * 192.168.0.0/24 would be created using the {@link InetAddress}  
     * 192.168.0.0 and the mask 24.
     * @param subnet The {@link InetAddress} of the subnet
     * @param mask The mask
     * 
     * 192.168.0.0/24這是IP地址的一個規範寫法,前面是IP地址,
     * 後面跟一個斜槓以及一個數字,這條斜槓及後面的數字稱爲網絡掩碼(network mask)。
     * 斜槓後面的數字表示有意義的比特位的個數(從左到右)。
     * 例如IP地址:255.255.255.255是IPv4中最大可能的IP地址,
     * 每個數字(255)都是由8個比特位表示的,每個比特位非0即1,最大值即爲11111111,即28=256(0-255)。
     * 瞭解了IP地址之後,就很容易理解上述的寫法了。
     * 比如192.168.0.0/24中的24表示從左到右的24位(也就是前24位)有效,那麼剩下的8位可以是任意數值,
     * 可以是0-254之間的任一地址(255爲廣播地址)。同樣192.168.0.0/32也很好理解,
     * 就是上述IP地址的前32位有效,也就是所有的位都是有效的,即爲192.168.0.0。
     */
    public Subnet(InetAddress subnet, int mask) {
        if(subnet == null) {
            throw new IllegalArgumentException("Subnet address can not be null");
        }
        if(!(subnet instanceof Inet4Address)) {
            throw new IllegalArgumentException("Only IPv4 supported");
        }

        if(mask < 0 || mask > 32) {
            throw new IllegalArgumentException("Mask has to be an integer between 0 and 32");
        }
        
        this.subnet = subnet;
        this.subnetInt = toInt(subnet);
        this.suffix = mask;
        
        // binary mask for this subnet 二進制掩碼   
        /** 這裏的右移是有符號右移,最高位仍是1,即爲負數,負數在計算機中是以補碼錶示的
         * ,例如假設計算機爲8位的處理器,-5用二進制表示爲1000 0101  ,
         *   但是在計算機中的存儲則爲 1000 0101的補碼,即爲  1111 1011 ,這一點要搞清楚
         *   
         *   並且在java中>>表示帶符號右移 ,右移後最高位補1
         *   >>>表示無符號右移,右移後最高位補0
         *   
         *   IP_MASK >> (24-1) ,表示帶符號右移23位 ,則this.subnetMask 的16製爲0xffff ff00
         */
        this.subnetMask = IP_MASK >> (mask - 1);//負數10100110 >>5(假設字長爲8位),則得到的是 11111101
       //符號位向右移動後,正數的話補0,負數補1,也就是彙編語言中的算術右移.
        //同樣當移動的位數超過類型的長度時,會取餘數,然後移動餘數個位 
        /**
   		System.out.println((0x80000000>>30));
		/**
		 * java中>>表示帶符號右移 ,(0x80000000>>30)右移30位,
		 * 在計算機表示爲11111111111111111111111111111110,但是在輸出時爲-2,
		 * 也說明了在計算機中作移位運算是對數的補碼作移位運算,正數的補碼爲其自身,要注意的是負數補碼
		 */
	/**	int a = (0x80000000>>30) ;//11111111111111111111111111111110   
		int b = 0x80000000;
		System.out.println(b);//輸出-2147483648
		for(int i=0;i<32;i++){
			if((a&b)!=0)
				System.out.print("1" );
			else
				System.out.println("0");
			b=b>>>1;//無符號右移
		}   http://blog.csdn.net/gaochizhen33/article/details/7161417
		System.out.println(b);//輸出0
         */
    }

    /** 
     * Converts an IP address into an integer
     */ 
    private int toInt(InetAddress inetAddress) {
        byte[] address = inetAddress.getAddress();
        int result = 0;//例如把134.168.98.75轉換爲int型,32位,每一部分有8位
        for (int i = 0; i < address.length; i++) {//一字節8位
            result <<= 8;//左移8位
            result |= address[i] & BYTE_MASK;
        }
        return result;
    }

    /**
     * Converts an IP address to a subnet using the provided 
     * mask
     * @param address The address to convert into a subnet
     * @return The subnet as an integer
     */
    private int toSubnet(InetAddress address) {
        return toInt(address) & subnetMask;
        //IP地址與子網掩碼相與得到該IP地址的網絡地址,最下面有解釋
    }
    
    /**
     * Checks if the {@link InetAddress} is within this subnet
     * @param address The {@link InetAddress} to check
     * @return True if the address is within this subnet, false otherwise
     */
    public boolean inSubnet(InetAddress address) {
    	//判斷該IP是否在本網段內
        return toSubnet(address) == subnetInt;
    }

    /**
     * @see Object#toString()
     */
    @Override
    public String toString() {
        return subnet.getHostAddress() + "/" + suffix;
    }

    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof Subnet)) {
            return false;
        }
        
        Subnet other = (Subnet) obj;
        
        return other.subnetInt == subnetInt && other.suffix == suffix;
    }

    
}
/**
回答1:
IP地址218.17.209.0/24不能說"0/24"的意思是什麼.這裏面的0是與前面的三個十進制數是一體的,是個IP地址,
也就是218.17.209.0.在這裏是指一個網段.  "/24"是指掩碼的位數是二進制的24位,也就是十進制的255.255.255.0   
 /24可以理解爲從0-255的所有IP地址,其中0爲網絡地址,255爲廣播地址.

回答2:
192.168.0.1/24 
24的意思就是說子網掩碼中表示網絡的二進制位數是24位,即: 11111111.11111111.11111111.00000000 
數一下看是不是24個1,變成十進制就是:255.255.255.0
如果把前面的IP也變成二進制數,即:
11000000.10101000.00000000.00000001 (192.168.0.1)
11111111.11111111.11111111.00000000 (255.255.255.0)
將兩者做'與'運算得:
11000000.10101000.00000000.00000000 
再變成十進制數得:
192.168.0.0
這個就是192.168.0.1這個IP所屬的網絡地址,也可以說192.168.0.1在192.168.0.0這個網段內。

24表示這個IP的子網掩碼是255.255.255.0 
子網掩碼可以表示子網的大小。
如192.168.0.0/24 表示這個IP範圍爲
192.168.0.1-192.168.0.254

*/

另一個就是限制IP訪問的過濾器,俗稱黑名單,如果發起會話的是黑名單上的IP地址或在某一個網段內,則關閉會話,不再將會話傳遞下去,非常好理解


/*
 *
 */
package org.apache.mina.filter.firewall;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A {@link IoFilter} which blocks connections from blacklisted remote
 * address.
 *
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 * @org.apache.xbean.XBean
 */
public class BlacklistFilter extends IoFilterAdapter {
    private final List<Subnet> blacklist = new CopyOnWriteArrayList<Subnet>();

    private final static Logger LOGGER = LoggerFactory.getLogger(BlacklistFilter.class);
    /**
     * Sets the addresses to be blacklisted.
     *
     * NOTE: this call will remove any previously blacklisted addresses.
     *
     * @param addresses an array of addresses to be blacklisted.
     */
    public void setBlacklist(InetAddress[] addresses) {
        if (addresses == null) {
            throw new IllegalArgumentException("addresses");
        }
        blacklist.clear();
        for (int i = 0; i < addresses.length; i++) {
            InetAddress addr = addresses[i];
            block(addr);
        }
    }

    /**
     * Sets the subnets to be blacklisted.
     *
     * NOTE: this call will remove any previously blacklisted subnets.
     *
     * @param subnets an array of subnets to be blacklisted.
     */
    public void setSubnetBlacklist(Subnet[] subnets) {
        if (subnets == null) {
            throw new IllegalArgumentException("Subnets must not be null");
        }
        blacklist.clear();
        for (Subnet subnet : subnets) {
            block(subnet);
        }
    }
    
    /**
     * Sets the addresses to be blacklisted.
     *
     * NOTE: this call will remove any previously blacklisted addresses.
     *
     * @param addresses a collection of InetAddress objects representing the
     *        addresses to be blacklisted.
     * @throws IllegalArgumentException if the specified collections contains
     *         non-{@link InetAddress} objects.
     */
    public void setBlacklist(Iterable<InetAddress> addresses) {
        if (addresses == null) {
            throw new IllegalArgumentException("addresses");
        }

        blacklist.clear();
        
        for( InetAddress address : addresses ){
            block(address);
        }
    }

    /**
     * Sets the subnets to be blacklisted.
     *
     * NOTE: this call will remove any previously blacklisted subnets.
     *
     * @param subnets an array of subnets to be blacklisted.
     */
    public void setSubnetBlacklist(Iterable<Subnet> subnets) {
        if (subnets == null) {
            throw new IllegalArgumentException("Subnets must not be null");
        }
        blacklist.clear();
        for (Subnet subnet : subnets) {
            block(subnet);
        }
    }

    /**
     * Blocks the specified endpoint.
     */
    public void block(InetAddress address) {
        if (address == null) {
            throw new IllegalArgumentException("Adress to block can not be null");
        }
      //這裏的32位表示網絡地址爲32,也就是一個IP,沒有分子網,若是24位(表示一個子網地址),則另外8位爲主機號
        block(new Subnet(address, 32));
    }

    /**
     * Blocks the specified subnet.
     */
    public void block(Subnet subnet) {
        if(subnet == null) {
            throw new IllegalArgumentException("Subnet can not be null");
        }
        
        blacklist.add(subnet);
    }
    
    /**
     * Unblocks the specified endpoint.
     */
    public void unblock(InetAddress address) {
        if (address == null) {
            throw new IllegalArgumentException("Adress to unblock can not be null");
        }
        
        unblock(new Subnet(address, 32));
    }

    /**
     * Unblocks the specified subnet.
     */
    public void unblock(Subnet subnet) {
        if (subnet == null) {
            throw new IllegalArgumentException("Subnet can not be null");
        }
        blacklist.remove(subnet);
    }

    @Override
    public void sessionCreated(NextFilter nextFilter, IoSession session) {
        if (!isBlocked(session)) {
            // forward if not blocked
            nextFilter.sessionCreated(session);
        } else {
            blockSession(session);
        }
    }

    @Override
    public void sessionOpened(NextFilter nextFilter, IoSession session)
            throws Exception {
        if (!isBlocked(session)) {
            // forward if not blocked
            nextFilter.sessionOpened(session);
        } else {
            blockSession(session);
        }
    }

    @Override
    public void sessionClosed(NextFilter nextFilter, IoSession session)
            throws Exception {
        if (!isBlocked(session)) {
            // forward if not blocked
            nextFilter.sessionClosed(session);
        } else {
            blockSession(session);
        }
    }

    @Override
    public void sessionIdle(NextFilter nextFilter, IoSession session,
            IdleStatus status) throws Exception {
        if (!isBlocked(session)) {
            // forward if not blocked
            nextFilter.sessionIdle(session, status);
        } else {
            blockSession(session);
        }
    }

    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session,
            Object message) {
        if (!isBlocked(session)) {
            // forward if not blocked
            nextFilter.messageReceived(session, message);
        } else {
            blockSession(session);
        }
    }

    @Override
    public void messageSent(NextFilter nextFilter, IoSession session,
            WriteRequest writeRequest) throws Exception {
        if (!isBlocked(session)) {
            // forward if not blocked
            nextFilter.messageSent(session, writeRequest);
        } else {
            blockSession(session);
        }
    }

    private void blockSession(IoSession session) {
        LOGGER.warn("Remote address in the blacklist; closing.");
        session.close(true);
    }

    private boolean isBlocked(IoSession session) {
        SocketAddress remoteAddress = session.getRemoteAddress();
        if (remoteAddress instanceof InetSocketAddress) {
            InetAddress address = ((InetSocketAddress) remoteAddress).getAddress(); 
            
            // check all subnets
            for(Subnet subnet : blacklist) {
                if(subnet.inSubnet(address)) {
                    return true;
                }
            }
        }

        return false;
    }
}





發佈了180 篇原創文章 · 獲贊 52 · 訪問量 92萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章