logicsw.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. <?php
  2. //-
  3. // Copyright (c) 2011-2018 Joe Clarke <jclarke@cisco.com>
  4. // All rights reserved.
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions
  7. // are met:
  8. // 1. Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // 2. Redistributions in binary form must reproduce the above copyright
  11. // notice, this list of conditions and the following disclaimer in the
  12. // documentation and/or other materials provided with the distribution.
  13. // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  14. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  17. // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  19. // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  20. // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23. // SUCH DAMAGE.
  24. include_once 'db.inc.php';
  25. include_once 'swreg/swreg.inc.php';
  26. require_once 'Log.php';
  27. require_once 'functions.php';
  28. $dsn = "$db_driver:host=$db_host;dbname=$db_name";
  29. $options = [
  30. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  31. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  32. PDO::ATTR_EMULATE_PREPARES => false,
  33. ];
  34. try {
  35. $dbh = new PDO($dsn, $db_user, $db_pass, $options);
  36. } catch (PDOException $e) {
  37. die($e->getMessage());
  38. }
  39. $logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Logical Switches');
  40. if ($logger === false) {
  41. die("Failed to open logfile.\n");
  42. }
  43. $mask = Log::UPTO(LOG_LEVEL);
  44. $logger->setMask($mask);
  45. $base = get_base($_SERVER['SCRIPT_NAME']);
  46. $ruser = '<AUTHENTICATION NOT ENABLED>';
  47. if (isset($_SERVER['REMOTE_USER'])) {
  48. $ruser = $_SERVER['REMOTE_USER'];
  49. }
  50. $errors = array();
  51. if (isset($_REQUEST['submit_top']) || isset($_REQUEST['submit_bottom'])) {
  52. $pia = $_REQUEST['prev_ip_address'];
  53. $ppid = $_REQUEST['prev_pid'];
  54. $ploc = $_REQUEST['prev_location'];
  55. $pidf = $_REQUEST['prev_is_idf'];
  56. $pexp = (isset($_REQUEST['prev_exception'])) ? $_REQUEST['prev_exception'] : array();
  57. $ia = $_REQUEST['address'];
  58. $pid = $_REQUEST['pid'];
  59. $loc = $_REQUEST['location'];
  60. $exp = $_REQUEST['exception'];
  61. $idf = (isset($_REQUEST['is_idf'])) ? $_REQUEST['is_idf'] : array();
  62. $d = (isset($_REQUEST['delete'])) ? $_REQUEST['delete'] : array();
  63. $made_change = false;
  64. foreach ($pia as $sname => $value) {
  65. $curr_del = (isset($d[$sname])) ? $d[$sname] : 0;
  66. if ($curr_del == 1) {
  67. if ($ia[$sname] !== null && $ia[$sname] != '') {
  68. $sql = 'UPDATE ADDRESSES SET used=? WHERE address=?';
  69. try {
  70. $sth = $dbh->prepare($sql);
  71. $sth->execute(array('0', $ia[$sname]));
  72. $sth->closeCursor();
  73. } catch (PDOException $e) {
  74. array_push($errors, "Failed to free IP address {$ia[$sname]}: {$e->getMessage()}");
  75. }
  76. }
  77. $sql = "DELETE FROM DEVICE_MAP WHERE assigned_switch='{$sname}'";
  78. try {
  79. $dbh->query($sql);
  80. } catch (PDOException $e) {
  81. array_push($errors, "Failed to delete {$sname}: {$e->getMessage()}");
  82. }
  83. $sql = "DELETE FROM SWITCHES WHERE name='{$sname}'";
  84. try {
  85. $dbh->query($sql);
  86. $logger->info("User {$ruser} deleted logical switch {$sname}");
  87. } catch (PDOException $e) {
  88. array_push($errors, "Failed to delete {$sname}: {$e->getMessage()}");
  89. }
  90. if (count($errors) == 0) {
  91. $made_change = true;
  92. @unlink(PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
  93. }
  94. continue;
  95. }
  96. $curr_idf = (isset($idf[$sname])) ? $idf[$sname] : 0;
  97. if (!isset($ppid[$sname]) || $ppid[$sname] == '') {
  98. $ppid[$sname] = '__BOGUS__';
  99. }
  100. if (!isset($pexp[$sname]) || $pexp[$sname] == '') {
  101. $pexp[$sname] = '__BOGUS__';
  102. }
  103. if ($value != $ia[$sname] || $ploc[$sname] != $loc[$sname] || $ppid[$sname] != $pid[$sname] || $pidf[$sname] != $curr_idf) {
  104. if ($pid[$sname] == '__BOGUS__') {
  105. array_push($errors, "You must select a Product ID for {$sname}");
  106. }
  107. $sql = "SELECT address, reserved FROM ADDRESSES WHERE address='{$ia[$sname]}'";
  108. $res = null;
  109. try {
  110. $res = $dbh->query($sql);
  111. } catch (PDOException $e) {
  112. }
  113. $row = $res->fetch();
  114. $newa = "'{$ia[$sname]}'";
  115. if ($ia[$sname] != '' && !$row['address']) {
  116. array_push($errors, "IP address {$ia[$sname]} is not valid for switch {$sname}");
  117. } elseif ((ADDRESS_SCHEME == 'IDF' && $row['reserved'] == 1 && $curr_idf != 1) || (ADDRESS_SCHEME != 'IDF' && ADDRESS_SCHEME != 'DNS' && $row['reserved'] == 1)) {
  118. array_push($errors, "IP address {$ia[$sname]} is reserved and cannot be used for this switch");
  119. } elseif ($ia[$sname] == '') {
  120. $newa = 'NULL';
  121. }
  122. if (count($errors) == 0) {
  123. $sql = "UPDATE SWITCHES SET ip_address = $newa, location = '{$loc[$sname]}', pid = '{$pid[$sname]}', is_idf = '{$curr_idf}' WHERE name='{$sname}'";
  124. try {
  125. $res = $dbh->query($sql);
  126. $logger->info("User {$ruser} updated logical switches: location={$loc[$sname]}, pid={$pid[$sname]}, is_idf={$curr_idf} for switch {$sname}");
  127. if ($ia[$sname] != '') {
  128. $sql = 'UPDATE ADDRESSES SET used=? WHERE address=?';
  129. try {
  130. $sth = $dbh->prepare($sql);
  131. $sth->execute(array('0', $ia[$sname]));
  132. $sth->closeCursor();
  133. $logger->info("User {$ruser} released address {$ia[$sname]}");
  134. } catch (PDOException $ie) {
  135. array_push($errors, "Failed to update address usage for $sname: '{$ie->getMessage()}'");
  136. }
  137. }
  138. if ($newa != 'NULL') {
  139. $sql = 'UPDATE ADDRESSES SET used=? WHERE address=?';
  140. try {
  141. $sth = $dbh->prepare($sql);
  142. $sth->execute(array('1', $newa));
  143. $sth->closeCursor();
  144. $logger->info("User {$ruser} allocated address {$newa} for {$sname}");
  145. } catch (PDOException $ie) {
  146. array_push($errors, "Failed to update address usage for $sname: '{$ie->getMessage()}'");
  147. }
  148. }
  149. } catch (PDOException $e) {
  150. array_push($errors, "Failed to update $sname: '{$e->getMessage()}'");
  151. }
  152. }
  153. }
  154. if (count($errors) == 0) {
  155. $made_change = true;
  156. if ($pexp[$sname] != $exp[$sname]) {
  157. if ($exp[$sname] != '__BOGUS__') {
  158. @symlink(PORT_PROFILE_DIR.'/'.$exp[$sname], PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
  159. } else {
  160. @unlink(PORT_TMPL_DIR.'/devices/'."{$sname}-ports.tmpl");
  161. }
  162. }
  163. }
  164. }
  165. if ($made_change) {
  166. $now = time();
  167. $sql = 'UPDATE SYS_PROPERTIES SET value=? WHERE name=?';
  168. try {
  169. $sth = $dbh->prepare($sql);
  170. $sth->execute([$now, 'last_logic_update']);
  171. $sth->closeCursor();
  172. $logger->info("User {$ruser} updated the last logic date");
  173. } catch (PDOException $e) {
  174. array_push($errors, "Failed to update the last logic update date: '{$e->getMessage()}'");
  175. }
  176. }
  177. }
  178. $wc = '';
  179. if (isset($_REQUEST['filter'])) {
  180. switch ($_REQUEST['filter']) {
  181. case 'a':
  182. $wc = '';
  183. break;
  184. case 'u':
  185. $wc = ' WHERE ip_address IS NULL';
  186. break;
  187. default:
  188. if (preg_match("/^pid:([\w\d-]+)/", $_REQUEST['filter'], $match)) {
  189. if (array_search($match[1], $ZTP_PIDS) === false) {
  190. $wc = '';
  191. } else {
  192. $wc = " WHERE pid = '{$match[1]}'";
  193. }
  194. } elseif (preg_match("/^mdf:([\w\d-_]+)/", $_REQUEST['filter'], $match)) {
  195. if (array_search($match[1], $MDFS) === false) {
  196. $wc = '';
  197. } else {
  198. $wc = ", ADDRESSES WHERE SWITCHES.ip_address = ADDRESSES.address AND ADDRESSES.location = '{$match[1]}'";
  199. }
  200. } else {
  201. $wc = '';
  202. }
  203. break;
  204. }
  205. }
  206. $res = null;
  207. if (isset($_REQUEST['switch_name'])) {
  208. $sql = 'SELECT * FROM SWITCHES WHERE name LIKE :swname1 OR ip_address LIKE :swname2 ORDER BY name';
  209. try {
  210. $res = $dbh->prepare($sql);
  211. $res->execute(['swname1' => "%{$_REQUEST['switch_name']}%", 'swname2' => "%{$_REQUEST['switch_name']}%"]);
  212. } catch (PDOException $e) {
  213. echo "<p><font color=\"red\">Error querying for logical switches: {$e->getMessage()}</font></p>\r\n";
  214. exit(1);
  215. }
  216. } else {
  217. $sql = 'SELECT SWITCHES.* FROM SWITCHES '.$wc.' ORDER BY name';
  218. try {
  219. $res = $dbh->query($sql);
  220. } catch (PDOException $e) {
  221. echo "<p><font color=\"red\">Error querying for logical switches: {$e->getMessage()}</font></p>\r\n";
  222. exit(1);
  223. }
  224. }
  225. $switches = array();
  226. while ($row = $res->fetch()) {
  227. array_push($switches, $row);
  228. }
  229. $sql = 'SELECT ip_address FROM SWITCHES WHERE ip_address IS NOT NULL';
  230. try {
  231. $res = $dbh->query($sql);
  232. } catch (PDOException $e) {
  233. echo "<p><font color=\"red\">Error querying for used IP addresses: {$e->getMessage()}</font></p>\r\n";
  234. exit(1);
  235. }
  236. $used = array();
  237. while ($row = $res->fetch()) {
  238. $used[$row['ip_address']] = true;
  239. }
  240. $sql = 'SELECT * FROM EXCEPTIONS';
  241. try {
  242. $res = $dbh->query($sql);
  243. } catch (PDOException $e) {
  244. echo "<p><font color=\"red\">Error querying for exceptions: {$e->getMessage()}</font></p>\r\n";
  245. exit(1);
  246. }
  247. $exceptions = array();
  248. while ($row = $res->fetch()) {
  249. $exceptions[$row['name']] = array($row['pid'], $row['path']);
  250. }
  251. $filter = '';
  252. if (isset($_REQUEST['filter'])) {
  253. $filter = $_REQUEST['filter'];
  254. }
  255. print_header(TOOL_NAME.': Logical Switches');
  256. ?>
  257. <body class="flex">
  258. <script language="javascript">
  259. var deletes = 0;
  260. var prop_list = ['location', 'ip_address', 'is_idf', 'pid', 'exception'];
  261. function refresh() {
  262. $.ajax({
  263. url: '<?=$base?>/get_logicsw_details.php',
  264. dataType: 'json',
  265. success: function(data) {
  266. $.each(data.response, function(k, v) {
  267. $.each(prop_list, function(pi, p) {
  268. if (v[p] != $('#prev_' + p + '_' + k).val()) {
  269. if ($('#' + p + '_' + k).val() != $('#prev_' + p + '_' + k).val()) {
  270. $('#' + p + '_' + k).css({
  271. 'border-style': 'solid',
  272. 'border-color': 'red'
  273. });
  274. $('input').prop('disabled', true);
  275. $('select').prop('disabled', true);
  276. $('#err_div').html('<p class="error">Conflicting change detected; reload page to continue.</p>');
  277. return;
  278. } else {
  279. $('#prev_' + p + '_' + k).val(v[p]);
  280. if ($('#' + p + '_' + k).attr('type') == 'checkbox') {
  281. $('#' + p + '_' + k).prop('checked', (v[p] == 1));
  282. } else if ($('#' + p + '_' + k).attr('type') == 'select' && v[p] == '') {
  283. $('#' + p + '_' + k).val('__BOGUS__');
  284. } else {
  285. $('#' + p + '_' + k).val(v[p]);
  286. }
  287. }
  288. }
  289. });
  290. });
  291. },
  292. complete: function(xhr, message) {
  293. setTimeout(refresh, 5000);
  294. }
  295. });
  296. }
  297. if ( window.history.replaceState ) {
  298. window.history.replaceState( null, null, window.location.href );
  299. }
  300. $(document).ready(function() {
  301. $('#devtable').DataTable({
  302. "scrollY": "400px",
  303. "scrollCollapse": true,
  304. "paging": false
  305. });
  306. refresh();
  307. });
  308. </script>
  309. <div id="headswreg">
  310. <div class="apage">
  311. <div id="header">
  312. <h1><?=TOOL_NAME?>: Logical Switches</h1>
  313. </div>
  314. <br/>
  315. </div>
  316. </div>
  317. <div class="apage">
  318. <form method="POST" name="search_form" action="<?=$_SERVER['PHP_SELF']?>">
  319. <table class="noborder" summary="Filter Table">
  320. <tr>
  321. <td class="left_act">Show Only Switches In:
  322. <select name="filter" onChange="MM_jumpMenu('parent', this, 0)">
  323. <option value="<?=$_SERVER['PHP_SELF']?>?filter=a" <?=($filter == 'a') ? 'selected' : ''?>>All</option>
  324. <?php
  325. foreach ($MDFS as $m) {
  326. ?>
  327. <option value="<?=$_SERVER['PHP_SELF']?>?filter=<?=$m?>" <?=($filter == $m) ? 'selected' : ''?>><?=$m?></option>
  328. <?php
  329. }
  330. ?>
  331. <option value="<?=$_SERVER['PHP_SELF']?>?filter=u" <?=($filter == 'u') ? 'selected' : ''?>>No IP Assigned</option>
  332. <?php
  333. foreach ($ZTP_PIDS as $spid) {
  334. $selected = ($filter == "pid:$spid") ? 'selected' : ''; ?>
  335. <option value="<?=$_SERVER['PHP_SELF']?>?filter=pid:<?=$spid?>" <?=$selected?>><?=$spid?></option>
  336. <?php
  337. }
  338. ?>
  339. </select></td>
  340. <td class="right">Switch Search:
  341. <input type="text" size="16" name="switch_name" value="<?=(isset($_REQUEST['switch_name'])) ? $_REQUEST['switch_name'] : ''?>">
  342. <input type="image" value="Submit" name="search" src="/images/submit_button.png">
  343. </td>
  344. </tr>
  345. </table>
  346. </form>
  347. <br/>
  348. <table class="noborder" summary="Control Table">
  349. <tr>
  350. <td class="left"><a href="<?=$base?>/add_logic.php">Add Logical Switch</a> |
  351. <a href="<?=$base?>/index.php">Physical Switches</a> |
  352. <a href="<?=$base?>/port_profiles.php">Port Profiles</a></td>
  353. </tr>
  354. </table>
  355. <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)?"); }'>
  356. <?php
  357. foreach (array_merge($_GET, $_POST) as $name => $value) {
  358. if (!is_array($value)) {
  359. ?>
  360. <input type="hidden" name="<?=$name?>" value="<?=$value?>">
  361. <?php
  362. }
  363. }
  364. ?>
  365. <div class="fbtable">
  366. <table summary="Button Table" width="100%" cellspacing="0">
  367. <tr>
  368. <td><input type="reset" value="Reset" name="reset">
  369. <input type="submit" value="Submit" id="submit_top" name="submit_top"></td>
  370. </tr>
  371. </table>
  372. </div>
  373. <br/>
  374. <div id="err_div" align="center">
  375. <?php
  376. foreach ($errors as $error) {
  377. ?>
  378. <p class="error"><?=$error?></p>
  379. <?php
  380. }
  381. ?>
  382. </div>
  383. <div class="fulltable">
  384. <table id="devtable" class="display compact" width="100%" cellspacing="0" summary="Logical Switch Table">
  385. <thead>
  386. <tr>
  387. <th class="headlink">Row No.</th>
  388. <th class="headlink">Delete?</th>
  389. <th class="headlink">Name</th>
  390. <th class="headlink">Is IDF?</th>
  391. <th class="headlink">IP Address</th>
  392. <th class="headlink">Product ID</th>
  393. <th class="headlink">SNMP Location</th>
  394. <!--<th class="headlink">Ports Required</th>-->
  395. <th class="headlink">Port Profile</th>
  396. </tr>
  397. </thead>
  398. <tbody>
  399. <?php
  400. $i = 0;
  401. foreach ($switches as $row) {
  402. $name = $row['name']; ?>
  403. <tr>
  404. <td><?=$i + 1?>.</td>
  405. <td><input type="checkbox" name="delete[<?=$name?>]" value="1" onClick="if (this.checked == true) { deletes++; } else { deletes--; }"></td>
  406. <td><?=$name?></td>
  407. <td><input type="hidden" id="prev_is_idf_<?=$name?>" name="prev_is_idf[<?=$name?>]" value="<?=$row['is_idf']?>">
  408. <input type="checkbox" id="is_idf_<?=$name?>" name="is_idf[<?=$name?>]" value="1" <?=($row['is_idf'] == 1) ? 'checked' : ''?>></td>
  409. <td><input type="hidden" id="prev_ip_address_<?=$name?>" name="prev_ip_address[<?=$name?>]" value="<?=$row['ip_address']?>">
  410. <input type="text" id="ip_address_<?=$name?>" name="address[<?=$name?>]" size="16" value="<?=$row['ip_address']?>"></td>
  411. <td><input type="hidden" id="prev_pid_<?=$name?>" name="prev_pid[<?=$name?>]" value="<?=$row['pid']?>">
  412. <select id="pid_<?=$name?>" name="pid[<?=$name?>]">
  413. <?php
  414. $pidarr = array_merge($ZTP_PIDS, array('__BOGUS__'));
  415. foreach ($ZTP_PIDS as $p) {
  416. $selected = ($row['pid'] == $p) ? 'selected' : '';
  417. if ($p == '__BOGUS__') {
  418. ?>
  419. <option value="__BOGUS__" <?=$selected?>>--Please Select--</option>
  420. <?php
  421. } else {
  422. ?>
  423. <option value="<?=$p?>" <?=$selected?>><?=$p?></option>
  424. <?php
  425. }
  426. } ?>
  427. </select></td>
  428. <td><input type="hidden" id="prev_location_<?=$name?>" name="prev_location[<?=$name?>]" value="<?=$row['location']?>">
  429. <input id="location_<?=$name?>" type="text" name="location[<?=$name?>]" size="32" value="<?=$row['location']?>"></td>
  430. <!--<td><?=$row['ports_required']?></td>-->
  431. <?php
  432. $tbase = '';
  433. if (file_exists(PORT_TMPL_DIR.'/devices/'."{$name}-ports.tmpl")) {
  434. $targ = readlink(PORT_TMPL_DIR.'/devices/'."{$name}-ports.tmpl");
  435. $tbase = basename($targ);
  436. } ?>
  437. <td><input type="hidden" id="prev_exception_<?=$name?>" name="prev_exception_<?=$name?>" value="<?=$tbase?>">
  438. <select id="exception_<?=$name?>" name="exception[<?=$name?>]">
  439. <option value="__BOGUS__">--Please Select--</option>
  440. <?php
  441. foreach ($exceptions as $exname => $exarr) {
  442. $path = $exarr[1];
  443. $expid = $exarr[0];
  444. $selected = '';
  445. if ($path == $tbase) {
  446. $selected = 'selected';
  447. }
  448. if ($selected == '' && $expid != $row['pid'] && $expid != '__ANY__') {
  449. continue;
  450. } ?>
  451. <option value="<?=$path?>" <?=$selected?>><?=$exname?></option>
  452. <?php
  453. } ?>
  454. </select>&nbsp;<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>
  455. </tr>
  456. <?php
  457. ++$i;
  458. }
  459. ?>
  460. </tbody>
  461. </table>
  462. </div>
  463. <br/>
  464. <div class="fbtable">
  465. <table summary="Button Table" width="100%" cellspacing="0">
  466. <tr>
  467. <td><input type="reset" value="Reset" name="reset">
  468. <input id="submit_bottom" type="submit" value="Submit" name="submit_bottom"></td>
  469. </tr>
  470. </table>
  471. </div>
  472. </form>
  473. </div>
  474. </body>
  475. </html>
  476. <?php
  477. cleanup();
  478. ?>