Repository navigation
Expand file tree
/
Copy pathmavftp.py
More file actions
4699 lines (4424 loc) · 196 KB
/
Copy pathmavftp.py
File metadata and controls
4699 lines (4424 loc) · 196 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
# PYTHON_ARGCOMPLETE_OK
"""
MAVLink File Transfer Protocol support - https://mavlink.io/en/services/ftp.html.
Original from MAVProxy/MAVProxy/modules/mavproxy_ftp.py.
SPDX-FileCopyrightText: 2011-2024 Andrew Tridgell, 2024-2026 Amilcar Lucas
SPDX-License-Identifier: GPL-3.0-or-later
"""
# FLAKE_CLEAN
import contextlib
import glob
import heapq
import logging
import math
import os
import random
import socket
import struct
import sys
import time
import zlib
from argparse import ArgumentParser
from dataclasses import dataclass
from datetime import datetime
from enum import IntEnum
from io import BufferedRandom, BufferedReader, BufferedWriter
from io import BytesIO as SIO # noqa: N814
from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast
try:
import argcomplete
from argcomplete.completers import FilesCompleter
_ARGCOMPLETE_AVAILABLE = True
except ImportError:
_ARGCOMPLETE_AVAILABLE = False
# Dummy class to avoid errors when argcomplete is not available
class FilesCompleter: # type: ignore[no-redef] # pylint: disable=too-few-public-methods,missing-class-docstring
def __init__(self, *args, **kwargs):
pass
from pymavlink import mavutil
# pylint: disable=too-many-lines
# mypy: disable-error-code="union-attr,arg-type"
from pymavlink.mavftp_op import (
FTP_OP,
OP_Ack,
OP_BurstReadFile,
OP_CalcFileCRC32,
OP_CreateDirectory,
OP_CreateFile,
OP_ListDirectory,
OP_ListDirectoryWithTime,
OP_Nack,
OP_None,
OP_OpenFileRO,
OP_OpenFileWO,
OP_ReadFile,
OP_RemoveDirectory,
OP_RemoveFile,
OP_Rename,
OP_ResetSessions,
OP_TerminateSession,
OP_TruncateFile,
OP_WriteFile,
)
ParameterDataType = Union[str, int]
SettingValue = Union[int, float]
# pylint: disable=invalid-name
class FtpError(IntEnum):
"""error codes."""
Success = 0
Fail = 1
FailErrno = 2
InvalidDataSize = 3
InvalidSession = 4
NoSessionsAvailable = 5
EndOfFile = 6
UnknownCommand = 7
FileExists = 8
FileProtected = 9
FileNotFound = 10
NoErrorCodeInPayload = 64
NoErrorCodeInNack = 65
NoFilesystemErrorInPayload = 66
InvalidErrorCode = 67
PayloadTooLarge = 68
InvalidOpcode = 69
InvalidArguments = 70
PutAlreadyInProgress = 71
FailToOpenLocalFile = 72
RemoteReplyTimeout = 73
HDR_Len = 12
MAX_Payload = 239
FTP_SEQ_MODULUS = 1 << 16
FTP_SESSION_MODULUS = 1 << 8
BURST_REPLY_SEQUENCE_WINDOW = 4096
MAX_READ_GAPS = 4096
MAX_READ_RETRIES = 10
MAX_INITIAL_RETRIES = 3
LIST_TIME_FAIL_LIMIT = 2
READ_DEADLINE_SECONDS = 5.0
CRC_TIMEOUT_SECONDS = 5.0
# Keep a batch of encoded MAVLink packets below a normal Ethernet MTU. This
# is used only when the underlying pymavlink link supports collecting writes.
MAX_NETWORK_BATCH = 1200
# The server null-terminates the final byte of its filename buffer.
MAX_FTP_NAME = MAX_Payload - 1
# pylint: enable=invalid-name
@dataclass
class DirectoryEntry:
"""Directory entry, optionally including a Unix modification timestamp."""
name: str
is_dir: bool
size_b: int
mtime: Optional[int] = None
def local_file_crc(name: str) -> int:
"""Return the ArduPilot-compatible CRC32 of a local file."""
crc = 0xFFFFFFFF
with open(name, "rb") as file_handle:
while True:
block = file_handle.read(65536)
if not block:
break
crc = zlib.crc32(block, crc)
return crc ^ 0xFFFFFFFF
class WriteQueue: # pylint: disable=too-few-public-methods
"""
Manages a queue of write operations for the MAVFTP class.
Keeps track of offsets and sizes for pending write operations to ensure orderly processing.
"""
def __init__(self, ofs: int, size: int) -> None:
self.ofs = ofs # Offset where the write operation starts.
self.size = size # Size of the data to be written.
self.last_send = 0 # Timestamp of the last send operation.
class MAVLinkBatchWriter: # pylint: disable=too-few-public-methods
"""Collect encoded MAVLink packets for one link write."""
def __init__(self) -> None:
self.packets: List[bytes] = []
def write(self, packet: bytes) -> int:
"""Collect one encoded packet."""
self.packets.append(bytes(packet))
return len(packet)
class ParamData:
"""A class to manage parameter values and defaults for ArduPilot configuration."""
def __init__(self) -> None:
self.params: List[
Tuple[bytes, float, type]
] = [] # params as (name, value, ptype)
self.defaults: Union[None, List[Tuple[bytes, float, type]]] = (
None # defaults as (name, value, ptype)
)
def add_param(self, name: bytes, value: float, ptype: type) -> None:
self.params.append((name, value, ptype))
def add_default(self, name: bytes, value: float, ptype: type) -> None:
if self.defaults is None:
self.defaults = []
self.defaults.append((name, value, ptype))
class MAVFTPSetting: # pylint: disable=too-few-public-methods
"""A single MAVFTP setting with a name, type, value and default value."""
def __init__(self, name: str, s_type: type, default: SettingValue) -> None:
self.name: str = name
self.type = s_type
try:
normalized_default = s_type(default)
except OverflowError as exc:
raise ValueError(f"invalid default for {name}: {default}") from exc
self.default: SettingValue = normalized_default
self.value: SettingValue = self.default
class MAVFTPSettings:
"""A collection of MAVFTP settings.
Timeout settings use exclusive lower bounds because zero or the minimum
retry interval would disable the state machine's safety margin.
"""
_BOUNDS = {
"debug": (0, 2, False),
"pkt_loss_tx": (0, 100, False),
"pkt_loss_rx": (0, 100, False),
"pkt_lag_tx": (0, None, False),
"pkt_lag_rx": (0, None, False),
"pkt_lag_jitter_tx": (0, None, False),
"pkt_lag_jitter_rx": (0, None, False),
"max_backlog": (1, None, False),
"burst_read_size": (1, MAX_Payload, False),
"write_size": (1, MAX_Payload, False),
"write_qsize": (1, None, False),
"read_retry_time": (0, None, False),
"retry_time": (0.1, None, True),
"crccmp_timeout": (0.1, None, True),
"idle_detection_time": (0, None, True),
"list_time": (0, 1, False),
"list_time_timeout": (0, None, True),
"list_retries": (0, None, False),
"initial_retries": (0, MAX_INITIAL_RETRIES, False),
}
def __init__(
self, s_vars: List[Union[MAVFTPSetting, Tuple[str, type, SettingValue]]]
) -> None:
self._vars: Dict[str, MAVFTPSetting] = {}
for v in s_vars:
self.append(v)
self.validate()
def append(
self, v: Union[MAVFTPSetting, Tuple[str, type, SettingValue]]
) -> None:
"""Add or replace a setting after validating the resulting collection."""
if isinstance(v, MAVFTPSetting):
setting = self.__copy_setting(v)
else:
(name, s_type, default) = v
setting = MAVFTPSetting(name, s_type, default)
candidate_vars = self._vars.copy()
candidate_vars[setting.name] = setting
self.__validate_vars(candidate_vars)
self._vars = candidate_vars
def validate(self) -> None:
"""Validate settings required by the MAVFTP state machine."""
self.__validate_vars(self._vars)
def has_setting(self, name: str) -> bool:
"""Return whether a setting exists."""
return name in self._vars
def get_setting(self, name: str) -> MAVFTPSetting:
"""Return a detached snapshot of a named setting."""
return self.__copy_setting(self._vars[name])
@classmethod
def __validate_vars(cls, settings: Dict[str, MAVFTPSetting]) -> None:
"""Validate settings without mutating the active collection."""
for name, setting in settings.items():
value = setting.type(setting.value)
if isinstance(value, float) and not math.isfinite(value):
raise ValueError(f"{name} must be finite")
bounds = cls._BOUNDS.get(name)
if bounds is None:
continue
minimum, maximum, exclusive_minimum = bounds
if (
(minimum is not None and (value <= minimum if exclusive_minimum else value < minimum))
or (maximum is not None and value > maximum)
):
raise ValueError(f"invalid value for {name}: {value}")
idle_detection = settings.get("idle_detection_time")
read_retry = settings.get("read_retry_time")
if idle_detection is not None and read_retry is not None:
if idle_detection.type(idle_detection.value) <= read_retry.type(read_retry.value):
raise ValueError("idle_detection_time must be greater than read_retry_time")
@staticmethod
def __copy_setting(setting: MAVFTPSetting) -> MAVFTPSetting:
"""Return a detached setting snapshot."""
setting_copy = MAVFTPSetting(setting.name, setting.type, setting.default)
setting_copy.value = setting.value
return setting_copy
def __getattr__(self, name: str) -> Union[int, float]:
"""Get attribute."""
try:
setting = self._vars[name]
except KeyError as exc:
raise AttributeError(name) from exc
return cast(Union[int, float], setting.type(setting.value))
def __setattr__(self, name: str, value: Any) -> None:
"""Set attribute."""
if name[0] == "_":
self.__dict__[name] = value
return
if name in self._vars:
setting = self.__copy_setting(self._vars[name])
try:
setting.value = setting.type(value)
except OverflowError as exc:
raise ValueError(f"invalid value for {name}: {value}") from exc
candidate_vars = self._vars.copy()
candidate_vars[name] = setting
self.__validate_vars(candidate_vars)
self._vars = candidate_vars
return
raise AttributeError
class MAVFTPReturn:
"""The result of a MAVFTP operation."""
def __init__( # pylint: disable=too-many-arguments
self,
operation_name: str,
error_code: int,
system_error: int = 0,
invalid_error_code: int = 0,
invalid_opcode: int = 0,
invalid_payload_size: int = 0,
directory_listing: Optional[List[DirectoryEntry]] = None,
) -> None:
self.operation_name = operation_name
self.error_code = error_code
self.system_error = system_error
self.invalid_error_code = invalid_error_code
self.invalid_opcode = invalid_opcode
self.invalid_payload_size = invalid_payload_size
self.directory_listing = directory_listing
def display_message(self) -> None: # pylint: disable=too-many-branches, too-many-statements # noqa: C901, PLR0912, PLR0915
if self.error_code == FtpError.Success:
logging.info("%s succeeded", self.operation_name)
elif self.error_code == FtpError.Fail:
logging.error("%s failed, generic error", self.operation_name)
elif self.error_code == FtpError.FailErrno:
logging.error(
"%s failed, system error %u", self.operation_name, self.system_error
)
elif self.error_code == FtpError.InvalidDataSize:
logging.error("%s failed, invalid data size", self.operation_name)
elif self.error_code == FtpError.InvalidSession:
logging.error(
"%s failed, session is not currently open", self.operation_name
)
elif self.error_code == FtpError.NoSessionsAvailable:
logging.error("%s failed, no sessions available", self.operation_name)
elif self.error_code == FtpError.EndOfFile:
logging.error("%s failed, offset past end of file", self.operation_name)
elif self.error_code == FtpError.UnknownCommand:
logging.error("%s failed, unknown command", self.operation_name)
elif self.error_code == FtpError.FileExists:
logging.warning(
"%s failed, file/directory already exists", self.operation_name
)
elif self.error_code == FtpError.FileProtected:
logging.warning(
"%s failed, file/directory is protected", self.operation_name
)
elif self.error_code == FtpError.FileNotFound:
logging.warning("%s failed, file/directory not found", self.operation_name)
elif self.error_code == FtpError.NoErrorCodeInPayload:
logging.error(
"%s failed, payload contains no error code", self.operation_name
)
elif self.error_code == FtpError.NoErrorCodeInNack:
logging.error("%s failed, no error code", self.operation_name)
elif self.error_code == FtpError.NoFilesystemErrorInPayload:
logging.error(
"%s failed, file-system error missing in payload", self.operation_name
)
elif self.error_code == FtpError.InvalidErrorCode:
logging.error(
"%s failed, invalid error code %u",
self.operation_name,
self.invalid_error_code,
)
elif self.error_code == FtpError.PayloadTooLarge:
logging.error(
"%s failed, payload is too long %u",
self.operation_name,
self.invalid_payload_size,
)
elif self.error_code == FtpError.InvalidOpcode:
logging.error(
"%s failed, invalid opcode %u", self.operation_name, self.invalid_opcode
)
elif self.error_code == FtpError.InvalidArguments:
logging.error("%s failed, invalid arguments", self.operation_name)
elif self.error_code == FtpError.PutAlreadyInProgress:
logging.error("%s failed, put already in progress", self.operation_name)
elif self.error_code == FtpError.FailToOpenLocalFile:
logging.error("%s failed, failed to open local file", self.operation_name)
elif self.error_code == FtpError.RemoteReplyTimeout:
logging.error("%s failed, remote reply timeout", self.operation_name)
else:
logging.error(
"%s failed, unknown error %u in display_message()",
self.operation_name,
self.error_code,
)
if self.directory_listing is not None and len(self.directory_listing) > 0:
total_size = 0
for entry in self.directory_listing:
name = entry.name
size = entry.size_b
if entry.is_dir and entry.mtime is None:
logging.info(" %s/", name)
elif entry.is_dir and entry.mtime == 0:
logging.info(" %s/\t-", name)
elif entry.is_dir:
try:
mtime = datetime.fromtimestamp(entry.mtime).strftime(
"%Y-%m-%d %H:%M:%S"
)
except (OverflowError, OSError, ValueError):
mtime = str(entry.mtime)
logging.info(" %s/\t%s", name, mtime)
elif entry.mtime is None:
logging.info(" %s\t%u", name, size)
elif entry.mtime == 0:
logging.info(" %s\t%u\t-", name, size)
else:
try:
mtime = datetime.fromtimestamp(entry.mtime).strftime(
"%Y-%m-%d %H:%M:%S"
)
except (OverflowError, OSError, ValueError):
mtime = str(entry.mtime)
logging.info(" %s\t%u\t%s", name, size, mtime)
total_size += max(0, size)
logging.info("Total size %.2f kByte", total_size / 1024.0)
@property
def return_code(self) -> int:
return self.error_code
TERMINATE_ATTEMPTS = 2
class MAVFTP: # pylint: disable=too-many-instance-attributes,too-many-public-methods
"""
Implements the client-side logic for the MAVLink File Transfer Protocol (FTP) over MAVLink connections.
Handles file operations such as reading, writing, listing directories, and managing sessions.
"""
def __init__( # noqa: PLR0915 pylint: disable=too-many-statements
self,
master,
target_system: int,
target_component: int,
settings: Optional[MAVFTPSettings] = None,
) -> None:
if settings is None:
settings = MAVFTPSettings(
[
("debug", int, 0),
# Timestamp listings are opt-in until they are implemented
# by released flight-controller firmware.
("list_time", int, 0),
# Some older servers silently discard unknown opcodes.
("list_time_timeout", float, 3.0),
("list_retries", int, 3),
# Retransmitting one-reply commands can repeat mutations
# on servers without a transaction-reply cache.
("initial_retries", int, 0),
("pkt_loss_tx", int, 0),
("pkt_loss_rx", int, 0),
# Optional link simulation. Delays are in milliseconds,
# matching MAVProxy's FTP module settings.
("pkt_lag_tx", float, 0.0),
("pkt_lag_rx", float, 0.0),
("pkt_lag_jitter_tx", float, 0.0),
("pkt_lag_jitter_rx", float, 0.0),
("loss_seed", int, 0),
("crccmp_timeout", float, 120.0),
("max_backlog", int, 5),
("burst_read_size", int, 80),
("write_size", int, 80),
("write_qsize", int, 5),
("idle_detection_time", float, 3.7),
("read_retry_time", float, 1.0),
("retry_time", float, 0.5),
]
)
self.ftp_settings = settings
self.seq = 0
self.session = 0
self.network = 0
self.last_op: Union[None, FTP_OP] = None
self.fh: Union[None, SIO, BufferedReader, BufferedWriter, BufferedRandom] = None
self.filename: Union[None, str] = None
self.callback = None
self.callback_failure: Optional[MAVFTPReturn] = None
self.callback_progress = None
self.put_callback = None
self.put_callback_progress = None
self.total_size = 0
self.read_gaps: List[Tuple[int, int]] = []
self.read_gap_times: Dict[Tuple[int, int], float] = {}
self.read_gap_retries: Dict[Tuple[int, int], int] = {}
# FTP permits several ReadFile requests in flight. Track their
# expected response sequences so delayed replies from a prior request
# cannot be dispatched as a current gap repair.
self.pending_read_replies: Dict[int, Tuple[int, int]] = {}
self.pending_read_requests: Dict[int, FTP_OP] = {}
self.last_gap_send = 0.0
self.read_retries = 0
self.read_total = 0
self.accepted_reply_generation = 0
self.remote_file_size: int = 0
self.remote_size_known = False
self.duplicates = 0
self.last_read = None
self.last_burst_read: Union[None, float] = None
# The start offset and first expected reply sequence of the active burst.
# Burst packets are streamed with advancing sequence numbers, so both
# identify whether a reply belongs to the current burst.
self.pending_burst_offset: Optional[int] = None
self.pending_burst_seq: Optional[int] = None
self.pending_burst_retry = False
self.pending_burst_request: Optional[FTP_OP] = None
self.op_start: Union[None, float] = None
self.dir_offset = 0
self.last_op_time = time.time()
self.last_send_time = time.time()
self.rtt = 0.5
self.rttvar = 0.25
self.rtt_valid = False
# Requests are keyed by their uint16 sequence. Retransmissions do
# not replace the sample (Karn's algorithm), so a reply to a retry
# cannot make the adaptive timeout spuriously small.
self.send_times: Dict[int, Optional[float]] = {}
self.reached_eof = False
self.read_complete = False
# Explicit terminal reply, identified by (request opcode, reply
# sequence). A boolean here lets a delayed reply from an earlier
# operation complete whichever command is currently waiting.
self.completed_reply: Optional[Tuple[int, int]] = None
# A request can be retried with its original sequence number. This is
# needed both for idempotent recovery after a lost reply and for
# distinguishing an already-open session from an initial failure.
self.request_retries = 0
# An explicit NoSessionsAvailable NACK is server backpressure rather
# than an ambiguous lost reply, so it gets one safe retry even when
# normal initial-request retries are disabled.
self.no_sessions_retry_pending = False
self.no_sessions_retries = 0
self.no_sessions_retry_generation = 0
# A command helper may calculate its own numeric default timeout,
# while still allowing the safe NoSessionsAvailable recovery used by
# an omitted public timeout. This is consumed by the next reply loop
# entry so process_ftp_reply keeps its long-standing public signature.
self._next_no_sessions_timeout_extension: Optional[bool] = None
self.last_op_reply = False
# A synchronous operation that has returned an error must not be
# retried later by idle_task(), including through the optional
# delayed-traffic simulator.
self.request_cancelled = False
self.terminal_timeout = False
self.crc_unbounded_wait = False
# sequence numbers of in-flight terminate/reset requests, None
# when nothing is outstanding: replies are correlated by
# sequence so a stale or duplicated reply from an earlier
# request cannot mark the current one complete
self.pending_terminate_seq: Optional[int] = None
self.pending_reset_seq: Optional[int] = None
self.backlog = 0
self.burst_size: int = int(self.ftp_settings.burst_read_size)
self.write_list: Union[None, Set[int]] = None
self.write_block_size: int = 0
self.write_acks = 0
self.write_acked_bytes = 0
self.write_total = 0
self.write_file_size = 0
self.write_idx = 0
self.write_recv_idx = -1
self.write_pending = 0
# Do not send WriteFile packets until the remote CreateFile handshake
# has completed. This matters on real links where the ACK can arrive
# after an idle-task pass.
self.write_open = False
# Uploads have several WriteFile requests in flight. Map each
# response sequence to its requested offset.
self.pending_write_replies: Dict[int, int] = {}
self.pending_write_requests: Dict[int, FTP_OP] = {}
self.write_inflight: Set[int] = set()
self.write_last_send: Union[None, float] = None
self.open_retries = 0
self.list_result: List[DirectoryEntry] = []
self.list_temp_result: List[DirectoryEntry] = []
self.list_with_time = False
self.list_time_retries = 0
self.list_time_failures = 0
self.list_time_probe_fail_pending = False
# A MAVFTP instance has one fixed target, so one capability cache is
# sufficient and avoids repeat probe delays on old servers.
self.list_time_supported: Optional[bool] = None
self.requested_size: int = 0
self.requested_offset: int = 0
# The synchronous read/read_sector API returns data to its caller and
# must never publish a file named after the remote path.
self.read_to_memory = False
# set per-download by __handle_open_ro_reply: a securely
# created unique staging file, so concurrent MAVFTP clients on
# one host (e.g. parallel simulator test runners) cannot share
# a staging file and its name is not predictable
self.temp_filename: Optional[str] = None
# only close file handles this instance opened itself; cmd_put
# stores a caller-owned handle in self.fh
self.fh_owned = False
self.master = master
self.target_system = target_system
self.target_component = target_component
# Optional deterministic loss/latency simulation used by link tests
# and by applications that want to exercise poor-link behavior.
self.loss_rng = random.Random()
self.active_loss_seed: Optional[int] = None
self.delay_sequence = 0
self.tx_delay_queue: List[Tuple[float, int, bytes]] = []
self.rx_delay_queue: List[Tuple[float, int, Any]] = []
self.delayed_rx_results: List[Tuple[MAVFTPReturn, bool, bool, bool, bool]] = []
self.last_tx_deadline = 0.0
self.last_rx_deadline = 0.0
self._rx_loss_applied = False
self._ftp_reply_processing_depth = 0
# ``get_result`` is the result buffer for synchronous ``read()`` and
# stdout downloads. File downloads deliberately stream to a staging
# file and do not retain a second, whole-file in-memory copy.
self.get_result: Union[None, bytes] = None
self.last_crc: Optional[int] = None
self.crccmp_results: List[str] = []
self.crccmp_start: Optional[float] = None
self.done = False
self.transfer_active = False
# Interactive transfers expose periodic status through cmd_status and
# the idle hook. Callback-driven operations stay quiet unless the
# caller explicitly asks for progress callbacks.
self.show_progress = False
self.last_status_time = 0.0
# The standalone client normally resets the flight controller FTP
# state-machine during construction. Keep construction useful for
# callers that create an instance before a link is available too.
if self.master is not None:
self.pending_reset_seq = self.seq
self.__send(FTP_OP(self.seq, self.session, OP_ResetSessions, 0, 0, 0, 0, None))
self.process_ftp_reply("ResetSessions")
def cmd_ftp(self, args: List[str]) -> MAVFTPReturn: # noqa: PLR0911 pylint: disable=too-many-branches,too-many-return-statements
"""FTP operations."""
usage = "Usage: ftp <list|set|get|getparams|put|rm|rmdir|rename|mkdir|status|cancel|crc|crclocal|crccmp>"
if len(args) < 1:
logging.error(usage)
return MAVFTPReturn("FTP command", FtpError.InvalidArguments)
if args[0] == "list":
return self.cmd_list(args[1:])
if args[0] == "set":
return self.cmd_set(args[1:])
if args[0] == "get":
return self.cmd_get(args[1:])
if args[0] == "getparams":
return self.cmd_getparams(args[1:])
if args[0] == "put":
return self.cmd_put(args[1:])
if args[0] == "rm":
return self.cmd_rm(args[1:])
if args[0] == "rmdir":
return self.cmd_rmdir(args[1:])
if args[0] == "rename":
return self.cmd_rename(args[1:])
if args[0] == "mkdir":
return self.cmd_mkdir(args[1:])
if args[0] == "crc":
return self.cmd_crc(args[1:])
if args[0] == "crclocal":
return self.cmd_crclocal(args[1:])
if args[0] == "crccmp":
return self.cmd_crccmp(args[1:])
if args[0] == "status":
return self.cmd_status()
if args[0] == "cancel":
return self.cmd_cancel()
logging.error(usage)
return MAVFTPReturn("FTP command", FtpError.InvalidArguments)
def __send( # pylint: disable=too-many-branches,too-many-statements
self,
op: FTP_OP,
retry: bool = False,
writer: Optional[Any] = None,
retain_no_sessions_retry: bool = False,
) -> None:
"""Send a request, preserving its sequence number on retransmission.
``retain_no_sessions_retry`` allocates a fresh sequence for an
explicitly rejected request without resetting its one-retry accounting.
"""
if not retry:
op.seq = self.seq
self.request_retries = 0
if not retain_no_sessions_retry:
self.no_sessions_retry_pending = False
self.no_sessions_retries = 0
self.last_op_reply = False
self.request_cancelled = False
payload = op.pack()
plen = len(payload)
if plen < MAX_Payload + HDR_Len:
payload.extend(bytearray([0] * ((HDR_Len + MAX_Payload) - plen)))
if self.master is None or not hasattr(self.master, "mav"):
logging.error("FTP: Can't send request, no master")
elif self.__packet_lost("TX"):
if self.ftp_settings.debug > 1:
logging.info("FTP: dropping packet TX")
else:
lag = self.__packet_delay("TX")
if lag == 0:
self.__transmit_payload(payload, writer)
else:
self.delay_sequence += 1
deadline = max(time.monotonic() + lag, self.last_tx_deadline)
self.last_tx_deadline = deadline
heapq.heappush(
self.tx_delay_queue,
(deadline, self.delay_sequence, bytes(payload)),
)
expected_reply_seq = (op.seq + 1) % FTP_SEQ_MODULUS
if op.opcode == OP_BurstReadFile:
self.pending_burst_offset = op.offset
self.pending_burst_seq = expected_reply_seq
self.pending_burst_retry = retry
self.pending_burst_request = op
elif op.opcode == OP_ReadFile:
self.pending_read_replies[expected_reply_seq] = (op.offset, op.size)
self.pending_read_requests[expected_reply_seq] = op
elif op.opcode == OP_WriteFile:
self.pending_write_replies[expected_reply_seq] = op.offset
self.pending_write_requests[expected_reply_seq] = op
if not retry:
self.seq = (self.seq + 1) % FTP_SEQ_MODULUS
self.send_times[op.seq] = time.time()
else:
# Do not use a reply to a retransmitted request as an RTT sample.
self.send_times[op.seq] = None
self.request_retries += 1
self.last_op = op
now = time.time()
if self.ftp_settings.debug > 1:
logging.info("FTP: > %s dt=%.2f", op, now - self.last_op_time)
self.last_op_time = time.time()
self.last_send_time = now
def __transmit_payload(self, payload: bytes, writer: Optional[Any] = None) -> None:
"""Transmit an already encoded MAVLink FTP payload."""
if self.master is None or not hasattr(self.master, "mav"):
return
if writer is not None:
mav = self.master.mav
message = mav.file_transfer_protocol_encode(
self.network, self.target_system, self.target_component, payload
)
packet = message.pack(mav) if hasattr(message, "pack") else bytes(message)
writer.write(packet)
if hasattr(mav, "seq"):
mav.seq = (mav.seq + 1) % 256
if hasattr(mav, "total_packets_sent"):
mav.total_packets_sent += 1
if hasattr(mav, "total_bytes_sent"):
mav.total_bytes_sent += len(packet)
return
self.master.mav.file_transfer_protocol_send(
self.network, self.target_system, self.target_component, payload
)
def __packet_lost(self, direction: str) -> bool:
"""Return whether the configured transport simulator drops a packet."""
seed = int(getattr(self.ftp_settings, "loss_seed", 0))
if seed != self.active_loss_seed:
self.loss_rng.seed(None if seed == 0 else seed)
self.active_loss_seed = seed
setting = "pkt_loss_tx" if direction == "TX" else "pkt_loss_rx"
percent = int(getattr(self.ftp_settings, setting))
return percent > 0 and self.loss_rng.uniform(0, 100) < percent
def packet_lost(self, direction: str) -> bool:
"""Return whether the configured transport simulator drops a packet."""
return self.__packet_lost(direction)
def __packet_delay(self, direction: str) -> float:
"""Return configured one-way delay in seconds, including jitter."""
lag_name = "pkt_lag_tx" if direction == "TX" else "pkt_lag_rx"
jitter_name = "pkt_lag_jitter_tx" if direction == "TX" else "pkt_lag_jitter_rx"
delay_ms = max(0.0, float(getattr(self.ftp_settings, lag_name, 0.0)))
jitter_ms = float(getattr(self.ftp_settings, jitter_name, 0.0))
if jitter_ms > 0:
delay_ms += self.loss_rng.uniform(0, jitter_ms)
return delay_ms * 0.001
def packet_delay(self, direction: str) -> float:
"""Return simulated one-way delay in seconds."""
return self.__packet_delay(direction)
def __discard_delayed_traffic(self) -> None:
"""Discard queued traffic belonging to a finished operation."""
self.tx_delay_queue.clear()
self.rx_delay_queue.clear()
self.delayed_rx_results.clear()
self.last_tx_deadline = 0.0
self.last_rx_deadline = 0.0
def __flush_delayed_traffic(self) -> None:
"""Deliver due simulated packets in FIFO order."""
now = time.monotonic()
while self.tx_delay_queue and self.tx_delay_queue[0][0] <= now:
_, _, payload = heapq.heappop(self.tx_delay_queue)
self.__transmit_payload(payload)
while self.rx_delay_queue and self.rx_delay_queue[0][0] <= now:
_, _, message = heapq.heappop(self.rx_delay_queue)
addressed_to_us = (
self.__reply_addressed_to_local_client(message)
and self.__reply_from_configured_target(message)
)
if addressed_to_us:
try:
op = self.__op_parse(message)
except (struct.error, TypeError, ValueError):
op = None
else:
op = None
reply_matches_last_op = (
op is not None
and self.last_op is not None
and op.req_opcode == self.last_op.opcode
and op.seq == (self.last_op.seq + 1) % FTP_SEQ_MODULUS
and op.session == self.session
)
reply_matches_active_request = (
op is not None
and op.session == self.session
and self.__reply_matches_active_request(op)
)
packet_ret = self.__dispatch_received_packet(message)
if self._ftp_reply_processing_depth:
self.delayed_rx_results.append(
(
packet_ret,
reply_matches_last_op,
reply_matches_active_request,
addressed_to_us and op is None,
addressed_to_us,
)
)
def __receive_packet(self, message) -> Optional[MAVFTPReturn]:
"""Dispatch a reply immediately or enqueue it for simulated latency."""
if self.__packet_lost("RX"):
if self.ftp_settings.debug > 1:
logging.info("FTP: dropping packet RX")
return MAVFTPReturn("mavlink_packet", FtpError.Fail)
lag = self.__packet_delay("RX")
if lag == 0:
return self.__dispatch_received_packet(message)
self.delay_sequence += 1
deadline = max(time.monotonic() + lag, self.last_rx_deadline)
self.last_rx_deadline = deadline
heapq.heappush(
self.rx_delay_queue,
(deadline, self.delay_sequence, message),
)
return None
def __dispatch_received_packet(self, message) -> MAVFTPReturn:
"""Dispatch a reply after the transport simulator has handled loss."""
self._rx_loss_applied = True
try:
return self.__mavlink_packet(message)
finally:
self._rx_loss_applied = False
def mavlink_packet(self, message) -> Optional[MAVFTPReturn]:
"""Accept an incoming FTP reply from an event-driven MAVLink loop."""
if self.master is None:
return MAVFTPReturn("mavlink_packet", FtpError.Fail)
if message.get_type() != "FILE_TRANSFER_PROTOCOL":
return MAVFTPReturn("mavlink_packet", FtpError.Fail)
return self.__receive_packet(message)
def idle_task(self) -> bool:
"""Service delayed traffic and run the FTP retry state machine."""
self.__flush_delayed_traffic()
return self.__idle_task()
def __write_link_data(self, link: Any, data: bytes, is_stream: bool) -> None:
"""Write encoded data, handling partial stream writes."""
if is_stream:
port = getattr(link, "port", None)
if port is not None and hasattr(port, "sendall"):
try:
port.sendall(data)
except BlockingIOError:
# A non-blocking stream is temporarily full. Leave the
# operation pending so the normal FTP retry machinery can
# resend it; this is not a disconnected link.
return
except OSError:
if hasattr(link, "handle_disconnect"):
link.handle_disconnect()
return
offset = 0
while offset < len(data):
written = link.write(data[offset:])
# Datagram and several pymavlink wrappers return None after a
# complete write. Integer-returning writers may accept a prefix.
if written is None or written <= 0:
return
offset += written
def __send_batch(self, operations: List[FTP_OP]) -> None:
"""Send several requests in one underlying link write when possible."""
if (
len(operations) <= 1
or self.master is None
or not hasattr(self.master, "mav")
or not hasattr(self.master.mav, "file")
or not hasattr(self.master.mav, "file_transfer_protocol_encode")
):
for operation in operations:
self.__send(operation)
return
mav = self.master.mav
signing = getattr(mav, "signing", None)
# Packing a signed packet consumes both the MAVLink sequence and the
# signing timestamp. A send callback (or another sender sharing the
# MAVLink instance) can send before the held batch is flushed, making
# the deferred packets appear to have old signatures at the receiver.
# Use the normal send path whenever that ordering matters.
if getattr(signing, "sign_outgoing", False) or getattr(
mav, "send_callback", None
) is not None:
for operation in operations:
self.__send(operation)
return
link = mav.file
collector = MAVLinkBatchWriter()
for operation in operations:
self.__send(operation, writer=collector)
if not collector.packets:
return
port = getattr(link, "port", None)
port_type = getattr(port, "type", None)
link_name = type(link).__name__
# WebSocket links also use a stream socket, but ``link.write()`` adds
# WebSocket framing. Only raw TCP transports may bypass that wrapper.
is_stream = link_name in ("mavtcp", "mavtcpin")
is_network = (
link_name == "mavudp"
or port_type in (socket.SOCK_DGRAM, socket.SOCK_STREAM)
or is_stream
)
if not is_network:
self.__write_link_data(link, b"".join(collector.packets), False)
return
batch = bytearray()
for packet in collector.packets:
if batch and len(batch) + len(packet) > MAX_NETWORK_BATCH:
self.__write_link_data(link, bytes(batch), is_stream)
batch = bytearray()
batch.extend(packet)
if batch:
self.__write_link_data(link, bytes(batch), is_stream)