MockLinkFileServer.cc 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

10

11 12 13 14 15 16 17 18 19
#include "MockLinkFileServer.h"
#include "MockLink.h"

const MockLinkFileServer::ErrorMode_t MockLinkFileServer::rgFailureModes[] = {
    MockLinkFileServer::errModeNoResponse,
    MockLinkFileServer::errModeNakResponse,
    MockLinkFileServer::errModeNoSecondResponse,
    MockLinkFileServer::errModeNakSecondResponse,
    MockLinkFileServer::errModeBadSequence,
20
};
21
const size_t MockLinkFileServer::cFailureModes = sizeof(MockLinkFileServer::rgFailureModes) / sizeof(MockLinkFileServer::rgFailureModes[0]);
22

23
const MockLinkFileServer::FileTestCase MockLinkFileServer::rgFileTestCases[MockLinkFileServer::cFileTestCases] = {
24
    // File fits one Read Ack packet, partially filling data
25
    { "partial.qgc",    sizeof(((FileManager::Request*)0)->data) - 1,     1,    false},
26
    // File fits one Read Ack packet, exactly filling all data
27
    { "exact.qgc",      sizeof(((FileManager::Request*)0)->data),         1,    true },
28
    // File is larger than a single Read Ack packets, requires multiple Reads
29
    { "multi.qgc",      sizeof(((FileManager::Request*)0)->data) + 1,     2,    false },
30
};
31

32
// We only support a single fixed session
33
const uint8_t MockLinkFileServer::_sessionId = 1;
34

35
MockLinkFileServer::MockLinkFileServer(uint8_t systemIdServer, uint8_t componentIdServer, MockLink* mockLink) :
36 37
    _errMode(errModeNone),
    _systemIdServer(systemIdServer),
38
    _componentIdServer(componentIdServer),
39 40 41 42
    _mockLink(mockLink),
    _lastReplyValid(false),
    _lastReplySequence(0),
    _randomDropsEnabled(false)
43
{
44 45 46 47 48 49 50
    srand(0); // make sure unit tests are deterministic
}

void MockLinkFileServer::ensureNullTemination(FileManager::Request* request)
{
    if (request->hdr.size < sizeof(request->data)) {
        request->data[request->hdr.size] = '\0';
51

52 53 54
    } else {
        request->data[sizeof(request->data)-1] = '\0';
    }
55 56
}

57 58
/// @brief Handles List command requests. Only supports root folder paths.
///         File list returned is set using the setFileList method.
59
void MockLinkFileServer::_listCommand(uint8_t senderSystemId, uint8_t senderComponentId, FileManager::Request* request, uint16_t seqNumber)
60
{
61 62
    // FIXME: Does not support directories that span multiple packets
    
63
    FileManager::Request  ackResponse;
Don Gagne's avatar
Don Gagne committed
64
    QString                     path;
65
    uint16_t                    outgoingSeqNumber = _nextSeqNumber(seqNumber);
Don Gagne's avatar
Don Gagne committed
66

67 68
    ensureNullTemination(request);

69 70 71
    // We only support root path
    path = (char *)&request->data[0];
    if (!path.isEmpty() && path != "/") {
72
		_sendNak(senderSystemId, senderComponentId, FileManager::kErrFail, outgoingSeqNumber, FileManager::kCmdListDirectory);
73 74 75 76 77
        return;
    }
    
    // Offset requested is past the end of the list
    if (request->hdr.offset > (uint32_t)_fileList.size()) {
78
        _sendNak(senderSystemId, senderComponentId, FileManager::kErrEOF, outgoingSeqNumber, FileManager::kCmdListDirectory);
79 80 81
        return;
    }
    
82
    ackResponse.hdr.opcode = FileManager::kRspAck;
83
    ackResponse.hdr.req_opcode = FileManager::kCmdListDirectory;
84
    ackResponse.hdr.session = 0;
85
    ackResponse.hdr.offset = request->hdr.offset;
86
    ackResponse.hdr.size = 0;
87

88 89 90 91 92
    if (request->hdr.offset == 0) {
        // Requesting first batch of file names
        Q_ASSERT(_fileList.size());
        char *bufPtr = (char *)&ackResponse.data[0];
        for (int i=0; i<_fileList.size(); i++) {
93
            strcpy(bufPtr, _fileList[i].toStdString().c_str());
Don Gagne's avatar
Don Gagne committed
94 95
            uint8_t cchFilename = static_cast<uint8_t>(strlen(bufPtr));
            Q_ASSERT(cchFilename);
96 97 98
            ackResponse.hdr.size += cchFilename + 1;
            bufPtr += cchFilename + 1;
        }
99

100
        _sendResponse(senderSystemId, senderComponentId, &ackResponse, outgoingSeqNumber);
101 102
    } else if (_errMode == errModeNakSecondResponse) {
        // Nak error all subsequent requests
103
        _sendNak(senderSystemId, senderComponentId, FileManager::kErrFail, outgoingSeqNumber, FileManager::kCmdListDirectory);
104 105 106 107
        return;
    } else if (_errMode == errModeNoSecondResponse) {
        // No response for all subsequent requests
        return;
108
    } else {
109
        // FIXME: Does not support directories that span multiple packets
110
        _sendNak(senderSystemId, senderComponentId, FileManager::kErrEOF, outgoingSeqNumber, FileManager::kCmdListDirectory);
111 112 113
    }
}

