~aleteoryx/muditaos

ref: 64cfe81ec546ed75b7be1cffaef781aa3b893236 muditaos/module-services/service-desktop/endpoints/filesystem/FilesystemEndpoint.cpp -rw-r--r-- 12.7 KiB
64cfe81e — Marek Niepieklo [CP-427] Set Mudita USB VID as default 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "FilesystemEndpoint.hpp"
#include "FileOperations.hpp"
#include "service-desktop/DesktopMessages.hpp"
#include "service-desktop/ServiceDesktop.hpp"
#include <filesystem>

using namespace parserFSM;

auto FilesystemEndpoint::handle(Context &context) -> void
{
    auto returnCode = sys::ReturnCodes::Success;
    switch (context.getMethod()) {
    case http::Method::get:
        returnCode = runGet(context);
        break;
    case http::Method::post:
        returnCode = runPost(context);
        break;
    case http::Method::put:
        returnCode = runPut(context);
        break;
    default:
        LOG_ERROR("Unhandled method request: %u", static_cast<unsigned>(context.getMethod()));
        returnCode = sys::ReturnCodes::Failure;
        break;
    }
    LOG_DEBUG("returnCode: %u", static_cast<unsigned>(returnCode));
}
static bool isWritable(const fs::path &file)
{
    auto lamb = [](std::FILE *stream) { std::fclose(stream); };

    std::unique_ptr<std::FILE, decltype(lamb)> sf(std::fopen(file.c_str(), "w"), lamb);

    return static_cast<bool>(sf);
}

auto FilesystemEndpoint::requestLogsFlush() const -> void
{
    auto owner = dynamic_cast<ServiceDesktop *>(ownerServicePtr);
    if (owner) {
        owner->requestLogsFlush();
    }
}

auto FilesystemEndpoint::startGetFile(Context &context) const -> sys::ReturnCodes
{
    std::filesystem::path filePath = context.getBody()[parserFSM::json::fileName].string_value();

    try {
        requestLogsFlush();
    }
    catch (const std::runtime_error &e) {
        LOG_ERROR("Logs flush exception: %s", e.what());

        context.setResponseStatus(parserFSM::http::Code::InternalServerError);
        context.setResponseBody(json11::Json::object({{json::reason, std::string(e.what())}}));
        return sys::ReturnCodes::Failure;
    }

    if (!std::filesystem::exists(filePath)) {
        LOG_ERROR("file not found");

        context.setResponseStatus(parserFSM::http::Code::NotFound);
        context.setResponseBody(json11::Json::object({{json::reason, json::filesystem::reasons::fileDoesNotExist}}));
        return sys::ReturnCodes::Failure;
    }

    LOG_DEBUG("Checking file");

    try {
        auto [rxID, fileSize] = fileOps.createReceiveIDForFile(filePath);

        auto fileHash = fileOps.getFileHashForReceiveID(rxID);

        context.setResponseStatus(parserFSM::http::Code::OK);
        context.setResponseBody(
            json11::Json::object({{json::filesystem::rxID, static_cast<int>(rxID)},
                                  {json::fileSize, static_cast<int>(fileSize)},
                                  {json::fileCrc32, fileHash},
                                  {json::filesystem::chunkSize, static_cast<int>(FileOperations::ChunkSize)}}));
    }
    catch (std::runtime_error &e) {
        LOG_ERROR("FileOperations exception: %s", e.what());

        context.setResponseStatus(parserFSM::http::Code::InternalServerError);
        context.setResponseBody(json11::Json::object({{json::reason, std::string(e.what())}}));
        return sys::ReturnCodes::Failure;
    }
    catch (std::exception &e) {
        LOG_ERROR("FileOperations exception: %s", e.what());

        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        context.setResponseBody(json11::Json::object({{json::reason, std::string(e.what())}}));
        return sys::ReturnCodes::Failure;
    }

    return sys::ReturnCodes::Success;
}

