Example #1
0
function dispatchImageRequest()
{
    genericAssertion('img', 'string');
    global $pageno, $tabno;
    switch ($_REQUEST['img']) {
        case 'minirack':
            // rack security context
            $pageno = 'rack';
            $tabno = 'default';
            fixContext();
            assertPermission();
            dispatchMiniRackThumbRequest(getBypassValue());
            break;
        case 'midirack':
            // rack security context
            $pageno = 'rack';
            $tabno = 'default';
            fixContext();
            assertPermission();
            genericAssertion('scale', 'uint');
            # Scaling implies no caching, there is no special dispatching.
            header('Content-type: image/png');
            printRackThumbImage(getBypassValue(), $_REQUEST['scale']);
            break;
        case 'preview':
            // file security context
            $pageno = 'file';
            $tabno = 'download';
            fixContext();
            assertPermission();
            renderImagePreview(getBypassValue());
            break;
        case 'cactigraph':
            $pageno = 'object';
            $tabno = 'cacti';
            fixContext();
            assertPermission();
            genericAssertion('server_id', 'uint');
            genericAssertion('graph_id', 'uint');
            if (!array_key_exists($_REQUEST['graph_id'], getCactiGraphsForObject(getBypassValue()))) {
                throw new InvalidRequestArgException('graph_id', $_REQUEST['graph_id']);
            }
            proxyCactiRequest($_REQUEST['server_id'], $_REQUEST['graph_id']);
            break;
        case 'muningraph':
            $pageno = 'object';
            $tabno = 'munin';
            fixContext();
            assertPermission();
            genericAssertion('server_id', 'uint');
            genericAssertion('graph', 'string');
            if (!array_key_exists($_REQUEST['graph'], getMuninGraphsForObject(getBypassValue()))) {
                throw new InvalidRequestArgException('graph', $_REQUEST['graph']);
            }
            proxyMuninRequest($_REQUEST['server_id'], $_REQUEST['graph']);
            break;
        default:
            renderErrorImage();
    }
}
function getAttrNewValue($attr_id)
{
    $num_attrs = genericAssertion('num_attrs', 'uint0');
    for ($i = 0; $i < $num_attrs; $i++) {
        if ($attr_id == genericAssertion("{$i}_attr_id", 'uint')) {
            return genericAssertion("{$i}_value", 'string0');
        }
    }
    return NULL;
}
function renderPatchCableHeapSummary()
{
    $summary = getPatchCableHeapSummary();
    if (!count($summary)) {
        return;
    }
    startPortlet('Heaps');
    global $nextorder;
    echo '<br><table class=cooltable align=center border=0 cellpadding=5 cellspacing=0>';
    echo '<tr><th>Amount</th><th>End 1</th><th>Cable type</th><th>End 2</th><th>Length</th><th>Description</th><th>&nbsp;</th></tr>';
    $order = 'odd';
    $zoom_heap_id = array_key_exists('zoom_heap_id', $_REQUEST) ? genericAssertion('zoom_heap_id', 'uint') : NULL;
    foreach ($summary as $heap) {
        echo "<tr class=row_{$order}>";
        echo "<td class=tdright>{$heap['amount']}</td>";
        echo "<td class=tdleft>{$heap['end1_connector']}</td>";
        echo "<td class=tdleft>{$heap['pctype']}</td>";
        echo "<td class=tdleft>{$heap['end2_connector']}</td>";
        echo "<td class=tdright>{$heap['length']}</td>";
        echo "<td class=tdleft>{$heap['description']}</td>";
        echo '<td>' . getPatchCableHeapCursorCode($heap, $zoom_heap_id) . '</td>';
        echo '</tr>';
        $order = $nextorder[$order];
    }
    echo '</table>';
    finishPortlet();
    if ($zoom_heap_id === NULL) {
        return;
    }
    if (!count($eventlog = getPatchCableHeapLogEntries($zoom_heap_id))) {
        return;
    }
    startPortlet('Event log');
    echo '<br><table class=cooltable align=center border=0 cellpadding=5 cellspacing=0>';
    echo '<tr><th>Date</th><th>User</th><th>Message</th></tr>';
    $order = 'odd';
    foreach ($eventlog as $event) {
        echo "<tr class=row_{$order}>";
        echo "<td class=tdleft>{$event['date']}</td>";
        echo '<td class=tdleft>' . stringForTD($event['user'], 255) . '</td>';
        echo '<td class=tdleft>' . stringForTD($event['message'], 255) . '</td>';
        echo '</tr>';
        $order = $nextorder[$order];
    }
    echo '</table>';
    finishPortlet();
}
function initRackTablesRack($remain_hostgroups)
{
    // get the data of zabbix hostgroup
    $params = array('output' => 'extend', 'sortfield' => array('name'));
    $result = doPost('hostgroup.get', $params);
    $hostgroups = isset($result['result']) ? $result['result'] : array();
    global $row_id;
    global $rack_height;
    $rowInfo = getRowInfo($row_id);
    $sort_order = $rowInfo['count'];
    foreach ($hostgroups as $hostgroup) {
        if (in_array($hostgroup['name'], $remain_hostgroups)) {
            continue;
        }
        $taglist = genericAssertion('taglist', 'array0');
        $sort_order += 1;
        $rack_id = commitAddObject($hostgroup['name'], NULL, 1560, "", $taglist);
        // set height
        $params = array('output' => array('hostids'), 'groupids' => array($hostgroup['groupid']));
        $result = doPost('host.get', $params);
        $height = isset($result['result']) ? count($result['result']) : 0;
        if ($height < $rack_height) {
            $height = $rack_height;
        }
        commitUpdateAttrValue($rack_id, 27, $height);
        commitUpdateAttrValue($rack_id, 29, $sort_order);
        // Link it to the row
        commitLinkEntities('row', $row_id, 'rack', $rack_id);
    }
    $rackDatas = array();
    $allRacks = scanRealmByText('rack');
    foreach ($allRacks as $rack_id => $rack) {
        $rackDatas[$rack['name']] = $allRacks[$rack_id];
    }
    return $rackDatas;
}
Example #5
0
function dispatchImageRequest()
{
    genericAssertion('img', 'string');
    global $pageno, $tabno;
    switch ($_REQUEST['img']) {
        case 'minirack':
            // rack security context
            $pageno = 'rack';
            $tabno = 'default';
            fixContext();
            assertPermission();
            renderRackThumb(getBypassValue());
            break;
        case 'preview':
            // file security context
            $pageno = 'file';
            $tabno = 'download';
            fixContext();
            assertPermission();
            renderImagePreview(getBypassValue());
            break;
        case 'cactigraph':
            $pageno = 'object';
            $tabno = 'cacti';
            fixContext();
            assertPermission();
            genericAssertion('graph_id', 'uint');
            if (!array_key_exists($_REQUEST['graph_id'], getCactiGraphsForObject(getBypassValue()))) {
                throw new InvalidRequestArgException('graph_id', $_REQUEST['graph_id']);
            }
            proxyCactiRequest($_REQUEST['graph_id']);
            break;
        default:
            renderErrorImage();
    }
}
function getPortInfoAJAX()
{
    $funcmap = array('get-port-link' => 'formatPortLinkHints', 'get-port-mac' => 'formatPortMacHints', 'get-port-conf' => 'formatPortConfigHints');
    $opmap = array('get-port-link' => 'get_link_status', 'get-port-mac' => 'get_mac_list', 'get-port-conf' => 'get_port_conf');
    genericAssertion('object_id', 'uint');
    fixContext(spotEntity('object', $_REQUEST['object_id']));
    assertPermission('object', 'liveports', $opmap[$_REQUEST['ac']]);
    echo json_encode($funcmap[$_REQUEST['ac']]($_REQUEST['object_id']));
}
Example #7
0
function setPatchCableAmount()
{
    commitSetPatchCableAmount(genericAssertion('id', 'uint'), genericAssertion('amount', 'uint0'));
    showFuncMessage(__FUNCTION__, 'OK');
}
function setPortVLAN()
{
    assertUIntArg('portcount');
    try {
        $data = getSwitchVLANs($_REQUEST['object_id']);
    } catch (RTGatewayError $re) {
        return showFuncMessage(__FUNCTION__, 'ERR', array($re->getMessage()));
    }
    list($vlanlist, $portlist) = $data;
    // Here we just build up 1 set command for the gateway with all of the ports
    // included. The gateway is expected to filter unnecessary changes silently
    // and to provide a list of responses with either error or success message
    // for each of the rest.
    $nports = $_REQUEST['portcount'];
    $prefix = 'set ';
    $setcmd = '';
    for ($i = 0; $i < $nports; $i++) {
        genericAssertion('portname_' . $i, 'string');
        genericAssertion('vlanid_' . $i, 'string');
        if ($_REQUEST['portname_' . $i] != $portlist[$i]['portname']) {
            throw new InvalidRequestArgException('portname_' . $i, $_REQUEST['portname_' . $i], 'expected to be ' . $portlist[$i]['portname']);
        }
        if ($_REQUEST['vlanid_' . $i] == $portlist[$i]['vlanid'] || $portlist[$i]['vlanid'] == 'TRUNK') {
            continue;
        }
        $portname = $_REQUEST['portname_' . $i];
        $oldvlanid = $portlist[$i]['vlanid'];
        $newvlanid = $_REQUEST['vlanid_' . $i];
        if (!permitted(NULL, NULL, NULL, array(array('tag' => '$fromvlan_' . $oldvlanid), array('tag' => '$vlan_' . $oldvlanid))) or !permitted(NULL, NULL, NULL, array(array('tag' => '$tovlan_' . $newvlanid), array('tag' => '$vlan_' . $newvlanid)))) {
            showOneLiner(159, array($portname, $oldvlanid, $newvlanid));
            continue;
        }
        $setcmd .= $prefix . $portname . '=' . $newvlanid;
        $prefix = ';';
    }
    // Feed the gateway and interpret its (non)response.
    if ($setcmd == '') {
        showOneLiner(201);
    } else {
        try {
            setSwitchVLANs($_REQUEST['object_id'], $setcmd);
            // shows messages by itself
        } catch (RTGatewayError $e) {
            showFuncMessage(__FUNCTION__, 'ERR', array($e->getMessage()));
        }
    }
}
Example #9
0
function handlePopupPortLink()
{
    assertPermission('depot', 'default');
    assertUIntArg('port');
    assertUIntArg('remote_port');
    assertStringArg('cable', TRUE);
    $port_info = getPortInfo($_REQUEST['port']);
    $remote_port_info = getPortInfo($_REQUEST['remote_port']);
    $POIFC = getPortOIFCompat();
    if (isset($_REQUEST['port_type']) and isset($_REQUEST['remote_port_type'])) {
        $type_local = $_REQUEST['port_type'];
        $type_remote = $_REQUEST['remote_port_type'];
    } else {
        $type_local = $port_info['oif_id'];
        $type_remote = $remote_port_info['oif_id'];
    }
    $matches = FALSE;
    $js_table = '';
    foreach ($POIFC as $pair) {
        if ($pair['type1'] == $type_local && $pair['type2'] == $type_remote) {
            $matches = TRUE;
            break;
        } else {
            $js_table .= "POIFC['{$pair['type1']}-{$pair['type2']}'] = 1;\n";
        }
    }
    if ($matches) {
        if ($port_info['oif_id'] != $type_local) {
            commitUpdatePortOIF($port_info['id'], $type_local);
        }
        if ($remote_port_info['oif_id'] != $type_remote) {
            commitUpdatePortOIF($remote_port_info['id'], $type_remote);
        }
        linkPorts($port_info['id'], $remote_port_info['id'], $_REQUEST['cable']);
        // patch cable?
        if (array_key_exists('heap_id', $_REQUEST)) {
            // Leave the compatibility constraints check up to the foreign keys.
            if (0 != ($heap_id = genericAssertion('heap_id', 'uint0'))) {
                $heaps = getPatchCableHeapSummary();
                if (commitModifyPatchCableAmount($heap_id, -1)) {
                    showSuccess('consumed a patch cable from ' . formatPatchCableHeapAsPlainText($heaps[$heap_id]));
                } else {
                    showError('failed to consume a patch cable');
                }
            }
        }
        showOneLiner(8, array(formatPortLink($port_info['object_id'], NULL, $port_info['id'], $port_info['name']), formatPort($remote_port_info)));
        addJS(<<<END
window.opener.location.reload(true);
window.close();
END
, TRUE);
        backupLogMessages();
    } else {
        // JS code to display port compatibility hint
        addJS(<<<END
POIFC = {};
{$js_table}
\$(document).ready(function () {
\t\$('select.porttype').change(onPortTypeChange);\t
\tonPortTypeChange();
});
function onPortTypeChange() {
\tvar key = \$('*[name=port_type]')[0].value + '-' + \$('*[name=remote_port_type]')[0].value;
\tif (POIFC[key] == 1)
\t{
\t\t\$('#hint-not-compat').hide();
\t\t\$('#hint-compat').show();
\t}
\telse
\t{
\t\t\$('#hint-compat').hide();
\t\t\$('#hint-not-compat').show();
\t}
}
END
, TRUE);
        addCSS(<<<END
.compat-hint {
\tdisplay: none;
\tfont-size: 125%;
}
.compat-hint#hint-compat {
\tcolor: green;
}
.compat-hint#hint-not-compat {
\tcolor: #804040;
}
END
, TRUE);
        // render port type editor form
        echo '<form method=GET>';
        echo '<input type=hidden name="module" value="popup">';
        echo '<input type=hidden name="helper" value="portlist">';
        echo '<input type=hidden name="port" value="' . $port_info['id'] . '">';
        echo '<input type=hidden name="remote_port" value="' . $remote_port_info['id'] . '">';
        echo '<input type=hidden name="cable" value="' . htmlspecialchars($_REQUEST['cable'], ENT_QUOTES) . '">';
        echo '<p>The ports you have selected are not compatible. Please select a compatible transceiver pair.';
        echo '<p>';
        echo formatPort($port_info) . ' ';
        if ($port_info['iif_id'] == 1) {
            echo formatPortIIFOIF($port_info);
            echo '<input type=hidden name="port_type" value="' . $port_info['oif_id'] . '">';
        } else {
            echo '<label>' . $port_info['iif_name'] . ' ';
            printSelect(getExistingPortTypeOptions($port_info), array('class' => 'porttype', 'name' => 'port_type'), $type_local);
            echo '</label>';
        }
        echo ' &mdash; ';
        if ($remote_port_info['iif_id'] == 1) {
            echo formatPortIIFOIF($remote_port_info);
            echo '<input type=hidden name="remote_port_type" value="' . $remote_port_info['oif_id'] . '">';
        } else {
            echo '<label>' . $remote_port_info['iif_name'] . ' ';
            printSelect(getExistingPortTypeOptions($remote_port_info), array('class' => 'porttype', 'name' => 'remote_port_type'), $type_remote);
            echo '</label>';
        }
        echo ' ' . formatPort($remote_port_info);
        echo '<p class="compat-hint" id="hint-not-compat">&#10005; Not compatible port types</p>';
        echo '<p class="compat-hint" id="hint-compat">&#10004; Compatible port types</p>';
        echo '<p><input type=submit name="do_link" value="Link">';
    }
}
Example #10
0
File: api.php Project: xtha/salt
     // TODO: raise exception if the IP doesn't exist
     unbindIPFromObject($ip_bin, $_REQUEST['object_id']);
     redirectUser($_SERVER['SCRIPT_NAME'] . '?method=get_object&object_id=' . $_REQUEST['object_id']);
     break;
     // add a port to an object
     //    UI equivalent: /index.php?page=
     //    UI handler: addPortForObject()
 // add a port to an object
 //    UI equivalent: /index.php?page=
 //    UI handler: addPortForObject()
 case 'add_port':
     require_once 'inc/init.php';
     assertUIntArg('object_id');
     assertStringArg('port_name', TRUE);
     genericAssertion('port_l2address', 'l2address0');
     genericAssertion('port_name', 'string');
     $new_port_id = commitAddPort($_REQUEST['object_id'], trim($_REQUEST['port_name']), $_REQUEST['port_type_id'], trim($_REQUEST['port_label']), trim($_REQUEST['port_l2address']));
     sendAPIResponse(array(), array('message' => 'port added successfully', 'port_id' => $new_port_id));
     break;
     // delete a port from an object
     //    UI equivalent: /index.php?page=
     //    UI handler: tableHandler()
 // delete a port from an object
 //    UI equivalent: /index.php?page=
 //    UI handler: tableHandler()
 case 'delete_port':
     require_once 'inc/init.php';
     assertUIntArg('object_id');
     assertUIntArg('port_id');
     // TODO: add confirmation that there is such a port
     usePreparedDeleteBlade('Port', array('id' => $_REQUEST['port_id'], 'object_id' => $_REQUEST['object_id']));
