functions.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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']) && !empty(SHOW_PKI_INDEX) && file_exists(SHOW_PKI_INDEX)) {
  114. // Безопасное выполнение скрипта
  115. $command = sprintf(
  116. 'sudo %s %s 2>&1',
  117. escapeshellcmd(SHOW_PKI_INDEX),
  118. escapeshellarg($server['cert_index']),
  119. );
  120. exec($command, $index_content, $return_var);
  121. if ($return_var == 0) {
  122. foreach ($index_content as $line) {
  123. if (empty(trim($line))) continue;
  124. $parts = preg_split('/\s+/', $line);
  125. if (count($parts) >= 1 && $parts[0] === 'V') { // Только валидные сертификаты
  126. $username = substr(strstr(end($parts), '/CN='), 4);
  127. $accounts[$username] = [
  128. "username" => $username,
  129. "ip" => null,
  130. "banned" => isClientBanned($server, $username)
  131. ];
  132. }
  133. }
  134. }
  135. }
  136. // Получаем список выданных IP из ipp.txt
  137. if (!empty($server['ipp_file']) && file_exists($server['ipp_file'])) {
  138. $ipp_content = file_get_contents($server['ipp_file']);
  139. $lines = explode("\n", $ipp_content);
  140. foreach ($lines as $line) {
  141. if (empty(trim($line))) continue;
  142. $parts = explode(',', $line);
  143. if (count($parts) >= 2) {
  144. $username = $parts[0];
  145. $ip = $parts[1];
  146. if (!isset($accounts[$username])) {
  147. $accounts[$username] = [
  148. "username" => $username,
  149. "banned" => false
  150. ];
  151. }
  152. $accounts[$username]["ip"] = $ip;
  153. $accounts[$username]["banned"] = isClientBanned($server, $username);
  154. }
  155. }
  156. }
  157. // Ищем IP-адреса в CCD файлах
  158. if (!empty($server['ccd']) && is_dir($server['ccd'])) {
  159. $ccd_files = scandir($server['ccd']);
  160. foreach ($ccd_files as $file) {
  161. if ($file === '.' || $file === '..') continue;
  162. $username = $file;
  163. $filepath = $server['ccd'] . '/' . $file;
  164. $content = file_get_contents($filepath);
  165. // Ищем строку ifconfig-push с IP адресом
  166. if (preg_match('/ifconfig-push\s+(\d+\.\d+\.\d+\.\d+)/', $content, $matches)) {
  167. $ip = $matches[1];
  168. if (!isset($accounts[$username])) {
  169. $accounts[$username] = [
  170. "username" => $username,
  171. "banned" => false
  172. ];
  173. }
  174. $accounts[$username]["ip"] = $ip;
  175. $accounts[$username]["banned"] = isClientBanned($server, $username);
  176. }
  177. }
  178. }
  179. return $accounts;
  180. }
  181. function isClientBanned($server, $client_name) {
  182. $ccd_file = "{$server['ccd']}/$client_name";
  183. return file_exists($ccd_file) &&
  184. preg_match('/^disable$/m', file_get_contents($ccd_file));
  185. }
  186. function kickClient($server, $client_name) {
  187. return openvpnManagementCommand($server, "kill $client_name");
  188. }
  189. function banClient($server, $client_name) {
  190. $ccd_file = "{$server['ccd']}/$client_name";
  191. // Добавляем директиву disable
  192. $content = file_exists($ccd_file) ? file_get_contents($ccd_file) : '';
  193. if (!preg_match('/^disable$/m', $content)) {
  194. file_put_contents($ccd_file, $content . "\ndisable\n");
  195. }
  196. // Кикаем клиента
  197. kickClient($server, $client_name);
  198. return true;
  199. }
  200. function unbanClient($server, $client_name) {
  201. $ccd_file = "{$server['ccd']}/$client_name";
  202. if (file_exists($ccd_file)) {
  203. $content = file_get_contents($ccd_file);
  204. $new_content = preg_replace('/^disable$\n?/m', '', $content);
  205. file_put_contents($ccd_file, $new_content);
  206. return true;
  207. }
  208. return false;
  209. }
  210. function formatBytes($bytes) {
  211. $bytes = (int)$bytes;
  212. if ($bytes <= 0) return '0 B';
  213. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  214. $pow = floor(log($bytes)/log(1024));
  215. return round($bytes/pow(1024,$pow),2).' '.$units[$pow];
  216. }
  217. function getBannedClients($server, $active_clients) {
  218. $banned = [];
  219. $active_names = array_column($active_clients, 'name');
  220. if (is_dir($server['ccd'])) {
  221. foreach (scandir($server['ccd']) as $file) {
  222. if ($file !== '.' && $file !== '..' && is_file("{$server['ccd']}/$file")) {
  223. if (isClientBanned($server, $file) && !in_array($file, $active_names)) {
  224. $banned[] = $file;
  225. }
  226. }
  227. }
  228. }
  229. return $banned;
  230. }
  231. function isClientActive($active_clients,$username) {
  232. $active_names = array_column($active_clients, 'name');
  233. if (in_array($username,$active_names)) { return true; }
  234. return false;
  235. }