functions.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. //CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual IPv6 Address,Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username,Client ID,Peer ID,Data Channel Cipher
  89. if ($in_client_list && strpos($line, 'CLIENT_LIST') === 0) {
  90. $parts = explode(',', $line);
  91. if (count($parts) >= 9) {
  92. $clients[] = [
  93. 'name' => $parts[1],
  94. 'real_ip' => $parts[2],
  95. 'virtual_ip' => $parts[3],
  96. 'bytes_received' => formatBytes($parts[5]),
  97. 'bytes_sent' => formatBytes($parts[6]),
  98. 'connected_since' => $parts[7],
  99. 'username' => $parts[8] ?? $parts[1],
  100. 'cipher' => end($parts),
  101. 'banned' => isClientBanned($server, $parts[1]),
  102. ];
  103. }
  104. }
  105. }
  106. // Кэшируем результат
  107. $_SESSION['cached_status'][$server['name']] = $clients;
  108. return $clients;
  109. }
  110. function getAccountList($server) {
  111. $accounts = [];
  112. // Получаем список из index.txt (неотозванные сертификаты)
  113. if (!empty($server['cert_index']) && file_exists($server['cert_index'])) {
  114. $index_content = file_get_contents($server['cert_index']);
  115. $lines = explode("\n", $index_content);
  116. foreach ($lines as $line) {
  117. if (empty(trim($line))) continue;
  118. $parts = preg_split('/\s+/', $line);
  119. if (count($parts) >= 6 && $parts[0] === 'V') { // Только валидные сертификаты
  120. $username = $parts[5];
  121. $accounts[$username] = [
  122. "username" => $username,
  123. "ip" => null,
  124. "banned" => isClientBanned($server, $username)
  125. ];
  126. }
  127. }
  128. }
  129. // Получаем список выданных IP из ipp.txt
  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. if (!isset($accounts[$username])) {
  140. $accounts[$username] = [
  141. "username" => $username,
  142. "banned" => false
  143. ];
  144. }
  145. $accounts[$username]["ip"] = $ip;
  146. $accounts[$username]["banned"] = isClientBanned($server, $username);
  147. }
  148. }
  149. }
  150. // Ищем IP-адреса в CCD файлах
  151. if (!empty($server['ccd']) && is_dir($server['ccd'])) {
  152. $ccd_files = scandir($server['ccd']);
  153. foreach ($ccd_files as $file) {
  154. if ($file === '.' || $file === '..') continue;
  155. $username = $file;
  156. $filepath = $server['ccd'] . '/' . $file;
  157. $content = file_get_contents($filepath);
  158. // Ищем строку ifconfig-push с IP адресом
  159. if (preg_match('/ifconfig-push\s+(\d+\.\d+\.\d+\.\d+)/', $content, $matches)) {
  160. $ip = $matches[1];
  161. if (!isset($accounts[$username])) {
  162. $accounts[$username] = [
  163. "username" => $username,
  164. "banned" => false
  165. ];
  166. }
  167. $accounts[$username]["ip"] = $ip;
  168. $accounts[$username]["banned"] = isClientBanned($server, $username);
  169. }
  170. }
  171. }
  172. return $accounts;
  173. }
  174. function isClientBanned($server, $client_name) {
  175. $ccd_file = "{$server['ccd']}/$client_name";
  176. return file_exists($ccd_file) &&
  177. preg_match('/^disable$/m', file_get_contents($ccd_file));
  178. }
  179. function kickClient($server, $client_name) {
  180. return openvpnManagementCommand($server, "kill $client_name");
  181. }
  182. function banClient($server, $client_name) {
  183. $ccd_file = "{$server['ccd']}/$client_name";
  184. // Добавляем директиву disable
  185. $content = file_exists($ccd_file) ? file_get_contents($ccd_file) : '';
  186. if (!preg_match('/^disable$/m', $content)) {
  187. file_put_contents($ccd_file, $content . "\ndisable\n");
  188. }
  189. // Кикаем клиента
  190. kickClient($server, $client_name);
  191. return true;
  192. }
  193. function unbanClient($server, $client_name) {
  194. $ccd_file = "{$server['ccd']}/$client_name";
  195. if (file_exists($ccd_file)) {
  196. $content = file_get_contents($ccd_file);
  197. $new_content = preg_replace('/^disable$\n?/m', '', $content);
  198. file_put_contents($ccd_file, $new_content);
  199. return true;
  200. }
  201. return false;
  202. }
  203. function formatBytes($bytes) {
  204. $bytes = (int)$bytes;
  205. if ($bytes <= 0) return '0 B';
  206. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  207. $pow = floor(log($bytes)/log(1024));
  208. return round($bytes/pow(1024,$pow),2).' '.$units[$pow];
  209. }
  210. function getBannedClients($server, $active_clients) {
  211. $banned = [];
  212. $active_names = array_column($active_clients, 'name');
  213. if (is_dir($server['ccd'])) {
  214. foreach (scandir($server['ccd']) as $file) {
  215. if ($file !== '.' && $file !== '..' && is_file("{$server['ccd']}/$file")) {
  216. if (isClientBanned($server, $file) && !in_array($file, $active_names)) {
  217. $banned[] = $file;
  218. }
  219. }
  220. }
  221. }
  222. return $banned;
  223. }
  224. function isClientActive($active_clients,$username) {
  225. $active_names = array_column($active_clients, 'name');
  226. if (in_array($username,$active_names)) { return true; }
  227. return false;
  228. }