ACC SHELL

Path : /usr/share/YaST2/modules/
File Upload :
Current File : //usr/share/YaST2/modules/Netmask.ycp

/**
 * File:	modules/Netmask.ycp
 * Module:	yast2
 * Summary:	Netmask manipulation routines
 * Authors:	Michal Svec <msvec@suse.cz>
 * Flags:	Stable
 *
 * $Id: Netmask.ycp 58786 2009-09-25 15:57:54Z mzugec $
 */

{

module "Netmask";
textdomain "base";

global string ValidChars = "0123456789.";
global string ValidChars4 = "0123456789.";
global string ValidChars6 = "0123456789";

global define boolean CheckPrefix4(string prefix){
    if(prefix == nil || prefix == "") return false;
    /* <0,32> */
    if(regexpmatch(prefix, "^[0-9]+$")) {
	integer nm = tointeger(prefix);
	return nm >= 0 && nm <= 32;
    } else
	return false;
}

/**
 * Check the IPv4 netmask
 * Note that 0.0.0.0 is not a correct netmask.
 * @param netmask network mask
 * @return true if correct
 */
global define boolean Check4(string netmask) ``{

    if(netmask == nil || netmask == "") return false;


    /* 255.255.240.0 */
    string s1 = "(128|192|224|240|248|252|254|255)";
    string nm = "^(" + s1 + ".0.0.0|" + "255." + s1 + ".0.0|"
	+ "255.255." + s1 + ".0|" + "255.255.255." + s1 + ")$";
    return regexpmatch(netmask, nm);
}

/**
 * Check the IPv6 netmask
 * @param netmask network mask
 * @return true if correct
 */
global define boolean Check6(string netmask) ``{

    if(netmask == nil || netmask == "") return false;

    /* <0,256> */
    if(!regexpmatch(netmask, "^[0-9]+$")) return false;
    integer nm = tointeger(netmask);
    return nm >= 0 && nm <= 256;
}

/**
 * Check the netmask
 * @param netmask network mask
 * @return true if correct
 */
global define boolean Check(string netmask) ``{
    return Check4(netmask) || Check6(netmask);
}

/**
 * Convert netmask in bits form (20) to netmask string (255.255.240.0)
 * @param bits number of bits in netmask
 * @return netmask string
 */
global define string FromBits(integer bits) ``{
    integer b = bits / 8;
    integer d = bits % 8;

    map l = $[ 1:"255.", 2:"255.255.", 3:"255.255.255.", 4:"255.255.255.255" ];
    map r = $[ 3:"0", 2:"0.0", 1:"0.0.0", 0:"0.0.0.0" ];
    map m = $[
	1:"128", 2:"192", 3:"224", 4:"240",
	5:"248", 6:"252", 7:"254", 8:"255",
    ];

    return l[b]:"" + (d!=0? m[d]:""+(b!=3?".":"") : "") + r[d==0?b:(b+1)]:"";
}

/**
 * Convert IPv4 netmask as string (255.255.240.0) to bits form (20)
 * @param netmask netmask as string
 * @return number of bits in netmask; 32 for empty string
 */
global define integer ToBits(string netmask) ``{
    if (netmask == "")
    {
	return 32;
    }
    integer bits = 0;
    map m = $[
	"128":1, "192":2, "224":3, "240":4,
	"248":5, "252":6, "254":7, "255":8,
    ];
    maplist(string i, splitstring(netmask, "."), ``{ bits = bits + m[i]:0; });
    return bits;
}

/* EOF */
}

ACC SHELL 2018