QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
FTPManager.cc
Go to the documentation of this file.
1#include "FTPManager.h"
2#include "MAVLinkProtocol.h"
3#include "AppMessages.h"
5#include "Vehicle.h"
8
9#include <QtCore/QFile>
10#include <QtCore/QFileInfo>
11#include <QtCore/QDir>
12#include <cerrno>
13#include <iterator>
14#include <limits>
15
16QGC_LOGGING_CATEGORY(FTPManagerLog, "Vehicle.FTPManager")
17
19 : QObject (vehicle)
20 , _vehicle (vehicle)
21{
22 _ackOrNakTimeoutTimer.setSingleShot(true);
23 _ackOrNakTimeoutTimer.setInterval(QGC::runningUnitTests() ? kTestAckTimeoutMs : _ackOrNakTimeoutMsecs);
24 connect(&_ackOrNakTimeoutTimer, &QTimer::timeout, this, &FTPManager::_ackOrNakTimeout);
25
26 // Make sure we don't have bad structure packing
27 static_assert(sizeof(MavlinkFTP::RequestHeader) == 12, "MavlinkFTP::RequestHeader must be 12 bytes");
28
29 _uploadState.reset();
30}
31
32bool FTPManager::download(uint8_t fromCompId, const QString& fromURI, const QString& toDir, const QString& fileName, bool checksize)
33{
34 qCDebug(FTPManagerLog) << "Download fromCompId:" << fromCompId
35 << "fromURI:" << fromURI
36 << "to:" << toDir
37 << "fileName:" << fileName;
38
39 if (!_rgStateMachine.isEmpty()) {
40 qCDebug(FTPManagerLog) << "Cannot download. Already in another operation";
41 return false;
42 }
43
44 // An empty path would make QDir fall back to the current working directory.
45 if (toDir.isEmpty()) {
46 qCWarning(FTPManagerLog) << "Cannot download. Destination directory is not set";
47 return false;
48 }
49 if (!QDir(toDir).exists()) {
50 qCWarning(FTPManagerLog) << "Cannot download. Destination directory does not exist:" << toDir;
51 return false;
52 }
53
54 _downloadState.reset();
55 _downloadState.toDir.setPath(toDir);
56 _downloadState.checksize = checksize;
57
58 if (!_parseURI(fromCompId, fromURI, _downloadState.fullPathOnVehicle, _ftpCompId)) {
59 qCWarning(FTPManagerLog) << "_parseURI failed";
60 return false;
61 }
62
63 // We need to strip off the file name from the fully qualified path. We can't use the usual QDir
64 // routines because this path does not exist locally.
65 int lastDirSlashIndex;
66 for (lastDirSlashIndex=_downloadState.fullPathOnVehicle.size()-1; lastDirSlashIndex>=0; lastDirSlashIndex--) {
67 if (_downloadState.fullPathOnVehicle[lastDirSlashIndex] == '/') {
68 break;
69 }
70 }
71 lastDirSlashIndex++; // move past slash
72
73 if (fileName.isEmpty()) {
74 _downloadState.fileName = _downloadState.fullPathOnVehicle.right(_downloadState.fullPathOnVehicle.size() - lastDirSlashIndex);
75 } else {
76 // fileName can originate from the vehicle: a MAVLink-FTP ListDirectory entry is
77 // surfaced to QML and handed straight back here as the local name. Reduce it the
78 // same way the derived branch above already does, so it cannot act as a path.
79 _downloadState.fileName = QFileInfo(fileName).fileName();
80 }
81
82 qCDebug(FTPManagerLog) << "_downloadState.fullPathOnVehicle:_downloadState.fileName" << _downloadState.fullPathOnVehicle << _downloadState.fileName;
83
84 static const StateFunctions_t rgDownloadStateMachine[] = {
85 { &FTPManager::_openFileROBegin, &FTPManager::_openFileROAckOrNak, &FTPManager::_openFileROTimeout },
86 { &FTPManager::_burstReadFileBegin, &FTPManager::_burstReadFileAckOrNak, &FTPManager::_burstReadFileTimeout },
87 { &FTPManager::_fillMissingBlocksBegin, &FTPManager::_fillMissingBlocksAckOrNak, &FTPManager::_fillMissingBlocksTimeout },
88 { &FTPManager::_resetSessionsBegin, &FTPManager::_resetSessionsAckOrNak, &FTPManager::_resetSessionsTimeout },
89 { &FTPManager::_downloadCompleteNoError, nullptr, nullptr },
90 };
91 _setStateMachine(rgDownloadStateMachine, std::size(rgDownloadStateMachine));
92
93 _downloadState.active = true;
94 _startStateMachine();
95
96 return true;
97}
98
99bool FTPManager::upload(uint8_t toCompId, const QString& toURI, const QString& fromFile)
100{
101 qCDebug(FTPManagerLog) << "upload fromFile:" << fromFile << "toURI:" << toURI << "toCompId:" << toCompId;
102
103 if (!_rgStateMachine.isEmpty()) {
104 qCDebug(FTPManagerLog) << "Cannot upload. Already in another operation";
105 return false;
106 }
107
108 QFileInfo sourceInfo(fromFile);
109 if (!sourceInfo.exists() || !sourceInfo.isFile()) {
110 qCWarning(FTPManagerLog) << "Cannot upload. Source file missing" << fromFile;
111 return false;
112 }
113
114 if (sourceInfo.size() > std::numeric_limits<uint32_t>::max()) {
115 qCWarning(FTPManagerLog) << "Cannot upload. File too large" << fromFile << sourceInfo.size();
116 return false;
117 }
118
119 _uploadState.reset();
120 _uploadState.localFilePath = fromFile;
121 _uploadState.file.setFileName(fromFile);
122 if (!_uploadState.file.open(QFile::ReadOnly)) {
123 qCWarning(FTPManagerLog) << "Cannot upload. Failed to open file" << fromFile << _uploadState.file.errorString();
124 _uploadState.reset();
125 return false;
126 }
127
128 _uploadState.fileSize = static_cast<uint32_t>(sourceInfo.size());
129 _uploadState.totalBytesSent = 0;
130 _uploadState.lastChunkSize = 0;
131 _uploadState.retryCount = 0;
132 _uploadState.sessionId = 0;
133 _uploadState.cancelled = false;
134
135 if (!_parseURI(toCompId, toURI, _uploadState.fullPathOnVehicle, _ftpCompId)) {
136 qCWarning(FTPManagerLog) << "_parseURI failed";
137 _uploadState.reset();
138 return false;
139 }
140
141 static const StateFunctions_t rgUploadStateMachine[] = {
142 { &FTPManager::_createFileBegin, &FTPManager::_createFileAckOrNak, &FTPManager::_createFileTimeout },
143 { &FTPManager::_writeFileBegin, &FTPManager::_writeFileAckOrNak, &FTPManager::_writeFileTimeout },
144 { &FTPManager::_resetSessionsBegin, &FTPManager::_resetSessionsAckOrNak, &FTPManager::_resetSessionsTimeout },
145 { &FTPManager::_uploadFinalize, nullptr, nullptr },
146 };
147 _setStateMachine(rgUploadStateMachine, std::size(rgUploadStateMachine));
148
149 _startStateMachine();
150
151 return true;
152}
153
154bool FTPManager::listDirectory(uint8_t fromCompId, const QString& fromURI)
155{
156 qCDebug(FTPManagerLog) << "list directory fromURI:" << fromURI << "fromCompId:" << fromCompId;
157
158 if (!_rgStateMachine.isEmpty()) {
159 qCDebug(FTPManagerLog) << "Cannot list directory. Already in another operation";
160 return false;
161 }
162
163 _listDirectoryState.reset();
164
165 // Prefer the timestamped listing unless we already learned this vehicle doesn't support it.
166 _listDirectoryState.opCode = (_listDirWithTimeSupport == WithTimeSupport_t::Unsupported)
169
170 // Re-report the cached capability on every listing so any log capture window shows it
171 const char* supportStr =
172 (_listDirWithTimeSupport == WithTimeSupport_t::Supported) ? "vehicle supports it" :
173 (_listDirWithTimeSupport == WithTimeSupport_t::Unsupported) ? "vehicle Nak'ed it earlier this connection" :
174 "support unknown, probing";
175 qCDebug(FTPManagerLog) << "listDirectory using" << MavlinkFTP::opCodeToString(_listDirectoryState.opCode)
176 << "-" << supportStr;
177
178 if (!_parseURI(fromCompId, fromURI, _listDirectoryState.fullPathOnVehicle, _ftpCompId)) {
179 qCWarning(FTPManagerLog) << "_parseURI failed";
180 return false;
181 }
182
183 qCDebug(FTPManagerLog) << "_listDirectoryState.fullPathOnVehicle" << _listDirectoryState.fullPathOnVehicle;
184
185 static const StateFunctions_t rgStateMachine[] = {
186 { &FTPManager::_listDirectoryBegin, &FTPManager::_listDirectoryAckOrNak, &FTPManager::_listDirectoryTimeout },
187 { &FTPManager::_listDirectoryCompleteNoError, nullptr, nullptr },
188 };
189 _setStateMachine(rgStateMachine, std::size(rgStateMachine));
190
191 _startStateMachine();
192
193 return true;
194}
195
196bool FTPManager::deleteFile(uint8_t fromCompId, const QString& fromURI)
197{
198 qCDebug(FTPManagerLog) << "delete file fromURI:" << fromURI << "fromCompId:" << fromCompId;
199
200 if (!_rgStateMachine.isEmpty()) {
201 qCDebug(FTPManagerLog) << "Cannot delete file. Already in another operation";
202 return false;
203 }
204
205 _deleteState.reset();
206
207 if (!_parseURI(fromCompId, fromURI, _deleteState.fullPathOnVehicle, _ftpCompId)) {
208 qCWarning(FTPManagerLog) << "_parseURI failed";
209 return false;
210 }
211
212 qCDebug(FTPManagerLog) << "_deleteState.fullPathOnVehicle" << _deleteState.fullPathOnVehicle;
213
214 static const StateFunctions_t rgStateMachine[] = {
215 { &FTPManager::_deleteFileBegin, &FTPManager::_deleteFileAckOrNak, &FTPManager::_deleteFileTimeout },
216 { &FTPManager::_deleteCompleteNoError, nullptr, nullptr },
217 };
218 _setStateMachine(rgStateMachine, std::size(rgStateMachine));
219
220 _startStateMachine();
221
222 return true;
223}
224
226{
227 if (!_downloadState.inProgress()) {
228 return;
229 }
230
231 // No point waiting for a Terminate ack on a download we are abandoning; _downloadComplete releases the
232 // vehicle session with a fire-and-forget reset instead.
233 _downloadComplete(tr("Aborted"));
234}
235
237{
238 if (!_listDirectoryState.inProgress()) {
239 return;
240 }
241
242 if (_rgStateMachine.isEmpty()) {
243 return;
244 }
245
246 _listDirectoryComplete(tr("Aborted"));
247}
248
250{
251 if (!_uploadState.inProgress()) {
252 return;
253 }
254
255 _uploadState.cancelled = true;
256 _ackOrNakTimeoutTimer.stop();
257 _rgStateMachine.clear();
258
259 if (_uploadState.sessionId != 0) {
260 static const StateFunctions_t rgTerminateStateMachine[] = {
261 { &FTPManager::_terminateUploadSessionBegin, &FTPManager::_terminateUploadSessionAckOrNak, &FTPManager::_terminateUploadSessionTimeout },
262 { &FTPManager::_uploadFinalize, nullptr, nullptr },
263 };
264 for (size_t i=0; i<sizeof(rgTerminateStateMachine)/sizeof(rgTerminateStateMachine[0]); i++) {
265 _rgStateMachine.append(rgTerminateStateMachine[i]);
266 }
267 _uploadState.retryCount = 0;
268 _startStateMachine();
269 } else {
270 _uploadComplete(tr("Aborted"));
271 }
272}
273
275{
276 if (!_deleteState.inProgress()) {
277 return;
278 }
279
280 _deleteComplete(tr("Aborted"));
281}
282
285void FTPManager::_downloadComplete(const QString& errorMsg)
286{
287 qCDebug(FTPManagerLog) << QString("_downloadComplete: errorMsg(%1)").arg(errorMsg);
288
289 QString downloadFilePath = _downloadState.toDir.absoluteFilePath(_downloadState.fileName);
290 QString error = errorMsg;
291
292 _ackOrNakTimeoutTimer.stop();
293 _rgStateMachine.clear();
294 _currentStateMachineIndex = -1;
295 if (_downloadState.file.isOpen()) {
296 _downloadState.file.close();
297 if (!errorMsg.isEmpty()) {
298 _downloadState.file.remove();
299 }
300 }
301
302 // Abandoning a session leaves single-session servers (PX4) unable to open anything else. Sent even if the
303 // open never acked: the server may have opened it after we gave up.
304 if (!errorMsg.isEmpty()) {
305 _sendResetSessionsNoAck();
306 }
307 _downloadState.active = false;
308
309 emit downloadComplete(downloadFilePath, errorMsg);
310}
311
314void FTPManager::_listDirectoryComplete(const QString& errorMsg)
315{
316 qCDebug(FTPManagerLog) << QString("_listDirectoryComplete: errorMsg(%1)").arg(errorMsg);
317
318 _ackOrNakTimeoutTimer.stop();
319 _rgStateMachine.clear();
320 _currentStateMachineIndex = -1;
321
322 QStringList rgDirectoryList = _listDirectoryState.rgDirectoryList;
323 if (!errorMsg.isEmpty()) {
324 rgDirectoryList.clear();
325 }
326
327 _listDirectoryState.reset();
328
329 emit listDirectoryComplete(errorMsg.isEmpty() ? rgDirectoryList : QStringList(), errorMsg);
330}
331
332void FTPManager::_deleteFileBegin(void)
333{
334 qCDebug(FTPManagerLog) << "file" << _deleteState.fullPathOnVehicle;
335
336 MavlinkFTP::Request request{};
337 request.hdr.session = 0;
338 request.hdr.opcode = MavlinkFTP::kCmdRemoveFile;
339 request.hdr.offset = 0;
340 request.hdr.size = 0;
341 _fillRequestDataWithString(&request, _deleteState.fullPathOnVehicle);
342 _sendRequestExpectAck(&request);
343}
344
345void FTPManager::_deleteFileAckOrNak(const MavlinkFTP::Request* ackOrNak)
346{
347 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
348 if (requestOpCode != MavlinkFTP::kCmdRemoveFile) {
349 qCDebug(FTPManagerLog) << "_deleteFileAckOrNak: Ack disregarding ack for incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
350 return;
351 }
352 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
353 qCDebug(FTPManagerLog) << "_deleteFileAckOrNak: Ack disregarding ack for incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
354 return;
355 }
356
357 _ackOrNakTimeoutTimer.stop();
358
359 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
360 _advanceStateMachine();
361 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
362 qCDebug(FTPManagerLog) << "_deleteFileAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
363 _deleteComplete(tr("Delete failed") + ": " + _errorMsgFromNak(ackOrNak));
364 }
365}
366
367void FTPManager::_deleteFileTimeout(void)
368{
369 if (++_deleteState.retryCount > _maxRetry) {
370 qCDebug(FTPManagerLog) << QString("_deleteFileTimeout retries exceeded");
371 _deleteComplete(tr("Delete failed"));
372 } else {
373 qCDebug(FTPManagerLog) << QString("_deleteFileTimeout: retrying - retryCount(%1)").arg(_deleteState.retryCount);
374 _deleteFileBegin();
375 }
376}
377
378void FTPManager::_deleteComplete(const QString& errorMsg)
379{
380 qCDebug(FTPManagerLog) << QString("_deleteComplete: errorMsg(%1)").arg(errorMsg);
381
382 const QString deletedPath = _deleteState.fullPathOnVehicle;
383
384 _ackOrNakTimeoutTimer.stop();
385 _rgStateMachine.clear();
386 _currentStateMachineIndex = -1;
387
388 _deleteState.reset();
389
390 emit deleteComplete(deletedPath, errorMsg);
391}
392
393void FTPManager::_createFileBegin(void)
394{
395 qCDebug(FTPManagerLog) << "file" << _uploadState.fullPathOnVehicle;
396
397 MavlinkFTP::Request request{};
398 request.hdr.session = 0;
399 request.hdr.opcode = MavlinkFTP::kCmdCreateFile;
400 request.hdr.offset = 0;
401 request.hdr.size = 0;
402 _fillRequestDataWithString(&request, _uploadState.fullPathOnVehicle);
403 _sendRequestExpectAck(&request);
404}
405
406void FTPManager::_createFileAckOrNak(const MavlinkFTP::Request* ackOrNak)
407{
408 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
409 if (requestOpCode != MavlinkFTP::kCmdCreateFile) {
410 qCDebug(FTPManagerLog) << "_createFileAckOrNak: Ack disregarding ack for incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
411 return;
412 }
413 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
414 qCDebug(FTPManagerLog) << "_createFileAckOrNak: Ack disregarding ack for incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
415 return;
416 }
417
418 _ackOrNakTimeoutTimer.stop();
419
420 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
421 qCDebug(FTPManagerLog) << "_createFileAckOrNak: Ack - sessionId" << ackOrNak->hdr.session;
422
423 _uploadState.sessionId = ackOrNak->hdr.session;
424 _advanceStateMachine();
425 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
426 qCDebug(FTPManagerLog) << "_createFileAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
427 _uploadComplete(tr("Upload failed for: %1 - error: %2").arg(_uploadState.fullPathOnVehicle).arg(_errorMsgFromNak(ackOrNak)));
428 }
429}
430
431void FTPManager::_createFileTimeout(void)
432{
433 qCDebug(FTPManagerLog) << "_createFileTimeout";
434 _uploadComplete(tr("Upload failed for: %1 - no response from vehicle").arg(_uploadState.fullPathOnVehicle));
435}
436
437void FTPManager::_writeFileBegin(void)
438{
439 _writeFileWorker(true /* firstRequest */);
440}
441
442void FTPManager::_writeFileWorker(bool firstRequest)
443{
444 if (!_uploadState.file.isOpen()) {
445 _uploadComplete(tr("Upload failed for: %1 - file not open").arg(_uploadState.fullPathOnVehicle));
446 return;
447 }
448
449 if (_uploadState.totalBytesSent >= _uploadState.fileSize) {
450 _advanceStateMachine();
451 return;
452 }
453
454 qCDebug(FTPManagerLog) << "_writeFileWorker: offset:firstRequest:retryCount" << _uploadState.totalBytesSent << firstRequest << _uploadState.retryCount;
455
456 MavlinkFTP::Request request{};
457 request.hdr.session = _uploadState.sessionId;
458 request.hdr.opcode = MavlinkFTP::kCmdWriteFile;
459 request.hdr.offset = _uploadState.totalBytesSent;
460
461 if (firstRequest) {
462 _uploadState.retryCount = 0;
463 } else {
464 _expectedIncomingSeqNumber -= 2;
465 }
466
467 qint64 bytesRemaining = static_cast<qint64>(_uploadState.fileSize) - static_cast<qint64>(_uploadState.totalBytesSent);
468 qint64 bytesToSend = bytesRemaining;
469 if (bytesToSend > static_cast<qint64>(sizeof(request.data))) {
470 bytesToSend = sizeof(request.data);
471 }
472
473 if (!_uploadState.file.seek(_uploadState.totalBytesSent)) {
474 qCDebug(FTPManagerLog) << "_writeFileWorker: seek failed" << _uploadState.file.errorString();
475 _uploadComplete(tr("Upload failed for: %1 - error reading file").arg(_uploadState.fullPathOnVehicle));
476 return;
477 }
478
479 qint64 bytesRead = _uploadState.file.read(reinterpret_cast<char*>(request.data), bytesToSend);
480 if (bytesRead != bytesToSend) {
481 qCDebug(FTPManagerLog) << "_writeFileWorker: read failed" << _uploadState.file.errorString();
482 _uploadComplete(tr("Upload failed for: %1 - error reading file").arg(_uploadState.fullPathOnVehicle));
483 return;
484 }
485
486 request.hdr.size = static_cast<uint8_t>(bytesRead);
487 _uploadState.lastChunkSize = static_cast<uint32_t>(bytesRead);
488
489 _sendRequestExpectAck(&request);
490}
491
492void FTPManager::_writeFileAckOrNak(const MavlinkFTP::Request* ackOrNak)
493{
494 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
495
496 if (requestOpCode != MavlinkFTP::kCmdWriteFile) {
497 qCDebug(FTPManagerLog) << "_writeFileAckOrNak: Disregarding due to incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
498 return;
499 }
500 if (ackOrNak->hdr.session != _uploadState.sessionId) {
501 qCDebug(FTPManagerLog) << "_writeFileAckOrNak: Disregarding due to incorrect session id actual:expected" << ackOrNak->hdr.session << _uploadState.sessionId;
502 return;
503 }
504
505 _ackOrNakTimeoutTimer.stop();
506
507 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
508 if (ackOrNak->hdr.seqNumber < _expectedIncomingSeqNumber) {
509 qCDebug(FTPManagerLog) << "_writeFileAckOrNak: Disregarding Ack due to incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
510 return;
511 }
512
513 if (ackOrNak->hdr.size != 0) {
514 qCDebug(FTPManagerLog) << "_writeFileAckOrNak: unexpected ack size expected:actual 0" << ackOrNak->hdr.size;
515 }
516
517 _uploadState.totalBytesSent += _uploadState.lastChunkSize;
518 _uploadState.lastChunkSize = 0;
519 _expectedIncomingSeqNumber = ackOrNak->hdr.seqNumber;
520
521 if (_uploadState.fileSize != 0) {
522 emit commandProgress(static_cast<float>(_uploadState.totalBytesSent) / static_cast<float>(_uploadState.fileSize));
523 }
524
525 if (_uploadState.totalBytesSent >= _uploadState.fileSize) {
526 _advanceStateMachine();
527 } else {
528 _writeFileWorker(true /* firstRequest */);
529 }
530 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
531 qCDebug(FTPManagerLog) << "_writeFileAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
532 _uploadComplete(tr("Upload failed for: %1 - error: %2").arg(_uploadState.fullPathOnVehicle).arg(_errorMsgFromNak(ackOrNak)));
533 }
534}
535
536void FTPManager::_writeFileTimeout(void)
537{
538 if (++_uploadState.retryCount > _maxRetry) {
539 qCDebug(FTPManagerLog) << QString("_writeFileTimeout retries exceeded");
540 _uploadComplete(tr("Upload failed for: %1 - no response from vehicle").arg(_uploadState.fullPathOnVehicle));
541 } else {
542 qCDebug(FTPManagerLog) << QString("_writeFileTimeout: retrying - retryCount(%1) offset(%2)").arg(_uploadState.retryCount).arg(_uploadState.totalBytesSent);
543 _writeFileWorker(false /* firstRequest */);
544 }
545}
546
547void FTPManager::_terminateUploadSessionBegin(void)
548{
549 if (_uploadState.sessionId == 0) {
550 qCWarning(FTPManagerLog) << "_terminateUploadSessionBegin: No session to terminate";
551 _advanceStateMachine();
552 return;
553 }
554
555 MavlinkFTP::Request request{};
556 request.hdr.session = _uploadState.sessionId;
557 request.hdr.opcode = MavlinkFTP::kCmdTerminateSession;
558 _sendRequestExpectAck(&request);
559}
560
561void FTPManager::_terminateUploadSessionAckOrNak(const MavlinkFTP::Request* ackOrNak)
562{
563 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
564 if (requestOpCode != MavlinkFTP::kCmdTerminateSession) {
565 qCDebug(FTPManagerLog) << "_terminateUploadSessionAckOrNak: Ack disregarding ack for incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
566 return;
567 }
568 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
569 qCDebug(FTPManagerLog) << "_terminateUploadSessionAckOrNak: Ack disregarding ack for incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
570 return;
571 }
572
573 _ackOrNakTimeoutTimer.stop();
574
575 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
576 qCDebug(FTPManagerLog) << "_terminateUploadSessionAckOrNak: Ack";
577 _advanceStateMachine();
578 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
579 qCDebug(FTPManagerLog) << "_terminateUploadSessionAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
580 _uploadComplete(tr("Upload failed for: %1 - error: %2").arg(_uploadState.fullPathOnVehicle).arg(_errorMsgFromNak(ackOrNak)));
581 }
582}
583
584void FTPManager::_terminateUploadSessionTimeout(void)
585{
586 if (++_uploadState.retryCount > _maxRetry) {
587 qCDebug(FTPManagerLog) << QString("_terminateUploadSessionTimeout retries exceeded");
588 _uploadComplete(tr("Upload failed for: %1 - no response from vehicle").arg(_uploadState.fullPathOnVehicle));
589 } else {
590 qCDebug(FTPManagerLog) << QString("_terminateUploadSessionTimeout: retrying - retryCount(%1)").arg(_uploadState.retryCount);
591 _terminateUploadSessionBegin();
592 }
593}
594
595void FTPManager::_uploadFinalize(void)
596{
597 QString error = _uploadState.cancelled ? tr("Aborted for: %1").arg(_uploadState.fullPathOnVehicle) : QString();
598 _uploadComplete(error);
599}
600
601void FTPManager::_uploadComplete(const QString& errorMsg)
602{
603 qCDebug(FTPManagerLog) << QString("_uploadComplete: errorMsg(%1)").arg(errorMsg)
604 << "local" << _uploadState.localFilePath
605 << "remote" << _uploadState.fullPathOnVehicle;
606
607 QString remotePath = _uploadState.fullPathOnVehicle;
608
609 _ackOrNakTimeoutTimer.stop();
610 _rgStateMachine.clear();
611 _currentStateMachineIndex = -1;
612
613 if (_uploadState.file.isOpen()) {
614 _uploadState.file.close();
615 }
616
617 _uploadState.reset();
618
619 emit uploadComplete(remotePath, errorMsg);
620}
621
622void FTPManager::_mavlinkMessageReceived(const mavlink_message_t& message)
623{
624 if (message.msgid != MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL ||
625 message.sysid != _vehicle->id() || message.compid != _ftpCompId) {
626 return;
627 }
628
629 if (_currentStateMachineIndex == -1) {
630 return;
631 }
632
633 mavlink_file_transfer_protocol_t data;
634 mavlink_msg_file_transfer_protocol_decode(&message, &data);
635
636 // Make sure we are the target system
637 quint32 qgcId = MAVLinkProtocol::instance()->getSystemId();
638 if (mavlink_msg_get_target_sysid(&message, mavlink_get_msg_entry(message.msgid)) != qgcId) {
639 return;
640 }
641
642 MavlinkFTP::Request* request = (MavlinkFTP::Request*)&data.payload[0];
643
644 // Reject messages where hdr.size exceeds data array bounds to prevent over-reads
645 if (request->hdr.size > sizeof(request->data)) {
646 qCWarning(FTPManagerLog) << "_mavlinkMessageReceived: hdr.size exceeds data array, discarding." << request->hdr.size;
647 return;
648 }
649
650 // Ignore old/reordered packets (handle wrap-around properly). Burst data is the exception: its offset says
651 // where it goes, and a late packet from an earlier burst is still good data.
652 uint16_t actualIncomingSeqNumber = request->hdr.seqNumber;
653 const bool isBurstData = (request->hdr.opcode == MavlinkFTP::kRspAck)
654 && (request->hdr.req_opcode == MavlinkFTP::kCmdBurstReadFile)
655 && (_rgStateMachine[_currentStateMachineIndex].ackNakFn == &FTPManager::_burstReadFileAckOrNak);
656 if (!isBurstData && (uint16_t)((_expectedIncomingSeqNumber - 1) - actualIncomingSeqNumber) < (std::numeric_limits<uint16_t>::max()/2)) {
657 qCDebug(FTPManagerLog) << "_mavlinkMessageReceived: Received old packet seqNum expected:actual" << _expectedIncomingSeqNumber << actualIncomingSeqNumber
658 << "hdr.opcode:hdr.req_opcode" << MavlinkFTP::opCodeToString(static_cast<MavlinkFTP::OpCode_t>(request->hdr.opcode)) << MavlinkFTP::opCodeToString(static_cast<MavlinkFTP::OpCode_t>(request->hdr.req_opcode));
659
660 return;
661 }
662
663 qCDebug(FTPManagerLog) << "_mavlinkMessageReceived: hdr.opcode:hdr.req_opcode:seqNumber"
664 << MavlinkFTP::opCodeToString(static_cast<MavlinkFTP::OpCode_t>(request->hdr.opcode)) << MavlinkFTP::opCodeToString(static_cast<MavlinkFTP::OpCode_t>(request->hdr.req_opcode))
665 << request->hdr.seqNumber;
666
667 (this->*_rgStateMachine[_currentStateMachineIndex].ackNakFn)(request);
668}
669
670void FTPManager::_startStateMachine(void)
671{
672 _currentStateMachineIndex = -1;
673 _advanceStateMachine();
674}
675
676void FTPManager::_advanceStateMachine(void)
677{
678 _currentStateMachineIndex++;
679 (this->*_rgStateMachine[_currentStateMachineIndex].beginFn)();
680}
681
682void FTPManager::_ackOrNakTimeout(void)
683{
684 (this->*_rgStateMachine[_currentStateMachineIndex].timeoutFn)();
685}
686
687void FTPManager::_fillRequestDataWithString(MavlinkFTP::Request* request, const QString& str)
688{
689 strncpy((char *)&request->data[0], str.toStdString().c_str(), sizeof(request->data));
690 request->hdr.size = static_cast<uint8_t>(strnlen((const char *)&request->data[0], sizeof(request->data)));
691}
692
693QString FTPManager::_errorMsgFromNak(const MavlinkFTP::Request* nak)
694{
695 QString errorMsg;
696 MavlinkFTP::ErrorCode_t errorCode = static_cast<MavlinkFTP::ErrorCode_t>(nak->data[0]);
697
698 // Nak's normally have 1 byte of data for error code, except for MavlinkFTP::kErrFailErrno which has additional byte for errno
699 if ((errorCode == MavlinkFTP::kErrFailErrno && nak->hdr.size != 2) || ((errorCode != MavlinkFTP::kErrFailErrno) && nak->hdr.size != 1)) {
700 errorMsg = tr("Invalid Nak format");
701 } else if (errorCode == MavlinkFTP::kErrFailErrno) {
702 // PX4 reports a missing file as errno rather than kErrFailFileNotFound. The value is the
703 // vehicle's, but ENOENT is 2 on every platform PX4 runs on.
704 errorMsg = (nak->data[1] == ENOENT) ? MavlinkFTP::errorCodeToString(MavlinkFTP::kErrFailFileNotFound)
705 : tr("errno %1").arg(nak->data[1]);
706 } else {
707 errorMsg = MavlinkFTP::errorCodeToString(errorCode);
708 }
709
710 return errorMsg;
711}
712
713void FTPManager::_openFileROBegin(void)
714{
715 MavlinkFTP::Request request{};
716 request.hdr.session = 0;
717 request.hdr.opcode = MavlinkFTP::kCmdOpenFileRO;
718 request.hdr.offset = 0;
719 request.hdr.size = 0;
720 _fillRequestDataWithString(&request, _downloadState.fullPathOnVehicle);
721 _sendRequestExpectAck(&request);
722}
723
724void FTPManager::_openFileROTimeout(void)
725{
726 qCDebug(FTPManagerLog) << "_openFileROTimeout";
727 _downloadComplete(tr("Download failed"));
728}
729
730void FTPManager::_openFileROAckOrNak(const MavlinkFTP::Request* ackOrNak)
731{
732 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
733 if (requestOpCode != MavlinkFTP::kCmdOpenFileRO) {
734 qCDebug(FTPManagerLog) << "_openFileROAckOrNak: Ack disregarding ack for incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
735 return;
736 }
737 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
738 qCDebug(FTPManagerLog) << "_openFileROAckOrNak: Ack disregarding ack for incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
739 return;
740 }
741
742 _ackOrNakTimeoutTimer.stop();
743
744 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
745 qCDebug(FTPManagerLog) << "_openFileROAckOrNak: Ack - sessionId:openFileLength" << ackOrNak->hdr.session << ackOrNak->openFileLength;
746
747 if (ackOrNak->hdr.size != sizeof(uint32_t)) {
748 qCDebug(FTPManagerLog) << "_openFileROAckOrNak: Ack ack->hdr.size != sizeof(uint32_t)" << ackOrNak->hdr.size << sizeof(uint32_t);
749 _downloadComplete(tr("Download failed"));
750 return;
751 }
752
753 if (_downloadState.resumeStateIndex >= 0) {
754 if (_downloadState.checksize && (ackOrNak->openFileLength != _downloadState.fileSize)) {
755 qCDebug(FTPManagerLog) << "_openFileROAckOrNak: file size changed across re-open" << ackOrNak->openFileLength << _downloadState.fileSize;
756 _downloadComplete(tr("Download failed"));
757 return;
758 }
759 const int resumeStateIndex = _downloadState.resumeStateIndex;
760 _downloadState.resumeStateIndex = -1;
761 _downloadState.sessionId = ackOrNak->hdr.session;
762 qCDebug(FTPManagerLog) << "_openFileROAckOrNak: session re-opened, resuming at offset" << _downloadState.expectedOffset;
763 _currentStateMachineIndex = resumeStateIndex;
764 (this->*_rgStateMachine[resumeStateIndex].beginFn)();
765 return;
766 }
767
768 _downloadState.sessionId = ackOrNak->hdr.session;
769 _downloadState.fileSize = ackOrNak->openFileLength;
770 _downloadState.expectedOffset = 0;
771
772 _downloadState.file.setFileName(_downloadState.toDir.filePath(_downloadState.fileName));
773 if (_downloadState.file.open(QFile::WriteOnly | QFile::Truncate)) {
774 _advanceStateMachine();
775 } else {
776 qCDebug(FTPManagerLog) << "_openFileROAckOrNak: Ack _downloadState.file open failed" << _downloadState.file.errorString();
777 _downloadComplete(tr("Download failed"));
778 }
779 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
780 qCDebug(FTPManagerLog) << "_handlOpenFileROAck: Nak -" << _errorMsgFromNak(ackOrNak);
781 _downloadComplete(tr("Download failed") + ": " + _errorMsgFromNak(ackOrNak));
782 }
783}
784
785uint8_t FTPManager::_readChunkSize(void) const
786{
787 const SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
788 if (!sharedLink || !sharedLink->isRadioLink()) {
789 return kFullReadChunkSize;
790 }
791
792 // Treat a link that is switching signing on or off as signed, packets may carry a signature either way
793 const VehicleSigningController* const signing = _vehicle->signingController();
794 const bool signedLink = signing && (signing->signingStatus().state != SigningStatus::State::Off);
796}
797
798void FTPManager::_burstReadFileWorker(bool firstRequest)
799{
800 const uint8_t chunkSize = _readChunkSize();
801 qCDebug(FTPManagerLog) << "_burstReadFileWorker: starting burst at offset:firstRequest:retryCount:chunkSize" << _downloadState.expectedOffset << firstRequest << _downloadState.retryCount << chunkSize;
802
803 MavlinkFTP::Request request{};
804 request.hdr.session = _downloadState.sessionId;
805 request.hdr.opcode = MavlinkFTP::kCmdBurstReadFile;
806 request.hdr.offset = _downloadState.expectedOffset;
807 request.hdr.size = chunkSize;
808
809 if (firstRequest) {
810 _downloadState.retryCount = 0;
811 } else {
812 // Must used same sequence number as previous request
813 _expectedIncomingSeqNumber -= 2;
814 }
815
816 _sendRequestExpectAck(&request);
817}
818
819void FTPManager::_burstReadFileBegin(void)
820{
821 _burstReadFileWorker(true /* firstRequestr */);
822}
823
824void FTPManager::_burstReadFileAckOrNak(const MavlinkFTP::Request* ackOrNak)
825{
826 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
827
828 if (requestOpCode != MavlinkFTP::kCmdBurstReadFile) {
829 qCDebug(FTPManagerLog) << "_burstReadFileAckOrNak: Disregarding due to incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
830 return;
831 }
832 if (ackOrNak->hdr.session != _downloadState.sessionId) {
833 qCDebug(FTPManagerLog) << "_burstReadFileAckOrNak: Disregarding due to incorrect session id actual:expected" << ackOrNak->hdr.session << _downloadState.sessionId;
834 return;
835 }
836
837 _ackOrNakTimeoutTimer.stop();
838
839 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
840 qCDebug(FTPManagerLog) << QString("_burstReadFileAckOrNak: Ack offset(%1) size(%2) burstComplete(%3)").arg(ackOrNak->hdr.offset).arg(ackOrNak->hdr.size).arg(ackOrNak->hdr.burstComplete);
841
842 if (ackOrNak->hdr.offset < _downloadState.expectedOffset) {
843 // Behind the frontier: a late packet from an earlier burst or a duplicate. Keep it if it plugs a hole,
844 // and leave sequence tracking alone since it belongs to a stream we have moved past.
845 if (_claimMissingRange(ackOrNak->hdr.offset, ackOrNak->hdr.size)) {
846 qCDebug(FTPManagerLog) << "_burstReadFileAckOrNak: late packet fills hole at offset" << ackOrNak->hdr.offset;
847 _downloadState.file.seek(ackOrNak->hdr.offset);
848 if (_downloadState.file.write((const char*)ackOrNak->data, ackOrNak->hdr.size) != ackOrNak->hdr.size) {
849 _downloadComplete(tr("Download failed: Error saving file"));
850 return;
851 }
852 _downloadState.bytesWritten += ackOrNak->hdr.size;
853 } else {
854 qCDebug(FTPManagerLog) << "_burstReadFileAckOrNak: duplicate packet at offset" << ackOrNak->hdr.offset;
855 }
856 _ackOrNakTimeoutTimer.start();
857 if (_downloadState.fileSize != 0) {
858 emit commandProgress((float)(_downloadState.bytesWritten) / (float)_downloadState.fileSize);
859 }
860 return;
861 }
862
863 if (ackOrNak->hdr.offset > _downloadState.expectedOffset) {
864 // There is a hole in our data, record it as missing and continue on
865 MissingData_t missingData;
866 missingData.offset = _downloadState.expectedOffset;
867 missingData.cBytesMissing = ackOrNak->hdr.offset - _downloadState.expectedOffset;
868 _downloadState.rgMissingData.append(missingData);
869 qCDebug(FTPManagerLog) << "_handleBurstReadFileAck: adding missing data offset:cBytesMissing" << missingData.offset << missingData.cBytesMissing;
870 }
871
872 _downloadState.file.seek(ackOrNak->hdr.offset);
873 int bytesWritten = _downloadState.file.write((const char*)ackOrNak->data, ackOrNak->hdr.size);
874 if (bytesWritten != ackOrNak->hdr.size) {
875 _downloadComplete(tr("Download failed: Error saving file"));
876 return;
877 }
878 _downloadState.bytesWritten += ackOrNak->hdr.size;
879 _downloadState.expectedOffset = ackOrNak->hdr.offset + ackOrNak->hdr.size;
880
881 if (ackOrNak->hdr.burstComplete) {
882 // The current burst is done, request next one in offset sequence
883 _expectedIncomingSeqNumber = ackOrNak->hdr.seqNumber;
884 _burstReadFileWorker(true /* firstRequest */);
885 } else {
886 // Still within a burst, next ack should come automatically
887 _expectedIncomingSeqNumber = ackOrNak->hdr.seqNumber + 1;
888 _ackOrNakTimeoutTimer.start();
889 }
890
891 // Emit progress last, as cancel could be called in there
892 if (_downloadState.fileSize != 0) {
893 emit commandProgress((float)(_downloadState.bytesWritten) / (float)_downloadState.fileSize);
894 }
895 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
896 MavlinkFTP::ErrorCode_t errorCode = static_cast<MavlinkFTP::ErrorCode_t>(ackOrNak->data[0]);
897
898 if (errorCode == MavlinkFTP::kErrEOF) {
899 // Burst sequence has gone through the whole file
900 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
901 qCDebug(FTPManagerLog) << "_burstReadFileAckOrNak: EOF Nak"
902 "with incorrect sequence nr actual:expected"
903 << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
904 /* We have received the EOF Nak but out of sequence, i.e. data is missing */
905 _expectedIncomingSeqNumber = ackOrNak->hdr.seqNumber;
906 _burstReadFileWorker(true); /* Retry from last expected offset */
907 } else {
908 qCDebug(FTPManagerLog) << "_burstReadFileAckOrNak EOF";
909 _advanceStateMachine();
910 }
911 } else if (errorCode == MavlinkFTP::kErrInvalidSession) {
912 _downloadSessionLost();
913 } else { /* Don't care is this is out of sequence */
914 qCDebug(FTPManagerLog) << "_burstReadFileAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
915 _downloadComplete(tr("Download failed"));
916 }
917 }
918}
919
920bool FTPManager::_claimMissingRange(uint32_t offset, uint32_t cBytes)
921{
922 if (cBytes == 0 || offset > std::numeric_limits<uint32_t>::max() - cBytes) {
923 return false;
924 }
925
926 for (int i = 0; i < _downloadState.rgMissingData.count(); i++) {
927 MissingData_t& hole = _downloadState.rgMissingData[i];
928 const uint32_t holeEnd = hole.offset + hole.cBytesMissing;
929 if ((offset < hole.offset) || (offset + cBytes > holeEnd)) {
930 continue;
931 }
932
933 const MissingData_t after{ offset + cBytes, holeEnd - (offset + cBytes) };
934 if (offset == hole.offset) {
935 if (after.cBytesMissing == 0) {
936 _downloadState.rgMissingData.removeAt(i);
937 } else {
938 hole = after;
939 }
940 } else {
941 hole.cBytesMissing = offset - hole.offset;
942 if (after.cBytesMissing != 0) {
943 _downloadState.rgMissingData.insert(i + 1, after);
944 }
945 }
946 return true;
947 }
948 return false;
949}
950
951void FTPManager::_downloadSessionLost(void)
952{
953 if (++_downloadState.sessionReopenCount > kMaxDownloadSessionReopens) {
954 qCDebug(FTPManagerLog) << "_downloadSessionLost: re-open limit reached";
955 _downloadComplete(tr("Download failed"));
956 return;
957 }
958
959 qCDebug(FTPManagerLog) << "_downloadSessionLost: re-opening to resume at offset" << _downloadState.expectedOffset << "reopenCount" << _downloadState.sessionReopenCount;
960 _downloadState.resumeStateIndex = _currentStateMachineIndex;
961 // Back to the front of the machine: ResetSessions then OpenFileRO, which jumps back to resumeStateIndex
962 _currentStateMachineIndex = -1;
963 _advanceStateMachine();
964}
965
966void FTPManager::_burstReadFileTimeout(void)
967{
968 if (++_downloadState.retryCount > _maxRetry) {
969 qCDebug(FTPManagerLog) << QString("_burstReadFileTimeout retries exceeded");
970 _downloadComplete(tr("Download failed"));
971 } else {
972 // Try again
973 qCDebug(FTPManagerLog) << QString("_burstReadFileTimeout: retrying - retryCount(%1) offset(%2)").arg(_downloadState.retryCount).arg(_downloadState.expectedOffset);
974 _burstReadFileWorker(false /* firstReqeust */);
975 }
976}
977
978void FTPManager::_listDirectoryWorker(bool firstRequest)
979{
980 qCDebug(FTPManagerLog) << "_listDirectoryWorker: offset:firstRequest:retryCount" << _listDirectoryState.expectedOffset << firstRequest << _listDirectoryState.retryCount;
981
982 MavlinkFTP::Request request{};
983 request.hdr.session = _downloadState.sessionId;
984 request.hdr.opcode = _listDirectoryState.opCode;
985 request.hdr.offset = _listDirectoryState.expectedOffset;
986 request.hdr.size = sizeof(request.data);
987 _fillRequestDataWithString(&request, _listDirectoryState.fullPathOnVehicle);
988
989 if (firstRequest) {
990 _listDirectoryState.retryCount = 0;
991 } else {
992 // Must used same sequence number as previous request
993 _expectedIncomingSeqNumber -= 2;
994 }
995
996 _sendRequestExpectAck(&request);
997}
998
999void FTPManager::_listDirectoryBegin(void)
1000{
1001 _listDirectoryWorker(true /* firstRequest */);
1002}
1003
1004void FTPManager::_listDirectoryAckOrNak(const MavlinkFTP::Request* ackOrNak)
1005{
1006 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
1007
1008 if (requestOpCode != _listDirectoryState.opCode) {
1009 qCDebug(FTPManagerLog) << "_listDirectoryAckOrNak: Disregarding due to incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
1010 return;
1011 }
1012
1013 _ackOrNakTimeoutTimer.stop();
1014
1015 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
1016 if (ackOrNak->hdr.seqNumber < _expectedIncomingSeqNumber) {
1017 qCDebug(FTPManagerLog) << "_listDirectoryAckOrNak: Disregarding Ack due to incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
1018 return;
1019 }
1020
1021 if (_listDirectoryState.opCode == MavlinkFTP::kCmdListDirectoryWithTime) {
1022 _listDirWithTimeSupport = WithTimeSupport_t::Supported;
1023 }
1024
1025 qCDebug(FTPManagerLog) << QString("_listDirectoryAckOrNak: Ack size(%1)").arg(ackOrNak->hdr.size);
1026
1027 // Parse entries in ackOrNak->data into _listDirectoryState.rgDirectoryList
1028 const char* curDataPtr = (const char*)ackOrNak->data;
1029 while (curDataPtr < (const char*)ackOrNak->data + ackOrNak->hdr.size) {
1030 QString dirEntry = curDataPtr;
1031 curDataPtr += dirEntry.size() + 1;
1032 _listDirectoryState.rgDirectoryList.append(dirEntry);
1033 _listDirectoryState.expectedOffset++;
1034 }
1035
1036 // Request next set of directory entries
1037 _expectedIncomingSeqNumber = ackOrNak->hdr.seqNumber;
1038 _listDirectoryWorker(true /* firstRequest */);
1039 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
1040 MavlinkFTP::ErrorCode_t errorCode = static_cast<MavlinkFTP::ErrorCode_t>(ackOrNak->data[0]);
1041
1042 if (errorCode == MavlinkFTP::kErrEOF) {
1043 // All entries returned
1044 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
1045 qCDebug(FTPManagerLog) << "_listDirectoryAckOrNak: Disregarding Nak due to incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
1046 _ackOrNakTimeoutTimer.start();
1047 return;
1048 } else {
1049 qCDebug(FTPManagerLog) << "_listDirectoryAckOrNak EOF";
1050 if (_listDirectoryState.opCode == MavlinkFTP::kCmdListDirectoryWithTime) {
1051 _listDirWithTimeSupport = WithTimeSupport_t::Supported;
1052 }
1053 _advanceStateMachine();
1054 }
1055 } else if (_listDirectoryState.opCode == MavlinkFTP::kCmdListDirectoryWithTime &&
1056 (errorCode == MavlinkFTP::kErrUnknownCommand ||
1057 (errorCode == MavlinkFTP::kErrFail && _listDirWithTimeSupport == WithTimeSupport_t::Unknown))) {
1058 // Server doesn't implement kCmdListDirectoryWithTime. Remember that, fall back to the
1059 // plain listing and restart from the beginning. ArduPilot Naks unknown opcodes with a
1060 // generic kErrFail rather than kErrUnknownCommand, so kErrFail is also treated as
1061 // unsupported while probing. We act on it without a strict sequence check; the restart
1062 // is idempotent (offset and accumulated entries are reset).
1063 qCDebug(FTPManagerLog) << "_listDirectoryAckOrNak: kCmdListDirectoryWithTime unsupported, falling back to kCmdListDirectory";
1064 _listDirWithTimeSupport = WithTimeSupport_t::Unsupported;
1065 _listDirectoryState.opCode = MavlinkFTP::kCmdListDirectory;
1066 _listDirectoryState.expectedOffset = 0;
1067 _listDirectoryState.rgDirectoryList.clear();
1068 _expectedIncomingSeqNumber = ackOrNak->hdr.seqNumber;
1069 _listDirectoryWorker(true /* firstRequest */);
1070 } else { /* Don't care is this is out of sequence */
1071 qCDebug(FTPManagerLog) << "_listDirectoryAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
1072 _listDirectoryComplete(tr("List directory failed"));
1073 }
1074 }
1075}
1076
1077void FTPManager::_listDirectoryTimeout(void)
1078{
1079 if (++_listDirectoryState.retryCount > _maxRetry) {
1080 qCDebug(FTPManagerLog) << QString("_listDirectoryTimeout retries exceeded");
1081 _listDirectoryComplete(tr("List directory failed"));
1082 } else {
1083 // Try again
1084 qCDebug(FTPManagerLog) << QString("_listDirectoryTimeout: retrying - retryCount(%1) offset(%2)").arg(_listDirectoryState.retryCount).arg(_listDirectoryState.expectedOffset);
1085 _listDirectoryWorker(false /* firstReqeust */);
1086 }
1087}
1088
1089void FTPManager::_fillMissingBlocksWorker(bool firstRequest)
1090{
1091 if (_downloadState.rgMissingData.count()) {
1092 MavlinkFTP::Request request{};
1093 MissingData_t& missingData = _downloadState.rgMissingData.first();
1094
1095 uint32_t cBytesToRead = qMin(static_cast<uint32_t>(_readChunkSize()), missingData.cBytesMissing);
1096
1097 qCDebug(FTPManagerLog) << "_fillMissingBlocksBegin: offset:cBytesToRead" << missingData.offset << cBytesToRead;
1098
1099 request.hdr.session = _downloadState.sessionId;
1100 request.hdr.opcode = MavlinkFTP::kCmdReadFile;
1101 request.hdr.offset = missingData.offset;
1102 request.hdr.size = cBytesToRead;
1103
1104 if (firstRequest) {
1105 _downloadState.retryCount = 0;
1106 } else {
1107 // Must used same sequence number as previous request
1108 _expectedIncomingSeqNumber -= 2;
1109 }
1110 _downloadState.expectedOffset = request.hdr.offset;
1111
1112 _sendRequestExpectAck(&request);
1113 } else {
1114 // We should have the full file now
1115 if (_downloadState.checksize == false || _downloadState.bytesWritten == _downloadState.fileSize) {
1116 _advanceStateMachine();
1117 } else {
1118 qCDebug(FTPManagerLog) << "_fillMissingBlocksWorker: no missing blocks but file still incomplete - bytesWritten:fileSize" << _downloadState.bytesWritten << _downloadState.fileSize;
1119 _downloadComplete(tr("Download failed"));
1120 }
1121 }
1122}
1123
1124void FTPManager::_fillMissingBlocksBegin(void)
1125{
1126 _fillMissingBlocksWorker(true /* firstRequest */);
1127}
1128
1129void FTPManager::_fillMissingBlocksAckOrNak(const MavlinkFTP::Request* ackOrNak)
1130{
1131 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
1132
1133 if (requestOpCode != MavlinkFTP::kCmdReadFile) {
1134 qCDebug(FTPManagerLog) << "_fillMissingBlocksAckOrNak: Disregarding due to incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
1135 return;
1136 }
1137 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
1138 qCDebug(FTPManagerLog) << "_fillMissingBlocksAckOrNak: Disregarding due to incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
1139 return;
1140 }
1141 if (ackOrNak->hdr.session != _downloadState.sessionId) {
1142 qCDebug(FTPManagerLog) << "_fillMissingBlocksAckOrNak: Disregarding due to incorrect session id actual:expected" << ackOrNak->hdr.session << _downloadState.sessionId;
1143 return;
1144 }
1145
1146 _ackOrNakTimeoutTimer.stop();
1147
1148 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
1149 qCDebug(FTPManagerLog) << "_fillMissingBlocksAckOrNak: Ack offset:size" << ackOrNak->hdr.offset << ackOrNak->hdr.size;
1150
1151 if (ackOrNak->hdr.offset != _downloadState.expectedOffset) {
1152 if (++_downloadState.retryCount > _maxRetry) {
1153 qCDebug(FTPManagerLog) << QString("_fillMissingBlocksAckOrNak: offset mismatch, retries exceeded");
1154 _downloadComplete(tr("Download failed"));
1155 return;
1156 }
1157
1158 // Ask for current offset again
1159 qCDebug(FTPManagerLog) << QString("_fillMissingBlocksAckOrNak: Ack offset mismatch retry, retryCount(%1) offset(%2)").arg(_downloadState.retryCount).arg(_downloadState.expectedOffset);
1160 _fillMissingBlocksWorker(false /* firstReqeust */);
1161 return;
1162 }
1163
1164 _downloadState.file.seek(ackOrNak->hdr.offset);
1165 int bytesWritten = _downloadState.file.write((const char*)ackOrNak->data, ackOrNak->hdr.size);
1166 if (bytesWritten != ackOrNak->hdr.size) {
1167 _downloadComplete(tr("Download failed: Error saving file"));
1168 return;
1169 }
1170 _downloadState.bytesWritten += ackOrNak->hdr.size;
1171
1172 MissingData_t& missingData = _downloadState.rgMissingData.first();
1173 missingData.offset += ackOrNak->hdr.size;
1174 missingData.cBytesMissing -= ackOrNak->hdr.size;
1175 if (missingData.cBytesMissing == 0) {
1176 // This block is finished, remove it
1177 _downloadState.rgMissingData.takeFirst();
1178 }
1179
1180 // Move on to fill in possible next hole
1181 _fillMissingBlocksWorker(true /* firstReqeust */);
1182
1183 // Emit progress last, as cancel could be called in there
1184 if (_downloadState.fileSize != 0) {
1185 emit commandProgress((float)(_downloadState.bytesWritten) / (float)_downloadState.fileSize);
1186 }
1187 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
1188 MavlinkFTP::ErrorCode_t errorCode = static_cast<MavlinkFTP::ErrorCode_t>(ackOrNak->data[0]);
1189
1190 if (errorCode == MavlinkFTP::kErrEOF) {
1191 qCDebug(FTPManagerLog) << "_fillMissingBlocksAckOrNak EOF";
1192 if (_downloadState.checksize == false || _downloadState.bytesWritten == _downloadState.fileSize) {
1193 // We've successfully complete filling in all missing blocks
1194 _advanceStateMachine();
1195 return;
1196 }
1197 } else if (errorCode == MavlinkFTP::kErrInvalidSession) {
1198 _downloadSessionLost();
1199 return;
1200 }
1201
1202 qCDebug(FTPManagerLog) << "_fillMissingBlocksAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
1203 _downloadComplete(tr("Download failed"));
1204 }
1205}
1206
1207void FTPManager::_fillMissingBlocksTimeout(void)
1208{
1209 if (++_downloadState.retryCount > _maxRetry) {
1210 qCDebug(FTPManagerLog) << QString("_fillMissingBlocksTimeout retries exceeded");
1211 _downloadComplete(tr("Download failed"));
1212 } else {
1213 // Ask for current offset again
1214 qCDebug(FTPManagerLog) << QString("_fillMissingBlocksTimeout: retrying - retryCount(%1) offset(%2)").arg(_downloadState.retryCount).arg(_downloadState.expectedOffset);
1215 _fillMissingBlocksWorker(false /* firstReqeust */);
1216 }
1217}
1218
1219void FTPManager::_resetSessionsBegin(void)
1220{
1221 MavlinkFTP::Request request{};
1222 request.hdr.opcode = MavlinkFTP::kCmdResetSessions;
1223 request.hdr.size = 0;
1224 _sendRequestExpectAck(&request);
1225}
1226
1227void FTPManager::_resetSessionsAckOrNak(const MavlinkFTP::Request* ackOrNak)
1228{
1229 MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
1230
1231 if (requestOpCode != MavlinkFTP::kCmdResetSessions) {
1232 qCDebug(FTPManagerLog) << "_fillMissingBlocksAckOrNak: Disregarding due to incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
1233 return;
1234 }
1235 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
1236 qCDebug(FTPManagerLog) << "_resetSessionsAckOrNak: Disregarding due to incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
1237 return;
1238 }
1239
1240 _ackOrNakTimeoutTimer.stop();
1241
1242 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspAck) {
1243 qCDebug(FTPManagerLog) << "_resetSessionsAckOrNak: Ack";
1244 _advanceStateMachine();
1245 } else if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
1246 qCDebug(FTPManagerLog) << "_resetSessionsAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak);
1247 _downloadComplete(QString());
1248 }
1249}
1250
1251void FTPManager::_resetSessionsTimeout(void)
1252{
1253 qCDebug(FTPManagerLog) << "_resetSessionsTimeout";
1254 _downloadComplete(QString());
1255}
1256
1257void FTPManager::_setStateMachine(const StateFunctions_t* rgStates, size_t cStates)
1258{
1259 _rgStateMachine.append({ &FTPManager::_clearStaleSessionsBegin, &FTPManager::_clearStaleSessionsAckOrNak, &FTPManager::_clearStaleSessionsTimeout });
1260 for (size_t i = 0; i < cStates; i++) {
1261 _rgStateMachine.append(rgStates[i]);
1262 }
1263}
1264
1265void FTPManager::_clearStaleSessionsBegin(void)
1266{
1267 _clearStaleSessionsRetryCount = 0;
1268 _resetSessionsBegin();
1269}
1270
1271void FTPManager::_clearStaleSessionsAckOrNak(const MavlinkFTP::Request* ackOrNak)
1272{
1273 const MavlinkFTP::OpCode_t requestOpCode = static_cast<MavlinkFTP::OpCode_t>(ackOrNak->hdr.req_opcode);
1274 if (requestOpCode != MavlinkFTP::kCmdResetSessions) {
1275 qCDebug(FTPManagerLog) << "_clearStaleSessionsAckOrNak: Disregarding due to incorrect requestOpCode" << MavlinkFTP::opCodeToString(requestOpCode);
1276 return;
1277 }
1278 if (ackOrNak->hdr.seqNumber != _expectedIncomingSeqNumber) {
1279 qCDebug(FTPManagerLog) << "_clearStaleSessionsAckOrNak: Disregarding due to incorrect sequence actual:expected" << ackOrNak->hdr.seqNumber << _expectedIncomingSeqNumber;
1280 return;
1281 }
1282
1283 _ackOrNakTimeoutTimer.stop();
1284 if (ackOrNak->hdr.opcode == MavlinkFTP::kRspNak) {
1285 qCDebug(FTPManagerLog) << "_clearStaleSessionsAckOrNak: Nak -" << _errorMsgFromNak(ackOrNak) << "- continuing anyway";
1286 }
1287 _advanceStateMachine();
1288}
1289
1290void FTPManager::_clearStaleSessionsTimeout(void)
1291{
1292 if (++_clearStaleSessionsRetryCount <= 1) {
1293 qCDebug(FTPManagerLog) << "_clearStaleSessionsTimeout: retrying";
1294 _resetSessionsBegin();
1295 return;
1296 }
1297 qCDebug(FTPManagerLog) << "_clearStaleSessionsTimeout: no reply, continuing anyway";
1298 _advanceStateMachine();
1299}
1300
1301void FTPManager::_sendResetSessionsNoAck(void)
1302{
1303 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
1304 if (!sharedLink) {
1305 return;
1306 }
1307
1308 MavlinkFTP::Request request{};
1309 request.hdr.opcode = MavlinkFTP::kCmdResetSessions;
1310 request.hdr.size = 0;
1311 request.hdr.seqNumber = _expectedIncomingSeqNumber + 1;
1312 _expectedIncomingSeqNumber += 2;
1313
1314 qCDebug(FTPManagerLog) << "_sendResetSessionsNoAck seqNumber:" << request.hdr.seqNumber;
1315
1316 mavlink_message_t message;
1317 mavlink_msg_file_transfer_protocol_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
1319 sharedLink->mavlinkChannel(),
1320 &message,
1321 0,
1322 _vehicle->id(),
1323 _ftpCompId,
1324 (uint8_t*)&request);
1325 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), message);
1326}
1327
1328void FTPManager::_sendRequestExpectAck(MavlinkFTP::Request* request)
1329{
1330 _ackOrNakTimeoutTimer.start();
1331
1332 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
1333 if (sharedLink) {
1334 request->hdr.seqNumber = _expectedIncomingSeqNumber + 1; // Outgoing is 1 past last incoming
1335 _expectedIncomingSeqNumber += 2;
1336
1337 qCDebug(FTPManagerLog) << "_sendRequestExpectAck opcode:" << MavlinkFTP::opCodeToString(static_cast<MavlinkFTP::OpCode_t>(request->hdr.opcode)) << "seqNumber:" << request->hdr.seqNumber;
1338
1339 mavlink_message_t message;
1340 mavlink_msg_file_transfer_protocol_pack_chan(MAVLinkProtocol::instance()->getSystemId(),
1342 sharedLink->mavlinkChannel(),
1343 &message,
1344 0, // Target network, 0=broadcast?
1345 _vehicle->id(),
1346 _ftpCompId,
1347 (uint8_t*)request); // Payload
1348 _vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), message);
1349 } else {
1350 qCDebug(FTPManagerLog) << "_sendRequestExpectAck No primary link. Allowing timeout to fail sequence.";
1351 }
1352}
1353
1354bool FTPManager::_parseURI(uint8_t fromCompId, const QString& uri, QString& parsedURI, uint8_t& compId)
1355{
1356 parsedURI = uri;
1357 compId = (fromCompId == MAV_COMP_ID_ALL) ? (uint8_t)MAV_COMP_ID_AUTOPILOT1 : fromCompId;
1358
1359 // Pull scheme off the front if there
1360 QString ftpPrefix(QStringLiteral("%1://").arg(mavlinkFTPScheme));
1361 if (parsedURI.startsWith(ftpPrefix, Qt::CaseInsensitive)) {
1362 parsedURI = parsedURI.mid(ftpPrefix.length());
1363 }
1364 if (parsedURI.contains("://")) {
1365 qCWarning(FTPManagerLog) << "Incorrect uri scheme or format" << uri;
1366 return false;
1367 }
1368
1369 // Pull component id off the front if there
1370 QRegularExpression regEx("^/??\\[\\;comp\\=(\\d+)\\]");
1371 QRegularExpressionMatch match = regEx.match(parsedURI);
1372 if (match.hasMatch()) {
1373 bool ok;
1374 compId = match.captured(1).toUInt(&ok);
1375 if (!ok) {
1376 qCWarning(FTPManagerLog) << "Incorrect format for component id" << uri;
1377 return false;
1378 }
1379
1380 qCDebug(FTPManagerLog) << "Found compId in MAVLink FTP URI: " << compId;
1381 parsedURI.replace(QRegularExpression("\\[\\;comp\\=\\d+\\]"), "");
1382 }
1383
1384 return true;
1385}
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static constexpr uint8_t kRadioReadChunkSizeSigned
Chunk size on a signed radio link, where every packet carries a 13 byte signature.
Definition FTPManager.h:295
static constexpr int kTestAckTimeoutMs
Keep timeout tests fast while allowing queued MockLink replies during UI startup.
Definition FTPManager.h:299
void cancelDownload()
bool listDirectory(uint8_t fromCompId, const QString &fromURI)
FTPManager(Vehicle *vehicle)
Definition FTPManager.cc:18
bool deleteFile(uint8_t fromCompId, const QString &fromURI)
static constexpr uint8_t kRadioReadChunkSize
Definition FTPManager.h:293
bool upload(uint8_t toCompId, const QString &toURI, const QString &fromFile)
Definition FTPManager.cc:99
static constexpr uint8_t kFullReadChunkSize
Bytes requested per ReadFile/BurstReadFile chunk on non-radio links: the full FTP payload.
Definition FTPManager.h:289
static constexpr const char * mavlinkFTPScheme
Definition FTPManager.h:81
friend class Vehicle
Definition FTPManager.h:15
void uploadComplete(const QString &file, const QString &errorMsg)
static constexpr int kMaxDownloadSessionReopens
Max times a download re-opens after the server expires the session (PX4 idle timer fires mid-burst).
Definition FTPManager.h:297
void cancelUpload()
void commandProgress(float value)
void downloadComplete(const QString &file, const QString &errorMsg)
void cancelListDirectory()
void deleteComplete(const QString &file, const QString &errorMsg)
void cancelDelete()
bool download(uint8_t fromCompId, const QString &fromURI, const QString &toDir, const QString &fileName="", bool checksize=true)
Definition FTPManager.cc:32
void listDirectoryComplete(const QStringList &dirList, const QString &errorMsg)
static int getComponentId()
quint32 getSystemId() const
static MAVLinkProtocol * instance()
ErrorCode_t
Error codes returned in Nak response PayloadHeader.data[0].
Definition MAVLinkFTP.h:62
@ kErrFail
Unknown failure.
Definition MAVLinkFTP.h:64
@ kErrEOF
Offset past end of file for List and Read commands.
Definition MAVLinkFTP.h:69
@ kErrUnknownCommand
Unknown command opcode.
Definition MAVLinkFTP.h:70
@ kErrFailErrno
errno sent back in PayloadHeader.data[1]
Definition MAVLinkFTP.h:65
@ kErrInvalidSession
Session is not currently open.
Definition MAVLinkFTP.h:67
@ kErrFailFileNotFound
Definition MAVLinkFTP.h:73
static QString errorCodeToString(ErrorCode_t errorCode)
Definition MAVLinkFTP.cc:49
@ kCmdRemoveFile
Remove file at <path>.
Definition MAVLinkFTP.h:47
@ kCmdWriteFile
Writes <size> bytes to <offset> in <session>.
Definition MAVLinkFTP.h:46
@ kCmdCreateFile
Creates file at <path> for writing, returns <session>.
Definition MAVLinkFTP.h:45
@ kCmdOpenFileRO
Opens file at <path> for reading, returns <session>.
Definition MAVLinkFTP.h:43
@ kCmdListDirectoryWithTime
List directory as kCmdListDirectory, each entry additionally carrying trailing \t<modification time>.
Definition MAVLinkFTP.h:55
@ kCmdReadFile
Reads <size> bytes from <offset> in <session>.
Definition MAVLinkFTP.h:44
@ kCmdResetSessions
Terminates all open Read sessions.
Definition MAVLinkFTP.h:41
@ kRspAck
Ack response.
Definition MAVLinkFTP.h:57
@ kCmdBurstReadFile
Burst download session file.
Definition MAVLinkFTP.h:54
@ kCmdTerminateSession
Terminates open Read session.
Definition MAVLinkFTP.h:40
@ kRspNak
Nak response.
Definition MAVLinkFTP.h:58
@ kCmdListDirectory
List files in <path> from <offset>.
Definition MAVLinkFTP.h:42
static QString opCodeToString(OpCode_t opCode)
Definition MAVLinkFTP.cc:3
SigningStatus signingStatus() const
bool runningUnitTests()