auto FilesystemEndpoint::getFileChunk(Context &context) const -> sys::ReturnCodes
{
    auto returnCode    = sys::ReturnCodes::Failure;
    const auto rxID    = context.getBody()[parserFSM::json::filesystem::rxID].int_value();
    const auto chunkNo = context.getBody()[parserFSM::json::filesystem::chunkNo].int_value();
    std::string data{};

    try {
        data = fileOps.getDataForReceiveID(rxID, chunkNo);
    }
    catch (std::exception &e) {
        LOG_ERROR("%s", e.what());
        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        context.setResponseBody(json11::Json::object({{json::reason, e.what()}}));

        return sys::ReturnCodes::Failure;
    }

    if (data.length()) {
        context.setResponseStatus(parserFSM::http::Code::OK);
        context.setResponseBody(json11::Json::object({{json::filesystem::rxID, static_cast<int>(rxID)},
                                                      {json::filesystem::chunkNo, static_cast<int>(chunkNo)},
                                                      {json::filesystem::data, data}}));

        returnCode = sys::ReturnCodes::Success;
    }
    else {
        std::ostringstream errorReason;
        errorReason << "Invalid request rxID: " << std::to_string(rxID) << ", chunkNo: " << std::to_string(chunkNo);
        LOG_ERROR("%s", errorReason.str().c_str());

        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        context.setResponseBody(json11::Json::object({{json::reason, errorReason.str()}}));
    }

    return returnCode;
}

auto FilesystemEndpoint::runGet(Context &context) -> sys::ReturnCodes
{
    LOG_DEBUG("Handling GET");
    auto returnCode = sys::ReturnCodes::Failure;

    if (context.getBody()[parserFSM::json::fileName].is_string()) {
        returnCode = startGetFile(context);
    }
    else if (context.getBody()[parserFSM::json::filesystem::rxID].is_number()) {
        returnCode = getFileChunk(context);
    }
    else {
        LOG_ERROR("unknown request");
        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        returnCode = sys::ReturnCodes::Failure;
    }

    MessageHandler::putToSendQueue(context.createSimpleResponse());

    return returnCode;
}

auto FilesystemEndpoint::runPost(Context &context) -> sys::ReturnCodes
{
    LOG_DEBUG("Handling POST");
    sys::ReturnCodes returnCode = sys::ReturnCodes::Failure;
    std::string cmd             = context.getBody()[parserFSM::json::filesystem::command].string_value();

    context.setResponseBody(
        json11::Json::object({{json::status, std::to_string(static_cast<int>(sys::ReturnCodes::Failure))}}));

    auto owner = static_cast<ServiceDesktop *>(ownerServicePtr);

    if (cmd == parserFSM::json::filesystem::commands::download) {
        fs::path filePath    = context.getBody()[parserFSM::json::fileName].string_value();
        fs::path tmpFilePath = purefs::dir::getUpdatesOSPath() / filePath;

        const uint32_t fileSize = context.getBody()[parserFSM::json::fileSize].int_value();
        const auto fileCrc32    = context.getBody()[parserFSM::json::fileCrc32].string_value();

        LOG_DEBUG("got owner for tmp file");

        if (isWritable(tmpFilePath)) {
            LOG_INFO("download %" PRIu32 " bytes to tmp file", fileSize);

            if (owner->desktopWorker->startDownload(tmpFilePath, fileSize, fileCrc32) == sys::ReturnCodes::Success) {
                context.setResponseStatus(parserFSM::http::Code::Accepted);
                returnCode = sys::ReturnCodes::Success;
            }
        }
        else {
            LOG_ERROR("download command failed, can't write %" PRIu32 " bytes to tmp file", fileSize);
        }
    }
    else if (cmd == parserFSM::json::filesystem::commands::checkFile) {
        fs::path filePath = context.getBody()[parserFSM::json::fileName].string_value();
        LOG_DEBUG("Checking file");

        context.setResponseBody(json11::Json::object{{json::fileExists, std::filesystem::exists(filePath)}});
        returnCode = sys::ReturnCodes::Success;
    }
    else {
        LOG_ERROR("unknown command");
        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        returnCode = sys::ReturnCodes::Failure;
    }

    MessageHandler::putToSendQueue(context.createSimpleResponse());
    return returnCode;
}

auto FilesystemEndpoint::runPut(Context &context) -> sys::ReturnCodes
{
    LOG_DEBUG("Handling PUT");
    auto returnCode         = sys::ReturnCodes::Failure;
    const auto &requestBody = context.getBody();

    if (requestBody[parserFSM::json::fileName].is_string() && requestBody[parserFSM::json::fileSize].is_number() &&
        requestBody[parserFSM::json::fileCrc32].is_string()) {
        returnCode = startSendFile(context);
    }
    else if (requestBody[parserFSM::json::filesystem::txID].is_number() &&
             requestBody[parserFSM::json::filesystem::chunkNo].is_number() &&
             requestBody[parserFSM::json::filesystem::data].is_string()) {
        returnCode = sendFileChunk(context);
    }
    else {
        LOG_ERROR("unknown request");
        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        returnCode = sys::ReturnCodes::Failure;
    }

    MessageHandler::putToSendQueue(context.createSimpleResponse());
    return returnCode;
}

