index.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. <?php
  2. // Настройки
  3. $page_title = 'OpenVPN Status';
  4. // Ограничение частоты запросов (в секундах)
  5. define('REQUEST_INTERVAL', 60);
  6. // Подключаем конфигурационный файл
  7. $config_file = __DIR__ . '/config.php';
  8. if (!file_exists($config_file)) {
  9. die("Configuration file not found: $config_file");
  10. }
  11. $servers = require $config_file;
  12. session_start();
  13. // Проверяем и инициализируем массив, если его нет
  14. if (!isset($_SESSION['last_request_time']) || !is_array($_SESSION['last_request_time'])) {
  15. $_SESSION['last_request_time'] = []; // Создаем пустой массив
  16. }
  17. function canRequestStatus($server) {
  18. if (!isset($_SESSION['last_request_time'][$server['name']])) { return true; }
  19. if (time() - $_SESSION['last_request_time'][$server['name']] >= REQUEST_INTERVAL) { return true; }
  20. return false;
  21. }
  22. function updateLastRequestTime($server) {
  23. $_SESSION['last_request_time'][$server['name']] = time();
  24. }
  25. function openvpnManagementCommand($server, $command) {
  26. $mgmt_host = $server['host'];
  27. $mgmt_port = $server['port'];
  28. $mgmt_pass = $server['password'];
  29. $timeout = 5;
  30. $socket = @fsockopen($mgmt_host, $mgmt_port, $errno, $errstr, $timeout);
  31. if (!$socket) {
  32. error_log("OpenVPN management connection failed to {$server['name']}: $errstr ($errno)");
  33. return false;
  34. }
  35. stream_set_timeout($socket, $timeout);
  36. try {
  37. // Читаем приветственное сообщение
  38. $welcome = '';
  39. while (!feof($socket)) {
  40. $line = fgets($socket);
  41. if ($line === false) break;
  42. $welcome .= $line;
  43. if (strpos($welcome, 'ENTER PASSWORD:') !== false) break;
  44. }
  45. // Отправляем пароль
  46. if (@fwrite($socket, "$mgmt_pass\n") === false) {
  47. throw new Exception("Failed to send password");
  48. }
  49. // Ждем подтверждения аутентификации
  50. $authResponse = '';
  51. while (!feof($socket)) {
  52. $line = fgets($socket);
  53. if ($line === false) break;
  54. $authResponse .= $line;
  55. if (strpos($authResponse, 'SUCCESS:') !== false || strpos($authResponse, '>INFO:') !== false) break;
  56. }
  57. // Отправляем команду
  58. if (@fwrite($socket, "$command\n") === false) {
  59. throw new Exception("Failed to send command");
  60. }
  61. // Читаем ответ
  62. $response = '';
  63. $expectedEnd = strpos($command, 'status') !== false ? "END\r\n" : ">";
  64. while (!feof($socket)) {
  65. $line = fgets($socket);
  66. if ($line === false) break;
  67. $response .= $line;
  68. if (strpos($response, $expectedEnd) !== false) break;
  69. }
  70. return $response;
  71. } catch (Exception $e) {
  72. error_log("OpenVPN management error ({$server['name']}): " . $e->getMessage());
  73. return false;
  74. } finally {
  75. @fwrite($socket, "quit\n");
  76. @fclose($socket);
  77. }
  78. }
  79. function getOpenVPNStatus($server) {
  80. // Проверяем, можно ли делать запрос
  81. if (!canRequestStatus($server)) {
  82. // Возвращаем кэшированные данные или пустой массив
  83. return $_SESSION['cached_status'][$server['name']] ?? [];
  84. }
  85. // Обновляем время последнего запроса
  86. updateLastRequestTime($server);
  87. $response = openvpnManagementCommand($server, "status 2");
  88. if (!$response) return $_SESSION['cached_status'][$server['name']] ?? [];
  89. $clients = [];
  90. $lines = explode("\n", $response);
  91. $in_client_list = false;
  92. foreach ($lines as $line) {
  93. $line = trim($line);
  94. if (strpos($line, 'HEADER,CLIENT_LIST') === 0) {
  95. $in_client_list = true;
  96. continue;
  97. }
  98. if (strpos($line, 'HEADER,ROUTING_TABLE') === 0) {
  99. $in_client_list = false;
  100. continue;
  101. }
  102. if ($in_client_list && strpos($line, 'CLIENT_LIST') === 0) {
  103. $parts = explode(',', $line);
  104. if (count($parts) >= 9) {
  105. $clients[] = [
  106. 'name' => $parts[1],
  107. 'real_ip' => $parts[2],
  108. 'virtual_ip' => $parts[3],
  109. 'bytes_received' => formatBytes($parts[5]),
  110. 'bytes_sent' => formatBytes($parts[6]),
  111. 'connected_since' => $parts[7],
  112. 'username' => $parts[8] ?? $parts[1],
  113. 'banned' => isClientBanned($server, $parts[1])
  114. ];
  115. }
  116. }
  117. }
  118. // Кэшируем результат
  119. $_SESSION['cached_status'][$server['name']] = $clients;
  120. return $clients;
  121. }
  122. function getAccountList($server) {
  123. $accounts = [];
  124. // Получаем список из index.txt (неотозванные сертификаты)
  125. if (!empty($server['cert_index']) && file_exists($server['cert_index'])) {
  126. $index_content = file_get_contents($server['cert_index']);
  127. $lines = explode("\n", $index_content);
  128. foreach ($lines as $line) {
  129. if (empty(trim($line))) continue;
  130. $parts = preg_split('/\s+/', $line);
  131. if (count($parts) >= 6 && $parts[0] === 'V') { // Только валидные сертификаты
  132. $username = $parts[5];
  133. $accounts[$username]["username"] = $username;
  134. $accounts[$username]["ip"] = $ip;
  135. $accounts[$username]["banned"] = false;
  136. if (isClientBanned($server,$username)) {
  137. $accounts[$username]["banned"] = true;
  138. }
  139. }
  140. }
  141. }
  142. // Получаем список выданных IP из ipp.txt
  143. $assigned_ips = [];
  144. if (!empty($server['ipp_file']) && file_exists($server['ipp_file'])) {
  145. $ipp_content = file_get_contents($server['ipp_file']);
  146. $lines = explode("\n", $ipp_content);
  147. foreach ($lines as $line) {
  148. if (empty(trim($line))) continue;
  149. $parts = explode(',', $line);
  150. if (count($parts) >= 2) {
  151. $username = $parts[0];
  152. $ip = $parts[1];
  153. $accounts[$username]["username"] = $username;
  154. $accounts[$username]["ip"] = $ip;
  155. $accounts[$username]["banned"] = false;
  156. if (isClientBanned($server,$username)) {
  157. $accounts[$username]["banned"] = true;
  158. }
  159. }
  160. }
  161. }
  162. return $accounts;
  163. }
  164. function isClientBanned($server, $client_name) {
  165. $ccd_file = "{$server['ccd']}/$client_name";
  166. return file_exists($ccd_file) &&
  167. preg_match('/^disable$/m', file_get_contents($ccd_file));
  168. }
  169. function kickClient($server, $client_name) {
  170. return openvpnManagementCommand($server, "kill $client_name");
  171. }
  172. function banClient($server, $client_name) {
  173. $ccd_file = "{$server['ccd']}/$client_name";
  174. // Добавляем директиву disable
  175. $content = file_exists($ccd_file) ? file_get_contents($ccd_file) : '';
  176. if (!preg_match('/^disable$/m', $content)) {
  177. file_put_contents($ccd_file, $content . "\ndisable\n");
  178. }
  179. // Кикаем клиента
  180. kickClient($server, $client_name);
  181. return true;
  182. }
  183. function unbanClient($server, $client_name) {
  184. $ccd_file = "{$server['ccd']}/$client_name";
  185. if (file_exists($ccd_file)) {
  186. $content = file_get_contents($ccd_file);
  187. $new_content = preg_replace('/^disable$\n?/m', '', $content);
  188. file_put_contents($ccd_file, $new_content);
  189. return true;
  190. }
  191. return false;
  192. }
  193. function formatBytes($bytes) {
  194. $bytes = (int)$bytes;
  195. if ($bytes <= 0) return '0 B';
  196. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  197. $pow = floor(log($bytes)/log(1024));
  198. return round($bytes/pow(1024,$pow),2).' '.$units[$pow];
  199. }
  200. function getBannedClients($server, $active_clients) {
  201. $banned = [];
  202. $active_names = array_column($active_clients, 'name');
  203. if (is_dir($server['ccd'])) {
  204. foreach (scandir($server['ccd']) as $file) {
  205. if ($file !== '.' && $file !== '..' && is_file("{$server['ccd']}/$file")) {
  206. if (isClientBanned($server, $file) && !in_array($file, $active_names)) {
  207. $banned[] = $file;
  208. }
  209. }
  210. }
  211. }
  212. return $banned;
  213. }
  214. function isClientActive($active_clients,$username) {
  215. $active_names = array_column($active_clients, 'name');
  216. if (!empty($active_names[$username])) { return true; }
  217. return false;
  218. }
  219. // Обработка POST-запросов
  220. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  221. foreach ($servers as $server_name => $server) {
  222. if (isset($_POST["ban-$server_name"])) {
  223. banClient($server, $_POST["ban-$server_name"]);
  224. } elseif (isset($_POST["unban-$server_name"])) {
  225. unbanClient($server, $_POST["unban-$server_name"]);
  226. }
  227. }
  228. header("Location: ".$_SERVER['PHP_SELF']);
  229. exit();
  230. }
  231. ?>
  232. <!DOCTYPE html>
  233. <html>
  234. <head>
  235. <title><?= htmlspecialchars($page_title) ?></title>
  236. <meta http-equiv="refresh" content="<?= REQUEST_INTERVAL ?>">
  237. <style>
  238. body { font-family: Arial, sans-serif; margin: 20px; }
  239. table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
  240. th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
  241. th { background-color: #f2f2f2; }
  242. .banned { background-color: #ffeeee; }
  243. .actions { white-space: nowrap; }
  244. .btn { padding: 3px 8px; margin: 2px; cursor: pointer; border: 1px solid #ccc; border-radius: 3px; }
  245. .kick-btn { background-color: #ffcccc; }
  246. .ban-btn { background-color: #ff9999; }
  247. .unban-btn { background-color: #ccffcc; }
  248. .section { margin-bottom: 30px; }
  249. .status-badge { padding: 2px 5px; border-radius: 3px; font-size: 0.8em; }
  250. .status-active { background-color: #ccffcc; }
  251. .status-banned { background-color: #ff9999; }
  252. .server-section { border: 1px solid #ddd; padding: 15px; margin-bottom: 20px; border-radius: 5px; }
  253. .spoiler { margin-top: 10px; }
  254. .spoiler-title {
  255. cursor: pointer;
  256. color: #0066cc;
  257. padding: 5px;
  258. background-color: #f0f0f0;
  259. border: 1px solid #ddd;
  260. border-radius: 3px;
  261. display: inline-block;
  262. margin-bottom: 5px;
  263. }
  264. .spoiler-title:after {
  265. content: " ▼";
  266. }
  267. .spoiler-title.collapsed:after {
  268. content: " ►";
  269. }
  270. .spoiler-content {
  271. display: none;
  272. padding: 10px;
  273. border: 1px solid #ddd;
  274. margin-top: 5px;
  275. background-color: #f9f9f9;
  276. border-radius: 3px;
  277. }
  278. </style>
  279. <script>
  280. function toggleSpoiler(button) {
  281. var content = button.nextElementSibling;
  282. if (content.style.display === "block") {
  283. content.style.display = "none";
  284. button.classList.add('collapsed');
  285. } else {
  286. content.style.display = "block";
  287. button.classList.remove('collapsed');
  288. }
  289. }
  290. </script>
  291. </head>
  292. <body>
  293. <h1><?= htmlspecialchars($page_title) ?></h1>
  294. <form method="post">
  295. <?php foreach ($servers as $server_name => $server):
  296. $clients = getOpenVPNStatus($server);
  297. $banned_clients = getBannedClients($server, $clients);
  298. $accounts = getAccountList($server);
  299. ?>
  300. <div class="server-section">
  301. <h2><?= htmlspecialchars($server['title']) ?></h2>
  302. <div class="section">
  303. <h3>Active Connections</h3>
  304. <table>
  305. <thead>
  306. <tr>
  307. <th>Client</th>
  308. <th>Real IP</th>
  309. <th>Virtual IP</th>
  310. <th>Traffic</th>
  311. <th>Connected</th>
  312. <th>Status</th>
  313. <th>Actions</th>
  314. </tr>
  315. </thead>
  316. <tbody>
  317. <?php foreach ($clients as $client): ?>
  318. <tr class="<?= $client['banned'] ? 'banned' : '' ?>">
  319. <td><?= htmlspecialchars($client['name']) ?></td>
  320. <td><?= htmlspecialchars($client['real_ip']) ?></td>
  321. <td><?= htmlspecialchars($client['virtual_ip']) ?></td>
  322. <td>↓<?= $client['bytes_received'] ?> ↑<?= $client['bytes_sent'] ?></td>
  323. <td><?= htmlspecialchars($client['connected_since']) ?></td>
  324. <td>
  325. <span class="status-badge <?= $client['banned'] ? 'status-banned' : 'status-active' ?>">
  326. <?= $client['banned'] ? 'BANNED' : 'Active' ?>
  327. </span>
  328. </td>
  329. <td class="actions">
  330. <?php if ($client['banned']): ?>
  331. <button type="submit" name="unban-<?= $server_name ?>" value="<?= htmlspecialchars($client['name']) ?>"
  332. class="btn unban-btn">Unban</button>
  333. <?php else: ?>
  334. <button type="submit" name="ban-<?= $server_name ?>" value="<?= htmlspecialchars($client['name']) ?>"
  335. class="btn ban-btn">Ban</button>
  336. <?php endif; ?>
  337. </td>
  338. </tr>
  339. <?php endforeach; ?>
  340. </tbody>
  341. </table>
  342. </div>
  343. <div class="section">
  344. <div class="spoiler">
  345. <div class="spoiler-title collapsed" onclick="toggleSpoiler(this)">
  346. Account List (<?= count($accounts) ?>)
  347. </div>
  348. <div class="spoiler-content">
  349. <table>
  350. <thead>
  351. <tr>
  352. <th>Account</th>
  353. <th>Assigned IP</th>
  354. <th>Status</th>
  355. <th>Actions</th>
  356. </tr>
  357. </thead>
  358. <tbody>
  359. <?php foreach ($accounts as $account): ?>
  360. <tr>
  361. <td><?= htmlspecialchars($account["username"]) ?></td>
  362. <td><?= htmlspecialchars($account['ip'] ?? 'N/A') ?></td>
  363. <td>
  364. <span class="status-badge <?= $account['banned'] ? 'status-banned' : 'status-active' ?>">
  365. <?= $account['banned'] ? 'BANNED' : 'ENABLED' ?>
  366. </span>
  367. </td>
  368. <td class="actions">
  369. <?php if ($account['banned']): ?>
  370. <button type="submit" name="unban-<?= $server_name ?>" value="<?= htmlspecialchars($account['username']) ?>"
  371. class="btn unban-btn">Unban</button>
  372. <?php else: ?>
  373. <button type="submit" name="ban-<?= $server_name ?>" value="<?= htmlspecialchars($account['username']) ?>"
  374. class="btn ban-btn">Ban</button>
  375. <?php endif; ?>
  376. </td>
  377. </tr>
  378. <?php endforeach; ?>
  379. </tbody>
  380. </table>
  381. </div>
  382. </div>
  383. </div>
  384. </div>
  385. <p>Next update in: <?= REQUEST_INTERVAL - (time() - $_SESSION['last_request_time'][$server['name']]) ?> seconds</p>
  386. <?php endforeach; ?>
  387. </form>
  388. </body>
  389. </html>