1ca1b71 Implement IP netmask calculation to replace "ipcalc -m"

1 file Authored by coiby 3 years ago, Committed by kasong 3 years ago,
    Implement IP netmask calculation to replace "ipcalc -m"
    
    Recently, dracut-network drops depedency on dhcp-client which requires
    ipcalc. Thus the dependency chain
    "kexec-tools -> dracut-network -> dhcp-client -> ipcalc"
    is broken. When NIC is configured to a static IP, kexec-tools depended
    on "ipcalc -m" to get netmask. This commit implements the shell
    equivalent of "ipcalc -m".
    
    The following test code shows cal_netmask_by_prefix is consistent with
    "ipcalc -m",
    
        #!/bin/bash
        . dracut-module-setup.sh
    
        for i in {0..128}; do
            mask_expected=$(ipcalc -m fe::/$i| cut -d"=" -f2)
            mask_actual=$(cal_netmask_by_prefix $i "-6")
            if [[ "$mask_expected" != "$mask_actual" ]]; then
                echo "prefix="$i, "expected="$mask_expected, "acutal="$mask_actual
                exit
            fi
        done
    
        echo "IPv6 tests passed"
    
        for i in {0..32}; do
            mask_expected=$(ipcalc -m 8.8.8.8/$i| cut -d"=" -f2)
            mask_actual=$(cal_netmask_by_prefix $i "")
            if [[ "$mask_expected" != "$mask_actual" ]]; then
                echo "prefix="$i, "expected="$mask_expected, "acutal="$mask_actual
                exit
            fi
        done
    
        echo "IPv4 tests passed"
    
        i=-2
        res=$(cal_netmask_by_prefix "$i" "")
        if [[ $? -ne 1 ]]; then
            echo "cal_netmask_by_prefix should exit when prefix<0"
            exit
        fi
    
        res=$(cal_netmask_by_prefix "$i" "")
        if [[ $? -ne 1 ]]; then
            echo "cal_netmask_by_prefix should exit when prefix<0"
            exit
        fi
    
        i=33
        $(cal_netmask_by_prefix $i "")
        if [[ $? -ne 1 ]]; then
            echo "cal_netmask_by_prefix should exit when prefix>32 for IPv4"
            exit
        fi
    
        i=129
        $(cal_netmask_by_prefix $i "-6")
        if [[ $? -ne 1 ]]; then
            echo "cal_netmask_by_prefix should exit when prefix>128 for IPv4"
            exit
        fi
    
        echo "Bad prefixes tests passed"
    
        echo "All tests passed"
    
    Reported-by: Jie Li <jieli@redhat.com>
    Signed-off-by: Coiby Xu <coxu@redhat.com>
    Acked-by: Kairui Song <kasong@redhat.com>
    
        
file modified
+117 -2