Example #11
0
function queryTerminal($object_id, $commands, $tolerate_remote_errors = TRUE)
{
    $objectInfo = spotEntity('object', $object_id);
    $endpoints = findAllEndpoints($object_id, $objectInfo['name']);
    if (count($endpoints) == 0) {
        throw new RTGatewayError('no management address set');
    }
    if (count($endpoints) > 1) {
        throw new RTGatewayError('cannot pick management address');
    }
    // telnet prompt and mode specification
    switch ($breed = detectDeviceBreed($object_id)) {
        case 'ios12':
        case 'fdry5':
        case 'ftos8':
            $protocol = 'netcat';
            // default is netcat mode
            $prompt = '^(Login|Username|Password): $|^\\S+[>#]$';
            // set the prompt in case user would like to specify telnet protocol
            break;
        case 'air12':
            $protocol = 'telnet';
            # Aironet IOS is broken
            $prompt = '^(Username|Password): $|^\\S+[>#]$';
            break;
        case 'vrp53':
        case 'vrp55':
            $protocol = 'telnet';
            $prompt = '^\\[[^[\\]]+\\]$|^<[^<>]+>$|^(Username|Password):$|(?:\\[Y\\/N\\]|\\(Y\\/N\\)\\[[YN]\\]):?$';
            break;
        case 'nxos4':
            $protocol = 'telnet';
            $prompt = '(^([Ll]ogin|[Pp]assword):|[>#]) $';
            break;
        case 'xos12':
            $protocol = 'telnet';
            $prompt = ': $|\\.\\d+ # $|\\?\\s*\\([Yy]\\/[Nn]\\)\\s*$';
            break;
        case 'jun10':
            $protocol = 'telnet';
            $prompt = '^login: $|^Password:$|^\\S+@\\S+[>#] $';
            break;
        case 'eos4':
            $protocol = 'telnet';
            # strict RFC854 implementation, netcat won't work
            $prompt = '^(\\xf2?login|Username|Password): $|^\\S+[>#]$';
            break;
        case 'ros11':
            $protocol = 'netcat';
            # see ftos8 case
            $prompt = '^(User Name|\\rPassword):$|^\\r?\\S+# $';
            break;
        case 'iosxr4':
            $protocol = 'telnet';
            $prompt = '^\\r?(Login|Username|Password): $|^\\r?\\S+[>#]$';
            break;
        case 'ucs':
            $protocol = 'ucssdk';
            break;
        default:
            $protocol = 'netcat';
            $prompt = NULL;
    }
    // set the default settings before calling user-defined callback
    $settings = array('hostname' => $endpoints[0], 'protocol' => $protocol, 'port' => NULL, 'prompt' => $prompt, 'username' => NULL, 'password' => NULL, 'timeout' => 15, 'connect_timeout' => 2, 'prompt_delay' => 0.001, 'sudo_user' => NULL, 'identity_file' => NULL);
    if (is_callable('terminal_settings')) {
        call_user_func('terminal_settings', $objectInfo, array(&$settings));
    }
    // override settings
    if (!isset($settings['port']) and $settings['protocol'] == 'netcat') {
        $settings['port'] = 23;
    }
    $params = array($settings['hostname']);
    $params_from_settings = array();
    switch ($settings['protocol']) {
        case 'telnet':
        case 'netcat':
            // prepend command list with vendor-specific disabling pager command
            switch ($breed) {
                case 'ios12':
                    $commands = "terminal length 0\n" . $commands;
                    break;
                case 'nxos4':
                case 'air12':
                case 'ftos8':
                    $commands = "terminal length 0\nterminal no monitor\n" . $commands;
                    break;
                case 'xos12':
                    $commands = "disable clipaging\n" . $commands;
                    break;
                case 'vrp55':
                    $commands = "screen-length 0 temporary\n" . $commands;
                    break;
                case 'fdry5':
                    $commands = "skip-page-display\n" . $commands;
                    break;
                case 'jun10':
                    $commands = "set cli screen-length 0\n" . $commands;
                    break;
                case 'eos4':
                    $commands = "enable\nno terminal monitor\nterminal length 0\n" . $commands;
                    break;
                case 'ros11':
                    $commands = "terminal datadump\n" . $commands;
                    $commands .= "\n\n";
                    # temporary workaround for telnet server
                    break;
                case 'iosxr4':
                    $commands = "terminal length 0\nterminal monitor disable\n" . $commands;
                    break;
                case 'dlink':
                    $commands = "disable clipaging\n" . $commands;
                    break;
            }
            // prepend telnet commands by credentials
            if (isset($settings['password'])) {
                $commands = $settings['password'] . "\n" . $commands;
            }
            if (isset($settings['username'])) {
                $commands = $settings['username'] . "\n" . $commands;
            }
            // command-line options are specific to client: telnet or netcat
            switch ($settings['protocol']) {
                case 'telnet':
                    $params_from_settings['port'] = 'port';
                    $params_from_settings['prompt'] = 'prompt';
                    $params_from_settings['connect-timeout'] = 'connect_timeout';
                    $params_from_settings['timeout'] = 'timeout';
                    $params_from_settings['prompt-delay'] = 'prompt_delay';
                    break;
                case 'netcat':
                    $params_from_settings['p'] = 'port';
                    $params_from_settings['w'] = 'timeout';
                    $params_from_settings['b'] = 'ncbin';
                    break;
            }
            break;
        case 'ssh':
            $params_from_settings['port'] = 'port';
            $params_from_settings['proto'] = 'proto';
            $params_from_settings['username'] = '******';
            $params_from_settings['i'] = 'identity_file';
            $params_from_settings['sudo-user'] = '******';
            $params_from_settings['connect-timeout'] = 'connect_timeout';
            break;
        case 'ucssdk':
            # remote XML through a Python backend
            $params = array();
            # reset
            # UCS in its current implementation besides the terminal_settings() provides
            # an additional username/password feed through the HTML from. Whenever the
            # user provides the credentials through the form, use these instead of the
            # credentials [supposedly] set by terminal_settings().
            if ($script_mode != TRUE && !isCheckSet('use_terminal_settings')) {
                genericAssertion('ucs_login', 'string');
                genericAssertion('ucs_password', 'string');
                $settings['username'] = $_REQUEST['ucs_login'];
                $settings['password'] = $_REQUEST['ucs_password'];
            }
            foreach (array('hostname', 'username', 'password') as $item) {
                if (empty($settings[$item])) {
                    throw new RTGatewayError("{$item} not available, check terminal_settings()");
                }
            }
            $commands = "login {$settings['hostname']} {$settings['username']} {$settings['password']}\n" . $commands;
            break;
        default:
            throw RTGatewayError("Invalid terminal protocol '{$settings['protocol']}' specified");
    }
    foreach ($params_from_settings as $param_name => $setting_name) {
        if (isset($settings[$setting_name])) {
            if (is_int($param_name)) {
                $params[] = $settings[$setting_name];
            } else {
                $params[$param_name] = $settings[$setting_name];
            }
        }
    }
    callHook('alterTerminalParams', $object_id, $tolerate_remote_errors, array(&$settings['protocol']), array(&$params));
    $ret_code = callScript($settings['protocol'], $params, $commands, $out, $errors);
    if ($settings['protocol'] != 'ssh' || !$tolerate_remote_errors) {
        if (!empty($errors)) {
            throw new RTGatewayError("{$settings['protocol']} error: " . rtrim($errors));
        } elseif ($ret_code !== 0) {
            throw new RTGatewayError("{$settings['protocol']} error: result code {$ret_code}");
        }
    } elseif (!empty($errors)) {
        // ssh and tolerate and non-empty $errors
        foreach (explode("\n", $errors) as $line) {
            if (strlen($line)) {
                showWarning("{$settings['protocol']} {$settings['hostname']}: {$line}");
            }
        }
    }
    return strtr($out, array("\r" => ""));
    // cut ^M symbols
}
Example #12
0
         echo "NAK\nPermission denied";
     } catch (Exception $e) {
         ob_clean();
         echo "NAK\nRuntime exception: " . $e->getMessage();
     }
     break;
 case 'redirect' == $_REQUEST['module']:
     // Include init after ophandlers/snmp, not before, so local.php can redefine things.
     require_once 'inc/ophandlers.php';
     // snmp.php is an exception, it is treated by a special hack
     if (isset($_REQUEST['op']) and $_REQUEST['op'] == 'querySNMPData') {
         require_once 'inc/snmp.php';
     }
     require_once 'inc/init.php';
     try {
         genericAssertion('op', 'string');
         $op = $_REQUEST['op'];
         prepareNavigation();
         $location = buildRedirectURL();
         // FIXME: find a better way to handle this error
         if ($op == 'addFile' && !isset($_FILES['file']['error'])) {
             throw new RackTablesError('File upload error, check upload_max_filesize in php.ini', RackTablesError::MISCONFIGURED);
         }
         fixContext();
         if (!isset($ophandler[$pageno][$tabno][$op]) or !is_callable($ophandler[$pageno][$tabno][$op])) {
             throw new RackTablesError("Invalid navigation data for '{$pageno}-{$tabno}-{$op}'", RackTablesError::INTERNAL);
         }
         // We have a chance to handle an error before starting HTTP header.
         if (!isset($delayauth["{$pageno}-{$tabno}-{$op}"])) {
             assertPermission();
         }
function handleNetworkAttrsChange()
{
    genericAssertion('num_attrs', 'uint0');
    global $dbxlink, $sic, $pageno;
    $network = spotEntity($pageno === 'ipv4net' ? 'ipv4net' : 'ipv6net', getBypassValue());
    $dbxlink->beginTransaction();
    // Update optional attributes
    $oldvalues = getAttrValuesForNetwork($network);
    for ($i = 0; $i < $_REQUEST['num_attrs']; $i++) {
        genericAssertion("{$i}_attr_id", 'uint');
        $attr_id = $_REQUEST["{$i}_attr_id"];
        if (!array_key_exists($attr_id, $oldvalues)) {
            throw new InvalidRequestArgException('attr_id', $attr_id, 'malformed request');
        }
        $value = $_REQUEST["{$i}_value"];
        if ('date' == $oldvalues[$attr_id]['type']) {
            assertDateArg("{$i}_value", TRUE);
            if ($value != '') {
                $value = strtotime($value);
            }
        }
        # Delete attribute and move on, when the field is empty or if the field
        # type is a dictionary and it is the "--NOT SET--" value of 0.
        if ($value == '' || $oldvalues[$attr_id]['type'] == 'dict' && $value == 0) {
            if (permitted(NULL, NULL, NULL, array(array('tag' => '$attr_' . $attr_id)))) {
                commitUpdateAttrForNetwork($network, $attr_id);
            } else {
                showError('Permission denied, "' . $oldvalues[$attr_id]['name'] . '" left unchanged');
            }
            continue;
        }
        // The value could be uint/float, but we don't know ATM. Let SQL
        // server check this and complain.
        assertStringArg("{$i}_value");
        switch ($oldvalues[$attr_id]['type']) {
            case 'uint':
            case 'float':
            case 'string':
            case 'date':
                $oldvalue = $oldvalues[$attr_id]['value'];
                break;
            case 'dict':
                $oldvalue = $oldvalues[$attr_id]['key'];
                break;
            default:
        }
        if ($value === $oldvalue) {
            // ('' == 0), but ('' !== 0)
            continue;
        }
        if (permitted(NULL, NULL, NULL, array(array('tag' => '$attr_' . $attr_id)))) {
            commitUpdateAttrForNetwork($network, $attr_id, $value);
        } else {
            showError('Permission denied, "' . $oldvalues[$attr_id]['name'] . '" left unchanged');
        }
    }
    $dbxlink->commit();
    return showSuccess("Attributes were updated successfully");
}
Example #14
0
function buildOpspecColumns($opspec, $listname)
{
    global $sic;
    $columns = array();
    if (!array_key_exists($listname, $opspec)) {
        throw new InvalidArgException('opspec', '(malformed structure)', "missing '{$listname}'");
    }
    foreach ($opspec[$listname] as $argspec) {
        switch (TRUE) {
            case array_key_exists('url_argname', $argspec):
                # HTTP input
                genericAssertion($argspec['url_argname'], $argspec['assertion']);
                // "table_colname" is normally used for an override, if it is not
                // set, use the URL argument name
                $table_colname = array_key_exists('table_colname', $argspec) ? $argspec['table_colname'] : $argspec['url_argname'];
                $arg_value = $sic[$argspec['url_argname']];
                if ($argspec['assertion'] == 'uint0' and $arg_value == 0 or $argspec['assertion'] == 'string0' and $arg_value == '') {
                    switch (TRUE) {
                        case !array_key_exists('if_empty', $argspec):
                            // no action requested
                            break;
                        case $argspec['if_empty'] == 'NULL':
                            $arg_value = NULL;
                            break;
                        default:
                            throw new InvalidArgException('opspec', '(malformed array structure)', '"if_empty" not recognized');
                    }
                }
                $columns[$table_colname] = $arg_value;
                break;
            case array_key_exists('fix_argname', $argspec):
                # fixed column
                if (!array_key_exists('fix_argvalue', $argspec)) {
                    throw new InvalidArgException('opspec', '(malformed structure)', 'missing "fix_argvalue"');
                }
                $columns[$argspec['fix_argname']] = $argspec['fix_argvalue'];
                break;
            default:
                throw new InvalidArgException('opspec', '(malformed structure)', 'unknown argument source');
        }
    }
    // switch (TRUE)
    return $columns;
}
Example #15
0
function getBypassValue()
{
    global $page, $pageno, $sic;
    if (!array_key_exists('bypass', $page[$pageno])) {
        return NULL;
    }
    if (!array_key_exists('bypass_type', $page[$pageno])) {
        throw new RackTablesError("Internal structure error at node '{$pageno}' (bypass_type is not set)", RackTablesError::INTERNAL);
    }
    genericAssertion($page[$pageno]['bypass'], $page[$pageno]['bypass_type']);
    return $sic[$page[$pageno]['bypass']];
}