-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCore.py
More file actions
1080 lines (898 loc) Β· 41.4 KB
/
Core.py
File metadata and controls
1080 lines (898 loc) Β· 41.4 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 python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
#
# FastFileLink CLI - Fast, no-fuss file sharing
# Copyright (C) 2025-2026 FastFileLink contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import platform
import sys
import os
import argparse
import signal
import json
import atexit
import time
if 'Cosmopolitan' in platform.version():
if sys.prefix not in sys.path:
sys.path.insert(0, sys.prefix)
if os.getenv('PYAPP'):
BASE_DIR = os.path.dirname(__file__)
if BASE_DIR not in sys.path:
sys.path.insert(0, BASE_DIR)
# This line must be the first to ensure all stubs working.
import bases.Stub # isort:skip
import requests
import certifi
import segno
from functools import partial
from bases.Kernel import UIDGenerator, getLogger, FFLEvent
from bases.Server import createServer, DownloadHandler, ServerConfig
from bases.Tunnel import TunnelRunner, TunnelUnavailableError
from bases.WebRTC import DummyWebRTCManager, WebRTCManager, WebRTCDownloader
from bases.Settings import DEFAULT_STATIC_ROOT, SettingsGetter, ExecutionMode
from bases.CLI import (
configureCLIParser, processGlobalArguments, processArgumentsAndCommands, loadEnvFile, preprocessArguments
)
from bases.Progress import Progress
from bases.Utils import (
copy2Clipboard, flushPrint, formatSize, getLogger, getAvailablePort, sendException, validateCompatibleWithServer,
ProxyConfig
)
from bases.Readers import SourceReader, FolderChangedException, SourceReaderProgressReporter
from bases.FileSystems import ExcludeFilter
from bases.Tor import verifyTorProxy
from bases.Auth import RecipientAuth, PUBKEY_PUBLIC_EXT, PUBKEY_PRIVATE_EXT
from bases.crypto import CryptoInterface
from bases.VFS import VFSServer
from bases.I18n import _
logger = getLogger(__name__)
class ScanFolderProgressReporter(SourceReaderProgressReporter):
"""Render SourceReader preprocessing progress for CLI and GUI modes."""
@staticmethod
def create(path):
"""Create a reader preprocessing reporter only for folder-like inputs."""
if path == "-":
return None
if isinstance(path, list):
return ScanFolderProgressReporter(useBar=isCLIMode())
if isinstance(path, str) and not path.startswith("vfs://") and os.path.isdir(path):
return ScanFolderProgressReporter(useBar=isCLIMode())
return None
def __init__(self, useBar: bool):
self._progress = Progress(
totalSize=None,
sizeFormatter=lambda value: f"{int(value):,}",
loggerCallback=lambda text: None,
useBar=useBar,
description=_('Scanning folder'),
unit='entry',
unitScale=False,
leave=False
)
self._useBar = useBar
self._started = False
self._count = 0
self._guiLabel = _('Scanning folder. Calculating size may take some time...')
def start(self, operation: str, total=None, unit: str = "items") -> None:
self._started = True
self._count = 0
if not self._useBar:
flushPrint(self._guiLabel)
def advance(self, amount: int = 1, processedBytes=None) -> None:
if not self._started:
return
self._count += amount
extraText = ""
if processedBytes is not None and processedBytes > 0:
extraText = _('Scanned {size}').format(size=formatSize(processedBytes))
self._progress.update(self._count, extraText=extraText)
def finish(self) -> None:
if not self._started:
return
self._started = False
if self._useBar:
self._progress.finishBar(complete=False)
def setupGracefulShutdown():
"""Setup signal handlers for graceful shutdown on multiple Ctrl+C and cleanup on exit"""
context = {'shutdownInProgress': False, 'shutdownEventTriggered': False}
def triggerShutdownEvent():
"""Trigger application shutdown event for cleanup (called on exit)"""
if not context['shutdownEventTriggered']:
context['shutdownEventTriggered'] = True
try:
FFLEvent.applicationShutdown.trigger()
except Exception as e:
# Fail silently - don't prevent exit
logger.debug(f'Shutdown event trigger error: {str(e)}')
def signalHandler(signum, frame):
if context['shutdownInProgress']:
# Second Ctrl+C - force immediate exit without cleanup messages
os._exit(0)
else:
# First Ctrl+C - set flag and raise KeyboardInterrupt normally
context['shutdownInProgress'] = True
raise KeyboardInterrupt()
# Register signal handler for SIGINT (Ctrl+C)
signal.signal(signal.SIGINT, signalHandler)
# Register shutdown event trigger on exit
atexit.register(triggerShutdownEvent)
def detectExecutionEnvironment():
"""
Detect the current execution environment (Python script, PyInstaller, PyApp, Cosmopolitan).
Returns:
tuple: (ExecutionMode, baseDir, exePath) where:
- ExecutionMode: The detected execution mode
- baseDir: Base directory for the application
- exePath: Path to the actual executable (wrapper for PyApp, sys.executable for others)
"""
baseDir = os.path.dirname(os.path.abspath(__file__))
exePath = sys.executable # Default to sys.executable
# Execute in PyInstaller .exe
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# NSIS sets EXE_PATH environment variable
exePath = os.getenv('EXE_PATH', sys.executable)
return ExecutionMode.EXECUTABLE, sys._MEIPASS, exePath
# Execute in PyApp exe
elif os.getenv('PYAPP'):
# PyApp extracts and runs the code, so sys.executable points to the extracted Python
exePath = os.getenv('PYAPP', sys.executable)
return ExecutionMode.EXECUTABLE, baseDir, exePath
# Execute in Cosmopolitan libc
elif os.__file__.startswith('/zip') or 'Cosmopolitan' in platform.version():
# Check if running from zip
if bases.Stub.__file__.startswith('/zip'):
baseDir = '/zip'
return ExecutionMode.COSMOPOLITAN_LIBC, baseDir, exePath
# Pure Python execution
else:
# Go up one level from bases/ to get project root
return ExecutionMode.PURE_PYTHON, baseDir, exePath
def setupSettings(logger):
# Load .env file early (before any configuration or addon loading)
loadEnvFile()
# Detect execution environment (PyInstaller, PyApp, Cosmopolitan, or pure Python)
exeMode, baseDir, exePath = detectExecutionEnvironment()
if platform.system().lower() != 'windows':
os.environ["SSL_CERT_FILE"] = certifi.where()
staticRoot = os.path.join(baseDir, DEFAULT_STATIC_ROOT)
return SettingsGetter(
exeMode=exeMode,
baseDir=baseDir,
staticRoot=staticRoot,
platform=platform.system(),
exePath=exePath,
)
# Initialize SettingsGetter
settingsGetter = setupSettings(logger)
featureManager = settingsGetter.getFeatureManager()
# Setup graceful shutdown handling
setupGracefulShutdown()
def isCLIMode():
"""Check if we should run in CLI mode (backward compatibility)"""
return settingsGetter.isCLIMode()
def determineAuthentication(args):
authPassword = args.authPassword or os.getenv('FFL_AUTH_PASSWORD')
authUser = args.authUser if authPassword else None
return authUser, authPassword
def promptAuthEnabled(authUser, authPassword):
flushPrint(_('Authentication enabled - Username: {authUser}\n').format(authUser=authUser))
def promptRecipientAuthInfo(recipientAuth):
if recipientAuth.requiresPickup():
flushPrint(_('Pickup code: {code}\n').format(code=recipientAuth.pickupCode))
def onShareLinkCreate(args, link, filePath, fileSize, tunnelType, e2ee, reader, recipientAuth=None, **kwargs):
"""Handle share link creation - invite, QR code, and JSON writing"""
# Handle --invite flag
if args.invite:
flushPrint(_('Opening invite page in browser...'))
featureManager.invite(link)
# Handle --qr flag
if args.qr:
try:
qr = segno.make(link)
# Check if args.qr is a file path (string) or True (terminal display)
if isinstance(args.qr, str):
# Save QR code to file
qr.save(args.qr, scale=5)
flushPrint(_('QR code saved to: {filePath}').format(filePath=args.qr))
else:
# Display in terminal
flushPrint(_('\nQR Code:\n'))
qr.terminal(compact=True)
flushPrint('')
except Exception as e:
flushPrint(_('Error generating QR code: {error}').format(error=e))
# It's ok only not generate QR code.
# Handle --json flag
if args.json:
user = featureManager.user
# Get content name (VFS mode has reader=None, use basename)
contentName = reader.contentName if reader else os.path.basename(filePath)
pickupCode = recipientAuth.pickupCode if recipientAuth and recipientAuth.requiresPickup() else None
pubkeyEnabled = recipientAuth.requiresPubkey() if recipientAuth else False
outputData = {
"file": filePath,
"content_name": contentName, # Download filename (may be custom via --name)
"file_size": fileSize if fileSize is not None else -1, # -1 indicates unknown size
"upload_mode": "server" if args.upload else "p2p",
"tunnel_type": tunnelType or "default",
"link": link,
"e2ee": e2ee,
"pickup_code": pickupCode,
"pubkey_enabled": pubkeyEnabled,
"user": {
"user": user.name,
"email": user.email,
"level": user.level,
"points": user.points,
"serial_number": user.serialNumber
}
}
try:
with open(args.json, 'w', encoding='utf-8') as f:
json.dump(outputData, f, indent=2)
flushPrint(_('Sharing information saved to {jsonFile}').format(jsonFile=args.json))
except Exception as e:
flushPrint(_('Failed to write JSON file: {error}').format(error=e))
sendException(logger, e)
def generateUid():
# Get UIDGenerator from FeatureManager
uidGeneratorClass = UIDGenerator
if settingsGetter.hasFeaturesSupport():
uidGeneratorClass = featureManager.getUIDGeneratorClass(uidGeneratorClass)
uidGenerator = uidGeneratorClass()
return uidGenerator.generate()
def processUpload(args, reader, proxyConfig: ProxyConfig):
from addons.Upload import (
createUploadStrategy,
UploadPredicate,
UploadResult,
confirmUploadPoints,
PauseUploadError,
ResumeNotSupportedError,
PauseNotSupportedError,
E2EENotSupportedError,
UploadParameterMismatchError,
ResumeValidationError,
)
authUser, authPassword = determineAuthentication(args)
recipientAuth = RecipientAuth.create(
args.recipientAuth,
getattr(args, 'recipientPublicKey', None),
getattr(args, 'pickupCode', None),
recipientEmail=getattr(args, 'recipientEmail', None),
)
def handlePublishPrompt(uploadResult):
if authPassword:
promptAuthEnabled(authUser, authPassword)
if recipientAuth.isEnabled():
promptRecipientAuthInfo(recipientAuth)
publishPromptCallback = handlePublishPrompt if (authPassword or recipientAuth.isEnabled()) else None
# Inform GUI users about upload resumability
if not isCLIMode():
flushPrint(_('You can stop the upload at any time and resume it later.\n'))
class UploadAbortResult(UploadResult):
def __init__(self, exitCode=0, *args, **kws):
super().__init__(*args, **kws)
self.exitCode = exitCode
def doUpload(uploadMethod, uid, link=None, resume=False):
uploadResult = None
try:
extraArgs = {}
if args.alias:
extraArgs['alias'] = args.alias
if authPassword:
extraArgs['authUser'] = authUser
extraArgs['authPassword'] = authPassword
if recipientAuth.isEnabled():
extraArgs['pickupCode'] = recipientAuth.pickupCode
if recipientAuth.requiresPubkey():
extraArgs['recipientPublicKey'] = recipientAuth.publicKeyPems
if recipientAuth.requiresEmail():
extraArgs['recipientEmail'] = recipientAuth.recipientEmails
if getattr(args, 'receipt', None) is not None:
extraArgs['receipt'] = args.receipt
if getattr(args, 'receiptConfirm', None) is not None:
extraArgs['receiptConfirm'] = args.receiptConfirm
if resume:
# Resume mode: use resume() instead of tell()
response = uploadMethod.resume(args.file, args.upload, reader=reader, fileName=args.fileName)
else:
# Normal mode: pass reader to tell() to avoid rebuilding
response = uploadMethod.tell(
uid, args.file, args.upload, link=link, reader=reader, fileName=args.fileName, **extraArgs
)
if response['success']:
# Pass pause percentage if specified
pausePercentage = args.pause
uploadResult = uploadMethod.execute(response, args.file, pausePercentage=pausePercentage, **extraArgs)
else:
message = response['message']
sendException(logger, message, errorPrefix="Server temporarily cannot process this file")
except PauseUploadError as e:
# Handle pause like Ctrl+C - print message and re-raise for elegant exit
flushPrint(_(
'Upload paused at {percentage:.1f}% ({completedChunks}/{totalChunks} chunks completed)'
).format(percentage=e.percentage, completedChunks=e.completedChunks, totalChunks=e.totalChunks))
flushPrint(_('Use --resume to continue upload'))
return UploadAbortResult(exitCode=0)
except ResumeNotSupportedError as e:
# Handle resume not supported by upload strategy (e.g., PullUpload)
sendException(
logger, _(
'Resume is only available for direct upload mode (without external tunnels).\n'
'Please restart the upload without --resume to upload the file normally.'
),
errorPrefix=None
)
return UploadAbortResult(exitCode=1)
except PauseNotSupportedError as e:
# Handle pause not supported by upload strategy (e.g., PullUpload)
sendException(
logger, _(
'Pause functionality is only available for direct upload mode '
'(without external tunnels).\n'
'Please restart the upload without --pause to upload the file normally.'
),
errorPrefix=None
)
return UploadAbortResult(exitCode=1)
except E2EENotSupportedError as e:
# Handle E2EE not supported by upload strategy (e.g., PullUpload)
sendException(
logger, _(
'End-to-end encryption is only available for direct upload mode '
'(without external tunnels).\n'
'Please restart the upload without --e2ee to upload the file normally.'
),
errorPrefix=None
)
return UploadAbortResult(exitCode=1)
except UploadParameterMismatchError as e:
# Handle parameter mismatch during resume
sendException(
logger, _(
'Cannot resume: {parameter} mismatch.\n'
'Original upload used "{originalValue}" but "{requestedValue}" was requested.\n'
'Please use the same parameters as the original upload.'
).format(parameter=e.parameter, originalValue=e.originalValue,
requestedValue=e.requestedValue),
errorPrefix=None
)
return UploadAbortResult(exitCode=1)
except ResumeValidationError as e:
# Handle resume validation failures (file changed, expired, corrupted)
sendException(logger, e, action=e.action, errorPrefix=None)
return UploadAbortResult(exitCode=1)
except KeyboardInterrupt:
raise
except Exception as e:
sendException(logger, e, errorPrefix="Server temporarily cannot process this file")
return UploadAbortResult(exitCode=1)
return uploadResult
class UploadProcessor:
def __init__(self, uploadMethod, uid, exitCode=None):
self.uploadMethod = uploadMethod
self.uid = uid
self.exitCode = exitCode
self.uploadResult = None
def isDone(self):
return self.exitCode is not None
def getDownloadHandlerClass(self, link, uid):
self.uploadResult = doUpload(self.uploadMethod, uid, link, resume=args.resume)
if self.uploadResult and isinstance(self.uploadResult, UploadAbortResult):
return self.uploadResult.exitCode
if self.uploadResult and self.uploadResult.success:
return self.uploadResult.requestHandler
else:
raise RuntimeError(self.uploadResult.message if self.uploadResult else _('Unknown error'))
def publish(self):
if self.uploadResult and self.uploadResult.success:
self.uploadMethod.publish(self.uploadResult, additionalPromptCallback=publishPromptCallback)
return self.uploadResult.link
return None
e2eeEnabled = args.e2ee
size = reader.size # None means unknown size (e.g., stdin)
# Regenerate UID for upload.
uid = generateUid()
# Create upload strategy (only if Upload addon is available)
user = featureManager.user
uploadMethod = createUploadStrategy(user.serialNumber, e2eeEnabled=e2eeEnabled)
# Check upload predicate
predicateResult = uploadMethod.predicate(reader.file, size, user.points, args.upload)
if not predicateResult.canUpload:
if predicateResult.type == UploadPredicate.INVALIDATE_POINTS:
flushPrint(_(
'Your user points are not enough. Please top up on our website (https://fastfilelink.com/).'
))
logger.error(f'User {user.email} points not enough.')
else:
flushPrint(predicateResult.message or _('Upload not allowed.'))
sendException(logger, predicateResult.message or 'Upload predicate failed.')
return UploadProcessor(uploadMethod=None, uid=uid, exitCode=1)
if not confirmUploadPoints(
fileName=reader.contentName,
fileSize=size,
retentionPeriod=args.upload,
cost=predicateResult.cost,
currentPoints=user.points,
autoConfirm=getattr(args, 'yes', False)
):
flushPrint(_('Upload cancelled before transfer started.'))
return UploadProcessor(uploadMethod=None, uid=uid, exitCode=0)
while uploadMethod:
if uploadMethod.requireServer():
return UploadProcessor(uploadMethod=uploadMethod, uid=uid)
# Try upload with current strategy
uploadResult = doUpload(uploadMethod, uid, resume=args.resume)
if uploadResult and isinstance(uploadResult, UploadAbortResult):
return UploadProcessor(uploadMethod=uploadMethod, uid=uid, exitCode=uploadResult.exitCode)
if uploadResult and uploadResult.success:
uploadMethod.publish(uploadResult, additionalPromptCallback=publishPromptCallback)
FFLEvent.shareLinkCreate.trigger(
link=uploadResult.link,
filePath=args.file,
fileSize=size,
tunnelType=None,
e2ee=e2eeEnabled,
reader=reader,
recipientAuth=recipientAuth,
)
return UploadProcessor(uploadMethod=uploadMethod, uid=uid, exitCode=0)
else:
# Try fallback strategy if available
uploadMethod = uploadMethod.createFallbackStrategy()
noRetry = os.environ.get('UPLOAD_NO_RETRY') == 'True'
# Resume can't retry, it only can be done with original upload method.
# TODO: We can design a ResumeUploadMismatchError to make sure using right method to resume.
if uploadMethod and not noRetry and not args.resume:
flushPrint(_('Retrying...\n'))
return UploadProcessor(uploadMethod=uploadMethod, uid=None) # no uid to regenerate
else:
sendException(logger, uploadResult.message if uploadResult else 'Upload failed')
return UploadProcessor(uploadMethod=uploadMethod, uid=uid, exitCode=1)
def processVFS(args):
# VFS mode requires file or folder (already validated in CLI.py)
if not os.path.isfile(args.file) and not os.path.isdir(args.file):
flushPrint(_('Error: VFS mode requires a file or folder path'))
return 1
# Get port (VFS server uses specified port or random)
vfsPort = args.port if args.port else 0
authUser, authPassword = determineAuthentication(args)
# Start VFS server (supports both files and folders)
vfsServer = VFSServer(args.file, host="127.0.0.1", port=vfsPort, authUser=authUser, authPassword=authPassword)
vfsServer.start()
vfsUri = vfsServer.clientUri
flushPrint(_("VFS server started successfully!\n"))
# Show appropriate message based on file or folder
shareType = 'file' if os.path.isfile(args.file) else 'folder'
flushPrint(_("Please share the URI below to access the {type} remotely:\n").format(type=shareType))
# Show auth info if enabled (password enables auth)
if authPassword:
promptAuthEnabled(authUser, authPassword)
# Never include password in URI (security issue)
flushPrint(f"{vfsUri}\n")
copy2Clipboard(vfsUri)
flushPrint(_('VFS server is running on loopback (127.0.0.1) - only accessible from this machine.'))
flushPrint(_('Please keep the application running for remote access.'))
if isCLIMode():
flushPrint(_('Press Ctrl+C to stop the server.\n'))
else:
flushPrint('')
FFLEvent.shareLinkCreate.trigger(
link=vfsUri,
filePath=args.file,
fileSize=None, # VFS TAR size unknown
tunnelType="vfs",
e2ee=False, # VFS doesn't support E2EE yet
reader=None,
)
try:
# Keep server running until interrupted
while True:
time.sleep(1)
except KeyboardInterrupt:
flushPrint(_('\nShutting down VFS server...'))
FFLEvent.applicationInterrupted.trigger(reason='user-interrupt')
finally:
vfsServer.stop()
flushPrint(_('VFS server stopped.'))
return 0
# Main business logic - shared between CLI and GUI modes
def processSharing(args, proxyConfig: ProxyConfig = None):
"""
Process the file sharing request with the given arguments
Args:
args: Parsed command-line arguments
proxyConfig: Optional proxy configuration dict from parseProxyString()
Returns:
int: Exit code (0 for success, 1 for error)
"""
if not getattr(args, 'file', None):
flushPrint(_('Error: Please select a file or folder to share'))
return 1
# Argument predicates.
# Allow "-" for stdin and vfs:// URIs, otherwise check file existence.
# Lists are already validated path-by-path in CLI.py.
isLocalPath = not isinstance(args.file, list) and args.file != "-" and not args.file.startswith("vfs://")
if isLocalPath and not os.path.exists(args.file):
flushPrint(_('{file} does not exist!').format(file=f'"{args.file}"'))
return 1
# Subscribe handler for share link creation with bound args
handler = partial(onShareLinkCreate, args)
FFLEvent.shareLinkCreate.subscribe(handler)
try:
if args.upload:
if not settingsGetter.hasUploadSupport():
flushPrint(_('Error: Upload functionality requires Upload addon (addons/Upload.py)'))
return 1
# Use FeatureManager to check upload permission
if not featureManager.allowUpload():
flushPrint(featureManager.getUploadUnavailableMessage())
return 1
# registered or for testing
if not featureManager.isRegisteredUser():
sendException(logger, _('User email address has been lost'))
return 1
# Handle VFS mode (--vfs): Start VFSServer instead of tunnelRunner
if args.vfs:
return processVFS(args)
if not isCLIMode():
flushPrint(_('If a firewall notification appears, please allow the application to connect.\n'))
# Hint user about folder content change detection for strict mode
if isLocalPath and os.path.isdir(args.file):
flushPrint(_('π Sharing folder as ZIP - please keep folder contents unchanged during transfer\n'))
# Get size using Reader abstraction (supports both files and folders)
# Reader will use its own default if args.fileName is None
excludeFilter = ExcludeFilter(args.exclude) if args.exclude else None
progressReporter = ScanFolderProgressReporter.create(args.file)
reader = SourceReader.build(
args.file, fileName=args.fileName, excludeFilter=excludeFilter, progressReporter=progressReporter
)
size = reader.size # None means unknown size (e.g., stdin)
# Show E2EE status if enabled (first line, before establishing tunnel)
e2eeEnabled = args.e2ee
if e2eeEnabled:
flushPrint(_('π End-to-end encryption enabled\n'))
# Detect if Tor proxy is being used (robust verification)
torDetected = False
if proxyConfig:
try:
if verifyTorProxy(proxyConfig, skipExitListCheck=True):
torDetected = True
args.forceRelay = True
logger.info(
f"Tor proxy verified ({proxyConfig['host']}:{proxyConfig['port']}) - "
f"enabling --force-relay for strict WebRTC blocking"
)
except RuntimeError as e:
logger.debug(f"Tor verification failed: {e}")
# Notify user if Tor privacy mode is active
if torDetected:
flushPrint(_("π§
Tor Privacy Mode Active"))
uploadProcessor = None
uid = None
if args.upload:
uploadProcessor = processUpload(args, reader, proxyConfig=proxyConfig)
if uploadProcessor.isDone():
return uploadProcessor.exitCode
uid = uploadProcessor.uid
# If we reach here, we need to start local server (either P2P or Pull upload)
if not uid:
uid = generateUid()
userPort = args.port
port = getAvailablePort(userPort)
# Get enhanced TunnelRunner from FeatureManager if Features or Tunnels addon is available
tunnelRunnerClass = TunnelRunner
if settingsGetter.hasFeaturesSupport():
tunnelRunnerClass = featureManager.getTunnelRunnerClass(tunnelRunnerClass)
if settingsGetter.hasTunnelsSupport():
try:
from addons.Tunnels import TunnelRunnerProvider
provider = TunnelRunnerProvider()
tunnelRunnerClass = provider.getTunnelRunnerClass(tunnelRunnerClass)
except Exception as e:
sendException(logger, _('Unable to create tunnel by your tunnel configuration.'))
# Use proxyConfig passed from global arguments processing
with tunnelRunnerClass(size, proxyConfig=proxyConfig) as tunnelRunner:
tunnelType = tunnelRunner.getTunnelType()
if tunnelType != "default":
flushPrint(_('Using tunnel: {tunnelType}').format(tunnelType=tunnelType))
# Show proxy status for tunnel connections
proxyInfo = tunnelRunner.getProxyInfo()
if proxyInfo:
flushPrint(_('Establishing tunnel connection via proxy {proxyInfo}...\n').format(
proxyInfo=proxyInfo))
else:
flushPrint(_('Establishing tunnel connection...\n'))
domain, tunnelLink = tunnelRunner.start(port)
link = f"{tunnelLink}{uid}"
# Determine recipient auth mode (P2P only; pull-upload uses server-side auth)
otpAPIBase = getattr(args, 'recipientOTPAPIBase', None)
recipientAuth = RecipientAuth.create(
args.recipientAuth,
getattr(args, 'recipientPublicKey', None),
getattr(args, 'pickupCode', None),
recipientEmail=getattr(args, 'recipientEmail', None),
otpRequestUrl=f'{otpAPIBase}/otp/email/request/' if otpAPIBase else None,
otpVerifyUrl=f'{otpAPIBase}/otp/email/verify/' if otpAPIBase else None,
)
# Determine handler class and setup link
if uploadProcessor:
try:
handlerClass = uploadProcessor.getDownloadHandlerClass(link, uid)
except RuntimeError as uploadError:
flushPrint(_('Upload failed: {error}').format(error=str(uploadError)))
sendException(logger, str(uploadError))
return 1
else:
# P2P mode
handlerClass = DownloadHandler
flushPrint(_("Please share the link below with the person you'd like to share the file with."))
flushPrint(f'{link}\n')
copy2Clipboard(f'{link}')
FFLEvent.shareLinkCreate.trigger(
link=link,
filePath=args.file,
fileSize=size,
tunnelType=tunnelType,
e2ee=e2eeEnabled,
reader=reader,
recipientAuth=recipientAuth,
upload=args.upload,
)
flushPrint(_('Please keep the application running so the recipient can download the file.'))
if isCLIMode():
flushPrint(_('Press Ctrl+C to terminate the program when done.\n'))
else:
flushPrint('')
try:
# Get maxDownloads and timeout values
maxDownloads = args.maxDownloads
timeout = args.timeout
# Get enhanced handlers from FeatureManager if Features addon is available
webRTCManagerClass = WebRTCManager
if settingsGetter.hasFeaturesSupport():
handlerClass = featureManager.getDownloadHandlerClass(handlerClass)
webRTCManagerClass = featureManager.getWebRTCManagerClass(
webRTCManagerClass, forceRelay=args.forceRelay
)
else:
if torDetected:
# Tor mode without Features addon: use DummyWebRTCManager to totally block WebRTC
webRTCManagerClass = DummyWebRTCManager
authUser, authPassword = determineAuthentication(args)
# Show auth info if enabled (password enables auth)
if authPassword:
promptAuthEnabled(authUser, authPassword)
if recipientAuth.isEnabled():
promptRecipientAuthInfo(recipientAuth)
# WebRTC default state: disabled by --force-relay flag
defaultWebRTC = not args.forceRelay
# Create server configuration
serverConfig = ServerConfig(
maxDownloads=maxDownloads,
timeout=timeout,
authUser=authUser,
authPassword=authPassword,
defaultWebRTC=defaultWebRTC,
e2eeEnabled=e2eeEnabled,
torEnabled=torDetected,
recipientAuth=recipientAuth,
)
# Create server with enhanced handler and WebRTC manager
# Reader provides file and directory information
server = createServer(reader, port, uid, domain, handlerClass, webRTCManagerClass, serverConfig)
server.start()
except KeyboardInterrupt:
flushPrint(_('\nExiting on user request (Ctrl+C)...'))
# Trigger applicationInterrupted event
FFLEvent.applicationInterrupted.trigger(reason='user-interrupt')
# Clean exit without stack trace - context manager will handle cleanup
return 0
except Exception as e:
raise e
# If we used pull upload, publish the link after server ends
if uploadProcessor:
link = uploadProcessor.publish()
if not link: # !?
sendException(logger, _('Unable to get uploaded link'))
return 1
FFLEvent.shareLinkCreate.trigger(
link=link,
filePath=args.file,
fileSize=size,
tunnelType=tunnelType,
e2ee=e2eeEnabled,
reader=reader,
recipientAuth=recipientAuth,
upload=args.upload,
)
return 0
except KeyboardInterrupt:
flushPrint(_('\nExiting on user request (Ctrl+C)...'))
FFLEvent.applicationInterrupted.trigger(reason='user-interrupt')
# Ensure clean exit
return 0
# Default success return for normal P2P completion
return 0
def processDownload(args):
"""
Process download command using WebRTCDownloader
Returns:
int: Exit code (0 for success, 1 for error)
"""
downloader = None
try:
# Setup credentials if provided
credentials = None
if args.authPassword:
credentials = (args.authUser, args.authPassword)
# Create downloader and download file
downloader = WebRTCDownloader(loggerCallback=flushPrint)
resume = args.resume if hasattr(args, 'resume') else False
pickupCode = args.pickupCode if hasattr(args, 'pickupCode') else None
recipientPrivateKey = args.recipientPrivateKey if hasattr(args, 'recipientPrivateKey') else None
outputPath = downloader.downloadFile(
args.url,
args.output,
credentials,
resume=resume,
pickupCode=pickupCode,
recipientPrivateKey=recipientPrivateKey
)
# Don't print success message - progress bar already shows completion
logger.debug(f"File downloaded successfully: {outputPath}")
# Print file path for test framework to parse
flushPrint(_('Downloaded: {outputPath}').format(outputPath=outputPath))
return 0
except Exception as e:
# Check if this is a FolderChangedException
if isinstance(e, FolderChangedException):
# Add user-facing guidance to server error message
serverMsg = str(e)
clientMsg = _(
'{serverMsg}\n\n'
'The shared folder contents changed during the transfer.\n'
'Please contact the person who shared the file and ask them to share it again.'
).format(serverMsg=serverMsg)
sendException(logger, clientMsg)
return 1
else:
sendException(logger, _('Download failed: {error}').format(error=e))
return 1
finally:
# Clean up downloader resources
if downloader:
downloader.close()
# CLI mode implementation
def runCLIMain():
"""Run the program in CLI mode using two-phase parsing"""
parser, globalsParent, commandNames, shareSubparser = configureCLIParser()
argv = sys.argv[1:]
# Handle special cases first (maintain original UX)
if argv == ['--cli'] or len(argv) == 0:
parser.print_help()
return 0
# Phase 1: Use globalsParent to separate global args from the rest
# This lets argparse handle all global argument validation (including --log-level missing values)
try:
globalArgs, rest = globalsParent.parse_known_args(argv)
except argparse.ArgumentError as e:
# Global argument error - let argparse report it properly
parser.error(str(e))
# Process global arguments (handles --log-level, --enable-reporting, --version, --proxy, etc.)
globalResult = processGlobalArguments(globalArgs)
if globalResult['exitCode'] is not None:
return globalResult['exitCode']
# Extract proxyConfig from global arguments processing
proxyConfig = globalResult['proxyConfig']
if not rest:
# No subcommand or remaining arguments -> show help
parser.print_help()
return 0
# Phase 2: Preprocess arguments (auto-insert commands, fix --upload)
argv = preprocessArguments(argv, commandNames, shareSubparser, globalsParent)
# Phase 3: Final parsing with subcommand determined
try:
args, unknownArgs = parser.parse_known_args(argv)
except argparse.ArgumentError as e:
parser.error(str(e))
# Collect any extra positional arguments (files after optional args like --json)
# and append them to args.file for multi-file sharing support
if unknownArgs:
extraFiles = [a for a in unknownArgs if not a.startswith('-')]
unrecognizedFlags = [a for a in unknownArgs if a.startswith('-')]
if unrecognizedFlags:
parser.error(f"unrecognized arguments: {' '.join(unrecognizedFlags)}")
if extraFiles and getattr(args, 'command', None) == 'share':
existingFiles = args.file if isinstance(args.file, list) else ([args.file] if args.file else [])
args.file = existingFiles + extraFiles
# Ensure we have a command after parsing
if args.command is None:
parser.print_help()
return 0
# Handle download command
if args.command == 'download':
return processDownload(args)
# Special validation for share command - must have file argument