-
Notifications
You must be signed in to change notification settings - Fork 597
/
mavftp.py
1666 lines (1498 loc) · 68.8 KB
/
mavftp.py
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
'''
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 Amilcar Lucas
SPDX-License-Identifier: GPL-3.0-or-later
'''
from argparse import ArgumentParser
from dataclasses import dataclass
from enum import IntEnum
import logging
import struct
import time
import random
import os
from io import BytesIO as SIO
import sys
from typing import Dict, List, Optional
from typing import Tuple
from datetime import datetime
from pymavlink import mavutil
# pylint: disable=too-many-lines
from pymavlink.mavftp_op import (
FTP_OP,
OP_Ack,
OP_BurstReadFile,
OP_ListDirectory,
OP_Nack,
OP_OpenFileRO,
OP_ReadFile,
OP_TerminateSession,
OP_ResetSessions,
OP_None,
OP_CreateFile,
OP_WriteFile,
OP_RemoveFile,
OP_RemoveDirectory,
OP_OpenFileWO,
OP_CreateDirectory,
OP_TruncateFile,
OP_Rename,
OP_CalcFileCRC32,
)
# 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
# pylint: enable=invalid-name
@dataclass
class DirectoryEntry:
"""Directory entry, either a file or a directory and the size"""
name: str
is_dir: bool
size_b: int
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):
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 ParamData:
"""
A class to manage parameter values and defaults for ArduPilot configuration.
"""
def __init__(self):
self.params = [] # params as (name, value, ptype)
self.defaults = None # defaults as (name, value, ptype)
def add_param(self, name, value, ptype):
self.params.append((name, value, ptype))
def add_default(self, name, value, ptype):
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, s_type, default):
self.name = name
self.type = s_type
self.default = default
self.value = default
class MAVFTPSettings:
"""A collection of MAVFTP settings."""
def __init__(self, s_vars):
self._vars = {}
for v in s_vars:
self.append(v)
def append(self, v):
if isinstance(v, MAVFTPSetting):
setting = v
else:
(name, s_type, default) = v
setting = MAVFTPSetting(name, s_type, default)
self._vars[setting.name] = setting
def __getattr__(self, name):
try:
return self._vars[name].value
except Exception as exc:
raise AttributeError from exc
def __setattr__(self, name, value):
if name[0] == '_':
self.__dict__[name] = value
return
if name in self._vars:
self._vars[name].value = value
return
raise AttributeError
class MAVFTPReturn:
"""The result of a MAVFTP operation."""
def __init__(self, operation_name: str, error_code: int, system_error: int=0, # pylint: disable=too-many-arguments
invalid_error_code: int=0, invalid_opcode: int=0, invalid_payload_size: int=0):
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
def display_message(self): # pylint: disable=too-many-branches
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)
@property
def return_code(self):
return self.error_code
class MAVFTP: # pylint: disable=too-many-instance-attributes
"""
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__(self, master, target_system, target_component, # pylint: disable=too-many-statements
settings=MAVFTPSettings(
[('debug', int, 0),
('pkt_loss_tx', int, 0),
('pkt_loss_rx', int, 0),
('max_backlog', int, 5),
('burst_read_size', int, 80),
('write_size', int, 80),
('write_qsize', int, 5),
('idle_detection_time', float, 1.2),
('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 = None
self.fh = None
self.filename = None
self.callback = None
self.callback_progress = None
self.put_callback = None
self.put_callback_progress = None
self.total_size = 0
self.read_gaps = []
self.read_gap_times = {}
self.last_gap_send = 0
self.read_retries = 0
self.read_total = 0
self.remote_file_size = None
self.duplicates = 0
self.last_read = None
self.last_burst_read = None
self.op_start = None
self.dir_offset = 0
self.last_op_time = time.time()
self.last_send_time = time.time()
self.rtt = 0.5
self.reached_eof = False
self.backlog = 0
self.burst_size = self.ftp_settings.burst_read_size
self.write_list = None
self.write_block_size = 0
self.write_acks = 0
self.write_total = 0
self.write_file_size = 0
self.write_idx = 0
self.write_recv_idx = -1
self.write_pending = 0
self.write_last_send = None
self.open_retries = 0
self.list_result: List[DirectoryEntry] = []
self.list_temp_result: List[DirectoryEntry] = []
self.requested_size: int = 0
self.requested_offset: int = 0
self.temp_filename = "/tmp/temp_mavftp_file"
self.master = master
self.target_system = target_system
self.target_component = target_component
self.get_result = None
self.done = False
# Reset the flight controller FTP state-machine
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) -> MAVFTPReturn: # pylint: disable=too-many-return-statements, too-many-branches
'''FTP operations'''
usage = "Usage: ftp <list|set|get|getparams|put|rm|rmdir|rename|mkdir|status|cancel|crc>"
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.ftp_settings.command(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] == 'status':
return self.cmd_status()
if args[0] == 'cancel':
return self.cmd_cancel()
logging.error(usage)
return MAVFTPReturn("FTP command", FtpError.InvalidArguments)
def __send(self, op):
'''send a request'''
op.seq = self.seq
payload = op.pack()
plen = len(payload)
if plen < MAX_Payload + HDR_Len:
payload.extend(bytearray([0]*((HDR_Len+MAX_Payload)-plen)))
self.master.mav.file_transfer_protocol_send(self.network, self.target_system, self.target_component, payload)
self.seq = (self.seq + 1) % 256
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 __terminate_session(self):
'''terminate current session'''
self.__send(FTP_OP(self.seq, self.session, OP_TerminateSession, 0, 0, 0, 0, None))
self.fh = None
self.filename = None
self.write_list = None
if self.callback is not None:
# tell caller that the transfer failed
self.callback(None)
self.callback = None
if self.callback_progress is not None:
self.callback_progress(None)
self.callback_progress = None
if self.put_callback is not None:
# tell caller that the transfer failed
self.put_callback(None)
self.put_callback = None
if self.put_callback_progress is not None:
self.put_callback_progress(None)
self.put_callback_progress = None
self.read_gaps = []
self.read_total = 0
self.read_gap_times = {}
self.last_read = None
self.last_burst_read = None
self.reached_eof = False
self.backlog = 0
self.duplicates = 0
if self.ftp_settings.debug > 0:
logging.info("FTP: Terminated session")
self.process_ftp_reply('TerminateSession')
self.session = (self.session + 1) % 256
def cmd_list(self, args) -> MAVFTPReturn:
'''list files'''
self.list_result = []
self.list_temp_result = []
if len(args) == 0:
dname = '/'
elif len(args) == 1:
dname = args[0]
else:
logging.error("Usage: list [directory]")
return MAVFTPReturn("ListDirectory", FtpError.InvalidArguments)
logging.info("Listing %s", dname)
enc_dname = bytearray(dname, 'ascii')
self.total_size = 0
self.dir_offset = 0
op = FTP_OP(self.seq, self.session, OP_ListDirectory, len(enc_dname), 0, 0, self.dir_offset, enc_dname)
self.__send(op)
return self.process_ftp_reply('ListDirectory')
def __handle_list_reply(self, op, _m) -> MAVFTPReturn:
'''handle OP_ListDirectory reply'''
output: List[DirectoryEntry] = []
if op.opcode == OP_Ack and op.payload is not None:
dentries = sorted(op.payload.split(b"\x00"))
for d in dentries:
if len(d) == 0:
continue
self.dir_offset += 1
try:
dir_entry = str(d, "ascii")
except Exception as error: # pylint: disable=broad-exception-caught
logging.debug(error)
continue
if dir_entry[0] == "D":
output.append(DirectoryEntry(name=dir_entry[1:], is_dir=True, size_b=0))
elif dir_entry[0] == "F":
(name, size_str) = dir_entry[1:].split("\t")
size = int(size_str)
output.append(DirectoryEntry(name=name, size_b=size, is_dir=False))
# ask for more
more = self.last_op
more.offset = self.dir_offset
self.__send(more)
elif op.opcode == OP_Nack and op.payload is not None and len(op.payload) == 1 and op.payload[0] == 6:
self.list_result = self.list_temp_result
self.list_temp_result.extend(output)
return MAVFTPReturn("ListDirectory", FtpError.Success)
def read_sector(self, path: str, offset: int, size: int) -> Optional[bytes]:
logging.info("reading sector %s, offset=%u, size=%u", path, offset, size)
return self.read(path, size, offset)
def read(self, path: str, size: int, offset: int = 0) -> Optional[bytes]:
"""get file"""
self.get_result = None
self.requested_offset = offset
self.requested_size = size
self.filename = path
self.done = False
logging.info("Getting %s starting at %u reading %u bytes", path, self.requested_offset, self.requested_size)
self.op_start = time.time()
self.read_total = 0
self.reached_eof = False
self.burst_size = self.ftp_settings.burst_read_size
if self.burst_size < 1:
self.burst_size = 239
elif self.burst_size > 239:
self.burst_size = 239
enc_fname = bytearray(path, "ascii")
self.open_retries = 0
op = FTP_OP(self.seq, self.session, OP_OpenFileRO, len(enc_fname), 0, 0, 0, enc_fname)
self.__send(op)
timeout = time.time() + 5
while not self.done and time.time() < timeout:
try:
m = self.master.recv_match(
type="FILE_TRANSFER_PROTOCOL",
blocking=True,
timeout=1.0,
)
if m is None:
self.__idle_task()
continue
timeout = time.time() + 5
self.__mavlink_packet(m)
except TypeError as e:
logging.error(e)
self.__idle_task()
time.sleep(0.0001)
logging.info("loop closed, gaps:%u, done: %u", self.read_gaps, self.done)
if len(self.read_gaps) == 0:
return self.get_result
logging.error("closed read with %u gaps", self.read_gaps)
return None
def cmd_get(self, args, callback=None, progress_callback=None) -> MAVFTPReturn:
'''get file'''
if len(args) == 0 or len(args) > 2:
logging.error("Usage: get [FILENAME <LOCALNAME>]")
return MAVFTPReturn("OpenFileRO", FtpError.InvalidArguments)
fname = args[0]
if len(args) > 1:
self.filename = args[1]
else:
self.filename = os.path.basename(fname)
if callback is None or self.ftp_settings.debug > 1:
logging.info("Getting %s to %s", fname, self.filename)
self.op_start = time.time()
self.callback = callback
self.callback_progress = progress_callback
self.read_retries = 0
self.duplicates = 0
self.reached_eof = False
self.burst_size = self.ftp_settings.burst_read_size
if self.burst_size < 1:
self.burst_size = 239
elif self.burst_size > 239:
self.burst_size = 239
self.remote_file_size = None
enc_fname = bytearray(fname, 'ascii')
self.open_retries = 0
op = FTP_OP(self.seq, self.session, OP_OpenFileRO, len(enc_fname), 0, 0, 0, enc_fname)
self.__send(op)
return MAVFTPReturn("OpenFileRO", FtpError.Success)
def __handle_open_ro_reply(self, op, _m) -> MAVFTPReturn:
'''handle OP_OpenFileRO reply'''
if op.opcode == OP_Ack:
if self.filename is None:
return MAVFTPReturn('OpenFileRO', FtpError.FileNotFound)
try:
if self.callback is not None or self.filename == '-':
self.fh = SIO()
else:
# pylint: disable=consider-using-with
self.fh = open(self.temp_filename, "wb+")
self.fh.truncate(0)
self.fh.seek(self.requested_offset)
read = FTP_OP(
self.seq, self.session, OP_BurstReadFile, self.burst_size, 0, 0, self.requested_offset, None
)
except Exception as ex: # pylint: disable=broad-except
logging.error("FTP: Failed to open local file %s: %s", self.filename, ex)
self.__terminate_session()
return MAVFTPReturn('OpenFileRO', FtpError.FileNotFound)
if op.size == 4 and len(op.payload) >= 4:
self.remote_file_size = op.payload[0] + (op.payload[1] << 8) + (op.payload[2] << 16) + \
(op.payload[3] << 24)
if self.ftp_settings.debug > 0:
logging.info("Remote file size: %u", self.remote_file_size)
else:
self.remote_file_size = None
read = FTP_OP(self.seq, self.session, OP_BurstReadFile, self.burst_size, 0, 0, 0, None)
self.last_burst_read = time.time()
self.__send(read)
return MAVFTPReturn('OpenFileRO', FtpError.Success)
ret = self.__decode_ftp_ack_and_nack(op)
if self.callback is None or self.ftp_settings.debug > 0:
ret.display_message()
self.__terminate_session()
return ret
def __check_read_finished(self) -> bool:
"""check if download has completed"""
if self.fh is None:
return True
if self.op_start is None:
return True
if len(self.read_gaps) == 0 and (self.reached_eof or self.read_total >= self.requested_size):
ofs = self.fh.tell()
dt = time.time() - self.op_start
rate = (ofs / dt) / 1024.0
if self.callback is not None:
self.fh.seek(0)
self.callback(self.fh)
self.callback = None
elif self.filename == "-":
self.fh.seek(0)
print(self.fh.read().decode('utf-8'))
else:
logging.info("Wrote %u/%u bytes to %s in %.2fs %.1fkByte/s",
self.read_total, self.requested_size, self.filename, dt, rate)
logging.info("terminating with %u out of %u (ofs=%u)", self.read_total, self.requested_size, ofs)
self.done = True
assert self.fh is not None
self.fh.seek(0)
result = self.fh.read()
self.get_result = result[self.requested_offset : self.requested_offset + self.requested_size]
assert self.get_result is not None
if len(self.get_result) < self.requested_size:
logging.warning("expected %u, got %u", self.requested_size, len(self.get_result))
logging.info("read %u bytes", len(self.get_result))
self.fh.flush()
self.fh.close()
self.__terminate_session()
return True
return False
def __write_payload(self, op):
'''write payload from a read op'''
self.fh.seek(op.offset)
self.fh.write(op.payload)
self.read_total += len(op.payload)
if self.callback_progress is not None and self.remote_file_size:
self.callback_progress(self.read_total/self.remote_file_size)
def __handle_burst_read(self, op, _m) -> MAVFTPReturn: # pylint: disable=too-many-branches, too-many-statements, too-many-return-statements
'''handle OP_BurstReadFile reply'''
if self.ftp_settings.pkt_loss_tx > 0:
if random.uniform(0, 100) < self.ftp_settings.pkt_loss_tx:
if self.ftp_settings.debug > 0:
logging.warning("FTP: dropping TX")
return MAVFTPReturn('BurstReadFile', FtpError.Fail)
if self.fh is None or self.filename is None:
if op.session != self.session:
# old session
return MAVFTPReturn('BurstReadFile', FtpError.InvalidSession)
logging.warning("FTP: Unexpected burst read reply. Will be discarded")
logging.info(op)
return MAVFTPReturn('BurstReadFile', FtpError.Fail)
self.last_burst_read = time.time()
size = len(op.payload)
if size > self.burst_size:
# this server doesn't handle the burst size argument
self.burst_size = MAX_Payload
if self.ftp_settings.debug > 0:
logging.info("FTP: Setting burst size to %u", self.burst_size)
if op.opcode == OP_Ack and self.fh is not None:
ofs = self.fh.tell()
if op.offset < ofs:
# writing an earlier portion, possibly remove a gap
gap = (op.offset, len(op.payload))
if gap in self.read_gaps:
self.read_gaps.remove(gap)
self.read_gap_times.pop(gap)
if self.ftp_settings.debug > 0:
logging.info("FTP: removed gap %u, %u, %u", gap, self.reached_eof, len(self.read_gaps))
else:
if self.ftp_settings.debug > 0:
logging.info("FTP: dup read reply at %u of len %u ofs=%u", op.offset, op.size, self.fh.tell())
self.duplicates += 1
return MAVFTPReturn('BurstReadFile', FtpError.Fail)
self.__write_payload(op)
self.fh.seek(ofs)
if self.__check_read_finished():
return MAVFTPReturn('BurstReadFile', FtpError.Success)
elif op.offset > ofs:
# we have a gap
gap = (ofs, op.offset-ofs)
max_read = self.burst_size
while True:
if gap[1] <= max_read:
self.read_gaps.append(gap)
self.read_gap_times[gap] = 0
break
g = (gap[0], max_read)
self.read_gaps.append(g)
self.read_gap_times[g] = 0
gap = (gap[0] + max_read, gap[1] - max_read)
self.__write_payload(op)
else:
self.__write_payload(op)
if op.burst_complete:
if op.size > 0 and op.size < self.burst_size:
# a burst complete with non-zero size and less than burst packet size
# means EOF
if not self.reached_eof and self.ftp_settings.debug > 0:
logging.info("FTP: EOF at %u with %u gaps t=%.2f", self.fh.tell(),
len(self.read_gaps), time.time() - self.op_start)
self.reached_eof = True
if self.__check_read_finished():
return MAVFTPReturn('BurstReadFile', FtpError.Success)
self.__check_read_send()
return MAVFTPReturn('BurstReadFile', FtpError.Success)
more = self.last_op
more.offset = op.offset + op.size
if self.ftp_settings.debug > 0:
logging.info("FTP: burst continue at %u %u", more.offset, self.fh.tell())
self.__send(more)
elif op.opcode == OP_Nack:
ecode = FtpError(op.payload[0])
if ecode in (FtpError.EndOfFile, 0):
if not self.reached_eof and op.offset > self.fh.tell():
# we lost the last part of the burst
if self.ftp_settings.debug > 0:
logging.error("FTP: burst lost EOF %u %u", self.fh.tell(), op.offset)
return MAVFTPReturn('BurstReadFile', FtpError.Fail)
if not self.reached_eof and self.ftp_settings.debug > 0:
logging.info("FTP: EOF at %u with %u gaps t=%.2f", self.fh.tell(),
len(self.read_gaps), time.time() - self.op_start)
self.reached_eof = True
if self.__check_read_finished():
return MAVFTPReturn('BurstReadFile', FtpError.Success)
self.__check_read_send()
elif self.ftp_settings.debug > 0:
logging.info("FTP: burst Nack (ecode:%u): %s", ecode, op)
return MAVFTPReturn('BurstReadFile', FtpError.Fail)
if self.ftp_settings.debug > 0:
logging.error("FTP: burst nack: %s", op)
return MAVFTPReturn('BurstReadFile', FtpError.Fail)
else:
logging.warning("FTP: burst error: %s", op)
return MAVFTPReturn('BurstReadFile', FtpError.Fail)
def __handle_reply_read(self, op, _m) -> MAVFTPReturn:
'''handle OP_ReadFile reply'''
if self.fh is None or self.filename is None:
if self.ftp_settings.debug > 0:
logging.warning("FTP: Unexpected read reply")
logging.warning(op)
return MAVFTPReturn('ReadFile', FtpError.Fail)
if self.backlog > 0:
self.backlog -= 1
if op.opcode == OP_Ack and self.fh is not None:
gap = (op.offset, op.size)
if gap in self.read_gaps:
self.read_gaps.remove(gap)
self.read_gap_times.pop(gap)
ofs = self.fh.tell()
self.__write_payload(op)
self.fh.seek(ofs)
if self.ftp_settings.debug > 0:
logging.info("FTP: removed gap %u, %u, %u", gap, self.reached_eof, len(self.read_gaps))
if self.__check_read_finished():
return MAVFTPReturn('ReadFile', FtpError.Success)
elif op.size < self.burst_size:
logging.info("FTP: file size changed to %u", op.offset+op.size)
self.__terminate_session()
else:
self.duplicates += 1
if self.ftp_settings.debug > 0:
logging.info("FTP: no gap read %u, %u", gap, len(self.read_gaps))
elif op.opcode == OP_Nack:
logging.info("FTP: Read failed with %u gaps %s", len(self.read_gaps), str(op))
self.__terminate_session()
self.__check_read_send()
return MAVFTPReturn('ReadFile', FtpError.Success)
def cmd_put(self, args, fh=None, callback=None, progress_callback=None) -> MAVFTPReturn:
'''put file'''
if len(args) == 0 or len(args) > 2:
logging.error("Usage: put [FILENAME <REMOTENAME>]")
return MAVFTPReturn("CreateFile", FtpError.InvalidArguments)
if self.write_list is not None:
logging.error("FTP: put already in progress")
return MAVFTPReturn("CreateFile", FtpError.PutAlreadyInProgress)
fname = args[0]
self.fh = fh
if self.fh is None:
try:
self.fh = open(fname, 'rb') # pylint: disable=consider-using-with
except Exception as ex: # pylint: disable=broad-exception-caught
logging.error("FTP: Failed to open %s: %s", fname, ex)
return MAVFTPReturn("CreateFile", FtpError.FailToOpenLocalFile)
if len(args) > 1:
self.filename = args[1]
else:
self.filename = os.path.basename(fname)
if self.filename.endswith("/"):
self.filename += os.path.basename(fname)
if callback is None:
logging.info("Putting %s to %s", fname, self.filename)
self.fh.seek(0,2)
file_size = self.fh.tell()
self.fh.seek(0)
# setup write list
self.write_block_size = self.ftp_settings.write_size
self.write_file_size = file_size
write_blockcount = file_size // self.write_block_size
if file_size % self.write_block_size != 0:
write_blockcount += 1
self.write_list = set(range(write_blockcount))
self.write_acks = 0
self.write_total = write_blockcount
self.write_idx = 0
self.write_recv_idx = -1
self.write_pending = 0
self.write_last_send = None
self.put_callback = callback
self.put_callback_progress = progress_callback
self.read_retries = 0
self.op_start = time.time()
enc_fname = bytearray(self.filename, 'ascii')
op = FTP_OP(self.seq, self.session, OP_CreateFile, len(enc_fname), 0, 0, 0, enc_fname)
self.__send(op)
return MAVFTPReturn("CreateFile", FtpError.Success)
def __put_finished(self, flen):
'''finish a put'''
if self.put_callback_progress:
self.put_callback_progress(1.0)
self.put_callback_progress = None
if self.put_callback is not None:
self.put_callback(flen)
self.put_callback = None
else:
dt = time.time() - self.op_start
rate = (flen / dt) / 1024.0
logging.info("Put %u bytes to %s file in %.2fs %.1fkByte/s", flen, self.filename, dt, rate)
def __handle_create_file_reply(self, op, _m) -> MAVFTPReturn:
'''handle OP_CreateFile reply'''
if self.fh is None:
self.__terminate_session()
return MAVFTPReturn('CreateFile', FtpError.FileNotFound)
if op.opcode == OP_Ack:
self.__send_more_writes()
else:
ret = self.__decode_ftp_ack_and_nack(op)
self.__terminate_session()
return ret
return MAVFTPReturn('CreateFile', FtpError.Success)
def __send_more_writes(self):
'''send some more writes'''
if len(self.write_list) == 0:
# all done
self.__put_finished(self.write_file_size)
self.__terminate_session()
return
now = time.time()
if self.write_last_send is not None:
if now - self.write_last_send > max(min(10*self.rtt, 1),0.2):
# we seem to have lost a block of replies
self.write_pending = max(0, self.write_pending-1)
n = min(self.ftp_settings.write_qsize-self.write_pending, len(self.write_list))
for _i in range(n):
# send in round-robin, skipping any that have been acked
idx = self.write_idx
while idx not in self.write_list:
idx = (idx + 1) % self.write_total
ofs = idx * self.write_block_size
self.fh.seek(ofs)
data = self.fh.read(self.write_block_size)
write = FTP_OP(self.seq, self.session, OP_WriteFile, len(data), 0, 0, ofs, bytearray(data))
self.__send(write)
self.write_idx = (idx + 1) % self.write_total
self.write_pending += 1
self.write_last_send = now
def __handle_write_reply(self, op, _m) -> MAVFTPReturn:
'''handle OP_WriteFile reply'''
if self.fh is None:
self.__terminate_session()
return MAVFTPReturn('WriteFile', FtpError.FileNotFound)
if op.opcode != OP_Ack:
logging.error("FTP: Write failed")
self.__terminate_session()
return MAVFTPReturn('WriteFile', FtpError.FileProtected)
# assume the FTP server processes the blocks sequentially. This means
# when we receive an ack that any blocks between the last ack and this
# one have been lost
idx = op.offset // self.write_block_size
count = (idx - self.write_recv_idx) % self.write_total
self.write_pending = max(0, self.write_pending - count)
self.write_recv_idx = idx
self.write_list.discard(idx)
self.write_acks += 1
if self.put_callback_progress:
self.put_callback_progress(self.write_acks/float(self.write_total))
self.__send_more_writes()
return MAVFTPReturn('WriteFile', FtpError.Success)
def cmd_rm(self, args) -> MAVFTPReturn:
'''remove file'''
if len(args) != 1:
logging.error("Usage: rm [FILENAME]")
return MAVFTPReturn("RemoveFile", FtpError.InvalidArguments)
fname = args[0]
logging.info("Removing file %s", fname)
enc_fname = bytearray(fname, 'ascii')
op = FTP_OP(self.seq, self.session, OP_RemoveFile, len(enc_fname), 0, 0, 0, enc_fname)
self.__send(op)
return self.process_ftp_reply('RemoveFile')
def cmd_rmdir(self, args):
'''remove directory'''
if len(args) != 1:
logging.error("Usage: rmdir [DIRECTORYNAME]")
return MAVFTPReturn("RemoveDirectory", FtpError.InvalidArguments)
dname = args[0]
logging.info("Removing directory %s", dname)
enc_dname = bytearray(dname, 'ascii')
op = FTP_OP(self.seq, self.session, OP_RemoveDirectory, len(enc_dname), 0, 0, 0, enc_dname)
self.__send(op)
return self.process_ftp_reply('RemoveDirectory')
def __handle_remove_reply(self, op, _m):
'''handle remove reply'''
return self.__decode_ftp_ack_and_nack(op)
def cmd_rename(self, args) -> MAVFTPReturn:
'''rename file or directory'''
if len(args) < 2:
logging.error("Usage: rename [OLDNAME NEWNAME]")
return MAVFTPReturn("Rename", FtpError.InvalidArguments)
name1 = args[0]
name2 = args[1]
logging.info("Renaming %s to %s", name1, name2)
enc_name1 = bytearray(name1, 'ascii')
enc_name2 = bytearray(name2, 'ascii')
enc_both = enc_name1 + b'\x00' + enc_name2
op = FTP_OP(self.seq, self.session, OP_Rename, len(enc_both), 0, 0, 0, enc_both)
self.__send(op)
return self.process_ftp_reply('Rename')
def __handle_rename_reply(self, op, _m):
'''handle rename reply'''
return self.__decode_ftp_ack_and_nack(op)
def cmd_mkdir(self, args) -> MAVFTPReturn:
'''make directory'''
if len(args) != 1:
logging.error("Usage: mkdir NAME")
return MAVFTPReturn("CreateDirectory", FtpError.InvalidArguments)
name = args[0]
logging.info("Creating directory %s", name)
enc_name = bytearray(name, 'ascii')
op = FTP_OP(self.seq, self.session, OP_CreateDirectory, len(enc_name), 0, 0, 0, enc_name)
self.__send(op)
return self.process_ftp_reply('CreateDirectory')
def __handle_mkdir_reply(self, op, _m):
'''handle mkdir reply'''
return self.__decode_ftp_ack_and_nack(op)
def cmd_crc(self, args) -> MAVFTPReturn:
'''get file crc'''
if len(args) != 1:
logging.error("Usage: crc [NAME]")
return MAVFTPReturn("CalcFileCRC32", FtpError.InvalidArguments)
name = args[0]
self.filename = name
self.op_start = time.time()
logging.info("Getting CRC for %s", name)
enc_name = bytearray(name, 'ascii')
op = FTP_OP(self.seq, self.session, OP_CalcFileCRC32, len(enc_name), 0, 0, 0, bytearray(enc_name))
self.__send(op)
return self.process_ftp_reply('CalcFileCRC32')
def __handle_crc_reply(self, op, _m):
'''handle crc reply'''
if op.opcode == OP_Ack and op.size == 4:
crc, = struct.unpack("<I", op.payload)
now = time.time()
logging.info("crc: %s 0x%08x in %.1fs", self.filename, crc, now - self.op_start)
return self.__decode_ftp_ack_and_nack(op)
def cmd_cancel(self) -> MAVFTPReturn:
'''cancel any pending op'''
self.__terminate_session()
return MAVFTPReturn("TerminateSession", FtpError.Success)
def cmd_status(self) -> MAVFTPReturn:
'''show status'''
if self.fh is None:
logging.info("No transfer in progress")
else:
ofs = self.fh.tell()
dt = time.time() - self.op_start
rate = (ofs / dt) / 1024.0
logging.info("Transfer at offset %u with %u gaps %u retries %.1f kByte/sec",
ofs, len(self.read_gaps), self.read_retries, rate)
return MAVFTPReturn("Status", FtpError.Success)
def __op_parse(self, m):
'''parse a FILE_TRANSFER_PROTOCOL msg'''
hdr = bytearray(m.payload[0:12])
(seq, session, opcode, size, req_opcode, burst_complete, _pad, offset) = struct.unpack("<HBBBBBBI", hdr)
payload = bytearray(m.payload[12:])[:size]
return FTP_OP(seq, session, opcode, size, req_opcode, burst_complete, offset, payload)
def __mavlink_packet(self, m) -> MAVFTPReturn: # pylint: disable=too-many-branches, too-many-return-statements
'''handle a mavlink packet'''
operation_name = "mavlink_packet"
mtype = m.get_type()
if mtype != "FILE_TRANSFER_PROTOCOL":
logging.error("FTP: Unexpected MAVLink message type %s", mtype)
return MAVFTPReturn(operation_name, FtpError.Fail)
if m.target_system != self.master.source_system or m.target_component != self.master.source_component:
logging.info("FTP: wrong MAVLink target %u component %u. Will discard message",
m.target_system, m.target_component)
return MAVFTPReturn(operation_name, FtpError.Fail)
op = self.__op_parse(m)
now = time.time()
dt = now - self.last_op_time
if self.ftp_settings.debug > 1:
logging.info("FTP: < %s dt=%.2f", op, dt)
if op.session != self.session:
if self.ftp_settings.debug > 0:
logging.warning("FTP: wrong session replied %u expected %u. Will discard message",
op.session, self.session)
return MAVFTPReturn(operation_name, FtpError.InvalidSession)
self.last_op_time = now
if self.ftp_settings.pkt_loss_rx > 0:
if random.uniform(0, 100) < self.ftp_settings.pkt_loss_rx:
if self.ftp_settings.debug > 1:
logging.warning("FTP: dropping packet RX")
return MAVFTPReturn(operation_name, FtpError.Fail)
if op.req_opcode == self.last_op.opcode and op.seq == (self.last_op.seq + 1) % 256:
self.rtt = max(min(self.rtt, dt), 0.01)