Skip to content

Commit

Permalink
subnet address: MDL-19509 Fix code and unit tests to comply with RFC4…
Browse files Browse the repository at this point in the history
…632 (prefix notations and behaviour)

Backported some code from HEAD to do it.
Merged from MOODLE_19_STABLE
  • Loading branch information
iarenaza committed Jun 21, 2009
1 parent f7fbea5 commit 6fac7bc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
33 changes: 27 additions & 6 deletions lib/moodlelib.php
Expand Up @@ -552,6 +552,22 @@ function clean_param($param, $type) {
}
}

/**
* Return true if given value is integer or string with integer value
*
* @param mixed $value String or Int
* @return bool true if number, false if not
*/
function is_number($value) {
if (is_int($value)) {
return true;
} else if (is_string($value)) {
return ((string)(int)$value) === $value;
} else {
return false;
}
}

/**
* This function is useful for testing whether something you got back from
* the HTML editor actually contains anything. Sometimes the HTML editor
Expand Down Expand Up @@ -6302,14 +6318,19 @@ function address_in_subnet($addr, $subnetstr) {
$subnet = trim($subnet);
if (strpos($subnet, '/') !== false) { /// type 1
list($ip, $mask) = explode('/', $subnet);
if ($mask === '' || $mask > 32) {
$mask = 32;
if (!is_number($mask) || $mask < 0 || $mask > 32) {
continue;
}
if ($mask == 0) {
return true;
}
// When $mask is zero, PHP's integer arithmetic gives us a mask
// of 255.255.255.255 instead of 0.0.0.0, so special case it
if ($mask != 0) {
$mask = 0xffffffff << (32 - $mask);
if ($mask == 32) {
if ($ip === $addr) {
return true;
}
continue;
}
$mask = 0xffffffff << (32 - $mask);
$found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
} else if (strpos($subnet, '-') !== false) {/// type 3
$subnetparts = explode('.', $subnet);
Expand Down
4 changes: 2 additions & 2 deletions lib/simpletest/testmoodlelib.php
Expand Up @@ -81,9 +81,9 @@ function test_address_in_subnet() {
$this->assertTrue(address_in_subnet('123.121.234.15', '123.121.234.2/28'));
$this->assertFalse(address_in_subnet('123.121.234.16', '123.121.234.2/28'));
$this->assertFalse(address_in_subnet('123.121.234.255', '123.121.234.2/28'));
$this->assertTrue(address_in_subnet('123.121.234.0', '123.121.234.0/')); // / is like /32.
$this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.0/'));
$this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.0/'));
$this->assertFalse(address_in_subnet('232.232.232.232', '123.121.234.0/0'));
$this->assertTrue(address_in_subnet('232.232.232.232', '123.121.234.0/0'));
$this->assertFalse(address_in_subnet('123.122.234.1', '123.121.'));
$this->assertFalse(address_in_subnet('223.121.234.1', '123.121.'));
$this->assertTrue(address_in_subnet('123.121.234.1', '123.121'));
Expand Down

0 comments on commit 6fac7bc

Please sign in to comment.