114
/// @brief Handles Open command requests.
115
void MockLinkFileServer::_openCommand(uint8_t senderSystemId, uint8_t senderComponentId, FileManager::Request* request, uint16_t seqNumber)
116
{
117
    FileManager::Request  response;
118
    QString                     path;
119
    uint16_t                    outgoingSeqNumber = _nextSeqNumber(seqNumber);
120
    
121 122
    ensureNullTemination(request);

123 124
    size_t cchPath = strnlen((char *)request->data, sizeof(request->data));
    Q_ASSERT(cchPath != sizeof(request->data));
125
    Q_UNUSED(cchPath); // Fix initialized-but-not-referenced warning on release builds
126 127 128
    path = (char *)request->data;
    
    // Check path against one of our known test cases
129

130 131 132 133 134 135 136 137 138
    bool found = false;
    for (size_t i=0; i<cFileTestCases; i++) {
        if (path == rgFileTestCases[i].filename) {
            found = true;
            _readFileLength = rgFileTestCases[i].length;
            break;
        }
    }
    if (!found) {
139
        _sendNak(senderSystemId, senderComponentId, FileManager::kErrFail, outgoingSeqNumber, FileManager::kCmdOpenFileRO);
140 141 142
        return;
    }
    
143 144
    response.hdr.opcode = FileManager::kRspAck;
	response.hdr.req_opcode = FileManager::kCmdOpenFileRO;
145 146
    response.hdr.session = _sessionId;
    
147 148
    // Data contains file length
    response.hdr.size = sizeof(uint32_t);
149
    response.openFileLength = _readFileLength;
150
    
151
    _sendResponse(senderSystemId, senderComponentId, &response, outgoingSeqNumber);
152 153
}

