-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathFileWorker.cpp
More file actions
531 lines (435 loc) · 18.1 KB
/
Copy pathFileWorker.cpp
File metadata and controls
531 lines (435 loc) · 18.1 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// ======================================================================
// \title FileWorker.cpp
// \author racheljt
// \brief cpp file for FileWorker component implementation class
// ======================================================================
#include "Svc/FileWorker/FileWorker.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Component construction and destruction
// ----------------------------------------------------------------------
FileWorker ::FileWorker(const char* const compName)
: FileWorkerComponentBase(compName), m_state(FileWorkerState::FW_STATE_IDLE), m_abort(false), m_chunkSize(0) {}
void FileWorker ::configure(U64 chunkSize) {
FW_ASSERT(chunkSize > 0);
this->m_chunkSize = chunkSize;
}
FileWorker ::~FileWorker() {}
// ----------------------------------------------------------------------
// Handler implementations for typed input ports
// ----------------------------------------------------------------------
void FileWorker ::cancelIn_handler(FwIndexType portNum) {
this->m_abort.store(true, std::memory_order_relaxed);
}
void FileWorker ::readIn_handler(FwIndexType portNum, const Fw::StringBase& path, Fw::Buffer& buffer) {
// Validate inputs before processing file
if (path.length() == 0) {
this->log_WARNING_HI_InvalidInput(Fw::LogStringArg("readIn"), Fw::LogStringArg("empty path"));
this->readDoneOut_out(0, FW_STATUS_INVALID_INPUT, 0);
return;
}
if (!buffer.isValid()) {
this->log_WARNING_HI_InvalidInput(Fw::LogStringArg("readIn"), Fw::LogStringArg("invalid buffer"));
this->readDoneOut_out(0, FW_STATUS_INVALID_INPUT, 0);
return;
}
const char* const fileName = path.toChar();
FwSizeType fileSize = 0;
if (this->m_state != FW_STATE_IDLE) {
this->log_WARNING_HI_NotInIdle(this->m_state);
this->readDoneOut_out(0, FW_STATUS_NOT_IDLE, 0);
return;
}
// New read request overrides any leftover abort state
this->m_abort.store(false, std::memory_order_relaxed);
this->m_state = FW_STATE_READING;
// Check CRC
U32 crcFromFile = 0;
U32 crcCalculated = 0;
Utils::crc_stat_t crcStat = Utils::verify_checksum(fileName, crcFromFile, crcCalculated);
if (crcStat != Utils::PASSED_FILE_CRC_CHECK) {
this->log_WARNING_HI_CrcFailed(crcStat);
this->readDoneOut_out(0, FW_STATUS_FAILED_CRC, 0);
this->m_state = FW_STATE_IDLE;
return;
}
// Get filesize
Os::FileSystem::Status fsStat = Os::FileSystem::getFileSize(fileName, fileSize);
if (fsStat != Os::FileSystem::OP_OK) {
// Path is ground-controlled and the file may change between the CRC check and here
this->log_WARNING_HI_ReadFailedFileSize(fsStat);
this->readDoneOut_out(0, FW_STATUS_FAILED_FILE_SIZE, 0);
this->m_state = FW_STATE_IDLE;
return;
}
// Start reading
FileWorkerStatus workerStat = this->readBufferFromFile(buffer, fileName);
// Signal done and pass U8* buffer with data
this->readDoneOut_out(0, workerStat, fileSize);
this->m_state = FW_STATE_IDLE;
}
void FileWorker ::verifyIn_handler(FwIndexType portNum, const Fw::StringBase& path, U32 crc) {
// Validate inputs before processing file
if (path.length() == 0) {
this->log_WARNING_HI_InvalidInput(Fw::LogStringArg("verifyIn"), Fw::LogStringArg("empty path"));
this->verifyDoneOut_out(0, FW_STATUS_INVALID_INPUT, 0);
return;
}
const char* const fileName = path.toChar();
FwSizeType fileSize = 0;
FileWorkerStatus workerStat = FW_STATUS_DONE;
U32 crcFromFile = 0;
U32 crcCalculated = 0;
Utils::crc_stat_t crcStat = Utils::verify_checksum(fileName, crcFromFile, crcCalculated);
if (crcStat != Utils::PASSED_FILE_CRC_CHECK) {
this->log_WARNING_HI_CrcFailed(crcStat);
workerStat = FW_STATUS_FAILED_CRC;
}
if (crc != crcFromFile) {
workerStat = FW_STATUS_FAILED_CRC;
this->log_WARNING_LO_CrcVerificationError(crc, crcCalculated);
}
// Get filesize
Os::FileSystem::Status fsStat = Os::FileSystem::getFileSize(fileName, fileSize);
if (fsStat != Os::FileSystem::OP_OK) {
this->log_WARNING_HI_ReadFailedFileSize(fsStat);
workerStat = FW_STATUS_FAILED_FILE_SIZE;
}
this->verifyDoneOut_out(0, workerStat, fileSize);
}
void FileWorker ::writeIn_handler(FwIndexType portNum,
const Fw::StringBase& path,
Fw::Buffer& buffer,
FwSizeType offsetBytes,
bool append) {
// Validate inputs before processing file
if (path.length() == 0) {
this->log_WARNING_HI_InvalidInput(Fw::LogStringArg("writeIn"), Fw::LogStringArg("empty path"));
this->writeDoneOut_out(0, FW_STATUS_INVALID_INPUT, 0);
return;
}
if (!buffer.isValid()) {
this->log_WARNING_HI_InvalidInput(Fw::LogStringArg("writeIn"), Fw::LogStringArg("invalid buffer"));
this->writeDoneOut_out(0, FW_STATUS_INVALID_INPUT, 0);
return;
}
if (offsetBytes > buffer.getSize()) {
this->log_WARNING_HI_InvalidInput(Fw::LogStringArg("writeIn"), Fw::LogStringArg("invalid offset"));
this->writeDoneOut_out(0, FW_STATUS_INVALID_INPUT, 0);
return;
}
char fileName[FileNameStringSize];
// Make sure we are in IDLE state before proceeding
if (this->m_state != FW_STATE_IDLE) {
this->log_WARNING_HI_NotInIdle(this->m_state);
this->writeDoneOut_out(0, FW_STATUS_NOT_IDLE, 0);
return;
}
this->m_state = FW_STATE_WRITING;
// New write request overrides any leftover abort state
this->m_abort.store(false, std::memory_order_relaxed);
// Save file name
// NB: may count null terminator due to FPRIME/fprime-sw#57, but should still be less than FileNameStringSize in any
// case
FwSizeType length = Fw::StringUtils::string_length(path.toChar(), FileNameStringSize);
if (length >= FileNameStringSize || length >= sizeof(fileName)) {
// Path length is ground-controlled, so an oversized path is invalid input, not a coding error.
this->log_WARNING_HI_InvalidInput(Fw::LogStringArg("writeIn"), Fw::LogStringArg("path too long"));
this->writeDoneOut_out(0, FW_STATUS_INVALID_INPUT, 0);
this->m_state = FW_STATE_IDLE;
return;
}
(void)Fw::StringUtils::string_copy(fileName, path.toChar(), sizeof(fileName));
fileName[sizeof(fileName) - 1] = 0; // guarantee termination
// Write
const bool isWrite = this->writeBufferToFile(buffer, fileName, offsetBytes, append);
if (isWrite) {
this->writeBufferHashToFile(buffer, fileName, offsetBytes, append);
}
// Report the actual outcome of the write. A failed writeBufferToFile (open
// failure, permission denied, disk full, partial write) must not be reported
// to ground as a successful FW_STATUS_DONE_WRITE.
const FileWorkerStatus writeStatus = isWrite ? FW_STATUS_DONE_WRITE : FW_STATUS_FAILED_TO_WRITE;
this->writeDoneOut_out(0, writeStatus, isWrite ? buffer.getSize() : 0);
this->m_state = FW_STATE_IDLE;
return;
}
// ----------------------------------------------------------------------
// Helper functions
// ----------------------------------------------------------------------
Svc ::FileWorkerStatus FileWorker ::readBufferFromFile(Fw::Buffer& buffer, const char* const fileName) {
FW_ASSERT(buffer.getData() != nullptr);
FW_ASSERT(fileName != nullptr);
Fw::LogStringArg fileNameStr(fileName);
Os::File file;
// Open file
Os::File::Status fileStat = file.open(fileName, Os::File::OPEN_READ);
if (fileStat != Os::File::OP_OK) {
this->log_WARNING_HI_OpenFileError(fileNameStr, fileStat);
return FW_STATUS_FAILED_TO_OPEN;
}
// Get buffer data and size
FwSizeType readSize = buffer.getSize();
// Read file
this->log_ACTIVITY_LO_ReadBegin(readSize, fileNameStr);
this->readFile(buffer, readSize, file, fileNameStr);
this->log_ACTIVITY_LO_ReadCompleted(readSize, fileNameStr);
file.close();
return FileWorkerStatus::FW_STATUS_DONE_READ;
}
void FileWorker ::readFile(Fw::Buffer& buffer, FwSizeType size, Os::File& file, const Fw::LogStringArg& fileNameStr) {
FW_ASSERT(buffer.getData() != nullptr);
FW_ASSERT(size > 0);
FW_ASSERT(fileNameStr != nullptr);
FwSizeType bytesRead = 0;
FwSizeType numChunks = 0;
U64 timeout = 0;
if (!file.isOpen()) {
return;
}
FileWorkerReadStatus readStat = this->readFileBytes(buffer, size, file, bytesRead);
switch (readStat) {
case FW_READ_ERROR:
// Some read error
this->log_WARNING_HI_ReadError(bytesRead, size, fileNameStr);
break;
case FW_READ_DONE:
break;
case FW_READ_ABORT:
// Abort command was sent
this->log_WARNING_LO_ReadAborted(bytesRead, size, fileNameStr);
break;
case FW_READ_TIMEOUT:
// Determine true timeout
static_assert(BLOCK_SIZE_BYTES > 0, "Divide by 0 error");
numChunks = (size / BLOCK_SIZE_BYTES);
if (size % BLOCK_SIZE_BYTES > 0) {
numChunks += 1;
}
timeout = numChunks * TIMEOUT_MS;
this->log_WARNING_HI_ReadTimeout(bytesRead, size, fileNameStr, timeout);
break;
default:
FW_ASSERT(0); // Should not get here
break;
}
return;
}
Svc ::FileWorkerReadStatus FileWorker ::readFileBytes(Fw::Buffer& buffer,
FwSizeType size,
Os::File& file,
FwSizeType& bytesRead) {
FW_ASSERT(buffer.getData() != nullptr);
FW_ASSERT(size > 0);
// Determine true timeout
static_assert(BLOCK_SIZE_BYTES > 0, "Divide by 0 error");
FwSizeType numChunks = (size / BLOCK_SIZE_BYTES);
if (size % BLOCK_SIZE_BYTES > 0) {
numChunks += 1;
}
U64 timeout = numChunks * TIMEOUT_MS;
// Read loop
bytesRead = 0;
Fw::Time start = this->getTime();
for (U32 i = 0; i < MAX_LOOP_ITERATIONS; i++) {
FwSizeType readAmt = FW_MIN(size - bytesRead, BLOCK_SIZE_BYTES);
FwSizeType readAmtActual = readAmt;
Os::File::Status ret = file.read(buffer.getData() + bytesRead, readAmtActual);
if (Os::File::OP_OK != ret || readAmt != readAmtActual) {
// Count the bytes actually transferred so ReadError telemetry reports
// the true amount. A short read stays an error on purpose: FileWorker
// reads a fixed, caller-specified size and must not silently accept a
// file shorter than expected (e.g. truncated mid-read).
bytesRead += readAmtActual;
return FileWorkerReadStatus::FW_READ_ERROR;
}
bool currAbort = this->m_abort.load(std::memory_order_relaxed);
if (currAbort) {
// Abort command was sent
return FileWorkerReadStatus::FW_READ_ABORT;
}
if (timeout > 0) {
// Only check timeout if > 0
Fw::Time now = this->getTime();
Fw::Time diff = Fw::Time::sub(now, start);
U64 elapsed = (diff.getSeconds() * 1000000) + diff.getUSeconds();
if (elapsed >= timeout) {
return FileWorkerReadStatus::FW_READ_TIMEOUT;
}
}
bytesRead += readAmt;
if (bytesRead >= size) {
// Finished, break out
return FileWorkerReadStatus::FW_READ_DONE;
}
}
return FileWorkerReadStatus::FW_READ_UNKNOWN;
}
bool FileWorker ::getHash(const char* const hashFileName,
Utils::Hash& hash,
Utils::HashBuffer& hashBuffer,
const U8* const data,
const FwSizeType size) {
FW_ASSERT(hashFileName != nullptr);
FW_ASSERT(data != nullptr);
FW_ASSERT(size > 0);
// Open file
Os::File file;
Os::File::Status stat = file.open(hashFileName, Os::File::OPEN_READ);
// Read value if it exists
if (stat == Os::File::OP_OK) {
HASH_HANDLE_TYPE hashValue;
FwSizeType hashSize = sizeof(hashValue);
U8* hashValuePtr = reinterpret_cast<U8*>(&hashValue);
FW_ASSERT(hashValuePtr != nullptr);
Os::File::Status readStat = file.read(hashValuePtr, hashSize);
if (readStat != Os::File::OP_OK) {
Fw::LogStringArg s(hashFileName);
this->log_WARNING_HI_WriteValidationReadError(s, readStat);
return false;
}
Utils::HashBuffer tmp(hashValuePtr, hashSize);
hash.setHashValue(tmp);
hash.update(data, size);
hash.finalize(hashBuffer);
} else if (stat == Os::File::DOESNT_EXIST) {
hash.hash(data, size, hashBuffer);
} else {
Fw::LogStringArg s(hashFileName);
this->log_WARNING_HI_WriteValidationOpenError(s, stat);
return false;
}
return true;
}
bool FileWorker ::writeBufferToFile(Fw::Buffer& buffer, const char* fileName, FwSizeType offset, bool append) {
FW_ASSERT(buffer.getData() != nullptr);
FW_ASSERT(fileName != nullptr);
Fw::LogStringArg logStringArg(fileName);
Os::File file;
Os::File::Status stat = Os::File::OP_OK;
// Open file
if (!append) {
stat = file.open(fileName, Os::File::Mode::OPEN_WRITE);
} else {
stat = file.open(fileName, Os::File::Mode::OPEN_APPEND);
}
if (stat != Os::File::OP_OK) {
this->log_WARNING_HI_OpenFileError(logStringArg, stat);
return false;
}
// Get buffer data and size
FwSizeType size = buffer.getSize();
U8* const data = reinterpret_cast<U8*>(buffer.getData());
FW_ASSERT(data != nullptr);
// Apply offset
FW_ASSERT(offset <= size);
size -= offset;
U8* const dataFromOffset = reinterpret_cast<U8*>(data + offset);
FW_ASSERT(dataFromOffset != nullptr);
// Write file
this->log_ACTIVITY_LO_WriteBegin(size, logStringArg);
FwSizeType writtenSize = this->writeToFile(dataFromOffset, size, file, fileName);
// Check written size
if (writtenSize != size) {
return false;
}
this->log_ACTIVITY_LO_WriteCompleted(size, logStringArg);
return true;
}
void FileWorker ::writeBufferHashToFile(Fw::Buffer& buffer, const char* fileName, FwSizeType offset, bool append) {
FW_ASSERT(buffer.getData() != nullptr);
FW_ASSERT(fileName != nullptr);
// Construct hash file name
const char* ext = Utils::Hash::getFileExtensionString();
FW_ASSERT(ext != nullptr);
char hashFileName[FileNameStringSize];
Fw::FormatStatus status = Fw::stringFormat(hashFileName, sizeof(hashFileName), "%s%s", fileName, ext);
FW_ASSERT(status == Fw::FormatStatus::SUCCESS);
// Compute hash
Utils::HashBuffer hashBuffer;
FwSizeType size = buffer.getSize();
U8* const data = reinterpret_cast<U8*>(buffer.getData());
FW_ASSERT(data != nullptr);
// Apply offset
FW_ASSERT(offset <= size);
size -= offset; // checked by assert
U8* const dataFromOffset = reinterpret_cast<U8*>(data + offset);
FW_ASSERT(dataFromOffset != nullptr);
Utils::Hash hash;
if (!append) {
hash.hash(dataFromOffset, size, hashBuffer);
} else {
bool isHash = this->getHash(hashFileName, hash, hashBuffer, dataFromOffset, size);
if (!isHash) {
return;
}
}
// Open file
Os::File file;
Os::File::Status stat = file.open(hashFileName, Os::File::Mode::OPEN_WRITE);
if (stat != Os::File::OP_OK) {
Fw::LogStringArg logStringArg(hashFileName);
this->log_WARNING_HI_OpenFileError(logStringArg, stat);
return;
}
// Write hash
FwSizeType writtenSize = this->writeToFile(hashBuffer.getBuffAddr(), hashBuffer.getSize(), file, hashFileName);
// Check written size
FwSizeType hashSize = hashBuffer.getSize();
if (writtenSize != hashSize) {
Fw::LogStringArg logStringArg(hashFileName);
this->log_WARNING_LO_WriteValidationError(logStringArg, writtenSize, hashSize);
return;
}
return;
}
FwSizeType FileWorker ::writeToFile(const U8* data, FwSizeType size, Os::File& file, const char* fileName) {
FW_ASSERT(data != nullptr);
FW_ASSERT(size > 0);
FW_ASSERT(file.isOpen());
FW_ASSERT(fileName != nullptr);
// Determine true timeout
static_assert(BLOCK_SIZE_BYTES > 0, "Divide by 0 error");
FwSizeType numChunks = (size / BLOCK_SIZE_BYTES);
if (size % BLOCK_SIZE_BYTES > 0) {
numChunks += 1;
}
U64 timeout = numChunks * TIMEOUT_MS;
// Write loop
FwSizeType bytesWritten = 0;
Fw::Time start = this->getTime();
for (U32 i = 0; i < MAX_LOOP_ITERATIONS; i++) {
FwSizeType writeAmt = FW_MIN(size - bytesWritten, BLOCK_SIZE_BYTES);
Os::File::Status ret = file.write(data + bytesWritten, writeAmt);
if (Os::File::OP_OK != ret || writeAmt == 0) {
Fw::LogStringArg logStringArg(fileName);
this->log_WARNING_HI_WriteFileError(bytesWritten, size, logStringArg, ret);
break;
}
bool currAbort = this->m_abort.load(std::memory_order_relaxed);
if (currAbort) {
// Abort command was sent
Fw::LogStringArg logStringArg(fileName);
this->log_WARNING_LO_WriteAborted(bytesWritten, size, logStringArg);
break;
}
if (timeout > 0) {
// Only check timeout if > 0
Fw::Time now = this->getTime();
Fw::Time diff = Fw::Time::sub(now, start);
U64 elapsed = (diff.getSeconds() * 1000000) + diff.getUSeconds();
if (elapsed >= timeout) {
Fw::LogStringArg logStringArg(fileName);
this->log_WARNING_HI_WriteTimeout(bytesWritten, size, logStringArg, timeout);
break;
}
}
bytesWritten += writeAmt;
if (bytesWritten >= size) {
// Finished, break out
break;
}
}
return bytesWritten;
}
} // namespace Svc