auto FilesystemEndpoint::startSendFile(parserFSM::Context &context) const -> sys::ReturnCodes
{
    auto returnCode         = sys::ReturnCodes::Failure;
    const auto &requestBody = context.getBody();

    std::filesystem::path filePath = requestBody[parserFSM::json::fileName].string_value();
    const uint32_t fileSize        = requestBody[parserFSM::json::fileSize].int_value();
    const auto fileCrc32           = requestBody[parserFSM::json::fileCrc32].string_value();

    LOG_DEBUG("Start sending of file: %s", filePath.c_str());

    if (fileSize == 0 || fileCrc32.empty()) {
        LOG_ERROR("File %s corrupted", filePath.c_str());

        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        return returnCode;
    }

    if (!std::filesystem::exists(filePath)) {
        LOG_DEBUG("Creating file %s", filePath.c_str());

        context.setResponseStatus(parserFSM::http::Code::Created);
    }
    else {
        LOG_DEBUG("Overwriting file %s", filePath.c_str());
    }

    try {
        auto txID = fileOps.createTransmitIDForFile(filePath, fileSize, fileCrc32);

        context.setResponseStatus(parserFSM::http::Code::OK);
        context.setResponseBody(
            json11::Json::object({{json::filesystem::txID, static_cast<int>(txID)},
                                  {json::filesystem::chunkSize, static_cast<int>(FileOperations::ChunkSize)}}));
    }
    catch (std::runtime_error &e) {
        LOG_ERROR("FileOperations exception: %s", e.what());

        context.setResponseStatus(parserFSM::http::Code::InternalServerError);
        context.setResponseBody(json11::Json::object({{json::reason, std::string(e.what())}}));
        return sys::ReturnCodes::Failure;
    }
    catch (std::exception &e) {
        LOG_ERROR("FileOperations exception: %s", e.what());

        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        context.setResponseBody(json11::Json::object({{json::reason, std::string(e.what())}}));
        return sys::ReturnCodes::Failure;
    }

    return sys::ReturnCodes::Success;
}

auto FilesystemEndpoint::sendFileChunk(parserFSM::Context &context) const -> sys::ReturnCodes
{
    auto returnCode         = sys::ReturnCodes::Failure;
    const auto &requestBody = context.getBody();
    const auto txID         = requestBody[parserFSM::json::filesystem::txID].int_value();
    const auto chunkNo      = requestBody[parserFSM::json::filesystem::chunkNo].int_value();
    const auto data         = requestBody[parserFSM::json::filesystem::data].string_value();

    if (data.empty()) {
        std::ostringstream errorReason;
        errorReason << "Invalid request txID: " << std::to_string(txID) << ", chunkNo: " << std::to_string(chunkNo);
        LOG_ERROR("%s", errorReason.str().c_str());

        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        context.setResponseBody(json11::Json::object({{json::reason, errorReason.str()}}));
        return returnCode;
    }

    try {
        returnCode = fileOps.sendDataForTransmitID(txID, chunkNo, data);
    }
    catch (std::exception &e) {
        LOG_ERROR("%s", e.what());
        context.setResponseStatus(parserFSM::http::Code::NotAcceptable);
        context.setResponseBody(json11::Json::object({{json::reason, e.what()}}));

        return sys::ReturnCodes::Failure;
    }

    if (returnCode == sys::ReturnCodes::Success) {
        LOG_DEBUG("FileOperations::sendDataForTransmitID success");
        context.setResponseStatus(parserFSM::http::Code::OK);
        context.setResponseBody(json11::Json::object({
            {json::filesystem::txID, static_cast<int>(txID)},
            {json::filesystem::chunkNo, static_cast<int>(chunkNo)},
        }));
    }
    else {
        LOG_ERROR("FileOperations::sendDataForTransmitID failed");
        context.setResponseStatus(parserFSM::http::Code::BadRequest);
        context.setResponseBody(json11::Json::object({
            {json::filesystem::txID, static_cast<int>(txID)},
            {json::filesystem::chunkNo, static_cast<int>(chunkNo)},
        }));
    }

    return returnCode;
}