154
void MockLinkFileServer::_readCommand(uint8_t senderSystemId, uint8_t senderComponentId, FileManager::Request* request, uint16_t seqNumber)
155
{
156 157
    FileManager::Request	response;
    uint16_t				outgoingSeqNumber = _nextSeqNumber(seqNumber);
158 159

    if (request->hdr.session != _sessionId) {
160
		_sendNak(senderSystemId, senderComponentId, FileManager::kErrFail, outgoingSeqNumber, FileManager::kCmdReadFile);
161 162 163
        return;
    }
    
164 165
    uint32_t readOffset = request->hdr.offset;  // offset into file for reading
    uint8_t cDataBytes = 0;                     // current number of data bytes used
166
    
167 168 169 170
    if (readOffset != 0) {
        // If we get here it means the client is requesting additional data past the first request
        if (_errMode == errModeNakSecondResponse) {
            // Nak error all subsequent requests
171
            _sendNak(senderSystemId, senderComponentId, FileManager::kErrFail, outgoingSeqNumber, FileManager::kCmdReadFile);
172 173 174 175 176 177 178
            return;
        } else if (_errMode == errModeNoSecondResponse) {
            // No rsponse for all subsequent requests
            return;
        }
    }
    
179
    if (readOffset >= _readFileLength) {
180
        _sendNak(senderSystemId, senderComponentId, FileManager::kErrEOF, outgoingSeqNumber, FileManager::kCmdReadFile);
181 182 183 184
        return;
    }
    
    // Write file bytes. Data is a repeating sequence of 0x00, 0x01, .. 0xFF.
185
    for (; cDataBytes < sizeof(response.data) && readOffset < _readFileLength; readOffset++, cDataBytes++) {
186
        response.data[cDataBytes] = readOffset & 0xFF;
187 188
    }
    
189 190
    // We should always have written something, otherwise there is something wrong with the code above
    Q_ASSERT(cDataBytes);
191 192
    
    response.hdr.session = _sessionId;
193
    response.hdr.size = cDataBytes;
194
    response.hdr.offset = request->hdr.offset;
195 196 197
    response.hdr.opcode = FileManager::kRspAck;
	response.hdr.req_opcode = FileManager::kCmdReadFile;

198
    _sendResponse(senderSystemId, senderComponentId, &response, outgoingSeqNumber);
199 200
}

201
void MockLinkFileServer::_streamCommand(uint8_t senderSystemId, uint8_t senderComponentId, FileManager::Request* request, uint16_t seqNumber)
202 203 204 205 206
{
    uint16_t                outgoingSeqNumber = _nextSeqNumber(seqNumber);
    FileManager::Request    response;

    if (request->hdr.session != _sessionId) {
207
		_sendNak(senderSystemId, senderComponentId, FileManager::kErrFail, outgoingSeqNumber, FileManager::kCmdBurstReadFile);
208 209 210 211 212 213 214 215 216 217 218 219 220 221
        return;
    }
    
    uint32_t readOffset = 0;	// offset into file for reading
    uint32_t ackOffset = 0;     // offset for ack
    uint8_t cDataAck;           // number of bytes in ack
    
    while (readOffset < _readFileLength) {
        cDataAck = 0;
        
        if (readOffset != 0) {
            // If we get here it means the client is requesting additional data past the first request
            if (_errMode == errModeNakSecondResponse) {
                // Nak error all subsequent requests
222
                _sendNak(senderSystemId, senderComponentId, FileManager::kErrFail, outgoingSeqNumber, FileManager::kCmdBurstReadFile);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
                return;
            } else if (_errMode == errModeNoSecondResponse) {
                // No response for all subsequent requests
                return;
            }
        }
        
        // Write file bytes. Data is a repeating sequence of 0x00, 0x01, .. 0xFF.
        for (; cDataAck < sizeof(response.data) && readOffset < _readFileLength; readOffset++, cDataAck++) {
            response.data[cDataAck] = readOffset & 0xFF;
        }
        
        // We should always have written something, otherwise there is something wrong with the code above
        Q_ASSERT(cDataAck);
        
        response.hdr.session = _sessionId;
        response.hdr.size = cDataAck;
        response.hdr.offset = ackOffset;
        response.hdr.opcode = FileManager::kRspAck;
        response.hdr.req_opcode = FileManager::kCmdBurstReadFile;
        
244
        _sendResponse(senderSystemId, senderComponentId, &response, outgoingSeqNumber);
245 246 247 248 249
        
        outgoingSeqNumber = _nextSeqNumber(outgoingSeqNumber);
        ackOffset += cDataAck;
    }
	
250
    _sendNak(senderSystemId, senderComponentId, FileManager::kErrEOF, outgoingSeqNumber, FileManager::kCmdBurstReadFile);
251 252
}

253
void MockLinkFileServer::_terminateCommand(uint8_t senderSystemId, uint8_t senderComponentId, FileManager::Request* request, uint16_t seqNumber)
254
{
255 256
    uint16_t outgoingSeqNumber = _nextSeqNumber(seqNumber);

257
    if (request->hdr.session != _sessionId) {
258
		_sendNak(senderSystemId, senderComponentId, FileManager::kErrInvalidSession, outgoingSeqNumber, FileManager::kCmdTerminateSession);
259 260 261
        return;
    }
    
262
	_sendAck(senderSystemId, senderComponentId, outgoingSeqNumber, FileManager::kCmdTerminateSession);
263
	
264 265 266
    emit terminateCommandReceived();
}

