forked from CJackHwang/AIstudioProxyAPI
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlaunch_camoufox.py
More file actions
executable file
·1913 lines (1757 loc) · 79.1 KB
/
launch_camoufox.py
File metadata and controls
executable file
·1913 lines (1757 loc) · 79.1 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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# launch_camoufox.py
import argparse
import asyncio
import atexit
import json
import logging
import logging.handlers
import os
import platform
import queue
import re
import select
import shutil
import signal
import socket
import subprocess
#!/usr/bin/env python3
# launch_camoufox.py
import sys
import threading
import time
import traceback
# --- New imports ---
from dotenv import load_dotenv
# Load .env file early to ensure subsequent modules get correct env vars
load_dotenv()
import uvicorn
from server import app # Import FastAPI app object from server.py
# -----------------
# Try importing launch_server (for internal launch mode, simulating Camoufox behavior)
try:
import camoufox.server
import camoufox.utils
from camoufox import (
DefaultAddons,
) # Assuming DefaultAddons contains AntiFingerprint
from camoufox.server import launch_server
# --- Monkeypatch Fix Start ---
# Fix "proxy: expected object, got null" error in camoufox.
# The launch_server function fails if 'proxy' is explicitly None in the config because
# camoufox.utils.launch_options returns 'proxy': None, which becomes null in JSON,
# causing the Node.js launcher to throw "expected object, got null".
_original_launch_options = camoufox.utils.launch_options
def _patched_launch_options(*args, **kwargs):
# Call original to get the full config dict (which includes defaults like proxy=None)
opts = _original_launch_options(*args, **kwargs)
# Remove 'proxy' key if it is None, so it doesn't get sent to the JS launcher
if "proxy" in opts and opts["proxy"] is None:
del opts["proxy"]
return opts
# Replace the function in camoufox.server module so launch_server uses our wrapper
camoufox.server.launch_options = _patched_launch_options
# --- Monkeypatch Fix End ---
except ImportError:
if "--internal-launch" in sys.argv or any(
arg.startswith("--internal-") for arg in sys.argv
): # Check for internal args broadly
print(
"❌ Fatal Error: Internal launch mode requires 'camoufox.server.launch_server' and 'camoufox.DefaultAddons' but failed to import.",
file=sys.stderr,
)
print(
" This usually means the 'camoufox' package is not installed correctly or not in PYTHONPATH.",
file=sys.stderr,
)
sys.exit(1)
else:
launch_server = None
DefaultAddons = None
# --- Configuration Constants ---
PYTHON_EXECUTABLE = sys.executable
ENDPOINT_CAPTURE_TIMEOUT = int(
os.environ.get("ENDPOINT_CAPTURE_TIMEOUT", "45")
) # Seconds (from dev)
DEFAULT_SERVER_PORT = int(
os.environ.get("DEFAULT_FASTAPI_PORT", "2048")
) # FastAPI server port
DEFAULT_CAMOUFOX_PORT = int(
os.environ.get("DEFAULT_CAMOUFOX_PORT", "9222")
) # Camoufox debug port (if needed for internal launch)
DEFAULT_STREAM_PORT = int(
os.environ.get("STREAM_PORT", "3120")
) # Stream proxy server port
DEFAULT_HELPER_ENDPOINT = os.environ.get(
"GUI_DEFAULT_HELPER_ENDPOINT", ""
) # External Helper endpoint
DEFAULT_AUTH_SAVE_TIMEOUT = int(
os.environ.get("AUTH_SAVE_TIMEOUT", "30")
) # Auth save timeout
DEFAULT_SERVER_LOG_LEVEL = os.environ.get(
"SERVER_LOG_LEVEL", "INFO"
) # Server log level
AUTH_PROFILES_DIR = os.path.join(os.path.dirname(__file__), "auth_profiles")
ACTIVE_AUTH_DIR = os.path.join(AUTH_PROFILES_DIR, "active")
SAVED_AUTH_DIR = os.path.join(AUTH_PROFILES_DIR, "saved")
EMERGENCY_AUTH_DIR = os.path.join(AUTH_PROFILES_DIR, "emergency")
HTTP_PROXY = os.environ.get("HTTP_PROXY", "")
HTTPS_PROXY = os.environ.get("HTTPS_PROXY", "")
LOG_DIR = os.path.join(os.path.dirname(__file__), "logs")
LAUNCHER_LOG_FILE_PATH = os.path.join(LOG_DIR, "launch_app.log")
# --- Global process handle ---
camoufox_proc = None
# --- Logger instance ---
logger = logging.getLogger("CamoufoxLauncher")
# --- WebSocket endpoint regex ---
ws_regex = re.compile(r"(ws://\S+)")
# --- Thread-safe output queue handler (_enqueue_output) (from dev - more robust error handling) ---
def _enqueue_output(
stream, stream_name, output_queue, process_pid_for_log="<UnknownPID>"
):
log_prefix = f"[ReadThread-{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 error: {decode_err}. Raw data (first 100 bytes): {line_bytes[:100]}"
)
output_queue.put(
(
stream_name,
f"[Decode Error: {decode_err}] {line_bytes[:100]}...\n",
)
)
except ValueError:
logger.debug(f"{log_prefix} ValueError (Stream might be closed).")
except Exception as e:
logger.error(
f"{log_prefix} Unexpected error reading stream: {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} Thread exiting.")
# --- Setup launcher logging system (setup_launcher_logging) (from dev - clears log on start) ---
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 Launcher Logging Initialized " + "=" * 30)
logger.info(f"Log level set to: {logging.getLevelName(logger.getEffectiveLevel())}")
logger.info(f"Log file path: {LAUNCHER_LOG_FILE_PATH}")
# --- Ensure auth directories exist (ensure_auth_dirs_exist) ---
def ensure_auth_dirs_exist():
logger.info("Checking and ensuring auth directories exist...")
try:
os.makedirs(ACTIVE_AUTH_DIR, exist_ok=True)
logger.info(f" ✓ Active auth directory ready: {ACTIVE_AUTH_DIR}")
os.makedirs(SAVED_AUTH_DIR, exist_ok=True)
logger.info(f" ✓ Saved auth directory ready: {SAVED_AUTH_DIR}")
os.makedirs(EMERGENCY_AUTH_DIR, exist_ok=True)
logger.info(f" ✓ Emergency auth directory ready: {EMERGENCY_AUTH_DIR}")
except Exception as e:
logger.error(f" ❌ Failed to create auth directories: {e}", exc_info=True)
sys.exit(1)
# --- Cleanup function (executed on exit) (from dev - more detailed logging and checks) ---
def cleanup():
global camoufox_proc
logger.info("--- Starting cleanup routine (launch_camoufox.py) ---")
if camoufox_proc and camoufox_proc.poll() is None:
pid = camoufox_proc.pid
logger.info(f"Terminating Camoufox internal subprocess (PID: {pid})...")
try:
if (
sys.platform != "win32"
and hasattr(os, "getpgid")
and hasattr(os, "killpg")
):
try:
pgid = os.getpgid(pid)
logger.info(
f" Sending SIGTERM to Camoufox process group (PGID: {pgid})..."
)
os.killpg(pgid, signal.SIGTERM)
except ProcessLookupError:
logger.info(
f" Camoufox process group (PID: {pid}) not found, attempting direct termination..."
)
camoufox_proc.terminate()
else:
if sys.platform == "win32":
logger.info(
f"🔥 [ID-02] Windows Force-Kill Strategy: Using immediate /F /T for process tree (PID: {pid})"
)
# [ID-02] Enhanced Windows Force-Kill: Immediate /F /T without grace period
result = subprocess.run(
["taskkill", "/F", "/T", "/PID", str(pid)],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
logger.info(
" ✅ Successfully force-killed Camoufox process tree via taskkill."
)
else:
logger.warning(
f" ⚠️ Taskkill /F /T returned code {result.returncode}: {result.stderr.strip()}"
)
# Fallback: try regular terminate
camoufox_proc.terminate()
else:
logger.info(f" Sending SIGTERM to Camoufox (PID: {pid})...")
camoufox_proc.terminate()
camoufox_proc.wait(timeout=5)
logger.info(
f" ✓ Camoufox (PID: {pid}) successfully terminated via SIGTERM."
)
except subprocess.TimeoutExpired:
logger.warning(
f" ⚠️ Camoufox (PID: {pid}) SIGTERM timed out. Sending SIGKILL to force terminate..."
)
if (
sys.platform != "win32"
and hasattr(os, "getpgid")
and hasattr(os, "killpg")
):
try:
pgid = os.getpgid(pid)
logger.info(
f" Sending SIGKILL to Camoufox process group (PGID: {pgid})..."
)
os.killpg(pgid, signal.SIGKILL)
except ProcessLookupError:
logger.info(
f" Camoufox process group (PID: {pid}) not found during SIGKILL, attempting direct force kill..."
)
camoufox_proc.kill()
else:
if sys.platform == "win32":
logger.info(
f" 🔥 [ID-02] Fallback: Force killing Camoufox process tree (PID: {pid})"
)
# [ID-02] Enhanced fallback force-kill with better error handling
result = subprocess.run(
["taskkill", "/F", "/T", "/PID", str(pid)],
capture_output=True,
text=True,
timeout=3,
)
if result.returncode == 0:
logger.info(
" ✅ Fallback: Successfully force-killed Camoufox process tree."
)
else:
logger.warning(
f" ⚠️ Fallback taskkill failed (code {result.returncode}): {result.stderr.strip()}"
)
else:
camoufox_proc.kill()
try:
camoufox_proc.wait(timeout=2)
logger.info(
f" ✓ Camoufox (PID: {pid}) successfully terminated via SIGKILL."
)
except Exception as e_kill:
logger.error(
f" ❌ Error waiting for Camoufox (PID: {pid}) SIGKILL completion: {e_kill}"
)
except Exception as e_term:
logger.error(
f" ❌ Error terminating 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 internal subprocess (PID: {camoufox_proc.pid if hasattr(camoufox_proc, 'pid') else 'N/A'}) ended previously, exit code: {camoufox_proc.poll()}."
)
camoufox_proc = None
else:
logger.info("Camoufox internal subprocess not running or already cleaned up.")
logger.info("--- Cleanup routine finished (launch_camoufox.py) ---")
atexit.register(cleanup)
def signal_handler(sig, frame):
from config.global_state import GlobalState
logger.info(
f"Received signal {signal.Signals(sig).name} ({sig}). Setting IS_SHUTTING_DOWN event..."
)
GlobalState.IS_SHUTTING_DOWN.set()
logger.info("Initiating exit procedure (Force Exit)...")
# [FIX-ZOMBIE] Run cleanup explicitly because os._exit skips atexit
try:
cleanup()
except Exception as e:
logger.error(f"Error during cleanup in signal handler: {e}")
logger.info("Exiting with os._exit(0)")
os._exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# --- Check dependencies (check_dependencies) (from dev - more comprehensive) ---
def check_dependencies():
logger.info("--- Step 1: Check Dependencies ---")
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' imported, but 'camoufox.DefaultAddons' not imported. Addon exclusion features might be limited."
)
missing_py_modules = []
dependencies_ok = True
if required_modules:
logger.info("Checking Python modules:")
for module_name, install_package_name in required_modules.items():
try:
__import__(module_name)
logger.info(f" ✓ Module '{module_name}' found.")
except ImportError:
logger.error(
f" ❌ Module '{module_name}' (package: '{install_package_name}') not found."
)
missing_py_modules.append(install_package_name)
dependencies_ok = False
else:
# Check if internal launch mode, if so, camoufox must be importable
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(
" ❌ Internal launch mode (--internal-*) requires 'camoufox' package, but import failed."
)
dependencies_ok = False
elif not is_any_internal_arg:
logger.info(
"Internal launch mode not requested and camoufox.server not imported, skipping 'camoufox' Python package check."
)
try:
from server import app as server_app_check
if server_app_check:
logger.info(" ✓ Successfully imported 'app' object from 'server.py'.")
except ImportError as e_import_server:
logger.error(
f" ❌ Failed to import 'app' object from 'server.py': {e_import_server}"
)
logger.error(" Please ensure 'server.py' exists and has no import errors.")
dependencies_ok = False
if not dependencies_ok:
logger.error("-------------------------------------------------")
logger.error("❌ Dependency check failed!")
if missing_py_modules:
logger.error(
f" Missing Python libraries: {', '.join(missing_py_modules)}"
)
logger.error(
f" Please try installing via pip: pip install {' '.join(missing_py_modules)}"
)
logger.error("-------------------------------------------------")
sys.exit(1)
else:
logger.info("✅ All launcher dependency checks passed.")
# --- Port check and cleanup functions (from dev - more robust) ---
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"Unknown error checking port {port} (host {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()]
# Check for localized "command not found" messages (e.g., "未找到命令" for Chinese systems)
elif process.returncode != 0 and (
"command not found" in stderr.lower() or "未找到命令" in stderr
):
logger.error("Command 'lsof' not found. Please ensure it is installed.")
elif process.returncode not in [0, 1]: # lsof returns 1 when not found
logger.warning(
f"Failed to execute lsof command (return code {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)) # Remove duplicates
elif process.returncode not in [0, 1]: # findstr returns 1 when not found
logger.warning(
f"Failed to execute netstat/findstr command (return code {process.returncode}): {stderr.strip()}"
)
else:
logger.warning(
f"Unsupported OS '{system_platform}' for finding processes on port."
)
except FileNotFoundError:
cmd_name = command.split()[0] if command else "Related tool"
logger.error(f"Command '{cmd_name}' not found.")
except subprocess.TimeoutExpired:
logger.error(f"Command '{command}' timed out.")
except Exception as e:
logger.error(f"Error finding processes on port {port}: {e}", exc_info=True)
return pids
def kill_process_interactive(pid: int) -> bool:
system_platform = platform.system()
success = False
logger.info(f" Attempting to terminate process 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} sent SIGTERM signal.")
success = True
else:
logger.warning(
f" PID {pid} SIGTERM failed: {result_term.stderr.strip() or result_term.stdout.strip()}. Attempting 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} sent SIGKILL signal.")
success = True
else:
logger.error(
f" ✗ PID {pid} SIGKILL failed: {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()
# Check for localized "Success" messages (e.g., "成功" for Chinese systems)
if result.returncode == 0 and (
"SUCCESS" in output.upper() or "成功" in output
):
logger.info(f" ✓ PID {pid} terminated via taskkill /F.")
success = True
# Check for localized "Not Found" messages (e.g., "找不到" for Chinese systems)
elif (
"could not find process" in error_output.lower()
or "找不到" in error_output
): # Process might have exited itself
logger.info(
f" PID {pid} not found during taskkill (might have exited)."
)
success = True # Considered success as target is port availability
else:
logger.error(
f" ✗ PID {pid} taskkill /F failed: {(error_output + ' ' + output).strip()}."
)
else:
logger.warning(
f" Unsupported OS '{system_platform}' for process termination."
)
except Exception as e:
logger.error(f" Unexpected error terminating PID {pid}: {e}", exc_info=True)
return success
# --- Input function with timeout (from dev - more robust Windows implementation) ---
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] = "" # Return empty string on error
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("\nInput timed out. Using default value.", flush=True)
return ""
return user_input_container[0] if user_input_container[0] is not None else ""
else: # Linux/macOS
readable_fds, _, _ = select.select([sys.stdin], [], [], timeout_seconds)
if readable_fds:
return sys.stdin.readline().strip()
else:
print("\nInput timed out. Using default value.", flush=True)
return ""
def get_proxy_from_gsettings():
"""
Retrieves the proxy settings from GSettings on Linux systems.
Returns a proxy string like "http://host:port" or None.
"""
def _run_gsettings_command(command_parts: list[str]) -> str | None:
"""Helper function to run gsettings command and return cleaned string output."""
try:
process_result = subprocess.run(
command_parts,
capture_output=True,
text=True,
check=False, # Do not raise CalledProcessError for non-zero exit codes
timeout=1, # Timeout for the subprocess call
)
if process_result.returncode == 0:
value = process_result.stdout.strip()
if value.startswith("'") and value.endswith(
"'"
): # Remove surrounding single quotes
value = value[1:-1]
# If after stripping quotes, value is empty, or it's a gsettings "empty" representation
if not value or value == "''" or value == "@as []" or value == "[]":
return None
return value
else:
return None
except subprocess.TimeoutExpired:
return None
except Exception: # Broad exception as per pseudocode
return None
proxy_mode = _run_gsettings_command(
["gsettings", "get", "org.gnome.system.proxy", "mode"]
)
if proxy_mode == "manual":
# Try HTTP proxy first
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 # Continue to HTTPS
# Try HTTPS proxy if HTTP not found or invalid
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:
# Note: Even for HTTPS proxy settings, the scheme for Playwright/requests is usually http://
return f"http://{https_host}:{https_port}"
except ValueError:
pass
return None
def determine_proxy_configuration(internal_camoufox_proxy_arg=None):
"""
Unified proxy configuration determination function
Order of priority: Command line args > Env vars > System settings
Args:
internal_camoufox_proxy_arg: --internal-camoufox-proxy command line argument value
Returns:
dict: Dictionary containing proxy configuration info
{
'camoufox_proxy': str or None, # Proxy used by Camoufox browser
'stream_proxy': str or None, # Upstream proxy used by stream proxy service
'source': str # Proxy source description
}
"""
result = {"camoufox_proxy": None, "stream_proxy": None, "source": "No Proxy"}
# 1. Prefer command line arguments
if internal_camoufox_proxy_arg is not None:
if internal_camoufox_proxy_arg.strip(): # Non-empty string
result["camoufox_proxy"] = internal_camoufox_proxy_arg.strip()
result["stream_proxy"] = internal_camoufox_proxy_arg.strip()
result["source"] = (
f"Command line arg --internal-camoufox-proxy: {internal_camoufox_proxy_arg.strip()}"
)
else: # Empty string, explicitly disable proxy
result["source"] = (
"Command line arg --internal-camoufox-proxy='' (explicitly disabled)"
)
return result
# 2. Try env var UNIFIED_PROXY_CONFIG (priority over HTTP/HTTPS_PROXY)
unified_proxy = os.environ.get("UNIFIED_PROXY_CONFIG")
if unified_proxy:
result["camoufox_proxy"] = unified_proxy
result["stream_proxy"] = unified_proxy
result["source"] = f"Env var UNIFIED_PROXY_CONFIG: {unified_proxy}"
return result
# 3. Try env var HTTP_PROXY
http_proxy = os.environ.get("HTTP_PROXY")
if http_proxy:
result["camoufox_proxy"] = http_proxy
result["stream_proxy"] = http_proxy
result["source"] = f"Env var HTTP_PROXY: {http_proxy}"
return result
# 4. Try env var HTTPS_PROXY
https_proxy = os.environ.get("HTTPS_PROXY")
if https_proxy:
result["camoufox_proxy"] = https_proxy
result["stream_proxy"] = https_proxy
result["source"] = f"Env var HTTPS_PROXY: {https_proxy}"
return result
# 5. Try system proxy settings (Linux only)
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 system proxy: {gsettings_proxy}"
return result
return result
# --- Main Execution Logic ---
if __name__ == "__main__":
# Check if internal launch call; if so, do not configure launcher logging
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="Launcher for Camoufox browser simulation and FastAPI proxy server.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# Internal arguments (from dev)
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
)
# User visible arguments (merged from dev and helper)
parser.add_argument(
"--server-port",
type=int,
default=DEFAULT_SERVER_PORT,
help=f"Port number for FastAPI server (Default: {DEFAULT_SERVER_PORT})",
)
parser.add_argument(
"--stream-port",
type=int,
default=DEFAULT_STREAM_PORT, # Read default from .env
help=(
f"Port for stream proxy server. "
f"Provide --stream-port=0 to disable. Default: {DEFAULT_STREAM_PORT}"
),
)
parser.add_argument(
"--helper",
type=str,
default=DEFAULT_HELPER_ENDPOINT, # Use default value
help=(
f"Helper server getStreamResponse endpoint (e.g., http://127.0.0.1:3121/getStreamResponse). "
f"Provide empty string (e.g., --helper='') to disable. Default: {DEFAULT_HELPER_ENDPOINT}"
),
)
parser.add_argument(
"--camoufox-debug-port", # from dev
type=int,
default=DEFAULT_CAMOUFOX_PORT,
help=f"Debug port number for internal Camoufox instance (Default: {DEFAULT_CAMOUFOX_PORT})",
)
mode_selection_group = (
parser.add_mutually_exclusive_group()
) # from dev (more options)
mode_selection_group.add_argument(
"--debug",
action="store_true",
help="Start debug mode (browser UI visible, allows interactive auth)",
)
mode_selection_group.add_argument(
"--headless",
action="store_true",
help="Start headless mode (no browser UI, requires saved auth file)",
)
mode_selection_group.add_argument(
"--virtual-display",
action="store_true",
help="Start headless mode with virtual display (Xvfb, Linux only)",
) # from dev
# --camoufox-os argument removed, will be auto-detected and set by script
parser.add_argument( # from dev
"--active-auth-json",
type=str,
default=None,
help="[Headless/Debug Optional] Path to active auth JSON file (in auth_profiles/active/ or saved/, or absolute path). "
"If not provided, headless mode uses latest in active/, debug mode prompts or uses none.",
)
parser.add_argument( # from dev
"--auto-save-auth",
action="store_true",
help="[Debug Mode] Automatically prompt to save new auth state after successful login if no auth file was loaded.",
)
parser.add_argument(
"--save-auth-as",
type=str,
default=None,
help="[Debug Mode] Specify filename for saving new auth file (without .json suffix).",
)
parser.add_argument( # from dev
"--auth-save-timeout",
type=int,
default=DEFAULT_AUTH_SAVE_TIMEOUT,
help=f"[Debug Mode] Timeout (seconds) for auto-save auth or filename input. Default: {DEFAULT_AUTH_SAVE_TIMEOUT}",
)
parser.add_argument(
"--exit-on-auth-save",
action="store_true",
help="[Debug Mode] Automatically close launcher and all processes after successful auth save via UI.",
)
parser.add_argument(
"--auto-auth-rotation-on-startup",
type=str,
default=os.environ.get("AUTO_AUTH_ROTATION_ON_STARTUP", "false"),
help="Enable auto-rotation to saved/emergency profiles on startup if active profile is missing (true/false).",
)
# Logging related arguments (from dev)
parser.add_argument(
"--server-log-level",
type=str,
default=DEFAULT_SERVER_LOG_LEVEL,
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
help=f"Log level for server.py. Default: {DEFAULT_SERVER_LOG_LEVEL}",
)
parser.add_argument(
"--server-redirect-print",
action="store_true",
help="Redirect print output in server.py to its logging system. Default is not to redirect so input() prompts in debug mode are visible.",
)
parser.add_argument(
"--debug-logs",
action="store_true",
help="Enable DEBUG level detailed logs inside server.py (env DEBUG_LOGS_ENABLED).",
)
parser.add_argument(
"--trace-logs",
action="store_true",
help="Enable TRACE level more detailed logs inside server.py (env TRACE_LOGS_ENABLED).",
)
args = parser.parse_args()
# Mark if --server-redirect-print was explicitly provided via CLI
args.server_redirect_print_from_cli = "--server-redirect-print" in sys.argv
# --- Auto-detect current system and set Camoufox OS simulation ---
# This variable will be used for internal Camoufox launch and HOST_OS_FOR_SHORTCUT
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": # macOS
simulated_os_for_camoufox = "macos"
else:
simulated_os_for_camoufox = "linux" # Default fallback for unknown systems
logger.warning(
f"Unrecognized system '{current_system_for_camoufox}'. Camoufox OS simulation defaulting to: {simulated_os_for_camoufox}"
)
logger.info(
f"Based on system '{current_system_for_camoufox}', Camoufox OS simulation auto-set to: {simulated_os_for_camoufox}"
)
# --- Handle internal Camoufox launch logic (if script called as subprocess) (from dev) ---
if args.internal_launch_mode:
if not launch_server or not DefaultAddons:
print(
"❌ Fatal Error (--internal-launch-mode): camoufox.server.launch_server or camoufox.DefaultAddons unavailable. Script cannot proceed.",
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
# Use unified proxy configuration determination logic
proxy_config = determine_proxy_configuration(args.internal_camoufox_proxy)
actual_proxy_to_use = proxy_config["camoufox_proxy"]
print(
f"--- [Internal Camoufox Launch] Proxy Config: {proxy_config['source']} ---",
flush=True,
)
camoufox_proxy_internal = actual_proxy_to_use # Update variable for later use
camoufox_os_internal = args.internal_camoufox_os
print(
f"--- [Internal Camoufox Launch] Mode: {internal_mode_arg}, Auth File: {os.path.basename(auth_file) if auth_file else 'None'}, "
f"Camoufox Port: {camoufox_port_internal}, Proxy: {camoufox_proxy_internal or 'None'}, Sim OS: {camoufox_os_internal} ---",
flush=True,
)
print(
"--- [Internal Camoufox Launch] Calling camoufox.server.launch_server ... ---",
flush=True,
)
try:
launch_args_for_internal_camoufox = {
"port": camoufox_port_internal,
"addons": [],
# "proxy": camoufox_proxy_internal, # Removed
"exclude_addons": [
DefaultAddons.UBO
], # Assuming DefaultAddons.UBO exists
"window": (1440, 900),
}
# Correct way to add proxy
if camoufox_proxy_internal: # If proxy string exists and is not empty
launch_args_for_internal_camoufox["proxy"] = {
"server": camoufox_proxy_internal
}
# If camoufox_proxy_internal is None or empty, "proxy" key won't be added.
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"❌ Internal Camoufox Launch Error: Invalid values in camoufox_os_internal list: {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"❌ Internal Camoufox Launch Error: Invalid camoufox_os_internal value: '{camoufox_os_internal}'",