MockMavlinkFileServer.cc 12.4 KB
Newer Older
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
/*=====================================================================
 
 QGroundControl Open Source Ground Control Station
 
 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 
 This file is part of the QGROUNDCONTROL project
 
 QGROUNDCONTROL is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 QGROUNDCONTROL is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
 
 ======================================================================*/

#include "MockMavlinkFileServer.h"

26 27 28 29 30 31
const MockMavlinkFileServer::ErrorMode_t MockMavlinkFileServer::rgFailureModes[] = {
    MockMavlinkFileServer::errModeNoResponse,
    MockMavlinkFileServer::errModeNakResponse,
    MockMavlinkFileServer::errModeNoSecondResponse,
    MockMavlinkFileServer::errModeNakSecondResponse,
    MockMavlinkFileServer::errModeBadCRC,
32
    MockMavlinkFileServer::errModeBadSequence,
33 34 35
};
const size_t MockMavlinkFileServer::cFailureModes = sizeof(MockMavlinkFileServer::rgFailureModes) / sizeof(MockMavlinkFileServer::rgFailureModes[0]);

36 37
const MockMavlinkFileServer::FileTestCase MockMavlinkFileServer::rgFileTestCases[MockMavlinkFileServer::cFileTestCases] = {
    // File fits one Read Ack packet, partially filling data
38
    { "partial.qgc",    sizeof(((QGCUASFileManager::Request*)0)->data) - 1,     false },
39
    // File fits one Read Ack packet, exactly filling all data
40
    { "exact.qgc",      sizeof(((QGCUASFileManager::Request*)0)->data),         true },
41
    // File is larger than a single Read Ack packets, requires multiple Reads
42
    { "multi.qgc",      sizeof(((QGCUASFileManager::Request*)0)->data) + 1,     true },
43
};
44

45
// We only support a single fixed session
46 47
const uint8_t MockMavlinkFileServer::_sessionId = 1;

48 49
MockMavlinkFileServer::MockMavlinkFileServer(void) :
    _errMode(errModeNone)
50 51 52 53
{

}

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

64 65 66
    // We only support root path
    path = (char *)&request->data[0];
    if (!path.isEmpty() && path != "/") {
67
        _sendNak(QGCUASFileManager::kErrNotDir, outgoingSeqNumber);
68 69 70 71 72
        return;
    }
    
    // Offset requested is past the end of the list
    if (request->hdr.offset > (uint32_t)_fileList.size()) {
73
        _sendNak(QGCUASFileManager::kErrEOF, outgoingSeqNumber);
74 75 76 77 78 79
        return;
    }
    
    ackResponse.hdr.magic = 'f';
    ackResponse.hdr.opcode = QGCUASFileManager::kRspAck;
    ackResponse.hdr.session = 0;
80
    ackResponse.hdr.offset = request->hdr.offset;
81
    ackResponse.hdr.size = 0;
82

83 84 85 86 87
    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++) {
88 89 90
            strcpy(bufPtr, _fileList[i].toStdString().c_str());
            size_t cchFilename = strlen(bufPtr);
			Q_ASSERT(cchFilename);
91 92 93
            ackResponse.hdr.size += cchFilename + 1;
            bufPtr += cchFilename + 1;
        }
94

95
        _emitResponse(&ackResponse, outgoingSeqNumber);
96 97
    } else if (_errMode == errModeNakSecondResponse) {
        // Nak error all subsequent requests
98
        _sendNak(QGCUASFileManager::kErrPerm, outgoingSeqNumber);
99 100 101 102
        return;
    } else if (_errMode == errModeNoSecondResponse) {
        // No response for all subsequent requests
        return;
103
    } else {
104
        // FIXME: Does not support directories that span multiple packets
105
        _sendNak(QGCUASFileManager::kErrEOF, outgoingSeqNumber);
106 107 108
    }
}

109
/// @brief Handles Open command requests.
110
void MockMavlinkFileServer::_openCommand(QGCUASFileManager::Request* request, uint16_t seqNumber)
111 112 113
{
    QGCUASFileManager::Request  response;
    QString                     path;
114
    uint16_t                    outgoingSeqNumber = _nextSeqNumber(seqNumber);
115
    
116 117
    size_t cchPath = strnlen((char *)request->data, sizeof(request->data));
    Q_ASSERT(cchPath != sizeof(request->data));
118
    Q_UNUSED(cchPath); // Fix initialized-but-not-referenced warning on release builds
119 120 121
    path = (char *)request->data;
    
    // Check path against one of our known test cases
122

123 124 125 126 127 128 129 130 131
    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) {
132
        _sendNak(QGCUASFileManager::kErrNotFile, outgoingSeqNumber);
133 134 135 136 137 138 139
        return;
    }
    
    response.hdr.magic = 'f';
    response.hdr.opcode = QGCUASFileManager::kRspAck;
    response.hdr.session = _sessionId;
    
