functions.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. defined('CONFIG') or die('Direct access not allowed');
  3. function canRequestStatus($server) {
  4. if (!isset($_SESSION['last_request_time'][$server['name']])) { return true; }
  5. if (time() - $_SESSION['last_request_time'][$server['name']] >= REQUEST_INTERVAL) { return true; }
  6. return false;
  7. }
  8. function updateLastRequestTime($server) {
  9. $_SESSION['last_request_time'][$server['name']] = time();
  10. }
  11. function openvpnManagementCommand($server, $command) {
  12. $mgmt_host = $server['host'];
  13. $mgmt_port = $server['port'];
  14. $mgmt_pass = $server['password'];
  15. $timeout = 5;
  16. $socket = @fsockopen($mgmt_host, $mgmt_port, $errno, $errstr, $timeout);
  17. if (!$socket) {
  18. error_log("OpenVPN management connection failed to {$server['name']}: $errstr ($errno)");
  19. return false;
  20. }
  21. stream_set_timeout($socket, $timeout);
  22. try {
  23. // Читаем приветственное сообщение
  24. $welcome = '';
  25. while (!feof($socket)) {
  26. $line = fgets($socket);
  27. if ($line === false) break;
  28. $welcome .= $line;
  29. if (strpos($welcome, 'ENTER PASSWORD:') !== false) break;
  30. }
  31. // Отправляем пароль
  32. if (@fwrite($socket, "$mgmt_pass\n") === false) {
  33. throw new Exception("Failed to send password");
  34. }
  35. // Ждем подтверждения аутентификации
  36. $authResponse = '';
  37. while (!feof($socket)) {
  38. $line = fgets($socket);
  39. if ($line === false) break;
  40. $authResponse .= $line;
  41. if (strpos($authResponse, 'SUCCESS:') !== false || strpos($authResponse, '>INFO:') !== false) break;
  42. }
  43. // Отправляем команду
  44. if (@fwrite($socket, "$command\n") === false) {
  45. throw new Exception("Failed to send command");
  46. }
  47. // Читаем ответ
  48. $response = '';
  49. $expectedEnd = strpos($command, 'status') !== false ? "END\r\n" : ">";
  50. while (!feof($socket)) {
  51. $line = fgets($socket);
  52. if ($line === false) break;
  53. $response .= $line;
  54. if (strpos($response, $expectedEnd) !== false) break;
  55. }
  56. return $response;
  57. } catch (Exception $e) {
  58. error_log("OpenVPN management error ({$server['name']}): " . $e->getMessage());
  59. return false;
  60. } finally {
  61. @fwrite($socket, "quit\n");
  62. @fclose($socket);
  63. }
  64. }
  65. function getOpenVPNStatus($server) {
  66. // Проверяем, можно ли делать запрос
  67. if (!canRequestStatus($server)) {
  68. // Возвращаем кэшированные данные или пустой массив
  69. return $_SESSION['cached_status'][$server['name']] ?? [];
  70. }
  71. // Обновляем время последнего запроса
  72. updateLastRequestTime($server);
  73. $response = openvpnManagementCommand($server, "status 2");
  74. if (!$response) return $_SESSION['cached_status'][$server['name']] ?? [];
  75. $clients = [];
  76. $lines = explode("\n", $response);
  77. $in_client_list = false;
  78. foreach ($lines as $line) {
  79. $line = trim($line);
  80. if (strpos($line, 'HEADER,CLIENT_LIST') === 0) {
  81. $in_client_list = true;
  82. continue;
  83. }
  84. if (strpos($line, 'HEADER,ROUTING_TABLE') === 0) {
  85. $in_client_list = false;
  86. continue;
  87. }
  88. if ($in_client_list && strpos($line, 'CLIENT_LIST') === 0) {
  89. $parts = explode(',', $line);
  90. if (count($parts) >= 9) {
  91. $clients[] = [
  92. 'name' => $parts[1],
  93. 'real_ip' => $parts[2],
  94. 'virtual_ip' => $parts[3],
  95. 'bytes_received' => formatBytes($parts[5]),
  96. 'bytes_sent' => formatBytes($parts[6]),
  97. 'connected_since' => $parts[7],
  98. 'username' => $parts[8] ?? $parts[1],
  99. 'banned' => isClientBanned($server, $parts[1])
  100. ];
  101. }
  102. }
  103. }
  104. // Кэшируем результат
  105. $_SESSION['cached_status'][$server['name']] = $clients;
  106. return $clients;
  107. }
  108. function getAccountList($server) {
  109. $accounts = [];
  110. // Получаем список из index.txt (неотозванные сертификаты)
  111. if (!empty($server['cert_index']) && file_exists($server['cert_index'])) {
  112. $index_content = file_get_contents($server['cert_index']);
  113. $lines = explode("\n", $index_content);
  114. foreach ($lines as $line) {
  115. if (empty(trim($line))) continue;
  116. $parts = preg_split('/\s+/', $line);
  117. if (count($parts) >= 6 && $parts[0] === 'V') { // Только валидные сертификаты
  118. $username = $parts[5];
  119. $accounts[$username]["username"] = $username;
  120. $accounts[$username]["ip"] = $ip;
  121. $accounts[$username]["banned"] = false;
  122. if (isClientBanned($server,$username)) {
  123. $accounts[$username]["banned"] = true;
  124. }
  125. }
  126. }
  127. }
  128. // Получаем список выданных IP из ipp.txt
  129. $assigned_ips = [];
  130. if (!empty($server['ipp_file']) && file_exists($server['ipp_file'])) {
  131. $ipp_content = file_get_contents($server['ipp_file']);
  132. $lines = explode("\n", $ipp_content);
  133. foreach ($lines as $line) {
  134. if (empty(trim($line))) continue;
  135. $parts = explode(',', $line);
  136. if (count($parts) >= 2) {
  137. $username = $parts[0];
  138. $ip = $parts[1];
  139. $accounts[$username]["username"] = $username;
  140. $accounts[$username]["ip"] = $ip;
  141. $accounts[$username]["banned"] = false;
  142. if (isClientBanned($server,$username)) {
  143. $accounts[$username]["banned"] = true;
  144. }
  145. }
  146. }
  147. }
  148. return $accounts;
  149. }
  150. function isClientBanned($server, $client_name) {
  151. $ccd_file = "{$server['ccd']}/$client_name";
  152. return file_exists($ccd_file) &&
  153. preg_match('/^disable$/m', file_get_contents($ccd_file));
  154. }
  155. function kickClient($server, $client_name) {
  156. return openvpnManagementCommand($server, "kill $client_name");
  157. }
  158. function banClient($server, $client_name) {
  159. $ccd_file = "{$server['ccd']}/$client_name";
  160. // Добавляем директиву disable
  161. $content = file_exists($ccd_file) ? file_get_contents($ccd_file) : '';
  162. if (!preg_match('/^disable$/m', $content)) {
  163. file_put_contents($ccd_file, $content . "\ndisable\n");
  164. }
  165. // Кикаем клиента
  166. kickClient($server, $client_name);
  167. return true;
  168. }
  169. function unbanClient($server, $client_name) {
  170. $ccd_file = "{$server['ccd']}/$client_name";
  171. if (file_exists($ccd_file)) {
  172. $content = file_get_contents($ccd_file);
  173. $new_content = preg_replace('/^disable$\n?/m', '', $content);
  174. file_put_contents($ccd_file, $new_content);
  175. return true;
  176. }
  177. return false;
  178. }
  179. function formatBytes($bytes) {
  180. $bytes = (int)$bytes;
  181. if ($bytes <= 0) return '0 B';
  182. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  183. $pow = floor(log($bytes)/log(1024));
  184. return round($bytes/pow(1024,$pow),2).' '.$units[$pow];
  185. }
  186. function getBannedClients($server, $active_clients) {
  187. $banned = [];
  188. $active_names = array_column($active_clients, 'name');
  189. if (is_dir($server['ccd'])) {
  190. foreach (scandir($server['ccd']) as $file) {
  191. if ($file !== '.' && $file !== '..' && is_file("{$server['ccd']}/$file")) {
  192. if (isClientBanned($server, $file) && !in_array($file, $active_names)) {
  193. $banned[] = $file;
  194. }
  195. }
  196. }
  197. }
  198. return $banned;
  199. }
  200. function isClientActive($active_clients,$username) {
  201. $active_names = array_column($active_clients, 'name');
  202. if (in_array($username,$active_names)) { return true; }
  203. return false;
  204. }