forked from ArduPilot/pymavlink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mavftp.py
1621 lines (1455 loc) · 66.7 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
import logging
import struct
import time
import random
import os
from io import BytesIO as SIO
import sys
from typing import Dict
from typing import Tuple
from datetime import datetime
from pymavlink import mavutil
# pylint: disable=too-many-lines
# pylint: disable=invalid-name
# opcodes
OP_None = 0
OP_TerminateSession = 1
OP_ResetSessions = 2
OP_ListDirectory = 3
OP_OpenFileRO = 4
OP_ReadFile = 5
OP_CreateFile = 6
OP_WriteFile = 7
OP_RemoveFile = 8
OP_CreateDirectory = 9
OP_RemoveDirectory = 10
OP_OpenFileWO = 11
OP_TruncateFile = 12
OP_Rename = 13
OP_CalcFileCRC32 = 14
OP_BurstReadFile = 15
OP_Ack = 128
OP_Nack = 129
# error codes
ERR_None = 0
ERR_Fail = 1
ERR_FailErrno = 2
ERR_InvalidDataSize = 3
ERR_InvalidSession = 4
ERR_NoSessionsAvailable = 5
ERR_EndOfFile = 6
ERR_UnknownCommand = 7
ERR_FileExists = 8
ERR_FileProtected = 9
ERR_FileNotFound = 10
ERR_NoErrorCodeInPayload = 64
ERR_NoErrorCodeInNack = 65
ERR_NoFilesystemErrorInPayload = 66
ERR_InvalidErrorCode = 67
ERR_PayloadTooLarge = 68
ERR_InvalidOpcode = 69
ERR_InvalidArguments = 70
ERR_PutAlreadyInProgress = 71
ERR_FailToOpenLocalFile = 72
ERR_RemoteReplyTimeout = 73
HDR_Len = 12
MAX_Payload = 239
# pylint: enable=invalid-name
class FTP_OP: # pylint: disable=invalid-name, too-many-instance-attributes
"""
Represents an operation in the MAVLink File Transfer Protocol (FTP).
This class encapsulates the details of a single FTP operation such as reading, writing, listing directories, etc.,
including the necessary parameters and payload for the operation.
"""
def __init__(self, seq, session, opcode, size, # pylint: disable=too-many-arguments
req_opcode, burst_complete, offset, payload):
self.seq = seq # Sequence number for the operation.
self.session = session # Session identifier.
self.opcode = opcode # Operation code indicating the type of FTP operation.
self.size = size # Size of the operation.
self.req_opcode = req_opcode # Request operation code.
self.burst_complete = burst_complete # (bool) Flag indicating if the burst transfer is complete.
self.offset = offset # Offset for read/write operations.
self.payload = payload # (bytes) Payload for the operation.
def pack(self):
'''pack message'''
ret = struct.pack("<HBBBBBBI", self.seq, self.session, self.opcode, self.size, self.req_opcode, self.burst_complete,
0, self.offset)
if self.payload is not None:
ret += self.payload
ret = bytearray(ret)
return ret
def __str__(self):
plen = 0
if self.payload is not None:
plen = len(self.payload)
ret = f"OP seq:{self.seq} sess:{self.session} opcode:{self.opcode} req_opcode:{self.req_opcode}" \
f" size:{self.size} bc:{self.burst_complete} ofs:{self.offset} plen={plen}"
if plen > 0:
ret += f" [{self.payload[0]}]"
return ret
def items(self):
"""Yield each attribute and its value for the FTP_OP instance. For debugging purposes."""
yield "seq", self.seq
yield "session", self.session
yield "opcode", self.opcode
yield "size", self.size
yield "req_opcode", self.req_opcode
yield "burst_complete", self.burst_complete
yield "offset", self.offset
yield "payload", self.payload
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 == ERR_None:
logging.info("%s succeeded", self.operation_name)
elif self.error_code == ERR_Fail:
logging.error("%s failed, generic error", self.operation_name)
elif self.error_code == ERR_FailErrno:
logging.error("%s failed, system error %u", self.operation_name, self.system_error)
elif self.error_code == ERR_InvalidDataSize:
logging.error("%s failed, invalid data size", self.operation_name)
elif self.error_code == ERR_InvalidSession:
logging.error("%s failed, session is not currently open", self.operation_name)
elif self.error_code == ERR_NoSessionsAvailable:
logging.error("%s failed, no sessions available", self.operation_name)
elif self.error_code == ERR_EndOfFile:
logging.error("%s failed, offset past end of file", self.operation_name)
elif self.error_code == ERR_UnknownCommand:
logging.error("%s failed, unknown command", self.operation_name)
elif self.error_code == ERR_FileExists:
logging.warning("%s failed, file/directory already exists", self.operation_name)
elif self.error_code == ERR_FileProtected:
logging.warning("%s failed, file/directory is protected", self.operation_name)
elif self.error_code == ERR_FileNotFound:
logging.warning("%s failed, file/directory not found", self.operation_name)
elif self.error_code == ERR_NoErrorCodeInPayload:
logging.error("%s failed, payload contains no error code", self.operation_name)
elif self.error_code == ERR_NoErrorCodeInNack:
logging.error("%s failed, no error code", self.operation_name)
elif self.error_code == ERR_NoFilesystemErrorInPayload:
logging.error("%s failed, file-system error missing in payload", self.operation_name)
elif self.error_code == ERR_InvalidErrorCode:
logging.error("%s failed, invalid error code %u", self.operation_name, self.invalid_error_code)
elif self.error_code == ERR_PayloadTooLarge:
logging.error("%s failed, payload is too long %u", self.operation_name, self.invalid_payload_size)
elif self.error_code == ERR_InvalidOpcode:
logging.error("%s failed, invalid opcode %u", self.operation_name, self.invalid_opcode)
elif self.error_code == ERR_InvalidArguments:
logging.error("%s failed, invalid arguments", self.operation_name)
elif self.error_code == ERR_PutAlreadyInProgress:
logging.error("%s failed, put already in progress", self.operation_name)
elif self.error_code == ERR_FailToOpenLocalFile:
logging.error("%s failed, failed to open local file", self.operation_name)
elif self.error_code == ERR_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,
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.master = master
self.target_system = target_system
self.target_component = target_component
# 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", ERR_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", ERR_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'''
if len(args) == 0:
dname = '/'
elif len(args) == 1:
dname = args[0]
else:
logging.error("Usage: list [directory]")
return MAVFTPReturn("ListDirectory", ERR_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'''
if op.opcode == OP_Ack:
dentries = sorted(op.payload.split(b'\x00'))
#logging.info(dentries)
for d in dentries:
if len(d) == 0:
continue
self.dir_offset += 1
try:
d = str(d, 'ascii')
except Exception: # pylint: disable=broad-exception-caught
continue
if d[0] == 'D':
logging.info(" D %s", d[1:])
elif d[0] == 'F':
(name, size) = d[1:].split('\t')
size = int(size)
self.total_size += size
logging.info(" %s\t%u", name, size)
else:
logging.info(d)
# ask for more
more = self.last_op
more.offset = self.dir_offset
self.__send(more)
elif op.opcode == OP_Nack and len(op.payload) == 1 and op.payload[0] == ERR_EndOfFile:
logging.info("Total size %.2f kByte", self.total_size / 1024.0)
self.total_size = 0
else:
return self.__decode_ftp_ack_and_nack(op)
return MAVFTPReturn("ListDirectory", ERR_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", ERR_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", ERR_None)
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', ERR_FileNotFound)
try:
if self.callback is not None or self.filename == '-':
self.fh = SIO()
else:
self.fh = open(self.filename, 'wb') # pylint: disable=consider-using-with
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', ERR_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', ERR_None)
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):
'''check if download has completed'''
#logging.debug("FTP: check_read_finished: %s %s", self.reached_eof, self.read_gaps)
if self.reached_eof and len(self.read_gaps) == 0:
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("Got %u bytes from %s in %.2fs %.1fkByte/s", ofs, self.filename, dt, rate)
self.remote_file_size = None
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', ERR_Fail)
if self.fh is None or self.filename is None:
if op.session != self.session:
# old session
return MAVFTPReturn('BurstReadFile', ERR_InvalidSession)
logging.warning("FTP: Unexpected burst read reply. Will be discarded")
logging.info(op)
return MAVFTPReturn('BurstReadFile', ERR_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', ERR_Fail)
self.__write_payload(op)
self.fh.seek(ofs)
if self.__check_read_finished():
return MAVFTPReturn('BurstReadFile', ERR_None)
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', ERR_None)
self.__check_read_send()
return MAVFTPReturn('BurstReadFile', ERR_None)
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 = op.payload[0]
if ecode in (ERR_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', ERR_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', ERR_None)
self.__check_read_send()
elif self.ftp_settings.debug > 0:
logging.info("FTP: burst Nack (ecode:%u): %s", ecode, op)
return MAVFTPReturn('BurstReadFile', ERR_Fail)
if self.ftp_settings.debug > 0:
logging.error("FTP: burst nack: %s", op)
return MAVFTPReturn('BurstReadFile', ERR_Fail)
else:
logging.warning("FTP: burst error: %s", op)
return MAVFTPReturn('BurstReadFile', ERR_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', ERR_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', ERR_None)
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', ERR_None)
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", ERR_InvalidArguments)
if self.write_list is not None:
logging.error("FTP: put already in progress")
return MAVFTPReturn("CreateFile", ERR_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", ERR_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", ERR_None)
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', ERR_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', ERR_None)
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', ERR_FileNotFound)
if op.opcode != OP_Ack:
logging.error("FTP: Write failed")
self.__terminate_session()
return MAVFTPReturn('WriteFile', ERR_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', ERR_None)
def cmd_rm(self, args) -> MAVFTPReturn:
'''remove file'''
if len(args) != 1:
logging.error("Usage: rm [FILENAME]")
return MAVFTPReturn("RemoveFile", ERR_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", ERR_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", ERR_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", ERR_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", ERR_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", ERR_None)
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", ERR_None)
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, ERR_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, ERR_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, ERR_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, ERR_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)
if op.req_opcode == OP_ListDirectory:
return self.__handle_list_reply(op, m)
if op.req_opcode == OP_OpenFileRO:
return self.__handle_open_ro_reply(op, m)
if op.req_opcode == OP_BurstReadFile:
return self.__handle_burst_read(op, m)
if op.req_opcode == OP_ResetSessions:
return self.__handle_reset_sessions_reply(op, m)
if op.req_opcode in [OP_None, OP_TerminateSession]:
return MAVFTPReturn(operation_name, ERR_None) # ignore reply
if op.req_opcode == OP_CreateFile:
return self.__handle_create_file_reply(op, m)
if op.req_opcode == OP_WriteFile:
return self.__handle_write_reply(op, m)
if op.req_opcode in [OP_RemoveFile, OP_RemoveDirectory]:
return self.__handle_remove_reply(op, m)
if op.req_opcode == OP_Rename:
return self.__handle_rename_reply(op, m)
if op.req_opcode == OP_CreateDirectory:
return self.__handle_mkdir_reply(op, m)
if op.req_opcode == OP_ReadFile:
return self.__handle_reply_read(op, m)
if op.req_opcode == OP_CalcFileCRC32:
return self.__handle_crc_reply(op, m)
logging.info('FTP Unknown %s', str(op))
return MAVFTPReturn(operation_name, ERR_InvalidOpcode)
def __send_gap_read(self, g):
'''send a read for a gap'''
(offset, length) = g
if self.ftp_settings.debug > 0:
logging.info("FTP: Gap read of %u at %u rem=%u blog=%u", length, offset, len(self.read_gaps), self.backlog)
read = FTP_OP(self.seq, self.session, OP_ReadFile, length, 0, 0, offset, None)
self.__send(read)
self.read_gaps.remove(g)
self.read_gaps.append(g)
self.last_gap_send = time.time()
self.read_gap_times[g] = self.last_gap_send
self.backlog += 1