1
0

ToolsController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Helpers\ProxyConfig;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\User;
  6. use App\Utils\IP;
  7. use DB;
  8. use Exception;
  9. use Illuminate\Contracts\View\View;
  10. use Illuminate\Http\JsonResponse;
  11. use Illuminate\Http\RedirectResponse;
  12. use Illuminate\Http\Request;
  13. use Log;
  14. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  15. class ToolsController extends Controller
  16. {
  17. use ProxyConfig;
  18. public function decompile(Request $request): JsonResponse|View
  19. { // SS(R)链接反解析
  20. if ($request->isMethod('POST')) {
  21. $content = $request->input('content');
  22. if (empty($content)) {
  23. return response()->json(['status' => 'fail', 'message' => trans('admin.tools.decompile.content_placeholder')]);
  24. }
  25. // 反解析处理
  26. $content = str_replace("\n", ',', $content);
  27. $content = explode(',', $content);
  28. $txt = '';
  29. foreach ($content as $item) {
  30. // 判断是SS还是SSR链接
  31. $str = '';
  32. if (str_contains($item, 'ssr://')) {
  33. $str = mb_substr($item, 6);
  34. } elseif (str_contains($item, 'ss://')) {
  35. $str = mb_substr($item, 5);
  36. }
  37. $txt .= "\r\n".base64url_decode($str);
  38. }
  39. return response()->json(['status' => 'success', 'data' => $txt, 'message' => trans('common.success_item', ['attribute' => trans('admin.tools.decompile.attribute')])]);
  40. }
  41. return view('admin.tools.decompile');
  42. }
  43. public function convert(Request $request): JsonResponse|View
  44. { // 格式转换(SS转SSR)
  45. if ($request->isMethod('POST')) {
  46. $method = $request->input('method');
  47. $transfer_enable = $request->input('transfer_enable');
  48. $protocol = $request->input('protocol');
  49. $protocol_param = $request->input('protocol_param');
  50. $obfs = $request->input('obfs');
  51. $obfs_param = $request->input('obfs_param');
  52. $content = $request->input('content');
  53. if (empty($content)) {
  54. return response()->json(['status' => 'fail', 'message' => trans('admin.tools.convert.content_placeholder')]);
  55. }
  56. // 校验格式
  57. $content = json_decode($content, true);
  58. if (! isset($content['port_password']) || ! is_array($content['port_password'])) {
  59. return response()->json(['status' => 'fail', 'message' => trans('admin.tools.convert.missing_error')]);
  60. }
  61. // 转换成SSR格式JSON
  62. $data = [];
  63. foreach ($content['port_password'] as $port => $passwd) {
  64. $data[] = [
  65. 'u' => 0,
  66. 'd' => 0,
  67. 'enable' => 1,
  68. 'method' => $method,
  69. 'obfs' => $obfs,
  70. 'obfs_param' => empty($obfs_param) ? '' : $obfs_param,
  71. 'passwd' => $passwd,
  72. 'port' => $port,
  73. 'protocol' => $protocol,
  74. 'protocol_param' => empty($protocol_param) ? '' : $protocol_param,
  75. 'transfer_enable' => $transfer_enable,
  76. 'user' => date('Ymd').'_IMPORT_'.$port,
  77. ];
  78. }
  79. $json = json_encode($data);
  80. // 生成转换好的JSON文件
  81. file_put_contents(public_path('downloads/convert.json'), $json);
  82. return response()->json(['status' => 'success', 'data' => $json, 'message' => trans('common.success_item', ['attribute' => trans('common.convert')])]);
  83. }
  84. return view('admin.tools.convert', $this->proxyConfigOptions());
  85. }
  86. public function download(Request $request): BinaryFileResponse
  87. { // 下载转换好的JSON文件
  88. $type = (int) $request->input('type');
  89. if (empty($type)) {
  90. abort(400, trans('admin.tools.convert.params_unknown'));
  91. }
  92. if ($type === 1) {
  93. $filePath = public_path('downloads/convert.json');
  94. } else {
  95. $filePath = public_path('downloads/decompile.json');
  96. }
  97. if (! file_exists($filePath)) {
  98. abort(404, trans('admin.tools.convert.file_missing'));
  99. }
  100. return response()->download($filePath);
  101. }
  102. public function import(Request $request): RedirectResponse|View
  103. { // 数据导入
  104. if ($request->isMethod('POST')) {
  105. if (! $request->hasFile('uploadFile')) {
  106. return redirect()->back()->withErrors(trans('admin.tools.import.file_required'));
  107. }
  108. $file = $request->file('uploadFile');
  109. // 只能上传JSON文件
  110. if ($file->getClientMimeType() !== 'application/json' || $file->getClientOriginalExtension() !== 'json') {
  111. return redirect()->back()->withErrors(trans('admin.tools.import.file_type_error', ['type' => 'JSON']));
  112. }
  113. if (! $file->isValid()) {
  114. return redirect()->back()->withErrors(trans('admin.tools.import.file_error'));
  115. }
  116. $save_path = realpath(storage_path('uploads'));
  117. $new_name = md5($file->getClientOriginalExtension()).'.json';
  118. try {
  119. $file->move($save_path, $new_name);
  120. } catch (Exception $e) {
  121. Log::error(trans('common.error_action_item', ['action' => trans('common.import'), 'attribute' => trans('admin.menu.tools.import')]).': '.$e->getMessage());
  122. return redirect()->back()->withErrors(trans('admin.tools.import.file_error'));
  123. }
  124. // 读取文件内容
  125. $file_path = $save_path.'/'.$new_name;
  126. $data = file_get_contents($file_path);
  127. // 删除临时文件
  128. @unlink($file_path);
  129. $data = json_decode($data, true);
  130. if (! $data || ! is_array($data)) {
  131. return redirect()->back()->withErrors(trans('admin.tools.import.format_error', ['type' => 'JSON']));
  132. }
  133. try {
  134. DB::beginTransaction();
  135. foreach ($data as $user) {
  136. User::create([
  137. 'nickname' => $user['user'] ?? ('User_'.time()),
  138. 'username' => $user['user'] ?? ('user_'.time().'_'.rand(1000, 9999)),
  139. 'password' => bcrypt('123456'),
  140. 'port' => $user['port'] ?? 0,
  141. 'passwd' => $user['passwd'] ?? '',
  142. 'vmess_id' => $user['uuid'] ?? '',
  143. 'transfer_enable' => $user['transfer_enable'] ?? 0,
  144. 'method' => $user['method'] ?? '',
  145. 'protocol' => $user['protocol'] ?? '',
  146. 'obfs' => $user['obfs'] ?? '',
  147. 'expired_at' => '2099-01-01',
  148. 'reg_ip' => IP::getClientIp(),
  149. ]);
  150. }
  151. DB::commit();
  152. } catch (Exception $e) {
  153. DB::rollBack();
  154. Log::error(trans('common.error_action_item', ['action' => trans('common.import'), 'attribute' => trans('admin.menu.tools.import')]).': '.$e->getMessage());
  155. return redirect()->back()->withErrors(trans('common.failed_item', ['attribute' => trans('common.import')]).', '.$e->getMessage());
  156. }
  157. return redirect()->back()->with('successMsg', trans('common.success_item', ['attribute' => trans('common.import')]));
  158. }
  159. return view('admin.tools.import');
  160. }
  161. public function analysis(): View
  162. { // 日志分析
  163. $file = storage_path('app/ssserver.log');
  164. if (! file_exists($file)) {
  165. session()->flash('analysisErrorMsg', trans('admin.tools.analysis.file_missing', ['file_name' => $file]));
  166. return view('admin.tools.analysis');
  167. }
  168. $logs = $this->tail($file, 10000);
  169. $url = [];
  170. if ($logs) {
  171. foreach ($logs as $log) {
  172. if (str_contains($log, 'TCP connecting')) {
  173. continue;
  174. }
  175. preg_match('/TCP request (\w+\.){2}\w+/', $log, $tcp_matches);
  176. if (! empty($tcp_matches)) {
  177. $url[] = str_replace('TCP request ', '[TCP] ', $tcp_matches[0]);
  178. } else {
  179. preg_match(
  180. '/UDP data to (25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/',
  181. $log,
  182. $udp_matches
  183. );
  184. if (! empty($udp_matches)) {
  185. $url[] = str_replace('UDP data to ', '[UDP] ', $udp_matches[0]);
  186. }
  187. }
  188. }
  189. }
  190. return view('admin.tools.analysis', ['urlList' => array_unique($url)]);
  191. }
  192. private function tail(string $file, int $n, int $base = 5): array|false
  193. { // 类似Linux中的tail命令
  194. $fileLines = $this->countLine($file);
  195. if ($fileLines < 15000) {
  196. return false;
  197. }
  198. $fp = fopen($file, 'rb+');
  199. assert($n > 0);
  200. $pos = $n + 1;
  201. $lines = [];
  202. $counts = 0;
  203. while ($counts <= $n) {
  204. try {
  205. fseek($fp, -$pos, SEEK_END);
  206. } catch (Exception) {
  207. break;
  208. }
  209. $pos *= $base;
  210. while (! feof($fp)) {
  211. array_unshift($lines, fgets($fp));
  212. $counts++;
  213. }
  214. }
  215. fclose($fp);
  216. return array_slice($lines, 0, $n);
  217. }
  218. private function countLine(string $file): int
  219. { // 计算文件行数
  220. $fp = fopen($file, 'rb');
  221. $i = 0;
  222. while (! feof($fp)) {
  223. // 每次读取2M
  224. if ($data = fread($fp, 1024 * 1024 * 2)) {
  225. // 计算读取到的行数
  226. $num = substr_count($data, "\n");
  227. $i += $num;
  228. }
  229. }
  230. fclose($fp);
  231. return $i;
  232. }
  233. }