-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathlaunch_camoufox.py
More file actions
917 lines (903 loc) · 55.2 KB
/
launch_camoufox.py
File metadata and controls
917 lines (903 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
import sys
import subprocess
import time
import re
import os
import signal
import atexit
import argparse
import select
import traceback
import json
import threading
import queue
import logging
import logging.handlers
import socket
import platform
import shutil
from dotenv import load_dotenv
load_dotenv()
import uvicorn
from server import app
try:
from camoufox.server import launch_server
from camoufox import DefaultAddons
except ImportError:
if '--internal-launch' in sys.argv or any((arg.startswith('--internal-') for arg in sys.argv)):
print("❌ 致命错误:内部启动模式需要 'camoufox.server.launch_server' 和 'camoufox.DefaultAddons' 但无法导入。", file=sys.stderr)
print(" 这通常意味着 'camoufox' 包未正确安装或不在 PYTHONPATH 中。", file=sys.stderr)
sys.exit(1)
else:
launch_server = None
DefaultAddons = None
PYTHON_EXECUTABLE = sys.executable
ENDPOINT_CAPTURE_TIMEOUT = int(os.environ.get('ENDPOINT_CAPTURE_TIMEOUT', '90'))
DEFAULT_SERVER_PORT = int(os.environ.get('DEFAULT_FASTAPI_PORT', '2048'))
DEFAULT_CAMOUFOX_PORT = int(os.environ.get('DEFAULT_CAMOUFOX_PORT', '40222'))
DEFAULT_STREAM_PORT = int(os.environ.get('STREAM_PORT', '3120'))
DEFAULT_HELPER_ENDPOINT = os.environ.get('GUI_DEFAULT_HELPER_ENDPOINT', '')
DEFAULT_AUTH_SAVE_TIMEOUT = int(os.environ.get('AUTH_SAVE_TIMEOUT', '30'))
DEFAULT_SERVER_LOG_LEVEL = os.environ.get('SERVER_LOG_LEVEL', 'INFO')
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
DATA_DIR = os.path.join(PROJECT_ROOT, 'data')
AUTH_PROFILES_DIR = os.path.join(DATA_DIR, 'auth_profiles')
ACTIVE_AUTH_DIR = os.path.join(AUTH_PROFILES_DIR, 'active')
SAVED_AUTH_DIR = os.path.join(AUTH_PROFILES_DIR, 'saved')
HTTP_PROXY = os.environ.get('HTTP_PROXY', '')
HTTPS_PROXY = os.environ.get('HTTPS_PROXY', '')
LOG_DIR = os.path.join(PROJECT_ROOT, 'logs')
LAUNCHER_LOG_FILE_PATH = os.path.join(LOG_DIR, 'launch_app.log')
camoufox_proc = None
logger = logging.getLogger('CamoufoxLauncher')
ws_regex = re.compile('(ws://\\S+)')
def _enqueue_output(stream, stream_name, output_queue, process_pid_for_log='<未知PID>'):
log_prefix = f'[读取线程-{stream_name}-PID:{process_pid_for_log}]'
try:
for line_bytes in iter(stream.readline, b''):
if not line_bytes:
break
try:
line_str = line_bytes.decode('utf-8', errors='replace')
output_queue.put((stream_name, line_str))
except Exception as decode_err:
logger.warning(f'{log_prefix} 解码错误: {decode_err}。原始数据 (前100字节): {line_bytes[:100]}')
output_queue.put((stream_name, f'[解码错误: {decode_err}] {line_bytes[:100]}...\n'))
except ValueError:
logger.debug(f'{log_prefix} ValueError (流可能已关闭)。')
except Exception as e:
logger.error(f'{log_prefix} 读取流时发生意外错误: {e}', exc_info=True)
finally:
output_queue.put((stream_name, None))
if hasattr(stream, 'close') and (not stream.closed):
try:
stream.close()
except Exception:
pass
logger.debug(f'{log_prefix} 线程退出。')
def setup_launcher_logging(log_level=logging.INFO):
os.makedirs(LOG_DIR, exist_ok=True)
file_log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - [%(name)s:%(funcName)s:%(lineno)d] - %(message)s')
console_log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
if logger.hasHandlers():
logger.handlers.clear()
logger.setLevel(log_level)
logger.propagate = False
if os.path.exists(LAUNCHER_LOG_FILE_PATH):
try:
os.remove(LAUNCHER_LOG_FILE_PATH)
except OSError:
pass
file_handler = logging.handlers.RotatingFileHandler(LAUNCHER_LOG_FILE_PATH, maxBytes=2 * 1024 * 1024, backupCount=3, encoding='utf-8', mode='w')
file_handler.setFormatter(file_log_formatter)
logger.addHandler(file_handler)
stream_handler = logging.StreamHandler(sys.stderr)
stream_handler.setFormatter(console_log_formatter)
logger.addHandler(stream_handler)
logger.info('=' * 30 + ' Camoufox启动器日志系统已初始化 ' + '=' * 30)
logger.info(f'日志级别设置为: {logging.getLevelName(logger.getEffectiveLevel())}')
logger.info(f'日志文件路径: {LAUNCHER_LOG_FILE_PATH}')
def ensure_auth_dirs_exist():
logger.info('正在检查并确保认证文件目录存在...')
try:
os.makedirs(ACTIVE_AUTH_DIR, exist_ok=True)
logger.info(f' ✓ 活动认证目录就绪: {ACTIVE_AUTH_DIR}')
os.makedirs(SAVED_AUTH_DIR, exist_ok=True)
logger.info(f' ✓ 已保存认证目录就绪: {SAVED_AUTH_DIR}')
except Exception as e:
logger.error(f' ❌ 创建认证目录失败: {e}', exc_info=True)
sys.exit(1)
def cleanup():
global camoufox_proc
logger.info('--- 开始执行清理程序 (launch_camoufox.py) ---')
if camoufox_proc and camoufox_proc.poll() is None:
pid = camoufox_proc.pid
logger.info(f'正在终止 Camoufox 内部子进程 (PID: {pid})...')
try:
if sys.platform != 'win32' and hasattr(os, 'getpgid') and hasattr(os, 'killpg'):
try:
pgid = os.getpgid(pid)
logger.info(f' 向 Camoufox 进程组 (PGID: {pgid}) 发送 SIGTERM 信号...')
os.killpg(pgid, signal.SIGTERM)
except ProcessLookupError:
logger.info(f' Camoufox 进程组 (PID: {pid}) 未找到,尝试直接终止进程...')
camoufox_proc.terminate()
elif sys.platform == 'win32':
logger.info(f'进程树 (PID: {pid}) 发送终止请求')
subprocess.call(['taskkill', '/F', '/T', '/PID', str(pid)])
else:
logger.info(f' 向 Camoufox (PID: {pid}) 发送 SIGTERM 信号...')
camoufox_proc.terminate()
camoufox_proc.wait(timeout=5)
logger.info(f' ✓ Camoufox (PID: {pid}) 已通过 SIGTERM 成功终止。')
except subprocess.TimeoutExpired:
logger.warning(f' ⚠️ Camoufox (PID: {pid}) SIGTERM 超时。正在发送 SIGKILL 强制终止...')
if sys.platform != 'win32' and hasattr(os, 'getpgid') and hasattr(os, 'killpg'):
try:
pgid = os.getpgid(pid)
logger.info(f' 向 Camoufox 进程组 (PGID: {pgid}) 发送 SIGKILL 信号...')
os.killpg(pgid, signal.SIGKILL)
except ProcessLookupError:
logger.info(f' Camoufox 进程组 (PID: {pid}) 在 SIGKILL 时未找到,尝试直接强制终止...')
camoufox_proc.kill()
elif sys.platform == 'win32':
logger.info(f' 强制杀死 Camoufox 进程树 (PID: {pid})')
subprocess.call(['taskkill', '/F', '/T', '/PID', str(pid)])
else:
camoufox_proc.kill()
try:
camoufox_proc.wait(timeout=2)
logger.info(f' ✓ Camoufox (PID: {pid}) 已通过 SIGKILL 成功终止。')
except Exception as e_kill:
logger.error(f' ❌ 等待 Camoufox (PID: {pid}) SIGKILL 完成时出错: {e_kill}')
except Exception as e_term:
logger.error(f' ❌ 终止 Camoufox (PID: {pid}) 时发生错误: {e_term}', exc_info=True)
finally:
if hasattr(camoufox_proc, 'stdout') and camoufox_proc.stdout and (not camoufox_proc.stdout.closed):
camoufox_proc.stdout.close()
if hasattr(camoufox_proc, 'stderr') and camoufox_proc.stderr and (not camoufox_proc.stderr.closed):
camoufox_proc.stderr.close()
camoufox_proc = None
elif camoufox_proc:
logger.info(f"Camoufox 内部子进程 (PID: {(camoufox_proc.pid if hasattr(camoufox_proc, 'pid') else 'N/A')}) 先前已自行结束,退出码: {camoufox_proc.poll()}。")
camoufox_proc = None
else:
logger.info('Camoufox 内部子进程未运行或已清理。')
logger.info('--- 清理程序执行完毕 (launch_camoufox.py) ---')
atexit.register(cleanup)
def signal_handler(sig, frame):
logger.info(f'接收到信号 {signal.Signals(sig).name} ({sig})。正在启动退出程序...')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
def check_dependencies():
logger.info('--- 步骤 1: 检查依赖项 ---')
required_modules = {}
if launch_server is not None and DefaultAddons is not None:
required_modules['camoufox'] = 'camoufox (for server and addons)'
elif launch_server is not None:
required_modules['camoufox_server'] = 'camoufox.server'
logger.warning(" ⚠️ 'camoufox.server' 已导入,但 'camoufox.DefaultAddons' 未导入。排除插件功能可能受限。")
missing_py_modules = []
dependencies_ok = True
if required_modules:
logger.info('正在检查 Python 模块:')
for module_name, install_package_name in required_modules.items():
try:
__import__(module_name)
logger.info(f" ✓ 模块 '{module_name}' 已找到。")
except ImportError:
logger.error(f" ❌ 模块 '{module_name}' (包: '{install_package_name}') 未找到。")
missing_py_modules.append(install_package_name)
dependencies_ok = False
else:
is_any_internal_arg = any((arg.startswith('--internal-') for arg in sys.argv))
if is_any_internal_arg and (launch_server is None or DefaultAddons is None):
logger.error(f" ❌ 内部启动模式 (--internal-*) 需要 'camoufox' 包,但未能导入。")
dependencies_ok = False
elif not is_any_internal_arg:
logger.info("未请求内部启动模式,且未导入 camoufox.server,跳过对 'camoufox' Python 包的检查。")
try:
from server import app as server_app_check
if server_app_check:
logger.info(f" ✓ 成功从 'server.py' 导入 'app' 对象。")
except ImportError as e_import_server:
logger.error(f" ❌ 无法从 'server.py' 导入 'app' 对象: {e_import_server}")
logger.error(f" 请确保 'server.py' 文件存在且没有导入错误。")
dependencies_ok = False
if not dependencies_ok:
logger.error('-------------------------------------------------')
logger.error('❌ 依赖项检查失败!')
if missing_py_modules:
logger.error(f" 缺少的 Python 库: {', '.join(missing_py_modules)}")
logger.error(f" 请尝试使用 pip 安装: pip install {' '.join(missing_py_modules)}")
logger.error('-------------------------------------------------')
sys.exit(1)
else:
logger.info('✅ 所有启动器依赖项检查通过。')
def is_port_in_use(port: int, host: str='0.0.0.0') -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
return False
except OSError:
return True
except Exception as e:
logger.warning(f'检查端口 {port} (主机 {host}) 时发生未知错误: {e}')
return True
def find_pids_on_port(port: int) -> list[int]:
pids = []
system_platform = platform.system()
command = ''
try:
if system_platform == 'Linux' or system_platform == 'Darwin':
command = f'lsof -ti :{port} -sTCP:LISTEN'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, close_fds=True)
stdout, stderr = process.communicate(timeout=5)
if process.returncode == 0 and stdout:
pids = [int(pid) for pid in stdout.strip().split('\n') if pid.isdigit()]
elif process.returncode != 0 and ('command not found' in stderr.lower() or '未找到命令' in stderr):
logger.error(f"命令 'lsof' 未找到。请确保已安装。")
elif process.returncode not in [0, 1]:
logger.warning(f'执行 lsof 命令失败 (返回码 {process.returncode}): {stderr.strip()}')
elif system_platform == 'Windows':
command = f'netstat -ano -p TCP | findstr "LISTENING" | findstr ":{port} "'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate(timeout=10)
if process.returncode == 0 and stdout:
for line in stdout.strip().split('\n'):
parts = line.split()
if len(parts) >= 4 and parts[0].upper() == 'TCP' and (f':{port}' in parts[1]):
if parts[-1].isdigit():
pids.append(int(parts[-1]))
pids = list(set(pids))
elif process.returncode not in [0, 1]:
logger.warning(f'执行 netstat/findstr 命令失败 (返回码 {process.returncode}): {stderr.strip()}')
else:
logger.warning(f"不支持的操作系统 '{system_platform}' 用于查找占用端口的进程。")
except FileNotFoundError:
cmd_name = command.split()[0] if command else '相关工具'
logger.error(f"命令 '{cmd_name}' 未找到。")
except subprocess.TimeoutExpired:
logger.error(f"执行命令 '{command}' 超时。")
except Exception as e:
logger.error(f'查找占用端口 {port} 的进程时出错: {e}', exc_info=True)
return pids
def kill_process_interactive(pid: int) -> bool:
system_platform = platform.system()
success = False
logger.info(f' 尝试终止进程 PID: {pid}...')
try:
if system_platform == 'Linux' or system_platform == 'Darwin':
result_term = subprocess.run(f'kill {pid}', shell=True, capture_output=True, text=True, timeout=3, check=False)
if result_term.returncode == 0:
logger.info(f' ✓ PID {pid} 已发送 SIGTERM 信号。')
success = True
else:
logger.warning(f' PID {pid} SIGTERM 失败: {result_term.stderr.strip() or result_term.stdout.strip()}. 尝试 SIGKILL...')
result_kill = subprocess.run(f'kill -9 {pid}', shell=True, capture_output=True, text=True, timeout=3, check=False)
if result_kill.returncode == 0:
logger.info(f' ✓ PID {pid} 已发送 SIGKILL 信号。')
success = True
else:
logger.error(f' ✗ PID {pid} SIGKILL 失败: {result_kill.stderr.strip() or result_kill.stdout.strip()}.')
elif system_platform == 'Windows':
command_desc = f'taskkill /PID {pid} /T /F'
result = subprocess.run(command_desc, shell=True, capture_output=True, text=True, timeout=5, check=False)
output = result.stdout.strip()
error_output = result.stderr.strip()
if result.returncode == 0 and ('SUCCESS' in output.upper() or '成功' in output):
logger.info(f' ✓ PID {pid} 已通过 taskkill /F 终止。')
success = True
elif 'could not find process' in error_output.lower() or '找不到' in error_output:
logger.info(f' PID {pid} 执行 taskkill 时未找到 (可能已退出)。')
success = True
else:
logger.error(f" ✗ PID {pid} taskkill /F 失败: {(error_output + ' ' + output).strip()}.")
else:
logger.warning(f" 不支持的操作系统 '{system_platform}' 用于终止进程。")
except Exception as e:
logger.error(f' 终止 PID {pid} 时发生意外错误: {e}', exc_info=True)
return success
def input_with_timeout(prompt_message: str, timeout_seconds: int=30) -> str:
print(prompt_message, end='', flush=True)
if sys.platform == 'win32':
user_input_container = [None]
def get_input_in_thread():
try:
user_input_container[0] = sys.stdin.readline().strip()
except Exception:
user_input_container[0] = ''
input_thread = threading.Thread(target=get_input_in_thread, daemon=True)
input_thread.start()
input_thread.join(timeout=timeout_seconds)
if input_thread.is_alive():
print('\n输入超时。将使用默认值。', flush=True)
return ''
return user_input_container[0] if user_input_container[0] is not None else ''
else:
readable_fds, _, _ = select.select([sys.stdin], [], [], timeout_seconds)
if readable_fds:
return sys.stdin.readline().strip()
else:
print('\n输入超时。将使用默认值。', flush=True)
return ''
def get_proxy_from_gsettings():
def _run_gsettings_command(command_parts: list[str]) -> str | None:
try:
process_result = subprocess.run(command_parts, capture_output=True, text=True, check=False, timeout=1)
if process_result.returncode == 0:
value = process_result.stdout.strip()
if value.startswith("'") and value.endswith("'"):
value = value[1:-1]
if not value or value == "''" or value == '@as []' or (value == '[]'):
return None
return value
else:
return None
except subprocess.TimeoutExpired:
return None
except Exception:
return None
proxy_mode = _run_gsettings_command(['gsettings', 'get', 'org.gnome.system.proxy', 'mode'])
if proxy_mode == 'manual':
http_host = _run_gsettings_command(['gsettings', 'get', 'org.gnome.system.proxy.http', 'host'])
http_port_str = _run_gsettings_command(['gsettings', 'get', 'org.gnome.system.proxy.http', 'port'])
if http_host and http_port_str:
try:
http_port = int(http_port_str)
if http_port > 0:
return f'http://{http_host}:{http_port}'
except ValueError:
pass
https_host = _run_gsettings_command(['gsettings', 'get', 'org.gnome.system.proxy.https', 'host'])
https_port_str = _run_gsettings_command(['gsettings', 'get', 'org.gnome.system.proxy.https', 'port'])
if https_host and https_port_str:
try:
https_port = int(https_port_str)
if https_port > 0:
return f'http://{https_host}:{https_port}'
except ValueError:
pass
return None
def determine_proxy_configuration(internal_camoufox_proxy_arg=None):
result = {'camoufox_proxy': None, 'stream_proxy': None, 'source': '无代理'}
if internal_camoufox_proxy_arg is not None:
if internal_camoufox_proxy_arg.strip():
result['camoufox_proxy'] = internal_camoufox_proxy_arg.strip()
result['stream_proxy'] = internal_camoufox_proxy_arg.strip()
result['source'] = f'命令行参数 --internal-camoufox-proxy: {internal_camoufox_proxy_arg.strip()}'
else:
result['source'] = "命令行参数 --internal-camoufox-proxy='' (明确禁用代理)"
return result
unified_proxy = os.environ.get('UNIFIED_PROXY_CONFIG')
if unified_proxy:
result['camoufox_proxy'] = unified_proxy
result['stream_proxy'] = unified_proxy
result['source'] = f'环境变量 UNIFIED_PROXY_CONFIG: {unified_proxy}'
return result
http_proxy = os.environ.get('HTTP_PROXY')
if http_proxy:
result['camoufox_proxy'] = http_proxy
result['stream_proxy'] = http_proxy
result['source'] = f'环境变量 HTTP_PROXY: {http_proxy}'
return result
https_proxy = os.environ.get('HTTPS_PROXY')
if https_proxy:
result['camoufox_proxy'] = https_proxy
result['stream_proxy'] = https_proxy
result['source'] = f'环境变量 HTTPS_PROXY: {https_proxy}'
return result
if sys.platform.startswith('linux'):
gsettings_proxy = get_proxy_from_gsettings()
if gsettings_proxy:
result['camoufox_proxy'] = gsettings_proxy
result['stream_proxy'] = gsettings_proxy
result['source'] = f'gsettings 系统代理: {gsettings_proxy}'
return result
return result
if __name__ == '__main__':
is_internal_call = any((arg.startswith('--internal-') for arg in sys.argv))
if not is_internal_call:
setup_launcher_logging(log_level=logging.INFO)
parser = argparse.ArgumentParser(description='Camoufox 浏览器模拟与 FastAPI 代理服务器的启动器。', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--internal-launch-mode', type=str, choices=['debug', 'headless', 'virtual_headless'], help=argparse.SUPPRESS)
parser.add_argument('--internal-auth-file', type=str, default=None, help=argparse.SUPPRESS)
parser.add_argument('--internal-camoufox-port', type=int, default=DEFAULT_CAMOUFOX_PORT, help=argparse.SUPPRESS)
parser.add_argument('--internal-camoufox-proxy', type=str, default=None, help=argparse.SUPPRESS)
parser.add_argument('--internal-camoufox-os', type=str, default='random', help=argparse.SUPPRESS)
parser.add_argument('--server-port', type=int, default=DEFAULT_SERVER_PORT, help=f'FastAPI 服务器监听的端口号 (默认: {DEFAULT_SERVER_PORT})')
parser.add_argument('--stream-port', type=int, default=DEFAULT_STREAM_PORT, help=f'流式代理服务器使用端口提供来禁用此功能 --stream-port=0 . 默认: {DEFAULT_STREAM_PORT}')
parser.add_argument('--helper', type=str, default=DEFAULT_HELPER_ENDPOINT, help=f"Helper 服务器的 getStreamResponse 端点地址 (例如: http://127.0.0.1:3121/getStreamResponse). 提供空字符串 (例如: --helper='') 来禁用此功能. 默认: {DEFAULT_HELPER_ENDPOINT}")
parser.add_argument('--camoufox-debug-port', type=int, default=DEFAULT_CAMOUFOX_PORT, help=f'内部 Camoufox 实例监听的调试端口号 (默认: {DEFAULT_CAMOUFOX_PORT})')
mode_selection_group = parser.add_mutually_exclusive_group()
mode_selection_group.add_argument('--debug', action='store_true', help='启动调试模式 (浏览器界面可见,允许交互式认证)')
mode_selection_group.add_argument('--headless', action='store_true', help='启动无头模式 (浏览器无界面,需要预先保存的认证文件)')
mode_selection_group.add_argument('--virtual-display', action='store_true', help='启动无头模式并使用虚拟显示 (Xvfb, 仅限 Linux)')
parser.add_argument('--active-auth-json', type=str, default=None, help='[无头模式/调试模式可选] 指定要使用的活动认证JSON文件的路径 (在 auth_profiles/active/ 或 auth_profiles/saved/ 中,或绝对路径)。如果未提供,无头模式将使用 active/ 目录中最新的JSON文件,调试模式将提示选择或不使用。')
parser.add_argument('--auto-save-auth', action='store_true', help='[调试模式] 在登录成功后,如果之前未加载认证文件,则自动提示并保存新的认证状态。')
parser.add_argument('--auth-save-timeout', type=int, default=DEFAULT_AUTH_SAVE_TIMEOUT, help=f'[调试模式] 自动保存认证或输入认证文件名的等待超时时间 (秒)。默认: {DEFAULT_AUTH_SAVE_TIMEOUT}')
parser.add_argument('--server-log-level', type=str, default=DEFAULT_SERVER_LOG_LEVEL, choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help=f'server.py 的日志级别。默认: {DEFAULT_SERVER_LOG_LEVEL}')
parser.add_argument('--server-redirect-print', action='store_true', help='将 server.py 中的 print 输出重定向到其日志系统。默认不重定向以便调试模式下的 input() 提示可见。')
parser.add_argument('--debug-logs', action='store_true', help='启用 server.py 内部的 DEBUG 级别详细日志 (环境变量 DEBUG_LOGS_ENABLED)。')
parser.add_argument('--trace-logs', action='store_true', help='启用 server.py 内部的 TRACE 级别更详细日志 (环境变量 TRACE_LOGS_ENABLED)。')
args = parser.parse_args()
current_system_for_camoufox = platform.system()
if current_system_for_camoufox == 'Linux':
simulated_os_for_camoufox = 'linux'
elif current_system_for_camoufox == 'Windows':
simulated_os_for_camoufox = 'windows'
elif current_system_for_camoufox == 'Darwin':
simulated_os_for_camoufox = 'macos'
else:
simulated_os_for_camoufox = 'linux'
logger.warning(f"无法识别当前系统 '{current_system_for_camoufox}'。Camoufox OS 模拟将默认设置为: {simulated_os_for_camoufox}")
logger.info(f"根据当前系统 '{current_system_for_camoufox}',Camoufox OS 模拟已自动设置为: {simulated_os_for_camoufox}")
if args.internal_launch_mode:
if not launch_server or not DefaultAddons:
print('❌ 致命错误 (--internal-launch-mode): camoufox.server.launch_server 或 camoufox.DefaultAddons 不可用。脚本无法继续。', file=sys.stderr)
sys.exit(1)
internal_mode_arg = args.internal_launch_mode
auth_file = args.internal_auth_file
camoufox_port_internal = args.internal_camoufox_port
proxy_config = determine_proxy_configuration(args.internal_camoufox_proxy)
actual_proxy_to_use = proxy_config['camoufox_proxy']
print(f"--- [内部Camoufox启动] 代理配置: {proxy_config['source']} ---", flush=True)
camoufox_proxy_internal = actual_proxy_to_use
camoufox_os_internal = args.internal_camoufox_os
print(f"--- [内部Camoufox启动] 模式: {internal_mode_arg}, 认证文件: {(os.path.basename(auth_file) if auth_file else '无')}, Camoufox端口: {camoufox_port_internal}, 代理: {camoufox_proxy_internal or '无'}, 模拟OS: {camoufox_os_internal} ---", flush=True)
print(f'--- [内部Camoufox启动] 正在调用 camoufox.server.launch_server ... ---', flush=True)
try:
memory_optimization_prefs = {
# Disable memory cache
'browser.cache.memory.enable': False,
'browser.cache.memory.capacity': 0,
# Minimal session history
'browser.sessionhistory.max_entries': 2,
'browser.sessionhistory.max_total_viewers': 0,
# JS memory limits
'javascript.options.mem.gc_frequency': 300,
'javascript.options.mem.high_water_mark': 32,
'javascript.options.mem.nursery.max_kb': 2048,
# Single process mode
'dom.ipc.processCount': 1,
'dom.ipc.processCount.webIsolated': 1,
'browser.tabs.remote.autostart': False,
'browser.tabs.remote.autostart.2': False,
# Disable unused features
'layout.css.grid-template-masonry-value.enabled': False,
'toolkit.cosmeticAnimations.enabled': False,
'media.memory_cache_max_size': 256,
'image.mem.max_ms_before_yield': 50,
# Disable telemetry/background services
'datareporting.healthreport.uploadEnabled': False,
'datareporting.policy.dataSubmissionEnabled': False,
'browser.ping-centre.telemetry': False,
'toolkit.telemetry.enabled': False,
'toolkit.telemetry.unified': False,
# Disable disk cache
'browser.cache.disk.enable': False,
'browser.cache.offline.enable': False,
# Disable prefetch
'network.prefetch-next': False,
'network.dns.disablePrefetch': True,
# Reduce font memory
'gfx.font_rendering.fontconfig.max_generic_substitutions': 3,
# Disable GPU / hardware acceleration
'layers.acceleration.disabled': True,
'gfx.direct2d.disabled': True,
'media.hardware-video-decoding.enabled': False,
# Disable WebGL (not needed for AI Studio)
'webgl.disabled': True,
'webgl.enable-webgl2': False,
# Reduce HTTP connections
'network.http.max-connections': 6,
'network.http.max-persistent-connections-per-server': 2,
# Disable push / notifications
'dom.push.enabled': False,
'dom.webnotifications.enabled': False,
# Reduce session store overhead
'browser.sessionstore.resume_from_crash': False,
'browser.sessionstore.interval': 600000,
# Reduce WebSocket connection limit
'network.websocket.max-connections': 10,
}
launch_args_for_internal_camoufox = {'port': camoufox_port_internal, 'addons': [], 'exclude_addons': [DefaultAddons.UBO], 'window': (1024, 600), 'firefox_user_prefs': memory_optimization_prefs}
if camoufox_proxy_internal:
launch_args_for_internal_camoufox['proxy'] = {'server': camoufox_proxy_internal}
if auth_file:
launch_args_for_internal_camoufox['storage_state'] = auth_file
if ',' in camoufox_os_internal:
camoufox_os_list_internal = [s.strip().lower() for s in camoufox_os_internal.split(',')]
valid_os_values = ['windows', 'macos', 'linux']
if not all((val in valid_os_values for val in camoufox_os_list_internal)):
print(f'❌ 内部Camoufox启动错误: camoufox_os_internal 列表中包含无效值: {camoufox_os_list_internal}', file=sys.stderr)
sys.exit(1)
launch_args_for_internal_camoufox['os'] = camoufox_os_list_internal
elif camoufox_os_internal.lower() in ['windows', 'macos', 'linux']:
launch_args_for_internal_camoufox['os'] = camoufox_os_internal.lower()
elif camoufox_os_internal.lower() != 'random':
print(f"❌ 内部Camoufox启动错误: camoufox_os_internal 值无效: '{camoufox_os_internal}'", file=sys.stderr)
sys.exit(1)
print(f' 传递给 launch_server 的参数: {launch_args_for_internal_camoufox}', flush=True)
if internal_mode_arg == 'headless':
launch_server(headless=True, **launch_args_for_internal_camoufox)
elif internal_mode_arg == 'virtual_headless':
launch_server(headless=True, **launch_args_for_internal_camoufox)
elif internal_mode_arg == 'debug':
launch_server(headless=False, **launch_args_for_internal_camoufox)
print(f'--- [内部Camoufox启动] camoufox.server.launch_server ({internal_mode_arg}模式) 调用已完成/阻塞。脚本将等待其结束。 ---', flush=True)
except Exception as e_internal_launch_final:
print(f'❌ 错误 (--internal-launch-mode): 执行 camoufox.server.launch_server 时发生异常: {e_internal_launch_final}', file=sys.stderr, flush=True)
traceback.print_exc(file=sys.stderr)
sys.exit(1)
sys.exit(0)
logger.info('🚀 Camoufox 启动器开始运行 🚀')
logger.info('=================================================')
ensure_auth_dirs_exist()
check_dependencies()
logger.info('=================================================')
deprecated_auth_state_path = os.path.join(os.path.dirname(__file__), 'auth_state.json')
if os.path.exists(deprecated_auth_state_path):
logger.warning(f'检测到已弃用的认证文件: {deprecated_auth_state_path}。此文件不再被直接使用。')
logger.warning("请使用调试模式生成新的认证文件,并按需管理 'auth_profiles' 目录中的文件。")
final_launch_mode = None
if args.debug:
final_launch_mode = 'debug'
elif args.headless:
final_launch_mode = 'headless'
elif args.virtual_display:
final_launch_mode = 'virtual_headless'
if platform.system() != 'Linux':
logger.warning('⚠️ --virtual-display 模式主要为 Linux 设计。在非 Linux 系统上,其行为可能与标准无头模式相同或导致 Camoufox 内部错误。')
else:
env_launch_mode = os.environ.get('LAUNCH_MODE', '').lower()
default_mode_from_env = None
default_interactive_choice = '1'
if env_launch_mode == 'headless':
default_mode_from_env = 'headless'
default_interactive_choice = '1'
elif env_launch_mode == 'debug' or env_launch_mode == 'normal':
default_mode_from_env = 'debug'
default_interactive_choice = '2'
elif env_launch_mode == 'virtual_display' or env_launch_mode == 'virtual_headless':
default_mode_from_env = 'virtual_headless'
default_interactive_choice = '3' if platform.system() == 'Linux' else '1'
logger.info('--- 请选择启动模式 (未通过命令行参数指定) ---')
if env_launch_mode and default_mode_from_env:
logger.info(f' 从 .env 文件读取到默认启动模式: {env_launch_mode} -> {default_mode_from_env}')
prompt_options_text = '[1] 无头模式, [2] 调试模式'
valid_choices = {'1': 'headless', '2': 'debug'}
if platform.system() == 'Linux':
prompt_options_text += ', [3] 无头模式 (虚拟显示 Xvfb)'
valid_choices['3'] = 'virtual_headless'
default_mode_name = valid_choices.get(default_interactive_choice, 'headless')
user_mode_choice = input_with_timeout(f' 请输入启动模式 ({prompt_options_text}; 默认: {default_interactive_choice} {default_mode_name}模式,{15}秒超时): ', 15) or default_interactive_choice
if user_mode_choice in valid_choices:
final_launch_mode = valid_choices[user_mode_choice]
else:
final_launch_mode = default_mode_from_env or 'headless'
logger.info(f"无效输入 '{user_mode_choice}' 或超时,使用默认启动模式: {final_launch_mode}模式")
logger.info(f"最终选择的启动模式: {final_launch_mode.replace('_', ' ')}模式")
logger.info('-------------------------------------------------')
if final_launch_mode == 'virtual_headless' and platform.system() == 'Linux':
logger.info('--- 检查 Xvfb (虚拟显示) 依赖 ---')
if not shutil.which('Xvfb'):
logger.error(' ❌ Xvfb 未找到。虚拟显示模式需要 Xvfb。请安装 (例如: sudo apt-get install xvfb) 后重试。')
sys.exit(1)
logger.info(' ✓ Xvfb 已找到。')
server_target_port = args.server_port
logger.info(f'--- 步骤 2: 检查 FastAPI 服务器目标端口 ({server_target_port}) 是否被占用 ---')
port_is_available = False
uvicorn_bind_host = '0.0.0.0'
if is_port_in_use(server_target_port, host=uvicorn_bind_host):
logger.warning(f' ❌ 端口 {server_target_port} (主机 {uvicorn_bind_host}) 当前被占用。')
pids_on_port = find_pids_on_port(server_target_port)
if pids_on_port:
logger.warning(f' 识别到以下进程 PID 可能占用了端口 {server_target_port}: {pids_on_port}')
if final_launch_mode == 'debug':
sys.stderr.flush()
choice = input_with_timeout(f' 是否尝试终止这些进程? (y/n, 输入 n 将继续并可能导致启动失败, 15s超时): ', 15).strip().lower()
if choice == 'y':
logger.info(' 用户选择尝试终止进程...')
all_killed = all((kill_process_interactive(pid) for pid in pids_on_port))
time.sleep(2)
if not is_port_in_use(server_target_port, host=uvicorn_bind_host):
logger.info(f' ✅ 端口 {server_target_port} (主机 {uvicorn_bind_host}) 现在可用。')
port_is_available = True
else:
logger.error(f' ❌ 尝试终止后,端口 {server_target_port} (主机 {uvicorn_bind_host}) 仍然被占用。')
else:
logger.info(' 用户选择不自动终止或超时。将继续尝试启动服务器。')
else:
logger.error(f' 无头模式下,不会尝试自动终止占用端口的进程。服务器启动可能会失败。')
else:
logger.warning(f' 未能自动识别占用端口 {server_target_port} 的进程。服务器启动可能会失败。')
if not port_is_available:
logger.warning(f'--- 端口 {server_target_port} 仍可能被占用。继续启动服务器,它将自行处理端口绑定。 ---')
else:
logger.info(f' ✅ 端口 {server_target_port} (主机 {uvicorn_bind_host}) 当前可用。')
port_is_available = True
logger.info('--- 步骤 3: 准备并启动 Camoufox 内部进程 ---')
captured_ws_endpoint = None
effective_active_auth_json_path = None
if args.active_auth_json:
logger.info(f" 尝试使用 --active-auth-json 参数提供的路径: '{args.active_auth_json}'")
candidate_path = os.path.expanduser(args.active_auth_json)
if os.path.isabs(candidate_path) and os.path.exists(candidate_path) and os.path.isfile(candidate_path):
effective_active_auth_json_path = candidate_path
else:
path_rel_to_cwd = os.path.abspath(candidate_path)
if os.path.exists(path_rel_to_cwd) and os.path.isfile(path_rel_to_cwd):
effective_active_auth_json_path = path_rel_to_cwd
else:
path_rel_to_script = os.path.join(os.path.dirname(__file__), candidate_path)
if os.path.exists(path_rel_to_script) and os.path.isfile(path_rel_to_script):
effective_active_auth_json_path = path_rel_to_script
elif not os.path.sep in candidate_path:
path_in_active = os.path.join(ACTIVE_AUTH_DIR, candidate_path)
if os.path.exists(path_in_active) and os.path.isfile(path_in_active):
effective_active_auth_json_path = path_in_active
else:
path_in_saved = os.path.join(SAVED_AUTH_DIR, candidate_path)
if os.path.exists(path_in_saved) and os.path.isfile(path_in_saved):
effective_active_auth_json_path = path_in_saved
if effective_active_auth_json_path:
logger.info(f' 将使用通过 --active-auth-json 解析的认证文件: {effective_active_auth_json_path}')
else:
logger.error(f"❌ 指定的认证文件 (--active-auth-json='{args.active_auth_json}') 未找到或不是一个文件。")
sys.exit(1)
else:
if final_launch_mode == 'debug':
logger.info(f' 调试模式: 扫描全目录并提示用户从可用认证文件中选择...')
else:
logger.info(f" --active-auth-json 未提供。检查 '{ACTIVE_AUTH_DIR}' 中的默认认证文件...")
try:
if os.path.exists(ACTIVE_AUTH_DIR):
active_json_files = sorted([f for f in os.listdir(ACTIVE_AUTH_DIR) if f.lower().endswith('.json') and os.path.isfile(os.path.join(ACTIVE_AUTH_DIR, f))])
if active_json_files:
effective_active_auth_json_path = os.path.join(ACTIVE_AUTH_DIR, active_json_files[0])
logger.info(f" 将使用 '{ACTIVE_AUTH_DIR}' 中按名称排序的第一个JSON文件: {os.path.basename(effective_active_auth_json_path)}")
else:
logger.info(f" 目录 '{ACTIVE_AUTH_DIR}' 为空或不包含JSON文件。")
else:
logger.info(f" 目录 '{ACTIVE_AUTH_DIR}' 不存在。")
except Exception as e_scan_active:
logger.warning(f" 扫描 '{ACTIVE_AUTH_DIR}' 时发生错误: {e_scan_active}", exc_info=True)
if final_launch_mode == 'debug':
available_profiles = []
for profile_dir_path_str, dir_label in [(ACTIVE_AUTH_DIR, 'active'), (SAVED_AUTH_DIR, 'saved')]:
if os.path.exists(profile_dir_path_str):
try:
filenames = sorted([f for f in os.listdir(profile_dir_path_str) if f.lower().endswith('.json') and os.path.isfile(os.path.join(profile_dir_path_str, f))])
for filename in filenames:
full_path = os.path.join(profile_dir_path_str, filename)
available_profiles.append({'name': f'{dir_label}/{filename}', 'path': full_path})
except OSError as e:
logger.warning(f" ⚠️ 警告: 无法读取目录 '{profile_dir_path_str}': {e}")
if available_profiles:
available_profiles.sort(key=lambda x: x['name'])
print('-' * 60 + '\n 找到以下可用的认证文件:', flush=True)
for i, profile in enumerate(available_profiles):
print(f" {i + 1}: {profile['name']}", flush=True)
print(' N: 不加载任何文件 (使用浏览器当前状态)\n' + '-' * 60, flush=True)
choice = input_with_timeout(f' 请选择要加载的认证文件编号 (输入 N 或直接回车则不加载, {args.auth_save_timeout}s超时): ', args.auth_save_timeout)
if choice.strip().lower() not in ['n', '']:
try:
choice_index = int(choice.strip()) - 1
if 0 <= choice_index < len(available_profiles):
selected_profile = available_profiles[choice_index]
effective_active_auth_json_path = selected_profile['path']
logger.info(f" 已选择加载认证文件: {selected_profile['name']}")
print(f" 已选择加载: {selected_profile['name']}", flush=True)
else:
logger.info(' 无效的选择编号或超时。将不加载认证文件。')
print(' 无效的选择编号或超时。将不加载认证文件。', flush=True)
except ValueError:
logger.info(' 无效的输入。将不加载认证文件。')
print(' 无效的输入。将不加载认证文件。', flush=True)
else:
logger.info(' 好的,不加载认证文件或超时。')
print(' 好的,不加载认证文件或超时。', flush=True)
print('-' * 60, flush=True)
else:
logger.info(' 未找到认证文件。将使用浏览器当前状态。')
print(' 未找到认证文件。将使用浏览器当前状态。', flush=True)
elif not effective_active_auth_json_path:
logger.error(f" ❌ {final_launch_mode} 模式错误: --active-auth-json 未提供,且活动认证目录 '{ACTIVE_AUTH_DIR}' 中未找到任何 '.json' 认证文件。请先在调试模式下保存一个或通过参数指定。")
sys.exit(1)
camoufox_internal_cmd_args = [PYTHON_EXECUTABLE, '-u', __file__, '--internal-launch-mode', final_launch_mode]
if effective_active_auth_json_path:
camoufox_internal_cmd_args.extend(['--internal-auth-file', effective_active_auth_json_path])
camoufox_internal_cmd_args.extend(['--internal-camoufox-os', simulated_os_for_camoufox])
camoufox_internal_cmd_args.extend(['--internal-camoufox-port', str(args.camoufox_debug_port)])
if args.internal_camoufox_proxy is not None:
camoufox_internal_cmd_args.extend(['--internal-camoufox-proxy', args.internal_camoufox_proxy])
camoufox_popen_kwargs = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'env': os.environ.copy()}
camoufox_popen_kwargs['env']['PYTHONIOENCODING'] = 'utf-8'
if sys.platform != 'win32' and final_launch_mode != 'debug':
camoufox_popen_kwargs['start_new_session'] = True
elif sys.platform == 'win32' and (final_launch_mode == 'headless' or final_launch_mode == 'virtual_headless'):
camoufox_popen_kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW
try:
logger.info(f" 将执行 Camoufox 内部启动命令: {' '.join(camoufox_internal_cmd_args)}")
def _find_free_port(start_port: int, max_tries: int = 20) -> int:
for p in range(start_port, start_port + max_tries):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 0)
s.bind(('127.0.0.1', p))
return p
except OSError:
continue
return start_port + max_tries
MAX_CAMOUFOX_RETRIES = 3
for camoufox_attempt in range(MAX_CAMOUFOX_RETRIES):
# Always find a free port (avoids EADDRINUSE on first and retry attempts)
free_port = _find_free_port(args.camoufox_debug_port + camoufox_attempt)
for i, arg in enumerate(camoufox_internal_cmd_args):
if arg == '--internal-camoufox-port' and i + 1 < len(camoufox_internal_cmd_args):
camoufox_internal_cmd_args[i + 1] = str(free_port)
break
if camoufox_attempt > 0:
logger.warning(f' 🔄 重试启动 Camoufox (第 {camoufox_attempt + 1}/{MAX_CAMOUFOX_RETRIES} 次, 端口: {free_port})...')
else:
logger.info(f' 使用端口 {free_port} 启动 Camoufox...')
camoufox_proc = subprocess.Popen(camoufox_internal_cmd_args, **camoufox_popen_kwargs)
logger.info(f' Camoufox 内部进程已启动 (PID: {camoufox_proc.pid})。正在等待 WebSocket 端点输出 (最长 {ENDPOINT_CAPTURE_TIMEOUT} 秒)...')
camoufox_output_q = queue.Queue()
camoufox_stdout_reader = threading.Thread(target=_enqueue_output, args=(camoufox_proc.stdout, 'stdout', camoufox_output_q, camoufox_proc.pid), daemon=True)
camoufox_stderr_reader = threading.Thread(target=_enqueue_output, args=(camoufox_proc.stderr, 'stderr', camoufox_output_q, camoufox_proc.pid), daemon=True)
camoufox_stdout_reader.start()
camoufox_stderr_reader.start()
ws_capture_start_time = time.time()
camoufox_ended_streams_count = 0
while time.time() - ws_capture_start_time < ENDPOINT_CAPTURE_TIMEOUT:
if camoufox_proc.poll() is not None:
logger.error(f' Camoufox 内部进程 (PID: {camoufox_proc.pid}) 在等待 WebSocket 端点期间已意外退出,退出码: {camoufox_proc.poll()}。')
break
try:
stream_name, line_from_camoufox = camoufox_output_q.get(timeout=0.2)
if line_from_camoufox is None:
camoufox_ended_streams_count += 1
logger.debug(f' [InternalCamoufox-{stream_name}-PID:{camoufox_proc.pid}] 输出流已关闭 (EOF)。')
if camoufox_ended_streams_count >= 2:
logger.info(f' Camoufox 内部进程 (PID: {camoufox_proc.pid}) 的所有输出流均已关闭。')
break
continue
log_line_content = f'[InternalCamoufox-{stream_name}-PID:{camoufox_proc.pid}]: {line_from_camoufox.rstrip()}'
if stream_name == 'stderr' or 'ERROR' in line_from_camoufox.upper() or '❌' in line_from_camoufox:
logger.warning(log_line_content)
else:
logger.info(log_line_content)
# Early exit on port conflict - no need to wait full timeout
if 'EADDRINUSE' in line_from_camoufox:
logger.warning(f' ⚡ 检测到端口冲突,立即终止并重试...')
break
ws_match = ws_regex.search(line_from_camoufox)
if ws_match:
captured_ws_endpoint = ws_match.group(1)
logger.info(f' ✅ 成功从 Camoufox 内部进程捕获到 WebSocket 端点: {captured_ws_endpoint[:40]}...')
break
except queue.Empty:
continue
if camoufox_stdout_reader.is_alive():
camoufox_stdout_reader.join(timeout=1.0)
if camoufox_stderr_reader.is_alive():
camoufox_stderr_reader.join(timeout=1.0)
if captured_ws_endpoint:
break
# Failed - kill process and retry
if camoufox_proc and camoufox_proc.poll() is None:
logger.warning(f' ❌ 未能在 {ENDPOINT_CAPTURE_TIMEOUT} 秒内捕获到 WebSocket 端点,终止进程 (PID: {camoufox_proc.pid})...')
camoufox_proc.terminate()
try:
camoufox_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
camoufox_proc.kill()
else:
logger.warning(f' ❌ Camoufox 内部进程已退出,未能捕获到 WebSocket 端点。')
if camoufox_attempt < MAX_CAMOUFOX_RETRIES - 1:
time.sleep(3)
if not captured_ws_endpoint:
logger.error(f' ❌ Camoufox 在 {MAX_CAMOUFOX_RETRIES} 次尝试后均未能输出 WebSocket 端点。')
cleanup()
sys.exit(1)
except Exception as e_launch_camoufox_internal:
logger.critical(f' ❌ 在内部启动 Camoufox 或捕获其 WebSocket 端点时发生致命错误: {e_launch_camoufox_internal}', exc_info=True)
cleanup()
sys.exit(1)
if args.helper:
logger.info(f' Helper 模式已启用,端点: {args.helper}')
os.environ['HELPER_ENDPOINT'] = args.helper
if effective_active_auth_json_path:
logger.info(f" 尝试从认证文件 '{os.path.basename(effective_active_auth_json_path)}' 提取 SAPISID...")
sapisid = ''
try:
with open(effective_active_auth_json_path, 'r', encoding='utf-8') as file:
auth_file_data = json.load(file)
if 'cookies' in auth_file_data and isinstance(auth_file_data['cookies'], list):
for cookie in auth_file_data['cookies']:
if isinstance(cookie, dict) and cookie.get('name') == 'SAPISID' and (cookie.get('domain') == '.google.com'):
sapisid = cookie.get('value', '')
break
except (FileNotFoundError, json.JSONDecodeError, KeyError, TypeError) as e:
logger.warning(f" ⚠️ 无法从认证文件 '{os.path.basename(effective_active_auth_json_path)}' 加载或解析SAPISID: {e}")
except Exception as e_sapisid_extraction:
logger.warning(f' ⚠️ 提取SAPISID时发生未知错误: {e_sapisid_extraction}')
if sapisid:
logger.info(f' ✅ 成功加载 SAPISID。将设置 HELPER_SAPISID 环境变量。')
os.environ['HELPER_SAPISID'] = sapisid
else:
logger.warning(f" ⚠️ 未能从认证文件 '{os.path.basename(effective_active_auth_json_path)}' 中找到有效的 SAPISID。HELPER_SAPISID 将不会被设置。")
if 'HELPER_SAPISID' in os.environ:
del os.environ['HELPER_SAPISID']
else:
logger.warning(f' ⚠️ Helper 模式已启用,但没有有效的认证文件来提取 SAPISID。HELPER_SAPISID 将不会被设置。')
if 'HELPER_SAPISID' in os.environ:
del os.environ['HELPER_SAPISID']
else:
logger.info(" Helper 模式已通过 --helper='' 禁用。")
if 'HELPER_ENDPOINT' in os.environ:
del os.environ['HELPER_ENDPOINT']
if 'HELPER_SAPISID' in os.environ:
del os.environ['HELPER_SAPISID']
logger.info('--- 步骤 4: 设置环境变量并准备启动 FastAPI/Uvicorn 服务器 ---')
if captured_ws_endpoint:
os.environ['CAMOUFOX_WS_ENDPOINT'] = captured_ws_endpoint
else:
logger.error(' 严重逻辑错误: WebSocket 端点未捕获,但程序仍在继续。')
sys.exit(1)
os.environ['LAUNCH_MODE'] = final_launch_mode
os.environ['SERVER_LOG_LEVEL'] = args.server_log_level.upper()
os.environ['SERVER_REDIRECT_PRINT'] = str(args.server_redirect_print).lower()
os.environ['DEBUG_LOGS_ENABLED'] = str(args.debug_logs).lower()
os.environ['TRACE_LOGS_ENABLED'] = str(args.trace_logs).lower()
if effective_active_auth_json_path:
os.environ['ACTIVE_AUTH_JSON_PATH'] = effective_active_auth_json_path
os.environ['AUTO_SAVE_AUTH'] = str(args.auto_save_auth).lower()
os.environ['AUTH_SAVE_TIMEOUT'] = str(args.auth_save_timeout)
os.environ['SERVER_PORT_INFO'] = str(args.server_port)
os.environ['STREAM_PORT'] = str(args.stream_port)
proxy_config = determine_proxy_configuration(args.internal_camoufox_proxy)
if proxy_config['stream_proxy']:
os.environ['UNIFIED_PROXY_CONFIG'] = proxy_config['stream_proxy']
logger.info(f" 设置统一代理配置: {proxy_config['source']}")
elif 'UNIFIED_PROXY_CONFIG' in os.environ:
del os.environ['UNIFIED_PROXY_CONFIG']
host_os_for_shortcut_env = None
camoufox_os_param_lower = simulated_os_for_camoufox.lower()
if camoufox_os_param_lower == 'macos':
host_os_for_shortcut_env = 'Darwin'
elif camoufox_os_param_lower == 'windows':
host_os_for_shortcut_env = 'Windows'
elif camoufox_os_param_lower == 'linux':
host_os_for_shortcut_env = 'Linux'
if host_os_for_shortcut_env:
os.environ['HOST_OS_FOR_SHORTCUT'] = host_os_for_shortcut_env
elif 'HOST_OS_FOR_SHORTCUT' in os.environ:
del os.environ['HOST_OS_FOR_SHORTCUT']
logger.info(f' 为 server.app 设置的环境变量:')
env_keys_to_log = ['CAMOUFOX_WS_ENDPOINT', 'LAUNCH_MODE', 'SERVER_LOG_LEVEL', 'SERVER_REDIRECT_PRINT', 'DEBUG_LOGS_ENABLED', 'TRACE_LOGS_ENABLED', 'ACTIVE_AUTH_JSON_PATH', 'AUTO_SAVE_AUTH', 'AUTH_SAVE_TIMEOUT', 'SERVER_PORT_INFO', 'HOST_OS_FOR_SHORTCUT', 'HELPER_ENDPOINT', 'HELPER_SAPISID', 'STREAM_PORT', 'UNIFIED_PROXY_CONFIG']
for key in env_keys_to_log:
if key in os.environ:
val_to_log = os.environ[key]
if key == 'CAMOUFOX_WS_ENDPOINT' and len(val_to_log) > 40:
val_to_log = val_to_log[:40] + '...'
if key == 'ACTIVE_AUTH_JSON_PATH':
val_to_log = os.path.basename(val_to_log)
logger.info(f' {key}={val_to_log}')
else:
logger.info(f' {key}= (未设置)')
logger.info(f'--- 步骤 5: 启动集成的 FastAPI 服务器 (监听端口: {args.server_port}) ---')
try:
uvicorn.run(app, host='0.0.0.0', port=args.server_port, log_config=None)
logger.info('Uvicorn 服务器已停止。')
except SystemExit as e_sysexit:
logger.info(f'Uvicorn 或其子系统通过 sys.exit({e_sysexit.code}) 退出。')
except Exception as e_uvicorn:
logger.critical(f'❌ 运行 Uvicorn 时发生致命错误: {e_uvicorn}', exc_info=True)
sys.exit(1)
logger.info('🚀 Camoufox 启动器主逻辑执行完毕 🚀')