267
void MockLinkFileServer::_resetCommand(uint8_t senderSystemId, uint8_t senderComponentId, uint16_t seqNumber)
268
{
269 270 271 272 273 274
    uint16_t outgoingSeqNumber = _nextSeqNumber(seqNumber);
    
    _sendAck(senderSystemId, senderComponentId, outgoingSeqNumber, FileManager::kCmdResetSessions);
    
    emit resetCommandReceived();
}
275

276 277 278 279 280
void MockLinkFileServer::handleFTPMessage(const mavlink_message_t& message)
{
    if (message.msgid != MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL) {
        return;
    }
281
    
282
    FileManager::Request  ackResponse;
283

284 285 286 287 288 289
    mavlink_file_transfer_protocol_t requestFTP;
    mavlink_msg_file_transfer_protocol_decode(&message, &requestFTP);
    
    if (requestFTP.target_system != _systemIdServer) {
        return;
    }
290

291 292
    FileManager::Request* request = (FileManager::Request*)&requestFTP.payload[0];

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
	if (_randomDropsEnabled) {
	    if (rand() % 3 == 0) {
	        qDebug() << "FileServer: Random drop of incoming packet";
	        return;
	    }
	}

	if (_lastReplyValid && request->hdr.seqNumber + 1 == _lastReplySequence) {
	    // this is the same request as the one we replied to last. It means the (n)ack got lost, and the GCS
	    // resent the request
	    qDebug() << "FileServer: resending response";
	    _mockLink->respondWithMavlinkMessage(_lastReply);
	    return;
	}

308
    uint16_t incomingSeqNumber = request->hdr.seqNumber;
309 310
    uint16_t outgoingSeqNumber = _nextSeqNumber(incomingSeqNumber);
    
311 312 313 314 315 316 317 318 319
    if (request->hdr.opcode != FileManager::kCmdResetSessions && request->hdr.opcode != FileManager::kCmdTerminateSession) {
        if (_errMode == errModeNoResponse) {
            // Don't respond to any requests, this shold cause the client to eventually timeout waiting for the ack
            return;
        } else if (_errMode == errModeNakResponse) {
            // Nak all requests, the actual error send back doesn't really matter as long as it's an error
            _sendNak(message.sysid, message.compid, FileManager::kErrFail, outgoingSeqNumber, (FileManager::Opcode)request->hdr.opcode);
            return;
        }
320
    }
321

Don Gagne's avatar
Don Gagne committed
322
    switch (request->hdr.opcode) {
323
        case FileManager::kCmdTestNoAck:
Don Gagne's avatar
Don Gagne committed
324 325 326
            // ignored, ack not sent back, for testing only
            break;
            
327
        case FileManager::kCmdNone:
328
            // ignored, always acked
329
            ackResponse.hdr.opcode = FileManager::kRspAck;
Don Gagne's avatar
Don Gagne committed
330 331
            ackResponse.hdr.session = 0;
            ackResponse.hdr.size = 0;
332
            _sendResponse(message.sysid, message.compid, &ackResponse, outgoingSeqNumber);
Don Gagne's avatar
Don Gagne committed
333 334
            break;

335
        case FileManager::kCmdListDirectory:
336
            _listCommand(message.sysid, message.compid, request, incomingSeqNumber);
337
            break;
338
            
339
        case FileManager::kCmdOpenFileRO:
340
            _openCommand(message.sysid, message.compid, request, incomingSeqNumber);
341
            break;
Don Gagne's avatar
Don Gagne committed
342

343
        case FileManager::kCmdReadFile:
344
            _readCommand(message.sysid, message.compid, request, incomingSeqNumber);
345
            break;
346

347
        case FileManager::kCmdBurstReadFile:
348
            _streamCommand(message.sysid, message.compid, request, incomingSeqNumber);
349 350 351
            break;

        case FileManager::kCmdTerminateSession:
352
            _terminateCommand(message.sysid, message.compid, request, incomingSeqNumber);
353 354
            break;

355 356 357 358
        case FileManager::kCmdResetSessions:
            _resetCommand(message.sysid, message.compid, incomingSeqNumber);
            break;
            
359 360
        default:
            // nack for all NYI opcodes
361
            _sendNak(message.sysid, message.compid, FileManager::kErrUnknownCommand, outgoingSeqNumber, (FileManager::Opcode)request->hdr.opcode);
362 363 364
            break;
    }
}
Don Gagne's avatar
Don Gagne committed
365