140 141
    // Data contains file length
    response.hdr.size = sizeof(uint32_t);
142
    response.openFileLength = _readFileLength;
143 144
    
    _emitResponse(&response, outgoingSeqNumber);
145 146 147
}

/// @brief Handles Read command requests.
148
void MockMavlinkFileServer::_readCommand(QGCUASFileManager::Request* request, uint16_t seqNumber)
149
{
150 151
    QGCUASFileManager::Request  response;
    uint16_t                    outgoingSeqNumber = _nextSeqNumber(seqNumber);
152 153

    if (request->hdr.session != _sessionId) {
154
        _sendNak(QGCUASFileManager::kErrNoSession, outgoingSeqNumber);
155 156 157
        return;
    }
    
158 159
    uint32_t readOffset = request->hdr.offset;  // offset into file for reading
    uint8_t cDataBytes = 0;                     // current number of data bytes used
160
    
161 162 163 164
    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
165
            _sendNak(QGCUASFileManager::kErrPerm, outgoingSeqNumber);
166 167 168 169 170 171 172
            return;
        } else if (_errMode == errModeNoSecondResponse) {
            // No rsponse for all subsequent requests
            return;
        }
    }
    
173
    if (readOffset >= _readFileLength) {
174
        _sendNak(QGCUASFileManager::kErrEOF, outgoingSeqNumber);
175 176 177 178
        return;
    }
    
    // Write file bytes. Data is a repeating sequence of 0x00, 0x01, .. 0xFF.
179
    for (; cDataBytes < sizeof(response.data) && readOffset < _readFileLength; readOffset++, cDataBytes++) {
180
        response.data[cDataBytes] = readOffset & 0xFF;
181 182
    }
    
183 184
    // We should always have written something, otherwise there is something wrong with the code above
    Q_ASSERT(cDataBytes);
185 186 187
    
    response.hdr.magic = 'f';
    response.hdr.session = _sessionId;
188
    response.hdr.size = cDataBytes;
189
    response.hdr.offset = request->hdr.offset;
190
    response.hdr.opcode = QGCUASFileManager::kRspAck;
191
    
192
    _emitResponse(&response, outgoingSeqNumber);
193 194
}

195
/// @brief Handles Terminate commands
196
void MockMavlinkFileServer::_terminateCommand(QGCUASFileManager::Request* request, uint16_t seqNumber)
197
{
198 199
    uint16_t outgoingSeqNumber = _nextSeqNumber(seqNumber);

200
    if (request->hdr.session != _sessionId) {
201
        _sendNak(QGCUASFileManager::kErrNoSession, outgoingSeqNumber);
202 203 204
        return;
    }
    
205
    _sendAck(outgoingSeqNumber);
206 207 208 209 210 211
    
    // Let our test harness know that we got a terminate command. This is used to validate the a Terminate is correctly
    // sent after an Open.
    emit terminateCommandReceived();
}

212 213 214
/// @brief Handles messages sent to the FTP server.
void MockMavlinkFileServer::sendMessage(mavlink_message_t message)
{
215
    QGCUASFileManager::Request  ackResponse;
216

217
    Q_ASSERT(message.msgid == MAVLINK_MSG_ID_ENCAPSULATED_DATA);
218
    
219 220 221 222 223 224 225 226 227
    mavlink_encapsulated_data_t requestEncapsulatedData;
    mavlink_msg_encapsulated_data_decode(&message, &requestEncapsulatedData);
    QGCUASFileManager::Request* request = (QGCUASFileManager::Request*)&requestEncapsulatedData.data[0];

    Q_ASSERT(request->hdr.magic == QGCUASFileManager::kProtocolMagic);

    uint16_t incomingSeqNumber = requestEncapsulatedData.seqnr;
    uint16_t outgoingSeqNumber = _nextSeqNumber(incomingSeqNumber);
    
228 229 230 231 232
    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
233
        _sendNak(QGCUASFileManager::kErrPerm, outgoingSeqNumber);
234 235
        return;
    }
236

Don Gagne's avatar
Don Gagne committed
237 238
    // Validate CRC
    if (request->hdr.crc32 != QGCUASFileManager::crc32(request)) {
239
        _sendNak(QGCUASFileManager::kErrCrc, outgoingSeqNumber);
Don Gagne's avatar
Don Gagne committed
240
    }
241

