/** * @covers ::is_ipv4 */ function test_is_ipv4() { $this->assertTrue(is_ipv4("0.0.0.0")); $this->assertFalse(is_ipv4("")); $this->assertFalse(is_ipv4("1")); $this->assertFalse(is_ipv4("17.17")); $this->assertTrue(is_ipv4("17.17.17.17")); $this->assertFalse(is_ipv4("17.17.17.256")); $this->assertFalse(is_ipv4("")); $this->assertFalse(is_ipv4("fe80:0000:0000:0000:0204:61ff:fe9d:f156")); }
function ws_draw_block($window_name, $form = '') { global $conf, $self, $ona; global $images, $color, $style; $html = ''; $js = ''; // Instantiate the xajaxResponse object $response = new xajaxResponse(); // If the user supplied an array in a string, build the array and store it in $form $form = parse_options_string($form); // Find out if $ip is valid $ip = ip_mangle($form['ip'], 'numeric'); if ($ip == -1) { $js .= "alert('Invalid IP address!');"; $response->addScript($js); return $response->getXML(); } // Build a few variables $label = ip_mangle($ip, 'dotted'); if (is_ipv4($ip)) { $string_size = 15; } else { $string_size = 20; } $function = "get_{$form['row_type']}_html"; $row_zoom = $form['row_zoom']; $row_height = $form['row_height']; $row_offset = $form['row_offset']; // This is the number of pixels to leave for the label on the left (.45 * row height, * $string_size possible characters) $label_width = round($form['row_height'] * 0.45 * $string_size); $font_height = $form['row_height'] - 2; // Label font-size if ($font_height < 8) { $font_height = 8; } $row_left = $label_width + 10; // Left offset for the block row // Get some html (the html that goes inside the div) $html = $function($ip, $row_zoom, $row_height); $el_name = $ip . '_row'; // Add a row label $response->addCreate("{$window_name}_substrate", "div", $el_name . '_label'); $response->addScript(<<<EOL var _el = el('{$el_name}_label'); _el.style.visibility = 'hidden'; _el.style.position = 'absolute'; _el.style.textAlign = 'right'; _el.style.color = '#000000'; _el.style.fontSize = '{$font_height}px'; _el.style.top = '{$row_offset}px'; _el.style.left = '2px'; _el.style.width = '{$label_width}px'; _el.style.overflow = 'visible'; _el.style.whiteSpace = 'nowrap'; EOL ); // Add the row $response->addCreate("{$window_name}_substrate", "div", $el_name); $response->addScript(<<<EOL var _el = el('{$el_name}'); _el.style.visibility = 'hidden'; _el.style.position = 'absolute'; _el.style.top = '{$row_offset}px'; _el.style.left = '{$row_left}px'; _el.style.borderTop = '1px solid #000000'; _el.style.borderBottom = '1px solid #000000'; _el.style.borderLeft = '1px solid #000000'; if (browser.isIE) _el.style.fontSize = ({$font_height} - 2) + 'px'; EOL ); // Fill the label and row $response->addAssign($el_name, "innerHTML", $html); $response->addAssign($el_name . '_label', "innerHTML", $label); // Javascript to make sure the container (row) div is the exact length to hold it's contents in one row $response->addScript(<<<EOL var nodes = _el.childNodes; var width = 0; for (var counter=0; counter < nodes.length; counter++) if (nodes[counter].nodeType == 1) width += parseInt(nodes[counter].offsetWidth); if (browser.isIE) width += 1; /* for the left border */ _el.style.width = width + 'px'; EOL ); // Display the label and block $response->addScript(<<<EOL el('{$el_name}_label').style.visibility = 'visible'; el('{$el_name}').style.visibility = 'visible'; /* Tell the browser we've sent it this block so it knows it can re-request it if it needs to */ _map_requests_['{$el_name}'] = undefined; EOL ); if ($js) { $response->addScript($js); } return $response->getXML(); }
function ws_display($window_name, $form = '') { global $conf, $self, $ona; global $images, $color, $style; $html = ''; $js = ''; // If the user supplied an array in a string, build the array and store it in $form $form = parse_options_string($form); // Build $ip from $form['ip_block_start'] $form['ip_block_start'] = ip_complete($form['ip_block_start'], '0'); // Since we currently only display /24 (C) class networks, the //GD Need to call ip_mangle() so we can use is_ipv4() // last quad needs to be a .0. $ip = ip_mangle($form['ip_block_start'], 'numeric'); if (is_ipv4($ip)) { $end = '\\.\\d+$'; $replace_end_by = '.0'; $version = 4; } else { $end = ':[0-9A-F]{0,4}$'; // $replace_end_by = ':0000'; $replace_end_by = ':'; $version = 6; } $ip = $form['ip_block_start'] = preg_replace("/{$end}/", $replace_end_by, $form['ip_block_start']); // Find out if $ip is valid $ip = ip_mangle($ip, 'numeric'); if ($ip == -1) { $js .= "alert('The IP address specified is invalid!');"; } // Update History Title $history = array_pop($_SESSION['ona']['work_space']['history']); $js .= "xajax_window_submit('work_space', ' ', 'rewrite_history');"; if ($history['title'] == $window_name) { $history['title'] = 'Map: ' . ip_mangle($ip, 'dotted'); array_push($_SESSION['ona']['work_space']['history'], $history); } // Create some javascript to refresh the current page $refresh = htmlentities(str_replace(array("'", '"'), array("\\'", '\\"'), $history['url']), ENT_QUOTES, $conf['php_charset']); $refresh = "xajax_window_submit('work_space', '{$refresh}');"; // Define the window's inner html $html .= <<<EOL <div id="{$window_name}_content" style="padding: 2px 4px;"> <form id="block_search_form" onsubmit="el('zoom_block_button').onclick(); return false;"> <div id="{$window_name}_tools"> <b>IP Address</b> <input type="hidden" id="{$window_name}_zoom" name="zoom" value="8"> <input id="{$window_name}_ip_block_start" name="{$window_name}_ip_block_start" value="{$form['ip_block_start']}" class="edit" type="text" size="15" /> <a id="zoom_block_button" title="Zoom block" class="act" onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'{$window_name}\\', \\'ip_block_start=>' + el('{$window_name}_ip_block_start').value + ',zoom=>' + el('{$window_name}_zoom').value + '\\', \\'display\\');');" ><img src="{$images}/silk/bullet_go.png" border="0"></a> <br><br> </div> </form> <div id="{$window_name}_portal"> <span id="{$window_name}_substrate"></span> </div> </div> EOL; // Position/size the portal ourselves $js .= <<<EOL var _el = el('{$window_name}_portal'); /* Now calculate where we will sit */ var my_height = el('work_space_content').offsetHeight - el('{$window_name}_tools').offsetHeight - 40; var my_width = el('{$window_name}_tools').offsetWidth - 10; /* Finally reposition/resize the window */ _el.style.position = 'relative'; _el.style.height = my_height + 'px'; EOL; // Get javascript to setup the map portal $js .= get_portal_js($window_name, $ip, $version); //*** Send a fake mouseup event to draw the initial map view *** $js .= "el('{$window_name}_portal').myonmouseup('fake event');"; // Insert the new html into the window // Instantiate the xajaxResponse object $response = new xajaxResponse(); // GDO need to use Big Int JS $response->addIncludeScript('include/js/bignumber.js'); $response->addAssign("work_space_content", "innerHTML", $html); if ($js) { $response->addScript($js); } return $response->getXML(); }
function type($ip) { if (!$ip) { return false; } if (is_ipv4($ip)) { return "ipv4"; } if (is_ipv6($ip)) { return "ipv6"; } return "unknown"; }
Domain : <input type="text" name="domain" placeholder="localhost.com" > <input type="submit" name="shcresolver" value="Resolver"> </form> <?php if ($_POST['shcresolver']) { echo "<hr>"; function is_ipv4($ip) { return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ? $ip : '(Null)'; } $url = $_POST['domain']; $sdom = array('www.', 'cpanel.', 'ftp.', 'mail.', 'webmail.', 'direct.', 'direct-connect.', 'record.', 'ssl.', 'dns.', 'help.', 'blog.', 'forum.'); $count = count($sdom); foreach ($sdom as $key => $value) { $urls = $value . $url; $ip = is_ipv4(gethostbyname($urls)); $headers = get_headers("http://" . $ip, 1); $server = $headers['Server']; $http_code = $headers['0']; if (preg_match('/cloudflare/i', $server)) { echo $urls . " [<font color=red>cloudflare {$ip} </font>] {$http_code}<br>"; } else { echo $urls . " [<font color=green>cloudflare {$ip} </font>] {$http_code}<br>"; } flush(); ob_flush(); } } ?> </div> <?php
function ipcalc_info($ip = '', $mask = '') { global $conf, $self; // MP: fix the fact that I"m not testing for the GMP module.. it will fail for ipv6 stuff $retarray = array(); $retarray['in_ip'] = $ip; $retarray['in_mask'] = $mask; $retarray['mask_cidr'] = ip_mangle($retarray['in_mask'], 'cidr'); // Process the IP address $retarray['ip_dotted'] = ip_mangle($retarray['in_ip'], dotted); $retarray['ip_numeric'] = ip_mangle($retarray['in_ip'], numeric); $retarray['ip_binary'] = ip_mangle($retarray['in_ip'], binary); $retarray['ip_bin128'] = ip_mangle($retarray['in_ip'], bin128); $retarray['ip_ipv6'] = ip_mangle($retarray['in_ip'], ipv6); $retarray['ip_ipv6gz'] = ip_mangle($retarray['in_ip'], ipv6gz); $retarray['ip_flip'] = ip_mangle($retarray['in_ip'], flip); // Process the mask $retarray['mask_dotted'] = ip_mangle($retarray['in_mask'], dotted); $retarray['mask_numeric'] = ip_mangle($retarray['in_mask'], numeric); $retarray['mask_binary'] = ip_mangle($retarray['in_mask'], binary); $retarray['mask_bin128'] = ip_mangle($retarray['in_mask'], bin128); $retarray['mask_ipv6'] = ip_mangle($retarray['in_mask'], ipv6); $retarray['mask_ipv6gz'] = ip_mangle($retarray['in_mask'], ipv6gz); $retarray['mask_flip'] = ip_mangle($retarray['in_mask'], flip); // Invert the binary mask $inverted = str_replace("0", "x", ip_mangle($retarray['in_mask'], binary)); $inverted = str_replace("1", "0", $inverted); $inverted = str_replace("x", "1", $inverted); $retarray['mask_bin_invert'] = $inverted; $retarray['mask_dotted_invert'] = ip_mangle($inverted, dotted); // Check boundaries // This section checks that the IP address and mask are valid together. // if the IP address does not fall on a proper boundary based on the provided mask // we will return the 'truenet' that it would fall into. $retarray['netboundary'] = 1; if (is_ipv4($retarray['ip_numeric'])) { // echo "ipv4"; $padding = 32; $fmt = 'dotted'; $ip1 = ip_mangle($retarray['ip_numeric'], 'binary'); $ip2 = str_pad(substr($ip1, 0, $retarray['mask_cidr']), $padding, '0'); $total = 0xffffffff - $retarray['mask_numeric'] + 1; $usable = $total - 2; $lastip = ip_mangle($ip2, numeric) - 1 + $total; $retarray['ip_last'] = ip_mangle($lastip, 'dotted'); } else { // echo "ipv6"; $padding = 128; $fmt = 'ipv6gz'; $ip1 = ip_mangle($retarray['ip_numeric'], 'bin128'); $ip2 = str_pad(substr($ip1, 0, $retarray['mask_cidr']), $padding, '0'); $sub = gmp_sub("340282366920938463463374607431768211455", $retarray['mask_numeric']); $total = gmp_strval(gmp_add($sub, '1')); $usable = gmp_strval(gmp_sub($total, '2')); $lastip = gmp_strval(gmp_add(gmp_sub(ip_mangle($ip2, 'numeric'), '1'), $total)); $retarray['ip_last'] = ip_mangle($lastip, 'ipv6'); } // Validate that the subnet IP & netmask combo are valid together. $ip1 = ip_mangle($ip1, $fmt); $ip2 = ip_mangle($ip2, $fmt); $retarray['truenet'] = $ip2; // this is the subnet IP that your IP would fall in given the mask provided. if ($ip1 != $ip2) { $retarray['netboundary'] = 0; } // this means the IP passed in is NOT on a network boundary // Get IP address counts $retarray['ip_total'] = $total; $retarray['ip_usable'] = $usable; return $retarray; }
function interface_modify($options = "") { global $conf, $self, $onadb; printmsg("DEBUG => interface_modify({$options}) called", 3); // Version - UPDATE on every edit! $version = '1.11'; // Parse incoming options string to an array $options = parse_options($options); // Set options[use_primary] to N if they're not set $options['use_primary'] = sanitize_YN($options['use_primary'], 'N'); // Set options[force] to N if it's not set $options['force'] = sanitize_YN($options['force'], 'N'); // Return the usage summary if we need to if ($options['help'] or !$options['interface'] and !$options['host'] or !$options['set_ip'] and !$options['set_mac'] and !$options['set_description'] and !$options['set_last_response'] and !$options['set_name']) { // NOTE: Help message lines should not exceed 80 characters for proper display on a console $self['error'] = 'ERROR => Insufficient parameters'; return array(1, <<<EOM interface_modify-v{$version} Modify an interface record Synopsis: interface_modify [KEY=VALUE] ... Required: interface=ID or IP or MAC interface ID or IP address or host=NAME[.DOMAIN] or ID find interface by hostname or host_id set_ip=IP change IP address (numeric or dotted format) set_mac=ADDRESS change the mac address (most formats ok) set_name=NAME interface name (i.e. "FastEthernet0/1.100") set_description=TEXT description (i.e. "VPN link to building 3") set_last_response=DATE date ip was last seen Optional: use_primary[=Y] use the host's primary interface (only applies when "host" option is used!). NOTE: dcm.pl requires a value ("Y"). EOM ); } // They provided a interface ID, IP address, interface name, or MAC address if ($options['interface']) { // Find an interface record by something in that interface's record list($status, $rows, $interface) = ona_find_interface($options['interface']); } else { if ($options['host']) { // Find a host by the user's input list($status, $rows, $host) = ona_find_host($options['host']); if (!$host['id']) { printmsg("DEBUG => Host not found ({$options['host']})!", 3); $self['error'] = "ERROR => Host not found ({$options['host']})!"; return array(2, $self['error'] . "\n"); } // If we got one, load an associated interface // ... or the primary interface, if the use_primary option is present if ($options['use_primary'] == 'Y') { list($status, $rows, $interface) = ona_get_interface_record(array('id' => $host['primary_interface_id'])); } else { list($status, $rows, $interface) = ona_get_interface_record(array('host_id' => $host['id'])); if ($rows > 1) { printmsg("DEBUG => Specified host ({$options['host']}) has more than one interface!", 3); $self['error'] = "ERROR => Specified host ({$options['host']}) has more than one interface!"; return array(3, $self['error'] . "\n"); } } } } // If we didn't get a record then exit if (!$interface or !$interface['id']) { printmsg("DEBUG => Interface not found ({$options['interface']})!", 3); $self['error'] = "ERROR => Interface not found ({$options['interface']})!"; return array(4, $self['error'] . "\n"); } // This array will contain the updated info we'll insert into the DB $SET = array(); // Setting an IP address? if ($options['set_ip']) { $options['set_ip'] = trim($options['set_ip']); $orig_ip = $options['set_ip']; $options['set_ip'] = ip_mangle($options['set_ip'], 'numeric'); if ($options['set_ip'] == -1) { printmsg("DEBUG => Invalid IP address ({$orig_ip})", 3); $self['error'] = "ERROR => Invalid IP address ({$orig_ip})"; return array(5, $self['error'] . "\n"); } // Validate that there isn't already another interface with the same IP address list($status, $rows, $record) = ona_get_interface_record("ip_addr = {$options['set_ip']}"); if ($rows and $record['id'] != $interface['id']) { printmsg("DEBUG => IP conflict: That IP address (" . ip_mangle($orig_ip, 'dotted') . ") is already in use!", 3); $self['error'] = "ERROR => IP conflict: specified IP (" . ip_mangle($orig_ip, 'dotted') . ") is already in use!"; return array(6, $self['error'] . "\nINFO => Conflicting interface record ID: {$record['ID']}\n"); } // Since the IP seems available, let's double check and make sure it's not in a DHCP address pool list($status, $rows, $pool) = ona_get_dhcp_pool_record("ip_addr_start <= '{$options['set_ip']}' AND ip_addr_end >= '{$options['set_ip']}'"); if ($status or $rows) { printmsg("DEBUG => IP conflict: That IP address (" . ip_mangle($orig_ip, 'dotted') . ") falls within a DHCP address pool!", 3); $self['error'] = "ERROR => IP conflict: That IP address (" . ip_mangle($orig_ip, 'dotted') . ") falls within a DHCP address pool!"; return array(5, $self['error'] . "\n" . "INFO => Conflicting DHCP pool record ID: {$pool['id']}\n"); } // Find the Subnet (network) ID to use from the IP address list($status, $rows, $subnet) = ona_find_subnet(ip_mangle($options['set_ip'], 'dotted')); if ($status or !$rows) { printmsg("DEBUG => That IP address (" . ip_mangle($orig_ip, 'dotted') . ") is not inside a defined subnet!", 3); $self['error'] = "ERROR => That IP address (" . ip_mangle($orig_ip, 'dotted') . ") is not inside a defined subnet!"; return array(7, $self['error'] . "\n"); } // Validate that the IP address supplied isn't the base or broadcast of the subnet if (is_ipv4($options['set_ip']) && $options['set_ip'] == $subnet['ip_addr'] || !is_ipv4($options['set_ip']) && !gmp_cmp(gmp_init($options['set_ip']), gmp_init($subnet['ip_addr']))) { printmsg("DEBUG => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be a subnet's base address!", 3); $self['error'] = "ERROR => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be a subnet's base address!"; return array(8, $self['error'] . "\n"); } if (is_ipv4($options['set_ip']) && $options['set_ip'] == 4294967295 - $subnet['ip_mask'] + $subnet['ip_addr'] || !is_ipv4($options['set_ip']) && !gmp_cmp(gmp_init($options['set_ip']), gmp_add(gmp_init($subnet['ip_addr']), gmp_sub("340282366920938463463374607431768211455", $subnet['ip_mask'])))) { printmsg("DEBUG => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be a subnet's broadcast address!", 3); $self['error'] = "ERROR => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be the subnet broadcast address!"; return array(9, $self['error'] . "\n"); } // Allow some overrides. if ($options['force'] != 'Y') { // Search for any existing interfaces on the same subnet // list($status, $rows, $record) = ona_get_interface_record(array('subnet_id' => $subnet['id'], // 'host_id' => $interface['host_id'])); // Check to be sure we don't exceed maximum lengths if (strlen($options['name']) > 255) { $self['error'] = "ERROR => 'name' exceeds maximum length of 255 characters."; return array(2, $self['error'] . "\n" . "NOTICE => You may ignore this error and add the interface anyway with the \"force=yes\" option.\n"); } if (strlen($options['description']) > 255) { $self['error'] = "ERROR => 'description' exceeds maximum length of 255 characters."; return array(2, $self['error'] . "\n" . "NOTICE => You may ignore this error and add the interface anyway with the \"force=yes\" option.\n"); } } // Make sure we update the ptr record domain if needed. // MP: TODO: would it be better to run the dns_modify module vs doing a direct db_update_record??? $ipflip = ip_mangle($options['set_ip'], 'flip'); $octets = explode(".", $ipflip); if (count($octets) > 4) { $arpa = '.ip6.arpa'; $octcount = 31; } else { $arpa = '.in-addr.arpa'; $octcount = 3; } // Find a pointer zone for this record to associate with. list($status, $prows, $ptrdomain) = ona_find_domain($ipflip . $arpa); if (isset($ptrdomain['id'])) { list($status, $rows, $dnsrec) = ona_get_dns_record(array('type' => 'PTR', 'interface_id' => $interface['id'])); // If the new ptrdomain does not match an existing ptr records domain then we need to change it. if ($rows > 0 and $dnsrec['domain_id'] != $ptrdomain['id']) { list($status, $rows) = db_update_record($onadb, 'dns', array('id' => $dnsrec['id']), array('domain_id' => $ptrdomain['id'], 'ebegin' => date('Y-m-j G:i:s'))); if ($status or !$rows) { $self['error'] = "ERROR => interface_modify() PTR record domain update failed: " . $self['error']; printmsg($self['error'], 0); return array(14, $self['error'] . "\n"); } } } // TRIGGER: Since we are changing the IP of an interface that dns records may point to, we need to loop through them all if ($interface['ip_addr'] != $options['set_ip']) { // Get all the DNS records using this interface ID list($status, $rows, $records) = db_get_records($onadb, 'dns', array('interface_id' => $interface['id'])); // Loop them and set their domains for rebuild foreach ($records as $record) { list($status, $rows) = db_update_record($onadb, 'dns_server_domains', array('domain_id' => $record['domain_id']), array('rebuild_flag' => 1)); if ($status) { $self['error'] = "ERROR => dns_record_add() Unable to update rebuild flags for domain.: {$self['error']}"; printmsg($self['error'], 0); return array(7, $self['error'] . "\n"); } } } // Check permissions // if (!authlvl($subnet['LVL'])) { // $self['error'] = "Permission denied!"; // printmsg($self['error'], 0); // return(array(13, $self['error'] . "\n")); // } // Everything looks ok, add it to $SET if ($interface['subnet_id'] != $subnet['id']) { $SET['subnet_id'] = $subnet['id']; } if ($interface['ip_addr'] != $options['set_ip']) { $SET['ip_addr'] = $options['set_ip']; } } // Setting an MAC address? if (array_key_exists('set_mac', $options)) { if ($options['set_mac']) { // allow null mac addresses (to unset one for example) $options['set_mac'] = trim($options['set_mac']); $orig_mac = $options['set_mac']; $options['set_mac'] = mac_mangle($options['set_mac'], 1); if ($options['set_mac'] == -1) { printmsg("DEBUG => The MAC address specified ({$orig_mac}) is invalid!", 3); $self['error'] = "ERROR => The MAC address specified ({$orig_mac}) is invalid!"; return array(11, $self['error'] . "\n"); } // Unless they have opted to allow duplicate mac addresses ... if ($options['force'] != 'Y') { // Validate that there isn't already another interface with the same MAC address on another host // Assume duplicate macs on the same host are ok list($status, $rows, $record) = db_get_record($onadb, 'interfaces', "mac_addr LIKE '{$options['set_mac']}' AND host_id != {$interface['host_id']}"); if ($rows and $record['id'] != $interface['id'] or $rows > 1) { printmsg("DEBUG => MAC conflict: That MAC address ({$options['set_mac']}) is already in use on another host!", 3); $self['error'] = "ERROR => MAC conflict: That MAC address ({$options['set_mac']}) is already in use on another host!"; return array(12, $self['error'] . "\n" . "NOTICE => You may ignore this error and update the interface anyway with the \"force=yes\" option.\n" . "INFO => Conflicting interface record ID: {$record['id']}\n"); } } } if ($interface['mac_addr'] != $options['set_mac']) { $SET['mac_addr'] = $options['set_mac']; } } // Check the date formatting etc if (isset($options['set_last_response'])) { // format the time that was passed in for the database $SET['last_response'] = date('Y-m-j G-i-s', strtotime($options['set_last_response'])); } // Set options[set_name]? if (array_key_exists('set_name', $options) && $interface['name'] != $options['set_name']) { $SET['name'] = trim($options['set_name']); } // Set options[set_description]? if (array_key_exists('set_description', $options) && $interface['description'] != $options['set_description']) { $SET['description'] = $options['set_description']; } // Check permissions list($status, $rows, $host) = ona_find_host($interface['host_id']); if (!auth('interface_modify')) { $self['error'] = "Permission denied!"; printmsg($self['error'], 0); return array(13, $self['error'] . "\n"); } // Get the interface record before updating (logging) list($status, $rows, $original_interface) = ona_get_interface_record(array('id' => $interface['id'])); // Update the interface record if (count($SET) > 0) { list($status, $rows) = db_update_record($onadb, 'interfaces', array('id' => $interface['id']), $SET); if ($status or !$rows) { $self['error'] = "ERROR => interface_modify() SQL Query failed: " . $self['error']; printmsg($self['error'], 0); return array(14, $self['error'] . "\n"); } } // Get the interface record after updating (logging) list($status, $rows, $new_interface) = ona_get_interface_record(array('id' => $interface['id'])); list($status, $rows, $new_int) = ona_find_interface($interface['id']); // Return the success notice $text = format_array($SET); $self['error'] = "INFO => Interface UPDATED:{$interface['id']}: {$new_int['ip_addr_text']}"; $log_msg = "INFO => Interface UPDATED:{$interface['id']}:{$new_int['ip_addr_text']}: "; $more = ""; foreach (array_keys($original_interface) as $key) { if ($original_interface[$key] != $new_interface[$key]) { $log_msg .= $more . $key . "[" . $original_interface[$key] . "=>" . $new_interface[$key] . "]"; $more = ";"; } } // only print to logfile if a change has been made to the record if ($more != '') { printmsg($log_msg, 0); } return array(0, $self['error'] . "\n{$text}\n"); }
function get_subnet_html($subnet_ip) { global $conf, $self, $onadb; global $font_family, $color, $style, $images; $html = $js = ''; $font_color = '#FFFFFF'; $style['content_box'] = <<<EOL margin: 10px 20px; padding: 2px 4px; background-color: #FFFFFF; vertical-align: top; EOL; $style['label_box'] = <<<EOL font-weight: bold; padding: 2px 4px; border: solid 1px {$color['border']}; background-color: {$color['window_content_bg']}; EOL; // Load the subnet record list($status, $rows, $subnet) = ona_find_subnet($subnet_ip); // If we didn't get one, tell them to add a record here if ($rows == 0 or $status) { // Calculate what the end of this block is so we can reccomend the max subnet size // GD: add IPv6 functionnality by imposing GMP use when not ipv4 subnet list($status, $rows, $subnets) = db_get_records($onadb, "subnets", "ip_addr > " . ip_mangle($subnet_ip, 'numeric'), "ip_addr", 1); if (!is_ipv4($subnet_ip)) { if ($rows >= 1) { $subnet_ip_end = gmp_sub(gmp_init($subnets[0]['ip_addr']), 1); $size = gmp_add(gmp_sub($subnet_ip_end, $subnet_ip), 1); if (gmp_mod($size, 2) == 1) { gmp_sub($size, 1); } // GD: very bad way to get the mask ... but gmp_log() does not exist ! for ($mask = 65; $mask > 48; $mask--) { if (gmp_cmp($size, gmp_pow("2", $mask)) > 0) { $mask++; break; } } $subnet['ip_addr'] = ip_mangle(gmp_strval($subnet_ip), 'dotted'); $subnet['ip_addr_end'] = ip_mangle(gmp_strval($subnet_ip_end), 'dotted'); $str_subnet_ip = gmp_strval($subnet_ip); $size = gmp_strval($size); } else { $subnet_ip_end = -1; $size = 0; } } else { if ($rows >= 1) { $subnet_ip_end = $subnets[0]['ip_addr'] - 1; $size = $subnet_ip_end - $subnet_ip + 1; if ($size % 2 == 1) { $size--; } $mask = ceil(32 - log($size) / log(2)); $subnet['ip_addr'] = ip_mangle($subnet_ip, 'dotted'); $subnet['ip_addr_end'] = ip_mangle($subnet_ip_end, 'dotted'); $str_subnet_ip = $subnet_ip; } else { $subnet_ip_end = -1; $size = 0; } } $html .= <<<EOL <!-- NO SUBNET --> <table cellspacing="0" border="0" cellpadding="0"> <!-- LABEL --> <tr><td width=100% colspan="2" nowrap="true" style="{$style['label_box']}"> <a title="Add a new subnet here" class="act" onClick="xajax_window_submit('edit_subnet', 'ip_addr=>{$str_subnet_ip}', 'editor');" >Add a subnet here</a> </td></tr> <tr> <td align="right" nowrap="true" style="color: {$font_color};"><b>IP Range</b> </td> <td class="padding" nowrap="true" align="left" style="color: {$font_color};">{$subnet['ip_addr']} - {$subnet['ip_addr_end']} ({$size} addresses)</td> </tr> EOL; $largest_subnet = array(0, 0, 0); // -- IPv4 if (is_ipv4($subnet_ip)) { $ip = $subnet_ip; while ($ip < $subnet_ip_end) { // find the largest mask for the specified ip $myip = ip_mangle($ip, 'dotted'); $mymask = $mask; while ($mymask <= 30) { $ip1 = ip_mangle($ip, 'binary'); $ip2 = str_pad(substr($ip1, 0, $mymask), 32, '0'); $mysize = pow(2, 32 - $mymask); $myhosts = $mysize - 2; $ip1 = ip_mangle($ip1, 'dotted'); $ip2 = ip_mangle($ip2, 'dotted'); if ($ip1 == $ip2 and $ip + $mysize - 1 <= $subnet_ip_end) { break; } $mymask++; } if ($mymask == 31) { break; } if ($mysize > $largest_subnet[2]) { $largest_subnet = array(ip_mangle($ip, 'dotted'), $mymask, $mysize); } $html .= <<<EOL <!-- <tr> <td align="right" nowrap="true" style="color: {$font_color};"> </td> <td class="padding" align="left" style="color: {$font_color};">{$myip} /{$mymask} ({$myhosts} hosts)</td> </tr> --> EOL; // Increment $ip $ip += $mysize; } // remove 2 for gateway and broadcast $largest_subnet[2] = $largest_subnet[2] - 2; } else { $ip = gmp_init($subnet_ip); // GD: trying to avoid falling into time/memory-trap // Won't enter in the loop if difference between IP and next subnet IP is too big // (more than 5 x /64) if (gmp_cmp(gmp_sub($subnet_ip_end, $ip), gmp_mul("18446744073709551616", "5")) > 0) { $html .= <<<EOL \t<tr> \t<td align="right" nowrap="true" style="color: {$font_color};"> </td> \t<td align="right" nowrap="true" style="color: {$font_color};">Next Subnet too far away</td> \t<tr> EOL; return array($html, $js); } while (gmp_cmp($ip, $subnet_ip_end) < 0) { // find the largest mask for the specified ip $myip = ip_mangle(gmp_strval($ip), 'dotted'); $mymask = $mask; while ($mymask <= 64) { $ip1 = ip_mangle(gmp_strval($ip), 'bin128'); $ip2 = str_pad(substr($ip1, 0, $mymask), 128, '0'); $mysize = gmp_pow("2", 128 - $mymask); $myhosts = gmp_strval(gmp_sub($mysize, 2)); $ip1 = ip_mangle($ip1, 'dotted'); $ip2 = ip_mangle($ip2, 'dotted'); if (strcmp($ip1, $ip2) == 0 and gmp_cmp(gmp_sub(gmp_add($ip, $mysize), 1), $subnet_ip_end) <= 0) { break; } $mymask++; } if ($mymask == 90) { break; } if (gmp_cmp($mysize, $largest_subnet[2]) > 0) { $largest_subnet = array(ip_mangle(gmp_strval($ip), 'dotted'), $mymask, $mysize); } $html .= <<<EOL <!-- <tr> <td align="right" nowrap="true" style="color: {$font_color};"> </td> <td class="padding" align="left" style="color: {$font_color};">{$mask} {$myip} /{$mymask} ({$myhosts} hosts)td> </tr> --> EOL; // Increment $ip $ip = gmp_add($ip, $mysize); } // DON'T remove 2 for gateway and broadcast $largest_subnet[2] = gmp_strval($largest_subnet[2]); } $html .= <<<EOL <tr> <td align="right" nowrap="true" style="color: {$font_color};"><b>Largest block</b> </td> <td class="padding" nowrap="true" align="left" style="color: {$font_color};">{$largest_subnet[0]} /{$largest_subnet[1]} ({$largest_subnet[2]} usable hosts)</td> </tr> </table> EOL; return array($html, $js); } // -- // -- FOUND SUBNET IN DB // -- // Convert IP and Netmask to a presentable format $subnet['ip_addr'] = ip_mangle($subnet['ip_addr'], 'dotted'); $subnet['ip_mask'] = ip_mangle($subnet['ip_mask'], 'dotted'); $subnet['ip_mask_cidr'] = ip_mangle($subnet['ip_mask'], 'cidr'); list($status, $rows, $type) = ona_get_subnet_type_record(array('id' => $subnet['subnet_type_id'])); $subnet['type'] = $type['display_name']; // Calculate the percentage of the subnet that's used (total size - allocated hosts - dhcp pool size) $usage_html = get_subnet_usage_html($subnet['id']); foreach (array_keys((array) $subnet) as $key) { $subnet[$key] = htmlentities($subnet[$key], ENT_QUOTES, $conf['php_charset']); } foreach (array_keys((array) $location) as $key) { $location[$key] = htmlentities($location[$key], ENT_QUOTES, $conf['php_charset']); } $html .= <<<EOL <!-- SUBNET INFORMATION --> <table cellspacing="0" border="0" cellpadding="0"> <!-- LABEL --> <tr><td width=100% colspan="2" nowrap="true" style="{$style['label_box']}"> <a title="View subnet. ID: {$subnet['id']}" class="nav" onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'subnet_id=>{$subnet['id']}\\', \\'display\\')');" >{$subnet['name']}</a> </td></tr> <tr> <td align="right" nowrap="true" style="color: {$font_color};"><b>IP Address</b> </td> <td class="padding" align="left" style="color: {$font_color};">{$subnet['ip_addr']} /{$subnet['ip_mask_cidr']}</td> </tr> <tr> <td align="right" nowrap="true" style="color: {$font_color};"><b>Usage</b> </td> <td class="padding" align="left" style="color: {$font_color};">{$usage_html}</td> </tr> EOL; if ($subnet['type']) { $html .= <<<EOL <tr> <td align="right" nowrap="true" style="color: {$font_color};"><b>Type</b> </td> <td class="padding" align="left" style="color: {$font_color};">{$subnet['type']} </td> </tr> EOL; } $html .= <<<EOL </table> EOL; return array($html, $js); }
function ws_display($window_name, $form = '') { global $conf, $self, $onadb; global $images, $color, $style; $html = ''; $js = ''; $debug_val = 3; // used in the auth() calls to supress logging // If the user supplied an array in a string, build the array and store it in $form $form = parse_options_string($form); // Load the host record list($status, $rows, $record) = ona_get_block_record(array('id' => $form['block_id'])); if ($status or !$rows) { array_pop($_SESSION['ona']['work_space']['history']); $html .= "<br><center><font color=\"red\"><b>Block doesn't exist!</b></font></center>"; $response = new xajaxResponse(); $response->addAssign("work_space_content", "innerHTML", $html); return $response->getXML(); } // Update History Title $history = array_pop($_SESSION['ona']['work_space']['history']); $js .= "xajax_window_submit('work_space', ' ', 'rewrite_history');"; if ($history['title'] == $window_name) { $history['title'] = $record['name']; array_push($_SESSION['ona']['work_space']['history'], $history); } // Create some javascript to refresh the current page $refresh = htmlentities(str_replace(array("'", '"'), array("\\'", '\\"'), $history['url']), ENT_QUOTES, $conf['php_charset']); $refresh = "xajax_window_submit('work_space', '{$refresh}');"; $record['ip_addr_start'] = ip_mangle($record['ip_addr_start'], 'dotted'); $record['ip_addr_end'] = ip_mangle($record['ip_addr_end'], 'dotted'); $style['content_box'] = <<<EOL margin: 10px 20px; padding: 2px 4px; background-color: #FFFFFF; vertical-align: top; EOL; $style['label_box'] = <<<EOL font-weight: bold; padding: 2px 4px; border: solid 1px {$color['border']}; background-color: {$color['window_content_bg']}; EOL; // Escape data for display in html foreach (array_keys($record) as $key) { $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']); } $html .= <<<EOL <!-- FORMATTING TABLE --> <div style="{$style['content_box']}"> <table cellspacing="0" border="0" cellpadding="0"><tr> <!-- START OF FIRST COLUMN OF SMALL BOXES --> <td nowrap="true" valign="top" style="padding-right: 15px;"> EOL; // BLOCK INFORMATION $html .= <<<EOL <table width=100% cellspacing="0" border="0" cellpadding="0" style="margin-bottom: 8px;"> <tr><td colspan="99" nowrap="true" style="{$style['label_box']}"> <!-- LABEL --> <form id="form_block_{$record['id']}" ><input type="hidden" name="block_id" value="{$record['id']}" ><input type="hidden" name="js" value="{$refresh}" ></form> EOL; if (auth('advanced', $debug_val)) { $html .= <<<EOL <a title="Edit block" class="act" onClick="xajax_window_submit('edit_block', xajax.getFormValues('form_block_{$record['id']}'), 'editor');" ><img src="{$images}/silk/page_edit.png" border="0"></a> <a title="Delete block" class="act" onClick="var doit=confirm('Are you sure you want to delete this block?'); if (doit == true) xajax_window_submit('edit_block', xajax.getFormValues('form_block_{$record['id']}'), 'delete');" ><img src="{$images}/silk/delete.png" border="0"></a> EOL; } $html .= <<<EOL {$record['name']} <a href="?work_space={$window_name}&block_id={$record['id']}"><img title="Direct link to {$record['name']}" src="{$images}/silk/application_link.png" border="0"></a> </td> </tr> <tr> <td align="right" nowrap="true"><b>Name</b> </td> <td class="padding" align="left">{$record['name']} </td> </tr> <tr> <td align="right" nowrap="true"><b>IP start</b> </td> <td class="padding" align="left"> {$record['ip_addr_start']} </td> </tr> <tr> <td align="right" nowrap="true"><b>IP end</b> </td> <td class="padding" align="left"> {$record['ip_addr_end']} </td> </tr> <tr> <td align="right" nowrap="true"><b>Notes</b> </td> <td class="padding" align="left"> {$record['notes']} </td> </tr> </table> EOL; // END BLOCK INFORMATION $html .= <<<EOL <!-- END OF FIRST COLUMN OF SMALL BOXES --> </td> <!-- START OF SECOND COLUMN OF SMALL BOXES --> <td valign="top" style="padding-right: 15px;"> EOL; // SMALL SUBNET MAP // Get the numeric IP address of our subnet (we replace the last quad with a .0) $ip_subnet = ip_mangle($record['ip_addr_start'], 'numeric'); if (is_ipv4($ip_subnet)) { $end = '\\.\\d+$'; $replace_end_by = '.0'; $version = 4; } else { $end = ':[0-9A-F]{0,4}$'; // $replace_end_by = ':0000'; $replace_end_by = ':'; $version = 6; } $ip = ip_mangle(preg_replace("/{$end}/", $replace_end_by, $record['ip_addr_start']), 'numeric'); $html .= <<<EOL <table width=100% cellspacing="0" border="0" cellpadding="0" style="margin-bottom: 8px;"> <tr><td colspan="99" nowrap="true"> <!-- LABEL --> <div style="{$style['label_box']}"> <a title="Display full sized subnet map" class="act" onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_block_map\\', \\'ip_block_start=>{$record['ip_addr_start']},ip_block_end=>{$record['ip_addr_end']},id=>{$record['id']}\\', \\'display\\');');" ><img src="{$images}/silk/shape_align_left.png" border="0"></a> <a title="Highlight start of block" class="act" onClick=" var _el = el('{$ip_subnet}_row_label'); if (_el) { if (_el.style.isHighlighted) { _el.style.backgroundColor = '#000000'; _el.style.isHighlighted = false; } else { _el.style.backgroundColor = '{$color['bgcolor_map_selected']}'; _el.style.isHighlighted = true; } } " ><img src="{$images}/silk/paintbrush.png" border="0"></a> <b>Block Map</b> </div> </td></tr> <tr><td colspan="99" nowrap="true"> <input type="hidden" id="{$window_name}_zoom" name="zoom" value="7"> <div id="{$window_name}_portal" style="position: relative; height: 150px; width: 355px;"> <span id="{$window_name}_substrate"></span> </div> </td></tr> </table> EOL; // Get javascript to setup the map portal mouse handlers // Force ip end to be less than ip start to prevent Block highlighting $portal_js .= get_portal_js($window_name, $ip, $version); //*** Send a fake mouseup event to draw the initial map view *** $portal_js .= "el('{$window_name}_portal').myonmouseup('fake event');"; // END SMALL SUBNET MAP $html .= <<<EOL <!-- END OF SECOND COLUMN OF SMALL BOXES --> </td> <!-- START OF THIRD COLUMN OF SMALL BOXES --> <td valign="top" style="padding-right: 15px;"> EOL; $html .= <<<EOL </td> <!-- END OF THIRD COLUMN OF SMALL BOXES --> </tr></table> </div> <!-- END OF TOP SECTION --> EOL; // SUBNET LIST $tab = 'subnets'; $submit_window = "list_{$tab}"; $form_id = "{$submit_window}_filter_form"; $_SESSION['ona'][$form_id]['tab'] = $tab; $content_id = "{$window_name}_{$submit_window}"; $html .= <<<EOL <!-- SUBNET LIST --> <div style="border: 1px solid {$color['border']}; margin: 10px 20px;"> <!-- Tab & Quick Filter --> <table id="{$form_id}_table" cellspacing="0" border="0" cellpadding="0"> <tr> <td id="{$form_id}_subnets_tab" class="table-tab-active"> Associated {$tab} <span id="{$form_id}_{$tab}_count"></span> </td> <td id="{$form_id}_quick_filter" class="padding" align="right" width="100%"> <form id="{$form_id}" onSubmit="return false;"> <input id="{$form_id}_page" name="page" value="1" type="hidden"> <input name="content_id" value="{$content_id}" type="hidden"> <input name="form_id" value="{$form_id}" type="hidden"> <input name="ip_subnet" value="{$record['ip_addr_start']}" type="hidden"> <input name="ip_subnet_thru" value="{$record['ip_addr_end']}" type="hidden"> <div id="{$form_id}_filter_overlay" title="Filter" style="position: relative; display: inline; color: #CACACA; cursor: text;" onClick="this.style.display = 'none'; el('{$form_id}_filter').focus();" >Name</div> <input id="{$form_id}_filter" name="filter" class="filter" type="text" value="" size="10" maxlength="20" alt="Quick Filter" onFocus="el('{$form_id}_filter_overlay').style.display = 'none';" onBlur="if (this.value == '') el('{$form_id}_filter_overlay').style.display = 'inline';" onKeyUp=" if (typeof(timer) != 'undefined') clearTimeout(timer); code = 'if ({$form_id}_last_search != el(\\'{$form_id}_filter\\').value) {' + ' {$form_id}_last_search = el(\\'{$form_id}_filter\\').value;' + ' document.getElementById(\\'{$form_id}_page\\').value = 1;' + ' xajax_window_submit(\\'{$submit_window}\\', xajax.getFormValues(\\'{$form_id}\\'), \\'display_list\\');' + '}'; timer = setTimeout(code, 700);" > </form> </td> </tr> </table> <div id='{$content_id}'> {$conf['loading_icon']} </div> </div> EOL; $js .= <<<EOL /* Setup the quick filter */ el('{$form_id}_filter_overlay').style.left = (el('{$form_id}_filter_overlay').offsetWidth + 10) + 'px'; {$form_id}_last_search = ''; /* Tell the browser to load/display the list */ xajax_window_submit('{$submit_window}', xajax.getFormValues('{$form_id}'), 'display_list'); EOL; // Insert the new html into the window // Instantiate the xajaxResponse object $response = new xajaxResponse(); // GDO need to use Big Int JS $response->addIncludeScript('include/js/bignumber.js'); $response->addAssign("work_space_content", "innerHTML", $html); if ($js) { $response->addScript($js . $portal_js); } return $response->getXML(); }
function subnet_modify($options = "") { global $conf, $self, $onadb; //printmsg('DEBUG => subnet_modify('.implode (";",$options).') called', 3); // Version - UPDATE on every edit! $version = '1.08'; // Parse incoming options string to an array $options = parse_options($options); // Return the usage summary if we need to if ($options['help'] or !$options['subnet'] or !($options['set_ip'] or $options['set_netmask'] or $options['set_type'] or $options['set_name'] or array_key_exists('set_vlan', $options) or $options['set_security_level'])) { // NOTE: Help message lines should not exceed 80 characters for proper display on a console $self['error'] = 'ERROR => Insufficient parameters'; return array(1, <<<EOM subnet_modify-v{$version} Modify a subnet (subnet) record Synopsis: subnet_modify [KEY=VALUE] ... Where: subnet=[ID|IP] select subnet by search string Update: set_ip=IP change subnet "subnet" address set_netmask=MASK change subnet netmask set_name=TEXT change subnet name (i.e. "LAN-1234") set_type=TYPE change subnet type by name or id set_vlan=VLAN change vlan by name, number campus=CAMPUS vlan campus name or id to help identify vlan set_security_level=LEVEL numeric security level ({$conf['ona_lvl']}) EOM ); } $check_boundaries = 0; // Find the subnet record we're modifying list($status, $rows, $subnet) = ona_find_subnet($options['subnet']); if ($status or !$rows) { $self['error'] = "ERROR => Subnet not found"; return array(2, $self['error'] . "\n"); } // Check permissions if (!auth('subnet_modify')) { $self['error'] = "Permission denied!"; printmsg($self['error'], 0); return array(3, $self['error'] . "\n"); } // Validate the ip address if (!$options['set_ip']) { $options['set_ip'] = $subnet['ip_addr']; } else { $check_boundaries = 1; $options['set_ip'] = $setip = ip_mangle($options['set_ip'], 'numeric'); // FIXME: what if ip_mangle returns a GMP object? if ($options['set_ip'] == -1) { $self['error'] = "ERROR => The IP address specified is invalid!"; return array(4, $self['error'] . "\n"); } } // Validate the netmask is okay if (!$options['set_netmask']) { $options['set_netmask'] = $subnet['ip_mask']; $cidr = ip_mangle($options['set_netmask'], 'cidr'); } else { $check_boundaries = 1; $cidr = ip_mangle($options['set_netmask'], 'cidr'); // FIXME: what if ip_mangle returns a GMP object? $options['set_netmask'] = ip_mangle($options['set_netmask'], 'numeric'); if ($cidr == -1 or $options['set_netmask'] == -1) { $self['error'] = "ERROR => The netmask specified is invalid!"; return array(5, $self['error'] . "\n"); } } if (is_ipv4($setip)) { $padding = 32; $fmt = 'dotted'; $ip1 = ip_mangle($setip, 'binary'); $num_hosts = 0xffffffff - $options['set_netmask']; $first_host = $options['set_ip'] + 1; $last_host = $options['set_ip'] + $num_hosts; $str_last_host = $last_host; $last_last_host = $last_host - 1; } else { $padding = 128; $fmt = 'ipv6gz'; $ip1 = ip_mangle($setip, 'bin128'); $first_host = gmp_strval(gmp_add($options['set_ip'], 1)); $sub = gmp_sub("340282366920938463463374607431768211455", $options['set_netmask']); $last_host = gmp_add($options['set_ip'], $sub); $str_last_host = gmp_strval($last_host); $last_last_host = gmp_strval(gmp_sub($last_host, 1)); } // Validate that the subnet IP & netmask combo are valid together. $ip2 = str_pad(substr($ip1, 0, $cidr), $padding, '0'); $ip1 = ip_mangle($ip1, $fmt); $ip2 = ip_mangle($ip2, $fmt); if ($ip1 != $ip2) { $self['error'] = "ERROR => Invalid subnet specified - did you mean: {$ip2}/{$cidr}?"; return array(6, $self['error'] . "\n"); } // If our IP or netmask changed we need to make sure that // we won't abandon any host interfaces. // We also need to verify that the new boundaries are valid and // don't interefere with any other subnets. if ($check_boundaries == 1) { // *** Check to see if the new subnet overlaps any existing ONA subnets *** // // I convert the IP address to dotted format when calling ona_find_subnet() // because it saves it from doing a few unnecessary sql queries. // Look for overlaps like this (where new subnet address starts inside an existing subnet): // [ -- new subnet -- ] // [ -- old subnet --] list($status, $rows, $record) = ona_find_subnet(ip_mangle($options['set_ip'], 'dotted')); if ($rows and $record['id'] != $subnet['id']) { $self['error'] = "ERROR => Subnet address conflict! New subnet starts inside an existing subnet."; return array(7, $self['error'] . "\n" . "ERROR => Conflicting subnet record ID: {$record['id']}\n"); } // Look for overlaps like this (where the new subnet ends inside an existing subnet): // [ -- new subnet -- ] // [ -- old subnet --] // Find last address of our subnet, and see if it's inside of any other subnet: list($status, $rows, $record) = ona_find_subnet(ip_mangle($str_last_host, 'dotted')); if ($rows and $record['id'] != $subnet['id']) { $self['error'] = "ERROR => Subnet address conflict! New subnet ends inside an existing subnet."; return array(8, $self['error'] . "\n" . "ERROR => Conflicting subnet record ID: {$record['id']}\n"); } // Look for overlaps like this (where the new subnet entirely overlaps an existing subnet): // [ -------- new subnet --------- ] // [ -- old subnet --] // // Do a cool SQL query to find all subnets whose start address is >= or <= the // new subnet base address. $where = "ip_addr >= {$options['set_ip']} AND ip_addr <= {$str_last_host}"; list($status, $rows, $record) = ona_get_subnet_record($where); if ($rows > 1 or $rows == 1 and $record['id'] != $subnet['id']) { $self['error'] = "ERROR => Subnet address conflict! New subnet would encompass an existing subnet."; return array(9, $self['error'] . "\n" . "ERROR => Conflicting subnet record ID: {$record['id']}\n"); } // Look for any hosts that are currently in our subnet that would be // abandoned if we were to make the proposed changes. // Look for hosts on either side of the new subnet boundaries: // [--- new subnet ---] // * ** * * <-- Hosts: the first and last host would be a problem! // [------- old subnet --------] // $where1 = "subnet_id = {$subnet['id']} AND ip_addr < {$first_host}"; $where2 = "subnet_id = {$subnet['id']} AND ip_addr > {$last_last_host}"; list($status, $rows1, $record) = ona_get_interface_record($where1); list($status, $rows2, $record) = ona_get_interface_record($where2); if ($rows1 or $rows2) { $num = $rows1 + $rows2; $self['error'] = "ERROR => Changes would abandon {$num} hosts in an unallocated ip space"; return array(10, $self['error'] . "\n"); } // Look for any dhcp pools that are currently in our subnet that would be // abandoned if we were to make the proposed changes. // Look for existin pools with start/end values outside of new subnet range // [--- new subnet ---] // [--cur pool--] // [------- old subnet --------] // $where1 = "subnet_id = {$subnet['id']} AND ip_addr_start < {$options['set_ip']}"; $where2 = "subnet_id = {$subnet['id']} AND ip_addr_end > {$str_last_host}"; list($status, $rows1, $record) = ona_get_dhcp_pool_record($where1); list($status, $rows2, $record) = ona_get_dhcp_pool_record($where2); if ($rows1 or $rows2) { $num = $rows1 + $rows2; $self['error'] = "ERROR => Changes would abandon a DHCP pool in an unallocated ip space, adjust pool sizes first"; return array(10, $self['error'] . "\n"); } } // // Define the fields we're updating // // This variable will contain the updated info we'll insert into the DB $SET = array(); $SET['ip_addr'] = $options['set_ip']; $SET['ip_mask'] = $options['set_netmask']; // Set options['set_security_level']? // Sanitize "security_level" option if (array_key_exists('set_security_level', $options)) { $options['set_security_level'] = sanitize_security_level($options['set_security_level']); if ($options['set_security_level'] == -1) { return array(11, $self['error'] . "\n"); } $SET['lvl'] = $options['set_security_level']; } // Set options['set_name']? if ($options['set_name']) { // BUSINESS RULE: We require subnet names to be in upper case and spaces are converted to -'s. $options['set_name'] = trim($options['set_name']); $options['set_name'] = preg_replace('/\\s+/', '-', $options['set_name']); $options['set_name'] = strtoupper($options['set_name']); // Make sure there's not another subnet with this name list($status, $rows, $tmp) = ona_get_subnet_record(array('name' => $options['set_name'])); if ($status or $rows > 1 or $rows == 1 and $tmp['id'] != $subnet['id']) { $self['error'] = "ERROR => That name is already used by another subnet!"; return array(12, $self['error'] . "\n"); } $SET['name'] = $options['set_name']; } // Set options['set_type']? if ($options['set_type']) { // Find the type from $options[type] list($status, $rows, $subnet_type) = ona_find_subnet_type($options['set_type']); if ($status or $rows != 1) { $self['error'] = "ERROR => Invalid subnet type specified!"; return array(13, $self['error'] . "\n"); } printmsg("Subnet type selected: {$subnet_type['display_name']} ({$subnet_type['short_name']})", 1); $SET['subnet_type_id'] = $subnet_type['id']; } // Set options['set_vlan']? if (array_key_exists('set_vlan', $options) or $options['campus']) { if (!$options['set_vlan']) { $SET['vlan_id'] = ''; } else { // Find the VLAN ID from $options[set_vlan] and $options[campus] list($status, $rows, $vlan) = ona_find_vlan($options['set_vlan'], $options['campus']); if ($status or $rows != 1) { $self['error'] = "ERROR => The vlan/campus pair specified is invalid!"; return array(15, $self['error'] . "\n"); } printmsg("VLAN selected: {$vlan['name']} in {$vlan['vlan_campus_name']} campus", 1); $SET['vlan_id'] = $vlan['id']; } } // Update the subnet record list($status, $rows) = db_update_record($onadb, 'subnets', array('id' => $subnet['id']), $SET); if ($status or !$rows) { return array(16, $self['error'] . "\n"); } // Load the updated record for display list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $subnet['id'])); // Return the (human-readable) success notice $text = format_array($SET); $self['error'] = "INFO => Subnet UPDATED"; return array(0, $self['error'] . ":\n{$text}\n"); }
//Add a normal handel to a multi handle } $null = NULL; try { curl_multi_exec($mh, $null); //Processes each of the handles in the stack. } catch (Exception $e) { echo "Could Not Execute"; //Display very informative error text } for ($i = 0; $i < $numberof; $i++) { if (!curl_error($ch[$i]) && empty(curl_multi_getcontent($ch[$i]))) { echo "<tr>"; echo "<td>" . 'http://' . htmlentities($Subdomains[$i] . "." . $target) . "</td>"; $site = htmlentities($Subdomains[$i] . "." . $target); $ip = is_ipv4(gethostbyname($site)); echo "<td>" . "{$ip}" . "</td>"; echo "</tr>"; } curl_multi_remove_handle($mh, $ch[$i]); //Close Connection curl_close($ch[$i]); //Close Connection } curl_multi_close($mh); //Closes a set of cURL handles. } elseif (isset($_POST['target'])) { echo "URL is invalid. URL must be formatted as: http(s)://example.com (for compatibility reasons)"; } else { } ?>
$ip = array_shift($line); if (is_ipv4($ip)) { $disabled['ipv4'][$ip] = $line; continue; } if (is_ipv6($ip)) { $disabled['ipv6'][$ip] = $line; continue; } $comment_line[] = "# " . implode(" ", $line); continue; } $line = preg_split("/[\\s\t]+/", $line); $ip = array_shift($line); // preveri če ip obstaja, da ne prepiše if (is_ipv4($ip)) { foreach ($line as $l) { $entry['ipv4'][$ip][] = $l; } continue; } if (is_ipv6($ip)) { foreach ($line as $l) { $entry['ipv6'][$ip][] = $l; } continue; } $i++; } $output['disabled'] = $disabled; $output['comment'] = $comment_line;
/** * Parse and lookup an IP address reference * * Given an ip in the form `net:`_netid_._hostid_, it will generate * IPv4 and/or IPv6 addresses for it. * * @param $ip string IP address reference * @param &$cf array_ref Configuration array, must have a `nets` element * @return array Array of strings containing IPv4/IPv6 addresses */ function lk_parse_ip($ip, &$cf) { list($netid, $hostid) = parse_ipnet($ip); $res = array(); if ($netid) { if (!isset($cf['nets'][$netid])) { trigger_error("Unknown network {$ip}", E_USER_WARNING); return $res; } $res['netid'] = $netid; $netdat =& $cf['nets'][$netid]; if (isset($netdat['vlan'])) { $res['vlan'] = $netdat['vlan']; } $res['hostid'] = $hostid; if (!$hostid) { return $res; } // Configured without IP... if (isset($netdat['ip6'])) { $res['ip6'] = $netdat['ip6'] . '::' . dechex($hostid); } if (isset($netdat['ip4'])) { $res['ip4'] = $netdat['ip4'] . '.' . $hostid; } } else { if (is_ipv6($ip)) { $res['ip6'] = $ip; } elseif (is_ipv4($ip)) { $res['ip4'] = $ip; } } return $res; }
function get_ip_suggestions($q, $max_results = 10) { global $onadb; $formatted = $results = array(); // Complete the (potentially incomplete) ip address $ip = ip_complete($q, '0'); $ip_end = ip_complete($q, '255'); // Find out if $ip and $ip_end are valid $ip = ip_mangle($ip, 'numeric'); $ip_end = ip_mangle($ip_end, 'numeric'); if ($ip == -1 or $ip_end == -1) { return array(); } // It's not valid ip addresses // Now use SQL to look for subnet ip records that match $table = 'subnets'; $field = 'ip_addr'; $where = "{$field} >= " . $onadb->qstr($ip) . " AND {$field} <= " . $onadb->qstr($ip_end); $order = "{$field} ASC"; // Search the db for results and put results into $results list($status, $rows, $records) = db_get_records($onadb, $table, $where, $order, $max_results); foreach ($records as $record) { $results[] = $record[$field]; } // If we need more suggestions, look in the host_subnets table $max_results -= count($results); if ($max_results) { $table = 'interfaces'; list($status, $rows, $records) = db_get_records($onadb, $table, $where, $order, $max_results); foreach ($records as $record) { $results[] = $record[$field]; } } // Format the ip's in dotted format sort($results); foreach ($results as $result) { // format ipv6 or regular $format = is_ipv4($result) ? 'dotted' : 'ipv6'; $formatted[] = ip_mangle($result, $format); } unset($results, $result, $records, $record); return $formatted; }
echo "SO_KEEPALIVE = " . $option . "\n"; } if (($options = socket_get_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 10, 'usec' => 0))) === FALSE) { echo "socket_set_option for SO_RCVTIMEO failed\n"; } else { echo "SO_RCVTIMEO = 5 seconds\n"; } $localURL = "esp8266.local"; $count = 0; $remote_port = '2652'; $secCnt = 0; $outputArray = array(); $execRet; //Do some communication, this loop can handle multiple clients if (isset($argv[1])) { if (is_ipv4($argv[1])) { $remote_ip = $argv[1]; } else { $execCmd = "avahi-resolve --name {$argv['1']}"; $execArray = explode("\t", exec($execCmd, $outputArray, $execRet)); //$outputCnt = count($outputArray); //echo "There are $outputCnt values in \$outputCnt\n"; //echo "\$outputArray[1] = $outputArray[1]\n"; //echo "\$execRet = $execRet\n"; $arrayCnt = count($execArray); //echo "There are $arrayCnt \$arrayCnt values\n"; for ($z = 0; $z < $arrayCnt; $z++) { if (!isset($execArray[$z]) || $execArray[$z] == NULL) { die("Couldn't resolve {$argv['1']}, exiting\n"); } }
function _fw_expand_ips($opt, $ipspec, $fam) { $res = array(); if (substr($ipspec, 0, 4) == 'net:') { _fw_add_ips($opt, $ipspec, $fam, $res); return $res; } if (($fam == 'ipv6' || $fam == 'any') && is_ipv6($ipspec)) { $res[] = ' option ' . $opt . ' ' . $addr . NL; return $res; } if (($fam == 'ipv4' || $fam == 'any') && is_ipv4($ipspec)) { $res[] = ' option ' . $opt . ' ' . $addr . NL; return $res; } $nic = NULL; $hn = $ipspec; if ($p = strrpos($ipspec, '-')) { if ($p) { $nic = substr($ipspec, $p + 1); $hn = substr($ipspec, 0, $p); } } foreach (lk_addr($hn, $nic) as $addr) { if (($fam == 'ipv4' || $fam == 'any') && isset($addr['ip4'])) { $res[] = ' option ' . $opt . ' ' . $addr['ip4'] . NL; } if (($fam == 'ipv6' || $fam == 'any') && isset($addr['ip6'])) { $res[] = ' option ' . $opt . ' ' . $addr['ip6'] . NL; } } if (!count($res)) { // trigger_error("Unable to lookup ipspec: $ipspec",E_USER_WARNING); $res[] = ' option ' . $opt . ' ' . $ipspec . NL; } return $res; }
/** * Determines whether the specified is a valid IP address * * @param string $string the string to validate as an IP * @return bool true if the specified string is a valid IP address; otherwise, false */ function is_ip($string) { return is_ipv4($string) || is_ipv6($string); }
function is_ip($test) { return is_ipv4($test) or is_ipv6($test); }
function testproxyin($proxy) { // Separate IP and port if (($splited = @explode(':', $proxy)) == true && is_ipv4($splited[0])) { if (!filter_var($splited[0], FILTER_VALIDATE_IP)) { helpe("Wrong proxy input."); } if ($con = @fsockopen($splited[0], $splited[1], $eroare, $eroare_str, 3)) { @fclose($con); // Close the socket handle return true; } else { return false; } } else { return false; } }