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

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the the copyright holders nor the names of their
 contributors may be used to endorse or promote products derived from this
 software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "sdl_rpc_plugin/commands/mobile/get_file_request.h"

#include <boost/crc.hpp>
#include "application_manager/app_service_manager.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "application_manager/rpc_service.h"
#include "interfaces/MOBILE_API.h"
#include "utils/file_system.h"

namespace {
/**
 * Calculates CRC32 checksum
 * @param binary_data - input data for which CRC32 should be calculated
 * @return calculated CRC32 checksum
 */
uint32_t GetCrc32CheckSum(const std::vector<uint8_t>& binary_data) {
  const std::size_t file_size = binary_data.size();
  boost::crc_32_type result;
  result.process_bytes(&binary_data[0], file_size);
  return result.checksum();
}

}  // namespace

namespace sdl_rpc_plugin {
using namespace application_manager;
namespace commands {

SDL_CREATE_LOG_VARIABLE("Commands")

GetFileRequest::GetFileRequest(
    const application_manager::commands::MessageSharedPtr& message,
    ApplicationManager& application_manager,
    app_mngr::rpc_service::RPCService& rpc_service,
    app_mngr::HMICapabilities& hmi_capabilities,
    policy::PolicyHandlerInterface& policy_handler)
    : CommandRequestImpl(message,
                         application_manager,
                         rpc_service,
                         hmi_capabilities,
                         policy_handler)
    , file_name_("")
    , file_type_(mobile_apis::FileType::INVALID_ENUM)
    , length_(0)
    , offset_(0) {}

GetFileRequest::~GetFileRequest() {}

bool GetFileRequest::GetFilePath(std::string& file_path, bool& forward_to_hmi) {
  std::string path = application_manager_.get_settings().app_storage_folder();
  auto connect_key = connection_key();
  forward_to_hmi = false;

  if ((*message_)[strings::msg_params].keyExists(strings::app_service_id)) {
    std::string service_id =
        (*message_)[strings::msg_params][strings::app_service_id].asString();
    SDL_LOG_DEBUG("Finding storage directory for service id: " << service_id);

    AppService* app_service_info =
        application_manager_.GetAppServiceManager().FindServiceByID(service_id);
    if (app_service_info) {
      if (app_service_info->mobile_service) {
        connect_key = app_service_info->connection_key;
      } else {
        forward_to_hmi = true;
        return true;
      }
    } else {
      return false;
    }
  } else {
    SDL_LOG_DEBUG("Using current storage directory");
  }

  ApplicationSharedPtr app = application_manager_.application(connect_key);
  file_path = path + "/" + app->folder_name();
  return true;
}

void GetFileRequest::Run() {
  SDL_LOG_AUTO_TRACE();
  SDL_LOG_INFO("Received GetFile request");

  ApplicationSharedPtr app = application_manager_.application(connection_key());
  smart_objects::SmartObject response_params =
      smart_objects::SmartObject(smart_objects::SmartType_Map);

  if (!app) {
    SDL_LOG_ERROR("Application is not registered");
    SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
    return;
  }

  file_name_ = (*message_)[strings::msg_params][strings::file_name].asString();

  if (!file_system::IsFileNameValid(file_name_)) {
    SDL_LOG_ERROR("File name " << file_name_ << " contains forbidden symbols.");
    SendResponse(false,
                 mobile_apis::Result::INVALID_DATA,
                 "File name contains forbidden symbols",
                 &response_params);
    return;
  }

  // Initialize other params with default values. If exists overwrite the values
  SDL_LOG_DEBUG("Intialize non manadatory params with default values");

  if ((*message_)[strings::msg_params].keyExists(strings::file_type)) {
    file_type_ = static_cast<mobile_apis::FileType::eType>(
        (*message_)[strings::msg_params][strings::file_type].asInt());
  }

  // Check if file exists on system (may have to use app service id to get the
  // correct app folder)
  SDL_LOG_DEBUG("Check if file exists on system");
  std::string file_path;
  bool forward_to_hmi;

  if (GetFilePath(file_path, forward_to_hmi)) {
    if (forward_to_hmi) {
      SDL_LOG_DEBUG("Forwarding GetFile request to HMI");
      application_manager_.IncreaseForwardedRequestTimeout(connection_key(),
                                                           correlation_id());
      SendHMIRequest(hmi_apis::FunctionID::BasicCommunication_GetFilePath,
                     &(*message_)[strings::msg_params],
                     true);
      return;
    }
  } else {
    SDL_LOG_ERROR("Could not get file path");
    SendResponse(false,
                 mobile_apis::Result::INVALID_DATA,
                 "Could not get file path",
                 &response_params);
    return;
  }

  const std::string full_path = file_path + "/" + file_name_;
  if (!file_system::FileExists(full_path)) {
    SDL_LOG_ERROR("File " << full_path << " does not exist");
    SendResponse(false,
                 mobile_apis::Result::FILE_NOT_FOUND,
                 "File does not exist",
                 &response_params);
    return;
  }

  // Handle offset
  SDL_LOG_DEBUG("Handle offset and length parameters");
  const uint64_t file_size = file_system::FileSize(full_path);

  if ((*message_)[strings::msg_params].keyExists(strings::offset)) {
    offset_ = (*message_)[strings::msg_params][strings::offset].asUInt();
  }

  length_ = file_size - offset_;
  if ((*message_)[strings::msg_params].keyExists(strings::length)) {
    length_ = std::min(
        static_cast<uint32_t>(
            (*message_)[strings::msg_params][strings::length].asUInt()),
        length_);
  }

  if (offset_ > file_size) {
    SDL_LOG_ERROR("Offset " << offset_ << " greater than file size "
                            << file_size);
    SendResponse(false,
                 mobile_apis::Result::INVALID_DATA,
                 "Offset greater than file size",
                 &response_params);
    return;
  }
  if (length_ > file_size - offset_) {
    SDL_LOG_ERROR("Length " << length_ << " greater than file size - offset"
                            << file_size);
    SendResponse(false,
                 mobile_apis::Result::INVALID_DATA,
                 "Length greater than file size - offset",
                 &response_params);
    return;
  }

  // Load data from file as binary data
  SDL_LOG_DEBUG("Load binary data from file");
  std::vector<uint8_t> bin_data;
  if (!file_system::ReadBinaryFile(full_path, bin_data, offset_, length_)) {
    SDL_LOG_ERROR("Failed to read from file: " << full_path);
    SendResponse(false,
                 mobile_apis::Result::GENERIC_ERROR,
                 "Unable to read from file",
                 &response_params);
    return;
  }

  // Construct response message
  if ((*message_)[strings::msg_params].keyExists(strings::offset)) {
    response_params[strings::offset] = offset_;
  }
  if ((*message_)[strings::msg_params].keyExists(strings::length)) {
    response_params[strings::length] = length_;
  }
  if ((*message_)[strings::msg_params].keyExists(strings::file_type)) {
    response_params[strings::file_type] = file_type_;
  }
  const uint32_t crc_calculated = GetCrc32CheckSum(bin_data);
  response_params[strings::crc32_check_sum] = crc_calculated;

  SendResponse(true,
               mobile_apis::Result::SUCCESS,
               "File uploaded",
               &response_params,
               bin_data);
}

void GetFileRequest::on_event(const app_mngr::event_engine::Event& event) {
  SDL_LOG_AUTO_TRACE();

  if (hmi_apis::FunctionID::BasicCommunication_GetFilePath != event.id()) {
    return;
  }
  const smart_objects::SmartObject& event_message = event.smart_object();

  hmi_apis::Common_Result::eType hmi_result =
      static_cast<hmi_apis::Common_Result::eType>(
          event_message[strings::params][hmi_response::code].asInt());

  mobile_apis::Result::eType result =
      MessageHelper::HMIToMobileResult(hmi_result);
  bool success = PrepareResultForMobileResponse(
      hmi_result, HmiInterfaces::HMI_INTERFACE_AppService);

  if (!success) {
    auto msg_params = event_message[strings::msg_params];
    const char* info = msg_params.keyExists(strings::info)
                           ? msg_params[strings::info].asCharArray()
                           : NULL;

    SendResponse(false, result, info, &msg_params);
    return;
  }
  smart_objects::SmartObject response_params =
      smart_objects::SmartObject(smart_objects::SmartType_Map);
  std::vector<uint8_t> bin_data;

  if (event_message[strings::msg_params].keyExists(strings::file_type)) {
    response_params[strings::file_type] =
        event_message[strings::msg_params][strings::file_type];
  }

  if (event_message[strings::msg_params].keyExists(strings::file_path)) {
    std::string full_path =
        event_message[strings::msg_params][strings::file_path].asString();

    if (!file_system::FileExists(full_path)) {
      SDL_LOG_ERROR("File " << full_path << " does not exist");
      SendResponse(false,
                   mobile_apis::Result::FILE_NOT_FOUND,
                   "File does not exist",
                   &response_params);
      return;
    }

    const uint64_t file_size = file_system::FileSize(full_path);
    if ((*message_)[strings::msg_params].keyExists(strings::offset)) {
      offset_ = (*message_)[strings::msg_params][strings::offset].asUInt();
    }

    length_ = file_size - offset_;
    if ((*message_)[strings::msg_params].keyExists(strings::length)) {
      length_ = std::min(
          static_cast<uint32_t>(
              (*message_)[strings::msg_params][strings::length].asUInt()),
          length_);
    }

    if (offset_ > file_size) {
      SDL_LOG_ERROR("Offset " << offset_ << " greater than file size "
                              << file_size);
      SendResponse(false,
                   mobile_apis::Result::INVALID_DATA,
                   "Offset greater than file size",
                   &response_params);
      return;
    }
    if (length_ > file_size - offset_) {
      SDL_LOG_ERROR("Length " << length_ << " greater than file size - offset"
                              << file_size);
      SendResponse(false,
                   mobile_apis::Result::INVALID_DATA,
                   "Length greater than file size - offset",
                   &response_params);
      return;
    }
    if (!file_system::ReadBinaryFile(full_path, bin_data, offset_, length_)) {
      SDL_LOG_ERROR("Failed to read from file: " << full_path);
      SendResponse(false,
                   mobile_apis::Result::GENERIC_ERROR,
                   "Failed to read from file",
                   &response_params);
      return;
    }

    const uint32_t crc_calculated = GetCrc32CheckSum(bin_data);
    response_params[strings::crc32_check_sum] = crc_calculated;

  } else {
    SDL_LOG_ERROR("HMI did not return a file path: ");
    SendResponse(false,
                 mobile_apis::Result::INVALID_DATA,
                 "HMI did not return a file path",
                 &response_params);
    return;
  }

  SendResponse(true, result, "File uploaded", &response_params, bin_data);
}

}  // namespace commands
}  // namespace sdl_rpc_plugin