/*********************************************************************************************************************************** Info Handler ***********************************************************************************************************************************/ #include #include #include #include #include "common/crypto/hash.h" #include "common/debug.h" #include "common/format/cipherBlockFormat.h" #include "common/format/format.h" #include "common/ini.h" #include "common/io/filter/filter.h" #include "common/io/io.h" #include "common/log.h" #include "common/type/convert.h" #include "common/type/json.h" #include "common/type/object.h" #include "info/info.h" #include "storage/helper.h" #include "version.h" /*********************************************************************************************************************************** Object types ***********************************************************************************************************************************/ struct Info { InfoPub pub; // Publicly accessible variables const CipherSpec *cipherSpecNone; // Returned by infoCipherSpec() when there are no keys }; struct InfoSave { MemContext *memContext; // Mem context IoWrite *write; // Write object IoFilter *checksum; // hash to generate file checksum String *sectionLast; // The last section seen }; /*********************************************************************************************************************************** Macros and buffer constants for checksum generation ***********************************************************************************************************************************/ #define INFO_CHECKSUM_BEGIN(checksum) \ do \ { \ ioFilterProcessIn(checksum, BRACEL_BUF); \ } \ while (0) BUFFER_STRDEF_STATIC(INFO_CHECKSUM_SECTION_END_BUF, "\":{"); #define INFO_CHECKSUM_SECTION(checksum, section) \ do \ { \ ioFilterProcessIn(checksum, QUOTED_BUF); \ ioFilterProcessIn(checksum, BUFSTR(section)); \ ioFilterProcessIn(checksum, INFO_CHECKSUM_SECTION_END_BUF); \ } \ while (0) BUFFER_STRDEF_STATIC(INFO_CHECKSUM_SECTION_NEXT_END_BUF, "},"); #define INFO_CHECKSUM_SECTION_NEXT(checksum) \ do \ { \ ioFilterProcessIn(checksum, INFO_CHECKSUM_SECTION_NEXT_END_BUF); \ } \ while (0) BUFFER_STRDEF_STATIC(INFO_CHECKSUM_KEY_VALUE_END_BUF, ":"); #define INFO_CHECKSUM_KEY_VALUE(checksum, key, value) \ do \ { \ ioFilterProcessIn(checksum, BUFSTR(jsonFromVar(VARSTR(key)))); \ ioFilterProcessIn(checksum, INFO_CHECKSUM_KEY_VALUE_END_BUF); \ ioFilterProcessIn(checksum, BUFSTR(value)); \ } \ while (0) #define INFO_CHECKSUM_KEY_VALUE_NEXT(checksum) \ do \ { \ ioFilterProcessIn(checksum, COMMA_BUF); \ } \ while (0) BUFFER_STRDEF_STATIC(INFO_CHECKSUM_END_BUF, "}}"); #define INFO_CHECKSUM_END(checksum) \ do \ { \ ioFilterProcessIn(checksum, INFO_CHECKSUM_END_BUF); \ } \ while (0) /**********************************************************************************************************************************/ FN_EXTERN Info * infoNew(const unsigned int format, const CipherSpec *const cipherSpecSub) { FUNCTION_LOG_BEGIN(logLevelDebug); FUNCTION_LOG_PARAM(UINT, format); FUNCTION_LOG_PARAM(CIPHER_SPEC, cipherSpecSub); FUNCTION_LOG_END(); ASSERT(format >= REPOSITORY_FORMAT_MIN && format <= REPOSITORY_FORMAT_MAX); OBJ_NEW_BEGIN(Info, .childQty = MEM_CONTEXT_QTY_MAX) { *this = (Info){}; // Cipher used to encrypt/decrypt subsequent dependent files. Value may be NULL. infoCipherSpecSet(this, cipherSpecSub); this->pub.format = format; this->pub.backrestVersion = STRDEF(PROJECT_VERSION); } OBJ_NEW_END(); FUNCTION_LOG_RETURN(INFO, this); } /**********************************************************************************************************************************/ #define INFO_SECTION_BACKREST "backrest" #define INFO_KEY_CHECKSUM "backrest-checksum" #define INFO_SECTION_CIPHER "cipher" #define INFO_KEY_CIPHER_PASS "cipher-pass" #define INFO_KEY_CIPHER_PASS_CURRENT "cipher-pass-current" #define INFO_KEY_CIPHER_PASS_ROTATE "cipher-pass-rotate" #define INFO_KEY_CIPHER_DIGEST "digest" #define INFO_KEY_CIPHER_KEY "key" FN_EXTERN Info * infoNewLoad( IoRead *const read, const CipherSpec *const cipherSpec, InfoLoadNewCallback *const callbackFunction, void *const callbackData) { FUNCTION_LOG_BEGIN(logLevelDebug); FUNCTION_LOG_PARAM(IO_READ, read); FUNCTION_LOG_PARAM(CIPHER_SPEC, cipherSpec); FUNCTION_LOG_PARAM(FUNCTIONP, callbackFunction); FUNCTION_LOG_PARAM_P(VOID, callbackData); FUNCTION_LOG_END(); FUNCTION_AUDIT_CALLBACK(); ASSERT(read != NULL); ASSERT(cipherSpec != NULL); ASSERT(callbackFunction != NULL); ASSERT(callbackData != NULL); OBJ_NEW_BEGIN(Info, .childQty = MEM_CONTEXT_QTY_MAX) { *this = (Info){}; MEM_CONTEXT_TEMP_BEGIN() { String *const sectionLast = strNew(); // The last section seen during load IoFilter *const checksumActualFilter = cryptoHashNew(hashTypeSha1); // Checksum calculated from the file const String *checksumExpected = NULL; // Checksum found in ini file INFO_CHECKSUM_BEGIN(checksumActualFilter); TRY_BEGIN() { Ini *const ini = iniNewP(read, .strict = true); MEM_CONTEXT_TEMP_RESET_BEGIN() { const IniValue *value = iniValueNext(ini); while (value != NULL) { // Calculate checksum if (!(strEqZ(value->section, INFO_SECTION_BACKREST) && strEqZ(value->key, INFO_KEY_CHECKSUM))) { if (strEmpty(sectionLast) || !strEq(value->section, sectionLast)) { if (!strEmpty(sectionLast)) INFO_CHECKSUM_SECTION_NEXT(checksumActualFilter); INFO_CHECKSUM_SECTION(checksumActualFilter, value->section); strCat(strTrunc(sectionLast), value->section); } else INFO_CHECKSUM_KEY_VALUE_NEXT(checksumActualFilter); INFO_CHECKSUM_KEY_VALUE(checksumActualFilter, value->key, value->value); } // Process backrest section if (strEqZ(value->section, INFO_SECTION_BACKREST)) { // Validate and store format if (strEqZ(value->key, INFO_KEY_FORMAT)) { const unsigned int format = jsonReadUInt(jsonReadNew(value->value)); repoFormatValidate(format); this->pub.format = format; } // Store pgBackRest version else if (strEqZ(value->key, INFO_KEY_VERSION)) { MEM_CONTEXT_OBJ_BEGIN(this) { this->pub.backrestVersion = varStr(jsonToVar(value->value)); } MEM_CONTEXT_OBJ_END(); } // Store checksum to be validated later else if (strEqZ(value->key, INFO_KEY_CHECKSUM)) { MEM_CONTEXT_OBJ_BEGIN(this) { checksumExpected = varStr(jsonToVar(value->value)); } MEM_CONTEXT_OBJ_END(); } } // Process cipher section else if (strEqZ(value->section, INFO_SECTION_CIPHER)) { // No validation needed for cipher-pass, just store it if (strEqZ(value->key, INFO_KEY_CIPHER_PASS)) { MEM_CONTEXT_TEMP_BEGIN() { // Dependent files are encrypted with the same cipher type as this one const CipherType cipherType = cipherSpecType(cipherSpec); CipherSpecMap *const cipherSpecMap = cipherSpecMapNew(); const Variant *const cipherPass = jsonToVar(value->value); // Format >= 6 stores every key by id along with the digest it derives with. A key that derives // with SHA-1 is from format 5 and is stored as text as before. Format 6 keys are stored as // base64 and decoded to the bytes they derive with. if (infoFormat(this) >= REPOSITORY_FORMAT_6) { const KeyValue *const keyKv = varKv(cipherPass); const VariantList *const idList = kvKeyList(keyKv); for (unsigned int idIdx = 0; idIdx < varLstSize(idList); idIdx++) { const Variant *const id = varLstGet(idList, idIdx); const KeyValue *const keyData = varKv(kvGet(keyKv, id)); const String *const key = varStr(kvGet(keyData, VARSTRDEF(INFO_KEY_CIPHER_KEY))); const HashType digest = strIdFromZ( strZ(varStr(kvGet(keyData, VARSTRDEF(INFO_KEY_CIPHER_DIGEST))))); cipherSpecMapAdd( cipherSpecMap, varStr(id), cipherSpecNewP( cipherType, digest == hashTypeSha1 ? BUFSTR(key) : bufNewDecode(encodingBase64, key), .digest = digest)); } } // Else there is one key with no id and no digest, which every repository derives with SHA-1 else { cipherSpecMapAdd( cipherSpecMap, CIPHER_SPEC_MAP_ID_DEFAULT_STR, cipherSpecNewP(cipherType, BUFSTR(varStr(cipherPass)), .digest = hashTypeSha1)); } infoCipherSpecMapSet(this, cipherSpecMap); } MEM_CONTEXT_TEMP_END(); } // Current key id else if (strEqZ(value->key, INFO_KEY_CIPHER_PASS_CURRENT)) { MEM_CONTEXT_TEMP_BEGIN() { cipherSpecMapIdCurrentSet( this->pub.cipherSpecMap, jsonReadStr(jsonReadNew(value->value))); } MEM_CONTEXT_TEMP_END(); } // Time of the last key rotation else if (strEqZ(value->key, INFO_KEY_CIPHER_PASS_ROTATE)) this->pub.cipherRotateTime = (time_t)jsonReadInt64(jsonReadNew(value->value)); } // Else pass to callback for processing else callbackFunction(callbackData, value->section, value->key, jsonReadNew(value->value)); value = iniValueNext(ini); MEM_CONTEXT_TEMP_RESET(1000); } } MEM_CONTEXT_TEMP_END(); } CATCH(CryptoError) { THROW_FMT(CryptoError, "%s\nHINT: is or was the repo encrypted?", errorMessage()); } TRY_END(); INFO_CHECKSUM_END(checksumActualFilter); // Verify the checksum first so a file that is empty or not an info file at all is reported as a checksum failure // rather than as a missing format const String *const checksumActual = strNewEncode( encodingHex, pckReadBinP(pckReadNew(ioFilterResult(checksumActualFilter)))); if (checksumExpected == NULL) THROW_FMT(ChecksumError, "invalid checksum, actual '%s' but no checksum found", strZ(checksumActual)); else if (!strEq(checksumExpected, checksumActual)) { THROW_FMT( ChecksumError, "invalid checksum, actual '%s' but expected '%s'", strZ(checksumActual), strZ(checksumExpected)); } // The format defines how everything else is read, so a file without one is not an info file this version can use. The // format is zero until the key is found and the value stored, so if we got here then the key was not found. if (infoFormat(this) == 0) THROW(FormatError, "repository format not found\nHINT: is this a valid " PROJECT_NAME " info file?"); // Only a read that looked for a header reports a format, so a result here means the file had one. The header is written // from the same format as the content, so a file where they disagree has been damaged or put together from parts of two // files. PackRead *const cipherResult = ioFilterGroupResultP(ioReadFilterGroup(read), CIPHER_BLOCK_FORMAT_FILTER_TYPE); if (cipherResult != NULL) { const unsigned int formatHeader = cipherBlockFormatResult(cipherResult); if (this->pub.format != formatHeader) { THROW_FMT( FormatError, "repository format %u does not match header format %u", this->pub.format, formatHeader); } } } MEM_CONTEXT_TEMP_END(); // A file with no cipher section has no encrypted dependent files if (this->pub.cipherSpecMap == NULL) infoCipherSpecMapSet(this, NULL); } OBJ_NEW_END(); FUNCTION_LOG_RETURN(INFO, this); } /**********************************************************************************************************************************/ FN_EXTERN bool infoSaveSection(InfoSave *const infoSaveData, const char *const section, const String *const sectionNext) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO_SAVE, infoSaveData); FUNCTION_TEST_PARAM(STRINGZ, section); FUNCTION_TEST_PARAM(STRING, sectionNext); FUNCTION_TEST_END(); ASSERT(infoSaveData != NULL); ASSERT(section != NULL); FUNCTION_TEST_RETURN( BOOL, (infoSaveData->sectionLast == NULL || strCmpZ(infoSaveData->sectionLast, section) < 0) && (sectionNext == NULL || strCmpZ(sectionNext, section) > 0)); } /**********************************************************************************************************************************/ FN_EXTERN void infoSaveValue(InfoSave *const infoSaveData, const char *const section, const char *const key, const String *const jsonValue) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO_SAVE, infoSaveData); FUNCTION_TEST_PARAM(STRINGZ, section); FUNCTION_TEST_PARAM(STRINGZ, key); FUNCTION_TEST_PARAM(STRING, jsonValue); FUNCTION_TEST_END(); FUNCTION_AUDIT_CALLBACK(); ASSERT(infoSaveData != NULL); ASSERT(section != NULL); ASSERT(key != NULL); ASSERT(jsonValue != NULL); ASSERT(strSize(jsonValue) != 0); // The JSON value must not be an array because this may be confused with a section in the ini file ASSERT(strZ(jsonValue)[0] != '['); // Save section if (infoSaveData->sectionLast == NULL || !strEqZ(infoSaveData->sectionLast, section)) { if (infoSaveData->sectionLast != NULL) { INFO_CHECKSUM_SECTION_NEXT(infoSaveData->checksum); ioWriteLine(infoSaveData->write, BUFSTRDEF("")); } INFO_CHECKSUM_SECTION(infoSaveData->checksum, STR(section)); ioWrite(infoSaveData->write, BRACKETL_BUF); ioWrite(infoSaveData->write, BUFSTRZ(section)); ioWriteLine(infoSaveData->write, BRACKETR_BUF); MEM_CONTEXT_BEGIN(infoSaveData->memContext) { infoSaveData->sectionLast = strNewZ(section); } MEM_CONTEXT_END(); } else INFO_CHECKSUM_KEY_VALUE_NEXT(infoSaveData->checksum); // Save key/value INFO_CHECKSUM_KEY_VALUE(infoSaveData->checksum, STR(key), jsonValue); ioWrite(infoSaveData->write, BUFSTRZ(key)); ioWrite(infoSaveData->write, EQ_BUF); ioWriteLine(infoSaveData->write, BUFSTR(jsonValue)); FUNCTION_TEST_RETURN_VOID(); } /**********************************************************************************************************************************/ FN_EXTERN void infoSave(Info *const this, IoWrite *const write, InfoSaveCallback *const callbackFunction, void *const callbackData) { FUNCTION_LOG_BEGIN(logLevelDebug); FUNCTION_LOG_PARAM(INFO, this); FUNCTION_LOG_PARAM(IO_WRITE, write); FUNCTION_LOG_PARAM(FUNCTIONP, callbackFunction); FUNCTION_LOG_PARAM_P(VOID, callbackData); FUNCTION_LOG_END(); ASSERT(this != NULL); ASSERT(write != NULL); ASSERT(callbackFunction != NULL); ASSERT(callbackData != NULL); MEM_CONTEXT_TEMP_BEGIN() { InfoSave data = { .memContext = MEM_CONTEXT_TEMP(), .write = write, }; ioWriteOpen(data.write); // Begin checksum calculation data.checksum = cryptoHashNew(hashTypeSha1); INFO_CHECKSUM_BEGIN(data.checksum); // Add version and format callbackFunction(callbackData, STRDEF(INFO_SECTION_BACKREST), &data); infoSaveValue(&data, INFO_SECTION_BACKREST, INFO_KEY_FORMAT, jsonFromVar(VARUINT(infoFormat(this)))); infoSaveValue(&data, INFO_SECTION_BACKREST, INFO_KEY_VERSION, jsonFromVar(VARSTRDEF(PROJECT_VERSION))); // Add cipher keys if defined const CipherSpecMap *const cipherSpecMap = infoCipherSpecMap(this); if (!cipherSpecMapEmpty(cipherSpecMap)) { callbackFunction(callbackData, STRDEF(INFO_SECTION_CIPHER), &data); MEM_CONTEXT_TEMP_BEGIN() { JsonWrite *const json = jsonWriteNewP(); // Format >= 6 stores every key by id along with the digest it derives with. A key that derives with SHA-1 is from // format 5 and is stored as its text. Other keys are stored as base64. if (infoFormat(this) >= REPOSITORY_FORMAT_6) { jsonWriteObjectBegin(json); for (unsigned int keyIdx = 0; keyIdx < cipherSpecMapSize(cipherSpecMap); keyIdx++) { const CipherSpecMapItem *const item = cipherSpecMapGetIdx(cipherSpecMap, keyIdx); // A key must have a digest to store. Release builds check this too, instead of silently writing a key // that no reader can derive. CHECK(AssertError, cipherSpecDigest(item->cipherSpec) != 0, "cipher key must have a digest from format 6"); jsonWriteObjectBegin(jsonWriteKey(json, item->id)); jsonWriteStrId(jsonWriteKeyZ(json, INFO_KEY_CIPHER_DIGEST), cipherSpecDigest(item->cipherSpec)); jsonWriteStr( jsonWriteKeyZ(json, INFO_KEY_CIPHER_KEY), cipherSpecDigest(item->cipherSpec) == hashTypeSha1 ? strNewBuf(cipherSpecPass(item->cipherSpec)) : strNewEncode(encodingBase64, cipherSpecPass(item->cipherSpec))); jsonWriteObjectEnd(json); } jsonWriteObjectEnd(json); } // Else store only the key else { const CipherSpec *const cipherSpec = infoCipherSpec(this); CHECK(AssertError, cipherSpecMapSize(cipherSpecMap) == 1, "only one cipher key can be stored before format 6"); CHECK( AssertError, cipherSpecDigest(cipherSpec) == hashTypeSha1, "cipher key must derive with sha1 before format 6"); jsonWriteStr(json, strNewBuf(cipherSpecPass(cipherSpec))); } infoSaveValue(&data, INFO_SECTION_CIPHER, INFO_KEY_CIPHER_PASS, jsonWriteResult(json)); // Record the current key id, which only exists at format >= 6 if (cipherSpecMapIdCurrent(cipherSpecMap) != NULL) { infoSaveValue( &data, INFO_SECTION_CIPHER, INFO_KEY_CIPHER_PASS_CURRENT, jsonFromVar(VARSTR(cipherSpecMapIdCurrent(cipherSpecMap)))); } // Record the time of the last key rotation if (infoCipherRotateTime(this) != 0) { infoSaveValue( &data, INFO_SECTION_CIPHER, INFO_KEY_CIPHER_PASS_ROTATE, jsonFromVar(VARINT64(infoCipherRotateTime(this)))); } } MEM_CONTEXT_TEMP_END(); } // Flush out any additional sections callbackFunction(callbackData, NULL, &data); // Add checksum (this must be set after all other values or it will not be valid) INFO_CHECKSUM_END(data.checksum); ioWrite(data.write, BUFSTRDEF("\n[" INFO_SECTION_BACKREST "]\n" INFO_KEY_CHECKSUM "=")); ioWriteLine( data.write, BUFSTR(jsonFromVar(VARSTR(strNewEncode(encodingHex, pckReadBinP(pckReadNew(ioFilterResult(data.checksum)))))))); // Close the file ioWriteClose(data.write); } MEM_CONTEXT_TEMP_END(); FUNCTION_LOG_RETURN_VOID(); } /*********************************************************************************************************************************** Getters/Setters ***********************************************************************************************************************************/ FN_EXTERN void infoFormatSet(Info *const this, const unsigned int format) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO, this); FUNCTION_TEST_PARAM(UINT, format); FUNCTION_TEST_END(); ASSERT(this != NULL); ASSERT(format >= REPOSITORY_FORMAT_MIN && format <= REPOSITORY_FORMAT_MAX); this->pub.format = format; FUNCTION_TEST_RETURN_VOID(); } FN_EXTERN const CipherSpec * infoCipherSpec(const Info *const this) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO, this); FUNCTION_TEST_END(); ASSERT(this != NULL); if (this->cipherSpecNone != NULL) FUNCTION_TEST_RETURN_CONST(CIPHER_SPEC, this->cipherSpecNone); FUNCTION_TEST_RETURN_CONST(CIPHER_SPEC, cipherSpecMapGet(infoCipherSpecMap(this), CIPHER_SPEC_MAP_ID_DEFAULT_STR)); } /**********************************************************************************************************************************/ FN_EXTERN void infoCipherSpecMapSet(Info *const this, const CipherSpecMap *const cipherSpecMap) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO, this); FUNCTION_TEST_PARAM(CIPHER_SPEC_MAP, cipherSpecMap); FUNCTION_TEST_END(); FUNCTION_AUDIT_IF(memContextCurrent() != objMemContext(this)); // Do not audit calls from within the object ASSERT(this != NULL); MEM_CONTEXT_OBJ_BEGIN(this) { // NULL becomes an empty map so the getter never returns NULL this->pub.cipherSpecMap = cipherSpecMap == NULL ? cipherSpecMapNew() : cipherSpecMapDup(cipherSpecMap); // The default key is looked up on demand, so only a caller that asks for one key errors when there is no default this->cipherSpecNone = cipherSpecMapEmpty(this->pub.cipherSpecMap) ? cipherSpecNewNone() : NULL; } MEM_CONTEXT_OBJ_END(); FUNCTION_TEST_RETURN_VOID(); } /**********************************************************************************************************************************/ FN_EXTERN void infoCipherSpecAdd(Info *const this, const String *const id, const CipherSpec *const cipherSpec) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO, this); FUNCTION_TEST_PARAM(STRING, id); FUNCTION_TEST_PARAM(CIPHER_SPEC, cipherSpec); FUNCTION_TEST_END(); FUNCTION_AUDIT_IF(memContextCurrent() != objMemContext(this)); // Do not audit calls from within the object ASSERT(this != NULL); ASSERT(id != NULL); ASSERT(cipherSpec != NULL && cipherSpecType(cipherSpec) != cipherTypeNone); ASSERT(cipherSpecDigest(cipherSpec) != 0); MEM_CONTEXT_OBJ_BEGIN(this) { CipherSpecMap *const cipherSpecMap = cipherSpecMapDup(this->pub.cipherSpecMap); cipherSpecMapAdd(cipherSpecMap, id, cipherSpec); this->pub.cipherSpecMap = cipherSpecMap; this->cipherSpecNone = NULL; } MEM_CONTEXT_OBJ_END(); FUNCTION_TEST_RETURN_VOID(); } /**********************************************************************************************************************************/ FN_EXTERN void infoCipherRotateTimeSet(Info *const this, const time_t cipherRotateTime) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO, this); FUNCTION_TEST_PARAM(TIME, cipherRotateTime); FUNCTION_TEST_END(); ASSERT(this != NULL); ASSERT(cipherRotateTime > 0); this->pub.cipherRotateTime = cipherRotateTime; FUNCTION_TEST_RETURN_VOID(); } /**********************************************************************************************************************************/ FN_EXTERN void infoCipherPriorSet(Info *const this, const bool cipherPrior) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO, this); FUNCTION_TEST_PARAM(BOOL, cipherPrior); FUNCTION_TEST_END(); ASSERT(this != NULL); this->pub.cipherPrior = cipherPrior; FUNCTION_TEST_RETURN_VOID(); } /**********************************************************************************************************************************/ FN_EXTERN void infoCipherSpecSet(Info *const this, const CipherSpec *const cipherSpec) { FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(INFO, this); FUNCTION_TEST_PARAM(CIPHER_SPEC, cipherSpec); FUNCTION_TEST_END(); FUNCTION_AUDIT_IF(memContextCurrent() != objMemContext(this)); // Do not audit calls from within the object ASSERT(this != NULL); // No keys needed when there is nothing to encrypt if (cipherSpec == NULL || cipherSpecType(cipherSpec) == cipherTypeNone) { infoCipherSpecMapSet(this, NULL); } // Else the one key, stored under the default id else { ASSERT(cipherSpecDigest(cipherSpec) != 0); MEM_CONTEXT_TEMP_BEGIN() { CipherSpecMap *const cipherSpecMap = cipherSpecMapNew(); cipherSpecMapAdd(cipherSpecMap, CIPHER_SPEC_MAP_ID_DEFAULT_STR, cipherSpec); infoCipherSpecMapSet(this, cipherSpecMap); } MEM_CONTEXT_TEMP_END(); } FUNCTION_TEST_RETURN_VOID(); } /**********************************************************************************************************************************/ FN_EXTERN void infoLoad(const String *const error, InfoLoadCallback *const callbackFunction, void *const callbackData) { FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM(STRING, error); FUNCTION_LOG_PARAM(FUNCTIONP, callbackFunction); FUNCTION_LOG_PARAM_P(VOID, callbackData); FUNCTION_LOG_END(); ASSERT(error != NULL); ASSERT(callbackFunction != NULL); ASSERT(callbackData != NULL); MEM_CONTEXT_TEMP_BEGIN() { unsigned int try = 0; volatile bool done = false; // Are all files tried? Must be preserved even on error. volatile bool loaded = false; // Was a file loaded? Must be preserved even on error. const ErrorType *loadErrorType = NULL; StringList *const loadErrorList = strLstNew(); do { // Attempt to load the file TRY_BEGIN() { loaded = callbackFunction(callbackData, try); done = true; CHECK(AssertError, loaded || try > 0, "file load must be attempted"); } CATCH_ANY() { // Set error type if none has been set if (loadErrorType == NULL) loadErrorType = errorType(); // Else if the error type is different else if (loadErrorType != errorType()) { // Set type that is not file missing (which is likely the most common error) if (loadErrorType == &FileMissingError) { loadErrorType = errorType(); } // Else set a generic error else if (errorType() != &FileMissingError) loadErrorType = &FileOpenError; } // Add the error unless the same error has already been added const String *const loadError = strNewFmt("%s: %s", errorTypeName(errorType()), errorMessage()); if (!strLstExists(loadErrorList, loadError)) strLstAdd(loadErrorList, loadError); // Try again try++; } TRY_END(); } while (!done); // Error when no file was loaded if (!loaded) THROWP_FMT(loadErrorType, "%s:\n%s", strZ(error), strZ(strLstJoin(loadErrorList, "\n"))); } MEM_CONTEXT_TEMP_END(); FUNCTION_LOG_RETURN_VOID(); } /**********************************************************************************************************************************/ typedef struct InfoLoadFileData { MemContext *memContext; // Mem context const Storage *storage; // Storage to load from const String *fileName; // Base filename const CipherSpec *cipherSpec; // Cipher spec InfoLoadFileNewCallback *newLoad; // Create the object from a read of the file void *result; // Loaded object } InfoLoadFileData; static bool infoLoadFileCallback(void *const data, const unsigned int try) { FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM_P(VOID, data); FUNCTION_LOG_PARAM(UINT, try); FUNCTION_LOG_END(); ASSERT(data != NULL); InfoLoadFileData *const loadData = data; bool result = false; // Tries 0 and 1 load the file and the copy with the cipher spec. Tries 2 and 3 load them with the prior cipher spec. if (try < (cipherSpecPrior(loadData->cipherSpec) == NULL ? 2 : 4)) { MEM_CONTEXT_TEMP_BEGIN() { // Construct filename and cipher spec based on try const String *const fileName = try % 2 == 0 ? loadData->fileName : strNewFmt("%s" INFO_COPY_EXT, strZ(loadData->fileName)); const CipherSpec *const cipherSpec = try < 2 ? loadData->cipherSpec : cipherSpecPrior(loadData->cipherSpec); // Attempt to load the file IoRead *const read = storageReadIo(storageNewReadP(loadData->storage, fileName)); cipherBlockFormatFilterGroupReadAdd(ioReadFilterGroup(read), cipherSpec); MEM_CONTEXT_BEGIN(loadData->memContext) { // Try >= 2 decrypts with the prior cipher spec. The object records this and a save encrypts with the same spec. loadData->result = loadData->newLoad(read, cipherSpec, try >= 2); result = true; } MEM_CONTEXT_END(); // Log when the file was decrypted with the prior cipher spec if (try >= 2) LOG_DEBUG_FMT("'%s' was decrypted with the old passphrase", strZ(storagePathP(loadData->storage, fileName))); } MEM_CONTEXT_TEMP_END(); } FUNCTION_LOG_RETURN(BOOL, result); } FN_EXTERN void * infoLoadFile( const Storage *const storage, const String *const fileName, const CipherSpec *const cipherSpec, InfoLoadFileNewCallback *const newLoad) { FUNCTION_LOG_BEGIN(logLevelDebug); FUNCTION_LOG_PARAM(STORAGE, storage); FUNCTION_LOG_PARAM(STRING, fileName); FUNCTION_LOG_PARAM(CIPHER_SPEC, cipherSpec); FUNCTION_LOG_PARAM(FUNCTIONP, newLoad); FUNCTION_LOG_END(); FUNCTION_AUDIT_CALLBACK(); ASSERT(storage != NULL); ASSERT(fileName != NULL); ASSERT(cipherSpec != NULL); ASSERT(newLoad != NULL); InfoLoadFileData data = { .memContext = memContextCurrent(), .storage = storage, .fileName = fileName, .cipherSpec = cipherSpec, .newLoad = newLoad, }; MEM_CONTEXT_TEMP_BEGIN() { const char *const fileNamePath = strZ(storagePathP(storage, fileName)); infoLoad( strNewFmt("unable to load info file '%s' or '%s" INFO_COPY_EXT "'", fileNamePath, fileNamePath), infoLoadFileCallback, &data); } MEM_CONTEXT_TEMP_END(); FUNCTION_LOG_RETURN_P(VOID, data.result); }