123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500 |
- <?php
- //-
- // Copyright (c) 2011-2018 Joe Clarke <jclarke@cisco.com>
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions
- // are met:
- // 1. Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // 2. Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- // SUCH DAMAGE.
- include_once 'db.inc.php';
- include_once 'swreg/swreg.inc.php';
- require_once 'Log.php';
- require_once 'functions.php';
- $dsn = "$db_driver:host=$db_host;dbname=$db_name";
- $options = [
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
- PDO::ATTR_EMULATE_PREPARES => false,
- ];
- try {
- $dbh = new PDO($dsn, $db_user, $db_pass, $options);
- } catch (PDOException $e) {
- die($e->getMessage());
- }
- $logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Logical Switches');
- if ($logger === false) {
- die("Failed to open logfile.\n");
- }
- $mask = Log::UPTO(LOG_LEVEL);
- $logger->setMask($mask);
- $base = get_base($_SERVER['SCRIPT_NAME']);
- $ruser = '<AUTHENTICATION NOT ENABLED>';
- if (isset($_SERVER['REMOTE_USER'])) {
- $ruser = $_SERVER['REMOTE_USER'];
- }
- $errors = array();
- if (isset($_REQUEST['submit_top']) || isset($_REQUEST['submit_bottom'])) {
- $pia = $_REQUEST['prev_ip_address'];
- $ppid = $_REQUEST['prev_pid'];
- $ploc = $_REQUEST['prev_location'];
- $pidf = $_REQUEST['prev_is_idf'];
- $pexp = (isset($_REQUEST['prev_exception'])) ? $_REQUEST['prev_exception'] : array();
- $ia = $_REQUEST['address'];
- $pid = $_REQUEST['pid'];
- $loc = $_REQUEST['location'];
- $exp = $_REQUEST['exception'];
- $idf = (isset($_REQUEST['is_idf'])) ? $_REQUEST['is_idf'] : array();
- $d = (isset($_REQUEST['delete'])) ? $_REQUEST['delete'] : array();
- $made_change = false;
- foreach ($pia as $sname => $value) {
- $curr_del = (isset($d[$sname])) ? $d[$sname] : 0;
- if ($curr_del == 1) {
- if ($ia[$sname] !== null && $ia[$sname] != '') {
- $sql = 'UPDATE ADDRESSES SET used=? WHERE address=?';
- try {
- $sth = $dbh->prepare($sql);
- $sth->execute(array('0', $ia[$sname]));
- $sth->closeCursor();
- } catch (PDOException $e) {
- array_push($errors, "Failed to free IP address {$ia[$sname]}: {$e->getMessage()}");
- }
- }
- $sql = "DELETE FROM DEVICE_MAP WHERE assigned_switch='{$sname}'";
- try {
- $dbh->query($sql);
- } catch (PDOException $e) {
- array_push($errors, "Failed to delete {$sname}: {$e->getMessage()}");
- }
- $sql = "DELETE FROM SWITCHES WHERE name='{$sname}'";
- try {
- $dbh->query($sql);
- $logger->info("User {$ruser} deleted logical switch {$sname}");
- } catch (PDOException $e) {
- array_push($errors, "Failed to delete {$sname}: {$e->getMessage()}");
- }
- if (count($errors) == 0) {
- $made_change = true;
- @unlink(PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
- }
- continue;
- }
- $curr_idf = (isset($idf[$sname])) ? $idf[$sname] : 0;
- if (!isset($ppid[$sname]) || $ppid[$sname] == '') {
- $ppid[$sname] = '__BOGUS__';
- }
- if (!isset($pexp[$sname]) || $pexp[$sname] == '') {
- $pexp[$sname] = '__BOGUS__';
- }
- if ($value != $ia[$sname] || $ploc[$sname] != $loc[$sname] || $ppid[$sname] != $pid[$sname] || $pidf[$sname] != $curr_idf) {
- if ($pid[$sname] == '__BOGUS__') {
- array_push($errors, "You must select a Product ID for {$sname}");
- }
- $sql = "SELECT address, reserved FROM ADDRESSES WHERE address='{$ia[$sname]}'";
- $res = null;
- try {
- $res = $dbh->query($sql);
- } catch (PDOException $e) {
- }
- $row = $res->fetch();
- $newa = "'{$ia[$sname]}'";
- if ($ia[$sname] != '' && !$row['address']) {
- array_push($errors, "IP address {$ia[$sname]} is not valid for switch {$sname}");
- } elseif ((ADDRESS_SCHEME == 'IDF' && $row['reserved'] == 1 && $curr_idf != 1) || (ADDRESS_SCHEME != 'IDF' && ADDRESS_SCHEME != 'DNS' && $row['reserved'] == 1)) {
- array_push($errors, "IP address {$ia[$sname]} is reserved and cannot be used for this switch");
- } elseif ($ia[$sname] == '') {
- $newa = 'NULL';
- }
- if (count($errors) == 0) {
- $sql = "UPDATE SWITCHES SET ip_address = $newa, location = '{$loc[$sname]}', pid = '{$pid[$sname]}', is_idf = '{$curr_idf}' WHERE name='{$sname}'";
- try {
- $res = $dbh->query($sql);
- $logger->info("User {$ruser} updated logical switches: location={$loc[$sname]}, pid={$pid[$sname]}, is_idf={$curr_idf} for switch {$sname}");
- if ($ia[$sname] != '') {
- $sql = 'UPDATE ADDRESSES SET used=? WHERE address=?';
- try {
- $sth = $dbh->prepare($sql);
- $sth->execute(array('0', $ia[$sname]));
- $sth->closeCursor();
- $logger->info("User {$ruser} released address {$ia[$sname]}");
- } catch (PDOException $ie) {
- array_push($errors, "Failed to update address usage for $sname: '{$ie->getMessage()}'");
- }
- }
- if ($newa != 'NULL') {
- $sql = 'UPDATE ADDRESSES SET used=? WHERE address=?';
- try {
- $sth = $dbh->prepare($sql);
- $sth->execute(array('1', $newa));
- $sth->closeCursor();
- $logger->info("User {$ruser} allocated address {$newa} for {$sname}");
- } catch (PDOException $ie) {
- array_push($errors, "Failed to update address usage for $sname: '{$ie->getMessage()}'");
- }
- }
- } catch (PDOException $e) {
- array_push($errors, "Failed to update $sname: '{$e->getMessage()}'");
- }
- }
- }
- if (count($errors) == 0) {
- $made_change = true;
- if ($pexp[$sname] != $exp[$sname]) {
- if ($exp[$sname] != '__BOGUS__') {
- @symlink(PORT_PROFILE_DIR.'/'.$exp[$sname], PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
- } else {
- @unlink(PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
- }
- }
- }
- }
- if ($made_change) {
- $now = time();
- $sql = 'UPDATE SYS_PROPERTIES SET value=? WHERE name=?';
- try {
- $sth = $dbh->prepare($sql);
- $sth->execute([$now, 'last_logic_update']);
- $sth->closeCursor();
- $logger->info("User {$ruser} updated the last logic date");
- } catch (PDOException $e) {
- array_push($errors, "Failed to update the last logic update date: '{$e->getMessage()}'");
- }
- }
- }
- $wc = '';
- if (isset($_REQUEST['filter'])) {
- switch ($_REQUEST['filter']) {
- case 'a':
- $wc = '';
- break;
- case 'u':
- $wc = ' WHERE ip_address IS NULL';
- break;
- default:
- if (preg_match("/^pid:([\w\d-]+)/", $_REQUEST['filter'], $match)) {
- if (array_search($match[1], $ZTP_PIDS) === false) {
- $wc = '';
- } else {
- $wc = " WHERE pid = '{$match[1]}'";
- }
- } elseif (preg_match("/^mdf:([\w\d-_]+)/", $_REQUEST['filter'], $match)) {
- if (array_search($match[1], $MDFS) === false) {
- $wc = '';
- } else {
- $wc = ", ADDRESSES WHERE SWITCHES.ip_address = ADDRESSES.address AND ADDRESSES.location = '{$match[1]}'";
- }
- } else {
- $wc = '';
- }
- break;
- }
- }
- $res = null;
- if (isset($_REQUEST['switch_name'])) {
- $sql = 'SELECT * FROM SWITCHES WHERE name LIKE :swname1 OR ip_address LIKE :swname2 ORDER BY name';
- try {
- $res = $dbh->prepare($sql);
- $res->execute(['swname1' => "%{$_REQUEST['switch_name']}%", 'swname2' => "%{$_REQUEST['switch_name']}%"]);
- } catch (PDOException $e) {
- echo "<p><font color=\"red\">Error querying for logical switches: {$e->getMessage()}</font></p>\r\n";
- exit(1);
- }
- } else {
- $sql = 'SELECT SWITCHES.* FROM SWITCHES '.$wc.' ORDER BY name';
- try {
- $res = $dbh->query($sql);
- } catch (PDOException $e) {
- echo "<p><font color=\"red\">Error querying for logical switches: {$e->getMessage()}</font></p>\r\n";
- exit(1);
- }
- }
- $switches = array();
- while ($row = $res->fetch()) {
- array_push($switches, $row);
- }
- $sql = 'SELECT ip_address FROM SWITCHES WHERE ip_address IS NOT NULL';
- try {
- $res = $dbh->query($sql);
- } catch (PDOException $e) {
- echo "<p><font color=\"red\">Error querying for used IP addresses: {$e->getMessage()}</font></p>\r\n";
- exit(1);
- }
- $used = array();
- while ($row = $res->fetch()) {
- $used[$row['ip_address']] = true;
- }
- $sql = 'SELECT * FROM EXCEPTIONS';
- try {
- $res = $dbh->query($sql);
- } catch (PDOException $e) {
- echo "<p><font color=\"red\">Error querying for exceptions: {$e->getMessage()}</font></p>\r\n";
- exit(1);
- }
- $exceptions = array();
- while ($row = $res->fetch()) {
- $exceptions[$row['name']] = array($row['pid'], $row['path']);
- }
- $filter = '';
- if (isset($_REQUEST['filter'])) {
- $filter = $_REQUEST['filter'];
- }
- print_header(TOOL_NAME.': Logical Switches');
- ?>
- <body class="flex">
- <script language="javascript">
- var deletes = 0;
- var prop_list = ['location', 'ip_address', 'is_idf', 'pid', 'exception'];
- function refresh() {
- $.ajax({
- url: '<?=$base?>/get_logicsw_details.php',
- dataType: 'json',
- success: function(data) {
- $.each(data.response, function(k, v) {
- $.each(prop_list, function(pi, p) {
- if (v[p] != $('#prev_' + p + '_' + k).val()) {
- if ($('#' + p + '_' + k).val() != $('#prev_' + p + '_' + k).val()) {
- $('#' + p + '_' + k).css({
- 'border-style': 'solid',
- 'border-color': 'red'
- });
- $('input').prop('disabled', true);
- $('select').prop('disabled', true);
- $('#err_div').html('<p class="error">Conflicting change detected; reload page to continue.</p>');
- return;
- } else {
- $('#prev_' + p + '_' + k).val(v[p]);
- if ($('#' + p + '_' + k).attr('type') == 'checkbox') {
- $('#' + p + '_' + k).prop('checked', (v[p] == 1));
- } else if ($('#' + p + '_' + k).attr('type') == 'select' && v[p] == '') {
- $('#' + p + '_' + k).val('__BOGUS__');
- } else {
- $('#' + p + '_' + k).val(v[p]);
- }
- }
- }
- });
- });
- },
- complete: function(xhr, message) {
- setTimeout(refresh, 5000);
- }
- });
- }
- if ( window.history.replaceState ) {
- window.history.replaceState( null, null, window.location.href );
- }
- $(document).ready(function() {
- $('#devtable').DataTable({
- "scrollY": "400px",
- "scrollCollapse": true,
- "paging": false
- });
- refresh();
- });
- </script>
- <div id="headswreg">
- <div class="apage">
- <div id="header">
- <h1><?=TOOL_NAME?>: Logical Switches</h1>
- </div>
- <br/>
- </div>
- </div>
- <div class="apage">
- <form method="POST" name="search_form" action="<?=$_SERVER['PHP_SELF']?>">
- <table class="noborder" summary="Filter Table">
- <tr>
- <td class="left_act">Show Only Switches In:
- <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
- <option value="<?=$_SERVER['PHP_SELF']?>?filter=a" <?=($filter == 'a') ? 'selected' : ''?>>All</option>
- <?php
- foreach ($MDFS as $m) {
- ?>
- <option value="<?=$_SERVER['PHP_SELF']?>?filter=<?=$m?>" <?=($filter == $m) ? 'selected' : ''?>><?=$m?></option>
- <?php
- }
- ?>
- <option value="<?=$_SERVER['PHP_SELF']?>?filter=u" <?=($filter == 'u') ? 'selected' : ''?>>No IP Assigned</option>
- <?php
- foreach ($ZTP_PIDS as $spid) {
- $selected = ($filter == "pid:$spid") ? 'selected' : ''; ?>
- <option value="<?=$_SERVER['PHP_SELF']?>?filter=pid:<?=$spid?>" <?=$selected?>><?=$spid?></option>
- <?php
- }
- ?>
- </select></td>
- <td class="right">Switch Search:
- <input type="text" size="16" name="switch_name" value="<?=(isset($_REQUEST['switch_name'])) ? $_REQUEST['switch_name'] : ''?>">
- <input type="image" value="Submit" name="search" src="/images/submit_button.png">
- </td>
- </tr>
- </table>
- </form>
- <br/>
- <table class="noborder" summary="Control Table">
- <tr>
- <td class="left"><a href="<?=$base?>/add_logic.php">Add Logical Switch</a> |
- <a href="<?=$base?>/index.php">Physical Switches</a> |
- <a href="<?=$base?>/port_profiles.php">Port Profiles</a></td>
- </tr>
- </table>
- <form name="mod_logic_switch_form" method="POST" action="<?=$_SERVER['PHP_SELF']?>" onSubmit='if (deletes > 0) { return confirm("Are you sure you want to delete these " + deletes + " logical switch(es)?"); }'>
- <?php
- foreach (array_merge($_GET, $_POST) as $name => $value) {
- if (!is_array($value)) {
- ?>
- <input type="hidden" name="<?=$name?>" value="<?=$value?>">
- <?php
- }
- }
- ?>
- <div class="fbtable">
- <table summary="Button Table" width="100%" cellspacing="0">
- <tr>
- <td><input type="reset" value="Reset" name="reset">
- <input type="submit" value="Submit" id="submit_top" name="submit_top"></td>
- </tr>
- </table>
- </div>
- <br/>
- <div id="err_div" align="center">
- <?php
- foreach ($errors as $error) {
- ?>
- <p class="error"><?=$error?></p>
- <?php
- }
- ?>
- </div>
- <div class="fulltable">
- <table id="devtable" class="display compact" width="100%" cellspacing="0" summary="Logical Switch Table">
- <thead>
- <tr>
- <th class="headlink">Row No.</th>
- <th class="headlink">Delete?</th>
- <th class="headlink">Name</th>
- <th class="headlink">Is IDF?</th>
- <th class="headlink">IP Address</th>
- <th class="headlink">Product ID</th>
- <th class="headlink">SNMP Location</th>
- <!--<th class="headlink">Ports Required</th>-->
- <th class="headlink">Port Profile</th>
- </tr>
- </thead>
- <tbody>
- <?php
- $i = 0;
- foreach ($switches as $row) {
- $name = $row['name']; ?>
- <tr>
- <td><?=$i + 1?>.</td>
- <td><input type="checkbox" name="delete[<?=$name?>]" value="1" onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
- <td><?=$name?></td>
- <td><input type="hidden" id="prev_is_idf_<?=$name?>" name="prev_is_idf[<?=$name?>]" value="<?=$row['is_idf']?>">
- <input type="checkbox" id="is_idf_<?=$name?>" name="is_idf[<?=$name?>]" value="1" <?=($row['is_idf'] == 1) ? 'checked' : ''?>></td>
- <td><input type="hidden" id="prev_ip_address_<?=$name?>" name="prev_ip_address[<?=$name?>]" value="<?=$row['ip_address']?>">
- <input type="text" id="ip_address_<?=$name?>" name="address[<?=$name?>]" size="16" value="<?=$row['ip_address']?>"></td>
- <td><input type="hidden" id="prev_pid_<?=$name?>" name="prev_pid[<?=$name?>]" value="<?=$row['pid']?>">
- <select id="pid_<?=$name?>" name="pid[<?=$name?>]">
- <?php
- $pidarr = array_merge($ZTP_PIDS, array('__BOGUS__'));
- foreach ($ZTP_PIDS as $p) {
- $selected = ($row['pid'] == $p) ? 'selected' : '';
- if ($p == '__BOGUS__') {
- ?>
- <option value="__BOGUS__" <?=$selected?>>--Please Select--</option>
- <?php
- } else {
- ?>
- <option value="<?=$p?>" <?=$selected?>><?=$p?></option>
- <?php
- }
- } ?>
- </select></td>
- <td><input type="hidden" id="prev_location_<?=$name?>" name="prev_location[<?=$name?>]" value="<?=$row['location']?>">
- <input id="location_<?=$name?>" type="text" name="location[<?=$name?>]" size="32" value="<?=$row['location']?>"></td>
- <!--<td><?=$row['ports_required']?></td>-->
- <?php
- $tbase = '';
- if (file_exists(PORT_TMPL_DIR.'/devices/'."{$name}-ports.tmpl")) {
- $targ = readlink(PORT_TMPL_DIR.'/devices/'."{$name}-ports.tmpl");
- $tbase = basename($targ);
- } ?>
- <td><input type="hidden" id="prev_exception_<?=$name?>" name="prev_exception_<?=$name?>" value="<?=$tbase?>">
- <select id="exception_<?=$name?>" name="exception[<?=$name?>]">
- <option value="__BOGUS__">--Please Select--</option>
- <?php
- foreach ($exceptions as $exname => $exarr) {
- $path = $exarr[1];
- $expid = $exarr[0];
- $selected = '';
- if ($path == $tbase) {
- $selected = 'selected';
- }
- if ($selected == '' && $expid != $row['pid'] && $expid != '__ANY__') {
- continue;
- } ?>
- <option value="<?=$path?>" <?=$selected?>><?=$exname?></option>
- <?php
- } ?>
- </select> <a href="#" onClick='var pp = document.getElementById("exception_<?=$name?>"); if (pp.value == "__BOGUS__") { alert("There is no port profile associated to this logical switch."); return false; } else { window.open("<?=$base?>/show_config.php?type=profile&cfg=" + pp.value + "&dname=<?=$name?>", "Config for profile " + pp.value, "height=650,width=980"); return false; }'><img src="/images/mag.gif" border="0" title="View port profile"></td>
- </tr>
- <?php
- ++$i;
- }
- ?>
- </tbody>
- </table>
- </div>
- <br/>
- <div class="fbtable">
- <table summary="Button Table" width="100%" cellspacing="0">
- <tr>
- <td><input type="reset" value="Reset" name="reset">
- <input id="submit_bottom" type="submit" value="Submit" name="submit_bottom"></td>
- </tr>
- </table>
- </div>
- </form>
- </div>
- </body>
- </html>
- <?php
- cleanup();
- ?>
|