366
/// @brief Sends an Ack
367
void MockLinkFileServer::_sendAck(uint8_t targetSystemId, uint8_t targetComponentId, uint16_t seqNumber, FileManager::Opcode reqOpcode)
368
{
369
    FileManager::Request ackResponse;
370
    
371 372
    ackResponse.hdr.opcode = FileManager::kRspAck;
	ackResponse.hdr.req_opcode = reqOpcode;
373 374 375
    ackResponse.hdr.session = 0;
    ackResponse.hdr.size = 0;
    
376
    _sendResponse(targetSystemId, targetComponentId, &ackResponse, seqNumber);
377 378
}

379
/// @brief Sends a Nak with the specified error code.
380
void MockLinkFileServer::_sendNak(uint8_t targetSystemId, uint8_t targetComponentId, FileManager::ErrorCode error, uint16_t seqNumber, FileManager::Opcode reqOpcode)
Don Gagne's avatar
Don Gagne committed
381
{
382
    FileManager::Request nakResponse;
Don Gagne's avatar
Don Gagne committed
383

384 385
    nakResponse.hdr.opcode = FileManager::kRspNak;
	nakResponse.hdr.req_opcode = reqOpcode;
Don Gagne's avatar
Don Gagne committed
386
    nakResponse.hdr.session = 0;
387 388
    nakResponse.hdr.size = 1;
    nakResponse.data[0] = error;
Don Gagne's avatar
Don Gagne committed
389
    
390
    _sendResponse(targetSystemId, targetComponentId, &nakResponse, seqNumber);
Don Gagne's avatar
Don Gagne committed
391 392
}

393
/// @brief Emits a Request through the messageReceived signal.
394
void MockLinkFileServer::_sendResponse(uint8_t targetSystemId, uint8_t targetComponentId, FileManager::Request* request, uint16_t seqNumber)
Don Gagne's avatar
Don Gagne committed
395
{
396
    request->hdr.seqNumber = seqNumber;
397 398
    _lastReplySequence = seqNumber;
    _lastReplyValid = true;
399
    
400 401 402
    mavlink_msg_file_transfer_protocol_pack_chan(_systemIdServer,    // System ID
                                                 0,                  // Component ID
                                                 _mockLink->mavlinkChannel(),
403
                                                 &_lastReply,    // Mavlink Message to pack into
404 405 406 407
                                                 0,                  // Target network
                                                 targetSystemId,
                                                 targetComponentId,
                                                 (uint8_t*)request); // Payload
408 409 410 411 412 413 414

	if (_randomDropsEnabled) {
	    if (rand() % 3 == 0) {
	        qDebug() << "FileServer: Random drop of outgoing packet";
	        return;
	    }
	}
Don Gagne's avatar
Don Gagne committed
415
    
416
    _mockLink->respondWithMavlinkMessage(_lastReply);
Lorenz Meier's avatar
Lorenz Meier committed
417
}
418 419 420

/// @brief Generates the next sequence number given an incoming sequence number. Handles generating
/// bad sequence numbers when errModeBadSequence is set.
421
uint16_t MockLinkFileServer::_nextSeqNumber(uint16_t seqNumber)
422 423 424 425 426 427 428 429
{
    uint16_t outgoingSeqNumber = seqNumber + 1;
    
    if (_errMode == errModeBadSequence) {
        outgoingSeqNumber++;
    }
    return outgoingSeqNumber;
}