Merge branch 'fz-dev' into dev

This commit is contained in:
MX
2022-08-03 21:09:13 +03:00
102 changed files with 2340 additions and 354 deletions
+1 -1
View File
@@ -15,7 +15,7 @@
- `microtar` - TAR archive support library
- `mlib` - Algorithms and containers
- `nanopb` - Nano Protobuf library
- `nfc_protocols` - Nfc protocols library
- `nfc` - Nfc library
- `one_wire` - One wire library
- `qrcode` - Qr code generator library
- `ST25RFAL002` - ST253916 driver and NFC hal
+2
View File
@@ -14,6 +14,7 @@ env.Append(
"lib/toolbox",
"lib/u8g2",
"lib/update_util",
"lib/print",
]
)
@@ -60,6 +61,7 @@ libs = env.BuildModules(
[
"STM32CubeWB",
"freertos",
"print",
"microtar",
"toolbox",
"ST25RFAL002",
+2 -2
View File
@@ -116,7 +116,7 @@ FlipperFormat* flipper_format_string_alloc();
FlipperFormat* flipper_format_file_alloc(Storage* storage);
/**
* Allocate FlipperFormat as file, buffered read-only mode.
* Allocate FlipperFormat as file, buffered mode.
* @return FlipperFormat* pointer to a FlipperFormat instance
*/
FlipperFormat* flipper_format_buffered_file_alloc(Storage* storage);
@@ -131,7 +131,7 @@ FlipperFormat* flipper_format_buffered_file_alloc(Storage* storage);
bool flipper_format_file_open_existing(FlipperFormat* flipper_format, const char* path);
/**
* Open existing file, read-only with buffered read operations.
* Open existing file, buffered mode.
* Use only if FlipperFormat allocated as a file.
* @param flipper_format Pointer to a FlipperFormat instance
* @param path File path
+10 -1
View File
@@ -6,6 +6,7 @@
#include <dialogs/dialogs.h>
#include <furi_hal_nfc.h>
#include <lib/nfc/helpers/mf_classic_dict.h>
#include <lib/nfc/protocols/emv.h>
#include <lib/nfc/protocols/mifare_ultralight.h>
#include <lib/nfc/protocols/mifare_classic.h>
@@ -13,6 +14,7 @@
#define NFC_DEV_NAME_MAX_LEN 22
#define NFC_READER_DATA_MAX_SIZE 64
#define NFC_DICT_KEY_BATCH_SIZE 50
#define NFC_APP_FOLDER ANY_PATH("nfc")
#define NFC_APP_EXTENSION ".nfc"
@@ -41,10 +43,17 @@ typedef struct {
uint16_t size;
} NfcReaderRequestData;
typedef struct {
MfClassicDict* dict;
} NfcMfClassicDictAttackData;
typedef struct {
FuriHalNfcDevData nfc_data;
NfcProtocol protocol;
NfcReaderRequestData reader_data;
union {
NfcReaderRequestData reader_data;
NfcMfClassicDictAttackData mf_classic_dict_attack_data;
};
union {
EmvData emv_data;
MfUltralightData mf_ul_data;
+18 -17
View File
@@ -101,10 +101,8 @@ int32_t nfc_worker_task(void* context) {
nfc_worker_emulate_mf_ultralight(nfc_worker);
} else if(nfc_worker->state == NfcWorkerStateMfClassicEmulate) {
nfc_worker_emulate_mf_classic(nfc_worker);
} else if(nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) {
nfc_worker_mf_classic_dict_attack(nfc_worker, MfClassicDictTypeUser);
} else if(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack) {
nfc_worker_mf_classic_dict_attack(nfc_worker, MfClassicDictTypeFlipper);
} else if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) {
nfc_worker_mf_classic_dict_attack(nfc_worker);
}
furi_hal_nfc_sleep();
nfc_worker_change_state(nfc_worker, NfcWorkerStateReady);
@@ -397,11 +395,13 @@ void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker) {
}
}
void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType type) {
void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker) {
furi_assert(nfc_worker);
furi_assert(nfc_worker->callback);
MfClassicData* data = &nfc_worker->dev_data->mf_classic_data;
NfcMfClassicDictAttackData* dict_attack_data =
&nfc_worker->dev_data->mf_classic_dict_attack_data;
uint32_t total_sectors = mf_classic_get_total_sectors_num(data->type);
uint64_t key = 0;
FuriHalNfcTxRxContext tx_rx = {};
@@ -409,15 +409,17 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
bool card_removed_notified = false;
// Load dictionary
MfClassicDict* dict = mf_classic_dict_alloc(type);
MfClassicDict* dict = dict_attack_data->dict;
if(!dict) {
FURI_LOG_E(TAG, "Dictionary not found");
nfc_worker->callback(NfcWorkerEventNoDictFound, nfc_worker->context);
mf_classic_dict_free(dict);
return;
}
FURI_LOG_D(TAG, "Start Dictionary attack");
FURI_LOG_D(
TAG,
"Start Dictionary attack, Key Count %d",
mf_classic_dict_get_total_keys(dict));
for(size_t i = 0; i < total_sectors; i++) {
FURI_LOG_I(TAG, "Sector %d", i);
nfc_worker->callback(NfcWorkerEventNewSector, nfc_worker->context);
@@ -425,7 +427,11 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
if(mf_classic_is_sector_read(data, i)) continue;
bool is_key_a_found = mf_classic_is_key_found(data, i, MfClassicKeyA);
bool is_key_b_found = mf_classic_is_key_found(data, i, MfClassicKeyB);
uint16_t key_index = 0;
while(mf_classic_dict_get_next_key(dict, &key)) {
if(++key_index % NFC_DICT_KEY_BATCH_SIZE == 0) {
nfc_worker->callback(NfcWorkerEventNewDictKeyBatch, nfc_worker->context);
}
furi_hal_nfc_sleep();
if(furi_hal_nfc_activate_nfca(200, NULL)) {
furi_hal_nfc_sleep();
@@ -456,8 +462,7 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
}
}
if(is_key_a_found && is_key_b_found) break;
if(!((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) ||
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)))
if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack)
break;
} else {
if(!card_removed_notified) {
@@ -465,20 +470,16 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
card_removed_notified = true;
card_found_notified = false;
}
if(!((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) ||
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)))
if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack)
break;
}
}
if(!((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) ||
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)))
if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack)
break;
mf_classic_read_sector(&tx_rx, data, i);
mf_classic_dict_rewind(dict);
}
mf_classic_dict_free(dict);
if((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) ||
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)) {
if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) {
nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context);
} else {
nfc_worker->callback(NfcWorkerEventAborted, nfc_worker->context);
+2 -2
View File
@@ -14,8 +14,7 @@ typedef enum {
NfcWorkerStateUidEmulate,
NfcWorkerStateMfUltralightEmulate,
NfcWorkerStateMfClassicEmulate,
NfcWorkerStateMfClassicUserDictAttack,
NfcWorkerStateMfClassicFlipperDictAttack,
NfcWorkerStateMfClassicDictAttack,
// Debug
NfcWorkerStateEmulateApdu,
NfcWorkerStateField,
@@ -49,6 +48,7 @@ typedef enum {
// Mifare Classic events
NfcWorkerEventNoDictFound,
NfcWorkerEventNewSector,
NfcWorkerEventNewDictKeyBatch,
NfcWorkerEventFoundKeyA,
NfcWorkerEventFoundKeyB,
} NfcWorkerEvent;
+1 -2
View File
@@ -13,7 +13,6 @@
#include <lib/nfc/protocols/mifare_desfire.h>
#include <lib/nfc/protocols/nfca.h>
#include "helpers/mf_classic_dict.h"
#include "helpers/nfc_debug_pcap.h"
struct NfcWorker {
@@ -43,6 +42,6 @@ void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker);
void nfc_worker_emulate_mf_classic(NfcWorker* nfc_worker);
void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType type);
void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker);
void nfc_worker_emulate_apdu(NfcWorker* nfc_worker);
+107
View File
@@ -0,0 +1,107 @@
Import("env")
wrapped_fn_list = [
#
# used by our firmware, so we provide their realizations
#
"fflush",
"printf",
"putc", # fallback from printf, thanks gcc
"putchar", # storage cli
"puts", # fallback from printf, thanks gcc
"snprintf",
"vsnprintf", # m-string
"__assert", # ???
"__assert_func", # ???
#
# wrap other functions to make sure they are not called
# realization is not provided
#
"setbuf",
"setvbuf",
"fprintf",
"vfprintf",
"vprintf",
"fputc",
"fputs",
"sprintf", # specially, because this function is dangerous
"asprintf",
"vasprintf",
"asiprintf",
"asniprintf",
"asnprintf",
"diprintf",
"fiprintf",
"iprintf",
"siprintf",
"sniprintf",
"vasiprintf",
"vasniprintf",
"vasnprintf",
"vdiprintf",
"vfiprintf",
"viprintf",
"vsiprintf",
"vsniprintf",
#
# Scanf is not implemented 4 now
#
# "fscanf",
# "scanf",
# "sscanf",
# "vsprintf",
# "fgetc",
# "fgets",
# "getc",
# "getchar",
# "gets",
# "ungetc",
# "vfscanf",
# "vscanf",
# "vsscanf",
# "fiscanf",
# "iscanf",
# "siscanf",
# "vfiscanf",
# "viscanf",
# "vsiscanf",
#
# File management
#
# "fclose",
# "freopen",
# "fread",
# "fwrite",
# "fgetpos",
# "fseek",
# "fsetpos",
# "ftell",
# "rewind",
# "feof",
# "ferror",
# "fopen",
# "remove",
# "rename",
# "fseeko",
# "ftello",
]
for wrapped_fn in wrapped_fn_list:
env.Append(
LINKFLAGS=[
"-Wl,--wrap," + wrapped_fn,
"-Wl,--wrap," + wrapped_fn + "_unlocked",
"-Wl,--wrap,_" + wrapped_fn + "_r",
"-Wl,--wrap,_" + wrapped_fn + "_unlocked_r",
]
)
libenv = env.Clone(FW_LIB_NAME="print")
libenv.ApplyLibFlags()
libenv.Append(CCFLAGS=["-Wno-double-promotion"])
sources = libenv.GlobRecursive("*.c*", ".")
lib = libenv.StaticLibrary("${FW_LIB_NAME}", sources)
libenv.Install("${LIB_DIST_DIR}", lib)
Return("lib")
File diff suppressed because it is too large Load Diff
+103
View File
@@ -0,0 +1,103 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on
// embedded systems with a very limited resources.
// Use this instead of bloated standard/newlib printf.
// These routines are thread safe and reentrant.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _PRINTF_H_
#define _PRINTF_H_
#include <stdarg.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Output a character to a custom device like UART, used by the printf() function
* This function is declared here only. You have to write your custom implementation somewhere
* \param character Character to output
*/
void _putchar(char character);
/**
* Tiny printf implementation
* You have to implement _putchar if you use printf()
* To avoid conflicts with the regular printf() API it is overridden by macro defines
* and internal underscore-appended functions like printf_() are used
* \param format A string that specifies the format of the output
* \return The number of characters that are written into the array, not counting the terminating null character
*/
int printf_(const char* format, ...);
/**
* Tiny sprintf implementation
* Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD!
* \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output!
* \param format A string that specifies the format of the output
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
int sprintf_(char* buffer, const char* format, ...);
/**
* Tiny snprintf/vsnprintf implementation
* \param buffer A pointer to the buffer where to store the formatted string
* \param count The maximum number of characters to store in the buffer, including a terminating null character
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that COULD have been written into the buffer, not counting the terminating
* null character. A value equal or larger than count indicates truncation. Only when the returned value
* is non-negative and less than count, the string has been completely written.
*/
int snprintf_(char* buffer, size_t count, const char* format, ...);
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va);
/**
* Tiny vprintf implementation
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
int vprintf_(const char* format, va_list va);
/**
* printf with output function
* You may use this as dynamic alternative to printf() with its fixed _putchar() output
* \param out An output function which takes one character and an argument pointer
* \param arg An argument pointer for user data passed to output function
* \param format A string that specifies the format of the output
* \return The number of characters that are sent to the output function, not counting the terminating null character
*/
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...);
#ifdef __cplusplus
}
#endif
#endif // _PRINTF_H_
+74
View File
@@ -0,0 +1,74 @@
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <furi/core/check.h>
#include <furi/core/thread.h>
#include <furi/core/common_defines.h>
#include <string.h>
#include "printf_tiny.h"
void _putchar(char character) {
furi_thread_stdout_write(&character, 1);
}
int __wrap_printf(const char* format, ...) {
va_list args;
va_start(args, format);
int ret = vprintf_(format, args);
va_end(args);
return ret;
}
int __wrap_vsnprintf(char* str, size_t size, const char* format, va_list args) {
return vsnprintf_(str, size, format, args);
}
int __wrap_puts(const char* str) {
size_t size = furi_thread_stdout_write(str, strlen(str));
size += furi_thread_stdout_write("\n", 1);
return size;
}
int __wrap_putchar(int ch) {
size_t size = furi_thread_stdout_write((char*)&ch, 1);
return size;
}
int __wrap_putc(int ch, FILE* stream) {
UNUSED(stream);
size_t size = furi_thread_stdout_write((char*)&ch, 1);
return size;
}
int __wrap_snprintf(char* str, size_t size, const char* format, ...) {
va_list args;
va_start(args, format);
int ret = __wrap_vsnprintf(str, size, format, args);
va_end(args);
return ret;
}
int __wrap_fflush(FILE* stream) {
UNUSED(stream);
furi_thread_stdout_flush();
return 0;
}
__attribute__((__noreturn__)) void __wrap___assert(const char* file, int line, const char* e) {
UNUSED(file);
UNUSED(line);
// TODO: message file and line number
furi_crash(e);
}
__attribute__((__noreturn__)) void
__wrap___assert_func(const char* file, int line, const char* func, const char* e) {
UNUSED(file);
UNUSED(line);
UNUSED(func);
// TODO: message file and line number
furi_crash(e);
}
+1 -1
View File
@@ -37,7 +37,7 @@ void set_random_name(char* name, uint8_t max_name_size) {
uint8_t prefix_i = rand() % COUNT_OF(prefix);
uint8_t suffix_i = rand() % COUNT_OF(suffix);
sniprintf(name, max_name_size, "%s_%s", prefix[prefix_i], suffix[suffix_i]);
snprintf(name, max_name_size, "%s_%s", prefix[prefix_i], suffix[suffix_i]);
// Set first symbol to upper case
name[0] = name[0] - 0x20;
}
+104 -27
View File
@@ -1,6 +1,5 @@
#include "buffered_file_stream.h"
#include "core/check.h"
#include "stream_i.h"
#include "file_stream.h"
#include "stream_cache.h"
@@ -9,6 +8,7 @@ typedef struct {
Stream stream_base;
Stream* file_stream;
StreamCache* cache;
bool sync_pending;
} BufferedFileStream;
static void buffered_file_stream_free(BufferedFileStream* stream);
@@ -27,6 +27,9 @@ static bool buffered_file_stream_delete_and_insert(
StreamWriteCB write_callback,
const void* ctx);
static bool buffered_file_stream_flush(BufferedFileStream* stream);
static bool buffered_file_stream_unread(BufferedFileStream* stream);
const StreamVTable buffered_file_stream_vtable = {
.free = (StreamFreeFn)buffered_file_stream_free,
.eof = (StreamEOFFn)buffered_file_stream_eof,
@@ -39,13 +42,12 @@ const StreamVTable buffered_file_stream_vtable = {
.delete_and_insert = (StreamDeleteAndInsertFn)buffered_file_stream_delete_and_insert,
};
static bool buffered_file_stream_unread(BufferedFileStream* stream);
Stream* buffered_file_stream_alloc(Storage* storage) {
BufferedFileStream* stream = malloc(sizeof(BufferedFileStream));
stream->file_stream = file_stream_alloc(storage);
stream->cache = stream_cache_alloc();
stream->sync_pending = false;
stream->stream_base.vtable = &buffered_file_stream_vtable;
return (Stream*)stream;
@@ -58,7 +60,6 @@ bool buffered_file_stream_open(
FS_OpenMode open_mode) {
furi_assert(_stream);
BufferedFileStream* stream = (BufferedFileStream*)_stream;
stream_cache_drop(stream->cache);
furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable);
return file_stream_open(stream->file_stream, path, access_mode, open_mode);
}
@@ -67,7 +68,22 @@ bool buffered_file_stream_close(Stream* _stream) {
furi_assert(_stream);
BufferedFileStream* stream = (BufferedFileStream*)_stream;
furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable);
return file_stream_close(stream->file_stream);
bool success = false;
do {
if(!(stream->sync_pending ? buffered_file_stream_flush(stream) :
buffered_file_stream_unread(stream)))
break;
if(!file_stream_close(stream->file_stream)) break;
success = true;
} while(false);
return success;
}
bool buffered_file_stream_sync(Stream* _stream) {
furi_assert(_stream);
BufferedFileStream* stream = (BufferedFileStream*)_stream;
furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable);
return stream->sync_pending ? buffered_file_stream_flush(stream) : true;
}
FS_Error buffered_file_stream_get_error(Stream* _stream) {
@@ -85,10 +101,23 @@ static void buffered_file_stream_free(BufferedFileStream* stream) {
}
static bool buffered_file_stream_eof(BufferedFileStream* stream) {
return stream_cache_at_end(stream->cache) && stream_eof(stream->file_stream);
bool ret;
const bool file_stream_eof = stream_eof(stream->file_stream);
const bool cache_at_end = stream_cache_at_end(stream->cache);
if(!stream->sync_pending) {
ret = file_stream_eof && cache_at_end;
} else {
const size_t remaining_size =
stream_size(stream->file_stream) - stream_tell(stream->file_stream);
ret = stream_cache_size(stream->cache) >=
(remaining_size ? cache_at_end : file_stream_eof);
}
return ret;
}
static void buffered_file_stream_clean(BufferedFileStream* stream) {
// Not syncing because data will be deleted anyway
stream->sync_pending = false;
stream_cache_drop(stream->cache);
stream_clean(stream->file_stream);
}
@@ -97,7 +126,7 @@ static bool buffered_file_stream_seek(
BufferedFileStream* stream,
int32_t offset,
StreamOffset offset_type) {
bool success = false;
bool success = true;
int32_t new_offset = offset;
if(offset_type == StreamOffsetFromCurrent) {
@@ -108,47 +137,71 @@ static bool buffered_file_stream_seek(
}
if((new_offset != 0) || (offset_type != StreamOffsetFromCurrent)) {
stream_cache_drop(stream->cache);
success = stream_seek(stream->file_stream, new_offset, offset_type);
} else {
success = true;
if(stream->sync_pending) {
success = buffered_file_stream_sync((Stream*)stream);
} else {
stream_cache_drop(stream->cache);
}
if(success) {
success = stream_seek(stream->file_stream, new_offset, offset_type);
}
}
return success;
}
static size_t buffered_file_stream_tell(BufferedFileStream* stream) {
return stream_tell(stream->file_stream) + stream_cache_pos(stream->cache) -
stream_cache_size(stream->cache);
size_t pos = stream_tell(stream->file_stream) + stream_cache_pos(stream->cache);
if(!stream->sync_pending) {
pos -= stream_cache_size(stream->cache);
}
return pos;
}
static size_t buffered_file_stream_size(BufferedFileStream* stream) {
return stream_cache_size(stream->cache) + stream_size(stream->file_stream);
size_t size = stream_size(stream->file_stream);
if(stream->sync_pending) {
const size_t remaining_size = size - stream_tell(stream->file_stream);
const size_t cache_size = stream_cache_size(stream->cache);
if(cache_size > remaining_size) {
size += (cache_size - remaining_size);
}
}
return size;
}
static size_t
buffered_file_stream_write(BufferedFileStream* stream, const uint8_t* data, size_t size) {
size_t need_to_write = size;
do {
if(!buffered_file_stream_unread(stream)) break;
need_to_write -= stream_write(stream->file_stream, data, size);
if(!stream->sync_pending) {
if(!buffered_file_stream_unread(stream)) break;
}
while(need_to_write) {
stream->sync_pending = true;
need_to_write -=
stream_cache_write(stream->cache, data + (size - need_to_write), need_to_write);
if(need_to_write) {
stream->sync_pending = false;
if(!stream_cache_flush(stream->cache, stream->file_stream)) break;
}
}
} while(false);
return size - need_to_write;
}
static size_t buffered_file_stream_read(BufferedFileStream* stream, uint8_t* data, size_t size) {
size_t need_to_read = size;
while(need_to_read) {
need_to_read -=
stream_cache_read(stream->cache, data + (size - need_to_read), need_to_read);
if(need_to_read) {
if(!stream_cache_fill(stream->cache, stream->file_stream)) {
break;
if(stream->sync_pending) {
if(!buffered_file_stream_flush(stream)) break;
}
if(!stream_cache_fill(stream->cache, stream->file_stream)) break;
}
}
return size - need_to_read;
}
@@ -157,19 +210,43 @@ static bool buffered_file_stream_delete_and_insert(
size_t delete_size,
StreamWriteCB write_callback,
const void* ctx) {
return buffered_file_stream_unread(stream) &&
stream_delete_and_insert(stream->file_stream, delete_size, write_callback, ctx);
bool success = false;
do {
if(!(stream->sync_pending ? buffered_file_stream_flush(stream) :
buffered_file_stream_unread(stream)))
break;
if(!stream_delete_and_insert(stream->file_stream, delete_size, write_callback, ctx)) break;
success = true;
} while(false);
return success;
}
// Write the cache into the underlying stream and adjust seek position
static bool buffered_file_stream_flush(BufferedFileStream* stream) {
bool success = false;
do {
const int32_t offset = stream_cache_size(stream->cache) - stream_cache_pos(stream->cache);
if(!stream_cache_flush(stream->cache, stream->file_stream)) break;
if(offset > 0) {
if(!stream_seek(stream->file_stream, -offset, StreamOffsetFromCurrent)) break;
}
success = true;
} while(false);
stream->sync_pending = false;
return success;
}
// Drop read cache and adjust the underlying stream seek position
static bool buffered_file_stream_unread(BufferedFileStream* stream) {
bool success = true;
const size_t cache_size = stream_cache_size(stream->cache);
const size_t cache_pos = stream_cache_pos(stream->cache);
if(cache_pos < cache_size) {
const int32_t offset = cache_size - cache_pos;
success = stream_seek(stream->file_stream, -offset, StreamOffsetFromCurrent);
if(cache_size > 0) {
const size_t cache_pos = stream_cache_pos(stream->cache);
if(cache_pos < cache_size) {
const int32_t offset = cache_size - cache_pos;
success = stream_seek(stream->file_stream, -offset, StreamOffsetFromCurrent);
}
stream_cache_drop(stream->cache);
}
stream_cache_drop(stream->cache);
return success;
}
+10 -4
View File
@@ -19,7 +19,7 @@ Stream* buffered_file_stream_alloc(Storage* storage);
* @param path path to file
* @param access_mode access mode from FS_AccessMode
* @param open_mode open mode from FS_OpenMode
* @return success flag. You need to close the file even if the open operation failed.
* @return True on success, False on failure. You need to close the file even if the open operation failed.
*/
bool buffered_file_stream_open(
Stream* stream,
@@ -29,12 +29,18 @@ bool buffered_file_stream_open(
/**
* Closes the file.
* @param stream
* @return true
* @return false
* @param stream pointer to file stream object.
* @return True on success, False on failure.
*/
bool buffered_file_stream_close(Stream* stream);
/**
* Forces write from cache to the underlying file.
* @param stream pointer to file stream object.
* @return True on success, False on failure.
*/
bool buffered_file_stream_sync(Stream* stream);
/**
* Retrieves the error id from the file object
* @param stream pointer to stream object.
+22 -1
View File
@@ -46,6 +46,14 @@ size_t stream_cache_fill(StreamCache* cache, Stream* stream) {
return size_read;
}
bool stream_cache_flush(StreamCache* cache, Stream* stream) {
const size_t size_written = stream_write(stream, cache->data, cache->data_size);
const bool success = (size_written == cache->data_size);
cache->data_size = 0;
cache->position = 0;
return success;
}
size_t stream_cache_read(StreamCache* cache, uint8_t* data, size_t size) {
furi_assert(cache->data_size >= cache->position);
const size_t size_read = MIN(size, cache->data_size - cache->position);
@@ -56,6 +64,19 @@ size_t stream_cache_read(StreamCache* cache, uint8_t* data, size_t size) {
return size_read;
}
size_t stream_cache_write(StreamCache* cache, const uint8_t* data, size_t size) {
furi_assert(cache->data_size >= cache->position);
const size_t size_written = MIN(size, STREAM_CACHE_MAX_SIZE - cache->position);
if(size_written > 0) {
memcpy(cache->data + cache->position, data, size_written);
cache->position += size_written;
if(cache->position > cache->data_size) {
cache->data_size = cache->position;
}
}
return size_written;
}
int32_t stream_cache_seek(StreamCache* cache, int32_t offset) {
furi_assert(cache->data_size >= cache->position);
int32_t actual_offset = 0;
@@ -63,7 +84,7 @@ int32_t stream_cache_seek(StreamCache* cache, int32_t offset) {
if(offset > 0) {
actual_offset = MIN(cache->data_size - cache->position, (size_t)offset);
} else if(offset < 0) {
actual_offset = -MIN(cache->position, (size_t)abs(offset));
actual_offset = MAX(-((int32_t)cache->position), offset);
}
cache->position += actual_offset;
+17
View File
@@ -55,6 +55,14 @@ size_t stream_cache_pos(StreamCache* cache);
*/
size_t stream_cache_fill(StreamCache* cache, Stream* stream);
/**
* Write as much cached data as possible to a stream.
* @param cache Pointer to a StreamCache instance
* @param stream Pointer to a Stream instance
* @return True on success, False on failure.
*/
bool stream_cache_flush(StreamCache* cache, Stream* stream);
/**
* Read cached data and advance the internal cursor.
* @param cache Pointer to a StreamCache instance.
@@ -64,6 +72,15 @@ size_t stream_cache_fill(StreamCache* cache, Stream* stream);
*/
size_t stream_cache_read(StreamCache* cache, uint8_t* data, size_t size);
/**
* Write to cached data and advance the internal cursor.
* @param cache Pointer to a StreamCache instance.
* @param data Pointer to a data buffer.
* @param size Maximum size in bytes to write to the cache.
* @return Actual size that was written.
*/
size_t stream_cache_write(StreamCache* cache, const uint8_t* data, size_t size);
/**
* Move the internal cursor relatively to its current position.
* @param cache Pointer to a StreamCache instance.