Don Gagne's avatar
Don Gagne committed
242 243 244 245 246 247 248 249 250 251
    switch (request->hdr.opcode) {
        case QGCUASFileManager::kCmdTestNoAck:
            // ignored, ack not sent back, for testing only
            break;
            
        case QGCUASFileManager::kCmdReset:
            // terminates all sessions
            // Fall through to send back Ack

        case QGCUASFileManager::kCmdNone:
252
            // ignored, always acked
Don Gagne's avatar
Don Gagne committed
253 254 255 256 257
            ackResponse.hdr.magic = 'f';
            ackResponse.hdr.opcode = QGCUASFileManager::kRspAck;
            ackResponse.hdr.session = 0;
            ackResponse.hdr.crc32 = 0;
            ackResponse.hdr.size = 0;
258
            _emitResponse(&ackResponse, outgoingSeqNumber);
Don Gagne's avatar
Don Gagne committed
259 260 261
            break;

        case QGCUASFileManager::kCmdList:
262
            _listCommand(request, incomingSeqNumber);
263
            break;
264
            
265
        case QGCUASFileManager::kCmdOpen:
266
            _openCommand(request, incomingSeqNumber);
267
            break;
Don Gagne's avatar
Don Gagne committed
268

269
        case QGCUASFileManager::kCmdRead:
270
            _readCommand(request, incomingSeqNumber);
271
            break;
272

273
        case QGCUASFileManager::kCmdTerminate:
274
            _terminateCommand(request, incomingSeqNumber);
275 276
            break;

Don Gagne's avatar
Don Gagne committed
277
        // Remainder of commands are NYI
278

Don Gagne's avatar
Don Gagne committed
279
        case QGCUASFileManager::kCmdCreate:
280
            // creates <path> for writing, returns <session>
Don Gagne's avatar
Don Gagne committed
281
        case QGCUASFileManager::kCmdWrite:
282
            // appends <size> bytes at <offset> in <session>
Don Gagne's avatar
Don Gagne committed
283
        case QGCUASFileManager::kCmdRemove:
284 285 286
            // remove file (only if created by server?)
        default:
            // nack for all NYI opcodes
287
            _sendNak(QGCUASFileManager::kErrUnknownCommand, outgoingSeqNumber);
288 289 290
            break;
    }
}
Don Gagne's avatar
Don Gagne committed
291

292
/// @brief Sends an Ack
293
void MockMavlinkFileServer::_sendAck(uint16_t seqNumber)
294 295 296 297 298 299 300 301
{
    QGCUASFileManager::Request ackResponse;
    
    ackResponse.hdr.magic = 'f';
    ackResponse.hdr.opcode = QGCUASFileManager::kRspAck;
    ackResponse.hdr.session = 0;
    ackResponse.hdr.size = 0;
    
302
    _emitResponse(&ackResponse, seqNumber);
303 304
}

305
/// @brief Sends a Nak with the specified error code.
306
void MockMavlinkFileServer::_sendNak(QGCUASFileManager::ErrorCode error, uint16_t seqNumber)
Don Gagne's avatar
Don Gagne committed
307 308 309 310 311 312
{
    QGCUASFileManager::Request nakResponse;

    nakResponse.hdr.magic = 'f';
    nakResponse.hdr.opcode = QGCUASFileManager::kRspNak;
    nakResponse.hdr.session = 0;
313 314
    nakResponse.hdr.size = 1;
    nakResponse.data[0] = error;
Don Gagne's avatar
Don Gagne committed
315
    
316
    _emitResponse(&nakResponse, seqNumber);
Don Gagne's avatar
Don Gagne committed
317 318
}

319
/// @brief Emits a Request through the messageReceived signal.
320
void MockMavlinkFileServer::_emitResponse(QGCUASFileManager::Request* request, uint16_t seqNumber)
Don Gagne's avatar
Don Gagne committed
321 322 323
{
    mavlink_message_t   mavlinkMessage;
    
324
    request->hdr.magic = QGCUASFileManager::kProtocolMagic;
Don Gagne's avatar
Don Gagne committed
325
    request->hdr.crc32 = QGCUASFileManager::crc32(request);
326 327 328 329
    if (_errMode == errModeBadCRC) {
        // Return a bad CRC
        request->hdr.crc32++;
    }
Don Gagne's avatar
Don Gagne committed
330
    
331
    mavlink_msg_encapsulated_data_pack(250, 50, &mavlinkMessage, seqNumber, (uint8_t*)request);
Don Gagne's avatar
Don Gagne committed
332 333
    
    emit messageReceived(NULL, mavlinkMessage);
Lorenz Meier's avatar
Lorenz Meier committed
334
}
335 336 337 338 339 340 341 342 343 344 345 346

/// @brief Generates the next sequence number given an incoming sequence number. Handles generating
/// bad sequence numbers when errModeBadSequence is set.
uint16_t MockMavlinkFileServer::_nextSeqNumber(uint16_t seqNumber)
{
    uint16_t outgoingSeqNumber = seqNumber + 1;
    
    if (_errMode == errModeBadSequence) {
        outgoingSeqNumber++;
    }
    return outgoingSeqNumber;
}