From 617789d4b967f38165c365786a1ec8b73f079014 Mon Sep 17 00:00:00 2001 From: gilzoide Date: Sat, 28 Jun 2025 11:32:47 -0300 Subject: [PATCH 1/2] Use SQLite3 Multiple Ciphers --- Plugins/Makefile | 5 +- Plugins/sqlite-amalgamation/sqlite3.c | 97838 +++++++++++++++- Plugins/sqlite-amalgamation/sqlite3.h | 272 + Plugins/sqlite-amalgamation/sqlite3_defines.h | 2 + README.md | 4 +- 5 files changed, 98112 insertions(+), 9 deletions(-) diff --git a/Plugins/Makefile b/Plugins/Makefile index 88649ba..01b85a1 100644 --- a/Plugins/Makefile +++ b/Plugins/Makefile @@ -3,6 +3,7 @@ ANDROID_NDK_ROOT ?= # macOS code signing setup CODESIGN ?= codesign MACOS_CODESIGN_SIGNATURE ?= +MACOS_VERSION_MIN ?= 11.0 # Download GitHub Action releases GITHUB_CLI_BIN ?= gh GITHUB_REPO ?= gilzoide/unity-sqlite-net @@ -49,8 +50,8 @@ lib/linux/%/libgilzoide-sqlite-net.so: lib/linux/%/sqlite3.o~ | lib/linux/% $(CC) -o $@ $^ $(LINKFLAGS) # macOS -lib/macos/libgilzoide-sqlite-net.dylib: CFLAGS += -arch arm64 -arch x86_64 -isysroot $(shell xcrun --show-sdk-path --sdk macosx) -lib/macos/libgilzoide-sqlite-net.dylib: LINKFLAGS += -shared -arch arm64 -arch x86_64 +lib/macos/libgilzoide-sqlite-net.dylib: CFLAGS += -arch arm64 -arch x86_64 -isysroot $(shell xcrun --show-sdk-path --sdk macosx) -mmacosx-version-min=$(MACOS_VERSION_MIN) +lib/macos/libgilzoide-sqlite-net.dylib: LINKFLAGS += -shared -arch arm64 -arch x86_64 -framework Security -mmacosx-version-min=$(MACOS_VERSION_MIN) lib/macos/libgilzoide-sqlite-net.dylib: lib/macos/sqlite3.o~ | lib/macos $(CC) -o $@ $^ $(LINKFLAGS) ifdef MACOS_CODESIGN_SIGNATURE diff --git a/Plugins/sqlite-amalgamation/sqlite3.c b/Plugins/sqlite-amalgamation/sqlite3.c index cf28b32..81de634 100644 --- a/Plugins/sqlite-amalgamation/sqlite3.c +++ b/Plugins/sqlite-amalgamation/sqlite3.c @@ -1,5 +1,125 @@ #include "sqlite3_defines.h" +/* +** Name: sqlite3mc.c +** Purpose: Amalgamation of the SQLite3 Multiple Ciphers encryption extension for SQLite +** Author: Ulrich Telle +** Created: 2020-02-28 +** Copyright: (c) 2006-2025 Ulrich Telle +** License: MIT +*/ + +/* +** Force some options required for WASM builds +*/ + +#ifdef __WASM__ + +/* Disable User Authentication Extension */ +#ifdef SQLITE_USER_AUTHENTICATION +#undef SQLITE_USER_AUTHENTICATION +#endif + +/* Disable AES hardware support */ +/* Note: this may be changed in the future depending on available support */ +#ifdef SQLITE3MC_OMIT_AES_HARDWARE_SUPPORT +#undef SQLITE3MC_OMIT_AES_HARDWARE_SUPPORT +#endif +#define SQLITE3MC_OMIT_AES_HARDWARE_SUPPORT 1 + +#endif + +/* +** Enable SQLite debug assertions if requested +*/ + +#ifndef SQLITE_DEBUG +#if defined(SQLITE_ENABLE_DEBUG) && (SQLITE_ENABLE_DEBUG == 1) +#define SQLITE_DEBUG 1 +#endif +#endif + +/* +** Declare all internal functions as 'static' unless told otherwise +*/ +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE static +#endif + +SQLITE_PRIVATE int sqlite3mc_initialize(const char* arg); +SQLITE_PRIVATE void sqlite3mc_shutdown(void); + +/* +** To enable the extension functions define SQLITE_ENABLE_EXTFUNC on compiling this module +** To enable the reading CSV files define SQLITE_ENABLE_CSV on compiling this module +** To enable the SHA3 support define SQLITE_ENABLE_SHA3 on compiling this module +** To enable the CARRAY support define SQLITE_ENABLE_CARRAY on compiling this module +** To enable the FILEIO support define SQLITE_ENABLE_FILEIO on compiling this module +** To enable the SERIES support define SQLITE_ENABLE_SERIES on compiling this module +** To enable the UUID support define SQLITE_ENABLE_UUID on compiling this module +*/ + +/* +** Disable the user authentication feature by default +*/ +#ifdef SQLITE_USER_AUTHENTICATION +/* Option defined and disabled, therefore undefine option */ +#undef SQLITE_USER_AUTHENTICATION +#endif + +#if defined(_WIN32) || defined(WIN32) + +#ifndef SQLITE3MC_USE_RAND_S +#define SQLITE3MC_USE_RAND_S 1 +#endif + +#if SQLITE3MC_USE_RAND_S +/* Force header stdlib.h to define rand_s() */ +#if !defined(_CRT_RAND_S) +#define _CRT_RAND_S +#endif + +#else /* !WIN32 */ + +/* Define this before is included to */ +/* retrieve memset_s() declaration if available. */ +#define __STDC_WANT_LIB_EXT1__ 1 + +#endif + +#ifndef SQLITE_API +#define SQLITE_API +#endif + +/* +** We need to do the following check here BEFORE including , +** because the header is included from somewhere within +** , and we need support for the new Neon intrinsics, if +** AES hardware support is enabled. +*/ +#if defined (_MSC_VER) +#if defined _M_ARM +#define _ARM_USE_NEW_NEON_INTRINSICS +#endif +#endif + +#include + +/* SQLite functions only needed on Win32 */ +SQLITE_API void sqlite3_win32_write_debug(const char*, int); +SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR); +SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char*); +SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char*, int); +SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char*); +SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char*, int); +SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char*); +#endif + +/* +** Include SQLite3 amalgamation +*/ +/* #include "sqlite3patched.c" */ +/*** Begin of #include "sqlite3patched.c" ***/ /****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite ** version 3.50.1. By combining all the individual C code files into this @@ -22,7 +142,7 @@ ** The content in this amalgamation comes from Fossil check-in ** b77dc5e0f596d2140d9ac682b2893ff65d3a with changes in files: ** -** +** */ #ifndef SQLITE_AMALGAMATION #define SQLITE_CORE 1 @@ -14093,6 +14213,20 @@ struct fts5_api { /******** End of fts5.h *********/ #endif /* SQLITE3_H */ +/* Function prototypes of SQLite3 Multiple Ciphers */ +SQLITE_PRIVATE int sqlite3mcCheckVfs(const char*); +SQLITE_PRIVATE int sqlite3mcFileControlPragma(sqlite3*, const char*, int, void*); +SQLITE_PRIVATE int sqlite3mcHandleAttachKey(sqlite3*, const char*, const char*, sqlite3_value*, char**); +SQLITE_PRIVATE int sqlite3mcHandleMainKey(sqlite3*, const char*); +typedef struct PgHdr PgHdrMC; +SQLITE_PRIVATE void* sqlite3mcPagerCodec(PgHdrMC* pPg); +typedef struct Pager PagerMC; +SQLITE_PRIVATE int sqlite3mcPagerHasCodec(PagerMC* pPager); +SQLITE_PRIVATE void sqlite3mcInitMemoryMethods(); +SQLITE_PRIVATE int sqlite3mcIsBackupSupported(sqlite3*, const char*, sqlite3*, const char*); +SQLITE_PRIVATE void sqlite3mcCodecGetKey(sqlite3* db, int nDb, void** zKey, int* nKey); +SQLITE_PRIVATE int sqlite3mc_builtin_extensions(sqlite3* db); + /************** End of sqlite3.h *********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ @@ -30897,6 +31031,12 @@ SQLITE_PRIVATE int sqlite3MallocInit(void){ } rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0)); + + /* Initialize wrapper for memory management.*/ + if( rc==SQLITE_OK ) { + sqlite3mcInitMemoryMethods(); + } + return rc; } @@ -39019,7 +39159,11 @@ SQLITE_PRIVATE int sqlite3KvvfsInit(void){ /* ** Maximum supported path-length. */ +#if SQLITE3MC_MAX_PATHNAME > 512 +#define MAX_PATHNAME SQLITE3MC_MAX_PATHNAME +#else #define MAX_PATHNAME 512 +#endif /* ** Maximum supported symbolic links @@ -58862,6 +59006,7 @@ SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){ assert( pPager->fd!=0 ); if( pPager->fd->pMethods==0 ) return 0; /* Case (1) */ if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0; /* Failed (3) */ + if( sqlite3mcPagerHasCodec(pPager) != 0 ) return 0; #ifndef SQLITE_OMIT_WAL if( pPager->pWal ){ u32 iRead = 0; @@ -59099,7 +59244,7 @@ static void setGetterMethod(Pager *pPager){ if( pPager->errCode ){ pPager->xGet = getPageError; #if SQLITE_MAX_MMAP_SIZE>0 - }else if( USEFETCH(pPager) ){ + }else if( USEFETCH(pPager) && sqlite3mcPagerHasCodec(pPager) == 0 ){ pPager->xGet = getPageMMap; #endif /* SQLITE_MAX_MMAP_SIZE>0 */ }else{ @@ -69817,7 +69962,7 @@ static int walWriteOneFrame( int rc; /* Result code from subfunctions */ void *pData; /* Data actually written */ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */ - pData = pPage->pData; + if( (pData = sqlite3mcPagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT; walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame); rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset); if( rc ) return rc; @@ -70002,7 +70147,7 @@ static int walFrames( if( pWal->iReCksum==0 || iWriteiReCksum ){ pWal->iReCksum = iWrite; } - pData = p->pData; + if( (pData = sqlite3mcPagerCodec(p))==0 ) return SQLITE_NOMEM; rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff); if( rc ) return rc; p->flags &= ~PGHDR_WAL_APPEND; @@ -83211,6 +83356,12 @@ SQLITE_API sqlite3_backup *sqlite3_backup_init( } #endif + /* Check whether databases are compatible with backup */ + if (!sqlite3mcIsBackupSupported(pSrcDb, zSrcDb, pDestDb, zDestDb)){ + sqlite3ErrorWithMsg(pDestDb, SQLITE_ERROR, "backup is not supported with incompatible source and target databases"); + return NULL; + } + /* Lock the source database handle. The destination database ** handle is not locked in this routine, but it is locked in ** sqlite3_backup_step(). The user is required to ensure that no @@ -122285,6 +122436,11 @@ static void attachFunc( if( rc==SQLITE_OK && pNew->zDbSName==0 ){ rc = SQLITE_NOMEM_BKPT; } + + /* Handle KEY parameter. */ + if( rc==SQLITE_OK ){ + rc = sqlite3mcHandleAttachKey(db, zName, zPath, argv[2], &zErrDyn); + } sqlite3_free_filename( zPath ); /* If the file was opened successfully, read the schema for the new database. @@ -141099,7 +141255,7 @@ SQLITE_PRIVATE void sqlite3Pragma( aFcntl[2] = zRight; aFcntl[3] = 0; db->busyHandler.nBusy = 0; - rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); + rc = sqlite3mcFileControlPragma(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); if( rc==SQLITE_OK ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); @@ -157332,6 +157488,15 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum( } nRes = sqlite3BtreeGetRequestedReserve(pMain); + /* A VACUUM cannot change the pagesize of an encrypted database. */ + if( db->nextPagesize ){ + extern void sqlite3mcCodecGetKey(sqlite3*, int, void**, int*); + int nKey; + char *zKey; + sqlite3mcCodecGetKey(db, iDb, (void**)&zKey, &nKey); + if( nKey ) db->nextPagesize = 0; + } + sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0)); sqlite3BtreeSetPagerFlags(pTemp, pgflags|PAGER_CACHESPILL); @@ -182651,6 +182816,7 @@ static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = { #ifdef SQLITE_EXTRA_AUTOEXT SQLITE_EXTRA_AUTOEXT, #endif + sqlite3mc_builtin_extensions, }; #ifndef SQLITE_AMALGAMATION @@ -182868,6 +183034,8 @@ SQLITE_API int sqlite3_initialize(void){ if( rc==SQLITE_OK ){ sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); + int sqlite3mc_initialize(const char*); + rc = sqlite3mc_initialize(0); #ifdef SQLITE_EXTRA_INIT_MUTEXED { int SQLITE_EXTRA_INIT_MUTEXED(const char*); @@ -182950,6 +183118,8 @@ SQLITE_API int sqlite3_shutdown(void){ void SQLITE_EXTRA_SHUTDOWN(void); SQLITE_EXTRA_SHUTDOWN(); #endif + void sqlite3mc_shutdown(void); + sqlite3mc_shutdown(); sqlite3_os_end(); sqlite3_reset_auto_extension(); sqlite3GlobalConfig.isInit = 0; @@ -185801,6 +185971,9 @@ SQLITE_PRIVATE int sqlite3ParseUri( flags &= ~SQLITE_OPEN_URI; } + /* Check VFS. */ + sqlite3mcCheckVfs(zVfs); + *ppVfs = sqlite3_vfs_find(zVfs); if( *ppVfs==0 ){ *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); @@ -186191,6 +186364,11 @@ static int openDatabase( sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); } #endif + + /* Handle encryption related URI parameters. */ + if( rc==SQLITE_OK ){ + rc = sqlite3mcHandleMainKey(db, zOpen); + } sqlite3_free_filename(zOpen); return rc; } @@ -262809,3 +262987,97653 @@ SQLITE_API int sqlite3_stmt_init( SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } #endif /* SQLITE_AMALGAMATION */ /************************** End of sqlite3.c ******************************/ +/*** End of #include "sqlite3patched.c" ***/ + + +/* +** Include SQLite3MultiCipher components +*/ +/* #include "sqlite3mc_config.h" */ +/*** Begin of #include "sqlite3mc_config.h" ***/ +/* +** Name: sqlite3mc_config.h +** Purpose: Header file for SQLite3 Multiple Ciphers compile-time configuration +** Author: Ulrich Telle +** Created: 2021-09-27 +** Copyright: (c) 2019-2025 Ulrich Telle +** License: MIT +*/ + +#ifndef SQLITE3MC_CONFIG_H_ +#define SQLITE3MC_CONFIG_H_ + +/* +** Definitions of supported ciphers +*/ + +/* +** Compatibility with wxSQLite3 +*/ +#ifdef WXSQLITE3_HAVE_CIPHER_AES_128_CBC +#define HAVE_CIPHER_AES_128_CBC WXSQLITE3_HAVE_CIPHER_AES_128_CBC +#endif + +#ifdef WXSQLITE3_HAVE_CIPHER_AES_256_CBC +#define HAVE_CIPHER_AES_256_CBC WXSQLITE3_HAVE_CIPHER_AES_256_CBC +#endif + +#ifdef WXSQLITE3_HAVE_CIPHER_CHACHA20 +#define HAVE_CIPHER_CHACHA20 WXSQLITE3_HAVE_CIPHER_CHACHA20 +#endif + +#ifdef WXSQLITE3_HAVE_CIPHER_SQLCIPHER +#define HAVE_CIPHER_SQLCIPHER WXSQLITE3_HAVE_CIPHER_SQLCIPHER +#endif + +#ifdef WXSQLITE3_HAVE_CIPHER_RC4 +#define HAVE_CIPHER_RC4 WXSQLITE3_HAVE_CIPHER_RC4 +#endif + +#ifdef WXSQLITE3_HAVE_CIPHER_ASCON128 +#define HAVE_CIPHER_ASCON128 WXSQLITE3_HAVE_CIPHER_ASCON128 +#endif + +#ifdef WXSQLITE3_HAVE_CIPHER_AEGIS +#define HAVE_CIPHER_AEGIS WXSQLITE3_HAVE_CIPHER_AEGIS +#endif + +/* +** Actual definitions of supported ciphers +*/ +#ifndef HAVE_CIPHER_AES_128_CBC +#define HAVE_CIPHER_AES_128_CBC 1 +#endif + +#ifndef HAVE_CIPHER_AES_256_CBC +#define HAVE_CIPHER_AES_256_CBC 1 +#endif + +#ifndef HAVE_CIPHER_CHACHA20 +#define HAVE_CIPHER_CHACHA20 1 +#endif + +#ifndef HAVE_CIPHER_SQLCIPHER +#define HAVE_CIPHER_SQLCIPHER 1 +#endif + +#ifndef HAVE_CIPHER_RC4 +#define HAVE_CIPHER_RC4 1 +#endif + +#ifndef HAVE_CIPHER_ASCON128 +#define HAVE_CIPHER_ASCON128 1 +#endif + +/* +** Disable AEGIS cipher scheme for MSVC 2015 and below +** MSVC versions below MSVC 2017 can't compile the AEGIS cipher code +** due to not supporting to pass aligned parameters by value +*/ +#if defined(_MSC_VER) && _MSC_VER < 1910 +#ifdef HAVE_CIPHER_AEGIS +#undef HAVE_CIPHER_AEGIS +#endif +#define HAVE_CIPHER_AEGIS 0 +#endif + +#ifndef HAVE_CIPHER_AEGIS +#define HAVE_CIPHER_AEGIS 1 +#endif + +/* +** Define whether dynamic ciphers will be used +*/ + +#ifndef SQLITE3MC_HAVE_DYNAMIC_CIPHERS +#define SQLITE3MC_HAVE_DYNAMIC_CIPHERS 0 +#endif + +/* +** Disable all built-in ciphers on request +*/ + +#if 0 +#define SQLITE3MC_OMIT_BUILTIN_CIPHERS +#endif + +#ifdef SQLITE3MC_OMIT_BUILTIN_CIPHERS +#undef HAVE_CIPHER_AES_128_CBC +#undef HAVE_CIPHER_AES_256_CBC +#undef HAVE_CIPHER_CHACHA20 +#undef HAVE_CIPHER_SQLCIPHER +#undef HAVE_CIPHER_RC4 +#undef HAVE_CIPHER_ASCON128 +#undef HAVE_CIPHER_AEGIS +#define HAVE_CIPHER_AES_128_CBC 0 +#define HAVE_CIPHER_AES_256_CBC 0 +#define HAVE_CIPHER_CHACHA20 0 +#define HAVE_CIPHER_SQLCIPHER 0 +#define HAVE_CIPHER_RC4 0 +#define HAVE_CIPHER_ASCON128 0 +#define HAVE_CIPHER_AEGIS 0 +#endif + +/* +** Check that at least one cipher is be supported +*/ +#if SQLITE3MC_HAVE_DYNAMIC_CIPHERS == 0 && \ + HAVE_CIPHER_AES_128_CBC == 0 && \ + HAVE_CIPHER_AES_256_CBC == 0 && \ + HAVE_CIPHER_CHACHA20 == 0 && \ + HAVE_CIPHER_SQLCIPHER == 0 && \ + HAVE_CIPHER_RC4 == 0 && \ + HAVE_CIPHER_ASCON128 == 0 && \ + HAVE_CIPHER_AEGIS == 0 +#pragma message ("sqlite3mc_config.h: WARNING - No built-in cipher scheme enabled!") +#endif + +/* +** Compile-time configuration +*/ + +/* +** Selection of default cipher scheme +** +** A specific default cipher scheme can be selected by defining +** the symbol CODEC_TYPE using one of the cipher scheme values +** CODEC_TYPE_AES128, CODEC_TYPE_AES256, CODEC_TYPE_CHACHA20, +** CODEC_TYPE_SQLCIPHER, or CODEC_TYPE_RC4. +** +** If the symbol CODEC_TYPE is not defined, CODEC_TYPE_CHACHA20 +** is selected as the default cipher scheme. +*/ +#if 0 +#define CODEC_TYPE CODEC_TYPE_CHACHA20 +#endif + +/* +** Selection of legacy mode +** +** A) CODEC_TYPE_AES128 and CODEC_TYPE_AES256 +** Defining the symbol WXSQLITE3_USE_OLD_ENCRYPTION_SCHEME +** selects the legacy mode for both cipher schemes. +** +** B) CODEC_TYPE_CHACHA20 +** Defining the symbol SQLITE3MC_USE_SQLEET_LEGACY +** selects the legacy mode. +** +** C) CODEC_TYPE_SQLCIPHER +** Defining the symbol SQLITE3MC_USE_SQLEET_LEGACY +** selects the legacy mode. +** +** D) CODEC_TYPE_RC4 +** This cipher scheme is available in legacy mode only. +*/ + +#if 0 +#define WXSQLITE3_USE_OLD_ENCRYPTION_SCHEME +#endif + +#if 0 +#define SQLITE3MC_USE_SQLEET_LEGACY +#endif + +#if 0 +#define SQLITE3MC_USE_SQLCIPHER_LEGACY +#endif + +/* +** Selection of default version for SQLCipher scheme +** +** A specific default version can be selected by defining +** the symbol SQLCIPHER_VERSION_DEFAULT using one of the +** supported version values (SQLCIPHER_VERSION_1, +** SQLCIPHER_VERSION_2, SQLCIPHER_VERSION_3, SQLCIPHER_VERSION_4). +** +** If the symbol SQLCIPHER_VERSION_DEFAULT is not defined, +** version 4 (SQLCIPHER_VERSION_4) is selected as the default value. +*/ + +#if 0 +#define SQLCIPHER_VERSION_DEFAULT SQLCIPHER_VERSION_4 +#endif + +#endif +/*** End of #include "sqlite3mc_config.h" ***/ + +/* #include "sqlite3mc.h" */ +/*** Begin of #include "sqlite3mc.h" ***/ +/* +** Name: sqlite3mc.h +** Purpose: Header file for SQLite3 Multiple Ciphers support +** Author: Ulrich Telle +** Created: 2020-03-01 +** Copyright: (c) 2019-2024 Ulrich Telle +** License: MIT +*/ + +#ifndef SQLITE3MC_H_ +#define SQLITE3MC_H_ + +/* +** Define SQLite3 Multiple Ciphers version information +*/ +/* #include "sqlite3mc_version.h" */ +/*** Begin of #include "sqlite3mc_version.h" ***/ +/* +** Name: sqlite3mc_version.h +** Purpose: SQLite3 Multiple Ciphers version numbers +** Author: Ulrich Telle +** Created: 2020-08-05 +** Copyright: (c) 2020-2025 Ulrich Telle +** License: MIT +*/ + +/// \file sqlite3mc_version.h Version information for the SQLite3 Multiple Ciphers library + +#ifndef SQLITE3MC_VERSION_H_ +#define SQLITE3MC_VERSION_H_ + +#define SQLITE3MC_VERSION_MAJOR 2 +#define SQLITE3MC_VERSION_MINOR 1 +#define SQLITE3MC_VERSION_RELEASE 3 +#define SQLITE3MC_VERSION_SUBRELEASE 0 +#define SQLITE3MC_VERSION_STRING "SQLite3 Multiple Ciphers 2.1.3" + +#endif /* SQLITE3MC_VERSION_H_ */ +/*** End of #include "sqlite3mc_version.h" ***/ + + +/* +** Define SQLite3 API +*/ +/* #include "sqlite3.h" */ +/*** Begin of #include "sqlite3.h" ***/ +/* +** 2001-09-15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve the right to make minor changes +** if experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are supposed to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +*/ +#ifndef SQLITE3_H +#define SQLITE3_H +#include /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +extern "C" { +#endif + + +/* +** Facilitate override of interface linkage and calling conventions. +** Be aware that these macros may not be used within this particular +** translation of the amalgamation and its associated header file. +** +** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the +** compiler that the target identifier should have external linkage. +** +** The SQLITE_CDECL macro is used to set the calling convention for +** public functions that accept a variable number of arguments. +** +** The SQLITE_APICALL macro is used to set the calling convention for +** public functions that accept a fixed number of arguments. +** +** The SQLITE_STDCALL macro is no longer used and is now deprecated. +** +** The SQLITE_CALLBACK macro is used to set the calling convention for +** function pointers. +** +** The SQLITE_SYSAPI macro is used to set the calling convention for +** functions provided by the operating system. +** +** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and +** SQLITE_SYSAPI macros are used only when building for environments +** that require non-default calling conventions. +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif +#ifndef SQLITE_API +# define SQLITE_API +#endif +#ifndef SQLITE_CDECL +# define SQLITE_CDECL +#endif +#ifndef SQLITE_APICALL +# define SQLITE_APICALL +#endif +#ifndef SQLITE_STDCALL +# define SQLITE_STDCALL SQLITE_APICALL +#endif +#ifndef SQLITE_CALLBACK +# define SQLITE_CALLBACK +#endif +#ifndef SQLITE_SYSAPI +# define SQLITE_SYSAPI +#endif + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are supported for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since [version 3.6.18] ([dateof:3.6.18]), +** SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and a SHA1 +** or SHA3-256 hash of the entire source tree. If the source code has +** been edited in any way since it was last checked in, then the last +** four hexadecimal digits of the hash may be modified. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "3.50.1" +#define SQLITE_VERSION_NUMBER 3050001 +#define SQLITE_SOURCE_ID "2025-06-06 14:52:32 b77dc5e0f596d2140d9ac682b2893ff65d3a4140aa86067a3efebe29dc914c95" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus ensure that the application is +** compiled with matching library and header files. +** +**
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** 
)^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built +** using an edited copy of [the amalgamation], then the last four characters +** of the hash might be different from [SQLITE_SOURCE_ID].)^ +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; +SQLITE_API const char *sqlite3_libversion(void); +SQLITE_API const char *sqlite3_sourceid(void); +SQLITE_API int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_API int sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *sqlite3_compileoption_get(int N); +#else +# define sqlite3_compileoption_used(X) 0 +# define sqlite3_compileoption_get(X) ((void*)0) +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled with mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +SQLITE_API int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** and [sqlite3_close_v2()] are its destructors. There are many other +** interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; +# ifdef SQLITE_UINT64_TYPE + typedef SQLITE_UINT64_TYPE sqlite_uint64; +# else + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +# endif +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** DESTRUCTOR: sqlite3 +** +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors +** for the [sqlite3] object. +** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if +** the [sqlite3] object is successfully destroyed and all associated +** resources are deallocated. +** +** Ideally, applications should [sqlite3_finalize | finalize] all +** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated +** with the [sqlite3] object prior to attempting to close the object. +** ^If the database connection is associated with unfinalized prepared +** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then +** sqlite3_close() will leave the database connection open and return +** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared +** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups, +** it returns [SQLITE_OK] regardless, but instead of deallocating the database +** connection immediately, it marks the database connection as an unusable +** "zombie" and makes arrangements to automatically deallocate the database +** connection after all prepared statements are finalized, all BLOB handles +** are closed, and all backups have finished. The sqlite3_close_v2() interface +** is intended for use with host languages that are garbage collected, and +** where the order in which destructors are called is arbitrary. +** +** ^If an [sqlite3] object is destroyed while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** argument is a harmless no-op. +*/ +SQLITE_API int sqlite3_close(sqlite3*); +SQLITE_API int sqlite3_close_v2(sqlite3*); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** METHOD: sqlite3 +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
    +**
  • The application must ensure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
  • The application must not close the [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not dereference the arrays or string pointers +** passed as the 3rd and 4th callback parameters after it returns. +**
+*/ +SQLITE_API int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: {result code definitions} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicate success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [extended result code definitions] +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* Generic error */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Internal use only */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Not used */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ +#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended result code definitions} +** +** In its default configuration, SQLite API routines return one of 30 integer +** [result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8] +** and later) include +** support for additional result codes that provide more detailed information +** about errors. These [extended result codes] are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. Or, the extended code for +** the most recent error can be obtained using +** [sqlite3_extended_errcode()]. +*/ +#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8)) +#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8)) +#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8)) +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) +#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) +#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) +#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) +#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) +#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) +#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) +#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) +#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8)) +#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8)) +#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8)) +#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8)) +#define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8)) +#define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) +#define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) +#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) +#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) +#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) +#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */ +#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8)) +#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8)) +#define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8)) +#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) +#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) +#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) +#define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) +#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8)) +#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8)) +#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) +#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) +#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) +#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) +#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) +#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) +#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) +#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) +#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) +#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) +#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) +#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8)) +#define SQLITE_CONSTRAINT_DATATYPE (SQLITE_CONSTRAINT |(12<<8)) +#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) +#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) +#define SQLITE_NOTICE_RBU (SQLITE_NOTICE | (3<<8)) +#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) +#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) +#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) +#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal use only */ + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +** +** Only those flags marked as "Ok for sqlite3_open_v2()" may be +** used as the third argument to the [sqlite3_open_v2()] interface. +** The other flags have historically been ignored by sqlite3_open_v2(), +** though future versions of SQLite might change so that an error is +** raised if any of the disallowed bits are passed into sqlite3_open_v2(). +** Applications should not depend on the historical behavior. +** +** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into +** [sqlite3_open_v2()] does *not* cause the underlying database file +** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into +** [sqlite3_open_v2()] has historically be a no-op and might become an +** error in future versions of SQLite. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_SUPER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ +#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_EXRESCODE 0x02000000 /* Extended result codes */ + +/* Reserved: 0x00F00000 */ +/* Legacy compatibility: */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ + + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that +** after reboot following a crash or power loss, the only bytes in a +** file that were written at the application level might have changed +** and that adjacent bytes, even bytes within the same sector are +** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN +** flag indicates that a file cannot be deleted when open. The +** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on +** read-only media and cannot be changed even by processes with +** elevated privileges. +** +** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying +** filesystem supports doing multiple write operations atomically when those +** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and +** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. +** +** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read +** from the database file in amounts that are not a multiple of the +** page size and that do not begin at a page boundary. Without this +** property, SQLite is careful to only do full-page reads and write +** on aligned pages, with the one exception that it will do a sub-page +** read of the first page to access the database header. +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 +#define SQLITE_IOCAP_IMMUTABLE 0x00002000 +#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000 +#define SQLITE_IOCAP_SUBPAGE_READ 0x00008000 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. These values are ordered from +** lest restrictive to most restrictive. +** +** The argument to xLock() is always SHARED or higher. The argument to +** xUnlock is either SHARED or NONE. +*/ +#define SQLITE_LOCK_NONE 0 /* xUnlock() only */ +#define SQLITE_LOCK_SHARED 1 /* xLock() or xUnlock() */ +#define SQLITE_LOCK_RESERVED 2 /* xLock() only */ +#define SQLITE_LOCK_PENDING 3 /* xLock() only */ +#define SQLITE_LOCK_EXCLUSIVE 4 /* xLock() only */ + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs.xOpen] method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
    +**
  • [SQLITE_LOCK_NONE], +**
  • [SQLITE_LOCK_SHARED], +**
  • [SQLITE_LOCK_RESERVED], +**
  • [SQLITE_LOCK_PENDING], or +**
  • [SQLITE_LOCK_EXCLUSIVE]. +**
+** xLock() upgrades the database file lock. In other words, xLock() moves the +** database file lock in the direction NONE toward EXCLUSIVE. The argument to +** xLock() is always one of SHARED, RESERVED, PENDING, or EXCLUSIVE, never +** SQLITE_LOCK_NONE. If the database file lock is already at or above the +** requested lock, then the call to xLock() is a no-op. +** xUnlock() downgrades the database file lock to either SHARED or NONE. +** If the lock is already at or below the requested lock state, then the call +** to xUnlock() is a no-op. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns, via its output +** pointer parameter, true if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [file control opcodes | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
    +**
  • [SQLITE_IOCAP_ATOMIC] +**
  • [SQLITE_IOCAP_ATOMIC512] +**
  • [SQLITE_IOCAP_ATOMIC1K] +**
  • [SQLITE_IOCAP_ATOMIC2K] +**
  • [SQLITE_IOCAP_ATOMIC4K] +**
  • [SQLITE_IOCAP_ATOMIC8K] +**
  • [SQLITE_IOCAP_ATOMIC16K] +**
  • [SQLITE_IOCAP_ATOMIC32K] +**
  • [SQLITE_IOCAP_ATOMIC64K] +**
  • [SQLITE_IOCAP_SAFE_APPEND] +**
  • [SQLITE_IOCAP_SEQUENTIAL] +**
  • [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] +**
  • [SQLITE_IOCAP_POWERSAFE_OVERWRITE] +**
  • [SQLITE_IOCAP_IMMUTABLE] +**
  • [SQLITE_IOCAP_BATCH_ATOMIC] +**
  • [SQLITE_IOCAP_SUBPAGE_READ] +**
+** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); + int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); + /* Methods above are valid for version 3 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** KEYWORDS: {file control opcodes} {file control opcode} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +**
    +**
  • [[SQLITE_FCNTL_LOCKSTATE]] +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. +** This capability is only available if SQLite is compiled with [SQLITE_DEBUG]. +** +**
  • [[SQLITE_FCNTL_SIZE_HINT]] +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +**
  • [[SQLITE_FCNTL_SIZE_LIMIT]] +** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that +** implements [sqlite3_deserialize()] to set an upper bound on the size +** of the in-memory database. The argument is a pointer to a [sqlite3_int64]. +** If the integer pointed to is negative, then it is filled in with the +** current limit. Otherwise the limit is set to the larger of the value +** of the integer pointed to and the current database size. The integer +** pointed to is set to the new limit. +** +**
  • [[SQLITE_FCNTL_CHUNK_SIZE]] +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +**
  • [[SQLITE_FCNTL_FILE_POINTER]] +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. +** +**
  • [[SQLITE_FCNTL_JOURNAL_POINTER]] +** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with the journal file (either +** the [rollback journal] or the [write-ahead log]) for a particular database +** connection. See also [SQLITE_FCNTL_FILE_POINTER]. +** +**
  • [[SQLITE_FCNTL_SYNC_OMITTED]] +** No longer in use. +** +**
  • [[SQLITE_FCNTL_SYNC]] +** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and +** sent to the VFS immediately before the xSync method is invoked on a +** database file descriptor. Or, if the xSync method is not invoked +** because the user has configured SQLite with +** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place +** of the xSync method. In most cases, the pointer argument passed with +** this file-control is NULL. However, if the database file is being synced +** as part of a multi-database commit, the argument points to a nul-terminated +** string containing the transactions super-journal file name. VFSes that +** do not need this signal should silently ignore this opcode. Applications +** should not call [sqlite3_file_control()] with this opcode as doing so may +** disrupt the operation of the specialized VFSes that do require it. +** +**
  • [[SQLITE_FCNTL_COMMIT_PHASETWO]] +** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite +** and sent to the VFS after a transaction has been committed immediately +** but before the database is unlocked. VFSes that do not need this signal +** should silently ignore this opcode. Applications should not call +** [sqlite3_file_control()] with this opcode as doing so may disrupt the +** operation of the specialized VFSes that do require it. +** +**
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic +** retry counts and intervals for certain disk I/O operations for the +** windows [VFS] in order to provide robustness in the presence of +** anti-virus programs. By default, the windows VFS will retry file read, +** file write, and file delete operations up to 10 times, with a delay +** of 25 milliseconds before the first retry and with the delay increasing +** by an additional 25 milliseconds with each subsequent retry. This +** opcode allows these two values (10 retries and 25 milliseconds of delay) +** to be adjusted. The values are changed for all database connections +** within the same process. The argument is a pointer to an array of two +** integers where the first integer is the new retry count and the second +** integer is the delay. If either integer is negative, then the setting +** is not changed but instead the prior value of that setting is written +** into the array entry, allowing the current retry settings to be +** interrogated. The zDbName parameter is ignored. +** +**
  • [[SQLITE_FCNTL_PERSIST_WAL]] +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the +** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary +** write ahead log ([WAL file]) and shared memory +** files used for transaction control +** are automatically deleted when the latest connection to the database +** closes. Setting persistent WAL mode causes those files to persist after +** close. Persisting the files is useful when other processes that do not +** have write permission on the directory containing the database file want +** to read the database file, as the WAL and shared memory files must exist +** in order for the database to be readable. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent +** WAL mode. If the integer is -1, then it is overwritten with the current +** WAL persistence setting. +** +**
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the +** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the +** xDeviceCharacteristics methods. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage +** mode. If the integer is -1, then it is overwritten with the current +** zero-damage mode setting. +** +**
  • [[SQLITE_FCNTL_OVERWRITE]] +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening +** a write transaction to indicate that, unless it is rolled back for some +** reason, the entire database file will be overwritten by the current +** transaction. This is used by VACUUM operations. +** +**
  • [[SQLITE_FCNTL_VFSNAME]] +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of +** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** final bottom-level VFS are written into memory obtained from +** [sqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [sqlite3_file_control()] points to. +** The caller is responsible for freeing the memory when done. As with +** all file-control actions, there is no guarantee that this will actually +** do anything. Callers should initialize the char* variable to a NULL +** pointer in case this file-control is not implemented. This file-control +** is intended for diagnostic use only. +** +**
  • [[SQLITE_FCNTL_VFS_POINTER]] +** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level +** [VFSes] currently in use. ^(The argument X in +** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be +** of type "[sqlite3_vfs] **". This opcodes will set *X +** to a pointer to the top-level VFS.)^ +** ^When there are multiple VFS shims in the stack, this opcode finds the +** upper-most shim only. +** +**
  • [[SQLITE_FCNTL_PRAGMA]] +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] +** file control is sent to the open [sqlite3_file] object corresponding +** to the database file to which the pragma statement refers. ^The argument +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of +** pointers to strings (char**) in which the second element of the array +** is the name of the pragma and the third element is the argument to the +** pragma or NULL if the pragma has no argument. ^The handler for an +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element +** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** or the equivalent and that string will become the result of the pragma or +** the error message if the pragma fails. ^If the +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal +** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] +** file control returns [SQLITE_OK], then the parser assumes that the +** VFS has handled the PRAGMA itself and the parser generates a no-op +** prepared statement if result string is NULL, or that returns a copy +** of the result string if the string is non-NULL. +** ^If the [SQLITE_FCNTL_PRAGMA] file control returns +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means +** that the VFS encountered an error while handling the [PRAGMA] and the +** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] +** file control occurs at the beginning of pragma statement analysis and so +** it is able to override built-in [PRAGMA] statements. +** +**
  • [[SQLITE_FCNTL_BUSYHANDLER]] +** ^The [SQLITE_FCNTL_BUSYHANDLER] +** file-control may be invoked by SQLite on the database file handle +** shortly after it is opened in order to provide a custom VFS with access +** to the connection's busy-handler callback. The argument is of type (void**) +** - an array of two (void *) values. The first (void *) actually points +** to a function of type (int (*)(void *)). In order to invoke the connection's +** busy-handler, this function should be invoked with the second (void *) in +** the array as the only argument. If it returns non-zero, then the operation +** should be retried. If it returns zero, the custom VFS should abandon the +** current operation. +** +**
  • [[SQLITE_FCNTL_TEMPFILENAME]] +** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control +** to have SQLite generate a +** temporary filename using the same algorithm that is followed to generate +** temporary filenames for TEMP tables and other internal uses. The +** argument should be a char** which will be filled with the filename +** written into memory obtained from [sqlite3_malloc()]. The caller should +** invoke [sqlite3_free()] on the result to avoid a memory leak. +** +**
  • [[SQLITE_FCNTL_MMAP_SIZE]] +** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the +** maximum number of bytes that will be used for memory-mapped I/O. +** The argument is a pointer to a value of type sqlite3_int64 that +** is an advisory maximum number of bytes in the file to memory map. The +** pointer is overwritten with the old value. The limit is not changed if +** the value originally pointed to is negative, and so the current limit +** can be queried by passing in a pointer to a negative number. This +** file-control is used internally to implement [PRAGMA mmap_size]. +** +**
  • [[SQLITE_FCNTL_TRACE]] +** The [SQLITE_FCNTL_TRACE] file control provides advisory information +** to the VFS about what the higher layers of the SQLite stack are doing. +** This file control is used by some VFS activity tracing [shims]. +** The argument is a zero-terminated string. Higher layers in the +** SQLite stack may generate instances of this file control if +** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled. +** +**
  • [[SQLITE_FCNTL_HAS_MOVED]] +** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a +** pointer to an integer and it writes a boolean into that integer depending +** on whether or not the file has been renamed, moved, or deleted since it +** was first opened. +** +**
  • [[SQLITE_FCNTL_WIN32_GET_HANDLE]] +** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the +** underlying native file handle associated with a file handle. This file +** control interprets its argument as a pointer to a native file handle and +** writes the resulting value there. +** +**
  • [[SQLITE_FCNTL_WIN32_SET_HANDLE]] +** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This +** opcode causes the xFileControl method to swap the file handle with the one +** pointed to by the pArg argument. This capability is used during testing +** and only needs to be supported when SQLITE_TEST is defined. +** +**
  • [[SQLITE_FCNTL_NULL_IO]] +** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor +** or file handle for the [sqlite3_file] object such that it will no longer +** read or write to the database file. +** +**
  • [[SQLITE_FCNTL_WAL_BLOCK]] +** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might +** be advantageous to block on the next WAL lock if the lock is not immediately +** available. The WAL subsystem issues this signal during rare +** circumstances in order to fix a problem with priority inversion. +** Applications should not use this file-control. +** +**
  • [[SQLITE_FCNTL_ZIPVFS]] +** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other +** VFS should return SQLITE_NOTFOUND for this opcode. +** +**
  • [[SQLITE_FCNTL_RBU]] +** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by +** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for +** this opcode. +** +**
  • [[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]] +** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then +** the file descriptor is placed in "batch write mode", which +** means all subsequent write operations will be deferred and done +** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems +** that do not support batch atomic writes will return SQLITE_NOTFOUND. +** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to +** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or +** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make +** no VFS interface calls on the same [sqlite3_file] file descriptor +** except for calls to the xWrite method and the xFileControl method +** with [SQLITE_FCNTL_SIZE_HINT]. +** +**
  • [[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]] +** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write +** operations since the previous successful call to +** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically. +** This file control returns [SQLITE_OK] if and only if the writes were +** all performed successfully and have been committed to persistent storage. +** ^Regardless of whether or not it is successful, this file control takes +** the file descriptor out of batch write mode so that all subsequent +** write operations are independent. +** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without +** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. +** +**
  • [[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]] +** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write +** operations since the previous successful call to +** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back. +** ^This file control takes the file descriptor out of batch write mode +** so that all subsequent write operations are independent. +** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without +** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. +** +**
  • [[SQLITE_FCNTL_LOCK_TIMEOUT]] +** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS +** to block for up to M milliseconds before failing when attempting to +** obtain a file lock using the xLock or xShmLock methods of the VFS. +** The parameter is a pointer to a 32-bit signed integer that contains +** the value that M is to be set to. Before returning, the 32-bit signed +** integer is overwritten with the previous value of M. +** +**
  • [[SQLITE_FCNTL_BLOCK_ON_CONNECT]] +** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the +** VFS to block when taking a SHARED lock to connect to a wal mode database. +** This is used to implement the functionality associated with +** SQLITE_SETLK_BLOCK_ON_CONNECT. +** +**
  • [[SQLITE_FCNTL_DATA_VERSION]] +** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to +** a database file. The argument is a pointer to a 32-bit unsigned integer. +** The "data version" for the pager is written into the pointer. The +** "data version" changes whenever any change occurs to the corresponding +** database file, either through SQL statements on the same database +** connection or through transactions committed by separate database +** connections possibly in other processes. The [sqlite3_total_changes()] +** interface can be used to find if any database on the connection has changed, +** but that interface responds to changes on TEMP as well as MAIN and does +** not provide a mechanism to detect changes to MAIN only. Also, the +** [sqlite3_total_changes()] interface responds to internal changes only and +** omits changes made by other database connections. The +** [PRAGMA data_version] command provides a mechanism to detect changes to +** a single attached database that occur due to other database connections, +** but omits changes implemented by the database connection on which it is +** called. This file control is the only mechanism to detect changes that +** happen either internally or externally and that are associated with +** a particular attached database. +** +**
  • [[SQLITE_FCNTL_CKPT_START]] +** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint +** in wal mode before the client starts to copy pages from the wal +** file to the database file. +** +**
  • [[SQLITE_FCNTL_CKPT_DONE]] +** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint +** in wal mode after the client has finished copying pages from the wal +** file to the database file, but before the *-shm file is updated to +** record the fact that the pages have been checkpointed. +** +**
  • [[SQLITE_FCNTL_EXTERNAL_READER]] +** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect +** whether or not there is a database client in another process with a wal-mode +** transaction open on the database or not. It is only available on unix.The +** (void*) argument passed with this file-control should be a pointer to a +** value of type (int). The integer value is set to 1 if the database is a wal +** mode database and there exists at least one client in another process that +** currently has an SQL transaction open on the database. It is set to 0 if +** the database is not a wal-mode db, or if there is no such connection in any +** other process. This opcode cannot be used to detect transactions opened +** by clients within the current process, only within other processes. +** +**
  • [[SQLITE_FCNTL_CKSM_FILE]] +** The [SQLITE_FCNTL_CKSM_FILE] opcode is for use internally by the +** [checksum VFS shim] only. +** +**
  • [[SQLITE_FCNTL_RESET_CACHE]] +** If there is currently no transaction open on the database, and the +** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control +** purges the contents of the in-memory page cache. If there is an open +** transaction, or if the db is a temp-db, this opcode is a no-op, not an error. +**
+*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2 +#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3 +#define SQLITE_FCNTL_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 +#define SQLITE_FCNTL_WIN32_AV_RETRY 9 +#define SQLITE_FCNTL_PERSIST_WAL 10 +#define SQLITE_FCNTL_OVERWRITE 11 +#define SQLITE_FCNTL_VFSNAME 12 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 +#define SQLITE_FCNTL_PRAGMA 14 +#define SQLITE_FCNTL_BUSYHANDLER 15 +#define SQLITE_FCNTL_TEMPFILENAME 16 +#define SQLITE_FCNTL_MMAP_SIZE 18 +#define SQLITE_FCNTL_TRACE 19 +#define SQLITE_FCNTL_HAS_MOVED 20 +#define SQLITE_FCNTL_SYNC 21 +#define SQLITE_FCNTL_COMMIT_PHASETWO 22 +#define SQLITE_FCNTL_WIN32_SET_HANDLE 23 +#define SQLITE_FCNTL_WAL_BLOCK 24 +#define SQLITE_FCNTL_ZIPVFS 25 +#define SQLITE_FCNTL_RBU 26 +#define SQLITE_FCNTL_VFS_POINTER 27 +#define SQLITE_FCNTL_JOURNAL_POINTER 28 +#define SQLITE_FCNTL_WIN32_GET_HANDLE 29 +#define SQLITE_FCNTL_PDB 30 +#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31 +#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32 +#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33 +#define SQLITE_FCNTL_LOCK_TIMEOUT 34 +#define SQLITE_FCNTL_DATA_VERSION 35 +#define SQLITE_FCNTL_SIZE_LIMIT 36 +#define SQLITE_FCNTL_CKPT_DONE 37 +#define SQLITE_FCNTL_RESERVE_BYTES 38 +#define SQLITE_FCNTL_CKPT_START 39 +#define SQLITE_FCNTL_EXTERNAL_READER 40 +#define SQLITE_FCNTL_CKSM_FILE 41 +#define SQLITE_FCNTL_RESET_CACHE 42 +#define SQLITE_FCNTL_NULL_IO 43 +#define SQLITE_FCNTL_BLOCK_ON_CONNECT 44 + +/* deprecated names */ +#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE +#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE +#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO + + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: Loadable Extension Thunk +** +** A pointer to the opaque sqlite3_api_routines structure is passed as +** the third parameter to entry points of [loadable extensions]. This +** structure must be typedefed in order to work around compiler warnings +** on some platforms. +*/ +typedef struct sqlite3_api_routines sqlite3_api_routines; + +/* +** CAPI3REF: File Name +** +** Type [sqlite3_filename] is used by SQLite to pass filenames to the +** xOpen method of a [VFS]. It may be cast to (const char*) and treated +** as a normal, nul-terminated, UTF-8 buffer containing the filename, but +** may also be passed to special APIs such as: +** +**
    +**
  • sqlite3_filename_database() +**
  • sqlite3_filename_journal() +**
  • sqlite3_filename_wal() +**
  • sqlite3_uri_parameter() +**
  • sqlite3_uri_boolean() +**
  • sqlite3_uri_int64() +**
  • sqlite3_uri_key() +**
+*/ +typedef const char *sqlite3_filename; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". See +** the [VFS | VFS documentation] for further information. +** +** The VFS interface is sometimes extended by adding new methods onto +** the end. Each time such an extension occurs, the iVersion field +** is incremented. The iVersion value started out as 1 in +** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2 +** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased +** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields +** may be appended to the sqlite3_vfs object and the iVersion value +** may increase again in future versions of SQLite. +** Note that due to an oversight, the structure +** of the sqlite3_vfs object changed in the transition from +** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0] +** and yet the iVersion field was not increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** [[sqlite3_vfs.xOpen]] +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 11 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
    +**
  • [SQLITE_OPEN_MAIN_DB] +**
  • [SQLITE_OPEN_MAIN_JOURNAL] +**
  • [SQLITE_OPEN_TEMP_DB] +**
  • [SQLITE_OPEN_TEMP_JOURNAL] +**
  • [SQLITE_OPEN_TRANSIENT_DB] +**
  • [SQLITE_OPEN_SUBJOURNAL] +**
  • [SQLITE_OPEN_SUPER_JOURNAL] +**
  • [SQLITE_OPEN_WAL] +**
)^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
    +**
  • [SQLITE_OPEN_DELETEONCLOSE] +**
  • [SQLITE_OPEN_EXCLUSIVE] +**
+** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** [[sqlite3_vfs.xAccess]] +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The SQLITE_ACCESS_READ +** flag is never actually used and is not implemented in the built-in +** VFSes of SQLite. The file is named by the second argument and can be a +** directory. The xAccess method returns [SQLITE_OK] on success or some +** non-zero error code if there is an I/O error or if the name of +** the file given in the second argument is illegal. If SQLITE_OK +** is returned, then non-zero or zero is written into *pResOut to indicate +** whether or not the file is accessible. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multiplied by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +** +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** are not used by the SQLite core. These optional interfaces are provided +** by some VFSes to facilitate testing of the VFS code. By overriding +** system calls with functions under its control, a test program can +** simulate faults and error conditions that would otherwise be difficult +** or impossible to induce. The set of system calls that can be overridden +** varies from one VFS to another, and from one version of the same VFS to the +** next. Applications that use these interfaces must be prepared for any +** or all of these interfaces to be NULL or for their behavior to change +** from one release to the next. Applications must not attempt to access +** any of these methods if the iVersion of the VFS is less than 3. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +typedef void (*sqlite3_syscall_ptr)(void); +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 3) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, sqlite3_filename zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); + sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in future versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
    +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
+** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given on the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +SQLITE_API int sqlite3_initialize(void); +SQLITE_API int sqlite3_shutdown(void); +SQLITE_API int sqlite3_os_init(void); +SQLITE_API int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must ensure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. +** +** The first argument to sqlite3_config() is an integer +** [configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [configuration option] +** in the first argument. +** +** For most configuration options, the sqlite3_config() interface +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** The exceptional configuration options that may be invoked at any time +** are called "anytime configuration options". +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] with a first argument that is not an anytime +** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +SQLITE_API int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** METHOD: sqlite3 +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). +** +** The second argument to sqlite3_db_config(D,V,...) is the +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code +** that indicates what aspect of the [database connection] is being configured. +** Subsequent arguments vary depending on the configuration verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc, xRealloc, and xFree methods must work like the +** malloc(), realloc() and free() functions from the standard C library. +** ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. For example, +** it might allocate any required mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** KEYWORDS: {configuration option} +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** Most of the configuration options for sqlite3_config() +** will only work if invoked prior to [sqlite3_initialize()] or after +** [sqlite3_shutdown()]. The few exceptions to this rule are called +** "anytime configuration options". +** ^Calling [sqlite3_config()] with a first argument that is not an +** anytime configuration option in between calls to [sqlite3_initialize()] and +** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE. +** +** The set of anytime configuration options can change (by insertions +** and/or deletions) from one release of SQLite to the next. +** As of SQLite version 3.42.0, the complete set of anytime configuration +** options is: +**
    +**
  • SQLITE_CONFIG_LOG +**
  • SQLITE_CONFIG_PCACHE_HDRSZ +**
+** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
+** +** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
+** +** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
+** +** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
+**
^(The SQLITE_CONFIG_MALLOC option takes a single argument which is +** a pointer to an instance of the [sqlite3_mem_methods] structure. +** The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
+** +** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
+**
^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which +** is a pointer to an instance of the [sqlite3_mem_methods] structure. +** The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
+** +** [[SQLITE_CONFIG_SMALL_MALLOC]]
SQLITE_CONFIG_SMALL_MALLOC
+**
^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of +** type int, interpreted as a boolean, which if true provides a hint to +** SQLite that it should avoid large memory allocations if possible. +** SQLite will run faster if it is free to make large memory allocations, +** but some application might prefer to run slower in exchange for +** guarantees about memory fragmentation that are possible if large +** allocations are avoided. This hint is normally off. +**
+** +** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
+**
^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, +** interpreted as a boolean, which enables or disables the collection of +** memory allocation statistics. ^(When memory allocation statistics are +** disabled, the following SQLite interfaces become non-operational: +**
    +**
  • [sqlite3_hard_heap_limit64()] +**
  • [sqlite3_memory_used()] +**
  • [sqlite3_memory_highwater()] +**
  • [sqlite3_soft_heap_limit64()] +**
  • [sqlite3_status64()] +**
)^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
+** +** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
+**
The SQLITE_CONFIG_SCRATCH option is no longer used. +**
+** +** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
+**
^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool +** that SQLite can use for the database page cache with the default page +** cache implementation. +** This configuration option is a no-op if an application-defined page +** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. +** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to +** 8-byte aligned memory (pMem), the size of each page cache line (sz), +** and the number of cache lines (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 65536) plus some extra bytes for each +** page header. ^The number of extra bytes needed by the page header +** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. +** ^It is harmless, apart from the wasted memory, +** for the sz parameter to be larger than necessary. The pMem +** argument must be either a NULL pointer or a pointer to an 8-byte +** aligned block of memory of at least sz*N bytes, otherwise +** subsequent behavior is undefined. +** ^When pMem is not NULL, SQLite will strive to use the memory provided +** to satisfy page cache needs, falling back to [sqlite3_malloc()] if +** a page cache line is larger than sz bytes or if all of the pMem buffer +** is exhausted. +** ^If pMem is NULL and N is non-zero, then each database connection +** does an initial bulk allocation for page cache memory +** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or +** of -1024*N bytes if N is negative, . ^If additional +** page cache memory is needed beyond what is provided by the initial +** allocation, then SQLite goes to [sqlite3_malloc()] separately for each +** additional cache line.
+** +** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
+**
^The SQLITE_CONFIG_HEAP option specifies a static memory buffer +** that SQLite will use for all of its dynamic memory allocation needs +** beyond those provided for by [SQLITE_CONFIG_PAGECACHE]. +** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled +** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns +** [SQLITE_ERROR] if invoked otherwise. +** ^There are three arguments to SQLITE_CONFIG_HEAP: +** An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined. +** The minimum allocation size is capped at 2**12. Reasonable values +** for the minimum allocation size are 2**5 through 2**8.
+** +** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
+**
^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a +** pointer to an instance of the [sqlite3_mutex_methods] structure. +** The argument specifies alternative low-level mutex routines to be used +** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of +** the content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
+**
^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which +** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
+**
^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine +** the default size of [lookaside memory] on each [database connection]. +** The first argument is the +** size of each lookaside buffer slot ("sz") and the second is the number of +** slots allocated to each database connection ("cnt").)^ +** ^(SQLITE_CONFIG_LOOKASIDE sets the default lookaside size. +** The [SQLITE_DBCONFIG_LOOKASIDE] option to [sqlite3_db_config()] can +** be used to change the lookaside configuration on individual connections.)^ +** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the +** default lookaside configuration at compile-time. +**
+** +** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
+**
^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is +** a pointer to an [sqlite3_pcache_methods2] object. This object specifies +** the interface to a custom page cache implementation.)^ +** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.
+** +** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
+**
^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which +** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of +** the current page cache implementation into that object.)^
+** +** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
+**
The SQLITE_CONFIG_LOG option is used to configure the SQLite +** global [error log]. +** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
+** +** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI +**
^(The SQLITE_CONFIG_URI option takes a single argument of type int. +** If non-zero, then URI handling is globally enabled. If the parameter is zero, +** then URI handling is globally disabled.)^ ^If URI handling is globally +** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], +** [sqlite3_open16()] or +** specified as part of [ATTACH] commands are interpreted as URIs, regardless +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database +** connection is opened. ^If it is globally disabled, filenames are +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the +** database connection is opened. ^(By default, URI handling is globally +** disabled. The default value may be changed by compiling with the +** [SQLITE_USE_URI] symbol defined.)^ +** +** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
SQLITE_CONFIG_COVERING_INDEX_SCAN +**
^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer +** argument which is interpreted as a boolean in order to enable or disable +** the use of covering indices for full table scans in the query optimizer. +** ^The default setting is determined +** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" +** if that compile-time option is omitted. +** The ability to disable the use of covering indices for full table scans +** is because some incorrectly coded legacy applications might malfunction +** when the optimization is enabled. Providing the ability to +** disable the optimization allows the older, buggy application code to work +** without change even with newer versions of SQLite. +** +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] +**
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE +**
These options are obsolete and should not be used by new code. +** They are retained for backwards compatibility but are now no-ops. +**
+** +** [[SQLITE_CONFIG_SQLLOG]] +**
SQLITE_CONFIG_SQLLOG +**
This option is only available if sqlite is compiled with the +** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should +** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). +** The second should be of type (void*). The callback is invoked by the library +** in three separate circumstances, identified by the value passed as the +** fourth parameter. If the fourth parameter is 0, then the database connection +** passed as the second argument has just been opened. The third argument +** points to a buffer containing the name of the main database file. If the +** fourth parameter is 1, then the SQL statement that the third parameter +** points to has just been executed. Or, if the fourth parameter is 2, then +** the connection being passed as the second parameter is being closed. The +** third parameter is passed NULL In this case. An example of using this +** configuration option can be seen in the "test_sqllog.c" source file in +** the canonical SQLite source tree.
+** +** [[SQLITE_CONFIG_MMAP_SIZE]] +**
SQLITE_CONFIG_MMAP_SIZE +**
^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values +** that are the default mmap size limit (the default setting for +** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. +** ^The default setting can be overridden by each database connection using +** either the [PRAGMA mmap_size] command, or by using the +** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size +** will be silently truncated if necessary so that it does not exceed the +** compile-time maximum mmap size set by the +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ +** ^If either argument to this option is negative, then that argument is +** changed to its compile-time default. +** +** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] +**
SQLITE_CONFIG_WIN32_HEAPSIZE +**
^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is +** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro +** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value +** that specifies the maximum size of the created heap. +** +** [[SQLITE_CONFIG_PCACHE_HDRSZ]] +**
SQLITE_CONFIG_PCACHE_HDRSZ +**
^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which +** is a pointer to an integer and writes into that integer the number of extra +** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. +** The amount of extra space required can change depending on the compiler, +** target platform, and SQLite version. +** +** [[SQLITE_CONFIG_PMASZ]] +**
SQLITE_CONFIG_PMASZ +**
^The SQLITE_CONFIG_PMASZ option takes a single parameter which +** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded +** sorter to that integer. The default minimum PMA Size is set by the +** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched +** to help with sort operations when multithreaded sorting +** is enabled (using the [PRAGMA threads] command) and the amount of content +** to be sorted exceeds the page size times the minimum of the +** [PRAGMA cache_size] setting and this value. +** +** [[SQLITE_CONFIG_STMTJRNL_SPILL]] +**
SQLITE_CONFIG_STMTJRNL_SPILL +**
^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which +** becomes the [statement journal] spill-to-disk threshold. +** [Statement journals] are held in memory until their size (in bytes) +** exceeds this threshold, at which point they are written to disk. +** Or if the threshold is -1, statement journals are always held +** exclusively in memory. +** Since many statement journals never become large, setting the spill +** threshold to a value such as 64KiB can greatly reduce the amount of +** I/O required to support statement rollback. +** The default value for this setting is controlled by the +** [SQLITE_STMTJRNL_SPILL] compile-time option. +** +** [[SQLITE_CONFIG_SORTERREF_SIZE]] +**
SQLITE_CONFIG_SORTERREF_SIZE +**
The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter +** of type (int) - the new value of the sorter-reference size threshold. +** Usually, when SQLite uses an external sort to order records according +** to an ORDER BY clause, all fields required by the caller are present in the +** sorted records. However, if SQLite determines based on the declared type +** of a table column that its values are likely to be very large - larger +** than the configured sorter-reference size threshold - then a reference +** is stored in each sorted record and the required column values loaded +** from the database as records are returned in sorted order. The default +** value for this option is to never use this optimization. Specifying a +** negative value for this option restores the default behavior. +** This option is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option. +** +** [[SQLITE_CONFIG_MEMDB_MAXSIZE]] +**
SQLITE_CONFIG_MEMDB_MAXSIZE +**
The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter +** [sqlite3_int64] parameter which is the default maximum size for an in-memory +** database created using [sqlite3_deserialize()]. This default maximum +** size can be adjusted up or down for individual databases using the +** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this +** configuration setting is never used, then the default maximum is determined +** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that +** compile-time option is not set, then the default maximum is 1073741824. +** +** [[SQLITE_CONFIG_ROWID_IN_VIEW]] +**
SQLITE_CONFIG_ROWID_IN_VIEW +**
The SQLITE_CONFIG_ROWID_IN_VIEW option enables or disables the ability +** for VIEWs to have a ROWID. The capability can only be enabled if SQLite is +** compiled with -DSQLITE_ALLOW_ROWID_IN_VIEW, in which case the capability +** defaults to on. This configuration option queries the current setting or +** changes the setting to off or on. The argument is a pointer to an integer. +** If that integer initially holds a value of 1, then the ability for VIEWs to +** have ROWIDs is activated. If the integer initially holds zero, then the +** ability is deactivated. Any other initial value for the integer leaves the +** setting unchanged. After changes, if any, the integer is written with +** a 1 or 0, if the ability for VIEWs to have ROWIDs is on or off. If SQLite +** is compiled without -DSQLITE_ALLOW_ROWID_IN_VIEW (which is the usual and +** recommended case) then the integer is always filled with zero, regardless +** if its initial value. +**
+*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* No longer used */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* no-op */ +#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ +#define SQLITE_CONFIG_URI 17 /* int */ +#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ +#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ +#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ +#define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ +#define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ +#define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ +#define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ +#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */ +#define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */ +#define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */ +#define SQLITE_CONFIG_ROWID_IN_VIEW 30 /* int* */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second parameter to the [sqlite3_db_config()] interface. +** +** The [sqlite3_db_config()] interface is a var-args functions. It takes a +** variable number of parameters, though always at least two. The number of +** parameters passed into sqlite3_db_config() depends on which of these +** constants is given as the second parameter. This documentation page +** refers to parameters beyond the second as "arguments". Thus, when this +** page says "the N-th argument" it means "the N-th parameter past the +** configuration option" or "the (N+2)-th parameter to sqlite3_db_config()". +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+** [[SQLITE_DBCONFIG_LOOKASIDE]] +**
SQLITE_DBCONFIG_LOOKASIDE
+**
The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the +** configuration of the [lookaside memory allocator] within a database +** connection. +** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are not +** in the [DBCONFIG arguments|usual format]. +** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two, +** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE +** should have a total of five parameters. +**
    +**
  1. The first argument ("buf") is a +** pointer to a memory buffer to use for lookaside memory. +** The first argument may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. +**

  2. The second argument ("sz") is the +** size of each lookaside buffer slot. Lookaside is disabled if "sz" +** is less than 8. The "sz" argument should be a multiple of 8 less than +** 65536. If "sz" does not meet this constraint, it is reduced in size until +** it does. +**

  3. The third argument ("cnt") is the number of slots. Lookaside is disabled +** if "cnt"is less than 1. The "cnt" value will be reduced, if necessary, so +** that the product of "sz" and "cnt" does not exceed 2,147,418,112. The "cnt" +** parameter is usually chosen so that the product of "sz" and "cnt" is less +** than 1,000,000. +**

+**

If the "buf" argument is not NULL, then it must +** point to a memory buffer with a size that is greater than +** or equal to the product of "sz" and "cnt". +** The buffer must be aligned to an 8-byte boundary. +** The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the value returned by [SQLITE_DBSTATUS_LOOKASIDE_USED] is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY]. +** If the "buf" argument is NULL and an attempt +** to allocate memory based on "sz" and "cnt" fails, then +** lookaside is silently disabled. +**

+** The [SQLITE_CONFIG_LOOKASIDE] configuration option can be used to set the +** default lookaside configuration at initialization. The +** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside +** configuration at compile-time. Typical values for lookaside are 1200 for +** "sz" and 40 to 100 for "cnt". +**

+** +** [[SQLITE_DBCONFIG_ENABLE_FKEY]] +**
SQLITE_DBCONFIG_ENABLE_FKEY
+**
^This option is used to enable or disable the enforcement of +** [foreign key constraints]. This is the same setting that is +** enabled or disabled by the [PRAGMA foreign_keys] statement. +** The first argument is an integer which is 0 to disable FK enforcement, +** positive to enable FK enforcement or negative to leave FK enforcement +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether FK enforcement is off or on +** following this call. The second parameter may be a NULL pointer, in +** which case the FK enforcement setting is not reported back.
+** +** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]] +**
SQLITE_DBCONFIG_ENABLE_TRIGGER
+**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable triggers, +** positive to enable triggers or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether triggers are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the trigger setting is not reported back. +** +**

Originally this option disabled all triggers. ^(However, since +** SQLite version 3.35.0, TEMP triggers are still allowed even if +** this option is off. So, in other words, this option now only disables +** triggers in the main database schema or in the schemas of [ATTACH]-ed +** databases.)^

+** +** [[SQLITE_DBCONFIG_ENABLE_VIEW]] +**
SQLITE_DBCONFIG_ENABLE_VIEW
+**
^This option is used to enable or disable [CREATE VIEW | views]. +** There must be two additional arguments. +** The first argument is an integer which is 0 to disable views, +** positive to enable views or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether views are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the view setting is not reported back. +** +**

Originally this option disabled all views. ^(However, since +** SQLite version 3.35.0, TEMP views are still allowed even if +** this option is off. So, in other words, this option now only disables +** views in the main database schema or in the schemas of ATTACH-ed +** databases.)^

+** +** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]] +**
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
+**
^This option is used to enable or disable the +** [fts3_tokenizer()] function which is part of the +** [FTS3] full-text search engine extension. +** There must be two additional arguments. +** The first argument is an integer which is 0 to disable fts3_tokenizer() or +** positive to enable fts3_tokenizer() or negative to leave the setting +** unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the new setting is not reported back.
+** +** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]] +**
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
+**
^This option is used to enable or disable the [sqlite3_load_extension()] +** interface independently of the [load_extension()] SQL function. +** The [sqlite3_enable_load_extension()] API enables or disables both the +** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. +** There must be two additional arguments. +** When the first argument to this interface is 1, then only the C-API is +** enabled and the SQL function remains disabled. If the first argument to +** this interface is 0, then both the C-API and the SQL function are disabled. +** If the first argument is -1, then no changes are made to state of either the +** C-API or the SQL function. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface +** is disabled or enabled following this call. The second parameter may +** be a NULL pointer, in which case the new setting is not reported back. +**
+** +** [[SQLITE_DBCONFIG_MAINDBNAME]]
SQLITE_DBCONFIG_MAINDBNAME
+**
^This option is used to change the name of the "main" database +** schema. This option does not follow the +** [DBCONFIG arguments|usual SQLITE_DBCONFIG argument format]. +** This option takes exactly one additional argument so that the +** [sqlite3_db_config()] call has a total of three parameters. The +** extra argument must be a pointer to a constant UTF8 string which +** will become the new schema name in place of "main". ^SQLite does +** not make a copy of the new main schema name string, so the application +** must ensure that the argument passed into SQLITE_DBCONFIG MAINDBNAME +** is unchanged until after the database connection closes. +**
+** +** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] +**
SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
+**
Usually, when a database in [WAL mode] is closed or detached from a +** database handle, SQLite checks if if there are other connections to the +** same database, and if there are no other database connection (if the +** connection being closed is the last open connection to the database), +** then SQLite performs a [checkpoint] before closing the connection and +** deletes the WAL file. The SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE option can +** be used to override that behavior. The first argument passed to this +** operation (the third parameter to [sqlite3_db_config()]) is an integer +** which is positive to disable checkpoints-on-close, or zero (the default) +** to enable them, and negative to leave the setting unchanged. +** The second argument (the fourth parameter) is a pointer to an integer +** into which is written 0 or 1 to indicate whether checkpoints-on-close +** have been disabled - 0 if they are not disabled, 1 if they are. +**
+** +** [[SQLITE_DBCONFIG_ENABLE_QPSG]]
SQLITE_DBCONFIG_ENABLE_QPSG
+**
^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates +** the [query planner stability guarantee] (QPSG). When the QPSG is active, +** a single SQL query statement will always use the same algorithm regardless +** of values of [bound parameters].)^ The QPSG disables some query optimizations +** that look at the values of bound parameters, which can make some queries +** slower. But the QPSG has the advantage of more predictable behavior. With +** the QPSG active, SQLite will always use the same query plan in the field as +** was used during testing in the lab. +** The first argument to this setting is an integer which is 0 to disable +** the QPSG, positive to enable QPSG, or negative to leave the setting +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether the QPSG is disabled or enabled +** following this call. +**
+** +** [[SQLITE_DBCONFIG_TRIGGER_EQP]]
SQLITE_DBCONFIG_TRIGGER_EQP
+**
By default, the output of EXPLAIN QUERY PLAN commands does not +** include output for any operations performed by trigger programs. This +** option is used to set or clear (the default) a flag that governs this +** behavior. The first parameter passed to this operation is an integer - +** positive to enable output for trigger programs, or zero to disable it, +** or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which is written +** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if +** it is not disabled, 1 if it is. +**
+** +** [[SQLITE_DBCONFIG_RESET_DATABASE]]
SQLITE_DBCONFIG_RESET_DATABASE
+**
Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run +** [VACUUM] in order to reset a database back to an empty database +** with no schema and no content. The following process works even for +** a badly corrupted database file: +**
    +**
  1. If the database connection is newly opened, make sure it has read the +** database schema by preparing then discarding some query against the +** database, or calling sqlite3_table_column_metadata(), ignoring any +** errors. This step is only necessary if the application desires to keep +** the database in WAL mode after the reset if it was in WAL mode before +** the reset. +**
  2. sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); +**
  3. [sqlite3_exec](db, "[VACUUM]", 0, 0, 0); +**
  4. sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0); +**
+** Because resetting a database is destructive and irreversible, the +** process requires the use of this obscure API and multiple steps to +** help ensure that it does not happen by accident. Because this +** feature must be capable of resetting corrupt databases, and +** shutting down virtual tables may require access to that corrupt +** storage, the library must abandon any installed virtual tables +** without calling their xDestroy() methods. +** +** [[SQLITE_DBCONFIG_DEFENSIVE]]
SQLITE_DBCONFIG_DEFENSIVE
+**
The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the +** "defensive" flag for a database connection. When the defensive +** flag is enabled, language features that allow ordinary SQL to +** deliberately corrupt the database file are disabled. The disabled +** features include but are not limited to the following: +**
    +**
  • The [PRAGMA writable_schema=ON] statement. +**
  • The [PRAGMA journal_mode=OFF] statement. +**
  • The [PRAGMA schema_version=N] statement. +**
  • Writes to the [sqlite_dbpage] virtual table. +**
  • Direct writes to [shadow tables]. +**
+**
+** +** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]]
SQLITE_DBCONFIG_WRITABLE_SCHEMA
+**
The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the +** "writable_schema" flag. This has the same effect and is logically equivalent +** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF]. +** The first argument to this setting is an integer which is 0 to disable +** the writable_schema, positive to enable writable_schema, or negative to +** leave the setting unchanged. The second parameter is a pointer to an +** integer into which is written 0 or 1 to indicate whether the writable_schema +** is enabled or disabled following this call. +**
+** +** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]] +**
SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
+**
The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates +** the legacy behavior of the [ALTER TABLE RENAME] command such it +** behaves as it did prior to [version 3.24.0] (2018-06-04). See the +** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for +** additional information. This feature can also be turned on and off +** using the [PRAGMA legacy_alter_table] statement. +**
+** +** [[SQLITE_DBCONFIG_DQS_DML]] +**
SQLITE_DBCONFIG_DQS_DML
+**
The SQLITE_DBCONFIG_DQS_DML option activates or deactivates +** the legacy [double-quoted string literal] misfeature for DML statements +** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The +** default value of this setting is determined by the [-DSQLITE_DQS] +** compile-time option. +**
+** +** [[SQLITE_DBCONFIG_DQS_DDL]] +**
SQLITE_DBCONFIG_DQS_DDL
+**
The SQLITE_DBCONFIG_DQS option activates or deactivates +** the legacy [double-quoted string literal] misfeature for DDL statements, +** such as CREATE TABLE and CREATE INDEX. The +** default value of this setting is determined by the [-DSQLITE_DQS] +** compile-time option. +**
+** +** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]] +**
SQLITE_DBCONFIG_TRUSTED_SCHEMA
+**
The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to +** assume that database schemas are untainted by malicious content. +** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite +** takes additional defensive steps to protect the application from harm +** including: +**
    +**
  • Prohibit the use of SQL functions inside triggers, views, +** CHECK constraints, DEFAULT clauses, expression indexes, +** partial indexes, or generated columns +** unless those functions are tagged with [SQLITE_INNOCUOUS]. +**
  • Prohibit the use of virtual tables inside of triggers or views +** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS]. +**
+** This setting defaults to "on" for legacy compatibility, however +** all applications are advised to turn it off if possible. This setting +** can also be controlled using the [PRAGMA trusted_schema] statement. +**
+** +** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]] +**
SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
+**
The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates +** the legacy file format flag. When activated, this flag causes all newly +** created database file to have a schema format version number (the 4-byte +** integer found at offset 44 into the database header) of 1. This in turn +** means that the resulting database file will be readable and writable by +** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting, +** newly created databases are generally not understandable by SQLite versions +** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there +** is now scarcely any need to generate database files that are compatible +** all the way back to version 3.0.0, and so this setting is of little +** practical use, but is provided so that SQLite can continue to claim the +** ability to generate new database files that are compatible with version +** 3.0.0. +**

Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on, +** the [VACUUM] command will fail with an obscure error when attempting to +** process a table with generated columns and a descending index. This is +** not considered a bug since SQLite versions 3.3.0 and earlier do not support +** either generated columns or descending indexes. +**

+** +** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]] +**
SQLITE_DBCONFIG_STMT_SCANSTATUS
+**
The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in +** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears +** a flag that enables collection of the sqlite3_stmt_scanstatus_v2() +** statistics. For statistics to be collected, the flag must be set on +** the database handle both when the SQL statement is prepared and when it +** is stepped. The flag is set (collection of statistics is enabled) +** by default.

This option takes two arguments: an integer and a pointer to +** an integer.. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the statement scanstatus option. If the second argument +** is not NULL, then the value of the statement scanstatus setting after +** processing the first argument is written into the integer that the second +** argument points to. +**

+** +** [[SQLITE_DBCONFIG_REVERSE_SCANORDER]] +**
SQLITE_DBCONFIG_REVERSE_SCANORDER
+**
The SQLITE_DBCONFIG_REVERSE_SCANORDER option changes the default order +** in which tables and indexes are scanned so that the scans start at the end +** and work toward the beginning rather than starting at the beginning and +** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the +** same as setting [PRAGMA reverse_unordered_selects].

This option takes +** two arguments which are an integer and a pointer to an integer. The first +** argument is 1, 0, or -1 to enable, disable, or leave unchanged the +** reverse scan order flag, respectively. If the second argument is not NULL, +** then 0 or 1 is written into the integer that the second argument points to +** depending on if the reverse scan order flag is set after processing the +** first argument. +**

+** +** [[SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]] +**
SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE
+**
The SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE option enables or disables +** the ability of the [ATTACH DATABASE] SQL command to create a new database +** file if the database filed named in the ATTACH command does not already +** exist. This ability of ATTACH to create a new database is enabled by +** default. Applications can disable or reenable the ability for ATTACH to +** create new database files using this DBCONFIG option.

+** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the attach-create flag, respectively. If the second +** argument is not NULL, then 0 or 1 is written into the integer that the +** second argument points to depending on if the attach-create flag is set +** after processing the first argument. +**

+** +** [[SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE]] +**
SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE
+**
The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the +** ability of the [ATTACH DATABASE] SQL command to open a database for writing. +** This capability is enabled by default. Applications can disable or +** reenable this capability using the current DBCONFIG option. If the +** the this capability is disabled, the [ATTACH] command will still work, +** but the database will be opened read-only. If this option is disabled, +** then the ability to create a new database using [ATTACH] is also disabled, +** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE] +** option.

+** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the ability to ATTACH another database for writing, +** respectively. If the second argument is not NULL, then 0 or 1 is written +** into the integer to which the second argument points, depending on whether +** the ability to ATTACH a read/write database is enabled or disabled +** after processing the first argument. +**

+** +** [[SQLITE_DBCONFIG_ENABLE_COMMENTS]] +**
SQLITE_DBCONFIG_ENABLE_COMMENTS
+**
The SQLITE_DBCONFIG_ENABLE_COMMENTS option enables or disables the +** ability to include comments in SQL text. Comments are enabled by default. +** An application can disable or reenable comments in SQL text using this +** DBCONFIG option.

+** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the ability to use comments in SQL text, +** respectively. If the second argument is not NULL, then 0 or 1 is written +** into the integer that the second argument points to depending on if +** comments are allowed in SQL text after processing the first argument. +**

+** +**
+** +** [[DBCONFIG arguments]]

Arguments To SQLITE_DBCONFIG Options

+** +**

Most of the SQLITE_DBCONFIG options take two arguments, so that the +** overall call to [sqlite3_db_config()] has a total of four parameters. +** The first argument (the third parameter to sqlite3_db_config()) is a integer. +** The second argument is a pointer to an integer. If the first argument is 1, +** then the option becomes enabled. If the first integer argument is 0, then the +** option is disabled. If the first argument is -1, then the option setting +** is unchanged. The second argument, the pointer to an integer, may be NULL. +** If the second argument is not NULL, then a value of 0 or 1 is written into +** the integer to which the second argument points, depending on whether the +** setting is disabled or enabled after applying any changes specified by +** the first argument. +** +**

While most SQLITE_DBCONFIG options use the argument format +** described in the previous paragraph, the [SQLITE_DBCONFIG_MAINDBNAME] +** and [SQLITE_DBCONFIG_LOOKASIDE] options are different. See the +** documentation of those exceptional options for details. +*/ +#define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ +#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ +#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */ +#define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */ +#define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */ +#define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */ +#define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */ +#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */ +#define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */ +#define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */ +#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */ +#define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */ +#define SQLITE_DBCONFIG_STMT_SCANSTATUS 1018 /* int int* */ +#define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */ +#define SQLITE_DBCONFIG_MAX 1022 /* Largest DBCONFIG */ + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** METHOD: sqlite3 +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** METHOD: sqlite3 +** +** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) +** has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of +** the most recent successful [INSERT] into a rowid table or [virtual table] +** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not +** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred +** on the database connection D, then sqlite3_last_insert_rowid(D) returns +** zero. +** +** As well as being set automatically as rows are inserted into database +** tables, the value returned by this function may be set explicitly by +** [sqlite3_set_last_insert_rowid()] +** +** Some virtual table implementations may INSERT rows into rowid tables as +** part of committing a transaction (e.g. to flush data accumulated in memory +** to disk). In this case subsequent calls to this function return the rowid +** associated with these internal INSERT operations, which leads to +** unintuitive results. Virtual table implementations that do write to rowid +** tables in this way can avoid this problem by restoring the original +** rowid value using [sqlite3_set_last_insert_rowid()] before returning +** control to the user. +** +** ^(If an [INSERT] occurs within a trigger then this routine will +** return the [rowid] of the inserted row as long as the trigger is +** running. Once the trigger program ends, the value returned +** by this routine reverts to what it was before the trigger was fired.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Set the Last Insert Rowid value. +** METHOD: sqlite3 +** +** The sqlite3_set_last_insert_rowid(D, R) method allows the application to +** set the value returned by calling sqlite3_last_insert_rowid(D) to R +** without inserting a row into the database. +*/ +SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** METHOD: sqlite3 +** +** ^These functions return the number of rows modified, inserted or +** deleted by the most recently completed INSERT, UPDATE or DELETE +** statement on the database connection specified by the only parameter. +** The two functions are identical except for the type of the return value +** and that if the number of rows modified by the most recent INSERT, UPDATE, +** or DELETE is greater than the maximum value supported by type "int", then +** the return value of sqlite3_changes() is undefined. ^Executing any other +** type of SQL statement does not modify the value returned by these functions. +** For the purposes of this interface, a CREATE TABLE AS SELECT statement +** does not count as an INSERT, UPDATE or DELETE statement and hence the rows +** added to the new table by the CREATE TABLE AS SELECT statement are not +** counted. +** +** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are +** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], +** [foreign key actions] or [REPLACE] constraint resolution are not counted. +** +** Changes to a view that are intercepted by +** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value +** returned by sqlite3_changes() immediately after an INSERT, UPDATE or +** DELETE statement run on a view is always zero. Only changes made to real +** tables are counted. +** +** Things are more complicated if the sqlite3_changes() function is +** executed while a trigger program is running. This may happen if the +** program uses the [changes() SQL function], or if some other callback +** function invokes sqlite3_changes() directly. Essentially: +** +**

    +**
  • ^(Before entering a trigger program the value returned by +** sqlite3_changes() function is saved. After the trigger program +** has finished, the original value is restored.)^ +** +**
  • ^(Within a trigger program each INSERT, UPDATE and DELETE +** statement sets the value returned by sqlite3_changes() +** upon completion as normal. Of course, this value will not include +** any changes performed by sub-triggers, as the sqlite3_changes() +** value will be saved and restored after each sub-trigger has run.)^ +**
+** +** ^This means that if the changes() SQL function (or similar) is used +** by the first INSERT, UPDATE or DELETE statement within a trigger, it +** returns the value as set when the calling statement began executing. +** ^If it is used by the second or subsequent such statement within a trigger +** program, the value returned reflects the number of rows modified by the +** previous INSERT, UPDATE or DELETE statement within the same trigger. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +** +** See also: +**
    +**
  • the [sqlite3_total_changes()] interface +**
  • the [count_changes pragma] +**
  • the [changes() SQL function] +**
  • the [data_version pragma] +**
+*/ +SQLITE_API int sqlite3_changes(sqlite3*); +SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** METHOD: sqlite3 +** +** ^These functions return the total number of rows inserted, modified or +** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed +** since the database connection was opened, including those executed as +** part of trigger programs. The two functions are identical except for the +** type of the return value and that if the number of rows modified by the +** connection exceeds the maximum value supported by type "int", then +** the return value of sqlite3_total_changes() is undefined. ^Executing +** any other type of SQL statement does not affect the value returned by +** sqlite3_total_changes(). +** +** ^Changes made as part of [foreign key actions] are included in the +** count, but those made as part of REPLACE constraint resolution are +** not. ^Changes to a view that are intercepted by INSTEAD OF triggers +** are not counted. +** +** The [sqlite3_total_changes(D)] interface only reports the number +** of rows that changed due to SQL statement run against database +** connection D. Any changes by other database connections are ignored. +** To detect changes against a database file from other database +** connections use the [PRAGMA data_version] command or the +** [SQLITE_FCNTL_DATA_VERSION] [file control]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +** +** See also: +**
    +**
  • the [sqlite3_changes()] interface +**
  • the [count_changes pragma] +**
  • the [changes() SQL function] +**
  • the [data_version pragma] +**
  • the [SQLITE_FCNTL_DATA_VERSION] [file control] +**
+*/ +SQLITE_API int sqlite3_total_changes(sqlite3*); +SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** METHOD: sqlite3 +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statement count reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** ^The [sqlite3_is_interrupted(D)] interface can be used to determine whether +** or not an interrupt is currently in effect for [database connection] D. +** It returns 1 if an interrupt is currently in effect, or 0 otherwise. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3*); +SQLITE_API int sqlite3_is_interrupted(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +SQLITE_API int sqlite3_complete(const char *sql); +SQLITE_API int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** KEYWORDS: {busy-handler callback} {busy handler} +** METHOD: sqlite3 +** +** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X +** that might be invoked with argument P whenever +** an attempt is made to access a database table associated with +** [database connection] D when another thread +** or process has the table locked. +** The sqlite3_busy_handler() interface is used to implement +** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked previously for the same locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] is returned +** to the application. +** ^If the callback returns non-zero, then another attempt +** is made to access the database and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** to the application instead of invoking the +** busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** or evaluating [PRAGMA busy_timeout=N] will change the +** busy handler and thus clear any previously set busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. In other words, +** the busy handler is not reentrant. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); + +/* +** CAPI3REF: Set A Busy Timeout +** METHOD: sqlite3 +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] at any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +** +** See also: [PRAGMA busy_timeout] +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Set the Setlk Timeout +** METHOD: sqlite3 +** +** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If +** the VFS supports blocking locks, it sets the timeout in ms used by +** eligible locks taken on wal mode databases by the specified database +** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does +** not support blocking locks, this function is a no-op. +** +** Passing 0 to this function disables blocking locks altogether. Passing +** -1 to this function requests that the VFS blocks for a long time - +** indefinitely if possible. The results of passing any other negative value +** are undefined. +** +** Internally, each SQLite database handle store two timeout values - the +** busy-timeout (used for rollback mode databases, or if the VFS does not +** support blocking locks) and the setlk-timeout (used for blocking locks +** on wal-mode databases). The sqlite3_busy_timeout() method sets both +** values, this function sets only the setlk-timeout value. Therefore, +** to configure separate busy-timeout and setlk-timeout values for a single +** database handle, call sqlite3_busy_timeout() followed by this function. +** +** Whenever the number of connections to a wal mode database falls from +** 1 to 0, the last connection takes an exclusive lock on the database, +** then checkpoints and deletes the wal file. While it is doing this, any +** new connection that tries to read from the database fails with an +** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is +** passed to this API, the new connection blocks until the exclusive lock +** has been released. +*/ +SQLITE_API int sqlite3_setlk_timeout(sqlite3*, int ms, int flags); + +/* +** CAPI3REF: Flags for sqlite3_setlk_timeout() +*/ +#define SQLITE_SETLK_BLOCK_ON_CONNECT 0x01 + +/* +** CAPI3REF: Convenience Routines For Running Queries +** METHOD: sqlite3 +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+** 
+** +** There are two columns (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array named azResult. Then azResult holds this content: +** +**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+** 
)^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +SQLITE_API void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** These routines understand most of the common formatting options from +** the standard library printf() +** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]). +** See the [built-in printf()] documentation for details. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc64()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** See also: [built-in printf()], [printf() SQL function] +*/ +SQLITE_API char *sqlite3_mprintf(const char*,...); +SQLITE_API char *sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific [VFS] implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^The sqlite3_malloc64(N) routine works just like +** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead +** of a signed 32-bit integer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^The sqlite3_realloc(X,N) interface attempts to resize a +** prior memory allocation X to be at least N bytes. +** ^If the X parameter to sqlite3_realloc(X,N) +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N). +** ^If the N parameter to sqlite3_realloc(X,N) is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(X). +** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation +** of at least N bytes in size or NULL if insufficient memory is available. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc(X,N) and the prior allocation is freed. +** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the +** prior allocation is not freed. +** +** ^The sqlite3_realloc64(X,N) interfaces works the same as +** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead +** of a 32-bit signed integer. +** +** ^If X is a memory allocation previously obtained from sqlite3_malloc(), +** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then +** sqlite3_msize(X) returns the size of that memory allocation in bytes. +** ^The value returned by sqlite3_msize(X) might be larger than the number +** of bytes requested when X was allocated. ^If X is a NULL pointer then +** sqlite3_msize(X) returns zero. If X points to something that is not +** the beginning of memory allocation, or if it points to a formerly +** valid memory allocation that has now been freed, then the behavior +** of sqlite3_msize(X) is undefined and possibly harmful. +** +** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), +** sqlite3_malloc64(), and sqlite3_realloc64() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +SQLITE_API void *sqlite3_malloc(int); +SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); +SQLITE_API void *sqlite3_realloc(void*, int); +SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); +SQLITE_API void sqlite3_free(void*); +SQLITE_API sqlite3_uint64 sqlite3_msize(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the built-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** ^The P parameter can be a NULL pointer. +** +** ^If this routine has not been previously called or if the previous +** call had N less than one or a NULL pointer for P, then the PRNG is +** seeded using randomness obtained from the xRandomness method of +** the default [sqlite3_vfs] object. +** ^If the previous call to this routine had an N of 1 or more and a +** non-NULL P then the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +SQLITE_API void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** METHOD: sqlite3 +** KEYWORDS: {authorizer callback} +** +** ^This routine registers an authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()], +** and [sqlite3_prepare16_v3()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are either NULL pointers or zero-terminated strings +** that contain additional details about the action to be authorized. +** Applications must always be prepared to encounter a NULL pointer in any +** of the third through the sixth parameters of the authorization callback. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^When a table is referenced by a [SELECT] but no column values are +** extracted from that table (for example in a query like +** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback +** is invoked once for that table with a column name that is an empty string. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +** +** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] +** returned from the [sqlite3_vtab_on_conflict()] interface. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ +#define SQLITE_RECURSIVE 33 /* NULL NULL */ + +/* +** CAPI3REF: Deprecated Tracing And Profiling Functions +** DEPRECATED +** +** These routines are deprecated. Use the [sqlite3_trace_v2()] interface +** instead of the routines described here. +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit +** the length of [bound parameter] expansion in the output of sqlite3_trace(). +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. Invoking +** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the +** profile callback. +*/ +SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, + void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: SQL Trace Event Codes +** KEYWORDS: SQLITE_TRACE +** +** These constants identify classes of events that can be monitored +** using the [sqlite3_trace_v2()] tracing logic. The M argument +** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of +** the following constants. ^The first argument to the trace callback +** is one of the following constants. +** +** New tracing constants may be added in future releases. +** +** ^A trace callback has four arguments: xCallback(T,C,P,X). +** ^The T argument is one of the integer type codes above. +** ^The C argument is a copy of the context pointer passed in as the +** fourth argument to [sqlite3_trace_v2()]. +** The P and X arguments are pointers whose meanings depend on T. +** +**
+** [[SQLITE_TRACE_STMT]]
SQLITE_TRACE_STMT
+**
^An SQLITE_TRACE_STMT callback is invoked when a prepared statement +** first begins running and possibly at other times during the +** execution of the prepared statement, such as at the start of each +** trigger subprogram. ^The P argument is a pointer to the +** [prepared statement]. ^The X argument is a pointer to a string which +** is the unexpanded SQL text of the prepared statement or an SQL comment +** that indicates the invocation of a trigger. ^The callback can compute +** the same text that would have been returned by the legacy [sqlite3_trace()] +** interface by using the X argument when X begins with "--" and invoking +** [sqlite3_expanded_sql(P)] otherwise. +** +** [[SQLITE_TRACE_PROFILE]]
SQLITE_TRACE_PROFILE
+**
^An SQLITE_TRACE_PROFILE callback provides approximately the same +** information as is provided by the [sqlite3_profile()] callback. +** ^The P argument is a pointer to the [prepared statement] and the +** X argument points to a 64-bit integer which is approximately +** the number of nanoseconds that the prepared statement took to run. +** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes. +** +** [[SQLITE_TRACE_ROW]]
SQLITE_TRACE_ROW
+**
^An SQLITE_TRACE_ROW callback is invoked whenever a prepared +** statement generates a single row of result. +** ^The P argument is a pointer to the [prepared statement] and the +** X argument is unused. +** +** [[SQLITE_TRACE_CLOSE]]
SQLITE_TRACE_CLOSE
+**
^An SQLITE_TRACE_CLOSE callback is invoked when a database +** connection closes. +** ^The P argument is a pointer to the [database connection] object +** and the X argument is unused. +**
+*/ +#define SQLITE_TRACE_STMT 0x01 +#define SQLITE_TRACE_PROFILE 0x02 +#define SQLITE_TRACE_ROW 0x04 +#define SQLITE_TRACE_CLOSE 0x08 + +/* +** CAPI3REF: SQL Trace Hook +** METHOD: sqlite3 +** +** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback +** function X against [database connection] D, using property mask M +** and context pointer P. ^If the X callback is +** NULL or if the M mask is zero, then tracing is disabled. The +** M argument should be the bitwise OR-ed combination of +** zero or more [SQLITE_TRACE] constants. +** +** ^Each call to either sqlite3_trace(D,X,P) or sqlite3_trace_v2(D,M,X,P) +** overrides (cancels) all prior calls to sqlite3_trace(D,X,P) or +** sqlite3_trace_v2(D,M,X,P) for the [database connection] D. Each +** database connection may have at most one trace callback. +** +** ^The X callback is invoked whenever any of the events identified by +** mask M occur. ^The integer return value from the callback is currently +** ignored, though this may change in future releases. Callback +** implementations should return zero to ensure future compatibility. +** +** ^A trace callback is invoked with four arguments: callback(T,C,P,X). +** ^The T argument is one of the [SQLITE_TRACE] +** constants to indicate why the callback was invoked. +** ^The C argument is a copy of the context pointer. +** The P and X arguments are pointers whose meanings depend on T. +** +** The sqlite3_trace_v2() interface is intended to replace the legacy +** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which +** are deprecated. +*/ +SQLITE_API int sqlite3_trace_v2( + sqlite3*, + unsigned uMask, + int(*xCallback)(unsigned,void*,void*,void*), + void *pCtx +); + +/* +** CAPI3REF: Query Progress Callbacks +** METHOD: sqlite3 +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_step()] and [sqlite3_prepare()] and similar for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the approximate number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. ^If N is less than one then the progress +** handler is disabled. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** The progress handler callback would originally only be invoked from the +** bytecode engine. It still might be invoked during [sqlite3_prepare()] +** and similar because those routines might force a reparse of the schema +** which involves running the bytecode engine. However, beginning with +** SQLite version 3.41.0, the progress handler callback might also be +** invoked directly from [sqlite3_prepare()] while analyzing and generating +** code for complex queries. +*/ +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** CONSTRUCTOR: sqlite3 +** +** ^These routines open an SQLite database file as specified by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding will be UTF-8 for databases created using +** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases +** created using sqlite3_open16() will be UTF-16 in the native byte order. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() must include, at a minimum, one of the following +** three flag combinations:)^ +** +**
+** ^(
[SQLITE_OPEN_READONLY]
+**
The database is opened in read-only mode. If the database does +** not already exist, an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE]
+**
The database is opened for reading and writing if possible, or +** reading only if the file is write protected by the operating +** system. In either case the database must already exist, otherwise +** an error is returned. For historical reasons, if opening in +** read-write mode fails due to OS-level permissions, an attempt is +** made to open it in read-only mode. [sqlite3_db_readonly()] can be +** used to determine whether the database is actually +** read-write.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
+**
The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
)^ +**
+** +** In addition to the required flags, the following optional flags are +** also supported: +** +**
+** ^(
[SQLITE_OPEN_URI]
+**
The filename can be interpreted as a URI if this flag is set.
)^ +** +** ^(
[SQLITE_OPEN_MEMORY]
+**
The database will be opened as an in-memory database. The database +** is named by the "filename" argument for the purposes of cache-sharing, +** if shared cache mode is enabled, but the "filename" is otherwise ignored. +**
)^ +** +** ^(
[SQLITE_OPEN_NOMUTEX]
+**
The new database connection will use the "multi-thread" +** [threading mode].)^ This means that separate threads are allowed +** to use SQLite at the same time, as long as each thread is using +** a different [database connection]. +** +** ^(
[SQLITE_OPEN_FULLMUTEX]
+**
The new database connection will use the "serialized" +** [threading mode].)^ This means the multiple threads can safely +** attempt to use the same database connection at the same time. +** (Mutexes will block any actual concurrency, but in this mode +** there is no harm in trying.) +** +** ^(
[SQLITE_OPEN_SHAREDCACHE]
+**
The database is opened [shared cache] enabled, overriding +** the default shared cache setting provided by +** [sqlite3_enable_shared_cache()].)^ +** The [use of shared cache mode is discouraged] and hence shared cache +** capabilities may be omitted from many builds of SQLite. In such cases, +** this option is a no-op. +** +** ^(
[SQLITE_OPEN_PRIVATECACHE]
+**
The database is opened [shared cache] disabled, overriding +** the default shared cache setting provided by +** [sqlite3_enable_shared_cache()].)^ +** +** [[OPEN_EXRESCODE]] ^(
[SQLITE_OPEN_EXRESCODE]
+**
The database connection comes up in "extended result code mode". +** In other words, the database behaves as if +** [sqlite3_extended_result_codes(db,1)] were called on the database +** connection as soon as the connection is created. In addition to setting +** the extended result code mode, this flag also causes [sqlite3_open_v2()] +** to return an extended result code.
+** +** [[OPEN_NOFOLLOW]] ^(
[SQLITE_OPEN_NOFOLLOW]
+**
The database filename is not allowed to contain a symbolic link
+**
)^ +** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** required combinations shown above optionally combined with other +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] +** then the behavior is undefined. Historic versions of SQLite +** have silently ignored surplus bits in the flags parameter to +** sqlite3_open_v2(), however that behavior might not be carried through +** into future versions of SQLite and so applications should not rely +** upon it. Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op +** for sqlite3_open_v2(). The SQLITE_OPEN_EXCLUSIVE does *not* cause +** the open to fail if the database already exists. The SQLITE_OPEN_EXCLUSIVE +** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not +** by sqlite3_open_v2(). +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** [[URI filenames in sqlite3_open()]]

URI Filenames

+** +** ^If [URI filename] interpretation is enabled, and the filename argument +** begins with "file:", then the filename is interpreted as a URI. ^URI +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is +** set in the third argument to sqlite3_open_v2(), or if it has +** been enabled globally using the [SQLITE_CONFIG_URI] option with the +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** URI filename interpretation is turned off +** by default, but future releases of SQLite might enable URI filename +** interpretation by default. See "[URI filenames]" for additional +** information. +** +** URI filenames are parsed according to RFC 3986. ^If the URI contains an +** authority, then it must be either an empty string or the string +** "localhost". ^If the authority is not an empty string or "localhost", an +** error is returned to the caller. ^The fragment component of a URI, if +** present, is ignored. +** +** ^SQLite uses the path component of the URI as the name of the disk file +** which contains the database. ^If the path begins with a '/' character, +** then it is interpreted as an absolute path. ^If the path does not begin +** with a '/' (meaning that the authority section is omitted from the URI) +** then the path is interpreted as a relative path. +** ^(On windows, the first component of an absolute path +** is a drive specification (e.g. "C:").)^ +** +** [[core URI query parameters]] +** The query component of a URI may contain parameters that are interpreted +** either by SQLite itself, or by a [VFS | custom VFS implementation]. +** SQLite and its built-in [VFSes] interpret the +** following query parameters: +** +**
    +**
  • vfs: ^The "vfs" parameter may be used to specify the name of +** a VFS object that provides the operating system interface that should +** be used to access the database file on disk. ^If this option is set to +** an empty string the default VFS object is used. ^Specifying an unknown +** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** present, then the VFS specified by the option takes precedence over +** the value passed as the fourth parameter to sqlite3_open_v2(). +** +**
  • mode: ^(The mode parameter may be set to either "ro", "rw", +** "rwc", or "memory". Attempting to set it to any other value is +** an error)^. +** ^If "ro" is specified, then the database is opened for read-only +** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the +** third argument to sqlite3_open_v2(). ^If the mode option is set to +** "rw", then the database is opened for read-write (but not create) +** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had +** been set. ^Value "rwc" is equivalent to setting both +** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is +** set to "memory" then a pure [in-memory database] that never reads +** or writes from disk is used. ^It is an error to specify a value for +** the mode parameter that is less restrictive than that specified by +** the flags passed in the third parameter to sqlite3_open_v2(). +** +**
  • cache: ^The cache parameter may be set to either "shared" or +** "private". ^Setting it to "shared" is equivalent to setting the +** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to +** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** a URI filename, its value overrides any behavior requested by setting +** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. +** +**
  • psow: ^The psow parameter indicates whether or not the +** [powersafe overwrite] property does or does not apply to the +** storage media on which the database file resides. +** +**
  • nolock: ^The nolock parameter is a boolean query parameter +** which if set disables file locking in rollback journal modes. This +** is useful for accessing a database on a filesystem that does not +** support locking. Caution: Database corruption might result if two +** or more processes write to the same database and any one of those +** processes uses nolock=1. +** +**
  • immutable: ^The immutable parameter is a boolean query +** parameter that indicates that the database file is stored on +** read-only media. ^When immutable is set, SQLite assumes that the +** database file cannot be changed, even by a process with higher +** privilege, and so the database is opened read-only and all locking +** and change detection is disabled. Caution: Setting the immutable +** property on a database file that does in fact change can result +** in incorrect query results and/or [SQLITE_CORRUPT] errors. +** See also: [SQLITE_IOCAP_IMMUTABLE]. +** +**
+** +** ^Specifying an unknown parameter in the query component of a URI is not an +** error. Future versions of SQLite might understand additional query +** parameters. See "[query parameters with special meaning to SQLite]" for +** additional information. +** +** [[URI filename examples]]

URI filename examples

+** +** +**
URI filenames Results +**
file:data.db +** Open the file "data.db" in the current directory. +**
file:/home/fred/data.db
+** file:///home/fred/data.db
+** file://localhost/home/fred/data.db
+** Open the database file "/home/fred/data.db". +**
file://darkstar/home/fred/data.db +** An error. "darkstar" is not a recognized authority. +**
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db +** Windows only: Open the file "data.db" on fred's desktop on drive +** C:. Note that the %20 escaping in this example is not strictly +** necessary - space characters can be used literally +** in URI filenames. +**
file:data.db?mode=ro&cache=private +** Open file "data.db" in the current directory for read-only access. +** Regardless of whether or not shared-cache mode is enabled by +** default, use a private cache. +**
file:/home/fred/data.db?vfs=unix-dotfile +** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile" +** that uses dot-files in place of posix advisory locking. +**
file:data.db?mode=readonly +** An error. "readonly" is not a valid option for the "mode" parameter. +** Use "ro" instead: "file:data.db?mode=ro". +**
+** +** ^URI hexadecimal escape sequences (%HH) are supported within the path and +** query components of a URI. A hexadecimal escape sequence consists of a +** percent sign - "%" - followed by exactly two hexadecimal digits +** specifying an octet value. ^Before the path or query components of a +** URI filename are interpreted, they are encoded using UTF-8 and all +** hexadecimal escape sequences replaced by a single byte containing the +** corresponding octet. If this process generates an invalid UTF-8 encoding, +** the results are undefined. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** features that require the use of temporary files may fail. +** +** See also: [sqlite3_temp_directory] +*/ +SQLITE_API int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Obtain Values For URI Parameters +** +** These are utility routines, useful to [VFS|custom VFS implementations], +** that check if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of that query parameter. +** +** The first parameter to these interfaces (hereafter referred to +** as F) must be one of: +**
    +**
  • A database filename pointer created by the SQLite core and +** passed into the xOpen() method of a VFS implementation, or +**
  • A filename obtained from [sqlite3_db_filename()], or +**
  • A new filename constructed using [sqlite3_create_filename()]. +**
+** If the F parameter is not one of the above, then the behavior is +** undefined and probably undesirable. Older versions of SQLite were +** more tolerant of invalid F parameters than newer versions. +** +** If F is a suitable filename (as described in the previous paragraph) +** and if P is the name of the query parameter, then +** sqlite3_uri_parameter(F,P) returns the value of the P +** parameter if it exists or a NULL pointer if P does not appear as a +** query parameter on F. If P is a query parameter of F and it +** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** a pointer to an empty string. +** +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** parameter and returns true (1) or false (0) according to the value +** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** value of query parameter P is one of "yes", "true", or "on" in any +** case or if the value begins with a non-zero number. The +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** query parameter P is one of "no", "false", or "off" in any case or +** if the value begins with a numeric zero. If P is not a query +** parameter on F or if the value of P does not match any of the +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** 64-bit signed integer and returns that integer, or D if P does not +** exist. If the value of P is something other than an integer, then +** zero is returned. +** +** The sqlite3_uri_key(F,N) returns a pointer to the name (not +** the value) of the N-th query parameter for filename F, or a NULL +** pointer if N is less than zero or greater than the number of query +** parameters minus 1. The N value is zero-based so N should be 0 to obtain +** the name of the first query parameter, 1 for the second parameter, and +** so forth. +** +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and +** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that the SQLite core passed +** into the xOpen VFS method, then the behavior of this routine is undefined +** and probably undesirable. +** +** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F +** parameter can also be the name of a rollback journal file or WAL file +** in addition to the main database file. Prior to version 3.31.0, these +** routines would only work if F was the name of the main database file. +** When the F parameter is the name of the rollback journal or WAL file, +** it has access to all the same query parameters as were found on the +** main database file. +** +** See the [URI filename] documentation for additional information. +*/ +SQLITE_API const char *sqlite3_uri_parameter(sqlite3_filename z, const char *zParam); +SQLITE_API int sqlite3_uri_boolean(sqlite3_filename z, const char *zParam, int bDefault); +SQLITE_API sqlite3_int64 sqlite3_uri_int64(sqlite3_filename, const char*, sqlite3_int64); +SQLITE_API const char *sqlite3_uri_key(sqlite3_filename z, int N); + +/* +** CAPI3REF: Translate filenames +** +** These routines are available to [VFS|custom VFS implementations] for +** translating filenames between the main database file, the journal file, +** and the WAL file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** passed by the SQLite core into the VFS, then sqlite3_filename_database(F) +** returns the name of the corresponding database file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** passed by the SQLite core into the VFS, or if F is a database filename +** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F) +** returns the name of the corresponding rollback journal file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** that was passed by the SQLite core into the VFS, or if F is a database +** filename obtained from [sqlite3_db_filename()], then +** sqlite3_filename_wal(F) returns the name of the corresponding +** WAL file. +** +** In all of the above, if F is not the name of a database, journal or WAL +** filename passed into the VFS from the SQLite core and F is not the +** return value from [sqlite3_db_filename()], then the result is +** undefined and is likely a memory access violation. +*/ +SQLITE_API const char *sqlite3_filename_database(sqlite3_filename); +SQLITE_API const char *sqlite3_filename_journal(sqlite3_filename); +SQLITE_API const char *sqlite3_filename_wal(sqlite3_filename); + +/* +** CAPI3REF: Database File Corresponding To A Journal +** +** ^If X is the name of a rollback or WAL-mode journal file that is +** passed into the xOpen method of [sqlite3_vfs], then +** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file] +** object that represents the main database file. +** +** This routine is intended for use in custom [VFS] implementations +** only. It is not a general-purpose interface. +** The argument sqlite3_file_object(X) must be a filename pointer that +** has been passed into [sqlite3_vfs].xOpen method where the +** flags parameter to xOpen contains one of the bits +** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use +** of this routine results in undefined and probably undesirable +** behavior. +*/ +SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*); + +/* +** CAPI3REF: Create and Destroy VFS Filenames +** +** These interfaces are provided for use by [VFS shim] implementations and +** are not useful outside of that context. +** +** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of +** database filename D with corresponding journal file J and WAL file W and +** with N URI parameters key/values pairs in the array P. The result from +** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that +** is safe to pass to routines like: +**
    +**
  • [sqlite3_uri_parameter()], +**
  • [sqlite3_uri_boolean()], +**
  • [sqlite3_uri_int64()], +**
  • [sqlite3_uri_key()], +**
  • [sqlite3_filename_database()], +**
  • [sqlite3_filename_journal()], or +**
  • [sqlite3_filename_wal()]. +**
+** If a memory allocation error occurs, sqlite3_create_filename() might +** return a NULL pointer. The memory obtained from sqlite3_create_filename(X) +** must be released by a corresponding call to sqlite3_free_filename(Y). +** +** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array +** of 2*N pointers to strings. Each pair of pointers in this array corresponds +** to a key and value for a query parameter. The P parameter may be a NULL +** pointer if N is zero. None of the 2*N pointers in the P array may be +** NULL pointers and key pointers should not be empty strings. +** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may +** be NULL pointers, though they can be empty strings. +** +** The sqlite3_free_filename(Y) routine releases a memory allocation +** previously obtained from sqlite3_create_filename(). Invoking +** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op. +** +** If the Y parameter to sqlite3_free_filename(Y) is anything other +** than a NULL pointer or a pointer previously acquired from +** sqlite3_create_filename(), then bad things such as heap +** corruption or segfaults may occur. The value Y should not be +** used again after sqlite3_free_filename(Y) has been called. This means +** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y, +** then the corresponding [sqlite3_module.xClose() method should also be +** invoked prior to calling sqlite3_free_filename(Y). +*/ +SQLITE_API sqlite3_filename sqlite3_create_filename( + const char *zDatabase, + const char *zJournal, + const char *zWal, + int nParam, + const char **azParam +); +SQLITE_API void sqlite3_free_filename(sqlite3_filename); + +/* +** CAPI3REF: Error Codes And Messages +** METHOD: sqlite3 +** +** ^If the most recent sqlite3_* API call associated with +** [database connection] D failed, then the sqlite3_errcode(D) interface +** returns the numeric [result code] or [extended result code] for that +** API call. +** ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** The values returned by sqlite3_errcode() and/or +** sqlite3_extended_errcode() might change with each API call. +** Except, there are some interfaces that are guaranteed to never +** change the value of the error code. The error-code preserving +** interfaces include the following: +** +**
    +**
  • sqlite3_errcode() +**
  • sqlite3_extended_errcode() +**
  • sqlite3_errmsg() +**
  • sqlite3_errmsg16() +**
  • sqlite3_error_offset() +**
+** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively, +** or NULL if no error message is available. +** (See how SQLite handles [invalid UTF] for exceptions to this rule.) +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** ^The sqlite3_errstr(E) interface returns the English-language text +** that describes the [result code] E, as UTF-8, or NULL if E is not an +** result code for which a text error message is available. +** ^(Memory to hold the error message string is managed internally +** and must not be freed by the application)^. +** +** ^If the most recent error references a specific token in the input +** SQL, the sqlite3_error_offset() interface returns the byte offset +** of the start of that token. ^The byte offset returned by +** sqlite3_error_offset() assumes that the input SQL is UTF8. +** ^If the most recent error does not reference a specific token in the input +** SQL, then the sqlite3_error_offset() function returns -1. +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db); +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *sqlite3_errmsg(sqlite3*); +SQLITE_API const void *sqlite3_errmsg16(sqlite3*); +SQLITE_API const char *sqlite3_errstr(int); +SQLITE_API int sqlite3_error_offset(sqlite3 *db); + +/* +** CAPI3REF: Prepared Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement that +** has been compiled into binary form and is ready to be evaluated. +** +** Think of each SQL statement as a separate computer program. The +** original SQL text is source code. A prepared statement object +** is the compiled object code. All SQL must be converted into a +** prepared statement before it can be run. +** +** The life-cycle of a prepared statement object usually goes like this: +** +**
    +**
  1. Create the prepared statement object using [sqlite3_prepare_v2()]. +**
  2. Bind values to [parameters] using the sqlite3_bind_*() +** interfaces. +**
  3. Run the SQL by calling [sqlite3_step()] one or more times. +**
  4. Reset the prepared statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
  5. Destroy the object using [sqlite3_finalize()]. +**
+*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** METHOD: sqlite3 +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
+** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
+**
The maximum size of any string or BLOB or table row, in bytes.
)^ +** +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
+**
The maximum length of an SQL statement, in bytes.
)^ +** +** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
+**
The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
)^ +** +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
+**
The maximum depth of the parse tree on any expression.
)^ +** +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
+**
The maximum number of terms in a compound SELECT statement.
)^ +** +** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
+**
The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. If [sqlite3_prepare_v2()] or +** the equivalent tries to allocate space for more than this many opcodes +** in a single prepared statement, an SQLITE_NOMEM error is returned.
)^ +** +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
+**
The maximum number of arguments on a function.
)^ +** +** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
+**
The maximum number of [ATTACH | attached databases].)^
+** +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] +** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+**
The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
)^ +** +** [[SQLITE_LIMIT_VARIABLE_NUMBER]] +** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+**
The maximum index number of any [parameter] in an SQL statement.)^ +** +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+**
The maximum depth of recursion for triggers.
)^ +** +** [[SQLITE_LIMIT_WORKER_THREADS]] ^(
SQLITE_LIMIT_WORKER_THREADS
+**
The maximum number of auxiliary worker threads that a single +** [prepared statement] may start.
)^ +**
+*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 +#define SQLITE_LIMIT_WORKER_THREADS 11 + +/* +** CAPI3REF: Prepare Flags +** +** These constants define various flags that can be passed into +** "prepFlags" parameter of the [sqlite3_prepare_v3()] and +** [sqlite3_prepare16_v3()] interfaces. +** +** New flags may be added in future releases of SQLite. +** +**
+** [[SQLITE_PREPARE_PERSISTENT]] ^(
SQLITE_PREPARE_PERSISTENT
+**
The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner +** that the prepared statement will be retained for a long time and +** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()] +** and [sqlite3_prepare16_v3()] assume that the prepared statement will +** be used just once or at most a few times and then destroyed using +** [sqlite3_finalize()] relatively soon. The current implementation acts +** on this hint by avoiding the use of [lookaside memory] so as not to +** deplete the limited store of lookaside memory. Future versions of +** SQLite may act on this hint differently. +** +** [[SQLITE_PREPARE_NORMALIZE]]
SQLITE_PREPARE_NORMALIZE
+**
The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used +** to be required for any prepared statement that wanted to use the +** [sqlite3_normalized_sql()] interface. However, the +** [sqlite3_normalized_sql()] interface is now available to all +** prepared statements, regardless of whether or not they use this +** flag. +** +** [[SQLITE_PREPARE_NO_VTAB]]
SQLITE_PREPARE_NO_VTAB
+**
The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler +** to return an error (error code SQLITE_ERROR) if the statement uses +** any virtual tables. +** +** [[SQLITE_PREPARE_DONT_LOG]]
SQLITE_PREPARE_DONT_LOG
+**
The SQLITE_PREPARE_DONT_LOG flag prevents SQL compiler +** errors from being sent to the error log defined by +** [SQLITE_CONFIG_LOG]. This can be used, for example, to do test +** compiles to see if some SQL syntax is well-formed, without generating +** messages on the global error log when it is not. If the test compile +** fails, the sqlite3_prepare_v3() call returns the same error indications +** with or without this flag; it just omits the call to [sqlite3_log()] that +** logs the error. +**
+*/ +#define SQLITE_PREPARE_PERSISTENT 0x01 +#define SQLITE_PREPARE_NORMALIZE 0x02 +#define SQLITE_PREPARE_NO_VTAB 0x04 +#define SQLITE_PREPARE_DONT_LOG 0x10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** METHOD: sqlite3 +** CONSTRUCTOR: sqlite3_stmt +** +** To execute an SQL statement, it must first be compiled into a byte-code +** program using one of these routines. Or, in other words, these routines +** are constructors for the [prepared statement] object. +** +** The preferred routine to use is [sqlite3_prepare_v2()]. The +** [sqlite3_prepare()] interface is legacy and should be avoided. +** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used +** for special purposes. +** +** The use of the UTF-8 interfaces is preferred, as SQLite currently +** does all parsing using UTF-8. The UTF-16 interfaces are provided +** as a convenience. The UTF-16 interfaces work by converting the +** input text into UTF-8, then invoking the corresponding UTF-8 interface. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(), +** and sqlite3_prepare_v3() +** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(), +** and sqlite3_prepare16_v3() use UTF-16. +** +** ^If the nByte argument is negative, then zSql is read up to the +** first zero terminator. ^If nByte is positive, then it is the maximum +** number of bytes read from zSql. When nByte is positive, zSql is read +** up to the first zero terminator or until the nByte bytes have been read, +** whichever comes first. ^If nByte is zero, then no prepared +** statement is generated. +** If the caller knows that the supplied string is nul-terminated, then +** there is a small performance advantage to passing an nByte parameter that +** is the number of bytes in the input string including +** the nul-terminator. +** Note that nByte measure the length of the input in bytes, not +** characters, even for the UTF-16 interfaces. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(), +** and sqlite3_prepare16_v3() interfaces are recommended for all new programs. +** The older interfaces (sqlite3_prepare() and sqlite3_prepare16()) +** are retained for backwards compatibility, but their use is discouraged. +** ^In the "vX" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
    +**
  1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] +** retries will occur before sqlite3_step() gives up and returns an error. +**
  2. +** +**
  3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
  4. +** +**
  5. +** ^If the specific value bound to a [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of a WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled. +**
  6. +**
+** +**

^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having +** the extra prepFlags parameter, which is a bit array consisting of zero or +** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The +** sqlite3_prepare_v2() interface works exactly the same as +** sqlite3_prepare_v3() with a zero prepFlags parameter. +*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v3( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v3( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** METHOD: sqlite3_stmt +** +** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 +** SQL text used to create [prepared statement] P if P was +** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], +** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()]. +** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 +** string containing the SQL text of prepared statement P with +** [bound parameters] expanded. +** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8 +** string containing the normalized SQL text of prepared statement P. The +** semantics used to normalize a SQL statement are unspecified and subject +** to change. At a minimum, literal values will be replaced with suitable +** placeholders. +** +** ^(For example, if a prepared statement is created using the SQL +** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 +** and parameter :xyz is unbound, then sqlite3_sql() will return +** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() +** will return "SELECT 2345,NULL".)^ +** +** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory +** is available to hold the result, or if the result would exceed the +** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. +** +** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of +** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time +** option causes sqlite3_expanded_sql() to always return NULL. +** +** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P) +** are managed by SQLite and are automatically freed when the prepared +** statement is finalized. +** ^The string returned by sqlite3_expanded_sql(P), on the other hand, +** is obtained from [sqlite3_malloc()] and must be freed by the application +** by passing it to [sqlite3_free()]. +** +** ^The sqlite3_normalized_sql() interface is only available if +** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined. +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); +SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); +#ifdef SQLITE_ENABLE_NORMALIZE +SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt); +#endif + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** METHOD: sqlite3_stmt +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**

+**    SELECT eval('DELETE FROM t1') FROM t2;
+** 
+** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since +** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and +** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so +** sqlite3_stmt_readonly() returns false for those commands. +** +** ^This routine returns false if there is any possibility that the +** statement might change the database file. ^A false return does +** not guarantee that the statement will change the database file. +** ^For example, an UPDATE statement might have a WHERE clause that +** makes it a no-op, but the sqlite3_stmt_readonly() result would still +** be false. ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a +** read-only no-op if the table already exists, but +** sqlite3_stmt_readonly() still returns false for such a statement. +** +** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN] +** statement, then sqlite3_stmt_readonly(X) returns the same value as +** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement +** METHOD: sqlite3_stmt +** +** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the +** prepared statement S is an EXPLAIN statement, or 2 if the +** statement S is an EXPLAIN QUERY PLAN. +** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is +** an ordinary statement or a NULL pointer. +*/ +SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Change The EXPLAIN Setting For A Prepared Statement +** METHOD: sqlite3_stmt +** +** The sqlite3_stmt_explain(S,E) interface changes the EXPLAIN +** setting for [prepared statement] S. If E is zero, then S becomes +** a normal prepared statement. If E is 1, then S behaves as if +** its SQL text began with "[EXPLAIN]". If E is 2, then S behaves as if +** its SQL text began with "[EXPLAIN QUERY PLAN]". +** +** Calling sqlite3_stmt_explain(S,E) might cause S to be reprepared. +** SQLite tries to avoid a reprepare, but a reprepare might be necessary +** on the first transition into EXPLAIN or EXPLAIN QUERY PLAN mode. +** +** Because of the potential need to reprepare, a call to +** sqlite3_stmt_explain(S,E) will fail with SQLITE_ERROR if S cannot be +** reprepared because it was created using [sqlite3_prepare()] instead of +** the newer [sqlite3_prepare_v2()] or [sqlite3_prepare_v3()] interfaces and +** hence has no saved SQL text with which to reprepare. +** +** Changing the explain setting for a prepared statement does not change +** the original SQL text for the statement. Hence, if the SQL text originally +** began with EXPLAIN or EXPLAIN QUERY PLAN, but sqlite3_stmt_explain(S,0) +** is called to convert the statement into an ordinary statement, the EXPLAIN +** or EXPLAIN QUERY PLAN keywords will still appear in the sqlite3_sql(S) +** output, even though the statement now acts like a normal SQL statement. +** +** This routine returns SQLITE_OK if the explain mode is successfully +** changed, or an error code if the explain mode could not be changed. +** The explain mode cannot be changed while a statement is active. +** Hence, it is good practice to call [sqlite3_reset(S)] +** immediately prior to calling sqlite3_stmt_explain(S,E). +*/ +SQLITE_API int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode); + +/* +** CAPI3REF: Determine If A Prepared Statement Has Been Reset +** METHOD: sqlite3_stmt +** +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** [prepared statement] S has been stepped at least once using +** [sqlite3_step(S)] but has neither run to completion (returned +** [SQLITE_DONE] from [sqlite3_step(S)]) nor +** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** interface returns false if S is a NULL pointer. If S is not a +** NULL pointer and is not a pointer to a valid [prepared statement] +** object, then the behavior is undefined and probably undesirable. +** +** This interface can be used in combination [sqlite3_next_stmt()] +** to locate all prepared statements associated with a database +** connection that are in need of being reset. This can be used, +** for example, in diagnostic routines to search for prepared +** statements that are holding a transaction open. +*/ +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. The +** [sqlite3_value_dup()] interface can be used to construct a new +** protected sqlite3_value from an unprotected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. An internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()] +** are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used as arguments +** to [sqlite3_result_value()], [sqlite3_bind_value()], and +** [sqlite3_value_dup()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct sqlite3_value sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** METHOD: sqlite3_stmt +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
    +**
  • ? +**
  • ?NNN +**
  • :VVV +**
  • @VVV +**
  • $VVV +**
+** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766). +** +** ^The third argument is the value to bind to the parameter. +** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter +** is ignored and the end result is the same as sqlite3_bind_null(). +** ^If the third parameter to sqlite3_bind_text() is not NULL, then +** it should be a pointer to well-formed UTF8 text. +** ^If the third parameter to sqlite3_bind_text16() is not NULL, then +** it should be a pointer to well-formed UTF16 text. +** ^If the third parameter to sqlite3_bind_text64() is not NULL, then +** it should be a pointer to a well-formed unicode string that is +** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16 +** otherwise. +** +** [[byte-order determination rules]] ^The byte-order of +** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF) +** found in first character, which is removed, or in the absence of a BOM +** the byte order is the native byte order of the host +** machine for sqlite3_bind_text16() or the byte order specified in +** the 6th parameter for sqlite3_bind_text64().)^ +** ^If UTF16 input text contains invalid unicode +** characters, then SQLite might change those invalid characters +** into the unicode replacement character: U+FFFD. +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** is negative, then the length of the string is +** the number of bytes up to the first zero terminator. +** If the fourth parameter to sqlite3_bind_blob() is negative, then +** the behavior is undefined. +** If a non-negative fourth parameter is provided to sqlite3_bind_text() +** or sqlite3_bind_text16() or sqlite3_bind_text64() then +** that parameter must be the byte offset +** where the NUL terminator would occur assuming the string were NUL +** terminated. If any NUL characters occurs at byte offsets less than +** the value of the fourth parameter then the resulting string value will +** contain embedded NULs. The result of expressions involving strings +** with embedded NULs is undefined. +** +** ^The fifth argument to the BLOB and string binding interfaces controls +** or indicates the lifetime of the object referenced by the third parameter. +** These three options exist: +** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished +** with it may be passed. ^It is called to dispose of the BLOB or string even +** if the call to the bind API fails, except the destructor is not called if +** the third parameter is a NULL pointer or the fourth parameter is negative. +** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that +** the application remains responsible for disposing of the object. ^In this +** case, the object and the provided pointer to it must remain valid until +** either the prepared statement is finalized or the same SQL parameter is +** bound to something else, whichever occurs sooner. +** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the +** object is to be copied prior to the return from sqlite3_bind_*(). ^The +** object and pointer to it must remain valid until then. ^SQLite will then +** manage the lifetime of its private copy. +** +** ^The sixth argument to sqlite3_bind_text64() must be one of +** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] +** to specify the encoding of the text in the third parameter. If +** the sixth argument to sqlite3_bind_text64() is not one of the +** allowed values shown above, or if the text encoding is different +** from the encoding specified by the sixth parameter, then the behavior +** is undefined. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in +** [prepared statement] S to have an SQL value of NULL, but to also be +** associated with the pointer P of type T. ^D is either a NULL pointer or +** a pointer to a destructor function for P. ^SQLite will invoke the +** destructor D with a single argument of P when it is finished using +** P. The T parameter should be a static string, preferably a string +** literal. The sqlite3_bind_pointer() routine is part of the +** [pointer passing interface] added for SQLite 3.20.0. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB +** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or +** [SQLITE_MAX_LENGTH]. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, + void(*)(void*)); +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, + void(*)(void*), unsigned char encoding); +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*)); +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); +SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); + +/* +** CAPI3REF: Number Of SQL Parameters +** METHOD: sqlite3_stmt +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** METHOD: sqlite3_stmt +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()], +** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** METHOD: sqlite3_stmt +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or +** [sqlite3_prepare16_v3()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_name()]. +*/ +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** METHOD: sqlite3_stmt +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** METHOD: sqlite3_stmt +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^If this routine returns 0, that means the +** [prepared statement] returns no data (for example an [UPDATE]). +** ^However, just because this routine returns a positive number does not +** mean that one or more rows of data will be returned. ^A SELECT statement +** will always have a positive sqlite3_column_count() but depending on the +** WHERE clause constraints and the table content, it might return no rows. +** +** See also: [sqlite3_data_count()] +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** METHOD: sqlite3_stmt +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** METHOD: sqlite3_stmt +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routines might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** METHOD: sqlite3_stmt +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** METHOD: sqlite3_stmt +** +** After a [prepared statement] has been prepared using any of +** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()], +** or [sqlite3_prepare16_v3()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "vX" interfaces +** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()], +** [sqlite3_prepare16_v2()] or the older legacy +** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "vX" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within an +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]), +** sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()] +** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "vX" interfaces is recommended. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** METHOD: sqlite3_stmt +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column()] family of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to +** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) +** will return non-zero if previous call to [sqlite3_step](P) returned +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] +** where it always returns zero since each step of that multi-step +** pragma returns 0 columns of data. +** +** See also: [sqlite3_column_count()] +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
    +**
  • 64-bit signed integer +**
  • 64-bit IEEE floating point number +**
  • string +**
  • BLOB +**
  • NULL +**
)^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** METHOD: sqlite3_stmt +** +** Summary: +**
+**
sqlite3_column_blobBLOB result +**
sqlite3_column_doubleREAL result +**
sqlite3_column_int32-bit INTEGER result +**
sqlite3_column_int6464-bit INTEGER result +**
sqlite3_column_textUTF-8 TEXT result +**
sqlite3_column_text16UTF-16 TEXT result +**
sqlite3_column_valueThe result as an +** [sqlite3_value|unprotected sqlite3_value] object. +**
    +**
sqlite3_column_bytesSize of a BLOB +** or a UTF-8 TEXT result in bytes +**
sqlite3_column_bytes16   +** →  Size of UTF-16 +** TEXT in bytes +**
sqlite3_column_typeDefault +** datatype of the result +**
+** +** Details: +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16) +** each return the value of a result column in a specific data format. If +** the result column is not initially in the requested format (for example, +** if the query returns an integer but the sqlite3_column_text() interface +** is used to extract the value) then an automatic type conversion is performed. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. +** The return value of sqlite3_column_type() can be used to decide which +** of the first six interface should be used to extract the column value. +** The value returned by sqlite3_column_type() is only meaningful if no +** automatic type conversions have occurred for the value in question. +** After a type conversion, the result of calling sqlite3_column_type() +** is undefined, though harmless. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes() +** or sqlite3_column_bytes16() interfaces can be used to determine the size +** of that BLOB or string. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero-terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^Strings returned by sqlite3_column_text16() always have the endianness +** which is native to the platform, regardless of the text encoding set +** for the database. +** +** Warning: ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. In a multithreaded environment, +** an unprotected sqlite3_value object may only be used safely with +** [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], the behavior is not threadsafe. +** Hence, the sqlite3_column_value() interface +** is normally only useful within the implementation of +** [application-defined SQL functions] or [virtual tables], not within +** top-level application code. +** +** These routines may attempt to convert the datatype of the result. +** ^For example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
+** +**
Internal
Type
Requested
Type
Conversion +** +**
NULL INTEGER Result is 0 +**
NULL FLOAT Result is 0.0 +**
NULL TEXT Result is a NULL pointer +**
NULL BLOB Result is a NULL pointer +**
INTEGER FLOAT Convert from integer to float +**
INTEGER TEXT ASCII rendering of the integer +**
INTEGER BLOB Same as INTEGER->TEXT +**
FLOAT INTEGER [CAST] to INTEGER +**
FLOAT TEXT ASCII rendering of the float +**
FLOAT BLOB [CAST] to BLOB +**
TEXT INTEGER [CAST] to INTEGER +**
TEXT FLOAT [CAST] to REAL +**
TEXT BLOB No change +**
BLOB INTEGER [CAST] to INTEGER +**
BLOB FLOAT [CAST] to REAL +**
BLOB TEXT [CAST] to TEXT, ensure zero terminator +**
+**
)^ +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
    +**
  • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
  • +**
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
  • +**
  • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
  • +**
+** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest policy is to invoke these routines +** in one of the following ways: +** +**
    +**
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • +**
+** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** As long as the input parameters are correct, these routines will only +** fail if an out-of-memory error occurs during a format conversion. +** Only the following subset of interfaces are subject to out-of-memory +** errors: +** +**
    +**
  • sqlite3_column_blob() +**
  • sqlite3_column_text() +**
  • sqlite3_column_text16() +**
  • sqlite3_column_bytes() +**
  • sqlite3_column_bytes16() +**
+** +** If an out-of-memory error occurs, then the return value from these +** routines is the same as if the column had contained an SQL NULL value. +** Valid SQL NULL returns can be distinguished from out-of-memory errors +** by invoking the [sqlite3_errcode()] immediately after the suspect +** return value is obtained and before any +** other SQLite interface is called on the same [database connection]. +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** DESTRUCTOR: sqlite3_stmt +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** METHOD: sqlite3_stmt +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^The return code from [sqlite3_reset(S)] indicates whether or not +** the previous evaluation of prepared statement S completed successfully. +** ^If [sqlite3_step(S)] has never before been called on S or if +** [sqlite3_step(S)] has not been called since the previous call +** to [sqlite3_reset(S)], then [sqlite3_reset(S)] will return +** [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** ^The [sqlite3_reset(S)] interface might also return an [error code] +** if there were no prior errors but the process of resetting +** the prepared statement caused a new error. ^For example, if an +** [INSERT] statement with a [RETURNING] clause is only stepped one time, +** that one call to [sqlite3_step(S)] might return SQLITE_ROW but +** the overall statement might still fail and the [sqlite3_reset(S)] call +** might return SQLITE_BUSY if locking constraints prevent the +** database change from committing. Therefore, it is important that +** applications check the return code from [sqlite3_reset(S)] even if +** no prior call to [sqlite3_step(S)] indicated a problem. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** METHOD: sqlite3 +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** the three "sqlite3_create_function*" routines are the text encoding +** expected for the second parameter (the name of the function being +** created) and the presence or absence of a destructor callback for +** the application data pointer. Function sqlite3_create_window_function() +** is similar, but allows the user to supply the extra callback functions +** needed by [aggregate window functions]. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. The application should set this parameter to +** [SQLITE_UTF16LE] if the function implementation invokes +** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the +** implementation invokes [sqlite3_value_text16be()] on an input, or +** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] +** otherwise. ^The same SQL function may be registered multiple times using +** different preferred text encodings, with different implementations for +** each encoding. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** +** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC] +** to signal that the function will always return the same result given +** the same inputs within a single SQL statement. Most SQL functions are +** deterministic. The built-in [random()] SQL function is an example of a +** function that is not deterministic. The SQLite query planner is able to +** perform additional optimizations on deterministic functions, so use +** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. +** +** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY] +** flag, which if present prevents the function from being invoked from +** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions, +** index expressions, or the WHERE clause of partial indexes. +** +** For best security, the [SQLITE_DIRECTONLY] flag is recommended for +** all application-defined SQL functions that do not need to be +** used inside of triggers, view, CHECK constraints, or other elements of +** the database schema. This flags is especially recommended for SQL +** functions that have side effects or reveal internal application state. +** Without this flag, an attacker might be able to modify the schema of +** a database file to include invocations of the function with parameters +** chosen by the attacker, which the application will then execute when +** the database file is opened and read. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters passed to the three +** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL pointers for all three function +** callbacks. +** +** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue +** and xInverse) passed to sqlite3_create_window_function are pointers to +** C-language callbacks that implement the new function. xStep and xFinal +** must both be non-NULL. xValue and xInverse may either both be NULL, in +** which case a regular aggregate function is created, or must both be +** non-NULL, in which case the new function may be used as either an aggregate +** or aggregate window function. More details regarding the implementation +** of aggregate window functions are +** [user-defined window functions|available here]. +** +** ^(If the final parameter to sqlite3_create_function_v2() or +** sqlite3_create_window_function() is not NULL, then it is destructor for +** the application data pointer. The destructor is invoked when the function +** is deleted, either by being overloaded or when the database connection +** closes.)^ ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. ^When the destructor callback is +** invoked, it is passed a single argument which is a copy of the application +** data pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_window_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void (*xValue)(sqlite3_context*), + void (*xInverse)(sqlite3_context*,int,sqlite3_value**), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ +#define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ +#define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* Deprecated */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Function Flags +** +** These constants may be ORed together with the +** [SQLITE_UTF8 | preferred text encoding] as the fourth argument +** to [sqlite3_create_function()], [sqlite3_create_function16()], or +** [sqlite3_create_function_v2()]. +** +**
+** [[SQLITE_DETERMINISTIC]]
SQLITE_DETERMINISTIC
+** The SQLITE_DETERMINISTIC flag means that the new function always gives +** the same output when the input parameters are the same. +** The [abs|abs() function] is deterministic, for example, but +** [randomblob|randomblob()] is not. Functions must +** be deterministic in order to be used in certain contexts such as +** with the WHERE clause of [partial indexes] or in [generated columns]. +** SQLite might also optimize deterministic functions by factoring them +** out of inner loops. +**
+** +** [[SQLITE_DIRECTONLY]]
SQLITE_DIRECTONLY
+** The SQLITE_DIRECTONLY flag means that the function may only be invoked +** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in +** schema structures such as [CHECK constraints], [DEFAULT clauses], +** [expression indexes], [partial indexes], or [generated columns]. +**

+** The SQLITE_DIRECTONLY flag is recommended for any +** [application-defined SQL function] +** that has side-effects or that could potentially leak sensitive information. +** This will prevent attacks in which an application is tricked +** into using a database file that has had its schema surreptitiously +** modified to invoke the application-defined function in ways that are +** harmful. +**

+** Some people say it is good practice to set SQLITE_DIRECTONLY on all +** [application-defined SQL functions], regardless of whether or not they +** are security sensitive, as doing so prevents those functions from being used +** inside of the database schema, and thus ensures that the database +** can be inspected and modified using generic tools (such as the [CLI]) +** that do not have access to the application-defined functions. +**

+** +** [[SQLITE_INNOCUOUS]]
SQLITE_INNOCUOUS
+** The SQLITE_INNOCUOUS flag means that the function is unlikely +** to cause problems even if misused. An innocuous function should have +** no side effects and should not depend on any values other than its +** input parameters. The [abs|abs() function] is an example of an +** innocuous function. +** The [load_extension() SQL function] is not innocuous because of its +** side effects. +**

SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not +** exactly the same. The [random|random() function] is an example of a +** function that is innocuous but not deterministic. +**

Some heightened security settings +** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF]) +** disable the use of SQL functions inside views and triggers and in +** schema structures such as [CHECK constraints], [DEFAULT clauses], +** [expression indexes], [partial indexes], and [generated columns] unless +** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions +** are innocuous. Developers are advised to avoid using the +** SQLITE_INNOCUOUS flag for application-defined functions unless the +** function has been carefully audited and found to be free of potentially +** security-adverse side-effects and information-leaks. +**

+** +** [[SQLITE_SUBTYPE]]
SQLITE_SUBTYPE
+** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call +** [sqlite3_value_subtype()] to inspect the sub-types of its arguments. +** This flag instructs SQLite to omit some corner-case optimizations that +** might disrupt the operation of the [sqlite3_value_subtype()] function, +** causing it to return zero rather than the correct subtype(). +** All SQL functions that invoke [sqlite3_value_subtype()] should have this +** property. If the SQLITE_SUBTYPE property is omitted, then the return +** value from [sqlite3_value_subtype()] might sometimes be zero even though +** a non-zero subtype was specified by the function argument expression. +** +** [[SQLITE_RESULT_SUBTYPE]]
SQLITE_RESULT_SUBTYPE
+** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call +** [sqlite3_result_subtype()] to cause a sub-type to be associated with its +** result. +** Every function that invokes [sqlite3_result_subtype()] should have this +** property. If it does not, then the call to [sqlite3_result_subtype()] +** might become a no-op if the function is used as term in an +** [expression index]. On the other hand, SQL functions that never invoke +** [sqlite3_result_subtype()] should avoid setting this property, as the +** purpose of this property is to disable certain optimizations that are +** incompatible with subtypes. +** +** [[SQLITE_SELFORDER1]]
SQLITE_SELFORDER1
+** The SQLITE_SELFORDER1 flag indicates that the function is an aggregate +** that internally orders the values provided to the first argument. The +** ordered-set aggregate SQL notation with a single ORDER BY term can be +** used to invoke this function. If the ordered-set aggregate notation is +** used on a function that lacks this flag, then an error is raised. Note +** that the ordered-set aggregate syntax is only available if SQLite is +** built using the -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES compile-time option. +**
+**
+*/ +#define SQLITE_DETERMINISTIC 0x000000800 +#define SQLITE_DIRECTONLY 0x000080000 +#define SQLITE_SUBTYPE 0x000100000 +#define SQLITE_INNOCUOUS 0x000200000 +#define SQLITE_RESULT_SUBTYPE 0x001000000 +#define SQLITE_SELFORDER1 0x002000000 + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To encourage programmers to avoid +** these functions, we will not explain what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), + void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Values +** METHOD: sqlite3_value +** +** Summary: +**
+**
sqlite3_value_blobBLOB value +**
sqlite3_value_doubleREAL value +**
sqlite3_value_int32-bit INTEGER value +**
sqlite3_value_int6464-bit INTEGER value +**
sqlite3_value_pointerPointer value +**
sqlite3_value_textUTF-8 TEXT value +**
sqlite3_value_text16UTF-16 TEXT value in +** the native byteorder +**
sqlite3_value_text16beUTF-16be TEXT value +**
sqlite3_value_text16leUTF-16le TEXT value +**
    +**
sqlite3_value_bytesSize of a BLOB +** or a UTF-8 TEXT in bytes +**
sqlite3_value_bytes16   +** →  Size of UTF-16 +** TEXT in bytes +**
sqlite3_value_typeDefault +** datatype of the value +**
sqlite3_value_numeric_type   +** →  Best numeric datatype of the value +**
sqlite3_value_nochange   +** →  True if the column is unchanged in an UPDATE +** against a virtual table. +**
sqlite3_value_frombind   +** →  True if value originated from a [bound parameter] +**
+** +** Details: +** +** These routines extract type, size, and content information from +** [protected sqlite3_value] objects. Protected sqlite3_value objects +** are used to pass parameter information into the functions that +** implement [application-defined SQL functions] and [virtual tables]. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** is not threadsafe. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^If [sqlite3_value] object V was initialized +** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)] +** and if X and Y are strings that compare equal according to strcmp(X,Y), +** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise, +** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() +** routine is part of the [pointer passing interface] added for SQLite 3.20.0. +** +** ^(The sqlite3_value_type(V) interface returns the +** [SQLITE_INTEGER | datatype code] for the initial datatype of the +** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^ +** Other interfaces might change the datatype for an sqlite3_value object. +** For example, if the datatype is initially SQLITE_INTEGER and +** sqlite3_value_text(V) is called to extract a text value for that +** integer, then subsequent calls to sqlite3_value_type(V) might return +** SQLITE_TEXT. Whether or not a persistent internal datatype conversion +** occurs is undefined and may change from one release of SQLite to the next. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** ^Within the [xUpdate] method of a [virtual table], the +** sqlite3_value_nochange(X) interface returns true if and only if +** the column corresponding to X is unchanged by the UPDATE operation +** that the xUpdate method call was invoked to implement and if +** and the prior [xColumn] method call that was invoked to extracted +** the value for that column returned without setting a result (probably +** because it queried [sqlite3_vtab_nochange()] and found that the column +** was unchanging). ^Within an [xUpdate] method, any value for which +** sqlite3_value_nochange(X) is true will in all other respects appear +** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other +** than within an [xUpdate] method call for an UPDATE statement, then +** the return value is arbitrary and meaningless. +** +** ^The sqlite3_value_frombind(X) interface returns non-zero if the +** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()] +** interfaces. ^If X comes from an SQL literal value, or a table column, +** or an expression, then sqlite3_value_frombind(X) returns zero. +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +** +** As long as the input parameter is correct, these routines can only +** fail if an out-of-memory error occurs during a format conversion. +** Only the following subset of interfaces are subject to out-of-memory +** errors: +** +**
    +**
  • sqlite3_value_blob() +**
  • sqlite3_value_text() +**
  • sqlite3_value_text16() +**
  • sqlite3_value_text16le() +**
  • sqlite3_value_text16be() +**
  • sqlite3_value_bytes() +**
  • sqlite3_value_bytes16() +**
+** +** If an out-of-memory error occurs, then the return value from these +** routines is the same as if the column had contained an SQL NULL value. +** Valid SQL NULL returns can be distinguished from out-of-memory errors +** by invoking the [sqlite3_errcode()] immediately after the suspect +** return value is obtained and before any +** other SQLite interface is called on the same [database connection]. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); +SQLITE_API double sqlite3_value_double(sqlite3_value*); +SQLITE_API int sqlite3_value_int(sqlite3_value*); +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*); +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); +SQLITE_API int sqlite3_value_type(sqlite3_value*); +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); +SQLITE_API int sqlite3_value_nochange(sqlite3_value*); +SQLITE_API int sqlite3_value_frombind(sqlite3_value*); + +/* +** CAPI3REF: Report the internal text encoding state of an sqlite3_value object +** METHOD: sqlite3_value +** +** ^(The sqlite3_value_encoding(X) interface returns one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE] according to the current text encoding +** of the value X, assuming that X has type TEXT.)^ If sqlite3_value_type(X) +** returns something other than SQLITE_TEXT, then the return value from +** sqlite3_value_encoding(X) is meaningless. ^Calls to +** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], [sqlite3_value_text16be(X)], +** [sqlite3_value_text16le(X)], [sqlite3_value_bytes(X)], or +** [sqlite3_value_bytes16(X)] might change the encoding of the value X and +** thus change the return from subsequent calls to sqlite3_value_encoding(X). +** +** This routine is intended for used by applications that test and validate +** the SQLite implementation. This routine is inquiring about the opaque +** internal state of an [sqlite3_value] object. Ordinary applications should +** not need to know what the internal state of an sqlite3_value object is and +** hence should not need to use this interface. +*/ +SQLITE_API int sqlite3_value_encoding(sqlite3_value*); + +/* +** CAPI3REF: Finding The Subtype Of SQL Values +** METHOD: sqlite3_value +** +** The sqlite3_value_subtype(V) function returns the subtype for +** an [application-defined SQL function] argument V. The subtype +** information can be used to pass a limited amount of context from +** one SQL function to another. Use the [sqlite3_result_subtype()] +** routine to set the subtype for the return value of an SQL function. +** +** Every [application-defined SQL function] that invokes this interface +** should include the [SQLITE_SUBTYPE] property in the text +** encoding argument when the function is [sqlite3_create_function|registered]. +** If the [SQLITE_SUBTYPE] property is omitted, then sqlite3_value_subtype() +** might return zero instead of the upstream subtype in some corner cases. +*/ +SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); + +/* +** CAPI3REF: Copy And Free SQL Values +** METHOD: sqlite3_value +** +** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] +** object D and returns a pointer to that copy. ^The [sqlite3_value] returned +** is a [protected sqlite3_value] object even if the input is not. +** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a +** memory allocation fails. ^If V is a [pointer value], then the result +** of sqlite3_value_dup(V) is a NULL value. +** +** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object +** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer +** then sqlite3_value_free(V) is a harmless no-op. +*/ +SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); +SQLITE_API void sqlite3_value_free(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** METHOD: sqlite3_context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite allocates +** N bytes of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer +** when first called if N is less than or equal to zero or if a memory +** allocation error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in any subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ Within the xFinal callback, it is customary to set +** N=0 in calls to sqlite3_aggregate_context(C,N) so that no +** pointless memory allocations occur. +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** METHOD: sqlite3_context +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** METHOD: sqlite3_context +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** METHOD: sqlite3_context +** +** These functions may be used by (non-aggregate) SQL functions to +** associate auxiliary data with argument values. If the same argument +** value is passed to multiple invocations of the same SQL function during +** query execution, under some circumstances the associated auxiliary data +** might be preserved. An example of where this might be useful is in a +** regular-expression matching function. The compiled version of the regular +** expression can be stored as auxiliary data associated with the pattern string. +** Then as long as the pattern string remains the same, +** the compiled regular expression can be reused on multiple +** invocations of the same function. +** +** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data +** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument +** value to the application-defined function. ^N is zero for the left-most +** function argument. ^If there is no auxiliary data +** associated with the function argument, the sqlite3_get_auxdata(C,N) interface +** returns a NULL pointer. +** +** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the +** N-th argument of the application-defined function. ^Subsequent +** calls to sqlite3_get_auxdata(C,N) return P from the most recent +** sqlite3_set_auxdata(C,N,P,X) call if the auxiliary data is still valid or +** NULL if the auxiliary data has been discarded. +** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, +** SQLite will invoke the destructor function X with parameter P exactly +** once, when the auxiliary data is discarded. +** SQLite is free to discard the auxiliary data at any time, including:
    +**
  • ^(when the corresponding function parameter changes)^, or +**
  • ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the +** SQL statement)^, or +**
  • ^(when sqlite3_set_auxdata() is invoked again on the same +** parameter)^, or +**
  • ^(during the original sqlite3_set_auxdata() call when a memory +** allocation error occurs.)^ +**
  • ^(during the original sqlite3_set_auxdata() call if the function +** is evaluated during query planning instead of during query execution, +** as sometimes happens with [SQLITE_ENABLE_STAT4].)^
+** +** Note the last two bullets in particular. The destructor X in +** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the +** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() +** should be called near the end of the function implementation and the +** function implementation should not make any use of P after +** sqlite3_set_auxdata() has been called. Furthermore, a call to +** sqlite3_get_auxdata() that occurs immediately after a corresponding call +** to sqlite3_set_auxdata() might still return NULL if an out-of-memory +** condition occurred during the sqlite3_set_auxdata() call or if the +** function is being evaluated during query planning rather than during +** query execution. +** +** ^(In practice, auxiliary data is preserved between function calls for +** function parameters that are compile-time constants, including literal +** values and [parameters] and expressions composed from the same.)^ +** +** The value of the N parameter to these interfaces should be non-negative. +** Future enhancements may make use of negative N values to define new +** kinds of function caching behavior. +** +** These routines must be called from the same thread in which +** the SQL function is running. +** +** See also: [sqlite3_get_clientdata()] and [sqlite3_set_clientdata()]. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + +/* +** CAPI3REF: Database Connection Client Data +** METHOD: sqlite3 +** +** These functions are used to associate one or more named pointers +** with a [database connection]. +** A call to sqlite3_set_clientdata(D,N,P,X) causes the pointer P +** to be attached to [database connection] D using name N. Subsequent +** calls to sqlite3_get_clientdata(D,N) will return a copy of pointer P +** or a NULL pointer if there were no prior calls to +** sqlite3_set_clientdata() with the same values of D and N. +** Names are compared using strcmp() and are thus case sensitive. +** +** If P and X are both non-NULL, then the destructor X is invoked with +** argument P on the first of the following occurrences: +**
    +**
  • An out-of-memory error occurs during the call to +** sqlite3_set_clientdata() which attempts to register pointer P. +**
  • A subsequent call to sqlite3_set_clientdata(D,N,P,X) is made +** with the same D and N parameters. +**
  • The database connection closes. SQLite does not make any guarantees +** about the order in which destructors are called, only that all +** destructors will be called exactly once at some point during the +** database connection closing process. +**
+** +** SQLite does not do anything with client data other than invoke +** destructors on the client data at the appropriate time. The intended +** use for client data is to provide a mechanism for wrapper libraries +** to store additional information about an SQLite database connection. +** +** There is no limit (other than available memory) on the number of different +** client data pointers (with different names) that can be attached to a +** single database connection. However, the implementation is optimized +** for the case of having only one or two different client data names. +** Applications and wrapper libraries are discouraged from using more than +** one client data name each. +** +** There is no way to enumerate the client data pointers +** associated with a database connection. The N parameter can be thought +** of as a secret key such that only code that knows the secret key is able +** to access the associated data. +** +** Security Warning: These interfaces should not be exposed in scripting +** languages or in other circumstances where it might be possible for an +** an attacker to invoke them. Any agent that can invoke these interfaces +** can probably also take control of the process. +** +** Database connection client data is only available for SQLite +** version 3.44.0 ([dateof:3.44.0]) and later. +** +** See also: [sqlite3_set_auxdata()] and [sqlite3_get_auxdata()]. +*/ +SQLITE_API void *sqlite3_get_clientdata(sqlite3*,const char*); +SQLITE_API int sqlite3_set_clientdata(sqlite3*, const char*, void*, void(*)(void*)); + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** METHOD: sqlite3_context +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) +** interfaces set the result of the application-defined function to be +** a BLOB containing all zero bytes and N bytes in size. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 using +** the same [byte-order determination rules] as [sqlite3_bind_text16()]. +** ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** error indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** error indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^The sqlite3_result_text64() interface sets the return value of an +** application-defined function to be a text string in an encoding +** specified by the fifth (and last) parameter, which must be one +** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces +** other than sqlite3_result_text64() is negative, then SQLite computes +** the string length itself by searching the 2nd parameter for the first +** zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. If the 3rd parameter is non-negative, then it +** must be the byte offset into the string where the NUL terminator would +** appear if the string where NUL terminated. If any NUL characters occur +** in the string at a byte offset that is less than the value of the 3rd +** parameter, then the resulting string will contain embedded NULs and the +** result of expressions operating on strings with embedded NULs is undefined. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained +** from [sqlite3_malloc()] before it returns. +** +** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and +** sqlite3_result_text16be() routines, and for sqlite3_result_text64() +** when the encoding is not UTF8, if the input UTF16 begins with a +** byte-order mark (BOM, U+FEFF) then the BOM is removed from the +** string and the rest of the string is interpreted according to the +** byte-order specified by the BOM. ^The byte-order specified by +** the BOM at the beginning of the text overrides the byte-order +** specified by the interface procedure. ^So, for example, if +** sqlite3_result_text16le() is invoked with text that begins +** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the +** first two bytes of input are skipped and the remaining input +** is interpreted as UTF16BE text. +** +** ^For UTF16 input text to the sqlite3_result_text16(), +** sqlite3_result_text16be(), sqlite3_result_text16le(), and +** sqlite3_result_text64() routines, if the text contains invalid +** UTF16 characters, the invalid characters might be converted +** into the unicode replacement character, U+FFFD. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy of the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an +** SQL NULL value, just like [sqlite3_result_null(C)], except that it +** also associates the host-language pointer P or type T with that +** NULL value such that the pointer can be retrieved within an +** [application-defined SQL function] using [sqlite3_value_pointer()]. +** ^If the D parameter is not NULL, then it is a pointer to a destructor +** for the P parameter. ^SQLite invokes D with P as its only argument +** when SQLite is finished with P. The T parameter should be a static +** string and preferably a string literal. The sqlite3_result_pointer() +** routine is part of the [pointer passing interface] added for SQLite 3.20.0. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, + sqlite3_uint64,void(*)(void*)); +SQLITE_API void sqlite3_result_double(sqlite3_context*, double); +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +SQLITE_API void sqlite3_result_null(sqlite3_context*); +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, + void(*)(void*), unsigned char encoding); +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*)); +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); +SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); + + +/* +** CAPI3REF: Setting The Subtype Of An SQL Function +** METHOD: sqlite3_context +** +** The sqlite3_result_subtype(C,T) function causes the subtype of +** the result from the [application-defined SQL function] with +** [sqlite3_context] C to be the value T. Only the lower 8 bits +** of the subtype T are preserved in current versions of SQLite; +** higher order bits are discarded. +** The number of subtype bytes preserved by SQLite might increase +** in future releases of SQLite. +** +** Every [application-defined SQL function] that invokes this interface +** should include the [SQLITE_RESULT_SUBTYPE] property in its +** text encoding argument when the SQL function is +** [sqlite3_create_function|registered]. If the [SQLITE_RESULT_SUBTYPE] +** property is omitted from the function that invokes sqlite3_result_subtype(), +** then in some cases the sqlite3_result_subtype() might fail to set +** the result subtype. +** +** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any +** SQL function that invokes the sqlite3_result_subtype() interface +** and that does not have the SQLITE_RESULT_SUBTYPE property will raise +** an error. Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1 +** by default. +*/ +SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); + +/* +** CAPI3REF: Define New Collating Sequences +** METHOD: sqlite3 +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
    +**
  • [SQLITE_UTF8], +**
  • [SQLITE_UTF16LE], +**
  • [SQLITE_UTF16BE], +**
  • [SQLITE_UTF16], or +**
  • [SQLITE_UTF16_ALIGNED]. +**
)^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCompare. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is an application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCompare, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCompare argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The two integer parameters to the collating +** function callback are the length of the two strings, in bytes. The collating +** function must return an integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must always return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
    +**
  1. If A==B then B==A. +**
  2. If A==B and B==C then A==C. +**
  3. If A<B THEN B>A. +**
  4. If A<B and B<C then A<C. +**
+** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +SQLITE_API int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** METHOD: sqlite3 +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +SQLITE_API int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +SQLITE_API void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +** +** If a negative argument is passed to sqlite3_sleep() the results vary by +** VFS and operating system. Some system treat a negative argument as an +** instruction to sleep forever. Others understand it to mean do not sleep +** at all. ^In SQLite version 3.42.0 and later, a negative +** argument passed into sqlite3_sleep() is changed to zero before it is relayed +** down into the xSleep method of the VFS. +*/ +SQLITE_API int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** Applications are strongly discouraged from using this global variable. +** It is required to set a temporary folder on Windows Runtime (WinRT). +** But for all other platforms, it is highly recommended that applications +** neither read nor write this variable. This global variable is a relic +** that exists for backwards compatibility of legacy applications and should +** be avoided in new projects. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +** Except when requested by the [temp_store_directory pragma], SQLite +** does not free the memory that sqlite3_temp_directory points to. If +** the application wants that memory to be freed, it must do +** so itself, taking care to only do so after all [database connection] +** objects have been destroyed. +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** features that require the use of temporary files may fail. Here is an +** example of how to do this using C++ with the Windows Runtime: +** +**
+** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
+**       TemporaryFolder->Path->Data();
+** char zPathBuf[MAX_PATH + 1];
+** memset(zPathBuf, 0, sizeof(zPathBuf));
+** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
+**       NULL, NULL);
+** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
+** 
+*/ +SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Name Of The Folder Holding Database Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all database files +** specified with a relative pathname and created or accessed by +** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** to be relative to that directory.)^ ^If this variable is a NULL +** pointer, then SQLite assumes that all database files specified +** with a relative pathname are relative to the current directory +** for the process. Only the windows VFS makes use of this global +** variable; it is ignored by the unix VFS. +** +** Changing the value of this variable while a database connection is +** open can result in a corrupt database. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [data_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [data_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [data_store_directory pragma] should be avoided. +*/ +SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory; + +/* +** CAPI3REF: Win32 Specific Interface +** +** These interfaces are available only on Windows. The +** [sqlite3_win32_set_directory] interface is used to set the value associated +** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to +** zValue, depending on the value of the type parameter. The zValue parameter +** should be NULL to cause the previous value to be freed via [sqlite3_free]; +** a non-NULL value will be copied into memory obtained from [sqlite3_malloc] +** prior to being used. The [sqlite3_win32_set_directory] interface returns +** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported, +** or [SQLITE_NOMEM] if memory could not be allocated. The value of the +** [sqlite3_data_directory] variable is intended to act as a replacement for +** the current directory on the sub-platforms of Win32 where that concept is +** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and +** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the +** sqlite3_win32_set_directory interface except the string parameter must be +** UTF-8 or UTF-16, respectively. +*/ +SQLITE_API int sqlite3_win32_set_directory( + unsigned long type, /* Identifier for directory being set or reset */ + void *zValue /* New value for directory being set or reset */ +); +SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue); +SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue); + +/* +** CAPI3REF: Win32 Directory Types +** +** These macros are only available on Windows. They define the allowed values +** for the type argument to the [sqlite3_win32_set_directory] interface. +*/ +#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1 +#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2 + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** METHOD: sqlite3 +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** METHOD: sqlite3_stmt +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Return The Schema Name For A Database Connection +** METHOD: sqlite3 +** +** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name +** for the N-th database on database connection D, or a NULL pointer of N is +** out of range. An N value of 0 means the main database file. An N of 1 is +** the "temp" schema. Larger values of N correspond to various ATTACH-ed +** databases. +** +** Space to hold the string that is returned by sqlite3_db_name() is managed +** by SQLite itself. The string might be deallocated by any operation that +** changes the schema, including [ATTACH] or [DETACH] or calls to +** [sqlite3_serialize()] or [sqlite3_deserialize()], even operations that +** occur on a different thread. Applications that need to +** remember the string long-term should make their own copy. Applications that +** are accessing the same database connection simultaneously on multiple +** threads should mutex-protect calls to this API and should make their own +** private copy of the result prior to releasing the mutex. +*/ +SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N); + +/* +** CAPI3REF: Return The Filename For A Database Connection +** METHOD: sqlite3 +** +** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename +** associated with database N of connection D. +** ^If there is no attached database N on the database +** connection D, or if database N is a temporary or in-memory database, then +** this function will return either a NULL pointer or an empty string. +** +** ^The string value returned by this routine is owned and managed by +** the database connection. ^The value will be valid until the database N +** is [DETACH]-ed or until the database connection closes. +** +** ^The filename returned by this function is the output of the +** xFullPathname method of the [VFS]. ^In other words, the filename +** will be an absolute pathname, even if the filename used +** to open the database originally was a URI or relative pathname. +** +** If the filename pointer returned by this routine is not NULL, then it +** can be used as the filename input parameter to these routines: +**
    +**
  • [sqlite3_uri_parameter()] +**
  • [sqlite3_uri_boolean()] +**
  • [sqlite3_uri_int64()] +**
  • [sqlite3_filename_database()] +**
  • [sqlite3_filename_journal()] +**
  • [sqlite3_filename_wal()] +**
+*/ +SQLITE_API sqlite3_filename sqlite3_db_filename(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Determine if a database is read-only +** METHOD: sqlite3 +** +** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** of connection D is read-only, 0 if it is read/write, or -1 if N is not +** the name of a database on connection D. +*/ +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Determine the transaction state of a database +** METHOD: sqlite3 +** +** ^The sqlite3_txn_state(D,S) interface returns the current +** [transaction state] of schema S in database connection D. ^If S is NULL, +** then the highest transaction state of any schema on database connection D +** is returned. Transaction states are (in order of lowest to highest): +**
    +**
  1. SQLITE_TXN_NONE +**
  2. SQLITE_TXN_READ +**
  3. SQLITE_TXN_WRITE +**
+** ^If the S argument to sqlite3_txn_state(D,S) is not the name of +** a valid schema, then -1 is returned. +*/ +SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema); + +/* +** CAPI3REF: Allowed return values from sqlite3_txn_state() +** KEYWORDS: {transaction state} +** +** These constants define the current transaction state of a database file. +** ^The [sqlite3_txn_state(D,S)] interface returns one of these +** constants in order to describe the transaction state of schema S +** in [database connection] D. +** +**
+** [[SQLITE_TXN_NONE]]
SQLITE_TXN_NONE
+**
The SQLITE_TXN_NONE state means that no transaction is currently +** pending.
+** +** [[SQLITE_TXN_READ]]
SQLITE_TXN_READ
+**
The SQLITE_TXN_READ state means that the database is currently +** in a read transaction. Content has been read from the database file +** but nothing in the database file has changed. The transaction state +** will advanced to SQLITE_TXN_WRITE if any changes occur and there are +** no other conflicting concurrent write transactions. The transaction +** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or +** [COMMIT].
+** +** [[SQLITE_TXN_WRITE]]
SQLITE_TXN_WRITE
+**
The SQLITE_TXN_WRITE state means that the database is currently +** in a write transaction. Content has been written to the database file +** but has not yet committed. The transaction state will change to +** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].
+*/ +#define SQLITE_TXN_NONE 0 +#define SQLITE_TXN_READ 1 +#define SQLITE_TXN_WRITE 2 + +/* +** CAPI3REF: Find the next prepared statement +** METHOD: sqlite3 +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** METHOD: sqlite3 +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The commit and rollback hook callbacks are not reentrant. +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that running any other SQL statements, including SELECT statements, +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** the database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Autovacuum Compaction Amount Callback +** METHOD: sqlite3 +** +** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback +** function C that is invoked prior to each autovacuum of the database +** file. ^The callback is passed a copy of the generic data pointer (P), +** the schema-name of the attached database that is being autovacuumed, +** the size of the database file in pages, the number of free pages, +** and the number of bytes per page, respectively. The callback should +** return the number of free pages that should be removed by the +** autovacuum. ^If the callback returns zero, then no autovacuum happens. +** ^If the value returned is greater than or equal to the number of +** free pages, then a complete autovacuum happens. +** +**

^If there are multiple ATTACH-ed database files that are being +** modified as part of a transaction commit, then the autovacuum pages +** callback is invoked separately for each file. +** +**

The callback is not reentrant. The callback function should +** not attempt to invoke any other SQLite interface. If it does, bad +** things may happen, including segmentation faults and corrupt database +** files. The callback function should be a simple function that +** does some arithmetic on its input parameters and returns a result. +** +** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional +** destructor for the P parameter. ^If X is not NULL, then X(P) is +** invoked whenever the database connection closes or when the callback +** is overwritten by another invocation of sqlite3_autovacuum_pages(). +** +**

^There is only one autovacuum pages callback per database connection. +** ^Each call to the sqlite3_autovacuum_pages() interface overrides all +** previous invocations for that database connection. ^If the callback +** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer, +** then the autovacuum steps callback is canceled. The return value +** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might +** be some other error code if something goes wrong. The current +** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other +** return codes might be added in future releases. +** +**

If no autovacuum pages callback is specified (the usual case) or +** a NULL pointer is provided for the callback, +** then the default behavior is to vacuum all free pages. So, in other +** words, the default behavior is the same as if the callback function +** were something like this: +** +**

+**     unsigned int demonstration_autovac_pages_callback(
+**       void *pClientData,
+**       const char *zSchema,
+**       unsigned int nDbPage,
+**       unsigned int nFreePage,
+**       unsigned int nBytePerPage
+**     ){
+**       return nFreePage;
+**     }
+** 
+*/ +SQLITE_API int sqlite3_autovacuum_pages( + sqlite3 *db, + unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int), + void*, + void(*)(void*) +); + + +/* +** CAPI3REF: Data Change Notification Callbacks +** METHOD: sqlite3 +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted in +** a [rowid table]. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted in a rowid table. +** ^The update hook is disabled by invoking sqlite3_update_hook() +** with a NULL pointer as the second parameter. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_sequence).)^ +** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. +** +** ^In the current implementation, the update hook +** is not invoked when conflicting rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** Whether the update hook is invoked before or after the +** corresponding change is currently unspecified and may differ +** depending on the type of change. Do not rely on the order of the +** hook call with regards to the final result of the operation which +** triggers the hook. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], +** and [sqlite3_preupdate_hook()] interfaces. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** This interface is omitted if SQLite is compiled with +** [-DSQLITE_OMIT_SHARED_CACHE]. The [-DSQLITE_OMIT_SHARED_CACHE] +** compile-time option is recommended because the +** [use of shared cache mode is discouraged]. +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). +** In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue to use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. It is recommended that it stay +** that way. In other words, do not use this routine. This interface +** continues to be provided for historical compatibility, but its use is +** discouraged. Any use of shared cache is discouraged. If shared cache +** must be used, it is recommended that shared cache only be enabled for +** individual database connections using the [sqlite3_open_v2()] interface +** with the [SQLITE_OPEN_SHAREDCACHE] flag. +** +** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 +** and will always return SQLITE_MISUSE. On those systems, +** shared cache mode should be enabled per-database connection via +** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. +** +** This interface is threadsafe on processors where writing a +** 32-bit integer is atomic. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +SQLITE_API int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** See also: [sqlite3_db_release_memory()] +*/ +SQLITE_API int sqlite3_release_memory(int); + +/* +** CAPI3REF: Free Memory Used By A Database Connection +** METHOD: sqlite3 +** +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** memory as possible from database connection D. Unlike the +** [sqlite3_release_memory()] interface, this interface is in effect even +** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is +** omitted. +** +** See also: [sqlite3_release_memory()] +*/ +SQLITE_API int sqlite3_db_release_memory(sqlite3*); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** These interfaces impose limits on the amount of heap memory that will be +** by all database connections within a single process. +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of +** N bytes on the amount of memory that will be allocated. ^The +** sqlite3_hard_heap_limit64(N) interface is similar to +** sqlite3_soft_heap_limit64(N) except that memory allocations will fail +** when the hard heap limit is reached. +** +** ^The return value from both sqlite3_soft_heap_limit64() and +** sqlite3_hard_heap_limit64() is the size of +** the heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the heap limit. Hence, the current +** size of heap limits can be determined by invoking +** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1). +** +** ^Setting the heap limits to zero disables the heap limiter mechanism. +** +** ^The soft heap limit may not be greater than the hard heap limit. +** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N) +** is invoked with a value of N that is greater than the hard heap limit, +** the soft heap limit is set to the value of the hard heap limit. +** ^The soft heap limit is automatically enabled whenever the hard heap +** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and +** the soft heap limit is outside the range of 1..N, then the soft heap +** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the +** hard heap limit is enabled makes the soft heap limit equal to the +** hard heap limit. +** +** The memory allocation limits can also be adjusted using +** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit]. +** +** ^(The heap limits are not enforced in the current implementation +** if one or more of following conditions are true: +** +**
    +**
  • The limit value is set to zero. +**
  • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
  • An alternative page cache implementation is specified using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +**
  • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
)^ +** +** The circumstances under which SQLite will enforce the heap limits may +** changes in future releases of SQLite. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); +SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** METHOD: sqlite3 +** +** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns +** information about column C of table T in database D +** on [database connection] X.)^ ^The sqlite3_table_column_metadata() +** interface returns SQLITE_OK and fills in the non-NULL pointers in +** the final five arguments with appropriate values if the specified +** column exists. ^The sqlite3_table_column_metadata() interface returns +** SQLITE_ERROR if the specified column does not exist. +** ^If the column-name parameter to sqlite3_table_column_metadata() is a +** NULL pointer, then this routine simply checks for the existence of the +** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it +** does not. If the table name parameter T in a call to +** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is +** undefined behavior. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^(The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL.)^ ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
+** +**
Parameter Output
Type
Description +** +**
5th const char* Data type +**
6th const char* Name of default collation sequence +**
7th int True if column has a NOT NULL constraint +**
8th int True if column is part of the PRIMARY KEY +**
9th int True if column is [AUTOINCREMENT] +**
+**
)^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and the table +** is not a [WITHOUT ROWID] table and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** [INTEGER PRIMARY KEY] column, then the outputs +** for the [rowid] are set as follows: +** +**
+**     data type: "INTEGER"
+**     collation sequence: "BINARY"
+**     not null: 0
+**     primary key: 1
+**     auto increment: 0
+** 
)^ +** +** ^This function causes all database schemas to be read from disk and +** parsed, if that has not already been done, and returns an error if +** any errors are encountered while loading the schema. +*/ +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** METHOD: sqlite3 +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** [SQLite extension] library contained in the file zFile. If +** the file cannot be loaded directly, attempts are made to load +** with various operating-system specific extensions added. +** So for example, if "samplelib" cannot be loaded, then names like +** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might +** be tried also. +** +** ^The entry point is zProc. +** ^(zProc may be 0, in which case SQLite will try to come up with an +** entry point name on its own. It first tries "sqlite3_extension_init". +** If that does not work, it constructs a name "sqlite3_X_init" where the +** X is consists of the lower-case equivalent of all ASCII alphabetic +** characters in the filename from the last "/" to the first following +** "." and omitting any initial "lib".)^ +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] or +** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) +** prior to calling this API, +** otherwise an error will be returned. +** +** Security warning: It is recommended that the +** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this +** interface. The use of the [sqlite3_enable_load_extension()] interface +** should be avoided. This will keep the SQL function [load_extension()] +** disabled and prevent SQL injections from giving attackers +** access to extension loading capabilities. +** +** See also the [load_extension() SQL function]. +*/ +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** METHOD: sqlite3 +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with [extension loading], and as a means of disabling +** [extension loading] while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +** +** ^This interface enables or disables both the C-API +** [sqlite3_load_extension()] and the SQL function [load_extension()]. +** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) +** to enable or disable only the C-API.)^ +** +** Security warning: It is recommended that extension loading +** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method +** rather than this interface, so the [load_extension()] SQL function +** remains disabled. This will prevent SQL injections from giving attackers +** access to extension loading capabilities. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked [SQLite extension] +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects an integer result as if the signature of the +** entry point where as follows: +** +**
+**    int xEntryPoint(
+**      sqlite3 *db,
+**      const char **pzErrMsg,
+**      const struct sqlite3_api_routines *pThunk
+**    );
+** 
)^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()] +** and [sqlite3_cancel_auto_extension()] +*/ +SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); + +/* +** CAPI3REF: Cancel Automatic Extension Loading +** +** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the +** initialization routine X that was registered using a prior call to +** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] +** routine returns 1 if initialization routine X was successfully +** unregistered and it returns 0 if X was not on the list of initialization +** routines. +*/ +SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void); + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a "virtual table module", +** defines the implementation of a [virtual table]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + int (*xSavepoint)(sqlite3_vtab *pVTab, int); + int (*xRelease)(sqlite3_vtab *pVTab, int); + int (*xRollbackTo)(sqlite3_vtab *pVTab, int); + /* The methods above are in versions 1 and 2 of the sqlite_module object. + ** Those below are for version 3 and greater. */ + int (*xShadowName)(const char*); + /* The methods above are in versions 1 through 3 of the sqlite_module object. + ** Those below are for version 4 and greater. */ + int (*xIntegrity)(sqlite3_vtab *pVTab, const char *zSchema, + const char *zTabName, int mFlags, char **pzErr); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
column OP expr
+** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The colUsed field indicates which columns of the virtual table may be +** required by the current scan. Virtual table columns are numbered from +** zero in the order in which they appear within the CREATE TABLE statement +** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), +** the corresponding bit is set within the colUsed mask if the column may be +** required by SQLite. If the table has at least 64 columns and any column +** to the right of the first 63 is required, then bit 63 of colUsed is also +** set. In other words, column iCol may be required if the expression +** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to +** non-zero. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and might not be checked again by the byte code.)^ ^(The +** aConstraintUsage[].omit flag is an optimization hint. When the omit flag +** is left in its default setting of false, the constraint will always be +** checked separately in byte code. If the omit flag is change to true, then +** the constraint may or may not be checked in byte code. In other words, +** when the omit flag is true there is no guarantee that the constraint will +** not be checked again using byte code.)^ +** +** ^The idxNum and idxStr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxStr if and only if +** needToFreeIdxStr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of a particular +** strategy. A cost of N indicates that the cost of the strategy is similar +** to a linear scan of an SQLite table with N rows. A cost of log(N) +** indicates that the expense of the operation is similar to that of a +** binary search on a unique indexed field of an SQLite table with N rows. +** +** ^The estimatedRows value is an estimate of the number of rows that +** will be returned by the strategy. +** +** The xBestIndex method may optionally populate the idxFlags field with a +** mask of SQLITE_INDEX_SCAN_* flags. One such flag is +** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN] +** output to show the idxNum has hex instead of as decimal. Another flag is +** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will +** return at most one row. +** +** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then +** SQLite also assumes that if a call to the xUpdate() method is made as +** part of the same statement to delete or update a virtual table row and the +** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback +** any database changes. In other words, if the xUpdate() returns +** SQLITE_CONSTRAINT, the database contents must be exactly as they were +** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not +** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by +** the xUpdate method are automatically rolled back by SQLite. +** +** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info +** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). +** If a virtual table extension is +** used with an SQLite version earlier than 3.8.2, the results of attempting +** to read or write the estimatedRows field are undefined (but are likely +** to include crashing the application). The estimatedRows field should +** therefore only be used if [sqlite3_libversion_number()] returns a +** value greater than or equal to 3008002. Similarly, the idxFlags field +** was added for [version 3.9.0] ([dateof:3.9.0]). +** It may therefore only be used if +** sqlite3_libversion_number() returns a value greater than or equal to +** 3009000. +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column constrained. -1 for ROWID */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ + /* Fields below are only available in SQLite 3.8.2 and later */ + sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ + /* Fields below are only available in SQLite 3.9.0 and later */ + int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ + /* Fields below are only available in SQLite 3.10.0 and later */ + sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ +}; + +/* +** CAPI3REF: Virtual Table Scan Flags +** +** Virtual table implementations are allowed to set the +** [sqlite3_index_info].idxFlags field to some combination of +** these bits. +*/ +#define SQLITE_INDEX_SCAN_UNIQUE 0x00000001 /* Scan visits at most 1 row */ +#define SQLITE_INDEX_SCAN_HEX 0x00000002 /* Display idxNum as hex */ + /* in EXPLAIN QUERY PLAN */ + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros define the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the WHERE clause of +** a query that uses a [virtual table]. +** +** ^The left-hand operand of the operator is given by the corresponding +** aConstraint[].iColumn field. ^An iColumn of -1 indicates the left-hand +** operand is the rowid. +** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET +** operators have no left-hand operand, and so for those operators the +** corresponding aConstraint[].iColumn is meaningless and should not be +** used. +** +** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through +** value 255 are reserved to represent functions that are overloaded +** by the [xFindFunction|xFindFunction method] of the virtual table +** implementation. +** +** The right-hand operands for each constraint might be accessible using +** the [sqlite3_vtab_rhs_value()] interface. Usually the right-hand +** operand is only available if it appears as a single constant literal +** in the input SQL. If the right-hand operand is another column or an +** expression (even a constant expression) or a parameter, then the +** sqlite3_vtab_rhs_value() probably will not be able to extract it. +** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and +** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand +** and hence calls to sqlite3_vtab_rhs_value() for those operators will +** always return SQLITE_NOTFOUND. +** +** The collating sequence to be used for comparison can be found using +** the [sqlite3_vtab_collation()] interface. For most real-world virtual +** tables, the collating sequence of constraints does not matter (for example +** because the constraints are numeric) and so the sqlite3_vtab_collation() +** interface is not commonly needed. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 +#define SQLITE_INDEX_CONSTRAINT_LIKE 65 +#define SQLITE_INDEX_CONSTRAINT_GLOB 66 +#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 +#define SQLITE_INDEX_CONSTRAINT_NE 68 +#define SQLITE_INDEX_CONSTRAINT_ISNOT 69 +#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70 +#define SQLITE_INDEX_CONSTRAINT_ISNULL 71 +#define SQLITE_INDEX_CONSTRAINT_IS 72 +#define SQLITE_INDEX_CONSTRAINT_LIMIT 73 +#define SQLITE_INDEX_CONSTRAINT_OFFSET 74 +#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** METHOD: sqlite3 +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +** +** ^If the third parameter (the pointer to the sqlite3_module object) is +** NULL then no new module is created and any existing modules with the +** same name are dropped. +** +** See also: [sqlite3_drop_modules()] +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Remove Unnecessary Virtual Table Implementations +** METHOD: sqlite3 +** +** ^The sqlite3_drop_modules(D,L) interface removes all virtual +** table modules from database connection D except those named on list L. +** The L parameter must be either NULL or a pointer to an array of pointers +** to strings where the array is terminated by a single NULL pointer. +** ^If the L parameter is NULL, then all virtual table modules are removed. +** +** See also: [sqlite3_create_module()] +*/ +SQLITE_API int sqlite3_drop_modules( + sqlite3 *db, /* Remove modules from this connection */ + const char **azKeep /* Except, do not remove the ones named here */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Number of open cursors */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** METHOD: sqlite3 +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** METHOD: sqlite3 +** CONSTRUCTOR: sqlite3_blob +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
+**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** 
)^ +** +** ^(Parameter zDb is not the filename that contains the database, but +** rather the symbolic name of the database. For attached databases, this is +** the name that appears after the AS keyword in the [ATTACH] statement. +** For the main database file, the database name is "main". For TEMP +** tables, the database name is "temp".)^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If the flags parameter is zero, the BLOB is opened for +** read-only access. +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored +** in *ppBlob. Otherwise an [error code] is returned and, unless the error +** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided +** the API is not misused, it is always safe to call [sqlite3_blob_close()] +** on *ppBlob after this function it returns. +** +** This function fails with SQLITE_ERROR if any of the following are true: +**
    +**
  • ^(Database zDb does not exist)^, +**
  • ^(Table zTable does not exist within database zDb)^, +**
  • ^(Table zTable is a WITHOUT ROWID table)^, +**
  • ^(Column zColumn does not exist)^, +**
  • ^(Row iRow is not present in the table)^, +**
  • ^(The specified column of row iRow contains a value that is not +** a TEXT or BLOB value)^, +**
  • ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE +** constraint and the blob is being opened for read/write access)^, +**
  • ^([foreign key constraints | Foreign key constraints] are enabled, +** column zColumn is part of a [child key] definition and the blob is +** being opened for read/write access)^. +**
+** +** ^Unless it returns SQLITE_MISUSE, this function sets the +** [database connection] error code and message accessible via +** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. +** +** A BLOB referenced by sqlite3_blob_open() may be read using the +** [sqlite3_blob_read()] interface and modified by using +** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a +** different row of the same table using the [sqlite3_blob_reopen()] +** interface. However, the column, table, or database of a [BLOB handle] +** cannot be changed after the [BLOB handle] is opened. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function may be used to create a +** zero-filled blob to read or write using the incremental-blob interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +** +** See also: [sqlite3_blob_close()], +** [sqlite3_blob_reopen()], [sqlite3_blob_read()], +** [sqlite3_blob_bytes()], [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** METHOD: sqlite3_blob +** +** ^This function is used to move an existing [BLOB handle] so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing [BLOB handle] to a new row is +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** DESTRUCTOR: sqlite3_blob +** +** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed +** unconditionally. Even if this routine returns an error code, the +** handle is still closed.)^ +** +** ^If the blob handle being closed was opened for read-write access, and if +** the database is in auto-commit mode and there are no other open read-write +** blob handles or active write statements, the current transaction is +** committed. ^If an error occurs while committing the transaction, an error +** code is returned and the transaction rolled back. +** +** Calling this function with an argument that is not a NULL pointer or an +** open blob handle results in undefined behavior. ^Calling this routine +** with a null pointer (such as would be returned by a failed call to +** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function +** is passed a valid open blob handle, the values returned by the +** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** METHOD: sqlite3_blob +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** METHOD: sqlite3_blob +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** METHOD: sqlite3_blob +** +** ^(This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset.)^ +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** ^Unless SQLITE_MISUSE is returned, this function sets the +** [database connection] error code and message accessible via +** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. The size of the +** BLOB (and hence the maximum value of N+iOffset) can be determined +** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less +** than zero [SQLITE_ERROR] is returned and no data is written. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
    +**
  • SQLITE_MUTEX_PTHREADS +**
  • SQLITE_MUTEX_W32 +**
  • SQLITE_MUTEX_NOOP +**
+** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_PTHREADS and +** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix +** and Windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize(). +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() +** routine returns NULL if it is unable to allocate the requested +** mutex. The argument to sqlite3_mutex_alloc() must one of these +** integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MAIN +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_OPEN +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_PMEM +**
  • SQLITE_MUTEX_STATIC_APP1 +**
  • SQLITE_MUTEX_STATIC_APP2 +**
  • SQLITE_MUTEX_STATIC_APP3 +**
  • SQLITE_MUTEX_STATIC_VFS1 +**
  • SQLITE_MUTEX_STATIC_VFS2 +**
  • SQLITE_MUTEX_STATIC_VFS3 +**
+** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. SQLite will only request a recursive mutex in +** cases where it really needs one. If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Nine static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^For the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. Attempting to deallocate a static +** mutex results in undefined behavior. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases, the +** mutex must be exited an equal number of times before another thread +** can enter.)^ If the same thread tries to enter any mutex other +** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. In most cases the SQLite core only uses +** sqlite3_mutex_try() as an optimization, so this is acceptable +** behavior. The exceptions are unix builds that set the +** SQLITE_ENABLE_SETLK_TIMEOUT build option. In that case a working +** sqlite3_mutex_try() is required.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), +** sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer, +** then any of the four routines behaves as a no-op. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the application has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the application +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
    +**
  • [sqlite3_mutex_alloc()]
  • +**
  • [sqlite3_mutex_free()]
  • +**
  • [sqlite3_mutex_enter()]
  • +**
  • [sqlite3_mutex_try()]
  • +**
  • [sqlite3_mutex_leave()]
  • +**
  • [sqlite3_mutex_held()]
  • +**
  • [sqlite3_mutex_notheld()]
  • +**
)^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case. The results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** The implementation is not required to provide versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MAIN 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ +#define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ +#define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ +#define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ +#define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */ +#define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */ +#define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */ + +/* Legacy compatibility: */ +#define SQLITE_MUTEX_STATIC_MASTER 2 + + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** METHOD: sqlite3 +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** METHOD: sqlite3 +** KEYWORDS: {file control} +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** A few opcodes for [sqlite3_file_control()] are handled directly +** by the SQLite core and never invoke the +** sqlite3_io_methods.xFileControl method. +** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. The +** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns +** the [sqlite3_file] object associated with the journal file instead of +** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns +** a pointer to the underlying [sqlite3_vfs] object for the file. +** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter +** from the pager. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [file control opcodes] +*/ +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +SQLITE_API int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */ +#define SQLITE_TESTCTRL_FK_NO_ACTION 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 /* NOT USED */ +#define SQLITE_TESTCTRL_JSON_SELFCHECK 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */ +#define SQLITE_TESTCTRL_GETOPT 16 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */ +#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 +#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ +#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 +#define SQLITE_TESTCTRL_NEVER_CORRUPT 20 +#define SQLITE_TESTCTRL_VDBE_COVERAGE 21 +#define SQLITE_TESTCTRL_BYTEORDER 22 +#define SQLITE_TESTCTRL_ISINIT 23 +#define SQLITE_TESTCTRL_SORTER_MMAP 24 +#define SQLITE_TESTCTRL_IMPOSTER 25 +#define SQLITE_TESTCTRL_PARSER_COVERAGE 26 +#define SQLITE_TESTCTRL_RESULT_INTREAL 27 +#define SQLITE_TESTCTRL_PRNG_SEED 28 +#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29 +#define SQLITE_TESTCTRL_SEEK_COUNT 30 +#define SQLITE_TESTCTRL_TRACEFLAGS 31 +#define SQLITE_TESTCTRL_TUNE 32 +#define SQLITE_TESTCTRL_LOGEST 33 +#define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */ +#define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */ + +/* +** CAPI3REF: SQL Keyword Checking +** +** These routines provide access to the set of SQL language keywords +** recognized by SQLite. Applications can uses these routines to determine +** whether or not a specific identifier needs to be escaped (for example, +** by enclosing in double-quotes) so as not to confuse the parser. +** +** The sqlite3_keyword_count() interface returns the number of distinct +** keywords understood by SQLite. +** +** The sqlite3_keyword_name(N,Z,L) interface finds the 0-based N-th keyword and +** makes *Z point to that keyword expressed as UTF8 and writes the number +** of bytes in the keyword into *L. The string that *Z points to is not +** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns +** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z +** or L are NULL or invalid pointers then calls to +** sqlite3_keyword_name(N,Z,L) result in undefined behavior. +** +** The sqlite3_keyword_check(Z,L) interface checks to see whether or not +** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero +** if it is and zero if not. +** +** The parser used by SQLite is forgiving. It is often possible to use +** a keyword as an identifier as long as such use does not result in a +** parsing ambiguity. For example, the statement +** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and +** creates a new table named "BEGIN" with three columns named +** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid +** using keywords as identifiers. Common techniques used to avoid keyword +** name collisions include: +**
    +**
  • Put all identifier names inside double-quotes. This is the official +** SQL way to escape identifier names. +**
  • Put identifier names inside [...]. This is not standard SQL, +** but it is what SQL Server does and so lots of programmers use this +** technique. +**
  • Begin every identifier with the letter "Z" as no SQL keywords start +** with "Z". +**
  • Include a digit somewhere in every identifier name. +**
+** +** Note that the number of keywords understood by SQLite can depend on +** compile-time options. For example, "VACUUM" is not a keyword if +** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also, +** new keywords may be added to future releases of SQLite. +*/ +SQLITE_API int sqlite3_keyword_count(void); +SQLITE_API int sqlite3_keyword_name(int,const char**,int*); +SQLITE_API int sqlite3_keyword_check(const char*,int); + +/* +** CAPI3REF: Dynamic String Object +** KEYWORDS: {dynamic string} +** +** An instance of the sqlite3_str object contains a dynamically-sized +** string under construction. +** +** The lifecycle of an sqlite3_str object is as follows: +**
    +**
  1. ^The sqlite3_str object is created using [sqlite3_str_new()]. +**
  2. ^Text is appended to the sqlite3_str object using various +** methods, such as [sqlite3_str_appendf()]. +**
  3. ^The sqlite3_str object is destroyed and the string it created +** is returned using the [sqlite3_str_finish()] interface. +**
+*/ +typedef struct sqlite3_str sqlite3_str; + +/* +** CAPI3REF: Create A New Dynamic String Object +** CONSTRUCTOR: sqlite3_str +** +** ^The [sqlite3_str_new(D)] interface allocates and initializes +** a new [sqlite3_str] object. To avoid memory leaks, the object returned by +** [sqlite3_str_new()] must be freed by a subsequent call to +** [sqlite3_str_finish(X)]. +** +** ^The [sqlite3_str_new(D)] interface always returns a pointer to a +** valid [sqlite3_str] object, though in the event of an out-of-memory +** error the returned object might be a special singleton that will +** silently reject new text, always return SQLITE_NOMEM from +** [sqlite3_str_errcode()], always return 0 for +** [sqlite3_str_length()], and always return NULL from +** [sqlite3_str_finish(X)]. It is always safe to use the value +** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter +** to any of the other [sqlite3_str] methods. +** +** The D parameter to [sqlite3_str_new(D)] may be NULL. If the +** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum +** length of the string contained in the [sqlite3_str] object will be +** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead +** of [SQLITE_MAX_LENGTH]. +*/ +SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*); + +/* +** CAPI3REF: Finalize A Dynamic String +** DESTRUCTOR: sqlite3_str +** +** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X +** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()] +** that contains the constructed string. The calling application should +** pass the returned value to [sqlite3_free()] to avoid a memory leak. +** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any +** errors were encountered during construction of the string. ^The +** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the +** string in [sqlite3_str] object X is zero bytes long. +*/ +SQLITE_API char *sqlite3_str_finish(sqlite3_str*); + +/* +** CAPI3REF: Add Content To A Dynamic String +** METHOD: sqlite3_str +** +** These interfaces add content to an sqlite3_str object previously obtained +** from [sqlite3_str_new()]. +** +** ^The [sqlite3_str_appendf(X,F,...)] and +** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf] +** functionality of SQLite to append formatted text onto the end of +** [sqlite3_str] object X. +** +** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S +** onto the end of the [sqlite3_str] object X. N must be non-negative. +** S must contain at least N non-zero bytes of content. To append a +** zero-terminated string in its entirety, use the [sqlite3_str_appendall()] +** method instead. +** +** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of +** zero-terminated string S onto the end of [sqlite3_str] object X. +** +** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the +** single-byte character C onto the end of [sqlite3_str] object X. +** ^This method can be used, for example, to add whitespace indentation. +** +** ^The [sqlite3_str_reset(X)] method resets the string under construction +** inside [sqlite3_str] object X back to zero bytes in length. +** +** These methods do not return a result code. ^If an error occurs, that fact +** is recorded in the [sqlite3_str] object and can be recovered by a +** subsequent call to [sqlite3_str_errcode(X)]. +*/ +SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...); +SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list); +SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N); +SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn); +SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C); +SQLITE_API void sqlite3_str_reset(sqlite3_str*); + +/* +** CAPI3REF: Status Of A Dynamic String +** METHOD: sqlite3_str +** +** These interfaces return the current status of an [sqlite3_str] object. +** +** ^If any prior errors have occurred while constructing the dynamic string +** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return +** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns +** [SQLITE_NOMEM] following any out-of-memory error, or +** [SQLITE_TOOBIG] if the size of the dynamic string exceeds +** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors. +** +** ^The [sqlite3_str_length(X)] method returns the current length, in bytes, +** of the dynamic string under construction in [sqlite3_str] object X. +** ^The length returned by [sqlite3_str_length(X)] does not include the +** zero-termination byte. +** +** ^The [sqlite3_str_value(X)] method returns a pointer to the current +** content of the dynamic string under construction in X. The value +** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X +** and might be freed or altered by any subsequent method on the same +** [sqlite3_str] object. Applications must not used the pointer returned +** [sqlite3_str_value(X)] after any subsequent method call on the same +** object. ^Applications may change the content of the string returned +** by [sqlite3_str_value(X)] as long as they do not write into any bytes +** outside the range of 0 to [sqlite3_str_length(X)] and do not read or +** write any byte after any subsequent sqlite3_str method call. +*/ +SQLITE_API int sqlite3_str_errcode(sqlite3_str*); +SQLITE_API int sqlite3_str_length(sqlite3_str*); +SQLITE_API char *sqlite3_str_value(sqlite3_str*); + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^These interfaces are used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [status parameters | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() and sqlite3_status64() routines return +** SQLITE_OK on success and a non-zero [error code] on failure. +** +** If either the current value or the highwater mark is too large to +** be represented by a 32-bit integer, then the values returned by +** sqlite3_status() are undefined. +** +** See also: [sqlite3_db_status()] +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); +SQLITE_API int sqlite3_status64( + int op, + sqlite3_int64 *pCurrent, + sqlite3_int64 *pHighwater, + int resetFlag +); + + +/* +** CAPI3REF: Status Parameters +** KEYWORDS: {status parameters} +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
+** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
+**
This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ +** +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
+**
This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
+**
This parameter records the number of separate memory allocations +** currently checked out.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
+**
This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] +** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+**
This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
+**
This parameter records the largest memory allocation request +** handed to the [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_SCRATCH_USED]]
SQLITE_STATUS_SCRATCH_USED
+**
No longer used.
+** +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+**
No longer used.
+** +** [[SQLITE_STATUS_SCRATCH_SIZE]]
SQLITE_STATUS_SCRATCH_SIZE
+**
No longer used.
+** +** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
+**
The *pHighwater parameter records the deepest parser stack. +** The *pCurrent value is undefined. The *pHighwater value is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ +**
+** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */ +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */ +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */ +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** METHOD: sqlite3 +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS options], that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS options] is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** KEYWORDS: {SQLITE_DBSTATUS options} +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+**
This parameter returns the number of lookaside memory slots currently +** checked out.
)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+**
This parameter returns the number of malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
+**
This parameter returns the approximate number of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] +** ^(
SQLITE_DBSTATUS_CACHE_USED_SHARED
+**
This parameter is similar to DBSTATUS_CACHE_USED, except that if a +** pager cache is shared between two or more connections the bytes of heap +** memory used by that pager cache is divided evenly between the attached +** connections.)^ In other words, if none of the pager caches associated +** with the database connection are shared, this request returns the same +** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are +** shared, the value returned by this call will be smaller than that returned +** by DBSTATUS_CACHE_USED. ^The highwater mark associated with +** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. +** +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
+**
This parameter returns the approximate number of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
+**
This parameter returns the approximate number of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
+**
This parameter returns the number of pager cache hits that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
+**
This parameter returns the number of pager cache misses that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
+**
This parameter returns the number of dirty cache entries that have +** been written to disk. Specifically, the number of pages written to the +** wal file in wal mode databases, or the number of pages written to the +** database file in rollback mode databases. Any pages written as part of +** transaction rollback or database recovery operations are not included. +** If an IO or other error occurs while writing a page to disk, the effect +** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The +** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(
SQLITE_DBSTATUS_CACHE_SPILL
+**
This parameter returns the number of dirty cache entries that have +** been written to disk in the middle of a transaction due to the page +** cache overflowing. Transactions are more efficient if they are written +** to disk all at once. When pages spill mid-transaction, that introduces +** additional overhead. This parameter can be used help identify +** inefficiencies that can be resolved by increasing the cache size. +**
+** +** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(
SQLITE_DBSTATUS_DEFERRED_FKS
+**
This parameter returns zero for the current value if and only if +** all foreign key constraints (deferred or immediate) have been +** resolved.)^ ^The highwater mark is always 0. +**
+**
+*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_CACHE_HIT 7 +#define SQLITE_DBSTATUS_CACHE_MISS 8 +#define SQLITE_DBSTATUS_CACHE_WRITE 9 +#define SQLITE_DBSTATUS_DEFERRED_FKS 10 +#define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 +#define SQLITE_DBSTATUS_CACHE_SPILL 12 +#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** METHOD: sqlite3_stmt +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
+**
^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
+** +** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
+**
^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
+** +** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
+**
^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
+** +** [[SQLITE_STMTSTATUS_VM_STEP]]
SQLITE_STMTSTATUS_VM_STEP
+**
^This is the number of virtual machine operations executed +** by the prepared statement if that number is less than or equal +** to 2147483647. The number of virtual machine operations can be +** used as a proxy for the total work done by the prepared statement. +** If the number of virtual machine operations exceeds 2147483647 +** then the value returned by this statement status code is undefined. +** +** [[SQLITE_STMTSTATUS_REPREPARE]]
SQLITE_STMTSTATUS_REPREPARE
+**
^This is the number of times that the prepare statement has been +** automatically regenerated due to schema changes or changes to +** [bound parameters] that might affect the query plan. +** +** [[SQLITE_STMTSTATUS_RUN]]
SQLITE_STMTSTATUS_RUN
+**
^This is the number of times that the prepared statement has +** been run. A single "run" for the purposes of this counter is one +** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()]. +** The counter is incremented on the first [sqlite3_step()] call of each +** cycle. +** +** [[SQLITE_STMTSTATUS_FILTER_MISS]] +** [[SQLITE_STMTSTATUS_FILTER HIT]] +**
SQLITE_STMTSTATUS_FILTER_HIT
+** SQLITE_STMTSTATUS_FILTER_MISS
+**
^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join +** step was bypassed because a Bloom filter returned not-found. The +** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of +** times that the Bloom filter returned a find, and thus the join step +** had to be processed as normal. +** +** [[SQLITE_STMTSTATUS_MEMUSED]]
SQLITE_STMTSTATUS_MEMUSED
+**
^This is the approximate number of bytes of heap memory +** used to store the prepared statement. ^This value is not actually +** a counter, and so the resetFlg parameter to sqlite3_stmt_status() +** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED. +**
+**
+*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 +#define SQLITE_STMTSTATUS_VM_STEP 4 +#define SQLITE_STMTSTATUS_REPREPARE 5 +#define SQLITE_STMTSTATUS_RUN 6 +#define SQLITE_STMTSTATUS_FILTER_MISS 7 +#define SQLITE_STMTSTATUS_FILTER_HIT 8 +#define SQLITE_STMTSTATUS_MEMUSED 99 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache_page object represents a single page in the +** page cache. The page cache will allocate instances of this +** object. Various methods of the page cache use pointers to instances +** of this object as parameters or as their return value. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache_page sqlite3_pcache_page; +struct sqlite3_pcache_page { + void *pBuf; /* The content of the page */ + void *pExtra; /* Extra information associated with the page */ +}; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods2 structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** [[the xInit() page cache method]] +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** [[the xShutdown() page cache method]] +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** [[the xCreate() page cache methods]] +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will always a power of two. ^The +** second parameter szExtra is a number of bytes of extra storage +** associated with each page cache entry. ^The szExtra parameter will +** a number less than 250. SQLite will use the +** extra szExtra bytes on each page to store metadata about the underlying +** database page on disk. The value passed into szExtra depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^The third argument to xCreate(), bPurgeable, is true if the cache being +** created will be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** [[the xCachesize() page cache method]] +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** [[the xPagecount() page cache methods]] +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** [[the xFetch() page cache methods]] +** The xFetch() method locates a page in the cache and returns a pointer to +** an sqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned sqlite3_pcache_page object will be a +** pointer to a buffer of szPage bytes used to store the content of a +** single database page. The pExtra element of sqlite3_pcache_page will be +** a pointer to the szExtra bytes of extra storage that SQLite has requested +** for each entry in the page cache. +** +** The page to be fetched is determined by the key. ^The minimum key value +** is 1. After it has been retrieved using xFetch, the page is considered +** to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
createFlag Behavior when page is not already in cache +**
0 Do not allocate a new page. Return NULL. +**
1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
+** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** [[the xUnpin() page cache method]] +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** [[the xRekey() page cache methods]] +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** [[the xDestroy() page cache method]] +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** functions. +** +** [[the xShrink() page cache method]] +** ^SQLite invokes the xShrink() method when it wants the page cache to +** free up as much of heap memory as possible. The page cache implementation +** is not obligated to free any memory, but well-behaved implementations should +** do their best. +*/ +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; +struct sqlite3_pcache_methods2 { + int iVersion; + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); + void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); + void (*xShrink)(sqlite3_pcache*); +}; + +/* +** This is the obsolete pcache_methods object that has now been replaced +** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** retained in the header file for backwards compatibility only. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
    +**
  1. sqlite3_backup_init() is called once to initialize the +** backup, +**
  2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
  3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
)^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** [[sqlite3_backup_init()]] sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^A call to sqlite3_backup_init() will fail, returning NULL, if +** there is already a read or read-write transaction open on the +** destination database. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** [[sqlite3_backup_step()]] sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
    +**
  1. the destination database was opened read-only, or +**
  2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
  3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
)^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** [[sqlite3_backup_finish()]] sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] +** sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** +** ^The sqlite3_backup_remaining() routine returns the number of pages still +** to be backed up at the conclusion of the most recent sqlite3_backup_step(). +** ^The sqlite3_backup_pagecount() routine returns the total number of pages +** in the source database at the conclusion of the most recent +** sqlite3_backup_step(). +** ^(The values returned by these functions are only updated by +** sqlite3_backup_step(). If the source database is modified in a way that +** changes the size of the source database or the number of pages remaining, +** those changes are not reflected in the output of sqlite3_backup_pagecount() +** and sqlite3_backup_remaining() until after the next +** sqlite3_backup_step().)^ +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +** +** Alternatives To Using The Backup API +** +** Other techniques for safely creating a consistent backup of an SQLite +** database include: +** +**
    +**
  • The [VACUUM INTO] command. +**
  • The [sqlite3_rsync] utility program. +**
+*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** METHOD: sqlite3 +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connection's transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connection's transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** and extensions to compare the contents of two buffers containing UTF-8 +** strings in a case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_stricmp(const char *, const char *); +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: String Globbing +* +** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if +** string X matches the [GLOB] pattern P. +** ^The definition of [GLOB] pattern matching used in +** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the +** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function +** is case sensitive. +** +** Note that this routine returns zero on a match and non-zero if the strings +** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +** +** See also: [sqlite3_strlike()]. +*/ +SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); + +/* +** CAPI3REF: String LIKE Matching +* +** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if +** string X matches the [LIKE] pattern P with escape character E. +** ^The definition of [LIKE] pattern matching used in +** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" +** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without +** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. +** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case +** insensitive - equivalent upper and lower case ASCII characters match +** one another. +** +** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though +** only ASCII characters are case folded. +** +** Note that this routine returns zero on a match and non-zero if the strings +** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +** +** See also: [sqlite3_strglob()]. +*/ +SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the [error log] +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** METHOD: sqlite3 +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** is invoked each time data is committed to a database in wal mode. +** +** ^(The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released)^, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^The return value is +** a copy of the third parameter from the previous call, if any, or 0. +** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** overwrite any prior [sqlite3_wal_hook()] settings. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** METHOD: sqlite3 +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Checkpoints initiated by this mechanism are +** [sqlite3_wal_checkpoint_v2|PASSIVE]. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** METHOD: sqlite3 +** +** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to +** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ +** +** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the +** [write-ahead log] for database X on [database connection] D to be +** transferred into the database file and for the write-ahead log to +** be reset. See the [checkpointing] documentation for addition +** information. +** +** This interface used to be the only way to cause a checkpoint to +** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] +** interface was added. This interface is retained for backwards +** compatibility and as a convenience for applications that need to manually +** start a callback but which do not need the full power (and corresponding +** complication) of [sqlite3_wal_checkpoint_v2()]. +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Checkpoint a database +** METHOD: sqlite3 +** +** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint +** operation on database X of [database connection] D in mode M. Status +** information is written back into integers pointed to by L and C.)^ +** ^(The M parameter must be a valid [checkpoint mode]:)^ +** +**
+**
SQLITE_CHECKPOINT_PASSIVE
+** ^Checkpoint as many frames as possible without waiting for any database +** readers or writers to finish, then sync the database file if all frames +** in the log were checkpointed. ^The [busy-handler callback] +** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode. +** ^On the other hand, passive mode might leave the checkpoint unfinished +** if there are concurrent readers or writers. +** +**
SQLITE_CHECKPOINT_FULL
+** ^This mode blocks (it invokes the +** [sqlite3_busy_handler|busy-handler callback]) until there is no +** database writer and all readers are reading from the most recent database +** snapshot. ^It then checkpoints all frames in the log file and syncs the +** database file. ^This mode blocks new database writers while it is pending, +** but new database readers are allowed to continue unimpeded. +** +**
SQLITE_CHECKPOINT_RESTART
+** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition +** that after checkpointing the log file it blocks (calls the +** [busy-handler callback]) +** until all readers are reading from the database file only. ^This ensures +** that the next writer will restart the log file from the beginning. +** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new +** database writer attempts while it is pending, but does not impede readers. +** +**
SQLITE_CHECKPOINT_TRUNCATE
+** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the +** addition that it also truncates the log file to zero bytes just prior +** to a successful return. +**
+** +** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in +** the log file or to -1 if the checkpoint could not run because +** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not +** NULL,then *pnCkpt is set to the total number of checkpointed frames in the +** log file (including any that were already checkpointed before the function +** was called) or to -1 if the checkpoint could not run due to an error or +** because the database is not in WAL mode. ^Note that upon successful +** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been +** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. +** +** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If +** any other process is running a checkpoint operation at the same time, the +** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a +** busy-handler configured, it will not be invoked in this case. +** +** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the +** exclusive "writer" lock on the database file. ^If the writer lock cannot be +** obtained immediately, and a busy-handler is configured, it is invoked and +** the writer lock retried until either the busy-handler returns 0 or the lock +** is successfully obtained. ^The busy-handler is also invoked while waiting for +** database readers as described above. ^If the busy-handler returns 0 before +** the writer lock is obtained or while waiting for database readers, the +** checkpoint operation proceeds from that point in the same way as +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible +** without blocking any further. ^SQLITE_BUSY is returned in this case. +** +** ^If parameter zDb is NULL or points to a zero length string, then the +** specified operation is attempted on all WAL databases [attached] to +** [database connection] db. In this case the +** values written to output parameters *pnLog and *pnCkpt are undefined. ^If +** an SQLITE_BUSY error is encountered when processing one or more of the +** attached WAL databases, the operation is still attempted on any remaining +** attached databases and SQLITE_BUSY is returned at the end. ^If any other +** error occurs while processing an attached database, processing is abandoned +** and the error code is returned to the caller immediately. ^If no error +** (SQLITE_BUSY or otherwise) is encountered while processing the attached +** databases, SQLITE_OK is returned. +** +** ^If database zDb is the name of an attached database that is not in WAL +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If +** zDb is not NULL (or a zero length string) and is not the name of any +** attached database, SQLITE_ERROR is returned to the caller. +** +** ^Unless it returns SQLITE_MISUSE, +** the sqlite3_wal_checkpoint_v2() interface +** sets the error information that is queried by +** [sqlite3_errcode()] and [sqlite3_errmsg()]. +** +** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface +** from SQL. +*/ +SQLITE_API int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +); + +/* +** CAPI3REF: Checkpoint Mode Values +** KEYWORDS: {checkpoint mode} +** +** These constants define all valid values for the "checkpoint mode" passed +** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. +** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the +** meaning of each of these checkpoint modes. +*/ +#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ +#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ +#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for readers */ +#define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */ + +/* +** CAPI3REF: Virtual Table Interface Configuration +** +** This function may be called by either the [xConnect] or [xCreate] method +** of a [virtual table] implementation to configure +** various facets of the virtual table interface. +** +** If this interface is invoked outside the context of an xConnect or +** xCreate virtual table method then the behavior is undefined. +** +** In the call sqlite3_vtab_config(D,C,...) the D parameter is the +** [database connection] in which the virtual table is being created and +** which is passed in as the first argument to the [xConnect] or [xCreate] +** method that is invoking sqlite3_vtab_config(). The C parameter is one +** of the [virtual table configuration options]. The presence and meaning +** of parameters after C depend on which [virtual table configuration option] +** is used. +*/ +SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Virtual Table Configuration Options +** KEYWORDS: {virtual table configuration options} +** KEYWORDS: {virtual table configuration option} +** +** These macros define the various options to the +** [sqlite3_vtab_config()] interface that [virtual table] implementations +** can use to customize and optimize their behavior. +** +**
+** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]] +**
SQLITE_VTAB_CONSTRAINT_SUPPORT
+**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** where X is an integer. If X is zero, then the [virtual table] whose +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** support constraints. In this configuration (which is the default) if +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been +** specified as part of the users SQL statement, regardless of the actual +** ON CONFLICT mode specified. +** +** If X is non-zero, then the virtual table implementation guarantees +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before +** any modifications to internal or persistent data structures have been made. +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite +** is able to roll back a statement or database transaction, and abandon +** or continue processing the current SQL statement as appropriate. +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode +** had been ABORT. +** +** Virtual table implementations that are required to handle OR REPLACE +** must do so within the [xUpdate] method. If a call to the +** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** CONFLICT policy is REPLACE, the virtual table implementation should +** silently replace the appropriate rows within the xUpdate callback and +** return SQLITE_OK. Or, if this is not possible, it may return +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT +** constraint handling. +**
+** +** [[SQLITE_VTAB_DIRECTONLY]]
SQLITE_VTAB_DIRECTONLY
+**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the +** the [xConnect] or [xCreate] methods of a [virtual table] implementation +** prohibits that virtual table from being used from within triggers and +** views. +**
+** +** [[SQLITE_VTAB_INNOCUOUS]]
SQLITE_VTAB_INNOCUOUS
+**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the +** the [xConnect] or [xCreate] methods of a [virtual table] implementation +** identify that virtual table as being safe to use from within triggers +** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the +** virtual table can do no serious harm even if it is controlled by a +** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS +** flag unless absolutely necessary. +**
+** +** [[SQLITE_VTAB_USES_ALL_SCHEMAS]]
SQLITE_VTAB_USES_ALL_SCHEMAS
+**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_USES_ALL_SCHEMA) from within the +** the [xConnect] or [xCreate] methods of a [virtual table] implementation +** instruct the query planner to begin at least a read transaction on +** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the +** virtual table is used. +**
+**
+*/ +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 +#define SQLITE_VTAB_INNOCUOUS 2 +#define SQLITE_VTAB_DIRECTONLY 3 +#define SQLITE_VTAB_USES_ALL_SCHEMAS 4 + +/* +** CAPI3REF: Determine The Virtual Table Conflict Policy +** +** This function may only be called from within a call to the [xUpdate] method +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode +** of the SQL statement that triggered the call to the [xUpdate] method of the +** [virtual table]. +*/ +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); + +/* +** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE +** +** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn] +** method of a [virtual table], then it might return true if the +** column is being fetched as part of an UPDATE operation during which the +** column value will not change. The virtual table implementation can use +** this hint as permission to substitute a return value that is less +** expensive to compute and that the corresponding +** [xUpdate] method understands as a "no-change" value. +** +** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that +** the column is not changed by the UPDATE statement, then the xColumn +** method can optionally return without setting a result, without calling +** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces]. +** In that case, [sqlite3_value_nochange(X)] will return true for the +** same column in the [xUpdate] method. +** +** The sqlite3_vtab_nochange() routine is an optimization. Virtual table +** implementations should continue to give a correct answer even if the +** sqlite3_vtab_nochange() interface were to always return false. In the +** current implementation, the sqlite3_vtab_nochange() interface does always +** returns false for the enhanced [UPDATE FROM] statement. +*/ +SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*); + +/* +** CAPI3REF: Determine The Collation For a Virtual Table Constraint +** METHOD: sqlite3_index_info +** +** This function may only be called from within a call to the [xBestIndex] +** method of a [virtual table]. This function returns a pointer to a string +** that is the name of the appropriate collation sequence to use for text +** comparisons on the constraint identified by its arguments. +** +** The first argument must be the pointer to the [sqlite3_index_info] object +** that is the first parameter to the xBestIndex() method. The second argument +** must be an index into the aConstraint[] array belonging to the +** sqlite3_index_info structure passed to xBestIndex. +** +** Important: +** The first parameter must be the same pointer that is passed into the +** xBestMethod() method. The first parameter may not be a pointer to a +** different [sqlite3_index_info] object, even an exact copy. +** +** The return value is computed as follows: +** +**
    +**
  1. If the constraint comes from a WHERE clause expression that contains +** a [COLLATE operator], then the name of the collation specified by +** that COLLATE operator is returned. +**

  2. If there is no COLLATE operator, but the column that is the subject +** of the constraint specifies an alternative collating sequence via +** a [COLLATE clause] on the column definition within the CREATE TABLE +** statement that was passed into [sqlite3_declare_vtab()], then the +** name of that alternative collating sequence is returned. +**

  3. Otherwise, "BINARY" is returned. +**

+*/ +SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); + +/* +** CAPI3REF: Determine if a virtual table query is DISTINCT +** METHOD: sqlite3_index_info +** +** This API may only be used from within an [xBestIndex|xBestIndex method] +** of a [virtual table] implementation. The result of calling this +** interface from outside of xBestIndex() is undefined and probably harmful. +** +** ^The sqlite3_vtab_distinct() interface returns an integer between 0 and +** 3. The integer returned by sqlite3_vtab_distinct() +** gives the virtual table additional information about how the query +** planner wants the output to be ordered. As long as the virtual table +** can meet the ordering requirements of the query planner, it may set +** the "orderByConsumed" flag. +** +**
  1. +** ^If the sqlite3_vtab_distinct() interface returns 0, that means +** that the query planner needs the virtual table to return all rows in the +** sort order defined by the "nOrderBy" and "aOrderBy" fields of the +** [sqlite3_index_info] object. This is the default expectation. If the +** virtual table outputs all rows in sorted order, then it is always safe for +** the xBestIndex method to set the "orderByConsumed" flag, regardless of +** the return value from sqlite3_vtab_distinct(). +**

  2. +** ^(If the sqlite3_vtab_distinct() interface returns 1, that means +** that the query planner does not need the rows to be returned in sorted order +** as long as all rows with the same values in all columns identified by the +** "aOrderBy" field are adjacent.)^ This mode is used when the query planner +** is doing a GROUP BY. +**

  3. +** ^(If the sqlite3_vtab_distinct() interface returns 2, that means +** that the query planner does not need the rows returned in any particular +** order, as long as rows with the same values in all columns identified +** by "aOrderBy" are adjacent.)^ ^(Furthermore, when two or more rows +** contain the same values for all columns identified by "colUsed", all but +** one such row may optionally be omitted from the result.)^ +** The virtual table is not required to omit rows that are duplicates +** over the "colUsed" columns, but if the virtual table can do that without +** too much extra effort, it could potentially help the query to run faster. +** This mode is used for a DISTINCT query. +**

  4. +** ^(If the sqlite3_vtab_distinct() interface returns 3, that means the +** virtual table must return rows in the order defined by "aOrderBy" as +** if the sqlite3_vtab_distinct() interface had returned 0. However if +** two or more rows in the result have the same values for all columns +** identified by "colUsed", then all but one such row may optionally be +** omitted.)^ Like when the return value is 2, the virtual table +** is not required to omit rows that are duplicates over the "colUsed" +** columns, but if the virtual table can do that without +** too much extra effort, it could potentially help the query to run faster. +** This mode is used for queries +** that have both DISTINCT and ORDER BY clauses. +**

+** +**

The following table summarizes the conditions under which the +** virtual table is allowed to set the "orderByConsumed" flag based on +** the value returned by sqlite3_vtab_distinct(). This table is a +** restatement of the previous four paragraphs: +** +** +** +**
sqlite3_vtab_distinct() return value +** Rows are returned in aOrderBy order +** Rows with the same value in all aOrderBy columns are adjacent +** Duplicates over all colUsed columns may be omitted +**
0yesyesno +**
1noyesno +**
2noyesyes +**
3yesyesyes +**
+** +** ^For the purposes of comparing virtual table output values to see if the +** values are same value for sorting purposes, two NULL values are considered +** to be the same. In other words, the comparison operator is "IS" +** (or "IS NOT DISTINCT FROM") and not "==". +** +** If a virtual table implementation is unable to meet the requirements +** specified above, then it must not set the "orderByConsumed" flag in the +** [sqlite3_index_info] object or an incorrect answer may result. +** +** ^A virtual table implementation is always free to return rows in any order +** it wants, as long as the "orderByConsumed" flag is not set. ^When the +** the "orderByConsumed" flag is unset, the query planner will add extra +** [bytecode] to ensure that the final results returned by the SQL query are +** ordered correctly. The use of the "orderByConsumed" flag and the +** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful +** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed" +** flag might help queries against a virtual table to run faster. Being +** overly aggressive and setting the "orderByConsumed" flag when it is not +** valid to do so, on the other hand, might cause SQLite to return incorrect +** results. +*/ +SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*); + +/* +** CAPI3REF: Identify and handle IN constraints in xBestIndex +** +** This interface may only be used from within an +** [xBestIndex|xBestIndex() method] of a [virtual table] implementation. +** The result of invoking this interface from any other context is +** undefined and probably harmful. +** +** ^(A constraint on a virtual table of the form +** "[IN operator|column IN (...)]" is +** communicated to the xBestIndex method as a +** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^ If xBestIndex wants to use +** this constraint, it must set the corresponding +** aConstraintUsage[].argvIndex to a positive integer. ^(Then, under +** the usual mode of handling IN operators, SQLite generates [bytecode] +** that invokes the [xFilter|xFilter() method] once for each value +** on the right-hand side of the IN operator.)^ Thus the virtual table +** only sees a single value from the right-hand side of the IN operator +** at a time. +** +** In some cases, however, it would be advantageous for the virtual +** table to see all values on the right-hand of the IN operator all at +** once. The sqlite3_vtab_in() interfaces facilitates this in two ways: +** +**

    +**
  1. +** ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero) +** if and only if the [sqlite3_index_info|P->aConstraint][N] constraint +** is an [IN operator] that can be processed all at once. ^In other words, +** sqlite3_vtab_in() with -1 in the third argument is a mechanism +** by which the virtual table can ask SQLite if all-at-once processing +** of the IN operator is even possible. +** +**

  2. +** ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates +** to SQLite that the virtual table does or does not want to process +** the IN operator all-at-once, respectively. ^Thus when the third +** parameter (F) is non-negative, this interface is the mechanism by +** which the virtual table tells SQLite how it wants to process the +** IN operator. +**

+** +** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times +** within the same xBestIndex method call. ^For any given P,N pair, +** the return value from sqlite3_vtab_in(P,N,F) will always be the same +** within the same xBestIndex call. ^If the interface returns true +** (non-zero), that means that the constraint is an IN operator +** that can be processed all-at-once. ^If the constraint is not an IN +** operator or cannot be processed all-at-once, then the interface returns +** false. +** +** ^(All-at-once processing of the IN operator is selected if both of the +** following conditions are met: +** +**
    +**
  1. The P->aConstraintUsage[N].argvIndex value is set to a positive +** integer. This is how the virtual table tells SQLite that it wants to +** use the N-th constraint. +** +**

  2. The last call to sqlite3_vtab_in(P,N,F) for which F was +** non-negative had F>=1. +**

)^ +** +** ^If either or both of the conditions above are false, then SQLite uses +** the traditional one-at-a-time processing strategy for the IN constraint. +** ^If both conditions are true, then the argvIndex-th parameter to the +** xFilter method will be an [sqlite3_value] that appears to be NULL, +** but which can be passed to [sqlite3_vtab_in_first()] and +** [sqlite3_vtab_in_next()] to find all values on the right-hand side +** of the IN constraint. +*/ +SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle); + +/* +** CAPI3REF: Find all elements on the right-hand side of an IN constraint. +** +** These interfaces are only useful from within the +** [xFilter|xFilter() method] of a [virtual table] implementation. +** The result of invoking these interfaces from any other context +** is undefined and probably harmful. +** +** The X parameter in a call to sqlite3_vtab_in_first(X,P) or +** sqlite3_vtab_in_next(X,P) should be one of the parameters to the +** xFilter method which invokes these routines, and specifically +** a parameter that was previously selected for all-at-once IN constraint +** processing use the [sqlite3_vtab_in()] interface in the +** [xBestIndex|xBestIndex method]. ^(If the X parameter is not +** an xFilter argument that was selected for all-at-once IN constraint +** processing, then these routines return [SQLITE_ERROR].)^ +** +** ^(Use these routines to access all values on the right-hand side +** of the IN constraint using code like the following: +** +**
+**    for(rc=sqlite3_vtab_in_first(pList, &pVal);
+**        rc==SQLITE_OK && pVal;
+**        rc=sqlite3_vtab_in_next(pList, &pVal)
+**    ){
+**      // do something with pVal
+**    }
+**    if( rc!=SQLITE_OK ){
+**      // an error has occurred
+**    }
+** 
)^ +** +** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P) +** routines return SQLITE_OK and set *P to point to the first or next value +** on the RHS of the IN constraint. ^If there are no more values on the +** right hand side of the IN constraint, then *P is set to NULL and these +** routines return [SQLITE_DONE]. ^The return value might be +** some other value, such as SQLITE_NOMEM, in the event of a malfunction. +** +** The *ppOut values returned by these routines are only valid until the +** next call to either of these routines or until the end of the xFilter +** method from which these routines were called. If the virtual table +** implementation needs to retain the *ppOut values for longer, it must make +** copies. The *ppOut values are [protected sqlite3_value|protected]. +*/ +SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut); +SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut); + +/* +** CAPI3REF: Constraint values in xBestIndex() +** METHOD: sqlite3_index_info +** +** This API may only be used from within the [xBestIndex|xBestIndex method] +** of a [virtual table] implementation. The result of calling this interface +** from outside of an xBestIndex method are undefined and probably harmful. +** +** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within +** the [xBestIndex] method of a [virtual table] implementation, with P being +** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and +** J being a 0-based index into P->aConstraint[], then this routine +** attempts to set *V to the value of the right-hand operand of +** that constraint if the right-hand operand is known. ^If the +** right-hand operand is not known, then *V is set to a NULL pointer. +** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if +** and only if *V is set to a value. ^The sqlite3_vtab_rhs_value(P,J,V) +** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th +** constraint is not available. ^The sqlite3_vtab_rhs_value() interface +** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if +** something goes wrong. +** +** The sqlite3_vtab_rhs_value() interface is usually only successful if +** the right-hand operand of a constraint is a literal value in the original +** SQL statement. If the right-hand operand is an expression or a reference +** to some other column or a [host parameter], then sqlite3_vtab_rhs_value() +** will probably return [SQLITE_NOTFOUND]. +** +** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and +** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand. For such +** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^ +** +** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value +** and remains valid for the duration of the xBestIndex method call. +** ^When xBestIndex returns, the sqlite3_value object returned by +** sqlite3_vtab_rhs_value() is automatically deallocated. +** +** The "_rhs_" in the name of this routine is an abbreviation for +** "Right-Hand Side". +*/ +SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal); + +/* +** CAPI3REF: Conflict resolution modes +** KEYWORDS: {conflict resolution mode} +** +** These constants are returned by [sqlite3_vtab_on_conflict()] to +** inform a [virtual table] implementation what the [ON CONFLICT] mode +** is for the SQL statement being evaluated. +** +** Note that the [SQLITE_IGNORE] constant is also used as a potential +** return value from the [sqlite3_set_authorizer()] callback and that +** [SQLITE_ABORT] is also a [result code]. +*/ +#define SQLITE_ROLLBACK 1 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +#define SQLITE_FAIL 3 +/* #define SQLITE_ABORT 4 // Also an error code */ +#define SQLITE_REPLACE 5 + +/* +** CAPI3REF: Prepared Statement Scan Status Opcodes +** KEYWORDS: {scanstatus options} +** +** The following constants can be used for the T parameter to the +** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a +** different metric for sqlite3_stmt_scanstatus() to return. +** +** When the value returned to V is a string, space to hold that string is +** managed by the prepared statement S and will be automatically freed when +** S is finalized. +** +** Not all values are available for all query elements. When a value is +** not available, the output variable is set to -1 if the value is numeric, +** or to NULL if it is a string (SQLITE_SCANSTAT_NAME). +** +**
+** [[SQLITE_SCANSTAT_NLOOP]]
SQLITE_SCANSTAT_NLOOP
+**
^The [sqlite3_int64] variable pointed to by the V parameter will be +** set to the total number of times that the X-th loop has run.
+** +** [[SQLITE_SCANSTAT_NVISIT]]
SQLITE_SCANSTAT_NVISIT
+**
^The [sqlite3_int64] variable pointed to by the V parameter will be set +** to the total number of rows examined by all iterations of the X-th loop.
+** +** [[SQLITE_SCANSTAT_EST]]
SQLITE_SCANSTAT_EST
+**
^The "double" variable pointed to by the V parameter will be set to the +** query planner's estimate for the average number of rows output from each +** iteration of the X-th loop. If the query planner's estimates was accurate, +** then this value will approximate the quotient NVISIT/NLOOP and the +** product of this value for all prior loops with the same SELECTID will +** be the NLOOP value for the current loop. +** +** [[SQLITE_SCANSTAT_NAME]]
SQLITE_SCANSTAT_NAME
+**
^The "const char *" variable pointed to by the V parameter will be set +** to a zero-terminated UTF-8 string containing the name of the index or table +** used for the X-th loop. +** +** [[SQLITE_SCANSTAT_EXPLAIN]]
SQLITE_SCANSTAT_EXPLAIN
+**
^The "const char *" variable pointed to by the V parameter will be set +** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] +** description for the X-th loop. +** +** [[SQLITE_SCANSTAT_SELECTID]]
SQLITE_SCANSTAT_SELECTID
+**
^The "int" variable pointed to by the V parameter will be set to the +** id for the X-th query plan element. The id value is unique within the +** statement. The select-id is the same value as is output in the first +** column of an [EXPLAIN QUERY PLAN] query. +** +** [[SQLITE_SCANSTAT_PARENTID]]
SQLITE_SCANSTAT_PARENTID
+**
The "int" variable pointed to by the V parameter will be set to the +** the id of the parent of the current query element, if applicable, or +** to zero if the query element has no parent. This is the same value as +** returned in the second column of an [EXPLAIN QUERY PLAN] query. +** +** [[SQLITE_SCANSTAT_NCYCLE]]
SQLITE_SCANSTAT_NCYCLE
+**
The sqlite3_int64 output value is set to the number of cycles, +** according to the processor time-stamp counter, that elapsed while the +** query element was being processed. This value is not available for +** all query elements - if it is unavailable the output variable is +** set to -1. +**
+*/ +#define SQLITE_SCANSTAT_NLOOP 0 +#define SQLITE_SCANSTAT_NVISIT 1 +#define SQLITE_SCANSTAT_EST 2 +#define SQLITE_SCANSTAT_NAME 3 +#define SQLITE_SCANSTAT_EXPLAIN 4 +#define SQLITE_SCANSTAT_SELECTID 5 +#define SQLITE_SCANSTAT_PARENTID 6 +#define SQLITE_SCANSTAT_NCYCLE 7 + +/* +** CAPI3REF: Prepared Statement Scan Status +** METHOD: sqlite3_stmt +** +** These interfaces return information about the predicted and measured +** performance for pStmt. Advanced applications can use this +** interface to compare the predicted and the measured performance and +** issue warnings and/or rerun [ANALYZE] if discrepancies are found. +** +** Since this interface is expected to be rarely used, it is only +** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS] +** compile-time option. +** +** The "iScanStatusOp" parameter determines which status information to return. +** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior +** of this interface is undefined. ^The requested measurement is written into +** a variable pointed to by the "pOut" parameter. +** +** The "flags" parameter must be passed a mask of flags. At present only +** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX +** is specified, then status information is available for all elements +** of a query plan that are reported by "EXPLAIN QUERY PLAN" output. If +** SQLITE_SCANSTAT_COMPLEX is not specified, then only query plan elements +** that correspond to query loops (the "SCAN..." and "SEARCH..." elements of +** the EXPLAIN QUERY PLAN output) are available. Invoking API +** sqlite3_stmt_scanstatus() is equivalent to calling +** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter. +** +** Parameter "idx" identifies the specific query element to retrieve statistics +** for. Query elements are numbered starting from zero. A value of -1 may be +** to query for statistics regarding the entire query. ^If idx is out of range +** - less than -1 or greater than or equal to the total number of query +** elements used to implement the statement - a non-zero value is returned and +** the variable that pOut points to is unchanged. +** +** See also: [sqlite3_stmt_scanstatus_reset()] +*/ +SQLITE_API int sqlite3_stmt_scanstatus( + sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ + int idx, /* Index of loop to report on */ + int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ + void *pOut /* Result written here */ +); +SQLITE_API int sqlite3_stmt_scanstatus_v2( + sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ + int idx, /* Index of loop to report on */ + int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ + int flags, /* Mask of flags defined below */ + void *pOut /* Result written here */ +); + +/* +** CAPI3REF: Prepared Statement Scan Status +** KEYWORDS: {scan status flags} +*/ +#define SQLITE_SCANSTAT_COMPLEX 0x0001 + +/* +** CAPI3REF: Zero Scan-Status Counters +** METHOD: sqlite3_stmt +** +** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. +** +** This API is only available if the library is built with pre-processor +** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. +*/ +SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); + +/* +** CAPI3REF: Flush caches to disk mid-transaction +** METHOD: sqlite3 +** +** ^If a write-transaction is open on [database connection] D when the +** [sqlite3_db_cacheflush(D)] interface invoked, any dirty +** pages in the pager-cache that are not currently in use are written out +** to disk. A dirty page may be in use if a database cursor created by an +** active SQL statement is reading from it, or if it is page 1 of a database +** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] +** interface flushes caches for all schemas - "main", "temp", and +** any [attached] databases. +** +** ^If this function needs to obtain extra database locks before dirty pages +** can be flushed to disk, it does so. ^If those locks cannot be obtained +** immediately and there is a busy-handler callback configured, it is invoked +** in the usual manner. ^If the required lock still cannot be obtained, then +** the database is skipped and an attempt made to flush any dirty pages +** belonging to the next (if any) database. ^If any databases are skipped +** because locks cannot be obtained, but no other error occurs, this +** function returns SQLITE_BUSY. +** +** ^If any other error occurs while flushing dirty pages to disk (for +** example an IO error or out-of-memory condition), then processing is +** abandoned and an SQLite [error code] is returned to the caller immediately. +** +** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. +** +** ^This function does not set the database handle error code or message +** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. +*/ +SQLITE_API int sqlite3_db_cacheflush(sqlite3*); + +/* +** CAPI3REF: The pre-update hook. +** METHOD: sqlite3 +** +** ^These interfaces are only available if SQLite is compiled using the +** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. +** +** ^The [sqlite3_preupdate_hook()] interface registers a callback function +** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation +** on a database table. +** ^At most one preupdate hook may be registered at a time on a single +** [database connection]; each call to [sqlite3_preupdate_hook()] overrides +** the previous setting. +** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] +** with a NULL pointer as the second parameter. +** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as +** the first parameter to callbacks. +** +** ^The preupdate hook only fires for changes to real database tables; the +** preupdate hook is not invoked for changes to [virtual tables] or to +** system tables like sqlite_sequence or sqlite_stat1. +** +** ^The second parameter to the preupdate callback is a pointer to +** the [database connection] that registered the preupdate hook. +** ^The third parameter to the preupdate callback is one of the constants +** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the +** kind of update operation that is about to occur. +** ^(The fourth parameter to the preupdate callback is the name of the +** database within the database connection that is being modified. This +** will be "main" for the main database or "temp" for TEMP tables or +** the name given after the AS keyword in the [ATTACH] statement for attached +** databases.)^ +** ^The fifth parameter to the preupdate callback is the name of the +** table that is being modified. +** +** For an UPDATE or DELETE operation on a [rowid table], the sixth +** parameter passed to the preupdate callback is the initial [rowid] of the +** row being modified or deleted. For an INSERT operation on a rowid table, +** or any operation on a WITHOUT ROWID table, the value of the sixth +** parameter is undefined. For an INSERT or UPDATE on a rowid table the +** seventh parameter is the final rowid value of the row being inserted +** or updated. The value of the seventh parameter passed to the callback +** function is not defined for operations on WITHOUT ROWID tables, or for +** DELETE operations on rowid tables. +** +** ^The sqlite3_preupdate_hook(D,C,P) function returns the P argument from +** the previous call on the same [database connection] D, or NULL for +** the first call on D. +** +** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], +** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces +** provide additional information about a preupdate event. These routines +** may only be called from within a preupdate callback. Invoking any of +** these routines from outside of a preupdate callback or with a +** [database connection] pointer that is different from the one supplied +** to the preupdate callback results in undefined and probably undesirable +** behavior. +** +** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns +** in the row that is being inserted, updated, or deleted. +** +** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to +** a [protected sqlite3_value] that contains the value of the Nth column of +** the table row before it is updated. The N parameter must be between 0 +** and one less than the number of columns or the behavior will be +** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE +** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the +** behavior is undefined. The [sqlite3_value] that P points to +** will be destroyed when the preupdate callback returns. +** +** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to +** a [protected sqlite3_value] that contains the value of the Nth column of +** the table row after it is updated. The N parameter must be between 0 +** and one less than the number of columns or the behavior will be +** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE +** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the +** behavior is undefined. The [sqlite3_value] that P points to +** will be destroyed when the preupdate callback returns. +** +** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate +** callback was invoked as a result of a direct insert, update, or delete +** operation; or 1 for inserts, updates, or deletes invoked by top-level +** triggers; or 2 for changes resulting from triggers called by top-level +** triggers; and so forth. +** +** When the [sqlite3_blob_write()] API is used to update a blob column, +** the pre-update hook is invoked with SQLITE_DELETE. This is because the +** in this case the new values are not available. In this case, when a +** callback made with op==SQLITE_DELETE is actually a write using the +** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns +** the index of the column being written. In other cases, where the +** pre-update hook is being invoked for some other reason, including a +** regular DELETE, sqlite3_preupdate_blobwrite() returns -1. +** +** See also: [sqlite3_update_hook()] +*/ +#if defined(SQLITE_ENABLE_PREUPDATE_HOOK) +SQLITE_API void *sqlite3_preupdate_hook( + sqlite3 *db, + void(*xPreUpdate)( + void *pCtx, /* Copy of third arg to preupdate_hook() */ + sqlite3 *db, /* Database handle */ + int op, /* SQLITE_UPDATE, DELETE or INSERT */ + char const *zDb, /* Database name */ + char const *zName, /* Table name */ + sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ + sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ + ), + void* +); +SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); +SQLITE_API int sqlite3_preupdate_count(sqlite3 *); +SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); +SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); +SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *); +#endif + +/* +** CAPI3REF: Low-level system error code +** METHOD: sqlite3 +** +** ^Attempt to return the underlying operating system error code or error +** number that caused the most recent I/O error or failure to open a file. +** The return value is OS-dependent. For example, on unix systems, after +** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be +** called to get back the underlying "errno" that caused the problem, such +** as ENOSPC, EAUTH, EISDIR, and so forth. +*/ +SQLITE_API int sqlite3_system_errno(sqlite3*); + +/* +** CAPI3REF: Database Snapshot +** KEYWORDS: {snapshot} {sqlite3_snapshot} +** +** An instance of the snapshot object records the state of a [WAL mode] +** database for some specific point in history. +** +** In [WAL mode], multiple [database connections] that are open on the +** same database file can each be reading a different historical version +** of the database file. When a [database connection] begins a read +** transaction, that connection sees an unchanging copy of the database +** as it existed for the point in time when the transaction first started. +** Subsequent changes to the database from other connections are not seen +** by the reader until a new read transaction is started. +** +** The sqlite3_snapshot object records state information about an historical +** version of the database file so that it is possible to later open a new read +** transaction that sees that historical version of the database rather than +** the most recent version. +*/ +typedef struct sqlite3_snapshot { + unsigned char hidden[48]; +} sqlite3_snapshot; + +/* +** CAPI3REF: Record A Database Snapshot +** CONSTRUCTOR: sqlite3_snapshot +** +** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a +** new [sqlite3_snapshot] object that records the current state of +** schema S in database connection D. ^On success, the +** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly +** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. +** If there is not already a read-transaction open on schema S when +** this function is called, one is opened automatically. +** +** If a read-transaction is opened by this function, then it is guaranteed +** that the returned snapshot object may not be invalidated by a database +** writer or checkpointer until after the read-transaction is closed. This +** is not guaranteed if a read-transaction is already open when this +** function is called. In that case, any subsequent write or checkpoint +** operation on the database may invalidate the returned snapshot handle, +** even while the read-transaction remains open. +** +** The following must be true for this function to succeed. If any of +** the following statements are false when sqlite3_snapshot_get() is +** called, SQLITE_ERROR is returned. The final value of *P is undefined +** in this case. +** +**
    +**
  • The database handle must not be in [autocommit mode]. +** +**
  • Schema S of [database connection] D must be a [WAL mode] database. +** +**
  • There must not be a write transaction open on schema S of database +** connection D. +** +**
  • One or more transactions must have been written to the current wal +** file since it was created on disk (by any connection). This means +** that a snapshot cannot be taken on a wal mode database with no wal +** file immediately after it is first opened. At least one transaction +** must be written to it first. +**
+** +** This function may also return SQLITE_NOMEM. If it is called with the +** database handle in autocommit mode but fails for some other reason, +** whether or not a read transaction is opened on schema S is undefined. +** +** The [sqlite3_snapshot] object returned from a successful call to +** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] +** to avoid a memory leak. +** +** The [sqlite3_snapshot_get()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot **ppSnapshot +); + +/* +** CAPI3REF: Start a read transaction on an historical snapshot +** METHOD: sqlite3_snapshot +** +** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read +** transaction or upgrades an existing one for schema S of +** [database connection] D such that the read transaction refers to +** historical [snapshot] P, rather than the most recent change to the +** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK +** on success or an appropriate [error code] if it fails. +** +** ^In order to succeed, the database connection must not be in +** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there +** is already a read transaction open on schema S, then the database handle +** must have no active statements (SELECT statements that have been passed +** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). +** SQLITE_ERROR is returned if either of these conditions is violated, or +** if schema S does not exist, or if the snapshot object is invalid. +** +** ^A call to sqlite3_snapshot_open() will fail to open if the specified +** snapshot has been overwritten by a [checkpoint]. In this case +** SQLITE_ERROR_SNAPSHOT is returned. +** +** If there is already a read transaction open when this function is +** invoked, then the same read transaction remains open (on the same +** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT +** is returned. If another error code - for example SQLITE_PROTOCOL or an +** SQLITE_IOERR error code - is returned, then the final state of the +** read transaction is undefined. If SQLITE_OK is returned, then the +** read transaction is now open on database snapshot P. +** +** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the +** database connection D does not know that the database file for +** schema S is in [WAL mode]. A database connection might not know +** that the database file is in [WAL mode] if there has been no prior +** I/O on that database connection, or if the database entered [WAL mode] +** after the most recent I/O on the database connection.)^ +** (Hint: Run "[PRAGMA application_id]" against a newly opened +** database connection in order to make it ready to use snapshots.) +** +** The [sqlite3_snapshot_open()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( + sqlite3 *db, + const char *zSchema, + sqlite3_snapshot *pSnapshot +); + +/* +** CAPI3REF: Destroy a snapshot +** DESTRUCTOR: sqlite3_snapshot +** +** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. +** The application must eventually free every [sqlite3_snapshot] object +** using this routine to avoid a memory leak. +** +** The [sqlite3_snapshot_free()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. +*/ +SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); + +/* +** CAPI3REF: Compare the ages of two snapshot handles. +** METHOD: sqlite3_snapshot +** +** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages +** of two valid snapshot handles. +** +** If the two snapshot handles are not associated with the same database +** file, the result of the comparison is undefined. +** +** Additionally, the result of the comparison is only valid if both of the +** snapshot handles were obtained by calling sqlite3_snapshot_get() since the +** last time the wal file was deleted. The wal file is deleted when the +** database is changed back to rollback mode or when the number of database +** clients drops to zero. If either snapshot handle was obtained before the +** wal file was last deleted, the value returned by this function +** is undefined. +** +** Otherwise, this API returns a negative value if P1 refers to an older +** snapshot than P2, zero if the two handles refer to the same database +** snapshot, and a positive value if P1 is a newer snapshot than P2. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SNAPSHOT] option. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( + sqlite3_snapshot *p1, + sqlite3_snapshot *p2 +); + +/* +** CAPI3REF: Recover snapshots from a wal file +** METHOD: sqlite3_snapshot +** +** If a [WAL file] remains on disk after all database connections close +** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control] +** or because the last process to have the database opened exited without +** calling [sqlite3_close()]) and a new connection is subsequently opened +** on that database and [WAL file], the [sqlite3_snapshot_open()] interface +** will only be able to open the last transaction added to the WAL file +** even though the WAL file contains other valid transactions. +** +** This function attempts to scan the WAL file associated with database zDb +** of database handle db and make all valid snapshots available to +** sqlite3_snapshot_open(). It is an error if there is already a read +** transaction open on the database, or if the database is not a WAL mode +** database. +** +** SQLITE_OK is returned if successful, or an SQLite error code otherwise. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SNAPSHOT] option. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Serialize a database +** +** The sqlite3_serialize(D,S,P,F) interface returns a pointer to +** memory that is a serialization of the S database on +** [database connection] D. If S is a NULL pointer, the main database is used. +** If P is not a NULL pointer, then the size of the database in bytes +** is written into *P. +** +** For an ordinary on-disk database file, the serialization is just a +** copy of the disk file. For an in-memory database or a "TEMP" database, +** the serialization is the same sequence of bytes which would be written +** to disk if that database where backed up to disk. +** +** The usual case is that sqlite3_serialize() copies the serialization of +** the database into memory obtained from [sqlite3_malloc64()] and returns +** a pointer to that memory. The caller is responsible for freeing the +** returned value to avoid a memory leak. However, if the F argument +** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations +** are made, and the sqlite3_serialize() function will return a pointer +** to the contiguous memory representation of the database that SQLite +** is currently using for that database, or NULL if the no such contiguous +** memory representation of the database exists. A contiguous memory +** representation of the database will usually only exist if there has +** been a prior call to [sqlite3_deserialize(D,S,...)] with the same +** values of D and S. +** The size of the database is written into *P even if the +** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy +** of the database exists. +** +** After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set, +** the returned buffer content will remain accessible and unchanged +** until either the next write operation on the connection or when +** the connection is closed, and applications must not modify the +** buffer. If the bit had been clear, the returned buffer will not +** be accessed by SQLite after the call. +** +** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the +** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory +** allocation error occurs. +** +** This interface is omitted if SQLite is compiled with the +** [SQLITE_OMIT_DESERIALIZE] option. +*/ +SQLITE_API unsigned char *sqlite3_serialize( + sqlite3 *db, /* The database connection */ + const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */ + sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */ + unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */ +); + +/* +** CAPI3REF: Flags for sqlite3_serialize +** +** Zero or more of the following constants can be OR-ed together for +** the F argument to [sqlite3_serialize(D,S,P,F)]. +** +** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return +** a pointer to contiguous in-memory database that it is currently using, +** without making a copy of the database. If SQLite is not currently using +** a contiguous in-memory database, then this option causes +** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be +** using a contiguous in-memory database if it has been initialized by a +** prior call to [sqlite3_deserialize()]. +*/ +#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */ + +/* +** CAPI3REF: Deserialize a database +** +** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the +** [database connection] D to disconnect from database S and then +** reopen S as an in-memory database based on the serialization contained +** in P. The serialized database P is N bytes in size. M is the size of +** the buffer P, which might be larger than N. If M is larger than N, and +** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is +** permitted to add content to the in-memory database as long as the total +** size does not exceed M bytes. +** +** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will +** invoke sqlite3_free() on the serialization buffer when the database +** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then +** SQLite will try to increase the buffer size using sqlite3_realloc64() +** if writes on the database cause it to grow larger than M bytes. +** +** Applications must not modify the buffer P or invalidate it before +** the database connection D is closed. +** +** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the +** database is currently in a read transaction or is involved in a backup +** operation. +** +** It is not possible to deserialized into the TEMP database. If the +** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the +** function returns SQLITE_ERROR. +** +** The deserialized database should not be in [WAL mode]. If the database +** is in WAL mode, then any attempt to use the database file will result +** in an [SQLITE_CANTOPEN] error. The application can set the +** [file format version numbers] (bytes 18 and 19) of the input database P +** to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the +** database file into rollback mode and work around this limitation. +** +** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the +** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then +** [sqlite3_free()] is invoked on argument P prior to returning. +** +** This interface is omitted if SQLite is compiled with the +** [SQLITE_OMIT_DESERIALIZE] option. +*/ +SQLITE_API int sqlite3_deserialize( + sqlite3 *db, /* The database connection */ + const char *zSchema, /* Which DB to reopen with the deserialization */ + unsigned char *pData, /* The serialized database content */ + sqlite3_int64 szDb, /* Number bytes in the deserialization */ + sqlite3_int64 szBuf, /* Total size of buffer pData[] */ + unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ +); + +/* +** CAPI3REF: Flags for sqlite3_deserialize() +** +** The following are allowed values for 6th argument (the F argument) to +** the [sqlite3_deserialize(D,S,P,N,M,F)] interface. +** +** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization +** in the P argument is held in memory obtained from [sqlite3_malloc64()] +** and that SQLite should take ownership of this memory and automatically +** free it when it has finished using it. Without this flag, the caller +** is responsible for freeing any dynamically allocated memory. +** +** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to +** grow the size of the database using calls to [sqlite3_realloc64()]. This +** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used. +** Without this flag, the deserialized database cannot increase in size beyond +** the number of bytes specified by the M parameter. +** +** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database +** should be treated as read-only. +*/ +#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */ +#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */ +#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */ + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if defined(__wasi__) +# undef SQLITE_WASI +# define SQLITE_WASI 1 +# ifndef SQLITE_OMIT_LOAD_EXTENSION +# define SQLITE_OMIT_LOAD_EXTENSION +# endif +# ifndef SQLITE_THREADSAFE +# define SQLITE_THREADSAFE 0 +# endif +#endif + +#ifdef __cplusplus +} /* End of the 'extern "C"' block */ +#endif +/* #endif for SQLITE3_H will be added by mksqlite3.tcl */ + +/******** Begin file sqlite3rtree.h *********/ +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; +typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; + +/* The double-precision datatype used by RTree depends on the +** SQLITE_RTREE_INT_ONLY compile-time option. +*/ +#ifdef SQLITE_RTREE_INT_ONLY + typedef sqlite3_int64 sqlite3_rtree_dbl; +#else + typedef double sqlite3_rtree_dbl; +#endif + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, + int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + +/* +** Register a 2nd-generation geometry callback named zScore that can be +** used as part of an R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zQueryFunc(... params ...) +*/ +SQLITE_API int sqlite3_rtree_query_callback( + sqlite3 *db, + const char *zQueryFunc, + int (*xQueryFunc)(sqlite3_rtree_query_info*), + void *pContext, + void (*xDestructor)(void*) +); + + +/* +** A pointer to a structure of the following type is passed as the +** argument to scored geometry callback registered using +** sqlite3_rtree_query_callback(). +** +** Note that the first 5 fields of this structure are identical to +** sqlite3_rtree_geometry. This structure is a subclass of +** sqlite3_rtree_geometry. +*/ +struct sqlite3_rtree_query_info { + void *pContext; /* pContext from when function registered */ + int nParam; /* Number of function parameters */ + sqlite3_rtree_dbl *aParam; /* value of function parameters */ + void *pUser; /* callback can use this, if desired */ + void (*xDelUser)(void*); /* function to free pUser */ + sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ + unsigned int *anQueue; /* Number of pending entries in the queue */ + int nCoord; /* Number of coordinates */ + int iLevel; /* Level of current node or entry */ + int mxLevel; /* The largest iLevel value in the tree */ + sqlite3_int64 iRowid; /* Rowid for current entry */ + sqlite3_rtree_dbl rParentScore; /* Score of parent node */ + int eParentWithin; /* Visibility of parent node */ + int eWithin; /* OUT: Visibility */ + sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ + /* The following fields are only available in 3.8.11 and later */ + sqlite3_value **apSqlParam; /* Original SQL values of parameters */ +}; + +/* +** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. +*/ +#define NOT_WITHIN 0 /* Object completely outside of query region */ +#define PARTLY_WITHIN 1 /* Object partially overlaps query region */ +#define FULLY_WITHIN 2 /* Object fully contained within query region */ + + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ + +/******** End of sqlite3rtree.h *********/ +/******** Begin file sqlite3session.h *********/ + +#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) +#define __SQLITESESSION_H_ 1 + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +extern "C" { +#endif + + +/* +** CAPI3REF: Session Object Handle +** +** An instance of this object is a [session] that can be used to +** record changes to a database. +*/ +typedef struct sqlite3_session sqlite3_session; + +/* +** CAPI3REF: Changeset Iterator Handle +** +** An instance of this object acts as a cursor for iterating +** over the elements of a [changeset] or [patchset]. +*/ +typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; + +/* +** CAPI3REF: Create A New Session Object +** CONSTRUCTOR: sqlite3_session +** +** Create a new session object attached to database handle db. If successful, +** a pointer to the new object is written to *ppSession and SQLITE_OK is +** returned. If an error occurs, *ppSession is set to NULL and an SQLite +** error code (e.g. SQLITE_NOMEM) is returned. +** +** It is possible to create multiple session objects attached to a single +** database handle. +** +** Session objects created using this function should be deleted using the +** [sqlite3session_delete()] function before the database handle that they +** are attached to is itself closed. If the database handle is closed before +** the session object is deleted, then the results of calling any session +** module function, including [sqlite3session_delete()] on the session object +** are undefined. +** +** Because the session module uses the [sqlite3_preupdate_hook()] API, it +** is not possible for an application to register a pre-update hook on a +** database handle that has one or more session objects attached. Nor is +** it possible to create a session object attached to a database handle for +** which a pre-update hook is already defined. The results of attempting +** either of these things are undefined. +** +** The session object will be used to create changesets for tables in +** database zDb, where zDb is either "main", or "temp", or the name of an +** attached database. It is not an error if database zDb is not attached +** to the database when the session object is created. +*/ +SQLITE_API int sqlite3session_create( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of db (e.g. "main") */ + sqlite3_session **ppSession /* OUT: New session object */ +); + +/* +** CAPI3REF: Delete A Session Object +** DESTRUCTOR: sqlite3_session +** +** Delete a session object previously allocated using +** [sqlite3session_create()]. Once a session object has been deleted, the +** results of attempting to use pSession with any other session module +** function are undefined. +** +** Session objects must be deleted before the database handle to which they +** are attached is closed. Refer to the documentation for +** [sqlite3session_create()] for details. +*/ +SQLITE_API void sqlite3session_delete(sqlite3_session *pSession); + +/* +** CAPI3REF: Configure a Session Object +** METHOD: sqlite3_session +** +** This method is used to configure a session object after it has been +** created. At present the only valid values for the second parameter are +** [SQLITE_SESSION_OBJCONFIG_SIZE] and [SQLITE_SESSION_OBJCONFIG_ROWID]. +** +*/ +SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg); + +/* +** CAPI3REF: Options for sqlite3session_object_config +** +** The following values may passed as the the 2nd parameter to +** sqlite3session_object_config(). +** +**
SQLITE_SESSION_OBJCONFIG_SIZE
+** This option is used to set, clear or query the flag that enables +** the [sqlite3session_changeset_size()] API. Because it imposes some +** computational overhead, this API is disabled by default. Argument +** pArg must point to a value of type (int). If the value is initially +** 0, then the sqlite3session_changeset_size() API is disabled. If it +** is greater than 0, then the same API is enabled. Or, if the initial +** value is less than zero, no change is made. In all cases the (int) +** variable is set to 1 if the sqlite3session_changeset_size() API is +** enabled following the current call, or 0 otherwise. +** +** It is an error (SQLITE_MISUSE) to attempt to modify this setting after +** the first table has been attached to the session object. +** +**
SQLITE_SESSION_OBJCONFIG_ROWID
+** This option is used to set, clear or query the flag that enables +** collection of data for tables with no explicit PRIMARY KEY. +** +** Normally, tables with no explicit PRIMARY KEY are simply ignored +** by the sessions module. However, if this flag is set, it behaves +** as if such tables have a column "_rowid_ INTEGER PRIMARY KEY" inserted +** as their leftmost columns. +** +** It is an error (SQLITE_MISUSE) to attempt to modify this setting after +** the first table has been attached to the session object. +*/ +#define SQLITE_SESSION_OBJCONFIG_SIZE 1 +#define SQLITE_SESSION_OBJCONFIG_ROWID 2 + +/* +** CAPI3REF: Enable Or Disable A Session Object +** METHOD: sqlite3_session +** +** Enable or disable the recording of changes by a session object. When +** enabled, a session object records changes made to the database. When +** disabled - it does not. A newly created session object is enabled. +** Refer to the documentation for [sqlite3session_changeset()] for further +** details regarding how enabling and disabling a session object affects +** the eventual changesets. +** +** Passing zero to this function disables the session. Passing a value +** greater than zero enables it. Passing a value less than zero is a +** no-op, and may be used to query the current state of the session. +** +** The return value indicates the final state of the session object: 0 if +** the session is disabled, or 1 if it is enabled. +*/ +SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable); + +/* +** CAPI3REF: Set Or Clear the Indirect Change Flag +** METHOD: sqlite3_session +** +** Each change recorded by a session object is marked as either direct or +** indirect. A change is marked as indirect if either: +** +**
    +**
  • The session object "indirect" flag is set when the change is +** made, or +**
  • The change is made by an SQL trigger or foreign key action +** instead of directly as a result of a users SQL statement. +**
+** +** If a single row is affected by more than one operation within a session, +** then the change is considered indirect if all operations meet the criteria +** for an indirect change above, or direct otherwise. +** +** This function is used to set, clear or query the session object indirect +** flag. If the second argument passed to this function is zero, then the +** indirect flag is cleared. If it is greater than zero, the indirect flag +** is set. Passing a value less than zero does not modify the current value +** of the indirect flag, and may be used to query the current state of the +** indirect flag for the specified session object. +** +** The return value indicates the final state of the indirect flag: 0 if +** it is clear, or 1 if it is set. +*/ +SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); + +/* +** CAPI3REF: Attach A Table To A Session Object +** METHOD: sqlite3_session +** +** If argument zTab is not NULL, then it is the name of a table to attach +** to the session object passed as the first argument. All subsequent changes +** made to the table while the session object is enabled will be recorded. See +** documentation for [sqlite3session_changeset()] for further details. +** +** Or, if argument zTab is NULL, then changes are recorded for all tables +** in the database. If additional tables are added to the database (by +** executing "CREATE TABLE" statements) after this call is made, changes for +** the new tables are also recorded. +** +** Changes can only be recorded for tables that have a PRIMARY KEY explicitly +** defined as part of their CREATE TABLE statement. It does not matter if the +** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY +** KEY may consist of a single column, or may be a composite key. +** +** It is not an error if the named table does not exist in the database. Nor +** is it an error if the named table does not have a PRIMARY KEY. However, +** no changes will be recorded in either of these scenarios. +** +** Changes are not recorded for individual rows that have NULL values stored +** in one or more of their PRIMARY KEY columns. +** +** SQLITE_OK is returned if the call completes without error. Or, if an error +** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. +** +**

Special sqlite_stat1 Handling

+** +** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to +** some of the rules above. In SQLite, the schema of sqlite_stat1 is: +**
+**        CREATE TABLE sqlite_stat1(tbl,idx,stat)
+**  
+** +** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are +** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes +** are recorded for rows for which (idx IS NULL) is true. However, for such +** rows a zero-length blob (SQL value X'') is stored in the changeset or +** patchset instead of a NULL value. This allows such changesets to be +** manipulated by legacy implementations of sqlite3changeset_invert(), +** concat() and similar. +** +** The sqlite3changeset_apply() function automatically converts the +** zero-length blob back to a NULL value when updating the sqlite_stat1 +** table. However, if the application calls sqlite3changeset_new(), +** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset +** iterator directly (including on a changeset iterator passed to a +** conflict-handler callback) then the X'' value is returned. The application +** must translate X'' to NULL itself if required. +** +** Legacy (older than 3.22.0) versions of the sessions module cannot capture +** changes made to the sqlite_stat1 table. Legacy versions of the +** sqlite3changeset_apply() function silently ignore any modifications to the +** sqlite_stat1 table that are part of a changeset or patchset. +*/ +SQLITE_API int sqlite3session_attach( + sqlite3_session *pSession, /* Session object */ + const char *zTab /* Table name */ +); + +/* +** CAPI3REF: Set a table filter on a Session Object. +** METHOD: sqlite3_session +** +** The second argument (xFilter) is the "filter callback". For changes to rows +** in tables that are not attached to the Session object, the filter is called +** to determine whether changes to the table's rows should be tracked or not. +** If xFilter returns 0, changes are not tracked. Note that once a table is +** attached, xFilter will not be called again. +*/ +SQLITE_API void sqlite3session_table_filter( + sqlite3_session *pSession, /* Session object */ + int(*xFilter)( + void *pCtx, /* Copy of third arg to _filter_table() */ + const char *zTab /* Table name */ + ), + void *pCtx /* First argument passed to xFilter */ +); + +/* +** CAPI3REF: Generate A Changeset From A Session Object +** METHOD: sqlite3_session +** +** Obtain a changeset containing changes to the tables attached to the +** session object passed as the first argument. If successful, +** set *ppChangeset to point to a buffer containing the changeset +** and *pnChangeset to the size of the changeset in bytes before returning +** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to +** zero and return an SQLite error code. +** +** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes, +** each representing a change to a single row of an attached table. An INSERT +** change contains the values of each field of a new database row. A DELETE +** contains the original values of each field of a deleted database row. An +** UPDATE change contains the original values of each field of an updated +** database row along with the updated values for each updated non-primary-key +** column. It is not possible for an UPDATE change to represent a change that +** modifies the values of primary key columns. If such a change is made, it +** is represented in a changeset as a DELETE followed by an INSERT. +** +** Changes are not recorded for rows that have NULL values stored in one or +** more of their PRIMARY KEY columns. If such a row is inserted or deleted, +** no corresponding change is present in the changesets returned by this +** function. If an existing row with one or more NULL values stored in +** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL, +** only an INSERT is appears in the changeset. Similarly, if an existing row +** with non-NULL PRIMARY KEY values is updated so that one or more of its +** PRIMARY KEY columns are set to NULL, the resulting changeset contains a +** DELETE change only. +** +** The contents of a changeset may be traversed using an iterator created +** using the [sqlite3changeset_start()] API. A changeset may be applied to +** a database with a compatible schema using the [sqlite3changeset_apply()] +** API. +** +** Within a changeset generated by this function, all changes related to a +** single table are grouped together. In other words, when iterating through +** a changeset or when applying a changeset to a database, all changes related +** to a single table are processed before moving on to the next table. Tables +** are sorted in the same order in which they were attached (or auto-attached) +** to the sqlite3_session object. The order in which the changes related to +** a single table are stored is undefined. +** +** Following a successful call to this function, it is the responsibility of +** the caller to eventually free the buffer that *ppChangeset points to using +** [sqlite3_free()]. +** +**

Changeset Generation

+** +** Once a table has been attached to a session object, the session object +** records the primary key values of all new rows inserted into the table. +** It also records the original primary key and other column values of any +** deleted or updated rows. For each unique primary key value, data is only +** recorded once - the first time a row with said primary key is inserted, +** updated or deleted in the lifetime of the session. +** +** There is one exception to the previous paragraph: when a row is inserted, +** updated or deleted, if one or more of its primary key columns contain a +** NULL value, no record of the change is made. +** +** The session object therefore accumulates two types of records - those +** that consist of primary key values only (created when the user inserts +** a new record) and those that consist of the primary key values and the +** original values of other table columns (created when the users deletes +** or updates a record). +** +** When this function is called, the requested changeset is created using +** both the accumulated records and the current contents of the database +** file. Specifically: +** +**
    +**
  • For each record generated by an insert, the database is queried +** for a row with a matching primary key. If one is found, an INSERT +** change is added to the changeset. If no such row is found, no change +** is added to the changeset. +** +**
  • For each record generated by an update or delete, the database is +** queried for a row with a matching primary key. If such a row is +** found and one or more of the non-primary key fields have been +** modified from their original values, an UPDATE change is added to +** the changeset. Or, if no such row is found in the table, a DELETE +** change is added to the changeset. If there is a row with a matching +** primary key in the database, but all fields contain their original +** values, no change is added to the changeset. +**
+** +** This means, amongst other things, that if a row is inserted and then later +** deleted while a session object is active, neither the insert nor the delete +** will be present in the changeset. Or if a row is deleted and then later a +** row with the same primary key values inserted while a session object is +** active, the resulting changeset will contain an UPDATE change instead of +** a DELETE and an INSERT. +** +** When a session object is disabled (see the [sqlite3session_enable()] API), +** it does not accumulate records when rows are inserted, updated or deleted. +** This may appear to have some counter-intuitive effects if a single row +** is written to more than once during a session. For example, if a row +** is inserted while a session object is enabled, then later deleted while +** the same session object is disabled, no INSERT record will appear in the +** changeset, even though the delete took place while the session was disabled. +** Or, if one field of a row is updated while a session is enabled, and +** then another field of the same row is updated while the session is disabled, +** the resulting changeset will contain an UPDATE change that updates both +** fields. +*/ +SQLITE_API int sqlite3session_changeset( + sqlite3_session *pSession, /* Session object */ + int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ + void **ppChangeset /* OUT: Buffer containing changeset */ +); + +/* +** CAPI3REF: Return An Upper-limit For The Size Of The Changeset +** METHOD: sqlite3_session +** +** By default, this function always returns 0. For it to return +** a useful result, the sqlite3_session object must have been configured +** to enable this API using sqlite3session_object_config() with the +** SQLITE_SESSION_OBJCONFIG_SIZE verb. +** +** When enabled, this function returns an upper limit, in bytes, for the size +** of the changeset that might be produced if sqlite3session_changeset() were +** called. The final changeset size might be equal to or smaller than the +** size in bytes returned by this function. +*/ +SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession); + +/* +** CAPI3REF: Load The Difference Between Tables Into A Session +** METHOD: sqlite3_session +** +** If it is not already attached to the session object passed as the first +** argument, this function attaches table zTbl in the same manner as the +** [sqlite3session_attach()] function. If zTbl does not exist, or if it +** does not have a primary key, this function is a no-op (but does not return +** an error). +** +** Argument zFromDb must be the name of a database ("main", "temp" etc.) +** attached to the same database handle as the session object that contains +** a table compatible with the table attached to the session by this function. +** A table is considered compatible if it: +** +**
    +**
  • Has the same name, +**
  • Has the same set of columns declared in the same order, and +**
  • Has the same PRIMARY KEY definition. +**
+** +** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables +** are compatible but do not have any PRIMARY KEY columns, it is not an error +** but no changes are added to the session object. As with other session +** APIs, tables without PRIMARY KEYs are simply ignored. +** +** This function adds a set of changes to the session object that could be +** used to update the table in database zFrom (call this the "from-table") +** so that its content is the same as the table attached to the session +** object (call this the "to-table"). Specifically: +** +**
    +**
  • For each row (primary key) that exists in the to-table but not in +** the from-table, an INSERT record is added to the session object. +** +**
  • For each row (primary key) that exists in the to-table but not in +** the from-table, a DELETE record is added to the session object. +** +**
  • For each row (primary key) that exists in both tables, but features +** different non-PK values in each, an UPDATE record is added to the +** session. +**
+** +** To clarify, if this function is called and then a changeset constructed +** using [sqlite3session_changeset()], then after applying that changeset to +** database zFrom the contents of the two compatible tables would be +** identical. +** +** Unless the call to this function is a no-op as described above, it is an +** error if database zFrom does not exist or does not contain the required +** compatible table. +** +** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite +** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg +** may be set to point to a buffer containing an English language error +** message. It is the responsibility of the caller to free this buffer using +** sqlite3_free(). +*/ +SQLITE_API int sqlite3session_diff( + sqlite3_session *pSession, + const char *zFromDb, + const char *zTbl, + char **pzErrMsg +); + + +/* +** CAPI3REF: Generate A Patchset From A Session Object +** METHOD: sqlite3_session +** +** The differences between a patchset and a changeset are that: +** +**
    +**
  • DELETE records consist of the primary key fields only. The +** original values of other fields are omitted. +**
  • The original values of any modified fields are omitted from +** UPDATE records. +**
+** +** A patchset blob may be used with up to date versions of all +** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), +** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, +** attempting to use a patchset blob with old versions of the +** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. +** +** Because the non-primary key "old.*" fields are omitted, no +** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset +** is passed to the sqlite3changeset_apply() API. Other conflict types work +** in the same way as for changesets. +** +** Changes within a patchset are ordered in the same way as for changesets +** generated by the sqlite3session_changeset() function (i.e. all changes for +** a single table are grouped together, tables appear in the order in which +** they were attached to the session object). +*/ +SQLITE_API int sqlite3session_patchset( + sqlite3_session *pSession, /* Session object */ + int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */ + void **ppPatchset /* OUT: Buffer containing patchset */ +); + +/* +** CAPI3REF: Test if a changeset has recorded any changes. +** +** Return non-zero if no changes to attached tables have been recorded by +** the session object passed as the first argument. Otherwise, if one or +** more changes have been recorded, return zero. +** +** Even if this function returns zero, it is possible that calling +** [sqlite3session_changeset()] on the session handle may still return a +** changeset that contains no changes. This can happen when a row in +** an attached table is modified and then later on the original values +** are restored. However, if this function returns non-zero, then it is +** guaranteed that a call to sqlite3session_changeset() will return a +** changeset containing zero changes. +*/ +SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession); + +/* +** CAPI3REF: Query for the amount of heap memory used by a session object. +** +** This API returns the total amount of heap memory in bytes currently +** used by the session object passed as the only argument. +*/ +SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession); + +/* +** CAPI3REF: Create An Iterator To Traverse A Changeset +** CONSTRUCTOR: sqlite3_changeset_iter +** +** Create an iterator used to iterate through the contents of a changeset. +** If successful, *pp is set to point to the iterator handle and SQLITE_OK +** is returned. Otherwise, if an error occurs, *pp is set to zero and an +** SQLite error code is returned. +** +** The following functions can be used to advance and query a changeset +** iterator created by this function: +** +**
    +**
  • [sqlite3changeset_next()] +**
  • [sqlite3changeset_op()] +**
  • [sqlite3changeset_new()] +**
  • [sqlite3changeset_old()] +**
+** +** It is the responsibility of the caller to eventually destroy the iterator +** by passing it to [sqlite3changeset_finalize()]. The buffer containing the +** changeset (pChangeset) must remain valid until after the iterator is +** destroyed. +** +** Assuming the changeset blob was created by one of the +** [sqlite3session_changeset()], [sqlite3changeset_concat()] or +** [sqlite3changeset_invert()] functions, all changes within the changeset +** that apply to a single table are grouped together. This means that when +** an application iterates through a changeset using an iterator created by +** this function, all changes that relate to a single table are visited +** consecutively. There is no chance that the iterator will visit a change +** the applies to table X, then one for table Y, and then later on visit +** another change for table X. +** +** The behavior of sqlite3changeset_start_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter. +** +** Note that the sqlite3changeset_start_v2() API is still experimental +** and therefore subject to change. +*/ +SQLITE_API int sqlite3changeset_start( + sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ + int nChangeset, /* Size of changeset blob in bytes */ + void *pChangeset /* Pointer to blob containing changeset */ +); +SQLITE_API int sqlite3changeset_start_v2( + sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ + int nChangeset, /* Size of changeset blob in bytes */ + void *pChangeset, /* Pointer to blob containing changeset */ + int flags /* SESSION_CHANGESETSTART_* flags */ +); + +/* +** CAPI3REF: Flags for sqlite3changeset_start_v2 +** +** The following flags may passed via the 4th parameter to +** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]: +** +**
SQLITE_CHANGESETSTART_INVERT
+** Invert the changeset while iterating through it. This is equivalent to +** inverting a changeset using sqlite3changeset_invert() before applying it. +** It is an error to specify this flag with a patchset. +*/ +#define SQLITE_CHANGESETSTART_INVERT 0x0002 + + +/* +** CAPI3REF: Advance A Changeset Iterator +** METHOD: sqlite3_changeset_iter +** +** This function may only be used with iterators created by the function +** [sqlite3changeset_start()]. If it is called on an iterator passed to +** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE +** is returned and the call has no effect. +** +** Immediately after an iterator is created by sqlite3changeset_start(), it +** does not point to any change in the changeset. Assuming the changeset +** is not empty, the first call to this function advances the iterator to +** point to the first change in the changeset. Each subsequent call advances +** the iterator to point to the next change in the changeset (if any). If +** no error occurs and the iterator points to a valid change after a call +** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. +** Otherwise, if all changes in the changeset have already been visited, +** SQLITE_DONE is returned. +** +** If an error occurs, an SQLite error code is returned. Possible error +** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or +** SQLITE_NOMEM. +*/ +SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter); + +/* +** CAPI3REF: Obtain The Current Operation From A Changeset Iterator +** METHOD: sqlite3_changeset_iter +** +** The pIter argument passed to this function may either be an iterator +** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator +** created by [sqlite3changeset_start()]. In the latter case, the most recent +** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this +** is not the case, this function returns [SQLITE_MISUSE]. +** +** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three +** outputs are set through these pointers: +** +** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the type of change that the iterator currently points to; +** +** *pnCol is set to the number of columns in the table affected by the change; and +** +** *pzTab is set to point to a nul-terminated utf-8 encoded string containing +** the name of the table affected by the current change. The buffer remains +** valid until either sqlite3changeset_next() is called on the iterator +** or until the conflict-handler function returns. +** +** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change +** is an indirect change, or false (0) otherwise. See the documentation for +** [sqlite3session_indirect()] for a description of direct and indirect +** changes. +** +** If no error occurs, SQLITE_OK is returned. If an error does occur, an +** SQLite error code is returned. The values of the output variables may not +** be trusted in this case. +*/ +SQLITE_API int sqlite3changeset_op( + sqlite3_changeset_iter *pIter, /* Iterator object */ + const char **pzTab, /* OUT: Pointer to table name */ + int *pnCol, /* OUT: Number of columns in table */ + int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ + int *pbIndirect /* OUT: True for an 'indirect' change */ +); + +/* +** CAPI3REF: Obtain The Primary Key Definition Of A Table +** METHOD: sqlite3_changeset_iter +** +** For each modified table, a changeset includes the following: +** +**
    +**
  • The number of columns in the table, and +**
  • Which of those columns make up the tables PRIMARY KEY. +**
+** +** This function is used to find which columns comprise the PRIMARY KEY of +** the table modified by the change that iterator pIter currently points to. +** If successful, *pabPK is set to point to an array of nCol entries, where +** nCol is the number of columns in the table. Elements of *pabPK are set to +** 0x01 if the corresponding column is part of the tables primary key, or +** 0x00 if it is not. +** +** If argument pnCol is not NULL, then *pnCol is set to the number of columns +** in the table. +** +** If this function is called when the iterator does not point to a valid +** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise, +** SQLITE_OK is returned and the output variables populated as described +** above. +*/ +SQLITE_API int sqlite3changeset_pk( + sqlite3_changeset_iter *pIter, /* Iterator object */ + unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ + int *pnCol /* OUT: Number of entries in output array */ +); + +/* +** CAPI3REF: Obtain old.* Values From A Changeset Iterator +** METHOD: sqlite3_changeset_iter +** +** The pIter argument passed to this function may either be an iterator +** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator +** created by [sqlite3changeset_start()]. In the latter case, the most recent +** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** Furthermore, it may only be called if the type of change that the iterator +** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, +** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. +** +** Argument iVal must be greater than or equal to 0, and less than the number +** of columns in the table affected by the current change. Otherwise, +** [SQLITE_RANGE] is returned and *ppValue is set to NULL. +** +** If successful, this function sets *ppValue to point to a protected +** sqlite3_value object containing the iVal'th value from the vector of +** original row values stored as part of the UPDATE or DELETE change and +** returns SQLITE_OK. The name of the function comes from the fact that this +** is similar to the "old.*" columns available to update or delete triggers. +** +** If some other error occurs (e.g. an OOM condition), an SQLite error code +** is returned and *ppValue is set to NULL. +*/ +SQLITE_API int sqlite3changeset_old( + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int iVal, /* Column number */ + sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ +); + +/* +** CAPI3REF: Obtain new.* Values From A Changeset Iterator +** METHOD: sqlite3_changeset_iter +** +** The pIter argument passed to this function may either be an iterator +** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator +** created by [sqlite3changeset_start()]. In the latter case, the most recent +** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** Furthermore, it may only be called if the type of change that the iterator +** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, +** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. +** +** Argument iVal must be greater than or equal to 0, and less than the number +** of columns in the table affected by the current change. Otherwise, +** [SQLITE_RANGE] is returned and *ppValue is set to NULL. +** +** If successful, this function sets *ppValue to point to a protected +** sqlite3_value object containing the iVal'th value from the vector of +** new row values stored as part of the UPDATE or INSERT change and +** returns SQLITE_OK. If the change is an UPDATE and does not include +** a new value for the requested column, *ppValue is set to NULL and +** SQLITE_OK returned. The name of the function comes from the fact that +** this is similar to the "new.*" columns available to update or delete +** triggers. +** +** If some other error occurs (e.g. an OOM condition), an SQLite error code +** is returned and *ppValue is set to NULL. +*/ +SQLITE_API int sqlite3changeset_new( + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int iVal, /* Column number */ + sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ +); + +/* +** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator +** METHOD: sqlite3_changeset_iter +** +** This function should only be used with iterator objects passed to a +** conflict-handler callback by [sqlite3changeset_apply()] with either +** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function +** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue +** is set to NULL. +** +** Argument iVal must be greater than or equal to 0, and less than the number +** of columns in the table affected by the current change. Otherwise, +** [SQLITE_RANGE] is returned and *ppValue is set to NULL. +** +** If successful, this function sets *ppValue to point to a protected +** sqlite3_value object containing the iVal'th value from the +** "conflicting row" associated with the current conflict-handler callback +** and returns SQLITE_OK. +** +** If some other error occurs (e.g. an OOM condition), an SQLite error code +** is returned and *ppValue is set to NULL. +*/ +SQLITE_API int sqlite3changeset_conflict( + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int iVal, /* Column number */ + sqlite3_value **ppValue /* OUT: Value from conflicting row */ +); + +/* +** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations +** METHOD: sqlite3_changeset_iter +** +** This function may only be called with an iterator passed to an +** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case +** it sets the output variable to the total number of known foreign key +** violations in the destination database and returns SQLITE_OK. +** +** In all other cases this function returns SQLITE_MISUSE. +*/ +SQLITE_API int sqlite3changeset_fk_conflicts( + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int *pnOut /* OUT: Number of FK violations */ +); + + +/* +** CAPI3REF: Finalize A Changeset Iterator +** METHOD: sqlite3_changeset_iter +** +** This function is used to finalize an iterator allocated with +** [sqlite3changeset_start()]. +** +** This function should only be called on iterators created using the +** [sqlite3changeset_start()] function. If an application calls this +** function with an iterator passed to a conflict-handler by +** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the +** call has no effect. +** +** If an error was encountered within a call to an sqlite3changeset_xxx() +** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an +** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding +** to that error is returned by this function. Otherwise, SQLITE_OK is +** returned. This is to allow the following pattern (pseudo-code): +** +**
+**   sqlite3changeset_start();
+**   while( SQLITE_ROW==sqlite3changeset_next() ){
+**     // Do something with change.
+**   }
+**   rc = sqlite3changeset_finalize();
+**   if( rc!=SQLITE_OK ){
+**     // An error has occurred
+**   }
+** 
+*/ +SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); + +/* +** CAPI3REF: Invert A Changeset +** +** This function is used to "invert" a changeset object. Applying an inverted +** changeset to a database reverses the effects of applying the uninverted +** changeset. Specifically: +** +**
    +**
  • Each DELETE change is changed to an INSERT, and +**
  • Each INSERT change is changed to a DELETE, and +**
  • For each UPDATE change, the old.* and new.* values are exchanged. +**
+** +** This function does not change the order in which changes appear within +** the changeset. It merely reverses the sense of each individual change. +** +** If successful, a pointer to a buffer containing the inverted changeset +** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and +** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are +** zeroed and an SQLite error code returned. +** +** It is the responsibility of the caller to eventually call sqlite3_free() +** on the *ppOut pointer to free the buffer allocation following a successful +** call to this function. +** +** WARNING/TODO: This function currently assumes that the input is a valid +** changeset. If it is not, the results are undefined. +*/ +SQLITE_API int sqlite3changeset_invert( + int nIn, const void *pIn, /* Input changeset */ + int *pnOut, void **ppOut /* OUT: Inverse of input */ +); + +/* +** CAPI3REF: Concatenate Two Changeset Objects +** +** This function is used to concatenate two changesets, A and B, into a +** single changeset. The result is a changeset equivalent to applying +** changeset A followed by changeset B. +** +** This function combines the two input changesets using an +** sqlite3_changegroup object. Calling it produces similar results as the +** following code fragment: +** +**
+**   sqlite3_changegroup *pGrp;
+**   rc = sqlite3_changegroup_new(&pGrp);
+**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
+**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
+**   if( rc==SQLITE_OK ){
+**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
+**   }else{
+**     *ppOut = 0;
+**     *pnOut = 0;
+**   }
+** 
+** +** Refer to the sqlite3_changegroup documentation below for details. +*/ +SQLITE_API int sqlite3changeset_concat( + int nA, /* Number of bytes in buffer pA */ + void *pA, /* Pointer to buffer containing changeset A */ + int nB, /* Number of bytes in buffer pB */ + void *pB, /* Pointer to buffer containing changeset B */ + int *pnOut, /* OUT: Number of bytes in output changeset */ + void **ppOut /* OUT: Buffer containing output changeset */ +); + +/* +** CAPI3REF: Changegroup Handle +** +** A changegroup is an object used to combine two or more +** [changesets] or [patchsets] +*/ +typedef struct sqlite3_changegroup sqlite3_changegroup; + +/* +** CAPI3REF: Create A New Changegroup Object +** CONSTRUCTOR: sqlite3_changegroup +** +** An sqlite3_changegroup object is used to combine two or more changesets +** (or patchsets) into a single changeset (or patchset). A single changegroup +** object may combine changesets or patchsets, but not both. The output is +** always in the same format as the input. +** +** If successful, this function returns SQLITE_OK and populates (*pp) with +** a pointer to a new sqlite3_changegroup object before returning. The caller +** should eventually free the returned object using a call to +** sqlite3changegroup_delete(). If an error occurs, an SQLite error code +** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. +** +** The usual usage pattern for an sqlite3_changegroup object is as follows: +** +**
    +**
  • It is created using a call to sqlite3changegroup_new(). +** +**
  • Zero or more changesets (or patchsets) are added to the object +** by calling sqlite3changegroup_add(). +** +**
  • The result of combining all input changesets together is obtained +** by the application via a call to sqlite3changegroup_output(). +** +**
  • The object is deleted using a call to sqlite3changegroup_delete(). +**
+** +** Any number of calls to add() and output() may be made between the calls to +** new() and delete(), and in any order. +** +** As well as the regular sqlite3changegroup_add() and +** sqlite3changegroup_output() functions, also available are the streaming +** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). +*/ +SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp); + +/* +** CAPI3REF: Add a Schema to a Changegroup +** METHOD: sqlite3_changegroup_schema +** +** This method may be used to optionally enforce the rule that the changesets +** added to the changegroup handle must match the schema of database zDb +** ("main", "temp", or the name of an attached database). If +** sqlite3changegroup_add() is called to add a changeset that is not compatible +** with the configured schema, SQLITE_SCHEMA is returned and the changegroup +** object is left in an undefined state. +** +** A changeset schema is considered compatible with the database schema in +** the same way as for sqlite3changeset_apply(). Specifically, for each +** table in the changeset, there exists a database table with: +** +**
    +**
  • The name identified by the changeset, and +**
  • at least as many columns as recorded in the changeset, and +**
  • the primary key columns in the same position as recorded in +** the changeset. +**
+** +** The output of the changegroup object always has the same schema as the +** database nominated using this function. In cases where changesets passed +** to sqlite3changegroup_add() have fewer columns than the corresponding table +** in the database schema, these are filled in using the default column +** values from the database schema. This makes it possible to combined +** changesets that have different numbers of columns for a single table +** within a changegroup, provided that they are otherwise compatible. +*/ +SQLITE_API int sqlite3changegroup_schema(sqlite3_changegroup*, sqlite3*, const char *zDb); + +/* +** CAPI3REF: Add A Changeset To A Changegroup +** METHOD: sqlite3_changegroup +** +** Add all changes within the changeset (or patchset) in buffer pData (size +** nData bytes) to the changegroup. +** +** If the buffer contains a patchset, then all prior calls to this function +** on the same changegroup object must also have specified patchsets. Or, if +** the buffer contains a changeset, so must have the earlier calls to this +** function. Otherwise, SQLITE_ERROR is returned and no changes are added +** to the changegroup. +** +** Rows within the changeset and changegroup are identified by the values in +** their PRIMARY KEY columns. A change in the changeset is considered to +** apply to the same row as a change already present in the changegroup if +** the two rows have the same primary key. +** +** Changes to rows that do not already appear in the changegroup are +** simply copied into it. Or, if both the new changeset and the changegroup +** contain changes that apply to a single row, the final contents of the +** changegroup depends on the type of each change, as follows: +** +** +** +** +**
Existing Change New Change Output Change +**
INSERT INSERT +** The new change is ignored. This case does not occur if the new +** changeset was recorded immediately after the changesets already +** added to the changegroup. +**
INSERT UPDATE +** The INSERT change remains in the changegroup. The values in the +** INSERT change are modified as if the row was inserted by the +** existing change and then updated according to the new change. +**
INSERT DELETE +** The existing INSERT is removed from the changegroup. The DELETE is +** not added. +**
UPDATE INSERT +** The new change is ignored. This case does not occur if the new +** changeset was recorded immediately after the changesets already +** added to the changegroup. +**
UPDATE UPDATE +** The existing UPDATE remains within the changegroup. It is amended +** so that the accompanying values are as if the row was updated once +** by the existing change and then again by the new change. +**
UPDATE DELETE +** The existing UPDATE is replaced by the new DELETE within the +** changegroup. +**
DELETE INSERT +** If one or more of the column values in the row inserted by the +** new change differ from those in the row deleted by the existing +** change, the existing DELETE is replaced by an UPDATE within the +** changegroup. Otherwise, if the inserted row is exactly the same +** as the deleted row, the existing DELETE is simply discarded. +**
DELETE UPDATE +** The new change is ignored. This case does not occur if the new +** changeset was recorded immediately after the changesets already +** added to the changegroup. +**
DELETE DELETE +** The new change is ignored. This case does not occur if the new +** changeset was recorded immediately after the changesets already +** added to the changegroup. +**
+** +** If the new changeset contains changes to a table that is already present +** in the changegroup, then the number of columns and the position of the +** primary key columns for the table must be consistent. If this is not the +** case, this function fails with SQLITE_SCHEMA. Except, if the changegroup +** object has been configured with a database schema using the +** sqlite3changegroup_schema() API, then it is possible to combine changesets +** with different numbers of columns for a single table, provided that +** they are otherwise compatible. +** +** If the input changeset appears to be corrupt and the corruption is +** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition +** occurs during processing, this function returns SQLITE_NOMEM. +** +** In all cases, if an error occurs the state of the final contents of the +** changegroup is undefined. If no error occurs, SQLITE_OK is returned. +*/ +SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); + +/* +** CAPI3REF: Add A Single Change To A Changegroup +** METHOD: sqlite3_changegroup +** +** This function adds the single change currently indicated by the iterator +** passed as the second argument to the changegroup object. The rules for +** adding the change are just as described for [sqlite3changegroup_add()]. +** +** If the change is successfully added to the changegroup, SQLITE_OK is +** returned. Otherwise, an SQLite error code is returned. +** +** The iterator must point to a valid entry when this function is called. +** If it does not, SQLITE_ERROR is returned and no change is added to the +** changegroup. Additionally, the iterator must not have been opened with +** the SQLITE_CHANGESETAPPLY_INVERT flag. In this case SQLITE_ERROR is also +** returned. +*/ +SQLITE_API int sqlite3changegroup_add_change( + sqlite3_changegroup*, + sqlite3_changeset_iter* +); + + + +/* +** CAPI3REF: Obtain A Composite Changeset From A Changegroup +** METHOD: sqlite3_changegroup +** +** Obtain a buffer containing a changeset (or patchset) representing the +** current contents of the changegroup. If the inputs to the changegroup +** were themselves changesets, the output is a changeset. Or, if the +** inputs were patchsets, the output is also a patchset. +** +** As with the output of the sqlite3session_changeset() and +** sqlite3session_patchset() functions, all changes related to a single +** table are grouped together in the output of this function. Tables appear +** in the same order as for the very first changeset added to the changegroup. +** If the second or subsequent changesets added to the changegroup contain +** changes for tables that do not appear in the first changeset, they are +** appended onto the end of the output changeset, again in the order in +** which they are first encountered. +** +** If an error occurs, an SQLite error code is returned and the output +** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK +** is returned and the output variables are set to the size of and a +** pointer to the output buffer, respectively. In this case it is the +** responsibility of the caller to eventually free the buffer using a +** call to sqlite3_free(). +*/ +SQLITE_API int sqlite3changegroup_output( + sqlite3_changegroup*, + int *pnData, /* OUT: Size of output buffer in bytes */ + void **ppData /* OUT: Pointer to output buffer */ +); + +/* +** CAPI3REF: Delete A Changegroup Object +** DESTRUCTOR: sqlite3_changegroup +*/ +SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); + +/* +** CAPI3REF: Apply A Changeset To A Database +** +** Apply a changeset or patchset to a database. These functions attempt to +** update the "main" database attached to handle db with the changes found in +** the changeset passed via the second and third arguments. +** +** The fourth argument (xFilter) passed to these functions is the "filter +** callback". If it is not NULL, then for each table affected by at least one +** change in the changeset, the filter callback is invoked with +** the table name as the second argument, and a copy of the context pointer +** passed as the sixth argument as the first. If the "filter callback" +** returns zero, then no attempt is made to apply any changes to the table. +** Otherwise, if the return value is non-zero or the xFilter argument to +** is NULL, all changes related to the table are attempted. +** +** For each table that is not excluded by the filter callback, this function +** tests that the target database contains a compatible table. A table is +** considered compatible if all of the following are true: +** +**
    +**
  • The table has the same name as the name recorded in the +** changeset, and +**
  • The table has at least as many columns as recorded in the +** changeset, and +**
  • The table has primary key columns in the same position as +** recorded in the changeset. +**
+** +** If there is no compatible table, it is not an error, but none of the +** changes associated with the table are applied. A warning message is issued +** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most +** one such warning is issued for each table in the changeset. +** +** For each change for which there is a compatible table, an attempt is made +** to modify the table contents according to the UPDATE, INSERT or DELETE +** change. If a change cannot be applied cleanly, the conflict handler +** function passed as the fifth argument to sqlite3changeset_apply() may be +** invoked. A description of exactly when the conflict handler is invoked for +** each type of change is below. +** +** Unlike the xFilter argument, xConflict may not be passed NULL. The results +** of passing anything other than a valid function pointer as the xConflict +** argument are undefined. +** +** Each time the conflict handler function is invoked, it must return one +** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or +** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned +** if the second argument passed to the conflict handler is either +** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler +** returns an illegal value, any changes already made are rolled back and +** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different +** actions are taken by sqlite3changeset_apply() depending on the value +** returned by each invocation of the conflict-handler function. Refer to +** the documentation for the three +** [SQLITE_CHANGESET_OMIT|available return values] for details. +** +**
+**
DELETE Changes
+** For each DELETE change, the function checks if the target database +** contains a row with the same primary key value (or values) as the +** original row values stored in the changeset. If it does, and the values +** stored in all non-primary key columns also match the values stored in +** the changeset the row is deleted from the target database. +** +** If a row with matching primary key values is found, but one or more of +** the non-primary key fields contains a value different from the original +** row value stored in the changeset, the conflict-handler function is +** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the +** database table has more columns than are recorded in the changeset, +** only the values of those non-primary key fields are compared against +** the current database contents - any trailing database table columns +** are ignored. +** +** If no row with matching primary key values is found in the database, +** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] +** passed as the second argument. +** +** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT +** (which can only happen if a foreign key constraint is violated), the +** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT] +** passed as the second argument. This includes the case where the DELETE +** operation is attempted because an earlier call to the conflict handler +** function returned [SQLITE_CHANGESET_REPLACE]. +** +**
INSERT Changes
+** For each INSERT change, an attempt is made to insert the new row into +** the database. If the changeset row contains fewer fields than the +** database table, the trailing fields are populated with their default +** values. +** +** If the attempt to insert the row fails because the database already +** contains a row with the same primary key values, the conflict handler +** function is invoked with the second argument set to +** [SQLITE_CHANGESET_CONFLICT]. +** +** If the attempt to insert the row fails because of some other constraint +** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is +** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT]. +** This includes the case where the INSERT operation is re-attempted because +** an earlier call to the conflict handler function returned +** [SQLITE_CHANGESET_REPLACE]. +** +**
UPDATE Changes
+** For each UPDATE change, the function checks if the target database +** contains a row with the same primary key value (or values) as the +** original row values stored in the changeset. If it does, and the values +** stored in all modified non-primary key columns also match the values +** stored in the changeset the row is updated within the target database. +** +** If a row with matching primary key values is found, but one or more of +** the modified non-primary key fields contains a value different from an +** original row value stored in the changeset, the conflict-handler function +** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since +** UPDATE changes only contain values for non-primary key fields that are +** to be modified, only those fields need to match the original values to +** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. +** +** If no row with matching primary key values is found in the database, +** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] +** passed as the second argument. +** +** If the UPDATE operation is attempted, but SQLite returns +** SQLITE_CONSTRAINT, the conflict-handler function is invoked with +** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument. +** This includes the case where the UPDATE operation is attempted after +** an earlier call to the conflict handler function returned +** [SQLITE_CHANGESET_REPLACE]. +**
+** +** It is safe to execute SQL statements, including those that write to the +** table that the callback related to, from within the xConflict callback. +** This can be used to further customize the application's conflict +** resolution strategy. +** +** All changes made by these functions are enclosed in a savepoint transaction. +** If any other error (aside from a constraint failure when attempting to +** write to the target database) occurs, then the savepoint transaction is +** rolled back, restoring the target database to its original state, and an +** SQLite error code returned. +** +** If the output parameters (ppRebase) and (pnRebase) are non-NULL and +** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2() +** may set (*ppRebase) to point to a "rebase" that may be used with the +** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase) +** is set to the size of the buffer in bytes. It is the responsibility of the +** caller to eventually free any such buffer using sqlite3_free(). The buffer +** is only allocated and populated if one or more conflicts were encountered +** while applying the patchset. See comments surrounding the sqlite3_rebaser +** APIs for further details. +** +** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter. +** +** Note that the sqlite3changeset_apply_v2() API is still experimental +** and therefore subject to change. +*/ +SQLITE_API int sqlite3changeset_apply( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx /* First argument passed to xConflict */ +); +SQLITE_API int sqlite3changeset_apply_v2( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase data */ + int flags /* SESSION_CHANGESETAPPLY_* flags */ +); + +/* +** CAPI3REF: Flags for sqlite3changeset_apply_v2 +** +** The following flags may passed via the 9th parameter to +** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]: +** +**
+**
SQLITE_CHANGESETAPPLY_NOSAVEPOINT
+** Usually, the sessions module encloses all operations performed by +** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The +** SAVEPOINT is committed if the changeset or patchset is successfully +** applied, or rolled back if an error occurs. Specifying this flag +** causes the sessions module to omit this savepoint. In this case, if the +** caller has an open transaction or savepoint when apply_v2() is called, +** it may revert the partially applied changeset by rolling it back. +** +**
SQLITE_CHANGESETAPPLY_INVERT
+** Invert the changeset before applying it. This is equivalent to inverting +** a changeset using sqlite3changeset_invert() before applying it. It is +** an error to specify this flag with a patchset. +** +**
SQLITE_CHANGESETAPPLY_IGNORENOOP
+** Do not invoke the conflict handler callback for any changes that +** would not actually modify the database even if they were applied. +** Specifically, this means that the conflict handler is not invoked +** for: +**
    +**
  • a delete change if the row being deleted cannot be found, +**
  • an update change if the modified fields are already set to +** their new values in the conflicting row, or +**
  • an insert change if all fields of the conflicting row match +** the row being inserted. +**
+** +**
SQLITE_CHANGESETAPPLY_FKNOACTION
+** If this flag it set, then all foreign key constraints in the target +** database behave as if they were declared with "ON UPDATE NO ACTION ON +** DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL +** or SET DEFAULT. +*/ +#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 +#define SQLITE_CHANGESETAPPLY_INVERT 0x0002 +#define SQLITE_CHANGESETAPPLY_IGNORENOOP 0x0004 +#define SQLITE_CHANGESETAPPLY_FKNOACTION 0x0008 + +/* +** CAPI3REF: Constants Passed To The Conflict Handler +** +** Values that may be passed as the second argument to a conflict-handler. +** +**
+**
SQLITE_CHANGESET_DATA
+** The conflict handler is invoked with CHANGESET_DATA as the second argument +** when processing a DELETE or UPDATE change if a row with the required +** PRIMARY KEY fields is present in the database, but one or more other +** (non primary-key) fields modified by the update do not contain the +** expected "before" values. +** +** The conflicting row, in this case, is the database row with the matching +** primary key. +** +**
SQLITE_CHANGESET_NOTFOUND
+** The conflict handler is invoked with CHANGESET_NOTFOUND as the second +** argument when processing a DELETE or UPDATE change if a row with the +** required PRIMARY KEY fields is not present in the database. +** +** There is no conflicting row in this case. The results of invoking the +** sqlite3changeset_conflict() API are undefined. +** +**
SQLITE_CHANGESET_CONFLICT
+** CHANGESET_CONFLICT is passed as the second argument to the conflict +** handler while processing an INSERT change if the operation would result +** in duplicate primary key values. +** +** The conflicting row in this case is the database row with the matching +** primary key. +** +**
SQLITE_CHANGESET_FOREIGN_KEY
+** If foreign key handling is enabled, and applying a changeset leaves the +** database in a state containing foreign key violations, the conflict +** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument +** exactly once before the changeset is committed. If the conflict handler +** returns CHANGESET_OMIT, the changes, including those that caused the +** foreign key constraint violation, are committed. Or, if it returns +** CHANGESET_ABORT, the changeset is rolled back. +** +** No current or conflicting row information is provided. The only function +** it is possible to call on the supplied sqlite3_changeset_iter handle +** is sqlite3changeset_fk_conflicts(). +** +**
SQLITE_CHANGESET_CONSTRAINT
+** If any other constraint violation occurs while applying a change (i.e. +** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is +** invoked with CHANGESET_CONSTRAINT as the second argument. +** +** There is no conflicting row in this case. The results of invoking the +** sqlite3changeset_conflict() API are undefined. +** +**
+*/ +#define SQLITE_CHANGESET_DATA 1 +#define SQLITE_CHANGESET_NOTFOUND 2 +#define SQLITE_CHANGESET_CONFLICT 3 +#define SQLITE_CHANGESET_CONSTRAINT 4 +#define SQLITE_CHANGESET_FOREIGN_KEY 5 + +/* +** CAPI3REF: Constants Returned By The Conflict Handler +** +** A conflict handler callback must return one of the following three values. +** +**
+**
SQLITE_CHANGESET_OMIT
+** If a conflict handler returns this value no special action is taken. The +** change that caused the conflict is not applied. The session module +** continues to the next change in the changeset. +** +**
SQLITE_CHANGESET_REPLACE
+** This value may only be returned if the second argument to the conflict +** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this +** is not the case, any changes applied so far are rolled back and the +** call to sqlite3changeset_apply() returns SQLITE_MISUSE. +** +** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict +** handler, then the conflicting row is either updated or deleted, depending +** on the type of change. +** +** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict +** handler, then the conflicting row is removed from the database and a +** second attempt to apply the change is made. If this second attempt fails, +** the original row is restored to the database before continuing. +** +**
SQLITE_CHANGESET_ABORT
+** If this value is returned, any changes applied so far are rolled back +** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. +**
+*/ +#define SQLITE_CHANGESET_OMIT 0 +#define SQLITE_CHANGESET_REPLACE 1 +#define SQLITE_CHANGESET_ABORT 2 + +/* +** CAPI3REF: Rebasing changesets +** EXPERIMENTAL +** +** Suppose there is a site hosting a database in state S0. And that +** modifications are made that move that database to state S1 and a +** changeset recorded (the "local" changeset). Then, a changeset based +** on S0 is received from another site (the "remote" changeset) and +** applied to the database. The database is then in state +** (S1+"remote"), where the exact state depends on any conflict +** resolution decisions (OMIT or REPLACE) made while applying "remote". +** Rebasing a changeset is to update it to take those conflict +** resolution decisions into account, so that the same conflicts +** do not have to be resolved elsewhere in the network. +** +** For example, if both the local and remote changesets contain an +** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)": +** +** local: INSERT INTO t1 VALUES(1, 'v1'); +** remote: INSERT INTO t1 VALUES(1, 'v2'); +** +** and the conflict resolution is REPLACE, then the INSERT change is +** removed from the local changeset (it was overridden). Or, if the +** conflict resolution was "OMIT", then the local changeset is modified +** to instead contain: +** +** UPDATE t1 SET b = 'v2' WHERE a=1; +** +** Changes within the local changeset are rebased as follows: +** +**
+**
Local INSERT
+** This may only conflict with a remote INSERT. If the conflict +** resolution was OMIT, then add an UPDATE change to the rebased +** changeset. Or, if the conflict resolution was REPLACE, add +** nothing to the rebased changeset. +** +**
Local DELETE
+** This may conflict with a remote UPDATE or DELETE. In both cases the +** only possible resolution is OMIT. If the remote operation was a +** DELETE, then add no change to the rebased changeset. If the remote +** operation was an UPDATE, then the old.* fields of change are updated +** to reflect the new.* values in the UPDATE. +** +**
Local UPDATE
+** This may conflict with a remote UPDATE or DELETE. If it conflicts +** with a DELETE, and the conflict resolution was OMIT, then the update +** is changed into an INSERT. Any undefined values in the new.* record +** from the update change are filled in using the old.* values from +** the conflicting DELETE. Or, if the conflict resolution was REPLACE, +** the UPDATE change is simply omitted from the rebased changeset. +** +** If conflict is with a remote UPDATE and the resolution is OMIT, then +** the old.* values are rebased using the new.* values in the remote +** change. Or, if the resolution is REPLACE, then the change is copied +** into the rebased changeset with updates to columns also updated by +** the conflicting remote UPDATE removed. If this means no columns would +** be updated, the change is omitted. +**
+** +** A local change may be rebased against multiple remote changes +** simultaneously. If a single key is modified by multiple remote +** changesets, they are combined as follows before the local changeset +** is rebased: +** +**
    +**
  • If there has been one or more REPLACE resolutions on a +** key, it is rebased according to a REPLACE. +** +**
  • If there have been no REPLACE resolutions on a key, then +** the local changeset is rebased according to the most recent +** of the OMIT resolutions. +**
+** +** Note that conflict resolutions from multiple remote changesets are +** combined on a per-field basis, not per-row. This means that in the +** case of multiple remote UPDATE operations, some fields of a single +** local change may be rebased for REPLACE while others are rebased for +** OMIT. +** +** In order to rebase a local changeset, the remote changeset must first +** be applied to the local database using sqlite3changeset_apply_v2() and +** the buffer of rebase information captured. Then: +** +**
    +**
  1. An sqlite3_rebaser object is created by calling +** sqlite3rebaser_create(). +**
  2. The new object is configured with the rebase buffer obtained from +** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure(). +** If the local changeset is to be rebased against multiple remote +** changesets, then sqlite3rebaser_configure() should be called +** multiple times, in the same order that the multiple +** sqlite3changeset_apply_v2() calls were made. +**
  3. Each local changeset is rebased by calling sqlite3rebaser_rebase(). +**
  4. The sqlite3_rebaser object is deleted by calling +** sqlite3rebaser_delete(). +**
+*/ +typedef struct sqlite3_rebaser sqlite3_rebaser; + +/* +** CAPI3REF: Create a changeset rebaser object. +** EXPERIMENTAL +** +** Allocate a new changeset rebaser object. If successful, set (*ppNew) to +** point to the new object and return SQLITE_OK. Otherwise, if an error +** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) +** to NULL. +*/ +SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew); + +/* +** CAPI3REF: Configure a changeset rebaser object. +** EXPERIMENTAL +** +** Configure the changeset rebaser object to rebase changesets according +** to the conflict resolutions described by buffer pRebase (size nRebase +** bytes), which must have been obtained from a previous call to +** sqlite3changeset_apply_v2(). +*/ +SQLITE_API int sqlite3rebaser_configure( + sqlite3_rebaser*, + int nRebase, const void *pRebase +); + +/* +** CAPI3REF: Rebase a changeset +** EXPERIMENTAL +** +** Argument pIn must point to a buffer containing a changeset nIn bytes +** in size. This function allocates and populates a buffer with a copy +** of the changeset rebased according to the configuration of the +** rebaser object passed as the first argument. If successful, (*ppOut) +** is set to point to the new buffer containing the rebased changeset and +** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the +** responsibility of the caller to eventually free the new buffer using +** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut) +** are set to zero and an SQLite error code returned. +*/ +SQLITE_API int sqlite3rebaser_rebase( + sqlite3_rebaser*, + int nIn, const void *pIn, + int *pnOut, void **ppOut +); + +/* +** CAPI3REF: Delete a changeset rebaser object. +** EXPERIMENTAL +** +** Delete the changeset rebaser object and all associated resources. There +** should be one call to this function for each successful invocation +** of sqlite3rebaser_create(). +*/ +SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p); + +/* +** CAPI3REF: Streaming Versions of API functions. +** +** The six streaming API xxx_strm() functions serve similar purposes to the +** corresponding non-streaming API functions: +** +** +** +**
Streaming functionNon-streaming equivalent
sqlite3changeset_apply_strm[sqlite3changeset_apply] +**
sqlite3changeset_apply_strm_v2[sqlite3changeset_apply_v2] +**
sqlite3changeset_concat_strm[sqlite3changeset_concat] +**
sqlite3changeset_invert_strm[sqlite3changeset_invert] +**
sqlite3changeset_start_strm[sqlite3changeset_start] +**
sqlite3session_changeset_strm[sqlite3session_changeset] +**
sqlite3session_patchset_strm[sqlite3session_patchset] +**
+** +** Non-streaming functions that accept changesets (or patchsets) as input +** require that the entire changeset be stored in a single buffer in memory. +** Similarly, those that return a changeset or patchset do so by returning +** a pointer to a single large buffer allocated using sqlite3_malloc(). +** Normally this is convenient. However, if an application running in a +** low-memory environment is required to handle very large changesets, the +** large contiguous memory allocations required can become onerous. +** +** In order to avoid this problem, instead of a single large buffer, input +** is passed to a streaming API functions by way of a callback function that +** the sessions module invokes to incrementally request input data as it is +** required. In all cases, a pair of API function parameters such as +** +**
+**        int nChangeset,
+**        void *pChangeset,
+**  
+** +** Is replaced by: +** +**
+**        int (*xInput)(void *pIn, void *pData, int *pnData),
+**        void *pIn,
+**  
+** +** Each time the xInput callback is invoked by the sessions module, the first +** argument passed is a copy of the supplied pIn context pointer. The second +** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no +** error occurs the xInput method should copy up to (*pnData) bytes of data +** into the buffer and set (*pnData) to the actual number of bytes copied +** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) +** should be set to zero to indicate this. Or, if an error occurs, an SQLite +** error code should be returned. In all cases, if an xInput callback returns +** an error, all processing is abandoned and the streaming API function +** returns a copy of the error code to the caller. +** +** In the case of sqlite3changeset_start_strm(), the xInput callback may be +** invoked by the sessions module at any point during the lifetime of the +** iterator. If such an xInput callback returns an error, the iterator enters +** an error state, whereby all subsequent calls to iterator functions +** immediately fail with the same error code as returned by xInput. +** +** Similarly, streaming API functions that return changesets (or patchsets) +** return them in chunks by way of a callback function instead of via a +** pointer to a single large buffer. In this case, a pair of parameters such +** as: +** +**
+**        int *pnChangeset,
+**        void **ppChangeset,
+**  
+** +** Is replaced by: +** +**
+**        int (*xOutput)(void *pOut, const void *pData, int nData),
+**        void *pOut
+**  
+** +** The xOutput callback is invoked zero or more times to return data to +** the application. The first parameter passed to each call is a copy of the +** pOut pointer supplied by the application. The second parameter, pData, +** points to a buffer nData bytes in size containing the chunk of output +** data being returned. If the xOutput callback successfully processes the +** supplied data, it should return SQLITE_OK to indicate success. Otherwise, +** it should return some other SQLite error code. In this case processing +** is immediately abandoned and the streaming API function returns a copy +** of the xOutput error code to the application. +** +** The sessions module never invokes an xOutput callback with the third +** parameter set to a value less than or equal to zero. Other than this, +** no guarantees are made as to the size of the chunks of data returned. +*/ +SQLITE_API int sqlite3changeset_apply_strm( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx /* First argument passed to xConflict */ +); +SQLITE_API int sqlite3changeset_apply_v2_strm( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +); +SQLITE_API int sqlite3changeset_concat_strm( + int (*xInputA)(void *pIn, void *pData, int *pnData), + void *pInA, + int (*xInputB)(void *pIn, void *pData, int *pnData), + void *pInB, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +SQLITE_API int sqlite3changeset_invert_strm( + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +SQLITE_API int sqlite3changeset_start_strm( + sqlite3_changeset_iter **pp, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn +); +SQLITE_API int sqlite3changeset_start_v2_strm( + sqlite3_changeset_iter **pp, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int flags +); +SQLITE_API int sqlite3session_changeset_strm( + sqlite3_session *pSession, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +SQLITE_API int sqlite3session_patchset_strm( + sqlite3_session *pSession, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn +); +SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +SQLITE_API int sqlite3rebaser_rebase_strm( + sqlite3_rebaser *pRebaser, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); + +/* +** CAPI3REF: Configure global parameters +** +** The sqlite3session_config() interface is used to make global configuration +** changes to the sessions module in order to tune it to the specific needs +** of the application. +** +** The sqlite3session_config() interface is not threadsafe. If it is invoked +** while any other thread is inside any other sessions method then the +** results are undefined. Furthermore, if it is invoked after any sessions +** related objects have been created, the results are also undefined. +** +** The first argument to the sqlite3session_config() function must be one +** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The +** interpretation of the (void*) value passed as the second parameter and +** the effect of calling this function depends on the value of the first +** parameter. +** +**
+**
SQLITE_SESSION_CONFIG_STRMSIZE
+** By default, the sessions module streaming interfaces attempt to input +** and output data in approximately 1 KiB chunks. This operand may be used +** to set and query the value of this configuration setting. The pointer +** passed as the second argument must point to a value of type (int). +** If this value is greater than 0, it is used as the new streaming data +** chunk size for both input and output. Before returning, the (int) value +** pointed to by pArg is set to the final value of the streaming interface +** chunk size. +**
+** +** This function returns SQLITE_OK if successful, or an SQLite error code +** otherwise. +*/ +SQLITE_API int sqlite3session_config(int op, void *pArg); + +/* +** CAPI3REF: Values for sqlite3session_config(). +*/ +#define SQLITE_SESSION_CONFIG_STRMSIZE 1 + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +} +#endif + +#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ + +/******** End of sqlite3session.h *********/ +/******** Begin file fts5.h *********/ +/* +** 2014 May 31 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** Interfaces to extend FTS5. Using the interfaces defined in this file, +** FTS5 may be extended with: +** +** * custom tokenizers, and +** * custom auxiliary functions. +*/ + + +#ifndef _FTS5_H +#define _FTS5_H + + +#ifdef __cplusplus +extern "C" { +#endif + +/************************************************************************* +** CUSTOM AUXILIARY FUNCTIONS +** +** Virtual table implementations may overload SQL functions by implementing +** the sqlite3_module.xFindFunction() method. +*/ + +typedef struct Fts5ExtensionApi Fts5ExtensionApi; +typedef struct Fts5Context Fts5Context; +typedef struct Fts5PhraseIter Fts5PhraseIter; + +typedef void (*fts5_extension_function)( + const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ + Fts5Context *pFts, /* First arg to pass to pApi functions */ + sqlite3_context *pCtx, /* Context for returning result/error */ + int nVal, /* Number of values in apVal[] array */ + sqlite3_value **apVal /* Array of trailing arguments */ +); + +struct Fts5PhraseIter { + const unsigned char *a; + const unsigned char *b; +}; + +/* +** EXTENSION API FUNCTIONS +** +** xUserData(pFts): +** Return a copy of the pUserData pointer passed to the xCreateFunction() +** API when the extension function was registered. +** +** xColumnTotalSize(pFts, iCol, pnToken): +** If parameter iCol is less than zero, set output variable *pnToken +** to the total number of tokens in the FTS5 table. Or, if iCol is +** non-negative but less than the number of columns in the table, return +** the total number of tokens in column iCol, considering all rows in +** the FTS5 table. +** +** If parameter iCol is greater than or equal to the number of columns +** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. +** an OOM condition or IO error), an appropriate SQLite error code is +** returned. +** +** xColumnCount(pFts): +** Return the number of columns in the table. +** +** xColumnSize(pFts, iCol, pnToken): +** If parameter iCol is less than zero, set output variable *pnToken +** to the total number of tokens in the current row. Or, if iCol is +** non-negative but less than the number of columns in the table, set +** *pnToken to the number of tokens in column iCol of the current row. +** +** If parameter iCol is greater than or equal to the number of columns +** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. +** an OOM condition or IO error), an appropriate SQLite error code is +** returned. +** +** This function may be quite inefficient if used with an FTS5 table +** created with the "columnsize=0" option. +** +** xColumnText: +** If parameter iCol is less than zero, or greater than or equal to the +** number of columns in the table, SQLITE_RANGE is returned. +** +** Otherwise, this function attempts to retrieve the text of column iCol of +** the current document. If successful, (*pz) is set to point to a buffer +** containing the text in utf-8 encoding, (*pn) is set to the size in bytes +** (not characters) of the buffer and SQLITE_OK is returned. Otherwise, +** if an error occurs, an SQLite error code is returned and the final values +** of (*pz) and (*pn) are undefined. +** +** xPhraseCount: +** Returns the number of phrases in the current query expression. +** +** xPhraseSize: +** If parameter iCol is less than zero, or greater than or equal to the +** number of phrases in the current query, as returned by xPhraseCount, +** 0 is returned. Otherwise, this function returns the number of tokens in +** phrase iPhrase of the query. Phrases are numbered starting from zero. +** +** xInstCount: +** Set *pnInst to the total number of occurrences of all phrases within +** the query within the current row. Return SQLITE_OK if successful, or +** an error code (i.e. SQLITE_NOMEM) if an error occurs. +** +** This API can be quite slow if used with an FTS5 table created with the +** "detail=none" or "detail=column" option. If the FTS5 table is created +** with either "detail=none" or "detail=column" and "content=" option +** (i.e. if it is a contentless table), then this API always returns 0. +** +** xInst: +** Query for the details of phrase match iIdx within the current row. +** Phrase matches are numbered starting from zero, so the iIdx argument +** should be greater than or equal to zero and smaller than the value +** output by xInstCount(). If iIdx is less than zero or greater than +** or equal to the value returned by xInstCount(), SQLITE_RANGE is returned. +** +** Otherwise, output parameter *piPhrase is set to the phrase number, *piCol +** to the column in which it occurs and *piOff the token offset of the +** first token of the phrase. SQLITE_OK is returned if successful, or an +** error code (i.e. SQLITE_NOMEM) if an error occurs. +** +** This API can be quite slow if used with an FTS5 table created with the +** "detail=none" or "detail=column" option. +** +** xRowid: +** Returns the rowid of the current row. +** +** xTokenize: +** Tokenize text using the tokenizer belonging to the FTS5 table. +** +** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): +** This API function is used to query the FTS table for phrase iPhrase +** of the current query. Specifically, a query equivalent to: +** +** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid +** +** with $p set to a phrase equivalent to the phrase iPhrase of the +** current query is executed. Any column filter that applies to +** phrase iPhrase of the current query is included in $p. For each +** row visited, the callback function passed as the fourth argument +** is invoked. The context and API objects passed to the callback +** function may be used to access the properties of each matched row. +** Invoking Api.xUserData() returns a copy of the pointer passed as +** the third argument to pUserData. +** +** If parameter iPhrase is less than zero, or greater than or equal to +** the number of phrases in the query, as returned by xPhraseCount(), +** this function returns SQLITE_RANGE. +** +** If the callback function returns any value other than SQLITE_OK, the +** query is abandoned and the xQueryPhrase function returns immediately. +** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. +** Otherwise, the error code is propagated upwards. +** +** If the query runs to completion without incident, SQLITE_OK is returned. +** Or, if some error occurs before the query completes or is aborted by +** the callback, an SQLite error code is returned. +** +** +** xSetAuxdata(pFts5, pAux, xDelete) +** +** Save the pointer passed as the second argument as the extension function's +** "auxiliary data". The pointer may then be retrieved by the current or any +** future invocation of the same fts5 extension function made as part of +** the same MATCH query using the xGetAuxdata() API. +** +** Each extension function is allocated a single auxiliary data slot for +** each FTS query (MATCH expression). If the extension function is invoked +** more than once for a single FTS query, then all invocations share a +** single auxiliary data context. +** +** If there is already an auxiliary data pointer when this function is +** invoked, then it is replaced by the new pointer. If an xDelete callback +** was specified along with the original pointer, it is invoked at this +** point. +** +** The xDelete callback, if one is specified, is also invoked on the +** auxiliary data pointer after the FTS5 query has finished. +** +** If an error (e.g. an OOM condition) occurs within this function, +** the auxiliary data is set to NULL and an error code returned. If the +** xDelete parameter was not NULL, it is invoked on the auxiliary data +** pointer before returning. +** +** +** xGetAuxdata(pFts5, bClear) +** +** Returns the current auxiliary data pointer for the fts5 extension +** function. See the xSetAuxdata() method for details. +** +** If the bClear argument is non-zero, then the auxiliary data is cleared +** (set to NULL) before this function returns. In this case the xDelete, +** if any, is not invoked. +** +** +** xRowCount(pFts5, pnRow) +** +** This function is used to retrieve the total number of rows in the table. +** In other words, the same value that would be returned by: +** +** SELECT count(*) FROM ftstable; +** +** xPhraseFirst() +** This function is used, along with type Fts5PhraseIter and the xPhraseNext +** method, to iterate through all instances of a single query phrase within +** the current row. This is the same information as is accessible via the +** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient +** to use, this API may be faster under some circumstances. To iterate +** through instances of phrase iPhrase, use the following code: +** +** Fts5PhraseIter iter; +** int iCol, iOff; +** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff); +** iCol>=0; +** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff) +** ){ +** // An instance of phrase iPhrase at offset iOff of column iCol +** } +** +** The Fts5PhraseIter structure is defined above. Applications should not +** modify this structure directly - it should only be used as shown above +** with the xPhraseFirst() and xPhraseNext() API methods (and by +** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below). +** +** This API can be quite slow if used with an FTS5 table created with the +** "detail=none" or "detail=column" option. If the FTS5 table is created +** with either "detail=none" or "detail=column" and "content=" option +** (i.e. if it is a contentless table), then this API always iterates +** through an empty set (all calls to xPhraseFirst() set iCol to -1). +** +** In all cases, matches are visited in (column ASC, offset ASC) order. +** i.e. all those in column 0, sorted by offset, followed by those in +** column 1, etc. +** +** xPhraseNext() +** See xPhraseFirst above. +** +** xPhraseFirstColumn() +** This function and xPhraseNextColumn() are similar to the xPhraseFirst() +** and xPhraseNext() APIs described above. The difference is that instead +** of iterating through all instances of a phrase in the current row, these +** APIs are used to iterate through the set of columns in the current row +** that contain one or more instances of a specified phrase. For example: +** +** Fts5PhraseIter iter; +** int iCol; +** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol); +** iCol>=0; +** pApi->xPhraseNextColumn(pFts, &iter, &iCol) +** ){ +** // Column iCol contains at least one instance of phrase iPhrase +** } +** +** This API can be quite slow if used with an FTS5 table created with the +** "detail=none" option. If the FTS5 table is created with either +** "detail=none" "content=" option (i.e. if it is a contentless table), +** then this API always iterates through an empty set (all calls to +** xPhraseFirstColumn() set iCol to -1). +** +** The information accessed using this API and its companion +** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext +** (or xInst/xInstCount). The chief advantage of this API is that it is +** significantly more efficient than those alternatives when used with +** "detail=column" tables. +** +** xPhraseNextColumn() +** See xPhraseFirstColumn above. +** +** xQueryToken(pFts5, iPhrase, iToken, ppToken, pnToken) +** This is used to access token iToken of phrase iPhrase of the current +** query. Before returning, output parameter *ppToken is set to point +** to a buffer containing the requested token, and *pnToken to the +** size of this buffer in bytes. +** +** If iPhrase or iToken are less than zero, or if iPhrase is greater than +** or equal to the number of phrases in the query as reported by +** xPhraseCount(), or if iToken is equal to or greater than the number of +** tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken + are both zeroed. +** +** The output text is not a copy of the query text that specified the +** token. It is the output of the tokenizer module. For tokendata=1 +** tables, this includes any embedded 0x00 and trailing data. +** +** xInstToken(pFts5, iIdx, iToken, ppToken, pnToken) +** This is used to access token iToken of phrase hit iIdx within the +** current row. If iIdx is less than zero or greater than or equal to the +** value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise, +** output variable (*ppToken) is set to point to a buffer containing the +** matching document token, and (*pnToken) to the size of that buffer in +** bytes. +** +** The output text is not a copy of the document text that was tokenized. +** It is the output of the tokenizer module. For tokendata=1 tables, this +** includes any embedded 0x00 and trailing data. +** +** This API may be slow in some cases if the token identified by parameters +** iIdx and iToken matched a prefix token in the query. In most cases, the +** first call to this API for each prefix token in the query is forced +** to scan the portion of the full-text index that matches the prefix +** token to collect the extra data required by this API. If the prefix +** token matches a large number of token instances in the document set, +** this may be a performance problem. +** +** If the user knows in advance that a query may use this API for a +** prefix token, FTS5 may be configured to collect all required data as part +** of the initial querying of the full-text index, avoiding the second scan +** entirely. This also causes prefix queries that do not use this API to +** run more slowly and use more memory. FTS5 may be configured in this way +** either on a per-table basis using the [FTS5 insttoken | 'insttoken'] +** option, or on a per-query basis using the +** [fts5_insttoken | fts5_insttoken()] user function. +** +** This API can be quite slow if used with an FTS5 table created with the +** "detail=none" or "detail=column" option. +** +** xColumnLocale(pFts5, iIdx, pzLocale, pnLocale) +** If parameter iCol is less than zero, or greater than or equal to the +** number of columns in the table, SQLITE_RANGE is returned. +** +** Otherwise, this function attempts to retrieve the locale associated +** with column iCol of the current row. Usually, there is no associated +** locale, and output parameters (*pzLocale) and (*pnLocale) are set +** to NULL and 0, respectively. However, if the fts5_locale() function +** was used to associate a locale with the value when it was inserted +** into the fts5 table, then (*pzLocale) is set to point to a nul-terminated +** buffer containing the name of the locale in utf-8 encoding. (*pnLocale) +** is set to the size in bytes of the buffer, not including the +** nul-terminator. +** +** If successful, SQLITE_OK is returned. Or, if an error occurs, an +** SQLite error code is returned. The final value of the output parameters +** is undefined in this case. +** +** xTokenize_v2: +** Tokenize text using the tokenizer belonging to the FTS5 table. This +** API is the same as the xTokenize() API, except that it allows a tokenizer +** locale to be specified. +*/ +struct Fts5ExtensionApi { + int iVersion; /* Currently always set to 4 */ + + void *(*xUserData)(Fts5Context*); + + int (*xColumnCount)(Fts5Context*); + int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); + int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); + + int (*xTokenize)(Fts5Context*, + const char *pText, int nText, /* Text to tokenize */ + void *pCtx, /* Context passed to xToken() */ + int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ + ); + + int (*xPhraseCount)(Fts5Context*); + int (*xPhraseSize)(Fts5Context*, int iPhrase); + + int (*xInstCount)(Fts5Context*, int *pnInst); + int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); + + sqlite3_int64 (*xRowid)(Fts5Context*); + int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); + int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); + + int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData, + int(*)(const Fts5ExtensionApi*,Fts5Context*,void*) + ); + int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*)); + void *(*xGetAuxdata)(Fts5Context*, int bClear); + + int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*); + void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff); + + int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*); + void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol); + + /* Below this point are iVersion>=3 only */ + int (*xQueryToken)(Fts5Context*, + int iPhrase, int iToken, + const char **ppToken, int *pnToken + ); + int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*); + + /* Below this point are iVersion>=4 only */ + int (*xColumnLocale)(Fts5Context*, int iCol, const char **pz, int *pn); + int (*xTokenize_v2)(Fts5Context*, + const char *pText, int nText, /* Text to tokenize */ + const char *pLocale, int nLocale, /* Locale to pass to tokenizer */ + void *pCtx, /* Context passed to xToken() */ + int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ + ); +}; + +/* +** CUSTOM AUXILIARY FUNCTIONS +*************************************************************************/ + +/************************************************************************* +** CUSTOM TOKENIZERS +** +** Applications may also register custom tokenizer types. A tokenizer +** is registered by providing fts5 with a populated instance of the +** following structure. All structure methods must be defined, setting +** any member of the fts5_tokenizer struct to NULL leads to undefined +** behaviour. The structure methods are expected to function as follows: +** +** xCreate: +** This function is used to allocate and initialize a tokenizer instance. +** A tokenizer instance is required to actually tokenize text. +** +** The first argument passed to this function is a copy of the (void*) +** pointer provided by the application when the fts5_tokenizer_v2 object +** was registered with FTS5 (the third argument to xCreateTokenizer()). +** The second and third arguments are an array of nul-terminated strings +** containing the tokenizer arguments, if any, specified following the +** tokenizer name as part of the CREATE VIRTUAL TABLE statement used +** to create the FTS5 table. +** +** The final argument is an output variable. If successful, (*ppOut) +** should be set to point to the new tokenizer handle and SQLITE_OK +** returned. If an error occurs, some value other than SQLITE_OK should +** be returned. In this case, fts5 assumes that the final value of *ppOut +** is undefined. +** +** xDelete: +** This function is invoked to delete a tokenizer handle previously +** allocated using xCreate(). Fts5 guarantees that this function will +** be invoked exactly once for each successful call to xCreate(). +** +** xTokenize: +** This function is expected to tokenize the nText byte string indicated +** by argument pText. pText may or may not be nul-terminated. The first +** argument passed to this function is a pointer to an Fts5Tokenizer object +** returned by an earlier call to xCreate(). +** +** The third argument indicates the reason that FTS5 is requesting +** tokenization of the supplied text. This is always one of the following +** four values: +** +**
  • FTS5_TOKENIZE_DOCUMENT - A document is being inserted into +** or removed from the FTS table. The tokenizer is being invoked to +** determine the set of tokens to add to (or delete from) the +** FTS index. +** +**
  • FTS5_TOKENIZE_QUERY - A MATCH query is being executed +** against the FTS index. The tokenizer is being called to tokenize +** a bareword or quoted string specified as part of the query. +** +**
  • (FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX) - Same as +** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is +** followed by a "*" character, indicating that the last token +** returned by the tokenizer will be treated as a token prefix. +** +**
  • FTS5_TOKENIZE_AUX - The tokenizer is being invoked to +** satisfy an fts5_api.xTokenize() request made by an auxiliary +** function. Or an fts5_api.xColumnSize() request made by the same +** on a columnsize=0 database. +**
+** +** The sixth and seventh arguments passed to xTokenize() - pLocale and +** nLocale - are a pointer to a buffer containing the locale to use for +** tokenization (e.g. "en_US") and its size in bytes, respectively. The +** pLocale buffer is not nul-terminated. pLocale may be passed NULL (in +** which case nLocale is always 0) to indicate that the tokenizer should +** use its default locale. +** +** For each token in the input string, the supplied callback xToken() must +** be invoked. The first argument to it should be a copy of the pointer +** passed as the second argument to xTokenize(). The third and fourth +** arguments are a pointer to a buffer containing the token text, and the +** size of the token in bytes. The 4th and 5th arguments are the byte offsets +** of the first byte of and first byte immediately following the text from +** which the token is derived within the input. +** +** The second argument passed to the xToken() callback ("tflags") should +** normally be set to 0. The exception is if the tokenizer supports +** synonyms. In this case see the discussion below for details. +** +** FTS5 assumes the xToken() callback is invoked for each token in the +** order that they occur within the input text. +** +** If an xToken() callback returns any value other than SQLITE_OK, then +** the tokenization should be abandoned and the xTokenize() method should +** immediately return a copy of the xToken() return value. Or, if the +** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally, +** if an error occurs with the xTokenize() implementation itself, it +** may abandon the tokenization and return any error code other than +** SQLITE_OK or SQLITE_DONE. +** +** If the tokenizer is registered using an fts5_tokenizer_v2 object, +** then the xTokenize() method has two additional arguments - pLocale +** and nLocale. These specify the locale that the tokenizer should use +** for the current request. If pLocale and nLocale are both 0, then the +** tokenizer should use its default locale. Otherwise, pLocale points to +** an nLocale byte buffer containing the name of the locale to use as utf-8 +** text. pLocale is not nul-terminated. +** +** FTS5_TOKENIZER +** +** There is also an fts5_tokenizer object. This is an older, deprecated, +** version of fts5_tokenizer_v2. It is similar except that: +** +**
    +**
  • There is no "iVersion" field, and +**
  • The xTokenize() method does not take a locale argument. +**
+** +** Legacy fts5_tokenizer tokenizers must be registered using the +** legacy xCreateTokenizer() function, instead of xCreateTokenizer_v2(). +** +** Tokenizer implementations registered using either API may be retrieved +** using both xFindTokenizer() and xFindTokenizer_v2(). +** +** SYNONYM SUPPORT +** +** Custom tokenizers may also support synonyms. Consider a case in which a +** user wishes to query for a phrase such as "first place". Using the +** built-in tokenizers, the FTS5 query 'first + place' will match instances +** of "first place" within the document set, but not alternative forms +** such as "1st place". In some applications, it would be better to match +** all instances of "first place" or "1st place" regardless of which form +** the user specified in the MATCH query text. +** +** There are several ways to approach this in FTS5: +** +**
  1. By mapping all synonyms to a single token. In this case, using +** the above example, this means that the tokenizer returns the +** same token for inputs "first" and "1st". Say that token is in +** fact "first", so that when the user inserts the document "I won +** 1st place" entries are added to the index for tokens "i", "won", +** "first" and "place". If the user then queries for '1st + place', +** the tokenizer substitutes "first" for "1st" and the query works +** as expected. +** +**
  2. By querying the index for all synonyms of each query term +** separately. In this case, when tokenizing query text, the +** tokenizer may provide multiple synonyms for a single term +** within the document. FTS5 then queries the index for each +** synonym individually. For example, faced with the query: +** +** +** ... MATCH 'first place' +** +** the tokenizer offers both "1st" and "first" as synonyms for the +** first token in the MATCH query and FTS5 effectively runs a query +** similar to: +** +** +** ... MATCH '(first OR 1st) place' +** +** except that, for the purposes of auxiliary functions, the query +** still appears to contain just two phrases - "(first OR 1st)" +** being treated as a single phrase. +** +**
  3. By adding multiple synonyms for a single term to the FTS index. +** Using this method, when tokenizing document text, the tokenizer +** provides multiple synonyms for each token. So that when a +** document such as "I won first place" is tokenized, entries are +** added to the FTS index for "i", "won", "first", "1st" and +** "place". +** +** This way, even if the tokenizer does not provide synonyms +** when tokenizing query text (it should not - to do so would be +** inefficient), it doesn't matter if the user queries for +** 'first + place' or '1st + place', as there are entries in the +** FTS index corresponding to both forms of the first token. +**
+** +** Whether it is parsing document or query text, any call to xToken that +** specifies a tflags argument with the FTS5_TOKEN_COLOCATED bit +** is considered to supply a synonym for the previous token. For example, +** when parsing the document "I won first place", a tokenizer that supports +** synonyms would call xToken() 5 times, as follows: +** +** +** xToken(pCtx, 0, "i", 1, 0, 1); +** xToken(pCtx, 0, "won", 3, 2, 5); +** xToken(pCtx, 0, "first", 5, 6, 11); +** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11); +** xToken(pCtx, 0, "place", 5, 12, 17); +** +** +** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time +** xToken() is called. Multiple synonyms may be specified for a single token +** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. +** There is no limit to the number of synonyms that may be provided for a +** single token. +** +** In many cases, method (1) above is the best approach. It does not add +** extra data to the FTS index or require FTS5 to query for multiple terms, +** so it is efficient in terms of disk space and query speed. However, it +** does not support prefix queries very well. If, as suggested above, the +** token "first" is substituted for "1st" by the tokenizer, then the query: +** +** +** ... MATCH '1s*' +** +** will not match documents that contain the token "1st" (as the tokenizer +** will probably not map "1s" to any prefix of "first"). +** +** For full prefix support, method (3) may be preferred. In this case, +** because the index contains entries for both "first" and "1st", prefix +** queries such as 'fi*' or '1s*' will match correctly. However, because +** extra entries are added to the FTS index, this method uses more space +** within the database. +** +** Method (2) offers a midpoint between (1) and (3). Using this method, +** a query such as '1s*' will match documents that contain the literal +** token "1st", but not "first" (assuming the tokenizer is not able to +** provide synonyms for prefixes). However, a non-prefix query like '1st' +** will match against "1st" and "first". This method does not require +** extra disk space, as no extra entries are added to the FTS index. +** On the other hand, it may require more CPU cycles to run MATCH queries, +** as separate queries of the FTS index are required for each synonym. +** +** When using methods (2) or (3), it is important that the tokenizer only +** provide synonyms when tokenizing document text (method (3)) or query +** text (method (2)), not both. Doing so will not cause any errors, but is +** inefficient. +*/ +typedef struct Fts5Tokenizer Fts5Tokenizer; +typedef struct fts5_tokenizer_v2 fts5_tokenizer_v2; +struct fts5_tokenizer_v2 { + int iVersion; /* Currently always 2 */ + + int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); + void (*xDelete)(Fts5Tokenizer*); + int (*xTokenize)(Fts5Tokenizer*, + void *pCtx, + int flags, /* Mask of FTS5_TOKENIZE_* flags */ + const char *pText, int nText, + const char *pLocale, int nLocale, + int (*xToken)( + void *pCtx, /* Copy of 2nd argument to xTokenize() */ + int tflags, /* Mask of FTS5_TOKEN_* flags */ + const char *pToken, /* Pointer to buffer containing token */ + int nToken, /* Size of token in bytes */ + int iStart, /* Byte offset of token within input text */ + int iEnd /* Byte offset of end of token within input text */ + ) + ); +}; + +/* +** New code should use the fts5_tokenizer_v2 type to define tokenizer +** implementations. The following type is included for legacy applications +** that still use it. +*/ +typedef struct fts5_tokenizer fts5_tokenizer; +struct fts5_tokenizer { + int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); + void (*xDelete)(Fts5Tokenizer*); + int (*xTokenize)(Fts5Tokenizer*, + void *pCtx, + int flags, /* Mask of FTS5_TOKENIZE_* flags */ + const char *pText, int nText, + int (*xToken)( + void *pCtx, /* Copy of 2nd argument to xTokenize() */ + int tflags, /* Mask of FTS5_TOKEN_* flags */ + const char *pToken, /* Pointer to buffer containing token */ + int nToken, /* Size of token in bytes */ + int iStart, /* Byte offset of token within input text */ + int iEnd /* Byte offset of end of token within input text */ + ) + ); +}; + + +/* Flags that may be passed as the third argument to xTokenize() */ +#define FTS5_TOKENIZE_QUERY 0x0001 +#define FTS5_TOKENIZE_PREFIX 0x0002 +#define FTS5_TOKENIZE_DOCUMENT 0x0004 +#define FTS5_TOKENIZE_AUX 0x0008 + +/* Flags that may be passed by the tokenizer implementation back to FTS5 +** as the third argument to the supplied xToken callback. */ +#define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */ + +/* +** END OF CUSTOM TOKENIZERS +*************************************************************************/ + +/************************************************************************* +** FTS5 EXTENSION REGISTRATION API +*/ +typedef struct fts5_api fts5_api; +struct fts5_api { + int iVersion; /* Currently always set to 3 */ + + /* Create a new tokenizer */ + int (*xCreateTokenizer)( + fts5_api *pApi, + const char *zName, + void *pUserData, + fts5_tokenizer *pTokenizer, + void (*xDestroy)(void*) + ); + + /* Find an existing tokenizer */ + int (*xFindTokenizer)( + fts5_api *pApi, + const char *zName, + void **ppUserData, + fts5_tokenizer *pTokenizer + ); + + /* Create a new auxiliary function */ + int (*xCreateFunction)( + fts5_api *pApi, + const char *zName, + void *pUserData, + fts5_extension_function xFunction, + void (*xDestroy)(void*) + ); + + /* APIs below this point are only available if iVersion>=3 */ + + /* Create a new tokenizer */ + int (*xCreateTokenizer_v2)( + fts5_api *pApi, + const char *zName, + void *pUserData, + fts5_tokenizer_v2 *pTokenizer, + void (*xDestroy)(void*) + ); + + /* Find an existing tokenizer */ + int (*xFindTokenizer_v2)( + fts5_api *pApi, + const char *zName, + void **ppUserData, + fts5_tokenizer_v2 **ppTokenizer + ); +}; + +/* +** END OF REGISTRATION API +*************************************************************************/ + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif + +#endif /* _FTS5_H */ + +/******** End of fts5.h *********/ +#endif /* SQLITE3_H */ +/*** End of #include "sqlite3.h" ***/ + + +#ifdef SQLITE_USER_AUTHENTICATION +#undef SQLITE_USER_AUTHENTICATION +#endif + +/* +** Symbols for ciphers +*/ +#define CODEC_TYPE_UNKNOWN 0 +#define CODEC_TYPE_AES128 1 +#define CODEC_TYPE_AES256 2 +#define CODEC_TYPE_CHACHA20 3 +#define CODEC_TYPE_SQLCIPHER 4 +#define CODEC_TYPE_RC4 5 +#define CODEC_TYPE_ASCON128 6 +#define CODEC_TYPE_AEGIS 7 +#define CODEC_TYPE_MAX_BUILTIN 7 + +/* +** Definition of API functions +*/ + +/* +** Define Windows specific SQLite API functions (not defined in sqlite3.h) +*/ +#if SQLITE_OS_WIN == 1 + +#ifdef __cplusplus +extern "C" { +#endif + +SQLITE_API int sqlite3_win32_set_directory(unsigned long type, void* zValue); + +#ifdef __cplusplus +} +#endif + +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Specify the key for an encrypted database. +** This routine should be called right after sqlite3_open(). +** +** Arguments: +** db - Database to be encrypted +** zDbName - Name of the database (e.g. "main") +** pKey - Passphrase +** nKey - Length of passphrase +*/ +SQLITE_API int sqlite3_key(sqlite3* db, const void* pKey, int nKey); +SQLITE_API int sqlite3_key_v2(sqlite3* db, const char* zDbName, const void* pKey, int nKey); + +/* +** Change the key on an open database. +** If the current database is not encrypted, this routine will encrypt +** it. If pNew==0 or nNew==0, the database is decrypted. +** +** Arguments: +** db - Database to be encrypted +** zDbName - Name of the database (e.g. "main") +** pKey - Passphrase +** nKey - Length of passphrase +*/ +SQLITE_API int sqlite3_rekey(sqlite3* db, const void* pKey, int nKey); +SQLITE_API int sqlite3_rekey_v2(sqlite3* db, const char* zDbName, const void* pKey, int nKey); + +/* +** Specify the activation key for a SEE database. +** Unless activated, none of the SEE routines will work. +** +** Arguments: +** zPassPhrase - Activation phrase +** +** Note: Provided only for API compatibility with SEE. +** Encryption support of SQLite3 Multi Cipher is always enabled. +*/ +SQLITE_API void sqlite3_activate_see(const char* zPassPhrase); + +/* +** Define functions for the configuration of the wxSQLite3 encryption extension +*/ +SQLITE_API int sqlite3mc_cipher_count(); +SQLITE_API int sqlite3mc_cipher_index(const char* cipherName); +SQLITE_API const char* sqlite3mc_cipher_name(int cipherIndex); +SQLITE_API int sqlite3mc_config(sqlite3* db, const char* paramName, int newValue); +SQLITE_API int sqlite3mc_config_cipher(sqlite3* db, const char* cipherName, const char* paramName, int newValue); +SQLITE_API unsigned char* sqlite3mc_codec_data(sqlite3* db, const char* zDbName, const char* paramName); +SQLITE_API const char* sqlite3mc_version(); + +#ifdef SQLITE3MC_WXSQLITE3_COMPATIBLE +SQLITE_API int wxsqlite3_config(sqlite3* db, const char* paramName, int newValue); +SQLITE_API int wxsqlite3_config_cipher(sqlite3* db, const char* cipherName, const char* paramName, int newValue); +SQLITE_API unsigned char* wxsqlite3_codec_data(sqlite3* db, const char* zDbName, const char* paramName); +#endif + +/* +** Structures and functions to dynamically register a cipher +*/ + +/* +** Structure for a single cipher configuration parameter +** +** Components: +** m_name - name of parameter (1st char = alpha, rest = alphanumeric or underscore, max 63 characters) +** m_value - current/transient parameter value +** m_default - default parameter value +** m_minValue - minimum valid parameter value +** m_maxValue - maximum valid parameter value +*/ +typedef struct _CipherParams +{ + const char* m_name; + int m_value; + int m_default; + int m_minValue; + int m_maxValue; +} CipherParams; + +/* +** Structure for a cipher API +** +** Components: +** m_name - name of cipher (1st char = alpha, rest = alphanumeric or underscore, max 63 characters) +** m_allocateCipher - Function pointer for function AllocateCipher +** m_freeCipher - Function pointer for function FreeCipher +** m_cloneCipher - Function pointer for function CloneCipher +** m_getLegacy - Function pointer for function GetLegacy +** m_getPageSize - Function pointer for function GetPageSize +** m_getReserved - Function pointer for function GetReserved +** m_getSalt - Function pointer for function GetSalt +** m_generateKey - Function pointer for function GenerateKey +** m_encryptPage - Function pointer for function EncryptPage +** m_decryptPage - Function pointer for function DecryptPage +*/ + +typedef struct BtShared BtSharedMC; + +typedef void* (*AllocateCipher_t)(sqlite3* db); +typedef void (*FreeCipher_t)(void* cipher); +typedef void (*CloneCipher_t)(void* cipherTo, void* cipherFrom); +typedef int (*GetLegacy_t)(void* cipher); +typedef int (*GetPageSize_t)(void* cipher); +typedef int (*GetReserved_t)(void* cipher); +typedef unsigned char* (*GetSalt_t)(void* cipher); +typedef void (*GenerateKey_t)(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt); +typedef int (*EncryptPage_t)(void* cipher, int page, unsigned char* data, int len, int reserved); +typedef int (*DecryptPage_t)(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck); + +typedef struct _CipherDescriptor +{ + const char* m_name; + AllocateCipher_t m_allocateCipher; + FreeCipher_t m_freeCipher; + CloneCipher_t m_cloneCipher; + GetLegacy_t m_getLegacy; + GetPageSize_t m_getPageSize; + GetReserved_t m_getReserved; + GetSalt_t m_getSalt; + GenerateKey_t m_generateKey; + EncryptPage_t m_encryptPage; + DecryptPage_t m_decryptPage; +} CipherDescriptor; + +/* +** Register a cipher +** +** Arguments: +** desc - Cipher descriptor structure +** params - Cipher configuration parameter table +** makeDefault - flag whether to make the cipher the default cipher +** +** Returns: +** SQLITE_OK - the cipher could be registered successfully +** SQLITE_ERROR - the cipher could not be registered +*/ +SQLITE_API int sqlite3mc_register_cipher(const CipherDescriptor* desc, const CipherParams* params, int makeDefault); + +#ifdef __cplusplus +} +#endif + +/* +** Define public SQLite3 Multiple Ciphers VFS interface +*/ +/* #include "sqlite3mc_vfs.h" */ +/*** Begin of #include "sqlite3mc_vfs.h" ***/ +/* +** Name: sqlite3mc_vfs.h +** Purpose: Header file for VFS of SQLite3 Multiple Ciphers support +** Author: Ulrich Telle +** Created: 2020-03-01 +** Copyright: (c) 2020-2023 Ulrich Telle +** License: MIT +*/ + +#ifndef SQLITE3MC_VFS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE +#endif + +SQLITE_PRIVATE int sqlite3mcCheckVfs(const char* zVfs); + +SQLITE_API int sqlite3mc_vfs_create(const char* zVfsReal, int makeDefault); +SQLITE_API void sqlite3mc_vfs_destroy(const char* zName); +SQLITE_API void sqlite3mc_vfs_shutdown(); + +#ifdef __cplusplus +} +#endif + +#endif /* SQLITE3MC_VFS_H_ */ +/*** End of #include "sqlite3mc_vfs.h" ***/ + + +#endif +/*** End of #include "sqlite3mc.h" ***/ + + +SQLITE_API const char* +sqlite3mc_version() +{ + static const char* version = SQLITE3MC_VERSION_STRING; + return version; +} + +SQLITE_PRIVATE void +sqlite3mcVersion(sqlite3_context* context, int argc, sqlite3_value** argv) +{ + assert(argc == 0); + sqlite3_result_text(context, sqlite3mc_version(), -1, 0); +} + +#ifndef SQLITE3MC_SECURE_MEMORY +#define SQLITE3MC_SECURE_MEMORY 0 +#endif + +#if SQLITE3MC_SECURE_MEMORY + +#define SECURE_MEMORY_NONE 0 +#define SECURE_MEMORY_FILL 1 +#define SECURE_MEMORY_LOCK 2 + +SQLITE_PRIVATE void sqlite3mcSetMemorySecurity(int value); +SQLITE_PRIVATE int sqlite3mcGetMemorySecurity(); + +/* Memory locking is currently not supported */ +#ifdef SQLITE3MC_ENABLE_MEMLOCK +#undef SQLITE3MC_ENABLE_MEMLOCK +#endif +#define SQLITE3MC_ENABLE_MEMLOCK 0 + +#endif + +/* +** Crypto algorithms +*/ +/* #include "md5.c" */ +/*** Begin of #include "md5.c" ***/ +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD5 Message-Digest Algorithm (RFC 1321). + * + * Homepage: + * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. + * In case this attempt to disclaim copyright and place the software in the + * public domain is deemed null and void, then the software is + * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + * + * This differs from Colin Plumb's older public domain implementation in that + * no exactly 32-bit integer data type is required (any 32-bit or wider + * unsigned integer data type will do), there's no compile-time endianness + * configuration, and the function prototypes match OpenSSL's. No code from + * Colin Plumb's implementation has been reused; this comment merely compares + * the properties of the two independent implementations. + * + * The primary goals of this implementation are portability and ease of use. + * It is meant to be fast, but not as fast as possible. Some known + * optimizations are not included to reduce source code size and avoid + * compile-time configuration. + */ + +#define MD5_HASHBYTES 16 + +#include + + /* Any 32-bit or wider unsigned integer data type will do */ +typedef unsigned int MD5_u32plus; + +typedef struct { + MD5_u32plus lo, hi; + MD5_u32plus a, b, c, d; + unsigned char buffer[64]; + MD5_u32plus block[16]; +} MD5_CTX; + +static void MD5_Init(MD5_CTX *ctx); +static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); +static void MD5_Final(unsigned char *result, MD5_CTX *ctx); + +/* +* The basic MD5 functions. +* +* F and G are optimized compared to their RFC 1321 definitions for +* architectures that lack an AND-NOT instruction, just like in Colin Plumb's +* implementation. +*/ +#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) +#define H(x, y, z) (((x) ^ (y)) ^ (z)) +#define H2(x, y, z) ((x) ^ ((y) ^ (z))) +#define I(x, y, z) ((y) ^ ((x) | ~(z))) + +/* +* The MD5 transformation for all four rounds. +*/ +#define STEP(f, a, b, c, d, x, t, s) \ + (a) += f((b), (c), (d)) + (x) + (t); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ + (a) += (b); + +/* +* SET reads 4 input bytes in little-endian byte order and stores them +* in a properly aligned word in host byte order. +* +* The check for little-endian architectures that tolerate unaligned +* memory accesses is just an optimization. Nothing will break if it +* doesn't work. +*/ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define SET(n) \ + (*(MD5_u32plus *)&ptr[(n) * 4]) +#define GET(n) \ + SET(n) +#else +#define SET(n) \ + (ctx->block[(n)] = \ + (MD5_u32plus)ptr[(n) * 4] | \ + ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ + ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ + ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) +#define GET(n) \ + (ctx->block[(n)]) +#endif + +/* +* This processes one or more 64-byte data blocks, but does NOT update +* the bit counters. There are no alignment requirements. +*/ +static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) +{ + const unsigned char *ptr; + MD5_u32plus a, b, c, d; + MD5_u32plus saved_a, saved_b, saved_c, saved_d; + + ptr = (const unsigned char *)data; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + + /* Round 1 */ + STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) + STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) + STEP(F, c, d, a, b, SET(2), 0x242070db, 17) + STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) + STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) + STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) + STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) + STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) + STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) + STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) + STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) + STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) + STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) + STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) + STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) + STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) + + /* Round 2 */ + STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) + STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) + STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) + STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) + STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) + STEP(G, d, a, b, c, GET(10), 0x02441453, 9) + STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) + STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) + STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) + STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) + STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) + STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) + STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) + STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) + STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) + STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) + + /* Round 3 */ + STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) + STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) + STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) + STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) + STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) + STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) + STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) + STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) + STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) + STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) + STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) + STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) + STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) + STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) + STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) + STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) + + /* Round 4 */ + STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) + STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) + STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) + STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) + STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) + STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) + STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) + STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) + STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) + STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) + STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) + STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) + STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) + STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) + STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) + STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while (size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +void MD5_Init(MD5_CTX *ctx) +{ + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; +} + +void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) +{ + MD5_u32plus saved_lo; + unsigned long used, available; + + saved_lo = ctx->lo; + if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) + ctx->hi++; + ctx->hi += size >> 29; + + used = saved_lo & 0x3f; + + if (used) { + available = 64 - used; + + if (size < available) { + memcpy(&ctx->buffer[used], data, size); + return; + } + + memcpy(&ctx->buffer[used], data, available); + data = (const unsigned char *)data + available; + size -= available; + body(ctx, ctx->buffer, 64); + } + + if (size >= 64) { + data = body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); +} + +void MD5_Final(unsigned char *result, MD5_CTX *ctx) +{ + unsigned long used, available; + + used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + available = 64 - used; + + if (available < 8) { + memset(&ctx->buffer[used], 0, available); + body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = ctx->lo; + ctx->buffer[57] = ctx->lo >> 8; + ctx->buffer[58] = ctx->lo >> 16; + ctx->buffer[59] = ctx->lo >> 24; + ctx->buffer[60] = ctx->hi; + ctx->buffer[61] = ctx->hi >> 8; + ctx->buffer[62] = ctx->hi >> 16; + ctx->buffer[63] = ctx->hi >> 24; + + body(ctx, ctx->buffer, 64); + + result[0] = ctx->a; + result[1] = ctx->a >> 8; + result[2] = ctx->a >> 16; + result[3] = ctx->a >> 24; + result[4] = ctx->b; + result[5] = ctx->b >> 8; + result[6] = ctx->b >> 16; + result[7] = ctx->b >> 24; + result[8] = ctx->c; + result[9] = ctx->c >> 8; + result[10] = ctx->c >> 16; + result[11] = ctx->c >> 24; + result[12] = ctx->d; + result[13] = ctx->d >> 8; + result[14] = ctx->d >> 16; + result[15] = ctx->d >> 24; + + memset(ctx, 0, sizeof(*ctx)); +} +/*** End of #include "md5.c" ***/ + +/* #include "sha1.c" */ +/*** Begin of #include "sha1.c" ***/ +/** +* @file sha1.c SHA-1 in C +*/ + +/* +By Steve Reid +100% Public Domain + +----------------- +Modified 7/98 +By James H. Brown +Still 100% Public Domain + +Corrected a problem which generated improper hash values on 16 bit machines +Routine SHA1Update changed from + void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int +len) +to + void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned +long len) + +The 'len' parameter was declared an int which works fine on 32 bit machines. +However, on 16 bit machines an int is too small for the shifts being done +against +it. This caused the hash function to generate incorrect values if len was +greater than 8191 (8K - 1) due to the 'len << 3' on line 3 of SHA1Update(). + +Since the file IO in main() reads 16K at a time, any file 8K or larger would +be guaranteed to generate the wrong hash (e.g. Test Vector #3, a million +"a"s). + +I also changed the declaration of variables i & j in SHA1Update to +unsigned long from unsigned int for the same reason. + +These changes should make no difference to any 32 bit implementations since +an +int and a long are the same size in those environments. + +-- +I also corrected a few compiler warnings generated by Borland C. +1. Added #include for exit() prototype +2. Removed unused variable 'j' in SHA1Final +3. Changed exit(0) to return(0) at end of main. + +ALL changes I made can be located by searching for comments containing 'JHB' +----------------- +Modified 8/98 +By Steve Reid +Still 100% public domain + +1- Removed #include and used return() instead of exit() +2- Fixed overwriting of finalcount in SHA1Final() (discovered by Chris Hall) +3- Changed email address from steve@edmweb.com to sreid@sea-to-sky.net + +----------------- +Modified 4/01 +By Saul Kravitz +Still 100% PD +Modified to run on Compaq Alpha hardware. + +----------------- +Modified 07/2002 +By Ralph Giles +Still 100% public domain +modified for use with stdint types, autoconf +code cleanup, removed attribution comments +switched SHA1Final() argument order for consistency +use SHA1_ prefix for public api +move public api to sha1.h + +----------------- +Modified 02/2018 +By Ulrich Telle +Still 100% public domain +modified for use with fast-pbkdf2 (written by Joseph Birr-Pixton) +detect endianess at run-time +*/ + +/* +Test Vectors (from FIPS PUB 180-1) +"abc" + A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D +"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 +A million repetitions of "a" + 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F +*/ + +/* #include "mystdint.h" */ +/*** Begin of #include "mystdint.h" ***/ +#ifndef MY_STDINT_H_ +#define MY_STDINT_H_ + +/* +** MS Visual C++ 2008 and below do not provide the header file +** That is, we need to define the necessary types ourselves +*/ + +#if defined(_MSC_VER) && (_MSC_VER < 1600) +typedef signed char int8_t; +typedef short int16_t; +typedef int int32_t; +typedef long long int64_t; +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long long uint64_t; + +#define UINT8_MAX 255 +#define UINT16_MAX 65535 +#define UINT32_MAX 0xffffffffU /* 4294967295U */ +#define UINT64_MAX 0xffffffffffffffffULL /* 18446744073709551615ULL */ +#else +#include +#endif + +#endif /* MY_STDINT_H_ */ +/*** End of #include "mystdint.h" ***/ + + +#include +#include +/* #include "sha1.h" */ +/*** Begin of #include "sha1.h" ***/ +/* public api for steve reid's public domain SHA-1 implementation */ +/* this file is in the public domain */ + +#ifndef SHA1_H_ +#define SHA1_H_ (1) + +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE +#endif + +/** SHA-1 Context */ +typedef struct { + uint32_t h[5]; + /**< Context state */ + uint32_t count[2]; + /**< Counter */ + uint8_t buffer[64]; /**< SHA-1 buffer */ +} sha1_ctx; + +#define SHA1_BLOCK_SIZE 64 +/** SHA-1 Digest size in bytes */ +#define SHA1_DIGEST_SIZE 20 + +SQLITE_PRIVATE void sha1_init(sha1_ctx *context); + +SQLITE_PRIVATE void sha1_update(sha1_ctx *context, const void *p, size_t len); + +SQLITE_PRIVATE void sha1_final(sha1_ctx *context, uint8_t digest[SHA1_DIGEST_SIZE]); + +SQLITE_PRIVATE void sha1_transform(sha1_ctx *context, const uint8_t buffer[64]); + +#endif /* SHA1_H_ */ +/*** End of #include "sha1.h" ***/ + + +#if 0 +/* TODO: asm doesn't compile under Linux, use generic C equivalent for now */ +#if __GNUC__ && (defined(__i386__) || defined(__x86_64__)) +/* +* GCC by itself only generates left rotates. Use right rotates if +* possible to be kinder to dinky implementations with iterative rotate +* instructions. +*/ +#define SHA_ROT(op, x, k) \ + ({ unsigned int y; asm(op " %1,%0" : "=r" (y) : "I" (k), "0" (x)); y; }) +#define rol(x,k) SHA_ROT("roll", x, k) +#define ror(x,k) SHA_ROT("rorl", x, k) +#else +/* Generic C equivalent */ +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) +#define ror(value, bits) (((value) << (32 - (bits))) | ((value) >> (bits))) +#endif +#endif + +/* Generic C equivalent */ +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) +#define ror(value, bits) (((value) << (32 - (bits))) | ((value) >> (bits))) + +#define blk0le(i) (block[i] = (ror(block[i],8)&0xFF00FF00) \ + |(rol(block[i],8)&0x00FF00FF)) +#define blk0be(i) block[i] +#define blk(i) (block[i&15] = rol(block[(i+13)&15]^block[(i+8)&15] \ + ^block[(i+2)&15]^block[i&15],1)) + +/* +* (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1 +* +* Rl0() for little-endian and Rb0() for big-endian. Endianness is +* determined at run-time. +*/ +#define Rl0(v,w,x,y,z,i) \ + z+=((w&(x^y))^y)+blk0le(i)+0x5A827999+rol(v,5);w=ror(w,2); +#define Rb0(v,w,x,y,z,i) \ + z+=((w&(x^y))^y)+blk0be(i)+0x5A827999+rol(v,5);w=ror(w,2); +#define R1(v,w,x,y,z,i) \ + z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=ror(w,2); +#define R2(v,w,x,y,z,i) \ + z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=ror(w,2); +#define R3(v,w,x,y,z,i) \ + z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=ror(w,2); +#define R4(v,w,x,y,z,i) \ + z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=ror(w,2); + +/* Hash a single 512-bit block. This is the core of the algorithm. */ +SQLITE_PRIVATE +void sha1_transform(sha1_ctx *context, const uint8_t buffer[64]) +{ + uint32_t a, b, c, d, e; + static int one = 1; + uint32_t block[16]; + memcpy(block, buffer, 64); + + /* Copy context->h[] to working vars */ + a = context->h[0]; + b = context->h[1]; + c = context->h[2]; + d = context->h[3]; + e = context->h[4]; + + /* 4 rounds of 20 operations each. Loop unrolled. */ + if (1 == *(unsigned char*)&one) /* Check for endianess */ + { + Rl0(a, b, c, d, e, 0); Rl0(e, a, b, c, d, 1); Rl0(d, e, a, b, c, 2); Rl0(c, d, e, a, b, 3); + Rl0(b, c, d, e, a, 4); Rl0(a, b, c, d, e, 5); Rl0(e, a, b, c, d, 6); Rl0(d, e, a, b, c, 7); + Rl0(c, d, e, a, b, 8); Rl0(b, c, d, e, a, 9); Rl0(a, b, c, d, e, 10); Rl0(e, a, b, c, d, 11); + Rl0(d, e, a, b, c, 12); Rl0(c, d, e, a, b, 13); Rl0(b, c, d, e, a, 14); Rl0(a, b, c, d, e, 15); + } + else + { + Rb0(a, b, c, d, e, 0); Rb0(e, a, b, c, d, 1); Rb0(d, e, a, b, c, 2); Rb0(c, d, e, a, b, 3); + Rb0(b, c, d, e, a, 4); Rb0(a, b, c, d, e, 5); Rb0(e, a, b, c, d, 6); Rb0(d, e, a, b, c, 7); + Rb0(c, d, e, a, b, 8); Rb0(b, c, d, e, a, 9); Rb0(a, b, c, d, e, 10); Rb0(e, a, b, c, d, 11); + Rb0(d, e, a, b, c, 12); Rb0(c, d, e, a, b, 13); Rb0(b, c, d, e, a, 14); Rb0(a, b, c, d, e, 15); + } + R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79); + + /* Add the working vars back into context.state[] */ + context->h[0] += a; + context->h[1] += b; + context->h[2] += c; + context->h[3] += d; + context->h[4] += e; + + /* Wipe variables */ + a = b = c = d = e = 0; + memset(block, 0, 64); +} + + +/** +* Initialize new context +* +* @param context SHA1-Context +*/ +SQLITE_PRIVATE +void sha1_init(sha1_ctx *context) +{ + /* SHA1 initialization constants */ + context->h[0] = 0x67452301; + context->h[1] = 0xefcdab89; + context->h[2] = 0x98badcfe; + context->h[3] = 0x10325476; + context->h[4] = 0xc3d2e1f0; + context->count[0] = context->count[1] = 0; +} + + +/** +* Run your data through this +* +* @param context SHA1-Context +* @param p Buffer to run SHA1 on +* @param len Number of bytes +*/ +SQLITE_PRIVATE +void sha1_update(sha1_ctx *context, const void *p, size_t len) +{ + const uint8_t *data = p; + size_t i, j; + + j = (context->count[0] >> 3) & 63; + if ((context->count[0] += (uint32_t) (len << 3)) < (len << 3)) + { + context->count[1]++; + } + context->count[1] += (uint32_t) (len >> 29); + if ((j + len) > 63) + { + memcpy(&context->buffer[j], data, (i = 64 - j)); + sha1_transform(context, context->buffer); + for (; i + 63 < len; i += 64) + { + sha1_transform(context, data + i); + } + j = 0; + } + else + { + i = 0; + } + memcpy(&context->buffer[j], &data[i], len - i); +} + + +/** +* Add padding and return the message digest +* +* @param digest Generated message digest +* @param context SHA1-Context +*/ +SQLITE_PRIVATE +void sha1_final(sha1_ctx *context, uint8_t digest[SHA1_DIGEST_SIZE]) +{ + uint32_t i; + uint8_t finalcount[8]; + + for (i = 0; i < 8; i++) + { + finalcount[i] = (uint8_t) ((context->count[(i >= 4 ? 0 : 1)] + >> ((3 - (i & 3)) * 8)) & 255); + } + sha1_update(context, (uint8_t *) "\200", 1); + while ((context->count[0] & 504) != 448) + { + sha1_update(context, (uint8_t *) "\0", 1); + } + sha1_update(context, finalcount, 8); /* Should cause SHA1_Transform */ + for (i = 0; i < SHA1_DIGEST_SIZE; i++) + { + digest[i] = (uint8_t) + ((context->h[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + + /* Wipe variables */ + i = 0; + memset(context->buffer, 0, 64); + /* fast-pbkdf2 needs access to the state*/ + /*memset(context->h, 0, 20);*/ + memset(context->count, 0, 8); + memset(finalcount, 0, 8); /* SWR */ +} +/*** End of #include "sha1.c" ***/ + +/* #include "sha2.c" */ +/*** Begin of #include "sha2.c" ***/ +/* + * FIPS 180-2 SHA-224/256/384/512 implementation + * Last update: 02/02/2007 + * Issue date: 04/30/2005 + * + * Copyright (C) 2005, 2007 Olivier Gay + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * 3. Neither the name of the project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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. + */ + +#if 1 +#define UNROLL_LOOPS /* Enable loops unrolling */ +#endif + +#include + +/* #include "sha2.h" */ +/*** Begin of #include "sha2.h" ***/ +/* + * FIPS 180-2 SHA-224/256/384/512 implementation + * Last update: 02/02/2007 + * Issue date: 04/30/2005 + * + * Copyright (C) 2005, 2007 Olivier Gay + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * 3. Neither the name of the project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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. + */ + +#ifndef SHA2_H +#define SHA2_H + +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE +#endif + +#define SHA224_DIGEST_SIZE ( 224 / 8) +#define SHA256_DIGEST_SIZE ( 256 / 8) +#define SHA384_DIGEST_SIZE ( 384 / 8) +#define SHA512_DIGEST_SIZE ( 512 / 8) + +#define SHA256_BLOCK_SIZE ( 512 / 8) +#define SHA512_BLOCK_SIZE (1024 / 8) +#define SHA384_BLOCK_SIZE SHA512_BLOCK_SIZE +#define SHA224_BLOCK_SIZE SHA256_BLOCK_SIZE + +#ifndef SHA2_TYPES +#define SHA2_TYPES +typedef unsigned char uint8; +typedef unsigned int uint32; + +typedef sqlite3_uint64 uint64; + +#if defined(_MSC_VER) || defined(__BORLANDC__) + #define li_64(h) 0x##h##ui64 +#else + #define li_64(h) 0x##h##ull +#endif + +#if 0 /* Start of original int64 defines */ + +#if defined(_MSC_VER) + #if _MSC_VER >= 1310 + typedef unsigned long long uint64; + #define li_64(h) 0x##h##ull + #else + typedef unsigned __int64 uint64; + #define li_64(h) 0x##h##ui64 + #endif +#elif defined(__BORLANDC__) && !defined(__MSDOS__) + #define li_64(h) 0x##h##ull + typedef __int64 uint64; +#elif defined(__sun) + #if defined(ULONG_MAX) && ULONG_MAX == 0xfffffffful + #define li_64(h) 0x##h##ull + typedef unsigned long long uint64; + #elif defined(ULONG_LONG_MAX) && ULONG_LONG_MAX == 0xfffffffffffffffful + #define li_64(h) 0x##h##ul + typedef unsigned long uint64; + #endif +#elif defined(__MVS__) + #define li_64(h) 0x##h##ull + typedef unsigned int long long uint64; +#elif defined(ULLONG_MAX) && ULLONG_MAX > 4294967295 + #if ULLONG_MAX == 18446744073709551615ull + #define li_64(h) 0x##h##ull + typedef unsigned long long uint64; + #endif +#elif defined(ULONG_LONG_MAX) && ULONG_LONG_MAX > 4294967295 + #if ULONG_LONG_MAX == 18446744073709551615 + #define li_64(h) 0x##h##ull + typedef unsigned long long uint64; + #endif +#elif defined(ULONG_MAX) && ULONG_MAX > 4294967295 + #if ULONG_MAX == 18446744073709551615 + #define li_64(h) 0x##h##ul + typedef unsigned long uint64; + #endif +#elif defined(UINT_MAX) && UINT_MAX > 4294967295 + #if UINT_MAX == 18446744073709551615 + #define li_64(h) 0x##h##u + typedef unsigned int uint64; + #endif +#endif +#endif + +#endif /* End of original int64 defines */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + unsigned int tot_len; + unsigned int len; + unsigned char block[2 * SHA256_BLOCK_SIZE]; + uint32 h[8]; +} sha256_ctx; + +typedef struct { + unsigned int tot_len; + unsigned int len; + unsigned char block[2 * SHA512_BLOCK_SIZE]; + uint64 h[8]; +} sha512_ctx; + +typedef sha512_ctx sha384_ctx; +typedef sha256_ctx sha224_ctx; + +SQLITE_PRIVATE void sha224_init(sha224_ctx *ctx); +SQLITE_PRIVATE void sha224_update(sha224_ctx *ctx, const unsigned char *message, unsigned int len); +SQLITE_PRIVATE void sha224_final(sha224_ctx *ctx, unsigned char *digest); +SQLITE_PRIVATE void sha224(const unsigned char *message, unsigned int len, unsigned char *digest); + +SQLITE_PRIVATE void sha256_init(sha256_ctx * ctx); +SQLITE_PRIVATE void sha256_update(sha256_ctx *ctx, const unsigned char *message, unsigned int len); +SQLITE_PRIVATE void sha256_final(sha256_ctx *ctx, unsigned char *digest); +SQLITE_PRIVATE void sha256_transform(sha256_ctx *ctx, const unsigned char *message); +SQLITE_PRIVATE void sha256(const unsigned char *message, unsigned int len, unsigned char *digest); + +SQLITE_PRIVATE void sha384_init(sha384_ctx *ctx); +SQLITE_PRIVATE void sha384_update(sha384_ctx *ctx, const unsigned char *message, unsigned int len); +SQLITE_PRIVATE void sha384_final(sha384_ctx *ctx, unsigned char *digest); +SQLITE_PRIVATE void sha384(const unsigned char *message, unsigned int len, unsigned char *digest); + +SQLITE_PRIVATE void sha512_init(sha512_ctx *ctx); +SQLITE_PRIVATE void sha512_update(sha512_ctx *ctx, const unsigned char *message, unsigned int len); +SQLITE_PRIVATE void sha512_final(sha512_ctx *ctx, unsigned char *digest); +SQLITE_PRIVATE void sha512_transform(sha512_ctx *ctx, const unsigned char *message); +SQLITE_PRIVATE void sha512(const unsigned char *message, unsigned int len, unsigned char *digest); + +#ifdef __cplusplus +} +#endif + +#endif /* !SHA2_H */ + +/*** End of #include "sha2.h" ***/ + + +#define SHFR(x, n) (x >> n) +#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) +#if 0 +/* SQLite version 3.40.0 and later already defines this macro. */ +/* The macro isn't used here anyway, so simply inactivate it. */ +#define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) +#endif +#define CH(x, y, z) ((x & y) ^ (~x & z)) +#define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) + +#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) +#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) +#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3)) +#define SHA256_F4(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10)) + +#define SHA512_F1(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39)) +#define SHA512_F2(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41)) +#define SHA512_F3(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHFR(x, 7)) +#define SHA512_F4(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHFR(x, 6)) + +#define UNPACK32(x, str) \ +{ \ + *((str) + 3) = (uint8) ((x) ); \ + *((str) + 2) = (uint8) ((x) >> 8); \ + *((str) + 1) = (uint8) ((x) >> 16); \ + *((str) + 0) = (uint8) ((x) >> 24); \ +} + +#define PACK32(str, x) \ +{ \ + *(x) = ((uint32) *((str) + 3) ) \ + | ((uint32) *((str) + 2) << 8) \ + | ((uint32) *((str) + 1) << 16) \ + | ((uint32) *((str) + 0) << 24); \ +} + +#define UNPACK64(x, str) \ +{ \ + *((str) + 7) = (uint8) ((x) ); \ + *((str) + 6) = (uint8) ((x) >> 8); \ + *((str) + 5) = (uint8) ((x) >> 16); \ + *((str) + 4) = (uint8) ((x) >> 24); \ + *((str) + 3) = (uint8) ((x) >> 32); \ + *((str) + 2) = (uint8) ((x) >> 40); \ + *((str) + 1) = (uint8) ((x) >> 48); \ + *((str) + 0) = (uint8) ((x) >> 56); \ +} + +#define PACK64(str, x) \ +{ \ + *(x) = ((uint64) *((str) + 7) ) \ + | ((uint64) *((str) + 6) << 8) \ + | ((uint64) *((str) + 5) << 16) \ + | ((uint64) *((str) + 4) << 24) \ + | ((uint64) *((str) + 3) << 32) \ + | ((uint64) *((str) + 2) << 40) \ + | ((uint64) *((str) + 1) << 48) \ + | ((uint64) *((str) + 0) << 56); \ +} + +/* Macros used for loops unrolling */ + +#define SHA256_SCR(i) \ +{ \ + w[i] = SHA256_F4(w[i - 2]) + w[i - 7] \ + + SHA256_F3(w[i - 15]) + w[i - 16]; \ +} + +#define SHA512_SCR(i) \ +{ \ + w[i] = SHA512_F4(w[i - 2]) + w[i - 7] \ + + SHA512_F3(w[i - 15]) + w[i - 16]; \ +} + +#define SHA256_EXP(a, b, c, d, e, f, g, h, j) \ +{ \ + t1 = wv[h] + SHA256_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \ + + sha256_k[j] + w[j]; \ + t2 = SHA256_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ + wv[d] += t1; \ + wv[h] = t1 + t2; \ +} + +#define SHA512_EXP(a, b, c, d, e, f, g ,h, j) \ +{ \ + t1 = wv[h] + SHA512_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \ + + sha512_k[j] + w[j]; \ + t2 = SHA512_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ + wv[d] += t1; \ + wv[h] = t1 + t2; \ +} + +static uint32 sha224_h0[8] = + {0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4}; + +static uint32 sha256_h0[8] = + {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + +static uint64 sha384_h0[8] = + {li_64(cbbb9d5dc1059ed8), li_64(629a292a367cd507), + li_64(9159015a3070dd17), li_64(152fecd8f70e5939), + li_64(67332667ffc00b31), li_64(8eb44a8768581511), + li_64(db0c2e0d64f98fa7), li_64(47b5481dbefa4fa4)}; + +static uint64 sha512_h0[8] = + {li_64(6a09e667f3bcc908), li_64(bb67ae8584caa73b), + li_64(3c6ef372fe94f82b), li_64(a54ff53a5f1d36f1), + li_64(510e527fade682d1), li_64(9b05688c2b3e6c1f), + li_64(1f83d9abfb41bd6b), li_64(5be0cd19137e2179)}; + +static uint32 sha256_k[64] = + {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + +static uint64 sha512_k[80] = + {li_64(428a2f98d728ae22), li_64(7137449123ef65cd), + li_64(b5c0fbcfec4d3b2f), li_64(e9b5dba58189dbbc), + li_64(3956c25bf348b538), li_64(59f111f1b605d019), + li_64(923f82a4af194f9b), li_64(ab1c5ed5da6d8118), + li_64(d807aa98a3030242), li_64(12835b0145706fbe), + li_64(243185be4ee4b28c), li_64(550c7dc3d5ffb4e2), + li_64(72be5d74f27b896f), li_64(80deb1fe3b1696b1), + li_64(9bdc06a725c71235), li_64(c19bf174cf692694), + li_64(e49b69c19ef14ad2), li_64(efbe4786384f25e3), + li_64(0fc19dc68b8cd5b5), li_64(240ca1cc77ac9c65), + li_64(2de92c6f592b0275), li_64(4a7484aa6ea6e483), + li_64(5cb0a9dcbd41fbd4), li_64(76f988da831153b5), + li_64(983e5152ee66dfab), li_64(a831c66d2db43210), + li_64(b00327c898fb213f), li_64(bf597fc7beef0ee4), + li_64(c6e00bf33da88fc2), li_64(d5a79147930aa725), + li_64(06ca6351e003826f), li_64(142929670a0e6e70), + li_64(27b70a8546d22ffc), li_64(2e1b21385c26c926), + li_64(4d2c6dfc5ac42aed), li_64(53380d139d95b3df), + li_64(650a73548baf63de), li_64(766a0abb3c77b2a8), + li_64(81c2c92e47edaee6), li_64(92722c851482353b), + li_64(a2bfe8a14cf10364), li_64(a81a664bbc423001), + li_64(c24b8b70d0f89791), li_64(c76c51a30654be30), + li_64(d192e819d6ef5218), li_64(d69906245565a910), + li_64(f40e35855771202a), li_64(106aa07032bbd1b8), + li_64(19a4c116b8d2d0c8), li_64(1e376c085141ab53), + li_64(2748774cdf8eeb99), li_64(34b0bcb5e19b48a8), + li_64(391c0cb3c5c95a63), li_64(4ed8aa4ae3418acb), + li_64(5b9cca4f7763e373), li_64(682e6ff3d6b2b8a3), + li_64(748f82ee5defb2fc), li_64(78a5636f43172f60), + li_64(84c87814a1f0ab72), li_64(8cc702081a6439ec), + li_64(90befffa23631e28), li_64(a4506cebde82bde9), + li_64(bef9a3f7b2c67915), li_64(c67178f2e372532b), + li_64(ca273eceea26619c), li_64(d186b8c721c0c207), + li_64(eada7dd6cde0eb1e), li_64(f57d4f7fee6ed178), + li_64(06f067aa72176fba), li_64(0a637dc5a2c898a6), + li_64(113f9804bef90dae), li_64(1b710b35131c471b), + li_64(28db77f523047d84), li_64(32caab7b40c72493), + li_64(3c9ebe0a15c9bebc), li_64(431d67c49c100d4c), + li_64(4cc5d4becb3e42b6), li_64(597f299cfc657e2a), + li_64(5fcb6fab3ad6faec), li_64(6c44198c4a475817)}; + +/* SHA-256 functions */ + +static +void sha256_transf(sha256_ctx *ctx, const unsigned char *message, + unsigned int block_nb) +{ + uint32 w[64]; + uint32 wv[8]; + uint32 t1, t2; + const unsigned char *sub_block; + int i; + +#ifndef UNROLL_LOOPS + int j; +#endif + + for (i = 0; i < (int) block_nb; i++) { + sub_block = message + (i << 6); + +#ifndef UNROLL_LOOPS + for (j = 0; j < 16; j++) { + PACK32(&sub_block[j << 2], &w[j]); + } + + for (j = 16; j < 64; j++) { + SHA256_SCR(j); + } + + for (j = 0; j < 8; j++) { + wv[j] = ctx->h[j]; + } + + for (j = 0; j < 64; j++) { + t1 = wv[7] + SHA256_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) + + sha256_k[j] + w[j]; + t2 = SHA256_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]); + wv[7] = wv[6]; + wv[6] = wv[5]; + wv[5] = wv[4]; + wv[4] = wv[3] + t1; + wv[3] = wv[2]; + wv[2] = wv[1]; + wv[1] = wv[0]; + wv[0] = t1 + t2; + } + + for (j = 0; j < 8; j++) { + ctx->h[j] += wv[j]; + } +#else + PACK32(&sub_block[ 0], &w[ 0]); PACK32(&sub_block[ 4], &w[ 1]); + PACK32(&sub_block[ 8], &w[ 2]); PACK32(&sub_block[12], &w[ 3]); + PACK32(&sub_block[16], &w[ 4]); PACK32(&sub_block[20], &w[ 5]); + PACK32(&sub_block[24], &w[ 6]); PACK32(&sub_block[28], &w[ 7]); + PACK32(&sub_block[32], &w[ 8]); PACK32(&sub_block[36], &w[ 9]); + PACK32(&sub_block[40], &w[10]); PACK32(&sub_block[44], &w[11]); + PACK32(&sub_block[48], &w[12]); PACK32(&sub_block[52], &w[13]); + PACK32(&sub_block[56], &w[14]); PACK32(&sub_block[60], &w[15]); + + SHA256_SCR(16); SHA256_SCR(17); SHA256_SCR(18); SHA256_SCR(19); + SHA256_SCR(20); SHA256_SCR(21); SHA256_SCR(22); SHA256_SCR(23); + SHA256_SCR(24); SHA256_SCR(25); SHA256_SCR(26); SHA256_SCR(27); + SHA256_SCR(28); SHA256_SCR(29); SHA256_SCR(30); SHA256_SCR(31); + SHA256_SCR(32); SHA256_SCR(33); SHA256_SCR(34); SHA256_SCR(35); + SHA256_SCR(36); SHA256_SCR(37); SHA256_SCR(38); SHA256_SCR(39); + SHA256_SCR(40); SHA256_SCR(41); SHA256_SCR(42); SHA256_SCR(43); + SHA256_SCR(44); SHA256_SCR(45); SHA256_SCR(46); SHA256_SCR(47); + SHA256_SCR(48); SHA256_SCR(49); SHA256_SCR(50); SHA256_SCR(51); + SHA256_SCR(52); SHA256_SCR(53); SHA256_SCR(54); SHA256_SCR(55); + SHA256_SCR(56); SHA256_SCR(57); SHA256_SCR(58); SHA256_SCR(59); + SHA256_SCR(60); SHA256_SCR(61); SHA256_SCR(62); SHA256_SCR(63); + + wv[0] = ctx->h[0]; wv[1] = ctx->h[1]; + wv[2] = ctx->h[2]; wv[3] = ctx->h[3]; + wv[4] = ctx->h[4]; wv[5] = ctx->h[5]; + wv[6] = ctx->h[6]; wv[7] = ctx->h[7]; + + SHA256_EXP(0,1,2,3,4,5,6,7, 0); SHA256_EXP(7,0,1,2,3,4,5,6, 1); + SHA256_EXP(6,7,0,1,2,3,4,5, 2); SHA256_EXP(5,6,7,0,1,2,3,4, 3); + SHA256_EXP(4,5,6,7,0,1,2,3, 4); SHA256_EXP(3,4,5,6,7,0,1,2, 5); + SHA256_EXP(2,3,4,5,6,7,0,1, 6); SHA256_EXP(1,2,3,4,5,6,7,0, 7); + SHA256_EXP(0,1,2,3,4,5,6,7, 8); SHA256_EXP(7,0,1,2,3,4,5,6, 9); + SHA256_EXP(6,7,0,1,2,3,4,5,10); SHA256_EXP(5,6,7,0,1,2,3,4,11); + SHA256_EXP(4,5,6,7,0,1,2,3,12); SHA256_EXP(3,4,5,6,7,0,1,2,13); + SHA256_EXP(2,3,4,5,6,7,0,1,14); SHA256_EXP(1,2,3,4,5,6,7,0,15); + SHA256_EXP(0,1,2,3,4,5,6,7,16); SHA256_EXP(7,0,1,2,3,4,5,6,17); + SHA256_EXP(6,7,0,1,2,3,4,5,18); SHA256_EXP(5,6,7,0,1,2,3,4,19); + SHA256_EXP(4,5,6,7,0,1,2,3,20); SHA256_EXP(3,4,5,6,7,0,1,2,21); + SHA256_EXP(2,3,4,5,6,7,0,1,22); SHA256_EXP(1,2,3,4,5,6,7,0,23); + SHA256_EXP(0,1,2,3,4,5,6,7,24); SHA256_EXP(7,0,1,2,3,4,5,6,25); + SHA256_EXP(6,7,0,1,2,3,4,5,26); SHA256_EXP(5,6,7,0,1,2,3,4,27); + SHA256_EXP(4,5,6,7,0,1,2,3,28); SHA256_EXP(3,4,5,6,7,0,1,2,29); + SHA256_EXP(2,3,4,5,6,7,0,1,30); SHA256_EXP(1,2,3,4,5,6,7,0,31); + SHA256_EXP(0,1,2,3,4,5,6,7,32); SHA256_EXP(7,0,1,2,3,4,5,6,33); + SHA256_EXP(6,7,0,1,2,3,4,5,34); SHA256_EXP(5,6,7,0,1,2,3,4,35); + SHA256_EXP(4,5,6,7,0,1,2,3,36); SHA256_EXP(3,4,5,6,7,0,1,2,37); + SHA256_EXP(2,3,4,5,6,7,0,1,38); SHA256_EXP(1,2,3,4,5,6,7,0,39); + SHA256_EXP(0,1,2,3,4,5,6,7,40); SHA256_EXP(7,0,1,2,3,4,5,6,41); + SHA256_EXP(6,7,0,1,2,3,4,5,42); SHA256_EXP(5,6,7,0,1,2,3,4,43); + SHA256_EXP(4,5,6,7,0,1,2,3,44); SHA256_EXP(3,4,5,6,7,0,1,2,45); + SHA256_EXP(2,3,4,5,6,7,0,1,46); SHA256_EXP(1,2,3,4,5,6,7,0,47); + SHA256_EXP(0,1,2,3,4,5,6,7,48); SHA256_EXP(7,0,1,2,3,4,5,6,49); + SHA256_EXP(6,7,0,1,2,3,4,5,50); SHA256_EXP(5,6,7,0,1,2,3,4,51); + SHA256_EXP(4,5,6,7,0,1,2,3,52); SHA256_EXP(3,4,5,6,7,0,1,2,53); + SHA256_EXP(2,3,4,5,6,7,0,1,54); SHA256_EXP(1,2,3,4,5,6,7,0,55); + SHA256_EXP(0,1,2,3,4,5,6,7,56); SHA256_EXP(7,0,1,2,3,4,5,6,57); + SHA256_EXP(6,7,0,1,2,3,4,5,58); SHA256_EXP(5,6,7,0,1,2,3,4,59); + SHA256_EXP(4,5,6,7,0,1,2,3,60); SHA256_EXP(3,4,5,6,7,0,1,2,61); + SHA256_EXP(2,3,4,5,6,7,0,1,62); SHA256_EXP(1,2,3,4,5,6,7,0,63); + + ctx->h[0] += wv[0]; ctx->h[1] += wv[1]; + ctx->h[2] += wv[2]; ctx->h[3] += wv[3]; + ctx->h[4] += wv[4]; ctx->h[5] += wv[5]; + ctx->h[6] += wv[6]; ctx->h[7] += wv[7]; +#endif /* !UNROLL_LOOPS */ + } +} + +SQLITE_PRIVATE +void sha256_transform(sha256_ctx *ctx, const unsigned char *message) +{ + sha256_transf(ctx, message, 1); +} + +SQLITE_PRIVATE +void sha256(const unsigned char *message, unsigned int len, unsigned char *digest) +{ + sha256_ctx ctx; + + sha256_init(&ctx); + sha256_update(&ctx, message, len); + sha256_final(&ctx, digest); +} + +SQLITE_PRIVATE +void sha256_init(sha256_ctx *ctx) +{ +#ifndef UNROLL_LOOPS + int i; + for (i = 0; i < 8; i++) { + ctx->h[i] = sha256_h0[i]; + } +#else + ctx->h[0] = sha256_h0[0]; ctx->h[1] = sha256_h0[1]; + ctx->h[2] = sha256_h0[2]; ctx->h[3] = sha256_h0[3]; + ctx->h[4] = sha256_h0[4]; ctx->h[5] = sha256_h0[5]; + ctx->h[6] = sha256_h0[6]; ctx->h[7] = sha256_h0[7]; +#endif /* !UNROLL_LOOPS */ + + ctx->len = 0; + ctx->tot_len = 0; +} + +SQLITE_PRIVATE +void sha256_update(sha256_ctx *ctx, const unsigned char *message, + unsigned int len) +{ + unsigned int block_nb; + unsigned int new_len, rem_len, tmp_len; + const unsigned char *shifted_message; + + tmp_len = SHA256_BLOCK_SIZE - ctx->len; + rem_len = len < tmp_len ? len : tmp_len; + + memcpy(&ctx->block[ctx->len], message, rem_len); + + if (ctx->len + len < SHA256_BLOCK_SIZE) { + ctx->len += len; + return; + } + + new_len = len - rem_len; + block_nb = new_len / SHA256_BLOCK_SIZE; + + shifted_message = message + rem_len; + + sha256_transf(ctx, ctx->block, 1); + sha256_transf(ctx, shifted_message, block_nb); + + rem_len = new_len % SHA256_BLOCK_SIZE; + + memcpy(ctx->block, &shifted_message[block_nb << 6], + rem_len); + + ctx->len = rem_len; + ctx->tot_len += (block_nb + 1) << 6; +} + +SQLITE_PRIVATE +void sha256_final(sha256_ctx *ctx, unsigned char *digest) +{ + unsigned int block_nb; + unsigned int pm_len; + unsigned int len_b; + +#ifndef UNROLL_LOOPS + int i; +#endif + + block_nb = (1 + ((SHA256_BLOCK_SIZE - 9) + < (ctx->len % SHA256_BLOCK_SIZE))); + + len_b = (ctx->tot_len + ctx->len) << 3; + pm_len = block_nb << 6; + + memset(ctx->block + ctx->len, 0, pm_len - ctx->len); + ctx->block[ctx->len] = 0x80; + UNPACK32(len_b, ctx->block + pm_len - 4); + + sha256_transf(ctx, ctx->block, block_nb); + +#ifndef UNROLL_LOOPS + for (i = 0 ; i < 8; i++) { + UNPACK32(ctx->h[i], &digest[i << 2]); + } +#else + UNPACK32(ctx->h[0], &digest[ 0]); + UNPACK32(ctx->h[1], &digest[ 4]); + UNPACK32(ctx->h[2], &digest[ 8]); + UNPACK32(ctx->h[3], &digest[12]); + UNPACK32(ctx->h[4], &digest[16]); + UNPACK32(ctx->h[5], &digest[20]); + UNPACK32(ctx->h[6], &digest[24]); + UNPACK32(ctx->h[7], &digest[28]); +#endif /* !UNROLL_LOOPS */ +} + +/* SHA-512 functions */ + +static +void sha512_transf(sha512_ctx *ctx, const unsigned char *message, + unsigned int block_nb) +{ + uint64 w[80]; + uint64 wv[8]; + uint64 t1, t2; + const unsigned char *sub_block; + int i, j; + + for (i = 0; i < (int) block_nb; i++) { + sub_block = message + (i << 7); + +#ifndef UNROLL_LOOPS + for (j = 0; j < 16; j++) { + PACK64(&sub_block[j << 3], &w[j]); + } + + for (j = 16; j < 80; j++) { + SHA512_SCR(j); + } + + for (j = 0; j < 8; j++) { + wv[j] = ctx->h[j]; + } + + for (j = 0; j < 80; j++) { + t1 = wv[7] + SHA512_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) + + sha512_k[j] + w[j]; + t2 = SHA512_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]); + wv[7] = wv[6]; + wv[6] = wv[5]; + wv[5] = wv[4]; + wv[4] = wv[3] + t1; + wv[3] = wv[2]; + wv[2] = wv[1]; + wv[1] = wv[0]; + wv[0] = t1 + t2; + } + + for (j = 0; j < 8; j++) { + ctx->h[j] += wv[j]; + } +#else + PACK64(&sub_block[ 0], &w[ 0]); PACK64(&sub_block[ 8], &w[ 1]); + PACK64(&sub_block[ 16], &w[ 2]); PACK64(&sub_block[ 24], &w[ 3]); + PACK64(&sub_block[ 32], &w[ 4]); PACK64(&sub_block[ 40], &w[ 5]); + PACK64(&sub_block[ 48], &w[ 6]); PACK64(&sub_block[ 56], &w[ 7]); + PACK64(&sub_block[ 64], &w[ 8]); PACK64(&sub_block[ 72], &w[ 9]); + PACK64(&sub_block[ 80], &w[10]); PACK64(&sub_block[ 88], &w[11]); + PACK64(&sub_block[ 96], &w[12]); PACK64(&sub_block[104], &w[13]); + PACK64(&sub_block[112], &w[14]); PACK64(&sub_block[120], &w[15]); + + SHA512_SCR(16); SHA512_SCR(17); SHA512_SCR(18); SHA512_SCR(19); + SHA512_SCR(20); SHA512_SCR(21); SHA512_SCR(22); SHA512_SCR(23); + SHA512_SCR(24); SHA512_SCR(25); SHA512_SCR(26); SHA512_SCR(27); + SHA512_SCR(28); SHA512_SCR(29); SHA512_SCR(30); SHA512_SCR(31); + SHA512_SCR(32); SHA512_SCR(33); SHA512_SCR(34); SHA512_SCR(35); + SHA512_SCR(36); SHA512_SCR(37); SHA512_SCR(38); SHA512_SCR(39); + SHA512_SCR(40); SHA512_SCR(41); SHA512_SCR(42); SHA512_SCR(43); + SHA512_SCR(44); SHA512_SCR(45); SHA512_SCR(46); SHA512_SCR(47); + SHA512_SCR(48); SHA512_SCR(49); SHA512_SCR(50); SHA512_SCR(51); + SHA512_SCR(52); SHA512_SCR(53); SHA512_SCR(54); SHA512_SCR(55); + SHA512_SCR(56); SHA512_SCR(57); SHA512_SCR(58); SHA512_SCR(59); + SHA512_SCR(60); SHA512_SCR(61); SHA512_SCR(62); SHA512_SCR(63); + SHA512_SCR(64); SHA512_SCR(65); SHA512_SCR(66); SHA512_SCR(67); + SHA512_SCR(68); SHA512_SCR(69); SHA512_SCR(70); SHA512_SCR(71); + SHA512_SCR(72); SHA512_SCR(73); SHA512_SCR(74); SHA512_SCR(75); + SHA512_SCR(76); SHA512_SCR(77); SHA512_SCR(78); SHA512_SCR(79); + + wv[0] = ctx->h[0]; wv[1] = ctx->h[1]; + wv[2] = ctx->h[2]; wv[3] = ctx->h[3]; + wv[4] = ctx->h[4]; wv[5] = ctx->h[5]; + wv[6] = ctx->h[6]; wv[7] = ctx->h[7]; + + j = 0; + + do { + SHA512_EXP(0,1,2,3,4,5,6,7,j); j++; + SHA512_EXP(7,0,1,2,3,4,5,6,j); j++; + SHA512_EXP(6,7,0,1,2,3,4,5,j); j++; + SHA512_EXP(5,6,7,0,1,2,3,4,j); j++; + SHA512_EXP(4,5,6,7,0,1,2,3,j); j++; + SHA512_EXP(3,4,5,6,7,0,1,2,j); j++; + SHA512_EXP(2,3,4,5,6,7,0,1,j); j++; + SHA512_EXP(1,2,3,4,5,6,7,0,j); j++; + } while (j < 80); + + ctx->h[0] += wv[0]; ctx->h[1] += wv[1]; + ctx->h[2] += wv[2]; ctx->h[3] += wv[3]; + ctx->h[4] += wv[4]; ctx->h[5] += wv[5]; + ctx->h[6] += wv[6]; ctx->h[7] += wv[7]; +#endif /* !UNROLL_LOOPS */ + } +} + +SQLITE_PRIVATE +void sha512_transform(sha512_ctx *ctx, const unsigned char *message) +{ + sha512_transf(ctx, message, 1); +} + +SQLITE_PRIVATE +void sha512(const unsigned char *message, unsigned int len, + unsigned char *digest) +{ + sha512_ctx ctx; + + sha512_init(&ctx); + sha512_update(&ctx, message, len); + sha512_final(&ctx, digest); +} + +SQLITE_PRIVATE +void sha512_init(sha512_ctx *ctx) +{ +#ifndef UNROLL_LOOPS + int i; + for (i = 0; i < 8; i++) { + ctx->h[i] = sha512_h0[i]; + } +#else + ctx->h[0] = sha512_h0[0]; ctx->h[1] = sha512_h0[1]; + ctx->h[2] = sha512_h0[2]; ctx->h[3] = sha512_h0[3]; + ctx->h[4] = sha512_h0[4]; ctx->h[5] = sha512_h0[5]; + ctx->h[6] = sha512_h0[6]; ctx->h[7] = sha512_h0[7]; +#endif /* !UNROLL_LOOPS */ + + ctx->len = 0; + ctx->tot_len = 0; +} + +SQLITE_PRIVATE +void sha512_update(sha512_ctx *ctx, const unsigned char *message, + unsigned int len) +{ + unsigned int block_nb; + unsigned int new_len, rem_len, tmp_len; + const unsigned char *shifted_message; + + tmp_len = SHA512_BLOCK_SIZE - ctx->len; + rem_len = len < tmp_len ? len : tmp_len; + + memcpy(&ctx->block[ctx->len], message, rem_len); + + if (ctx->len + len < SHA512_BLOCK_SIZE) { + ctx->len += len; + return; + } + + new_len = len - rem_len; + block_nb = new_len / SHA512_BLOCK_SIZE; + + shifted_message = message + rem_len; + + sha512_transf(ctx, ctx->block, 1); + sha512_transf(ctx, shifted_message, block_nb); + + rem_len = new_len % SHA512_BLOCK_SIZE; + + memcpy(ctx->block, &shifted_message[block_nb << 7], + rem_len); + + ctx->len = rem_len; + ctx->tot_len += (block_nb + 1) << 7; +} + +SQLITE_PRIVATE +void sha512_final(sha512_ctx *ctx, unsigned char *digest) +{ + unsigned int block_nb; + unsigned int pm_len; + unsigned int len_b; + +#ifndef UNROLL_LOOPS + int i; +#endif + + block_nb = 1 + ((SHA512_BLOCK_SIZE - 17) + < (ctx->len % SHA512_BLOCK_SIZE)); + + len_b = (ctx->tot_len + ctx->len) << 3; + pm_len = block_nb << 7; + + memset(ctx->block + ctx->len, 0, pm_len - ctx->len); + ctx->block[ctx->len] = 0x80; + UNPACK32(len_b, ctx->block + pm_len - 4); + + sha512_transf(ctx, ctx->block, block_nb); + +#ifndef UNROLL_LOOPS + for (i = 0 ; i < 8; i++) { + UNPACK64(ctx->h[i], &digest[i << 3]); + } +#else + UNPACK64(ctx->h[0], &digest[ 0]); + UNPACK64(ctx->h[1], &digest[ 8]); + UNPACK64(ctx->h[2], &digest[16]); + UNPACK64(ctx->h[3], &digest[24]); + UNPACK64(ctx->h[4], &digest[32]); + UNPACK64(ctx->h[5], &digest[40]); + UNPACK64(ctx->h[6], &digest[48]); + UNPACK64(ctx->h[7], &digest[56]); +#endif /* !UNROLL_LOOPS */ +} + +/* SHA-384 functions */ + +SQLITE_PRIVATE +void sha384(const unsigned char *message, unsigned int len, + unsigned char *digest) +{ + sha384_ctx ctx; + + sha384_init(&ctx); + sha384_update(&ctx, message, len); + sha384_final(&ctx, digest); +} + +SQLITE_PRIVATE +void sha384_init(sha384_ctx *ctx) +{ +#ifndef UNROLL_LOOPS + int i; + for (i = 0; i < 8; i++) { + ctx->h[i] = sha384_h0[i]; + } +#else + ctx->h[0] = sha384_h0[0]; ctx->h[1] = sha384_h0[1]; + ctx->h[2] = sha384_h0[2]; ctx->h[3] = sha384_h0[3]; + ctx->h[4] = sha384_h0[4]; ctx->h[5] = sha384_h0[5]; + ctx->h[6] = sha384_h0[6]; ctx->h[7] = sha384_h0[7]; +#endif /* !UNROLL_LOOPS */ + + ctx->len = 0; + ctx->tot_len = 0; +} + +SQLITE_PRIVATE +void sha384_update(sha384_ctx *ctx, const unsigned char *message, + unsigned int len) +{ + unsigned int block_nb; + unsigned int new_len, rem_len, tmp_len; + const unsigned char *shifted_message; + + tmp_len = SHA384_BLOCK_SIZE - ctx->len; + rem_len = len < tmp_len ? len : tmp_len; + + memcpy(&ctx->block[ctx->len], message, rem_len); + + if (ctx->len + len < SHA384_BLOCK_SIZE) { + ctx->len += len; + return; + } + + new_len = len - rem_len; + block_nb = new_len / SHA384_BLOCK_SIZE; + + shifted_message = message + rem_len; + + sha512_transf(ctx, ctx->block, 1); + sha512_transf(ctx, shifted_message, block_nb); + + rem_len = new_len % SHA384_BLOCK_SIZE; + + memcpy(ctx->block, &shifted_message[block_nb << 7], + rem_len); + + ctx->len = rem_len; + ctx->tot_len += (block_nb + 1) << 7; +} + +SQLITE_PRIVATE +void sha384_final(sha384_ctx *ctx, unsigned char *digest) +{ + unsigned int block_nb; + unsigned int pm_len; + unsigned int len_b; + +#ifndef UNROLL_LOOPS + int i; +#endif + + block_nb = (1 + ((SHA384_BLOCK_SIZE - 17) + < (ctx->len % SHA384_BLOCK_SIZE))); + + len_b = (ctx->tot_len + ctx->len) << 3; + pm_len = block_nb << 7; + + memset(ctx->block + ctx->len, 0, pm_len - ctx->len); + ctx->block[ctx->len] = 0x80; + UNPACK32(len_b, ctx->block + pm_len - 4); + + sha512_transf(ctx, ctx->block, block_nb); + +#ifndef UNROLL_LOOPS + for (i = 0 ; i < 6; i++) { + UNPACK64(ctx->h[i], &digest[i << 3]); + } +#else + UNPACK64(ctx->h[0], &digest[ 0]); + UNPACK64(ctx->h[1], &digest[ 8]); + UNPACK64(ctx->h[2], &digest[16]); + UNPACK64(ctx->h[3], &digest[24]); + UNPACK64(ctx->h[4], &digest[32]); + UNPACK64(ctx->h[5], &digest[40]); +#endif /* !UNROLL_LOOPS */ +} + +/* SHA-224 functions */ + +SQLITE_PRIVATE +void sha224(const unsigned char *message, unsigned int len, + unsigned char *digest) +{ + sha224_ctx ctx; + + sha224_init(&ctx); + sha224_update(&ctx, message, len); + sha224_final(&ctx, digest); +} + +SQLITE_PRIVATE +void sha224_init(sha224_ctx *ctx) +{ +#ifndef UNROLL_LOOPS + int i; + for (i = 0; i < 8; i++) { + ctx->h[i] = sha224_h0[i]; + } +#else + ctx->h[0] = sha224_h0[0]; ctx->h[1] = sha224_h0[1]; + ctx->h[2] = sha224_h0[2]; ctx->h[3] = sha224_h0[3]; + ctx->h[4] = sha224_h0[4]; ctx->h[5] = sha224_h0[5]; + ctx->h[6] = sha224_h0[6]; ctx->h[7] = sha224_h0[7]; +#endif /* !UNROLL_LOOPS */ + + ctx->len = 0; + ctx->tot_len = 0; +} + +SQLITE_PRIVATE +void sha224_update(sha224_ctx *ctx, const unsigned char *message, + unsigned int len) +{ + unsigned int block_nb; + unsigned int new_len, rem_len, tmp_len; + const unsigned char *shifted_message; + + tmp_len = SHA224_BLOCK_SIZE - ctx->len; + rem_len = len < tmp_len ? len : tmp_len; + + memcpy(&ctx->block[ctx->len], message, rem_len); + + if (ctx->len + len < SHA224_BLOCK_SIZE) { + ctx->len += len; + return; + } + + new_len = len - rem_len; + block_nb = new_len / SHA224_BLOCK_SIZE; + + shifted_message = message + rem_len; + + sha256_transf(ctx, ctx->block, 1); + sha256_transf(ctx, shifted_message, block_nb); + + rem_len = new_len % SHA224_BLOCK_SIZE; + + memcpy(ctx->block, &shifted_message[block_nb << 6], + rem_len); + + ctx->len = rem_len; + ctx->tot_len += (block_nb + 1) << 6; +} + +SQLITE_PRIVATE +void sha224_final(sha224_ctx *ctx, unsigned char *digest) +{ + unsigned int block_nb; + unsigned int pm_len; + unsigned int len_b; + +#ifndef UNROLL_LOOPS + int i; +#endif + + block_nb = (1 + ((SHA224_BLOCK_SIZE - 9) + < (ctx->len % SHA224_BLOCK_SIZE))); + + len_b = (ctx->tot_len + ctx->len) << 3; + pm_len = block_nb << 6; + + memset(ctx->block + ctx->len, 0, pm_len - ctx->len); + ctx->block[ctx->len] = 0x80; + UNPACK32(len_b, ctx->block + pm_len - 4); + + sha256_transf(ctx, ctx->block, block_nb); + +#ifndef UNROLL_LOOPS + for (i = 0 ; i < 7; i++) { + UNPACK32(ctx->h[i], &digest[i << 2]); + } +#else + UNPACK32(ctx->h[0], &digest[ 0]); + UNPACK32(ctx->h[1], &digest[ 4]); + UNPACK32(ctx->h[2], &digest[ 8]); + UNPACK32(ctx->h[3], &digest[12]); + UNPACK32(ctx->h[4], &digest[16]); + UNPACK32(ctx->h[5], &digest[20]); + UNPACK32(ctx->h[6], &digest[24]); +#endif /* !UNROLL_LOOPS */ +} + +#ifdef TEST_VECTORS + +/* FIPS 180-2 Validation tests */ + +#include +#include + +void test(const unsigned char *vector, unsigned char *digest, + unsigned int digest_size) +{ + unsigned char output[2 * SHA512_DIGEST_SIZE + 1]; + int i; + + output[2 * digest_size] = '\0'; + + for (i = 0; i < (int) digest_size ; i++) { + sprintf((char *) output + 2 * i, "%02x", digest[i]); + } + + printf("H: %s\n", output); + if (strcmp((char *) vector, (char *) output)) { + fprintf(stderr, "Test failed.\n"); + exit(EXIT_FAILURE); + } +} + +int main() +{ + static const unsigned char *vectors[4][3] = + { /* SHA-224 */ + { + "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", + "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525", + "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67", + }, + /* SHA-256 */ + { + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0", + }, + /* SHA-384 */ + { + "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed" + "8086072ba1e7cc2358baeca134c825a7", + "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712" + "fcc7c71a557e2db966c3e9fa91746039", + "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b" + "07b8b3dc38ecc4ebae97ddd87f3d8985", + }, + /* SHA-512 */ + { + "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" + "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", + "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" + "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909", + "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" + "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b" + } + }; + + static const unsigned char message1[] = "abc"; + static const unsigned char message2a[] = "abcdbcdecdefdefgefghfghighijhi" + "jkijkljklmklmnlmnomnopnopq"; + static const unsigned char message2b[] = + "abcdefghbcdefghicdefghijdefghijkefghij" + "klfghijklmghijklmnhijklmnoijklmnopjklm" + "nopqklmnopqrlmnopqrsmnopqrstnopqrstu"; + unsigned char *message3; + unsigned int message3_len = 1000000; + unsigned char digest[SHA512_DIGEST_SIZE]; + + message3 = malloc(message3_len); + if (message3 == NULL) { + fprintf(stderr, "Can't allocate memory\n"); + return -1; + } + memset(message3, 'a', message3_len); + + printf("SHA-2 FIPS 180-2 Validation tests\n\n"); + printf("SHA-224 Test vectors\n"); + + sha224(message1, strlen((char *) message1), digest); + test(vectors[0][0], digest, SHA224_DIGEST_SIZE); + sha224(message2a, strlen((char *) message2a), digest); + test(vectors[0][1], digest, SHA224_DIGEST_SIZE); + sha224(message3, message3_len, digest); + test(vectors[0][2], digest, SHA224_DIGEST_SIZE); + printf("\n"); + + printf("SHA-256 Test vectors\n"); + + sha256(message1, strlen((char *) message1), digest); + test(vectors[1][0], digest, SHA256_DIGEST_SIZE); + sha256(message2a, strlen((char *) message2a), digest); + test(vectors[1][1], digest, SHA256_DIGEST_SIZE); + sha256(message3, message3_len, digest); + test(vectors[1][2], digest, SHA256_DIGEST_SIZE); + printf("\n"); + + printf("SHA-384 Test vectors\n"); + + sha384(message1, strlen((char *) message1), digest); + test(vectors[2][0], digest, SHA384_DIGEST_SIZE); + sha384(message2b, strlen((char *) message2b), digest); + test(vectors[2][1], digest, SHA384_DIGEST_SIZE); + sha384(message3, message3_len, digest); + test(vectors[2][2], digest, SHA384_DIGEST_SIZE); + printf("\n"); + + printf("SHA-512 Test vectors\n"); + + sha512(message1, strlen((char *) message1), digest); + test(vectors[3][0], digest, SHA512_DIGEST_SIZE); + sha512(message2b, strlen((char *) message2b), digest); + test(vectors[3][1], digest, SHA512_DIGEST_SIZE); + sha512(message3, message3_len, digest); + test(vectors[3][2], digest, SHA512_DIGEST_SIZE); + printf("\n"); + + printf("All tests passed.\n"); + + return 0; +} + +#endif /* TEST_VECTORS */ +/*** End of #include "sha2.c" ***/ + + +#if HAVE_CIPHER_CHACHA20 || HAVE_CIPHER_SQLCIPHER || HAVE_CIPHER_ASCON128 || HAVE_CIPHER_AEGIS +/* #include "fastpbkdf2.c" */ +/*** Begin of #include "fastpbkdf2.c" ***/ +/* + * fast-pbkdf2 - Optimal PBKDF2-HMAC calculation + * Written in 2015 by Joseph Birr-Pixton + * + * To the extent possible under law, the author(s) have dedicated all + * copyright and related and neighboring rights to this software to the + * public domain worldwide. This software is distributed without any + * warranty. + * + * You should have received a copy of the CC0 Public Domain Dedication + * along with this software. If not, see + * . + */ + +/* #include "fastpbkdf2.h" */ +/*** Begin of #include "fastpbkdf2.h" ***/ +/* + * fastpbkdf2 - Faster PBKDF2-HMAC calculation + * Written in 2015 by Joseph Birr-Pixton + * + * To the extent possible under law, the author(s) have dedicated all + * copyright and related and neighboring rights to this software to the + * public domain worldwide. This software is distributed without any + * warranty. + * + * You should have received a copy of the CC0 Public Domain Dedication + * along with this software. If not, see + * . + */ + +#ifndef FASTPBKDF2_H +#define FASTPBKDF2_H + +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE +#endif + +#include +/* #include "mystdint.h" */ + + +#ifdef __cplusplus +extern "C" { +#endif + +/** Calculates PBKDF2-HMAC-SHA1. + * + * @p npw bytes at @p pw are the password input. + * @p nsalt bytes at @p salt are the salt input. + * @p iterations is the PBKDF2 iteration count and must be non-zero. + * @p nout bytes of output are written to @p out. @p nout must be non-zero. + * + * This function cannot fail; it does not report errors. + */ +SQLITE_PRIVATE +void fastpbkdf2_hmac_sha1(const uint8_t *pw, size_t npw, + const uint8_t *salt, size_t nsalt, + uint32_t iterations, + uint8_t *out, size_t nout); + +/** Calculates PBKDF2-HMAC-SHA256. + * + * @p npw bytes at @p pw are the password input. + * @p nsalt bytes at @p salt are the salt input. + * @p iterations is the PBKDF2 iteration count and must be non-zero. + * @p nout bytes of output are written to @p out. @p nout must be non-zero. + * + * This function cannot fail; it does not report errors. + */ +SQLITE_PRIVATE +void fastpbkdf2_hmac_sha256(const uint8_t *pw, size_t npw, + const uint8_t *salt, size_t nsalt, + uint32_t iterations, + uint8_t *out, size_t nout); + +/** Calculates PBKDF2-HMAC-SHA512. + * + * @p npw bytes at @p pw are the password input. + * @p nsalt bytes at @p salt are the salt input. + * @p iterations is the PBKDF2 iteration count and must be non-zero. + * @p nout bytes of output are written to @p out. @p nout must be non-zero. + * + * This function cannot fail; it does not report errors. + */ +SQLITE_PRIVATE +void fastpbkdf2_hmac_sha512(const uint8_t *pw, size_t npw, + const uint8_t *salt, size_t nsalt, + uint32_t iterations, + uint8_t *out, size_t nout); + +/** Calculates SQLCipher HMAC. + * + * This function cannot fail; it does not report errors. + */ +SQLITE_PRIVATE +void sqlcipher_hmac(int algorithm, + unsigned char* key, int nkey, + unsigned char* in, int in_sz, + unsigned char* in2, int in2_sz, + unsigned char* out); + +#ifdef __cplusplus +} +#endif + +#endif +/*** End of #include "fastpbkdf2.h" ***/ + + +#include +#include + +/* #include "sha1.h" */ + +/* #include "sha2.h" */ + + +/* --- MSVC doesn't support C99 --- */ +#if defined(_MSC_VER) && !defined(__clang__) +#define restrict +#define inline __inline +#define _Pragma __pragma +#endif + +/* --- Common useful things --- */ +#ifndef MIN +#define MIN(a, b) ((a) > (b)) ? (b) : (a) +#endif + +static inline void write32_be(uint32_t n, uint8_t out[4]) +{ +#if SQLITE_BYTEORDER==4321 + memcpy(out, &n, 4); +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + u32 x = __builtin_bswap32(n); + memcpy(out, &x, 4); +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + u32 x = _byteswap_ulong(n); + memcpy(out, &x, 4); +#else + out[0] = (n >> 24) & 0xFF; + out[1] = (n >> 16) & 0xFF; + out[2] = (n >> 8) & 0xFF; + out[3] = (n >> 0) & 0xFF; +#endif +} + +static inline void write64_be(uint64_t n, uint8_t out[8]) +{ +#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + n = __builtin_bswap64(n); + memcpy(out, &n, 8); +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + n = _byteswap_uint64(n); + memcpy(out, &n, 8); +#elif SQLITE_BYTEORDER==4321 + memcpy(out, &n, 8); +#else + out[0] = (n >> 56) & 0xFF; + out[1] = (n >> 48) & 0xFF; + out[2] = (n >> 40) & 0xFF; + out[3] = (n >> 32) & 0xFF; + out[4] = (n >> 24) & 0xFF; + out[5] = (n >> 16) & 0xFF; + out[6] = (n >> 8) & 0xFF; + out[7] = (n >> 0) & 0xFF; +#endif +} + +/* --- Optional OpenMP parallelisation of consecutive blocks --- */ +#ifdef WITH_OPENMP +# define OPENMP_PARALLEL_FOR _Pragma("omp parallel for") +#else +# define OPENMP_PARALLEL_FOR +#endif + +/* Prepare block (of blocksz bytes) to contain md padding denoting a msg-size + * message (in bytes). block has a prefix of used bytes. + * + * Message length is expressed in 32 bits (so suitable for sha1, sha256, sha512). */ +static inline void md_pad(uint8_t *block, size_t blocksz, size_t used, size_t msg) +{ + memset(block + used, 0, blocksz - used - 4); + block[used] = 0x80; + block += blocksz - 4; + write32_be((uint32_t) (msg * 8), block); +} + +/* Internal function/type names for hash-specific things. */ +#define HMAC_CTX(_name) HMAC_ ## _name ## _ctx +#define HMAC_INIT(_name) HMAC_ ## _name ## _init +#define HMAC_UPDATE(_name) HMAC_ ## _name ## _update +#define HMAC_FINAL(_name) HMAC_ ## _name ## _final + +#define PBKDF2_F(_name) pbkdf2_f_ ## _name +#define PBKDF2(_name) pbkdf2_ ## _name + +/* This macro expands to decls for the whole implementation for a given + * hash function. Arguments are: + * + * _name like 'sha1', added to symbol names + * _blocksz block size, in bytes + * _hashsz digest output, in bytes + * _ctx hash context type + * _init hash context initialisation function + * args: (_ctx *c) + * _update hash context update function + * args: (_ctx *c, const void *data, size_t ndata) + * _final hash context finish function + * args: (void *out, _ctx *c) + * _xform hash context raw block update function + * args: (_ctx *c, const void *data) + * _xcpy hash context raw copy function (only need copy hash state) + * args: (_ctx * restrict out, const _ctx *restrict in) + * _xtract hash context state extraction + * args: args (_ctx *restrict c, uint8_t *restrict out) + * _xxor hash context xor function (only need xor hash state) + * args: (_ctx *restrict out, const _ctx *restrict in) + * + * The resulting function is named PBKDF2(_name). + */ +#define DECL_PBKDF2(_name, _blocksz, _hashsz, _ctx, \ + _init, _update, _xform, _final, _xcpy, _xtract, _xxor) \ + typedef struct { \ + _ctx inner; \ + _ctx outer; \ + } HMAC_CTX(_name); \ + \ + static inline void HMAC_INIT(_name)(HMAC_CTX(_name) *ctx, \ + const uint8_t *key, size_t nkey) \ + { \ + /* Prepare key: */ \ + uint8_t k[_blocksz]; \ + \ + /* Shorten long keys. */ \ + if (nkey > _blocksz) \ + { \ + _init(&ctx->inner); \ + _update(&ctx->inner, key, (unsigned int) nkey); \ + _final(&ctx->inner, k); \ + \ + key = k; \ + nkey = _hashsz; \ + } \ + \ + /* Standard doesn't cover case where blocksz < hashsz. */ \ + assert(nkey <= _blocksz); \ + \ + /* Right zero-pad short keys. */ \ + if (k != key) \ + memcpy(k, key, nkey); \ + if (_blocksz > nkey) \ + memset(k + nkey, 0, _blocksz - nkey); \ + \ + { \ + /* Start inner hash computation */ \ + uint8_t blk_inner[_blocksz]; \ + uint8_t blk_outer[_blocksz]; \ + size_t i; \ + \ + for (i = 0; i < _blocksz; i++) \ + { \ + blk_inner[i] = 0x36 ^ k[i]; \ + blk_outer[i] = 0x5c ^ k[i]; \ + } \ + \ + _init(&ctx->inner); \ + _update(&ctx->inner, blk_inner, sizeof blk_inner); \ + \ + /* And outer. */ \ + _init(&ctx->outer); \ + _update(&ctx->outer, blk_outer, sizeof blk_outer); \ + } \ + } \ + \ + static inline void HMAC_UPDATE(_name)(HMAC_CTX(_name) *ctx, \ + const void *data, size_t ndata) \ + { \ + _update(&ctx->inner, data, (unsigned int) ndata); \ + } \ + \ + static inline void HMAC_FINAL(_name)(HMAC_CTX(_name) *ctx, \ + uint8_t out[_hashsz]) \ + { \ + _final(&ctx->inner, out); \ + _update(&ctx->outer, out, _hashsz); \ + _final(&ctx->outer, out); \ + } \ + \ + \ + /* --- PBKDF2 --- */ \ + static inline void PBKDF2_F(_name)(const HMAC_CTX(_name) *startctx, \ + uint32_t counter, \ + const uint8_t *salt, size_t nsalt, \ + uint32_t iterations, \ + uint8_t *out) \ + { \ + uint8_t countbuf[4]; \ + uint8_t Ublock[_blocksz]; \ + HMAC_CTX(_name) ctx; \ + uint32_t i; \ + _ctx result; \ + \ + write32_be(counter, countbuf); \ + \ + /* Prepare loop-invariant padding block. */ \ + md_pad(Ublock, _blocksz, _hashsz, _blocksz + _hashsz); \ + \ + /* First iteration: \ + * U_1 = PRF(P, S || INT_32_BE(i)) \ + */ \ + ctx = *startctx; \ + HMAC_UPDATE(_name)(&ctx, salt, nsalt); \ + HMAC_UPDATE(_name)(&ctx, countbuf, sizeof countbuf); \ + HMAC_FINAL(_name)(&ctx, Ublock); \ + result = ctx.outer; \ + \ + /* Subsequent iterations: \ + * U_c = PRF(P, U_{c-1}) \ + */ \ + for (i = 1; i < iterations; i++) \ + { \ + /* Complete inner hash with previous U */ \ + _xcpy(&ctx.inner, &startctx->inner); \ + _xform(&ctx.inner, Ublock); \ + _xtract(&ctx.inner, Ublock); \ + /* Complete outer hash with inner output */ \ + _xcpy(&ctx.outer, &startctx->outer); \ + _xform(&ctx.outer, Ublock); \ + _xtract(&ctx.outer, Ublock); \ + _xxor(&result, &ctx.outer); \ + } \ + \ + /* Reform result into output buffer. */ \ + _xtract(&result, out); \ + } \ + \ + static inline void PBKDF2(_name)(const uint8_t *pw, size_t npw, \ + const uint8_t *salt, size_t nsalt, \ + uint32_t iterations, \ + uint8_t *out, size_t nout) \ + { \ + HMAC_CTX(_name) ctx; \ + uint32_t blocks_needed; \ + uint32_t counter; \ + assert(iterations); \ + assert(out && nout); \ + \ + /* Starting point for inner loop. */ \ + HMAC_INIT(_name)(&ctx, pw, npw); \ + \ + /* How many blocks do we need? */ \ + blocks_needed = (uint32_t)(nout + _hashsz - 1) / _hashsz; \ + \ + OPENMP_PARALLEL_FOR \ + for (counter = 1; counter <= blocks_needed; counter++) \ + { \ + uint8_t block[_hashsz]; \ + size_t offset; \ + size_t taken; \ + PBKDF2_F(_name)(&ctx, counter, salt, nsalt, iterations, block); \ + \ + offset = (counter - 1) * _hashsz; \ + taken = MIN(nout - offset, _hashsz); \ + memcpy(out + offset, block, taken); \ + } \ + } + +static inline void sha1_extract(sha1_ctx *restrict ctx, uint8_t *restrict out) +{ + write32_be(ctx->h[0], out); + write32_be(ctx->h[1], out + 4); + write32_be(ctx->h[2], out + 8); + write32_be(ctx->h[3], out + 12); + write32_be(ctx->h[4], out + 16); +} + +static inline void sha1_cpy(sha1_ctx *restrict out, const sha1_ctx *restrict in) +{ + out->h[0] = in->h[0]; + out->h[1] = in->h[1]; + out->h[2] = in->h[2]; + out->h[3] = in->h[3]; + out->h[4] = in->h[4]; +} + +static inline void sha1_xor(sha1_ctx *restrict out, const sha1_ctx *restrict in) +{ + out->h[0] ^= in->h[0]; + out->h[1] ^= in->h[1]; + out->h[2] ^= in->h[2]; + out->h[3] ^= in->h[3]; + out->h[4] ^= in->h[4]; +} + +DECL_PBKDF2(sha1, + SHA1_BLOCK_SIZE, + SHA1_DIGEST_SIZE, + sha1_ctx, + sha1_init, + sha1_update, + sha1_transform, + sha1_final, + sha1_cpy, + sha1_extract, + sha1_xor) + +static inline void sha256_extract(sha256_ctx *restrict ctx, uint8_t *restrict out) +{ + write32_be(ctx->h[0], out); + write32_be(ctx->h[1], out + 4); + write32_be(ctx->h[2], out + 8); + write32_be(ctx->h[3], out + 12); + write32_be(ctx->h[4], out + 16); + write32_be(ctx->h[5], out + 20); + write32_be(ctx->h[6], out + 24); + write32_be(ctx->h[7], out + 28); +} + +static inline void sha256_cpy(sha256_ctx *restrict out, const sha256_ctx *restrict in) +{ + out->h[0] = in->h[0]; + out->h[1] = in->h[1]; + out->h[2] = in->h[2]; + out->h[3] = in->h[3]; + out->h[4] = in->h[4]; + out->h[5] = in->h[5]; + out->h[6] = in->h[6]; + out->h[7] = in->h[7]; +} + +static inline void sha256_xor(sha256_ctx *restrict out, const sha256_ctx *restrict in) +{ + out->h[0] ^= in->h[0]; + out->h[1] ^= in->h[1]; + out->h[2] ^= in->h[2]; + out->h[3] ^= in->h[3]; + out->h[4] ^= in->h[4]; + out->h[5] ^= in->h[5]; + out->h[6] ^= in->h[6]; + out->h[7] ^= in->h[7]; +} + +DECL_PBKDF2(sha256, + SHA256_BLOCK_SIZE, + SHA256_DIGEST_SIZE, + sha256_ctx, + sha256_init, + sha256_update, + sha256_transform, + sha256_final, + sha256_cpy, + sha256_extract, + sha256_xor) + +static inline void sha512_extract(sha512_ctx *restrict ctx, uint8_t *restrict out) +{ + write64_be(ctx->h[0], out); + write64_be(ctx->h[1], out + 8); + write64_be(ctx->h[2], out + 16); + write64_be(ctx->h[3], out + 24); + write64_be(ctx->h[4], out + 32); + write64_be(ctx->h[5], out + 40); + write64_be(ctx->h[6], out + 48); + write64_be(ctx->h[7], out + 56); +} + +static inline void sha512_cpy(sha512_ctx *restrict out, const sha512_ctx *restrict in) +{ + out->h[0] = in->h[0]; + out->h[1] = in->h[1]; + out->h[2] = in->h[2]; + out->h[3] = in->h[3]; + out->h[4] = in->h[4]; + out->h[5] = in->h[5]; + out->h[6] = in->h[6]; + out->h[7] = in->h[7]; +} + +static inline void sha512_xor(sha512_ctx *restrict out, const sha512_ctx *restrict in) +{ + out->h[0] ^= in->h[0]; + out->h[1] ^= in->h[1]; + out->h[2] ^= in->h[2]; + out->h[3] ^= in->h[3]; + out->h[4] ^= in->h[4]; + out->h[5] ^= in->h[5]; + out->h[6] ^= in->h[6]; + out->h[7] ^= in->h[7]; +} + +DECL_PBKDF2(sha512, + SHA512_BLOCK_SIZE, + SHA512_DIGEST_SIZE, + sha512_ctx, + sha512_init, + sha512_update, + sha512_transform, + sha512_final, + sha512_cpy, + sha512_extract, + sha512_xor) + +SQLITE_PRIVATE +void fastpbkdf2_hmac_sha1(const uint8_t *pw, size_t npw, + const uint8_t *salt, size_t nsalt, + uint32_t iterations, + uint8_t *out, size_t nout) +{ + PBKDF2(sha1)(pw, npw, salt, nsalt, iterations, out, nout); +#if 0 + pbkdf2_sha1(pw, npw, salt, nsalt, iterations, out, nout); +#endif +} + +SQLITE_PRIVATE +void fastpbkdf2_hmac_sha256(const uint8_t *pw, size_t npw, + const uint8_t *salt, size_t nsalt, + uint32_t iterations, + uint8_t *out, size_t nout) +{ + PBKDF2(sha256)(pw, npw, salt, nsalt, iterations, out, nout); +} + +SQLITE_PRIVATE +void fastpbkdf2_hmac_sha512(const uint8_t *pw, size_t npw, + const uint8_t *salt, size_t nsalt, + uint32_t iterations, + uint8_t *out, size_t nout) +{ + PBKDF2(sha512)(pw, npw, salt, nsalt, iterations, out, nout); +} + +SQLITE_PRIVATE +void sqlcipher_hmac(int algorithm, unsigned char* key, int nkey, unsigned char* in, int in_sz, unsigned char* in2, int in2_sz, unsigned char* out) +{ + switch (algorithm) + { + case 0: + { + HMAC_sha1_ctx hctx; + HMAC_sha1_init(&hctx, key, nkey); + HMAC_sha1_update(&hctx, in, in_sz); + if (in2 != NULL) + { + HMAC_sha1_update(&hctx, in2, in2_sz); + } + HMAC_sha1_final(&hctx, out); + } + break; + + case 1: + { + HMAC_sha256_ctx hctx; + HMAC_sha256_init(&hctx, key, nkey); + HMAC_sha256_update(&hctx, in, in_sz); + if (in2 != NULL) + { + HMAC_sha256_update(&hctx, in2, in2_sz); + } + HMAC_sha256_final(&hctx, out); + } + break; + + case 2: + default: + { + HMAC_sha512_ctx hctx; + HMAC_sha512_init(&hctx, key, nkey); + HMAC_sha512_update(&hctx, in, in_sz); + if (in2 != NULL) + { + HMAC_sha512_update(&hctx, in2, in2_sz); + } + HMAC_sha512_final(&hctx, out); + } + break; + } +} +/*** End of #include "fastpbkdf2.c" ***/ + + +/* Prototypes for several crypto functions to make pedantic compilers happy */ +SQLITE_PRIVATE void chacha20_xor(void* data, size_t n, const uint8_t key[32], const uint8_t nonce[12], uint32_t counter); +SQLITE_PRIVATE void poly1305(const uint8_t* msg, size_t n, const uint8_t key[32], uint8_t tag[16]); +SQLITE_PRIVATE int poly1305_tagcmp(const uint8_t tag1[16], const uint8_t tag2[16]); +SQLITE_PRIVATE void chacha20_rng(void* out, size_t n); + +/* #include "chacha20poly1305.c" */ +/*** Begin of #include "chacha20poly1305.c" ***/ +/* +** This file contains the implementation for +** - the ChaCha20 cipher +** - the Poly1305 message digest +** +** The code was taken from the public domain implementation +** of the sqleet project (https://github.com/resilar/sqleet) +*/ + +/* #include "mystdint.h" */ + +#include + +#define ROL32(x, c) (((x) << (c)) | ((x) >> (32-(c)))) +#define ROR32(x, c) (((x) >> (c)) | ((x) << (32-(c)))) + +#define LOAD32_LE(p) \ + ( ((uint32_t)((p)[0]) << 0) \ + | ((uint32_t)((p)[1]) << 8) \ + | ((uint32_t)((p)[2]) << 16) \ + | ((uint32_t)((p)[3]) << 24) \ + ) +#define LOAD32_BE(p) \ + ( ((uint32_t)((p)[3]) << 0) \ + | ((uint32_t)((p)[2]) << 8) \ + | ((uint32_t)((p)[1]) << 16) \ + | ((uint32_t)((p)[0]) << 24) \ + ) + +#define STORE32_LE(p, v) \ + (p)[0] = ((v) >> 0) & 0xFF; \ + (p)[1] = ((v) >> 8) & 0xFF; \ + (p)[2] = ((v) >> 16) & 0xFF; \ + (p)[3] = ((v) >> 24) & 0xFF; +#define STORE32_BE(p, v) \ + (p)[3] = ((v) >> 0) & 0xFF; \ + (p)[2] = ((v) >> 8) & 0xFF; \ + (p)[1] = ((v) >> 16) & 0xFF; \ + (p)[0] = ((v) >> 24) & 0xFF; +#define STORE64_BE(p, v) \ + (p)[7] = ((v) >> 0) & 0xFF; \ + (p)[6] = ((v) >> 8) & 0xFF; \ + (p)[5] = ((v) >> 16) & 0xFF; \ + (p)[4] = ((v) >> 24) & 0xFF; \ + (p)[3] = ((v) >> 32) & 0xFF; \ + (p)[2] = ((v) >> 40) & 0xFF; \ + (p)[1] = ((v) >> 48) & 0xFF; \ + (p)[0] = ((v) >> 56) & 0xFF; + +/* + * ChaCha20 stream cipher + */ +static void chacha20_block(uint32_t x[16]) +{ + int i; + /* Macro renamed from QR to CC20QR to avoid name clashes. */ + #define CC20QR(x, a, b, c, d) \ + x[a] += x[b]; x[d] ^= x[a]; x[d] = ROL32(x[d], 16); \ + x[c] += x[d]; x[b] ^= x[c]; x[b] = ROL32(x[b], 12); \ + x[a] += x[b]; x[d] ^= x[a]; x[d] = ROL32(x[d], 8); \ + x[c] += x[d]; x[b] ^= x[c]; x[b] = ROL32(x[b], 7); + for (i = 0; i < 10; i++) + { + /* Column round */ + CC20QR(x, 0, 4, 8, 12) + CC20QR(x, 1, 5, 9, 13) + CC20QR(x, 2, 6, 10, 14) + CC20QR(x, 3, 7, 11, 15) + /* Diagonal round */ + CC20QR(x, 0, 5, 10, 15) + CC20QR(x, 1, 6, 11, 12) + CC20QR(x, 2, 7, 8, 13) + CC20QR(x, 3, 4, 9, 14) + } + #undef CC20QR +} + +SQLITE_PRIVATE +void chacha20_xor(void* buffer, size_t n, const uint8_t key[32], + const uint8_t nonce[12], uint32_t counter) +{ + size_t i; + union { + uint8_t bytes[64]; + uint32_t words[16]; + } block; + uint32_t state[16]; + uint8_t* buf = buffer; + + state[ 0] = 0x61707865; /* 'expa' */ + state[ 1] = 0x3320646e; /* 'nd 3' */ + state[ 2] = 0x79622d32; /* '2-by' */ + state[ 3] = 0x6b206574; /* 'te k' */ + + state[ 4] = LOAD32_LE(key + 0); + state[ 5] = LOAD32_LE(key + 4); + state[ 6] = LOAD32_LE(key + 8); + state[ 7] = LOAD32_LE(key + 12); + state[ 8] = LOAD32_LE(key + 16); + state[ 9] = LOAD32_LE(key + 20); + state[10] = LOAD32_LE(key + 24); + state[11] = LOAD32_LE(key + 28); + + state[12] = counter; + state[13] = LOAD32_LE(nonce + 0); + state[14] = LOAD32_LE(nonce + 4); + state[15] = LOAD32_LE(nonce + 8); + + while (n > 64) + { + for (i = 0; i < 16; ++i) + { + block.words[i] = state[i]; + } + chacha20_block(block.words); + for (i = 0; i < 16; ++i) + { + block.words[i] += state[i]; + block.words[i] ^= LOAD32_LE(buf); + STORE32_LE(buf, block.words[i]); + buf += 4; + } + ++state[12]; + n -= 64; + } + + for (i = 0; i < 16; ++i) + { + block.words[i] = state[i]; + } + chacha20_block(state); + for (i = 0; i < 16; ++i) + { + state[i] += block.words[i]; + STORE32_LE(&block.bytes[4*i], state[i]); + } + for (i = 0; i < n; i++) + { + buf[i] ^= block.bytes[i]; + } +} + +/* + * Poly1305 authentication tags + */ +SQLITE_PRIVATE +void poly1305(const uint8_t* msg, size_t n, const uint8_t key[32], + uint8_t tag[16]) +{ + uint64_t d0, d1, d2, d3, d4; + uint32_t h0, h1, h2, h3, h4; + uint32_t r0, r1, r2, r3, r4; + uint32_t s1, s2, s3, s4; + + h0 = h1 = h2 = h3 = h4 = 0; + r0 = (LOAD32_LE(key + 0) >> 0) & 0x03FFFFFF; + r1 = (LOAD32_LE(key + 3) >> 2) & 0x03FFFF03; s1 = r1 * 5; + r2 = (LOAD32_LE(key + 6) >> 4) & 0x03FFC0FF; s2 = r2 * 5; + r3 = (LOAD32_LE(key + 9) >> 6) & 0x03F03FFF; s3 = r3 * 5; + r4 = (LOAD32_LE(key + 12) >> 8) & 0x000FFFFF; s4 = r4 * 5; + while (n >= 16) + { + h4 += 0x01000000; +process_block: + h0 += (LOAD32_LE(msg + 0) >> 0) & 0x03FFFFFF; + h1 += (LOAD32_LE(msg + 3) >> 2) & 0x03FFFFFF; + h2 += (LOAD32_LE(msg + 6) >> 4) & 0x03FFFFFF; + h3 += (LOAD32_LE(msg + 9) >> 6) & 0x03FFFFFF; + h4 += (LOAD32_LE(msg + 12) >> 8); + + #define MUL(a,b) ((uint64_t)(a) * (b)) + d0 = MUL(h0,r0) + MUL(h1,s4) + MUL(h2,s3) + MUL(h3,s2) + MUL(h4,s1); + d1 = MUL(h0,r1) + MUL(h1,r0) + MUL(h2,s4) + MUL(h3,s3) + MUL(h4,s2); + d2 = MUL(h0,r2) + MUL(h1,r1) + MUL(h2,r0) + MUL(h3,s4) + MUL(h4,s3); + d3 = MUL(h0,r3) + MUL(h1,r2) + MUL(h2,r1) + MUL(h3,r0) + MUL(h4,s4); + d4 = MUL(h0,r4) + MUL(h1,r3) + MUL(h2,r2) + MUL(h3,r1) + MUL(h4,r0); + #undef MUL + + h0 = d0 & 0x03FFFFFF; d1 += (d0 >> 26); + h1 = d1 & 0x03FFFFFF; d2 += (d1 >> 26); + h2 = d2 & 0x03FFFFFF; d3 += (d2 >> 26); + h3 = d3 & 0x03FFFFFF; d4 += (d3 >> 26); + h4 = d4 & 0x03FFFFFF; h0 += (uint32_t)(d4 >> 26) * 5; + + msg += 16; + n -= 16; + } + if (n) + { + size_t i; + for (i = 0; i < n; tag[i] = msg[i], i++); + for (tag[i++] = 1; i < 16; tag[i++] = 0); + msg = tag; + n = 16; + goto process_block; + } + + r0 = (h0 + 5) >> 26; + r1 = (h1 + r0) >> 26; + r2 = (h2 + r1) >> 26; + r3 = (h3 + r2) >> 26; + r4 = (h4 + r3) >> 26; + h0 += r4 * 5; + + d1 = (uint64_t)LOAD32_LE(key + 16) + (h0 >> 0) + (h1 << 26); + d2 = (uint64_t)LOAD32_LE(key + 20) + (h1 >> 6) + (h2 << 20) + (d1 >> 32); + d3 = (uint64_t)LOAD32_LE(key + 24) + (h2 >> 12) + (h3 << 14) + (d2 >> 32); + d4 = (uint64_t)LOAD32_LE(key + 28) + (h3 >> 18) + (h4 << 8) + (d3 >> 32); + + s1 = d1; STORE32_LE(tag + 0, s1); + s2 = d2; STORE32_LE(tag + 4, s2); + s3 = d3; STORE32_LE(tag + 8, s3); + s4 = d4; STORE32_LE(tag + 12, s4); +} + +SQLITE_PRIVATE +int poly1305_tagcmp(const uint8_t tag1[16], const uint8_t tag2[16]) +{ + uint8_t d = 0; + d |= tag1[ 0] ^ tag2[ 0]; + d |= tag1[ 1] ^ tag2[ 1]; + d |= tag1[ 2] ^ tag2[ 2]; + d |= tag1[ 3] ^ tag2[ 3]; + d |= tag1[ 4] ^ tag2[ 4]; + d |= tag1[ 5] ^ tag2[ 5]; + d |= tag1[ 6] ^ tag2[ 6]; + d |= tag1[ 7] ^ tag2[ 7]; + d |= tag1[ 8] ^ tag2[ 8]; + d |= tag1[ 9] ^ tag2[ 9]; + d |= tag1[10] ^ tag2[10]; + d |= tag1[11] ^ tag2[11]; + d |= tag1[12] ^ tag2[12]; + d |= tag1[13] ^ tag2[13]; + d |= tag1[14] ^ tag2[14]; + d |= tag1[15] ^ tag2[15]; + return (int) d; +} + +/* + * Platform-specific entropy functions for seeding RNG + */ +#if defined(__WASM__) + +extern int getentropy(void* buf, size_t n); + +static size_t entropy(void* buf, size_t n) +{ + return (getentropy(buf, n) == 0) ? n : 0; +} + +#elif defined(_WIN32) || defined(__CYGWIN__) + +#if SQLITE3MC_USE_RAND_S + +/* Force header stdlib.h to define rand_s() */ +#if !defined(_CRT_RAND_S) +#define _CRT_RAND_S +#endif +#include + +/* + Provide declaration of rand_s() for MinGW-32 (not 64). + MinGW-32 didn't declare it prior to version 5.3.0. +*/ +#if defined(__MINGW32__) && defined(__MINGW32_VERSION) && __MINGW32_VERSION < 5003000L && !defined(__MINGW64_VERSION_MAJOR) +__declspec(dllimport) int rand_s(unsigned int *); +#endif + +static size_t entropy(void* buf, size_t n) +{ + size_t totalBytes = 0; + while (totalBytes < n) + { + unsigned int random32 = 0; + size_t j = 0; + + if (rand_s(&random32)) + { + /* rand_s failed */ + return 0; + } + + for (; (j < sizeof(random32)) && (totalBytes < n); j++, totalBytes++) + { + const uint8_t random8 = (uint8_t)(random32 >> (j * 8)); + ((uint8_t*) buf)[totalBytes] = random8; + } + } + return n; +} + +#else + +#include +#define RtlGenRandom SystemFunction036 +BOOLEAN NTAPI RtlGenRandom(PVOID RandomBuffer, ULONG RandomBufferLength); +#pragma comment(lib, "advapi32.lib") +static size_t entropy(void* buf, size_t n) +{ + return RtlGenRandom(buf, (ULONG) n) ? n : 0; +} + +#endif + +#elif defined(__linux__) || defined(__unix__) || defined(__APPLE__) || defined(__QNX__) + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#include +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +/* musl does not have so let's define RNDGETENTCNT here */ +#ifndef RNDGETENTCNT +#define RNDGETENTCNT _IOR('R', 0x00, int) +#endif +#endif + +/* Returns the number of urandom bytes read (either 0 or n) */ +static size_t read_urandom(void* buf, size_t n) +{ + size_t i; + ssize_t ret; + int fd, count; + struct stat st; + int errnold = errno; + + do + { + fd = open("/dev/urandom", O_RDONLY, 0); + } + while (fd == -1 && errno == EINTR); + if (fd == -1) + goto fail; + fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); + + /* Check the sanity of the device node */ + if (fstat(fd, &st) == -1 || !S_ISCHR(st.st_mode) + #ifdef __linux__ + || ioctl(fd, RNDGETENTCNT, &count) == -1 + #endif + ) + { + close(fd); + goto fail; + } + + /* Read bytes */ + for (i = 0; i < n; i += ret) + { + while ((ret = read(fd, (char *)buf + i, n - i)) == -1) + { + if (errno != EAGAIN && errno != EINTR) + { + close(fd); + goto fail; + } + } + } + close(fd); + + /* Verify that the random device returned non-zero data */ + for (i = 0; i < n; i++) + { + if (((uint8_t*) buf)[i] != 0) + { + errno = errnold; + return n; + } + } + + /* Tiny n may unintentionally fall through! */ +fail: + fprintf(stderr, "bad /dev/urandom RNG\n"); + abort(); /* PANIC! */ + return 0; +} + +#if defined(__APPLE__) +#include +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 +#include +#endif +#endif + +static size_t entropy(void* buf, size_t n) +{ +#if defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 + if (SecRandomCopyBytes(kSecRandomDefault, n, (uint8_t*) buf) == 0) + return n; +#elif defined(__linux__) && defined(SYS_getrandom) + if (syscall(SYS_getrandom, buf, n, 0) == n) + return n; +#elif defined(SYS_getentropy) + if (syscall(SYS_getentropy, buf, n) == 0) + return n; +#endif + return read_urandom(buf, n); +} + +#else +# error "Secure pseudorandom number generator not implemented for this OS" +#endif + +/* + * ChaCha20 random number generator + */ +SQLITE_PRIVATE +void chacha20_rng(void* out, size_t n) +{ + static uint8_t key[32], nonce[12], buffer[64] = { 0 }; + static uint32_t counter = 0; + static size_t available = 0; + +#if SQLITE_THREADSAFE + sqlite3_mutex* mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG); + sqlite3_mutex_enter(mutex); +#endif + + while (n > 0) + { + size_t m; + if (available == 0) + { + if (counter == 0) + { + if (entropy(key, sizeof(key)) != sizeof(key)) + abort(); + if (entropy(nonce, sizeof(nonce)) != sizeof(nonce)) + abort(); + } + chacha20_xor(buffer, sizeof(buffer), key, nonce, counter++); + available = sizeof(buffer); + } + m = (available < n) ? available : n; + memcpy(out, buffer + (sizeof(buffer) - available), m); + out = (uint8_t*)out + m; + available -= m; + n -= m; + } + +#if SQLITE_THREADSAFE + sqlite3_mutex_leave(mutex); +#endif +} +/*** End of #include "chacha20poly1305.c" ***/ + +#endif + +/* +** Declare function prototype for registering the codec extension functions +*/ +static int +mcRegisterCodecExtensions(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); + +/* +** Codec implementation +*/ +#if HAVE_CIPHER_AES_128_CBC || HAVE_CIPHER_AES_256_CBC || HAVE_CIPHER_SQLCIPHER +/* #include "rijndael.c" */ +/*** Begin of #include "rijndael.c" ***/ +/* +** Name: rijndael.c +** Purpose: Implementation of the Rijndael cipher +** Author: Ulrich Telle +** Created: 2006-12-06 +** Copyright: (c) 2006-2020 Ulrich Telle +** License: MIT +** +** Adjustments were made to make this code work with the wxSQLite3's +** SQLite encryption extension. +** The original code is public domain (see comments below). +*/ + +/* +/// \file rijndael.cpp Implementation of the Rijndael cipher +// +// File : rijndael.cpp +// Creation date : Sun Nov 5 2000 03:22:10 CEST +// Author : Szymon Stefanek (stefanek@tin.it) +// +// Another implementation of the Rijndael cipher. +// This is intended to be an easily usable library file. +// This code is public domain. +// Based on the Vincent Rijmen and K.U.Leuven implementation 2.4. +// +// Original Copyright notice: +// +// rijndael-alg-fst.c v2.4 April '2000 +// rijndael-alg-fst.h +// rijndael-api-fst.c +// rijndael-api-fst.h +// +// Optimised ANSI C code +// +// authors: v1.0: Antoon Bosselaers +// v2.0: Vincent Rijmen, K.U.Leuven +// v2.3: Paulo Barreto +// v2.4: Vincent Rijmen, K.U.Leuven +// +// This code is placed in the public domain. +// +// This implementation works on 128 , 192 , 256 bit keys +// and on 128 bit blocks +*/ + +#define RIJNDAEL_CPP_ + +/* #include "rijndael.h" */ +/*** Begin of #include "rijndael.h" ***/ +/* +** Name: rijndael.h +** Purpose: Header file for the Rijndael cipher +** Author: Ulrich Telle +** Created: 2006-12-06 +** Copyright: (c) 2006-2020 Ulrich Telle +** License: MIT +** +** Adjustments were made to make this code work with the wxSQLite3's +** SQLite encryption extension. +** The original code is public domain (see comments below). +*/ + +/* +/// \file rijndael.h Interface of the Rijndael cipher +*/ + +#ifndef _RIJNDAEL_H_ +#define _RIJNDAEL_H_ + +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE +#endif + +/* +// File : rijndael.h +// Creation date : Sun Nov 5 2000 03:21:05 CEST +// Author : Szymon Stefanek (stefanek@tin.it) +// +// Another implementation of the Rijndael cipher. +// This is intended to be an easily usable library file. +// This code is public domain. +// Based on the Vincent Rijmen and K.U.Leuven implementation 2.4. +// +// Original Copyright notice: +// +// rijndael-alg-fst.c v2.4 April '2000 +// rijndael-alg-fst.h +// rijndael-api-fst.c +// rijndael-api-fst.h +// +// Optimised ANSI C code +// +// authors: v1.0: Antoon Bosselaers +// v2.0: Vincent Rijmen, K.U.Leuven +// v2.3: Paulo Barreto +// v2.4: Vincent Rijmen, K.U.Leuven +// +// This code is placed in the public domain. +// + +// +// This implementation works on 128 , 192 , 256 bit keys +// and on 128 bit blocks +// + +// +// Example of usage: +// +// // Input data +// unsigned char key[32]; // The key +// initializeYour256BitKey(); // Obviously initialized with sth +// const unsigned char * plainText = getYourPlainText(); // Your plain text +// int plainTextLen = strlen(plainText); // Plain text length +// +// // Encrypting +// Rijndael rin; +// unsigned char output[plainTextLen + 16]; +// +// rin.init(Rijndael::CBC,Rijndael::Encrypt,key,Rijndael::Key32Bytes); +// // It is a good idea to check the error code +// int len = rin.padEncrypt(plainText,len,output); +// if(len >= 0)useYourEncryptedText(); +// else encryptError(len); +// +// // Decrypting: we can reuse the same object +// unsigned char output2[len]; +// rin.init(Rijndael::CBC,Rijndael::Decrypt,key,Rijndael::Key32Bytes)); +// len = rin.padDecrypt(output,len,output2); +// if(len >= 0)useYourDecryptedText(); +// else decryptError(len); +// +*/ + +#define _MAX_KEY_COLUMNS (256/32) +#define _MAX_ROUNDS 14 +#define MAX_IV_SIZE 16 + +/* We assume that unsigned int is 32 bits long.... */ +typedef unsigned char UINT8; +typedef unsigned int UINT32; +typedef unsigned short UINT16; + +/* Error codes */ +#define RIJNDAEL_SUCCESS 0 +#define RIJNDAEL_UNSUPPORTED_MODE -1 +#define RIJNDAEL_UNSUPPORTED_DIRECTION -2 +#define RIJNDAEL_UNSUPPORTED_KEY_LENGTH -3 +#define RIJNDAEL_BAD_KEY -4 +#define RIJNDAEL_NOT_INITIALIZED -5 +#define RIJNDAEL_BAD_DIRECTION -6 +#define RIJNDAEL_CORRUPTED_DATA -7 + +#define RIJNDAEL_Direction_Encrypt 0 +#define RIJNDAEL_Direction_Decrypt 1 + +#define RIJNDAEL_Direction_Mode_ECB 0 +#define RIJNDAEL_Direction_Mode_CBC 1 +#define RIJNDAEL_Direction_Mode_CFB1 2 + +#define RIJNDAEL_Direction_KeyLength_Key16Bytes 0 +#define RIJNDAEL_Direction_KeyLength_Key24Bytes 1 +#define RIJNDAEL_Direction_KeyLength_Key32Bytes 2 + +#define RIJNDAEL_State_Valid 0 +#define RIJNDAEL_State_Invalid 1 + +/* +/// Class implementing the Rijndael cipher. (For internal use only) +*/ + +typedef struct _Rijndael +{ + int m_state; + int m_mode; + int m_direction; + UINT8 m_initVector[MAX_IV_SIZE]; + UINT32 m_uRounds; + UINT8 m_expandedKey[_MAX_ROUNDS+1][4][4]; +} Rijndael; + +SQLITE_PRIVATE void RijndaelCreate(Rijndael* rijndael); + +/* +////////////////////////////////////////////////////////////////////////////////////////// +// API +////////////////////////////////////////////////////////////////////////////////////////// + +// init(): Initializes the crypt session +// Returns RIJNDAEL_SUCCESS or an error code +// mode : Rijndael::ECB, Rijndael::CBC or Rijndael::CFB1 +// You have to use the same mode for encrypting and decrypting +// dir : Rijndael::Encrypt or Rijndael::Decrypt +// A cipher instance works only in one direction +// (Well , it could be easily modified to work in both +// directions with a single init() call, but it looks +// useless to me...anyway , it is a matter of generating +// two expanded keys) +// key : array of unsigned octets , it can be 16 , 24 or 32 bytes long +// this CAN be binary data (it is not expected to be null terminated) +// keyLen : Rijndael::Key16Bytes , Rijndael::Key24Bytes or Rijndael::Key32Bytes +// initVector: initialization vector, you will usually use 0 here +*/ +SQLITE_PRIVATE int RijndaelInit(Rijndael* rijndael, int mode, int dir, UINT8* key, int keyLen, UINT8* initVector); + +/* +// Encrypts the input array (can be binary data) +// The input array length must be a multiple of 16 bytes, the remaining part +// is DISCARDED. +// so it actually encrypts inputLen / 128 blocks of input and puts it in outBuffer +// Input len is in BITS! +// outBuffer must be at least inputLen / 8 bytes long. +// Returns the encrypted buffer length in BITS or an error code < 0 in case of error +*/ +SQLITE_PRIVATE int RijndaelBlockEncrypt(Rijndael* rijndael, UINT8 *input, int inputLen, UINT8 *outBuffer); + +/* +// Encrypts the input array (can be binary data) +// The input array can be any length , it is automatically padded on a 16 byte boundary. +// Input len is in BYTES! +// outBuffer must be at least (inputLen + 16) bytes long +// Returns the encrypted buffer length in BYTES or an error code < 0 in case of error +*/ +SQLITE_PRIVATE int RijndaelPadEncrypt(Rijndael* rijndael, UINT8 *input, int inputOctets, UINT8 *outBuffer); + +/* +// Decrypts the input vector +// Input len is in BITS! +// outBuffer must be at least inputLen / 8 bytes long +// Returns the decrypted buffer length in BITS and an error code < 0 in case of error +*/ +SQLITE_PRIVATE int RijndaelBlockDecrypt(Rijndael* rijndael, UINT8 *input, int inputLen, UINT8 *outBuffer); + +/* +// Decrypts the input vector +// Input len is in BYTES! +// outBuffer must be at least inputLen bytes long +// Returns the decrypted buffer length in BYTES and an error code < 0 in case of error +*/ +SQLITE_PRIVATE int RijndaelPadDecrypt(Rijndael* rijndael, UINT8 *input, int inputOctets, UINT8 *outBuffer); + +SQLITE_PRIVATE void RijndaelInvalidate(Rijndael* rijndael); +SQLITE_PRIVATE void RijndaelKeySched(Rijndael* rijndael, UINT8 key[_MAX_KEY_COLUMNS][4]); +SQLITE_PRIVATE void RijndaelKeyEncToDec(Rijndael* rijndael); +SQLITE_PRIVATE void RijndaelEncrypt(Rijndael* rijndael, UINT8 a[16], UINT8 b[16]); +SQLITE_PRIVATE void RijndaelDecrypt(Rijndael* rijndael, UINT8 a[16], UINT8 b[16]); + +#endif /* _RIJNDAEL_H_ */ +/*** End of #include "rijndael.h" ***/ + + +#include +#include +#include + +#ifdef TEST_AES_HW +#define TEST_AES_HW_DEBUG +#define TEST_AES_HW_DEBUG_DATA +#endif + +#ifdef TEST_AES_HW_DEBUG +#define TEST_AES_HW_DEBUG_LOG(...) { fprintf(stdout, __VA_ARGS__); fflush(stdout); } +#else +#define TEST_AES_HW_DEBUG_LOG(...) +#endif + +#ifdef TEST_AES_HW_DEBUG_DATA +#define TEST_AES_HW_DEBUG_HEX(DESC,BUFFER,LEN) \ + { \ + int count; \ + printf(DESC); \ + for (count = 0; count < LEN; ++count) \ + { \ + if (count % 16 == 0) printf("\n%05x: ", count); \ + printf("%02x ", ((unsigned char*) BUFFER)[count]); \ + } \ + printf("\n"); \ + fflush(stdout); \ + } +#else +#define TEST_AES_HW_DEBUG_HEX(DESC,BUFFER,LEN) +#endif + +/* +** Use AES hardware support if available +*/ +/* #include "aes_hardware.c" */ +/*** Begin of #include "aes_hardware.c" ***/ +/* +** Name: aes_hardware.c +** Purpose: AES algorithms based on AES NI +** Author: Ulrich Telle +** Created: 2020-12-01 +** Copyright: (c) 2020 Ulrich Telle +** License: MIT +*/ + +/* +** Check whether the platform offers hardware support for AES +*/ + +#define AES_HARDWARE_NONE 0 +#define AES_HARDWARE_NI 1 +#define AES_HARDWARE_NEON 2 + +#ifndef SQLITE3MC_OMIT_AES_HARDWARE_SUPPORT + +#if defined __ARM_FEATURE_CRYPTO +#define HAS_AES_HARDWARE AES_HARDWARE_NEON + + +/* --- CLang --- */ +#elif defined(__clang__) + +#if __has_attribute(target) && __has_include() && (defined(__x86_64__) || defined(__i386)) +#define HAS_AES_HARDWARE AES_HARDWARE_NI + +#elif __has_attribute(target) && __has_include() && (defined(__aarch64__)) +#define HAS_AES_HARDWARE AES_HARDWARE_NEON + +/* Crypto extension in AArch64 can be enabled using __attribute__((target)) */ +#define USE_CLANG_ATTR_TARGET_AARCH64 + +#endif + + +/* --- GNU C/C++ */ +#elif defined(__GNUC__) + +#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) && (defined(__x86_64__) || defined(__i386)) +#define HAS_AES_HARDWARE AES_HARDWARE_NI +#endif + + +/* --- Visual C/C++ --- */ +#elif defined (_MSC_VER) + +/* Architecture: x86 or x86_64 */ +#if (defined(_M_X64) || defined(_M_IX86)) && _MSC_FULL_VER >= 150030729 +#define HAS_AES_HARDWARE AES_HARDWARE_NI + +/* Architecture: ARM 64-bit */ +#elif defined(_M_ARM64) +#define HAS_AES_HARDWARE AES_HARDWARE_NEON + +/* Use header instead of */ +#define USE_ARM64_NEON_H + +/* Architecture: ARM 32-bit */ +#elif defined _M_ARM +#define HAS_AES_HARDWARE AES_HARDWARE_NEON + +/* The following #define is required to enable intrinsic definitions + that do not omit one of the parameters for vaes[ed]q_u8 */ +#define _ARM_USE_NEW_NEON_INTRINSICS + +#endif + +#else + +#define HAS_AES_HARDWARE AES_HARDWARE_NONE + +#endif + +#else /* SQLITE3MC_OMIT_AES_HARDWARE_SUPPORT defined */ + +/* Omit AES hardware support */ +#define HAS_AES_HARDWARE AES_HARDWARE_NONE + +#endif /* SQLITE3MC_OMIT_AES_HARDWARE_SUPPORT */ + + +#if HAS_AES_HARDWARE != AES_HARDWARE_NONE +/* --- Implementation of common data and functions for any AES hardware --- */ + +/* The first few powers of X in GF(2^8), used during key setup */ +static const uint8_t gKeySetupRoundConstants[] = +{ + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, +}; + +static inline uint32_t +toUint32FromLE(const void* buffer) +{ + const uint8_t* p = (const uint8_t*) buffer; + return (((uint32_t) p[0]) | ((uint32_t) p[1] << 8) | + ((uint32_t) p[2] << 16) | ((uint32_t) p[3] << 24)); +} + +#endif + +#if HAS_AES_HARDWARE == AES_HARDWARE_NI +/* --- Implementation for AES-NI --- */ + +/* Define SQLITE3MC_COMPILER_HAS_ATTRIBUTE */ +#if defined(__has_attribute) + #define SQLITE3MC_COMPILER_HAS_ATTRIBUTE(x) __has_attribute(x) + #define SQLITE3MC_COMPILER_ATTRIBUTE(x) __attribute__((x)) +#else + #define SQLITE3MC_COMPILER_HAS_ATTRIBUTE(x) 0 + #define SQLITE3MC_COMPILER_ATTRIBUTE(x) /**/ +#endif + +/* Define SQLITE3MC_FORCE_INLINE */ +#if !defined(SQLITE3MC_FORCE_INLINE) + #if SQLITE3MC_COMPILER_HAS_ATTRIBUTE(always_inline) + #define SQLITE3MC_FORCE_INLINE inline SQLITE3MC_COMPILER_ATTRIBUTE(always_inline) + #elif defined(_MSC_VER) + #define SQLITE3MC_FORCE_INLINE __forceinline + #else + #define SQLITE3MC_FORCE_INLINE inline + #endif +#endif + +/* Define SQLITE3MC_FUNC_ISA */ +#if SQLITE3MC_COMPILER_HAS_ATTRIBUTE(target) + #define SQLITE3MC_FUNC_ISA(isa) SQLITE3MC_COMPILER_ATTRIBUTE(target(isa)) +#else + #define SQLITE3MC_FUNC_ISA(isa) +#endif + +/* Define SQLITE3MC_FUNC_ISA_INLINE */ +#define SQLITE3MC_FUNC_ISA_INLINE(isa) SQLITE3MC_FUNC_ISA(isa) SQLITE3MC_FORCE_INLINE + + +/* +** Define function for detecting hardware AES support at runtime +*/ + +#if defined(__clang__) || defined(__GNUC__) +/* Compiler CLang or GCC */ + +#include + +static int +aesHardwareCheck() +{ + unsigned int cpuInfo[4]; + __cpuid(1, cpuInfo[0], cpuInfo[1], cpuInfo[2], cpuInfo[3]); + /* Check AES and SSE4.1 */ + return (cpuInfo[2] & (1 << 25)) != 0 && (cpuInfo[2] & (1 << 19)) != 0; +} + +#else /* !(defined(__clang__) || defined(__GNUC__)) */ +/* Compiler Visual C++ */ + +#include + +static int +aesHardwareCheck() +{ + unsigned int CPUInfo[4]; + __cpuid((int*) CPUInfo, 1); + return (CPUInfo[2] & (1 << 25)) != 0 && (CPUInfo[2] & (1 << 19)) != 0; /* Check AES and SSE4.1 */ +} + +#endif /* defined(__clang__) || defined(__GNUC__) */ + +#include +#include + +SQLITE3MC_FUNC_ISA("sse4.2,aes") +static int +aesGenKeyEncryptInternal(const unsigned char* userKey, const int bits, __m128i* keyData) +{ + int rc = 0; + int i; + int j; + int numberOfRounds = (bits == 128) ? 10 : (bits == 192) ? 12 : (bits == 256) ? 14 : 0; + int keyWords = bits / 32; + int schedWords = (numberOfRounds + 1) * 4; + + /* + ** Key schedule stored as 32-bit integers during expansion. + ** Final __m128i form produced in the last step. + */ + uint32_t sched[(_MAX_ROUNDS + 1) * 4]; + + unsigned roundConstantPos = 0; + + for (i = 0; i < schedWords; i++) + { + if (i < keyWords) + { + sched[i] = toUint32FromLE(userKey + 4 * i); + } + else + { + uint32_t temp = sched[i - 1]; + + int rotateAndRoundConstant = (i % keyWords == 0); + int subOnly = (keyWords == 8 && i % 8 == 4); + + if (rotateAndRoundConstant) + { + temp = _mm_extract_epi32(_mm_aeskeygenassist_si128(_mm_setr_epi32(0, temp, 0, 0), 0), 1); + temp ^= gKeySetupRoundConstants[roundConstantPos++]; + } + else if (subOnly) + { + temp = _mm_extract_epi32(_mm_aeskeygenassist_si128(_mm_setr_epi32(0, temp, 0, 0), 0), 0); + } + + sched[i] = sched[i - keyWords] ^ temp; + } + } + + /* Convert key schedule words into __m128i vectors */ + for (j = 0; j <= numberOfRounds; j++) + { + keyData[j] = _mm_setr_epi32(sched[4 * j], sched[4 * j + 1], sched[4 * j + 2], sched[4 * j + 3]); + } + return rc; +} + +SQLITE3MC_FUNC_ISA("sse4.2,aes") +static int +aesGenKeyEncrypt(const unsigned char* userKey, const int bits, unsigned char* keyData) +{ + int numberOfRounds = (bits == 128) ? 10 : (bits == 192) ? 12 : (bits == 256) ? 14 : 0; + int rc = (!userKey || !keyData) ? -1 : (numberOfRounds > 0) ? 0 : -2; + + if (rc == 0) + { + __m128i tempKey[_MAX_ROUNDS + 1]; + rc = aesGenKeyEncryptInternal(userKey, bits, tempKey); + if (rc == 0) + { + int j; + for (j = 0; j <= numberOfRounds; ++j) + { + _mm_storeu_si128(&((__m128i*) keyData)[j], tempKey[j]); + } + } + } + return rc; +} + +SQLITE3MC_FUNC_ISA("sse4.2,aes") +static int +aesGenKeyDecrypt(const unsigned char* userKey, const int bits, unsigned char* keyData) +{ + int numberOfRounds = (bits == 128) ? 10 : (bits == 192) ? 12 : (bits == 256) ? 14 : 0; + int rc = (!userKey || !keyData) ? -1 : (numberOfRounds > 0) ? 0 : -2; + + if (rc == 0) + { + __m128i tempKeySchedule[_MAX_ROUNDS + 1]; + __m128i keySchedule[_MAX_ROUNDS + 1]; + rc = aesGenKeyEncryptInternal(userKey, bits, tempKeySchedule); + if (rc == 0) + { + int j; + keySchedule[0] = tempKeySchedule[0]; + for (j = 1; j < numberOfRounds; ++j) + { + keySchedule[j] = _mm_aesimc_si128(tempKeySchedule[j]); + } + keySchedule[numberOfRounds] = tempKeySchedule[numberOfRounds]; + + for (j = 0; j <= numberOfRounds; ++j) + { + _mm_storeu_si128(&((__m128i*) keyData)[j], keySchedule[j]); + } + } + } + return rc; +} + +/* +** AES CBC CTS Encryption +*/ + +SQLITE3MC_FUNC_ISA("sse4.2,aes") +static void +aesEncryptCBC(const unsigned char* in, + unsigned char* out, + unsigned char ivec[16], + unsigned long length, + const unsigned char* keyData, + int numberOfRounds) +{ + __m128i key[_MAX_ROUNDS + 1]; + __m128i feedback; + __m128i data; + unsigned long i; + int j; + unsigned long numBlocks = length / 16; + unsigned long lenFrag = (length % 16); + + /* Load key data into properly aligned local storage */ + for (j = 0; j <= numberOfRounds; ++j) + { + key[j] = _mm_loadu_si128(&((__m128i*) keyData)[j]); + } + + /* Encrypt all complete blocks */ + feedback = _mm_loadu_si128((__m128i*) ivec); + for (i = 0; i < numBlocks; ++i) + { + data = _mm_loadu_si128(&((__m128i*) in)[i]); + feedback = _mm_xor_si128(data, feedback); + + feedback = _mm_xor_si128(feedback, key[0]); + for (j = 1; j < numberOfRounds; j++) + { + feedback = _mm_aesenc_si128(feedback, key[j]); + } + feedback = _mm_aesenclast_si128(feedback, key[j]); + _mm_storeu_si128(&((__m128i*) out)[i], feedback); + } + + /* Use Cipher Text Stealing (CTS) for incomplete last block */ + if (lenFrag > 0) + { + UINT8 lastblock[16]; + UINT8 partialblock[16]; + /* Adjust the second last plain block. */ + memcpy(lastblock, &out[16*(numBlocks-1)], lenFrag); + /* Encrypt the last plain block. */ + memset(partialblock, 0, 16); + memcpy(partialblock, &in[16*numBlocks], lenFrag); + + data = _mm_loadu_si128(&((__m128i*) partialblock)[0]); + feedback = _mm_xor_si128(data, feedback); + + feedback = _mm_xor_si128(feedback, key[0]); + for (j = 1; j < numberOfRounds; j++) + { + feedback = _mm_aesenc_si128(feedback, key[j]); + } + feedback = _mm_aesenclast_si128(feedback, key[j]); + _mm_storeu_si128(&((__m128i*) out)[numBlocks-1], feedback); + + memcpy(&out[16*numBlocks], lastblock, lenFrag); + } +} + +/* +** AES CBC CTS decryption +*/ +SQLITE3MC_FUNC_ISA("sse4.2,aes") +static void +aesDecryptCBC(const unsigned char* in, + unsigned char* out, + unsigned char ivec[16], + unsigned long length, + const unsigned char* keyData, + int numberOfRounds) +{ + __m128i key[_MAX_ROUNDS + 1]; + __m128i data; + __m128i feedback; + __m128i last_in; + unsigned long i; + int j; + unsigned long numBlocks = length / 16; + unsigned long lenFrag = (length % 16); + + /* Load key data into properly aligned local storage */ + for (j = 0; j <= numberOfRounds; ++j) + { + key[j] = _mm_loadu_si128(&((__m128i*) keyData)[j]); + } + + /* Use Cipher Text Stealing (CTS) for incomplete last block */ + if (lenFrag > 0) + { + UINT8 lastblock[16]; + UINT8 partialblock[16]; + int offset; + --numBlocks; + offset = numBlocks * 16; + + /* Decrypt the last plain block. */ + last_in = _mm_loadu_si128(&((__m128i*) in)[numBlocks]); + data = _mm_xor_si128(last_in, key[numberOfRounds - 0]); + for (j = 1; j < numberOfRounds; j++) + { + data = _mm_aesdec_si128(data, key[numberOfRounds - j]); + } + data = _mm_aesdeclast_si128(data, key[numberOfRounds - j]); + _mm_storeu_si128(&((__m128i*) partialblock)[0], data); + + memcpy(partialblock, &in[16 * numBlocks + 16], lenFrag); + last_in = _mm_loadu_si128(&((__m128i*) partialblock)[0]); + + data = _mm_xor_si128(data, last_in); + _mm_storeu_si128(&((__m128i*) lastblock)[0], data); + + /* Decrypt the second last block. */ + data = _mm_xor_si128(last_in, key[numberOfRounds - 0]); + for (j = 1; j < numberOfRounds; j++) + { + data = _mm_aesdec_si128(data, key[numberOfRounds - j]); + } + data = _mm_aesdeclast_si128(data, key[numberOfRounds - j]); + + if (numBlocks > 0) + { + feedback = _mm_loadu_si128(&((__m128i*) in)[numBlocks - 1]); + } + else + { + feedback = _mm_loadu_si128((__m128i*) ivec); + } + data = _mm_xor_si128(data, feedback); + _mm_storeu_si128(&((__m128i*) out)[numBlocks], data); + + memcpy(out + offset + 16, lastblock, lenFrag); + } + + /* Encrypt all complete blocks */ + feedback = _mm_loadu_si128((__m128i*) ivec); + for (i = 0; i < numBlocks; i++) + { + last_in =_mm_loadu_si128(&((__m128i*) in)[i]); + data = _mm_xor_si128(last_in, key[numberOfRounds - 0]); + for (j = 1; j < numberOfRounds; j++) + { + data = _mm_aesdec_si128(data, key[numberOfRounds - j]); + } + data = _mm_aesdeclast_si128(data, key[numberOfRounds - j]); + data = _mm_xor_si128(data, feedback); + _mm_storeu_si128(&((__m128i*) out)[i], data); + feedback = last_in; + } +} + +#elif HAS_AES_HARDWARE == AES_HARDWARE_NEON +/* --- Implementation for AES-NEON --- */ + +/* Set target architecture manually, if necessary */ +#ifdef USE_CLANG_ATTR_TARGET_AARCH64 +#define __ARM_NEON 1 +#define __ARM_FEATURE_CRYPTO 1 +#define __ARM_FEATURE_AES 1 +#define FUNC_ISA __attribute__ ((target("neon,crypto"))) +#endif /* USE_CLANG_ATTR_TARGET_AARCH64 */ + +/* FUNCtion attributes for ISA (Instruction Set Architecture) */ +#ifndef FUNC_ISA +#define FUNC_ISA +#endif + +#ifdef USE_ARM64_NEON_H +#include +#else +#include +#endif + +#if defined(__linux__) && (defined(__arm__) || defined(__aarch64__)) + +#include +#include + +static int +aesHardwareAvailableOnPlatform() +{ +#if defined HWCAP_AES + return getauxval(AT_HWCAP) & HWCAP_AES; +#elif defined HWCAP2_AES + return getauxval(AT_HWCAP2) & HWCAP2_AES; +#else + return 0; +#endif +} + +#elif defined _M_ARM || defined _M_ARM64 + +static int +aesHardwareAvailableOnPlatform() +{ + return (int) IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE); +} + +#else + +static int +aesHardwareAvailableOnPlatform() +{ + return 0; +} + +#endif + +static int +aesHardwareCheck() +{ + return aesHardwareAvailableOnPlatform(); +} + +/* +** Set up expanded key +*/ + +static FUNC_ISA int +aesGenKeyEncryptInternal(const unsigned char* userKey, const int bits, uint8x16_t* keyData) +{ + int rc = 0; + int i; + int j; + int numberOfRounds = (bits == 128) ? 10 : (bits == 192) ? 12 : (bits == 256) ? 14 : 0; + int keyWords = bits / 32; + int schedWords = (numberOfRounds + 1) * 4; + + /* + ** Key schedule stored as 32-bit integers during expansion. + ** Final uint8x16_t form produced in the last step. + */ + uint32_t sched[(_MAX_ROUNDS + 1) * 4]; + + unsigned roundConstantPos = 0; + + for (i = 0; i < schedWords; i++) + { + if (i < keyWords) + { + sched[i] = toUint32FromLE(userKey + 4 * i); + } + else + { + uint32_t temp = sched[i - 1]; + + int rotateAndRoundConstant = (i % keyWords == 0); + int sub = rotateAndRoundConstant || (keyWords == 8 && i % 8 == 4); + + if (rotateAndRoundConstant) + { + temp = (temp << 24) | (temp >> 8); + } + + if (sub) + { + uint32x4_t v32 = vdupq_n_u32(temp); + uint8x16_t v8 = vreinterpretq_u8_u32(v32); + v8 = vaeseq_u8(v8, vdupq_n_u8(0)); + v32 = vreinterpretq_u32_u8(v8); + temp = vget_lane_u32(vget_low_u32(v32), 0); + } + + if (rotateAndRoundConstant) + { + temp ^= gKeySetupRoundConstants[roundConstantPos++]; + } + + sched[i] = sched[i - keyWords] ^ temp; + } + } + + /* Convert key schedule words into uint8x16_t vectors */ + for (j = 0; j <= numberOfRounds; j++) + { + keyData[j] = vreinterpretq_u8_u32(vld1q_u32(sched + 4*j)); + } + + return rc; +} + +static FUNC_ISA int +aesGenKeyEncrypt(const unsigned char* userKey, const int bits, unsigned char* keyData) +{ + int numberOfRounds = (bits == 128) ? 10 : (bits == 192) ? 12 : (bits == 256) ? 14 : 0; + int rc = (!userKey || !keyData) ? -1 : (numberOfRounds > 0) ? 0 : -2; + + if (rc == 0) + { + uint8x16_t tempKey[_MAX_ROUNDS + 1]; + rc = aesGenKeyEncryptInternal(userKey, bits, tempKey); + if (rc == 0) + { + int j; + for (j = 0; j <= numberOfRounds; ++j) + { + vst1q_u8(&keyData[j*16], tempKey[j]); + } + } + } + return rc; +} + +static FUNC_ISA int +aesGenKeyDecrypt(const unsigned char* userKey, const int bits, unsigned char* keyData) +{ + int numberOfRounds = (bits == 128) ? 10 : (bits == 192) ? 12 : (bits == 256) ? 14 : 0; + int rc = (!userKey || !keyData) ? -1 : (numberOfRounds > 0) ? 0 : -2; + + if (rc == 0) + { + uint8x16_t tempKeySchedule[_MAX_ROUNDS + 1]; + uint8x16_t keySchedule[_MAX_ROUNDS + 1]; + rc = aesGenKeyEncryptInternal(userKey, bits, tempKeySchedule); + if (rc == 0) + { + int j; + keySchedule[0] = tempKeySchedule[0]; + + for (j = 1; j < numberOfRounds; ++j) + { + keySchedule[j] = vaesimcq_u8(tempKeySchedule[j]); + } + keySchedule[numberOfRounds] = tempKeySchedule[numberOfRounds]; + + for (j = 0; j <= numberOfRounds; ++j) + { + vst1q_u8(&keyData[j*16], keySchedule[j]); + } + } + } + return rc; +} + +/* +** AES CBC CTS Encryption +*/ +static FUNC_ISA void +aesEncryptCBC(const unsigned char* in, + unsigned char* out, + unsigned char ivec[16], + unsigned long length, + const unsigned char* keyData, + int numberOfRounds) +{ + uint8x16_t key[_MAX_ROUNDS + 1]; + uint8x16_t feedback; + uint8x16_t data; + unsigned long i; + int j; + unsigned long numBlocks = length / 16; + unsigned long lenFrag = (length % 16); + + /* Load key data into properly aligned local storage */ + for (j = 0; j <= numberOfRounds; ++j) + { + key[j] = vld1q_u8(&keyData[j*16]); + } + + /* Encrypt all complete blocks */ + feedback = vld1q_u8(ivec); + for (i = 0; i < numBlocks; ++i) + { + data = vld1q_u8(&in[i*16]); + feedback = veorq_u8(data, feedback); + + for (j = 0; j < numberOfRounds-1; j++) + { + feedback = vaesmcq_u8(vaeseq_u8(feedback, key[j])); + } + feedback = vaeseq_u8(feedback, key[numberOfRounds-1]); + feedback = veorq_u8(feedback, key[numberOfRounds]); \ + + vst1q_u8(&out[i*16], feedback); + } + + /* Use Cipher Text Stealing (CTS) for incomplete last block */ + if (lenFrag > 0) + { + UINT8 lastblock[16]; + UINT8 partialblock[16]; + /* Adjust the second last plain block. */ + memcpy(lastblock, &out[(numBlocks-1)*16], lenFrag); + /* Encrypt the last plain block. */ + memset(partialblock, 0, 16); + memcpy(partialblock, &in[numBlocks*16], lenFrag); + + data = vld1q_u8(partialblock); + feedback = veorq_u8(data, feedback); + + for (j = 0; j < numberOfRounds-1; j++) + { + feedback = vaesmcq_u8(vaeseq_u8(feedback, key[j])); + } + feedback = vaeseq_u8(feedback, key[numberOfRounds-1]); + feedback = veorq_u8(feedback, key[numberOfRounds]); \ + + vst1q_u8(&out[(numBlocks-1)*16], feedback); + + memcpy(&out[numBlocks*16], lastblock, lenFrag); + } +} + +/* +** AES CBC CTS decryption +*/ +static FUNC_ISA void +aesDecryptCBC(const unsigned char* in, + unsigned char* out, + unsigned char ivec[16], + unsigned long length, + const unsigned char* keyData, + int numberOfRounds) +{ + uint8x16_t key[_MAX_ROUNDS + 1]; + uint8x16_t data; + uint8x16_t feedback; + uint8x16_t last_in; + unsigned long i; + int j; + unsigned long numBlocks = length / 16; + unsigned long lenFrag = (length % 16); + + /* Load key data into properly aligned local storage */ + for (j = 0; j <= numberOfRounds; ++j) + { + key[j] = vld1q_u8(&keyData[j*16]); + } + + /* Use Cipher Text Stealing (CTS) for incomplete last block */ + if (lenFrag > 0) + { + UINT8 lastblock[16]; + UINT8 partialblock[16]; + int offset; + --numBlocks; + offset = numBlocks * 16; + + /* Decrypt the last plain block. */ + last_in = vld1q_u8(&in[numBlocks*16]); + + data = last_in; + for (j = 0; j < numberOfRounds-1; j++) + { + data = vaesimcq_u8(vaesdq_u8(data, key[numberOfRounds-j])); + } + data = vaesdq_u8(data, key[1]); + data = veorq_u8(data, key[0]); + + vst1q_u8(partialblock, data); + + memcpy(partialblock, &in[(numBlocks + 1)*16], lenFrag); + last_in = vld1q_u8(partialblock); + + data = veorq_u8(data, last_in); + vst1q_u8(lastblock, data); + + /* Decrypt the second last block. */ + data = last_in; + for (j = 0; j < numberOfRounds-1; j++) + { + data = vaesimcq_u8(vaesdq_u8(data, key[numberOfRounds-j])); + } + data = vaesdq_u8(data, key[1]); + data = veorq_u8(data, key[0]); + + if (numBlocks > 0) + { + feedback = vld1q_u8(&in[(numBlocks - 1)*16]); + } + else + { + feedback = vld1q_u8(ivec); + } + data = veorq_u8(data, feedback); + vst1q_u8(&out[numBlocks*16], data); + + memcpy(out + offset + 16, lastblock, lenFrag); + } + + /* Decrypt all complete blocks */ + feedback = vld1q_u8(ivec); + for (i = 0; i < numBlocks; i++) + { + last_in = vld1q_u8(&in[i*16]); + + data = last_in; + for (j = 0; j < numberOfRounds-1; j++) + { + data = vaesimcq_u8(vaesdq_u8(data, key[numberOfRounds-j])); + } + data = vaesdq_u8(data, key[1]); + data = veorq_u8(data, key[0]); + + data = veorq_u8(data, feedback); + vst1q_u8(&out[i*16], data); + + feedback = last_in; + } +} + +#else +/* --- No AES hardware available --- */ + +static int +aesHardwareCheck() +{ + return 0; +} + +#endif + +/* +** The top-level selection function, caching the results of +** aesHardwareCheck() so it only has to run once. +*/ +static int +aesHardwareAvailable() +{ + static int initialized = 0; + static int hwAvailable = 0; + if (!initialized) + { + hwAvailable = aesHardwareCheck(); + initialized = 1; + } + return hwAvailable; +} +/*** End of #include "aes_hardware.c" ***/ + + +static UINT8 S[256]= +{ + 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, + 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, + 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, + 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, + 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, + 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, + 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, + 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, + 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, + 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, + 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, + 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, + 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, + 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, + 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, + 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22 +}; + +static UINT8 T1[256][4]= +{ + {0xc6,0x63,0x63,0xa5}, {0xf8,0x7c,0x7c,0x84}, {0xee,0x77,0x77,0x99}, {0xf6,0x7b,0x7b,0x8d}, + {0xff,0xf2,0xf2,0x0d}, {0xd6,0x6b,0x6b,0xbd}, {0xde,0x6f,0x6f,0xb1}, {0x91,0xc5,0xc5,0x54}, + {0x60,0x30,0x30,0x50}, {0x02,0x01,0x01,0x03}, {0xce,0x67,0x67,0xa9}, {0x56,0x2b,0x2b,0x7d}, + {0xe7,0xfe,0xfe,0x19}, {0xb5,0xd7,0xd7,0x62}, {0x4d,0xab,0xab,0xe6}, {0xec,0x76,0x76,0x9a}, + {0x8f,0xca,0xca,0x45}, {0x1f,0x82,0x82,0x9d}, {0x89,0xc9,0xc9,0x40}, {0xfa,0x7d,0x7d,0x87}, + {0xef,0xfa,0xfa,0x15}, {0xb2,0x59,0x59,0xeb}, {0x8e,0x47,0x47,0xc9}, {0xfb,0xf0,0xf0,0x0b}, + {0x41,0xad,0xad,0xec}, {0xb3,0xd4,0xd4,0x67}, {0x5f,0xa2,0xa2,0xfd}, {0x45,0xaf,0xaf,0xea}, + {0x23,0x9c,0x9c,0xbf}, {0x53,0xa4,0xa4,0xf7}, {0xe4,0x72,0x72,0x96}, {0x9b,0xc0,0xc0,0x5b}, + {0x75,0xb7,0xb7,0xc2}, {0xe1,0xfd,0xfd,0x1c}, {0x3d,0x93,0x93,0xae}, {0x4c,0x26,0x26,0x6a}, + {0x6c,0x36,0x36,0x5a}, {0x7e,0x3f,0x3f,0x41}, {0xf5,0xf7,0xf7,0x02}, {0x83,0xcc,0xcc,0x4f}, + {0x68,0x34,0x34,0x5c}, {0x51,0xa5,0xa5,0xf4}, {0xd1,0xe5,0xe5,0x34}, {0xf9,0xf1,0xf1,0x08}, + {0xe2,0x71,0x71,0x93}, {0xab,0xd8,0xd8,0x73}, {0x62,0x31,0x31,0x53}, {0x2a,0x15,0x15,0x3f}, + {0x08,0x04,0x04,0x0c}, {0x95,0xc7,0xc7,0x52}, {0x46,0x23,0x23,0x65}, {0x9d,0xc3,0xc3,0x5e}, + {0x30,0x18,0x18,0x28}, {0x37,0x96,0x96,0xa1}, {0x0a,0x05,0x05,0x0f}, {0x2f,0x9a,0x9a,0xb5}, + {0x0e,0x07,0x07,0x09}, {0x24,0x12,0x12,0x36}, {0x1b,0x80,0x80,0x9b}, {0xdf,0xe2,0xe2,0x3d}, + {0xcd,0xeb,0xeb,0x26}, {0x4e,0x27,0x27,0x69}, {0x7f,0xb2,0xb2,0xcd}, {0xea,0x75,0x75,0x9f}, + {0x12,0x09,0x09,0x1b}, {0x1d,0x83,0x83,0x9e}, {0x58,0x2c,0x2c,0x74}, {0x34,0x1a,0x1a,0x2e}, + {0x36,0x1b,0x1b,0x2d}, {0xdc,0x6e,0x6e,0xb2}, {0xb4,0x5a,0x5a,0xee}, {0x5b,0xa0,0xa0,0xfb}, + {0xa4,0x52,0x52,0xf6}, {0x76,0x3b,0x3b,0x4d}, {0xb7,0xd6,0xd6,0x61}, {0x7d,0xb3,0xb3,0xce}, + {0x52,0x29,0x29,0x7b}, {0xdd,0xe3,0xe3,0x3e}, {0x5e,0x2f,0x2f,0x71}, {0x13,0x84,0x84,0x97}, + {0xa6,0x53,0x53,0xf5}, {0xb9,0xd1,0xd1,0x68}, {0x00,0x00,0x00,0x00}, {0xc1,0xed,0xed,0x2c}, + {0x40,0x20,0x20,0x60}, {0xe3,0xfc,0xfc,0x1f}, {0x79,0xb1,0xb1,0xc8}, {0xb6,0x5b,0x5b,0xed}, + {0xd4,0x6a,0x6a,0xbe}, {0x8d,0xcb,0xcb,0x46}, {0x67,0xbe,0xbe,0xd9}, {0x72,0x39,0x39,0x4b}, + {0x94,0x4a,0x4a,0xde}, {0x98,0x4c,0x4c,0xd4}, {0xb0,0x58,0x58,0xe8}, {0x85,0xcf,0xcf,0x4a}, + {0xbb,0xd0,0xd0,0x6b}, {0xc5,0xef,0xef,0x2a}, {0x4f,0xaa,0xaa,0xe5}, {0xed,0xfb,0xfb,0x16}, + {0x86,0x43,0x43,0xc5}, {0x9a,0x4d,0x4d,0xd7}, {0x66,0x33,0x33,0x55}, {0x11,0x85,0x85,0x94}, + {0x8a,0x45,0x45,0xcf}, {0xe9,0xf9,0xf9,0x10}, {0x04,0x02,0x02,0x06}, {0xfe,0x7f,0x7f,0x81}, + {0xa0,0x50,0x50,0xf0}, {0x78,0x3c,0x3c,0x44}, {0x25,0x9f,0x9f,0xba}, {0x4b,0xa8,0xa8,0xe3}, + {0xa2,0x51,0x51,0xf3}, {0x5d,0xa3,0xa3,0xfe}, {0x80,0x40,0x40,0xc0}, {0x05,0x8f,0x8f,0x8a}, + {0x3f,0x92,0x92,0xad}, {0x21,0x9d,0x9d,0xbc}, {0x70,0x38,0x38,0x48}, {0xf1,0xf5,0xf5,0x04}, + {0x63,0xbc,0xbc,0xdf}, {0x77,0xb6,0xb6,0xc1}, {0xaf,0xda,0xda,0x75}, {0x42,0x21,0x21,0x63}, + {0x20,0x10,0x10,0x30}, {0xe5,0xff,0xff,0x1a}, {0xfd,0xf3,0xf3,0x0e}, {0xbf,0xd2,0xd2,0x6d}, + {0x81,0xcd,0xcd,0x4c}, {0x18,0x0c,0x0c,0x14}, {0x26,0x13,0x13,0x35}, {0xc3,0xec,0xec,0x2f}, + {0xbe,0x5f,0x5f,0xe1}, {0x35,0x97,0x97,0xa2}, {0x88,0x44,0x44,0xcc}, {0x2e,0x17,0x17,0x39}, + {0x93,0xc4,0xc4,0x57}, {0x55,0xa7,0xa7,0xf2}, {0xfc,0x7e,0x7e,0x82}, {0x7a,0x3d,0x3d,0x47}, + {0xc8,0x64,0x64,0xac}, {0xba,0x5d,0x5d,0xe7}, {0x32,0x19,0x19,0x2b}, {0xe6,0x73,0x73,0x95}, + {0xc0,0x60,0x60,0xa0}, {0x19,0x81,0x81,0x98}, {0x9e,0x4f,0x4f,0xd1}, {0xa3,0xdc,0xdc,0x7f}, + {0x44,0x22,0x22,0x66}, {0x54,0x2a,0x2a,0x7e}, {0x3b,0x90,0x90,0xab}, {0x0b,0x88,0x88,0x83}, + {0x8c,0x46,0x46,0xca}, {0xc7,0xee,0xee,0x29}, {0x6b,0xb8,0xb8,0xd3}, {0x28,0x14,0x14,0x3c}, + {0xa7,0xde,0xde,0x79}, {0xbc,0x5e,0x5e,0xe2}, {0x16,0x0b,0x0b,0x1d}, {0xad,0xdb,0xdb,0x76}, + {0xdb,0xe0,0xe0,0x3b}, {0x64,0x32,0x32,0x56}, {0x74,0x3a,0x3a,0x4e}, {0x14,0x0a,0x0a,0x1e}, + {0x92,0x49,0x49,0xdb}, {0x0c,0x06,0x06,0x0a}, {0x48,0x24,0x24,0x6c}, {0xb8,0x5c,0x5c,0xe4}, + {0x9f,0xc2,0xc2,0x5d}, {0xbd,0xd3,0xd3,0x6e}, {0x43,0xac,0xac,0xef}, {0xc4,0x62,0x62,0xa6}, + {0x39,0x91,0x91,0xa8}, {0x31,0x95,0x95,0xa4}, {0xd3,0xe4,0xe4,0x37}, {0xf2,0x79,0x79,0x8b}, + {0xd5,0xe7,0xe7,0x32}, {0x8b,0xc8,0xc8,0x43}, {0x6e,0x37,0x37,0x59}, {0xda,0x6d,0x6d,0xb7}, + {0x01,0x8d,0x8d,0x8c}, {0xb1,0xd5,0xd5,0x64}, {0x9c,0x4e,0x4e,0xd2}, {0x49,0xa9,0xa9,0xe0}, + {0xd8,0x6c,0x6c,0xb4}, {0xac,0x56,0x56,0xfa}, {0xf3,0xf4,0xf4,0x07}, {0xcf,0xea,0xea,0x25}, + {0xca,0x65,0x65,0xaf}, {0xf4,0x7a,0x7a,0x8e}, {0x47,0xae,0xae,0xe9}, {0x10,0x08,0x08,0x18}, + {0x6f,0xba,0xba,0xd5}, {0xf0,0x78,0x78,0x88}, {0x4a,0x25,0x25,0x6f}, {0x5c,0x2e,0x2e,0x72}, + {0x38,0x1c,0x1c,0x24}, {0x57,0xa6,0xa6,0xf1}, {0x73,0xb4,0xb4,0xc7}, {0x97,0xc6,0xc6,0x51}, + {0xcb,0xe8,0xe8,0x23}, {0xa1,0xdd,0xdd,0x7c}, {0xe8,0x74,0x74,0x9c}, {0x3e,0x1f,0x1f,0x21}, + {0x96,0x4b,0x4b,0xdd}, {0x61,0xbd,0xbd,0xdc}, {0x0d,0x8b,0x8b,0x86}, {0x0f,0x8a,0x8a,0x85}, + {0xe0,0x70,0x70,0x90}, {0x7c,0x3e,0x3e,0x42}, {0x71,0xb5,0xb5,0xc4}, {0xcc,0x66,0x66,0xaa}, + {0x90,0x48,0x48,0xd8}, {0x06,0x03,0x03,0x05}, {0xf7,0xf6,0xf6,0x01}, {0x1c,0x0e,0x0e,0x12}, + {0xc2,0x61,0x61,0xa3}, {0x6a,0x35,0x35,0x5f}, {0xae,0x57,0x57,0xf9}, {0x69,0xb9,0xb9,0xd0}, + {0x17,0x86,0x86,0x91}, {0x99,0xc1,0xc1,0x58}, {0x3a,0x1d,0x1d,0x27}, {0x27,0x9e,0x9e,0xb9}, + {0xd9,0xe1,0xe1,0x38}, {0xeb,0xf8,0xf8,0x13}, {0x2b,0x98,0x98,0xb3}, {0x22,0x11,0x11,0x33}, + {0xd2,0x69,0x69,0xbb}, {0xa9,0xd9,0xd9,0x70}, {0x07,0x8e,0x8e,0x89}, {0x33,0x94,0x94,0xa7}, + {0x2d,0x9b,0x9b,0xb6}, {0x3c,0x1e,0x1e,0x22}, {0x15,0x87,0x87,0x92}, {0xc9,0xe9,0xe9,0x20}, + {0x87,0xce,0xce,0x49}, {0xaa,0x55,0x55,0xff}, {0x50,0x28,0x28,0x78}, {0xa5,0xdf,0xdf,0x7a}, + {0x03,0x8c,0x8c,0x8f}, {0x59,0xa1,0xa1,0xf8}, {0x09,0x89,0x89,0x80}, {0x1a,0x0d,0x0d,0x17}, + {0x65,0xbf,0xbf,0xda}, {0xd7,0xe6,0xe6,0x31}, {0x84,0x42,0x42,0xc6}, {0xd0,0x68,0x68,0xb8}, + {0x82,0x41,0x41,0xc3}, {0x29,0x99,0x99,0xb0}, {0x5a,0x2d,0x2d,0x77}, {0x1e,0x0f,0x0f,0x11}, + {0x7b,0xb0,0xb0,0xcb}, {0xa8,0x54,0x54,0xfc}, {0x6d,0xbb,0xbb,0xd6}, {0x2c,0x16,0x16,0x3a} +}; + +static UINT8 T2[256][4]= +{ + {0xa5,0xc6,0x63,0x63}, {0x84,0xf8,0x7c,0x7c}, {0x99,0xee,0x77,0x77}, {0x8d,0xf6,0x7b,0x7b}, + {0x0d,0xff,0xf2,0xf2}, {0xbd,0xd6,0x6b,0x6b}, {0xb1,0xde,0x6f,0x6f}, {0x54,0x91,0xc5,0xc5}, + {0x50,0x60,0x30,0x30}, {0x03,0x02,0x01,0x01}, {0xa9,0xce,0x67,0x67}, {0x7d,0x56,0x2b,0x2b}, + {0x19,0xe7,0xfe,0xfe}, {0x62,0xb5,0xd7,0xd7}, {0xe6,0x4d,0xab,0xab}, {0x9a,0xec,0x76,0x76}, + {0x45,0x8f,0xca,0xca}, {0x9d,0x1f,0x82,0x82}, {0x40,0x89,0xc9,0xc9}, {0x87,0xfa,0x7d,0x7d}, + {0x15,0xef,0xfa,0xfa}, {0xeb,0xb2,0x59,0x59}, {0xc9,0x8e,0x47,0x47}, {0x0b,0xfb,0xf0,0xf0}, + {0xec,0x41,0xad,0xad}, {0x67,0xb3,0xd4,0xd4}, {0xfd,0x5f,0xa2,0xa2}, {0xea,0x45,0xaf,0xaf}, + {0xbf,0x23,0x9c,0x9c}, {0xf7,0x53,0xa4,0xa4}, {0x96,0xe4,0x72,0x72}, {0x5b,0x9b,0xc0,0xc0}, + {0xc2,0x75,0xb7,0xb7}, {0x1c,0xe1,0xfd,0xfd}, {0xae,0x3d,0x93,0x93}, {0x6a,0x4c,0x26,0x26}, + {0x5a,0x6c,0x36,0x36}, {0x41,0x7e,0x3f,0x3f}, {0x02,0xf5,0xf7,0xf7}, {0x4f,0x83,0xcc,0xcc}, + {0x5c,0x68,0x34,0x34}, {0xf4,0x51,0xa5,0xa5}, {0x34,0xd1,0xe5,0xe5}, {0x08,0xf9,0xf1,0xf1}, + {0x93,0xe2,0x71,0x71}, {0x73,0xab,0xd8,0xd8}, {0x53,0x62,0x31,0x31}, {0x3f,0x2a,0x15,0x15}, + {0x0c,0x08,0x04,0x04}, {0x52,0x95,0xc7,0xc7}, {0x65,0x46,0x23,0x23}, {0x5e,0x9d,0xc3,0xc3}, + {0x28,0x30,0x18,0x18}, {0xa1,0x37,0x96,0x96}, {0x0f,0x0a,0x05,0x05}, {0xb5,0x2f,0x9a,0x9a}, + {0x09,0x0e,0x07,0x07}, {0x36,0x24,0x12,0x12}, {0x9b,0x1b,0x80,0x80}, {0x3d,0xdf,0xe2,0xe2}, + {0x26,0xcd,0xeb,0xeb}, {0x69,0x4e,0x27,0x27}, {0xcd,0x7f,0xb2,0xb2}, {0x9f,0xea,0x75,0x75}, + {0x1b,0x12,0x09,0x09}, {0x9e,0x1d,0x83,0x83}, {0x74,0x58,0x2c,0x2c}, {0x2e,0x34,0x1a,0x1a}, + {0x2d,0x36,0x1b,0x1b}, {0xb2,0xdc,0x6e,0x6e}, {0xee,0xb4,0x5a,0x5a}, {0xfb,0x5b,0xa0,0xa0}, + {0xf6,0xa4,0x52,0x52}, {0x4d,0x76,0x3b,0x3b}, {0x61,0xb7,0xd6,0xd6}, {0xce,0x7d,0xb3,0xb3}, + {0x7b,0x52,0x29,0x29}, {0x3e,0xdd,0xe3,0xe3}, {0x71,0x5e,0x2f,0x2f}, {0x97,0x13,0x84,0x84}, + {0xf5,0xa6,0x53,0x53}, {0x68,0xb9,0xd1,0xd1}, {0x00,0x00,0x00,0x00}, {0x2c,0xc1,0xed,0xed}, + {0x60,0x40,0x20,0x20}, {0x1f,0xe3,0xfc,0xfc}, {0xc8,0x79,0xb1,0xb1}, {0xed,0xb6,0x5b,0x5b}, + {0xbe,0xd4,0x6a,0x6a}, {0x46,0x8d,0xcb,0xcb}, {0xd9,0x67,0xbe,0xbe}, {0x4b,0x72,0x39,0x39}, + {0xde,0x94,0x4a,0x4a}, {0xd4,0x98,0x4c,0x4c}, {0xe8,0xb0,0x58,0x58}, {0x4a,0x85,0xcf,0xcf}, + {0x6b,0xbb,0xd0,0xd0}, {0x2a,0xc5,0xef,0xef}, {0xe5,0x4f,0xaa,0xaa}, {0x16,0xed,0xfb,0xfb}, + {0xc5,0x86,0x43,0x43}, {0xd7,0x9a,0x4d,0x4d}, {0x55,0x66,0x33,0x33}, {0x94,0x11,0x85,0x85}, + {0xcf,0x8a,0x45,0x45}, {0x10,0xe9,0xf9,0xf9}, {0x06,0x04,0x02,0x02}, {0x81,0xfe,0x7f,0x7f}, + {0xf0,0xa0,0x50,0x50}, {0x44,0x78,0x3c,0x3c}, {0xba,0x25,0x9f,0x9f}, {0xe3,0x4b,0xa8,0xa8}, + {0xf3,0xa2,0x51,0x51}, {0xfe,0x5d,0xa3,0xa3}, {0xc0,0x80,0x40,0x40}, {0x8a,0x05,0x8f,0x8f}, + {0xad,0x3f,0x92,0x92}, {0xbc,0x21,0x9d,0x9d}, {0x48,0x70,0x38,0x38}, {0x04,0xf1,0xf5,0xf5}, + {0xdf,0x63,0xbc,0xbc}, {0xc1,0x77,0xb6,0xb6}, {0x75,0xaf,0xda,0xda}, {0x63,0x42,0x21,0x21}, + {0x30,0x20,0x10,0x10}, {0x1a,0xe5,0xff,0xff}, {0x0e,0xfd,0xf3,0xf3}, {0x6d,0xbf,0xd2,0xd2}, + {0x4c,0x81,0xcd,0xcd}, {0x14,0x18,0x0c,0x0c}, {0x35,0x26,0x13,0x13}, {0x2f,0xc3,0xec,0xec}, + {0xe1,0xbe,0x5f,0x5f}, {0xa2,0x35,0x97,0x97}, {0xcc,0x88,0x44,0x44}, {0x39,0x2e,0x17,0x17}, + {0x57,0x93,0xc4,0xc4}, {0xf2,0x55,0xa7,0xa7}, {0x82,0xfc,0x7e,0x7e}, {0x47,0x7a,0x3d,0x3d}, + {0xac,0xc8,0x64,0x64}, {0xe7,0xba,0x5d,0x5d}, {0x2b,0x32,0x19,0x19}, {0x95,0xe6,0x73,0x73}, + {0xa0,0xc0,0x60,0x60}, {0x98,0x19,0x81,0x81}, {0xd1,0x9e,0x4f,0x4f}, {0x7f,0xa3,0xdc,0xdc}, + {0x66,0x44,0x22,0x22}, {0x7e,0x54,0x2a,0x2a}, {0xab,0x3b,0x90,0x90}, {0x83,0x0b,0x88,0x88}, + {0xca,0x8c,0x46,0x46}, {0x29,0xc7,0xee,0xee}, {0xd3,0x6b,0xb8,0xb8}, {0x3c,0x28,0x14,0x14}, + {0x79,0xa7,0xde,0xde}, {0xe2,0xbc,0x5e,0x5e}, {0x1d,0x16,0x0b,0x0b}, {0x76,0xad,0xdb,0xdb}, + {0x3b,0xdb,0xe0,0xe0}, {0x56,0x64,0x32,0x32}, {0x4e,0x74,0x3a,0x3a}, {0x1e,0x14,0x0a,0x0a}, + {0xdb,0x92,0x49,0x49}, {0x0a,0x0c,0x06,0x06}, {0x6c,0x48,0x24,0x24}, {0xe4,0xb8,0x5c,0x5c}, + {0x5d,0x9f,0xc2,0xc2}, {0x6e,0xbd,0xd3,0xd3}, {0xef,0x43,0xac,0xac}, {0xa6,0xc4,0x62,0x62}, + {0xa8,0x39,0x91,0x91}, {0xa4,0x31,0x95,0x95}, {0x37,0xd3,0xe4,0xe4}, {0x8b,0xf2,0x79,0x79}, + {0x32,0xd5,0xe7,0xe7}, {0x43,0x8b,0xc8,0xc8}, {0x59,0x6e,0x37,0x37}, {0xb7,0xda,0x6d,0x6d}, + {0x8c,0x01,0x8d,0x8d}, {0x64,0xb1,0xd5,0xd5}, {0xd2,0x9c,0x4e,0x4e}, {0xe0,0x49,0xa9,0xa9}, + {0xb4,0xd8,0x6c,0x6c}, {0xfa,0xac,0x56,0x56}, {0x07,0xf3,0xf4,0xf4}, {0x25,0xcf,0xea,0xea}, + {0xaf,0xca,0x65,0x65}, {0x8e,0xf4,0x7a,0x7a}, {0xe9,0x47,0xae,0xae}, {0x18,0x10,0x08,0x08}, + {0xd5,0x6f,0xba,0xba}, {0x88,0xf0,0x78,0x78}, {0x6f,0x4a,0x25,0x25}, {0x72,0x5c,0x2e,0x2e}, + {0x24,0x38,0x1c,0x1c}, {0xf1,0x57,0xa6,0xa6}, {0xc7,0x73,0xb4,0xb4}, {0x51,0x97,0xc6,0xc6}, + {0x23,0xcb,0xe8,0xe8}, {0x7c,0xa1,0xdd,0xdd}, {0x9c,0xe8,0x74,0x74}, {0x21,0x3e,0x1f,0x1f}, + {0xdd,0x96,0x4b,0x4b}, {0xdc,0x61,0xbd,0xbd}, {0x86,0x0d,0x8b,0x8b}, {0x85,0x0f,0x8a,0x8a}, + {0x90,0xe0,0x70,0x70}, {0x42,0x7c,0x3e,0x3e}, {0xc4,0x71,0xb5,0xb5}, {0xaa,0xcc,0x66,0x66}, + {0xd8,0x90,0x48,0x48}, {0x05,0x06,0x03,0x03}, {0x01,0xf7,0xf6,0xf6}, {0x12,0x1c,0x0e,0x0e}, + {0xa3,0xc2,0x61,0x61}, {0x5f,0x6a,0x35,0x35}, {0xf9,0xae,0x57,0x57}, {0xd0,0x69,0xb9,0xb9}, + {0x91,0x17,0x86,0x86}, {0x58,0x99,0xc1,0xc1}, {0x27,0x3a,0x1d,0x1d}, {0xb9,0x27,0x9e,0x9e}, + {0x38,0xd9,0xe1,0xe1}, {0x13,0xeb,0xf8,0xf8}, {0xb3,0x2b,0x98,0x98}, {0x33,0x22,0x11,0x11}, + {0xbb,0xd2,0x69,0x69}, {0x70,0xa9,0xd9,0xd9}, {0x89,0x07,0x8e,0x8e}, {0xa7,0x33,0x94,0x94}, + {0xb6,0x2d,0x9b,0x9b}, {0x22,0x3c,0x1e,0x1e}, {0x92,0x15,0x87,0x87}, {0x20,0xc9,0xe9,0xe9}, + {0x49,0x87,0xce,0xce}, {0xff,0xaa,0x55,0x55}, {0x78,0x50,0x28,0x28}, {0x7a,0xa5,0xdf,0xdf}, + {0x8f,0x03,0x8c,0x8c}, {0xf8,0x59,0xa1,0xa1}, {0x80,0x09,0x89,0x89}, {0x17,0x1a,0x0d,0x0d}, + {0xda,0x65,0xbf,0xbf}, {0x31,0xd7,0xe6,0xe6}, {0xc6,0x84,0x42,0x42}, {0xb8,0xd0,0x68,0x68}, + {0xc3,0x82,0x41,0x41}, {0xb0,0x29,0x99,0x99}, {0x77,0x5a,0x2d,0x2d}, {0x11,0x1e,0x0f,0x0f}, + {0xcb,0x7b,0xb0,0xb0}, {0xfc,0xa8,0x54,0x54}, {0xd6,0x6d,0xbb,0xbb}, {0x3a,0x2c,0x16,0x16} +}; + +static UINT8 T3[256][4]= +{ + {0x63,0xa5,0xc6,0x63}, {0x7c,0x84,0xf8,0x7c}, {0x77,0x99,0xee,0x77}, {0x7b,0x8d,0xf6,0x7b}, + {0xf2,0x0d,0xff,0xf2}, {0x6b,0xbd,0xd6,0x6b}, {0x6f,0xb1,0xde,0x6f}, {0xc5,0x54,0x91,0xc5}, + {0x30,0x50,0x60,0x30}, {0x01,0x03,0x02,0x01}, {0x67,0xa9,0xce,0x67}, {0x2b,0x7d,0x56,0x2b}, + {0xfe,0x19,0xe7,0xfe}, {0xd7,0x62,0xb5,0xd7}, {0xab,0xe6,0x4d,0xab}, {0x76,0x9a,0xec,0x76}, + {0xca,0x45,0x8f,0xca}, {0x82,0x9d,0x1f,0x82}, {0xc9,0x40,0x89,0xc9}, {0x7d,0x87,0xfa,0x7d}, + {0xfa,0x15,0xef,0xfa}, {0x59,0xeb,0xb2,0x59}, {0x47,0xc9,0x8e,0x47}, {0xf0,0x0b,0xfb,0xf0}, + {0xad,0xec,0x41,0xad}, {0xd4,0x67,0xb3,0xd4}, {0xa2,0xfd,0x5f,0xa2}, {0xaf,0xea,0x45,0xaf}, + {0x9c,0xbf,0x23,0x9c}, {0xa4,0xf7,0x53,0xa4}, {0x72,0x96,0xe4,0x72}, {0xc0,0x5b,0x9b,0xc0}, + {0xb7,0xc2,0x75,0xb7}, {0xfd,0x1c,0xe1,0xfd}, {0x93,0xae,0x3d,0x93}, {0x26,0x6a,0x4c,0x26}, + {0x36,0x5a,0x6c,0x36}, {0x3f,0x41,0x7e,0x3f}, {0xf7,0x02,0xf5,0xf7}, {0xcc,0x4f,0x83,0xcc}, + {0x34,0x5c,0x68,0x34}, {0xa5,0xf4,0x51,0xa5}, {0xe5,0x34,0xd1,0xe5}, {0xf1,0x08,0xf9,0xf1}, + {0x71,0x93,0xe2,0x71}, {0xd8,0x73,0xab,0xd8}, {0x31,0x53,0x62,0x31}, {0x15,0x3f,0x2a,0x15}, + {0x04,0x0c,0x08,0x04}, {0xc7,0x52,0x95,0xc7}, {0x23,0x65,0x46,0x23}, {0xc3,0x5e,0x9d,0xc3}, + {0x18,0x28,0x30,0x18}, {0x96,0xa1,0x37,0x96}, {0x05,0x0f,0x0a,0x05}, {0x9a,0xb5,0x2f,0x9a}, + {0x07,0x09,0x0e,0x07}, {0x12,0x36,0x24,0x12}, {0x80,0x9b,0x1b,0x80}, {0xe2,0x3d,0xdf,0xe2}, + {0xeb,0x26,0xcd,0xeb}, {0x27,0x69,0x4e,0x27}, {0xb2,0xcd,0x7f,0xb2}, {0x75,0x9f,0xea,0x75}, + {0x09,0x1b,0x12,0x09}, {0x83,0x9e,0x1d,0x83}, {0x2c,0x74,0x58,0x2c}, {0x1a,0x2e,0x34,0x1a}, + {0x1b,0x2d,0x36,0x1b}, {0x6e,0xb2,0xdc,0x6e}, {0x5a,0xee,0xb4,0x5a}, {0xa0,0xfb,0x5b,0xa0}, + {0x52,0xf6,0xa4,0x52}, {0x3b,0x4d,0x76,0x3b}, {0xd6,0x61,0xb7,0xd6}, {0xb3,0xce,0x7d,0xb3}, + {0x29,0x7b,0x52,0x29}, {0xe3,0x3e,0xdd,0xe3}, {0x2f,0x71,0x5e,0x2f}, {0x84,0x97,0x13,0x84}, + {0x53,0xf5,0xa6,0x53}, {0xd1,0x68,0xb9,0xd1}, {0x00,0x00,0x00,0x00}, {0xed,0x2c,0xc1,0xed}, + {0x20,0x60,0x40,0x20}, {0xfc,0x1f,0xe3,0xfc}, {0xb1,0xc8,0x79,0xb1}, {0x5b,0xed,0xb6,0x5b}, + {0x6a,0xbe,0xd4,0x6a}, {0xcb,0x46,0x8d,0xcb}, {0xbe,0xd9,0x67,0xbe}, {0x39,0x4b,0x72,0x39}, + {0x4a,0xde,0x94,0x4a}, {0x4c,0xd4,0x98,0x4c}, {0x58,0xe8,0xb0,0x58}, {0xcf,0x4a,0x85,0xcf}, + {0xd0,0x6b,0xbb,0xd0}, {0xef,0x2a,0xc5,0xef}, {0xaa,0xe5,0x4f,0xaa}, {0xfb,0x16,0xed,0xfb}, + {0x43,0xc5,0x86,0x43}, {0x4d,0xd7,0x9a,0x4d}, {0x33,0x55,0x66,0x33}, {0x85,0x94,0x11,0x85}, + {0x45,0xcf,0x8a,0x45}, {0xf9,0x10,0xe9,0xf9}, {0x02,0x06,0x04,0x02}, {0x7f,0x81,0xfe,0x7f}, + {0x50,0xf0,0xa0,0x50}, {0x3c,0x44,0x78,0x3c}, {0x9f,0xba,0x25,0x9f}, {0xa8,0xe3,0x4b,0xa8}, + {0x51,0xf3,0xa2,0x51}, {0xa3,0xfe,0x5d,0xa3}, {0x40,0xc0,0x80,0x40}, {0x8f,0x8a,0x05,0x8f}, + {0x92,0xad,0x3f,0x92}, {0x9d,0xbc,0x21,0x9d}, {0x38,0x48,0x70,0x38}, {0xf5,0x04,0xf1,0xf5}, + {0xbc,0xdf,0x63,0xbc}, {0xb6,0xc1,0x77,0xb6}, {0xda,0x75,0xaf,0xda}, {0x21,0x63,0x42,0x21}, + {0x10,0x30,0x20,0x10}, {0xff,0x1a,0xe5,0xff}, {0xf3,0x0e,0xfd,0xf3}, {0xd2,0x6d,0xbf,0xd2}, + {0xcd,0x4c,0x81,0xcd}, {0x0c,0x14,0x18,0x0c}, {0x13,0x35,0x26,0x13}, {0xec,0x2f,0xc3,0xec}, + {0x5f,0xe1,0xbe,0x5f}, {0x97,0xa2,0x35,0x97}, {0x44,0xcc,0x88,0x44}, {0x17,0x39,0x2e,0x17}, + {0xc4,0x57,0x93,0xc4}, {0xa7,0xf2,0x55,0xa7}, {0x7e,0x82,0xfc,0x7e}, {0x3d,0x47,0x7a,0x3d}, + {0x64,0xac,0xc8,0x64}, {0x5d,0xe7,0xba,0x5d}, {0x19,0x2b,0x32,0x19}, {0x73,0x95,0xe6,0x73}, + {0x60,0xa0,0xc0,0x60}, {0x81,0x98,0x19,0x81}, {0x4f,0xd1,0x9e,0x4f}, {0xdc,0x7f,0xa3,0xdc}, + {0x22,0x66,0x44,0x22}, {0x2a,0x7e,0x54,0x2a}, {0x90,0xab,0x3b,0x90}, {0x88,0x83,0x0b,0x88}, + {0x46,0xca,0x8c,0x46}, {0xee,0x29,0xc7,0xee}, {0xb8,0xd3,0x6b,0xb8}, {0x14,0x3c,0x28,0x14}, + {0xde,0x79,0xa7,0xde}, {0x5e,0xe2,0xbc,0x5e}, {0x0b,0x1d,0x16,0x0b}, {0xdb,0x76,0xad,0xdb}, + {0xe0,0x3b,0xdb,0xe0}, {0x32,0x56,0x64,0x32}, {0x3a,0x4e,0x74,0x3a}, {0x0a,0x1e,0x14,0x0a}, + {0x49,0xdb,0x92,0x49}, {0x06,0x0a,0x0c,0x06}, {0x24,0x6c,0x48,0x24}, {0x5c,0xe4,0xb8,0x5c}, + {0xc2,0x5d,0x9f,0xc2}, {0xd3,0x6e,0xbd,0xd3}, {0xac,0xef,0x43,0xac}, {0x62,0xa6,0xc4,0x62}, + {0x91,0xa8,0x39,0x91}, {0x95,0xa4,0x31,0x95}, {0xe4,0x37,0xd3,0xe4}, {0x79,0x8b,0xf2,0x79}, + {0xe7,0x32,0xd5,0xe7}, {0xc8,0x43,0x8b,0xc8}, {0x37,0x59,0x6e,0x37}, {0x6d,0xb7,0xda,0x6d}, + {0x8d,0x8c,0x01,0x8d}, {0xd5,0x64,0xb1,0xd5}, {0x4e,0xd2,0x9c,0x4e}, {0xa9,0xe0,0x49,0xa9}, + {0x6c,0xb4,0xd8,0x6c}, {0x56,0xfa,0xac,0x56}, {0xf4,0x07,0xf3,0xf4}, {0xea,0x25,0xcf,0xea}, + {0x65,0xaf,0xca,0x65}, {0x7a,0x8e,0xf4,0x7a}, {0xae,0xe9,0x47,0xae}, {0x08,0x18,0x10,0x08}, + {0xba,0xd5,0x6f,0xba}, {0x78,0x88,0xf0,0x78}, {0x25,0x6f,0x4a,0x25}, {0x2e,0x72,0x5c,0x2e}, + {0x1c,0x24,0x38,0x1c}, {0xa6,0xf1,0x57,0xa6}, {0xb4,0xc7,0x73,0xb4}, {0xc6,0x51,0x97,0xc6}, + {0xe8,0x23,0xcb,0xe8}, {0xdd,0x7c,0xa1,0xdd}, {0x74,0x9c,0xe8,0x74}, {0x1f,0x21,0x3e,0x1f}, + {0x4b,0xdd,0x96,0x4b}, {0xbd,0xdc,0x61,0xbd}, {0x8b,0x86,0x0d,0x8b}, {0x8a,0x85,0x0f,0x8a}, + {0x70,0x90,0xe0,0x70}, {0x3e,0x42,0x7c,0x3e}, {0xb5,0xc4,0x71,0xb5}, {0x66,0xaa,0xcc,0x66}, + {0x48,0xd8,0x90,0x48}, {0x03,0x05,0x06,0x03}, {0xf6,0x01,0xf7,0xf6}, {0x0e,0x12,0x1c,0x0e}, + {0x61,0xa3,0xc2,0x61}, {0x35,0x5f,0x6a,0x35}, {0x57,0xf9,0xae,0x57}, {0xb9,0xd0,0x69,0xb9}, + {0x86,0x91,0x17,0x86}, {0xc1,0x58,0x99,0xc1}, {0x1d,0x27,0x3a,0x1d}, {0x9e,0xb9,0x27,0x9e}, + {0xe1,0x38,0xd9,0xe1}, {0xf8,0x13,0xeb,0xf8}, {0x98,0xb3,0x2b,0x98}, {0x11,0x33,0x22,0x11}, + {0x69,0xbb,0xd2,0x69}, {0xd9,0x70,0xa9,0xd9}, {0x8e,0x89,0x07,0x8e}, {0x94,0xa7,0x33,0x94}, + {0x9b,0xb6,0x2d,0x9b}, {0x1e,0x22,0x3c,0x1e}, {0x87,0x92,0x15,0x87}, {0xe9,0x20,0xc9,0xe9}, + {0xce,0x49,0x87,0xce}, {0x55,0xff,0xaa,0x55}, {0x28,0x78,0x50,0x28}, {0xdf,0x7a,0xa5,0xdf}, + {0x8c,0x8f,0x03,0x8c}, {0xa1,0xf8,0x59,0xa1}, {0x89,0x80,0x09,0x89}, {0x0d,0x17,0x1a,0x0d}, + {0xbf,0xda,0x65,0xbf}, {0xe6,0x31,0xd7,0xe6}, {0x42,0xc6,0x84,0x42}, {0x68,0xb8,0xd0,0x68}, + {0x41,0xc3,0x82,0x41}, {0x99,0xb0,0x29,0x99}, {0x2d,0x77,0x5a,0x2d}, {0x0f,0x11,0x1e,0x0f}, + {0xb0,0xcb,0x7b,0xb0}, {0x54,0xfc,0xa8,0x54}, {0xbb,0xd6,0x6d,0xbb}, {0x16,0x3a,0x2c,0x16} +}; + +static UINT8 T4[256][4]= +{ + {0x63,0x63,0xa5,0xc6}, {0x7c,0x7c,0x84,0xf8}, {0x77,0x77,0x99,0xee}, {0x7b,0x7b,0x8d,0xf6}, + {0xf2,0xf2,0x0d,0xff}, {0x6b,0x6b,0xbd,0xd6}, {0x6f,0x6f,0xb1,0xde}, {0xc5,0xc5,0x54,0x91}, + {0x30,0x30,0x50,0x60}, {0x01,0x01,0x03,0x02}, {0x67,0x67,0xa9,0xce}, {0x2b,0x2b,0x7d,0x56}, + {0xfe,0xfe,0x19,0xe7}, {0xd7,0xd7,0x62,0xb5}, {0xab,0xab,0xe6,0x4d}, {0x76,0x76,0x9a,0xec}, + {0xca,0xca,0x45,0x8f}, {0x82,0x82,0x9d,0x1f}, {0xc9,0xc9,0x40,0x89}, {0x7d,0x7d,0x87,0xfa}, + {0xfa,0xfa,0x15,0xef}, {0x59,0x59,0xeb,0xb2}, {0x47,0x47,0xc9,0x8e}, {0xf0,0xf0,0x0b,0xfb}, + {0xad,0xad,0xec,0x41}, {0xd4,0xd4,0x67,0xb3}, {0xa2,0xa2,0xfd,0x5f}, {0xaf,0xaf,0xea,0x45}, + {0x9c,0x9c,0xbf,0x23}, {0xa4,0xa4,0xf7,0x53}, {0x72,0x72,0x96,0xe4}, {0xc0,0xc0,0x5b,0x9b}, + {0xb7,0xb7,0xc2,0x75}, {0xfd,0xfd,0x1c,0xe1}, {0x93,0x93,0xae,0x3d}, {0x26,0x26,0x6a,0x4c}, + {0x36,0x36,0x5a,0x6c}, {0x3f,0x3f,0x41,0x7e}, {0xf7,0xf7,0x02,0xf5}, {0xcc,0xcc,0x4f,0x83}, + {0x34,0x34,0x5c,0x68}, {0xa5,0xa5,0xf4,0x51}, {0xe5,0xe5,0x34,0xd1}, {0xf1,0xf1,0x08,0xf9}, + {0x71,0x71,0x93,0xe2}, {0xd8,0xd8,0x73,0xab}, {0x31,0x31,0x53,0x62}, {0x15,0x15,0x3f,0x2a}, + {0x04,0x04,0x0c,0x08}, {0xc7,0xc7,0x52,0x95}, {0x23,0x23,0x65,0x46}, {0xc3,0xc3,0x5e,0x9d}, + {0x18,0x18,0x28,0x30}, {0x96,0x96,0xa1,0x37}, {0x05,0x05,0x0f,0x0a}, {0x9a,0x9a,0xb5,0x2f}, + {0x07,0x07,0x09,0x0e}, {0x12,0x12,0x36,0x24}, {0x80,0x80,0x9b,0x1b}, {0xe2,0xe2,0x3d,0xdf}, + {0xeb,0xeb,0x26,0xcd}, {0x27,0x27,0x69,0x4e}, {0xb2,0xb2,0xcd,0x7f}, {0x75,0x75,0x9f,0xea}, + {0x09,0x09,0x1b,0x12}, {0x83,0x83,0x9e,0x1d}, {0x2c,0x2c,0x74,0x58}, {0x1a,0x1a,0x2e,0x34}, + {0x1b,0x1b,0x2d,0x36}, {0x6e,0x6e,0xb2,0xdc}, {0x5a,0x5a,0xee,0xb4}, {0xa0,0xa0,0xfb,0x5b}, + {0x52,0x52,0xf6,0xa4}, {0x3b,0x3b,0x4d,0x76}, {0xd6,0xd6,0x61,0xb7}, {0xb3,0xb3,0xce,0x7d}, + {0x29,0x29,0x7b,0x52}, {0xe3,0xe3,0x3e,0xdd}, {0x2f,0x2f,0x71,0x5e}, {0x84,0x84,0x97,0x13}, + {0x53,0x53,0xf5,0xa6}, {0xd1,0xd1,0x68,0xb9}, {0x00,0x00,0x00,0x00}, {0xed,0xed,0x2c,0xc1}, + {0x20,0x20,0x60,0x40}, {0xfc,0xfc,0x1f,0xe3}, {0xb1,0xb1,0xc8,0x79}, {0x5b,0x5b,0xed,0xb6}, + {0x6a,0x6a,0xbe,0xd4}, {0xcb,0xcb,0x46,0x8d}, {0xbe,0xbe,0xd9,0x67}, {0x39,0x39,0x4b,0x72}, + {0x4a,0x4a,0xde,0x94}, {0x4c,0x4c,0xd4,0x98}, {0x58,0x58,0xe8,0xb0}, {0xcf,0xcf,0x4a,0x85}, + {0xd0,0xd0,0x6b,0xbb}, {0xef,0xef,0x2a,0xc5}, {0xaa,0xaa,0xe5,0x4f}, {0xfb,0xfb,0x16,0xed}, + {0x43,0x43,0xc5,0x86}, {0x4d,0x4d,0xd7,0x9a}, {0x33,0x33,0x55,0x66}, {0x85,0x85,0x94,0x11}, + {0x45,0x45,0xcf,0x8a}, {0xf9,0xf9,0x10,0xe9}, {0x02,0x02,0x06,0x04}, {0x7f,0x7f,0x81,0xfe}, + {0x50,0x50,0xf0,0xa0}, {0x3c,0x3c,0x44,0x78}, {0x9f,0x9f,0xba,0x25}, {0xa8,0xa8,0xe3,0x4b}, + {0x51,0x51,0xf3,0xa2}, {0xa3,0xa3,0xfe,0x5d}, {0x40,0x40,0xc0,0x80}, {0x8f,0x8f,0x8a,0x05}, + {0x92,0x92,0xad,0x3f}, {0x9d,0x9d,0xbc,0x21}, {0x38,0x38,0x48,0x70}, {0xf5,0xf5,0x04,0xf1}, + {0xbc,0xbc,0xdf,0x63}, {0xb6,0xb6,0xc1,0x77}, {0xda,0xda,0x75,0xaf}, {0x21,0x21,0x63,0x42}, + {0x10,0x10,0x30,0x20}, {0xff,0xff,0x1a,0xe5}, {0xf3,0xf3,0x0e,0xfd}, {0xd2,0xd2,0x6d,0xbf}, + {0xcd,0xcd,0x4c,0x81}, {0x0c,0x0c,0x14,0x18}, {0x13,0x13,0x35,0x26}, {0xec,0xec,0x2f,0xc3}, + {0x5f,0x5f,0xe1,0xbe}, {0x97,0x97,0xa2,0x35}, {0x44,0x44,0xcc,0x88}, {0x17,0x17,0x39,0x2e}, + {0xc4,0xc4,0x57,0x93}, {0xa7,0xa7,0xf2,0x55}, {0x7e,0x7e,0x82,0xfc}, {0x3d,0x3d,0x47,0x7a}, + {0x64,0x64,0xac,0xc8}, {0x5d,0x5d,0xe7,0xba}, {0x19,0x19,0x2b,0x32}, {0x73,0x73,0x95,0xe6}, + {0x60,0x60,0xa0,0xc0}, {0x81,0x81,0x98,0x19}, {0x4f,0x4f,0xd1,0x9e}, {0xdc,0xdc,0x7f,0xa3}, + {0x22,0x22,0x66,0x44}, {0x2a,0x2a,0x7e,0x54}, {0x90,0x90,0xab,0x3b}, {0x88,0x88,0x83,0x0b}, + {0x46,0x46,0xca,0x8c}, {0xee,0xee,0x29,0xc7}, {0xb8,0xb8,0xd3,0x6b}, {0x14,0x14,0x3c,0x28}, + {0xde,0xde,0x79,0xa7}, {0x5e,0x5e,0xe2,0xbc}, {0x0b,0x0b,0x1d,0x16}, {0xdb,0xdb,0x76,0xad}, + {0xe0,0xe0,0x3b,0xdb}, {0x32,0x32,0x56,0x64}, {0x3a,0x3a,0x4e,0x74}, {0x0a,0x0a,0x1e,0x14}, + {0x49,0x49,0xdb,0x92}, {0x06,0x06,0x0a,0x0c}, {0x24,0x24,0x6c,0x48}, {0x5c,0x5c,0xe4,0xb8}, + {0xc2,0xc2,0x5d,0x9f}, {0xd3,0xd3,0x6e,0xbd}, {0xac,0xac,0xef,0x43}, {0x62,0x62,0xa6,0xc4}, + {0x91,0x91,0xa8,0x39}, {0x95,0x95,0xa4,0x31}, {0xe4,0xe4,0x37,0xd3}, {0x79,0x79,0x8b,0xf2}, + {0xe7,0xe7,0x32,0xd5}, {0xc8,0xc8,0x43,0x8b}, {0x37,0x37,0x59,0x6e}, {0x6d,0x6d,0xb7,0xda}, + {0x8d,0x8d,0x8c,0x01}, {0xd5,0xd5,0x64,0xb1}, {0x4e,0x4e,0xd2,0x9c}, {0xa9,0xa9,0xe0,0x49}, + {0x6c,0x6c,0xb4,0xd8}, {0x56,0x56,0xfa,0xac}, {0xf4,0xf4,0x07,0xf3}, {0xea,0xea,0x25,0xcf}, + {0x65,0x65,0xaf,0xca}, {0x7a,0x7a,0x8e,0xf4}, {0xae,0xae,0xe9,0x47}, {0x08,0x08,0x18,0x10}, + {0xba,0xba,0xd5,0x6f}, {0x78,0x78,0x88,0xf0}, {0x25,0x25,0x6f,0x4a}, {0x2e,0x2e,0x72,0x5c}, + {0x1c,0x1c,0x24,0x38}, {0xa6,0xa6,0xf1,0x57}, {0xb4,0xb4,0xc7,0x73}, {0xc6,0xc6,0x51,0x97}, + {0xe8,0xe8,0x23,0xcb}, {0xdd,0xdd,0x7c,0xa1}, {0x74,0x74,0x9c,0xe8}, {0x1f,0x1f,0x21,0x3e}, + {0x4b,0x4b,0xdd,0x96}, {0xbd,0xbd,0xdc,0x61}, {0x8b,0x8b,0x86,0x0d}, {0x8a,0x8a,0x85,0x0f}, + {0x70,0x70,0x90,0xe0}, {0x3e,0x3e,0x42,0x7c}, {0xb5,0xb5,0xc4,0x71}, {0x66,0x66,0xaa,0xcc}, + {0x48,0x48,0xd8,0x90}, {0x03,0x03,0x05,0x06}, {0xf6,0xf6,0x01,0xf7}, {0x0e,0x0e,0x12,0x1c}, + {0x61,0x61,0xa3,0xc2}, {0x35,0x35,0x5f,0x6a}, {0x57,0x57,0xf9,0xae}, {0xb9,0xb9,0xd0,0x69}, + {0x86,0x86,0x91,0x17}, {0xc1,0xc1,0x58,0x99}, {0x1d,0x1d,0x27,0x3a}, {0x9e,0x9e,0xb9,0x27}, + {0xe1,0xe1,0x38,0xd9}, {0xf8,0xf8,0x13,0xeb}, {0x98,0x98,0xb3,0x2b}, {0x11,0x11,0x33,0x22}, + {0x69,0x69,0xbb,0xd2}, {0xd9,0xd9,0x70,0xa9}, {0x8e,0x8e,0x89,0x07}, {0x94,0x94,0xa7,0x33}, + {0x9b,0x9b,0xb6,0x2d}, {0x1e,0x1e,0x22,0x3c}, {0x87,0x87,0x92,0x15}, {0xe9,0xe9,0x20,0xc9}, + {0xce,0xce,0x49,0x87}, {0x55,0x55,0xff,0xaa}, {0x28,0x28,0x78,0x50}, {0xdf,0xdf,0x7a,0xa5}, + {0x8c,0x8c,0x8f,0x03}, {0xa1,0xa1,0xf8,0x59}, {0x89,0x89,0x80,0x09}, {0x0d,0x0d,0x17,0x1a}, + {0xbf,0xbf,0xda,0x65}, {0xe6,0xe6,0x31,0xd7}, {0x42,0x42,0xc6,0x84}, {0x68,0x68,0xb8,0xd0}, + {0x41,0x41,0xc3,0x82}, {0x99,0x99,0xb0,0x29}, {0x2d,0x2d,0x77,0x5a}, {0x0f,0x0f,0x11,0x1e}, + {0xb0,0xb0,0xcb,0x7b}, {0x54,0x54,0xfc,0xa8}, {0xbb,0xbb,0xd6,0x6d}, {0x16,0x16,0x3a,0x2c} +}; + +static UINT8 T5[256][4]= +{ + {0x51,0xf4,0xa7,0x50}, {0x7e,0x41,0x65,0x53}, {0x1a,0x17,0xa4,0xc3}, {0x3a,0x27,0x5e,0x96}, + {0x3b,0xab,0x6b,0xcb}, {0x1f,0x9d,0x45,0xf1}, {0xac,0xfa,0x58,0xab}, {0x4b,0xe3,0x03,0x93}, + {0x20,0x30,0xfa,0x55}, {0xad,0x76,0x6d,0xf6}, {0x88,0xcc,0x76,0x91}, {0xf5,0x02,0x4c,0x25}, + {0x4f,0xe5,0xd7,0xfc}, {0xc5,0x2a,0xcb,0xd7}, {0x26,0x35,0x44,0x80}, {0xb5,0x62,0xa3,0x8f}, + {0xde,0xb1,0x5a,0x49}, {0x25,0xba,0x1b,0x67}, {0x45,0xea,0x0e,0x98}, {0x5d,0xfe,0xc0,0xe1}, + {0xc3,0x2f,0x75,0x02}, {0x81,0x4c,0xf0,0x12}, {0x8d,0x46,0x97,0xa3}, {0x6b,0xd3,0xf9,0xc6}, + {0x03,0x8f,0x5f,0xe7}, {0x15,0x92,0x9c,0x95}, {0xbf,0x6d,0x7a,0xeb}, {0x95,0x52,0x59,0xda}, + {0xd4,0xbe,0x83,0x2d}, {0x58,0x74,0x21,0xd3}, {0x49,0xe0,0x69,0x29}, {0x8e,0xc9,0xc8,0x44}, + {0x75,0xc2,0x89,0x6a}, {0xf4,0x8e,0x79,0x78}, {0x99,0x58,0x3e,0x6b}, {0x27,0xb9,0x71,0xdd}, + {0xbe,0xe1,0x4f,0xb6}, {0xf0,0x88,0xad,0x17}, {0xc9,0x20,0xac,0x66}, {0x7d,0xce,0x3a,0xb4}, + {0x63,0xdf,0x4a,0x18}, {0xe5,0x1a,0x31,0x82}, {0x97,0x51,0x33,0x60}, {0x62,0x53,0x7f,0x45}, + {0xb1,0x64,0x77,0xe0}, {0xbb,0x6b,0xae,0x84}, {0xfe,0x81,0xa0,0x1c}, {0xf9,0x08,0x2b,0x94}, + {0x70,0x48,0x68,0x58}, {0x8f,0x45,0xfd,0x19}, {0x94,0xde,0x6c,0x87}, {0x52,0x7b,0xf8,0xb7}, + {0xab,0x73,0xd3,0x23}, {0x72,0x4b,0x02,0xe2}, {0xe3,0x1f,0x8f,0x57}, {0x66,0x55,0xab,0x2a}, + {0xb2,0xeb,0x28,0x07}, {0x2f,0xb5,0xc2,0x03}, {0x86,0xc5,0x7b,0x9a}, {0xd3,0x37,0x08,0xa5}, + {0x30,0x28,0x87,0xf2}, {0x23,0xbf,0xa5,0xb2}, {0x02,0x03,0x6a,0xba}, {0xed,0x16,0x82,0x5c}, + {0x8a,0xcf,0x1c,0x2b}, {0xa7,0x79,0xb4,0x92}, {0xf3,0x07,0xf2,0xf0}, {0x4e,0x69,0xe2,0xa1}, + {0x65,0xda,0xf4,0xcd}, {0x06,0x05,0xbe,0xd5}, {0xd1,0x34,0x62,0x1f}, {0xc4,0xa6,0xfe,0x8a}, + {0x34,0x2e,0x53,0x9d}, {0xa2,0xf3,0x55,0xa0}, {0x05,0x8a,0xe1,0x32}, {0xa4,0xf6,0xeb,0x75}, + {0x0b,0x83,0xec,0x39}, {0x40,0x60,0xef,0xaa}, {0x5e,0x71,0x9f,0x06}, {0xbd,0x6e,0x10,0x51}, + {0x3e,0x21,0x8a,0xf9}, {0x96,0xdd,0x06,0x3d}, {0xdd,0x3e,0x05,0xae}, {0x4d,0xe6,0xbd,0x46}, + {0x91,0x54,0x8d,0xb5}, {0x71,0xc4,0x5d,0x05}, {0x04,0x06,0xd4,0x6f}, {0x60,0x50,0x15,0xff}, + {0x19,0x98,0xfb,0x24}, {0xd6,0xbd,0xe9,0x97}, {0x89,0x40,0x43,0xcc}, {0x67,0xd9,0x9e,0x77}, + {0xb0,0xe8,0x42,0xbd}, {0x07,0x89,0x8b,0x88}, {0xe7,0x19,0x5b,0x38}, {0x79,0xc8,0xee,0xdb}, + {0xa1,0x7c,0x0a,0x47}, {0x7c,0x42,0x0f,0xe9}, {0xf8,0x84,0x1e,0xc9}, {0x00,0x00,0x00,0x00}, + {0x09,0x80,0x86,0x83}, {0x32,0x2b,0xed,0x48}, {0x1e,0x11,0x70,0xac}, {0x6c,0x5a,0x72,0x4e}, + {0xfd,0x0e,0xff,0xfb}, {0x0f,0x85,0x38,0x56}, {0x3d,0xae,0xd5,0x1e}, {0x36,0x2d,0x39,0x27}, + {0x0a,0x0f,0xd9,0x64}, {0x68,0x5c,0xa6,0x21}, {0x9b,0x5b,0x54,0xd1}, {0x24,0x36,0x2e,0x3a}, + {0x0c,0x0a,0x67,0xb1}, {0x93,0x57,0xe7,0x0f}, {0xb4,0xee,0x96,0xd2}, {0x1b,0x9b,0x91,0x9e}, + {0x80,0xc0,0xc5,0x4f}, {0x61,0xdc,0x20,0xa2}, {0x5a,0x77,0x4b,0x69}, {0x1c,0x12,0x1a,0x16}, + {0xe2,0x93,0xba,0x0a}, {0xc0,0xa0,0x2a,0xe5}, {0x3c,0x22,0xe0,0x43}, {0x12,0x1b,0x17,0x1d}, + {0x0e,0x09,0x0d,0x0b}, {0xf2,0x8b,0xc7,0xad}, {0x2d,0xb6,0xa8,0xb9}, {0x14,0x1e,0xa9,0xc8}, + {0x57,0xf1,0x19,0x85}, {0xaf,0x75,0x07,0x4c}, {0xee,0x99,0xdd,0xbb}, {0xa3,0x7f,0x60,0xfd}, + {0xf7,0x01,0x26,0x9f}, {0x5c,0x72,0xf5,0xbc}, {0x44,0x66,0x3b,0xc5}, {0x5b,0xfb,0x7e,0x34}, + {0x8b,0x43,0x29,0x76}, {0xcb,0x23,0xc6,0xdc}, {0xb6,0xed,0xfc,0x68}, {0xb8,0xe4,0xf1,0x63}, + {0xd7,0x31,0xdc,0xca}, {0x42,0x63,0x85,0x10}, {0x13,0x97,0x22,0x40}, {0x84,0xc6,0x11,0x20}, + {0x85,0x4a,0x24,0x7d}, {0xd2,0xbb,0x3d,0xf8}, {0xae,0xf9,0x32,0x11}, {0xc7,0x29,0xa1,0x6d}, + {0x1d,0x9e,0x2f,0x4b}, {0xdc,0xb2,0x30,0xf3}, {0x0d,0x86,0x52,0xec}, {0x77,0xc1,0xe3,0xd0}, + {0x2b,0xb3,0x16,0x6c}, {0xa9,0x70,0xb9,0x99}, {0x11,0x94,0x48,0xfa}, {0x47,0xe9,0x64,0x22}, + {0xa8,0xfc,0x8c,0xc4}, {0xa0,0xf0,0x3f,0x1a}, {0x56,0x7d,0x2c,0xd8}, {0x22,0x33,0x90,0xef}, + {0x87,0x49,0x4e,0xc7}, {0xd9,0x38,0xd1,0xc1}, {0x8c,0xca,0xa2,0xfe}, {0x98,0xd4,0x0b,0x36}, + {0xa6,0xf5,0x81,0xcf}, {0xa5,0x7a,0xde,0x28}, {0xda,0xb7,0x8e,0x26}, {0x3f,0xad,0xbf,0xa4}, + {0x2c,0x3a,0x9d,0xe4}, {0x50,0x78,0x92,0x0d}, {0x6a,0x5f,0xcc,0x9b}, {0x54,0x7e,0x46,0x62}, + {0xf6,0x8d,0x13,0xc2}, {0x90,0xd8,0xb8,0xe8}, {0x2e,0x39,0xf7,0x5e}, {0x82,0xc3,0xaf,0xf5}, + {0x9f,0x5d,0x80,0xbe}, {0x69,0xd0,0x93,0x7c}, {0x6f,0xd5,0x2d,0xa9}, {0xcf,0x25,0x12,0xb3}, + {0xc8,0xac,0x99,0x3b}, {0x10,0x18,0x7d,0xa7}, {0xe8,0x9c,0x63,0x6e}, {0xdb,0x3b,0xbb,0x7b}, + {0xcd,0x26,0x78,0x09}, {0x6e,0x59,0x18,0xf4}, {0xec,0x9a,0xb7,0x01}, {0x83,0x4f,0x9a,0xa8}, + {0xe6,0x95,0x6e,0x65}, {0xaa,0xff,0xe6,0x7e}, {0x21,0xbc,0xcf,0x08}, {0xef,0x15,0xe8,0xe6}, + {0xba,0xe7,0x9b,0xd9}, {0x4a,0x6f,0x36,0xce}, {0xea,0x9f,0x09,0xd4}, {0x29,0xb0,0x7c,0xd6}, + {0x31,0xa4,0xb2,0xaf}, {0x2a,0x3f,0x23,0x31}, {0xc6,0xa5,0x94,0x30}, {0x35,0xa2,0x66,0xc0}, + {0x74,0x4e,0xbc,0x37}, {0xfc,0x82,0xca,0xa6}, {0xe0,0x90,0xd0,0xb0}, {0x33,0xa7,0xd8,0x15}, + {0xf1,0x04,0x98,0x4a}, {0x41,0xec,0xda,0xf7}, {0x7f,0xcd,0x50,0x0e}, {0x17,0x91,0xf6,0x2f}, + {0x76,0x4d,0xd6,0x8d}, {0x43,0xef,0xb0,0x4d}, {0xcc,0xaa,0x4d,0x54}, {0xe4,0x96,0x04,0xdf}, + {0x9e,0xd1,0xb5,0xe3}, {0x4c,0x6a,0x88,0x1b}, {0xc1,0x2c,0x1f,0xb8}, {0x46,0x65,0x51,0x7f}, + {0x9d,0x5e,0xea,0x04}, {0x01,0x8c,0x35,0x5d}, {0xfa,0x87,0x74,0x73}, {0xfb,0x0b,0x41,0x2e}, + {0xb3,0x67,0x1d,0x5a}, {0x92,0xdb,0xd2,0x52}, {0xe9,0x10,0x56,0x33}, {0x6d,0xd6,0x47,0x13}, + {0x9a,0xd7,0x61,0x8c}, {0x37,0xa1,0x0c,0x7a}, {0x59,0xf8,0x14,0x8e}, {0xeb,0x13,0x3c,0x89}, + {0xce,0xa9,0x27,0xee}, {0xb7,0x61,0xc9,0x35}, {0xe1,0x1c,0xe5,0xed}, {0x7a,0x47,0xb1,0x3c}, + {0x9c,0xd2,0xdf,0x59}, {0x55,0xf2,0x73,0x3f}, {0x18,0x14,0xce,0x79}, {0x73,0xc7,0x37,0xbf}, + {0x53,0xf7,0xcd,0xea}, {0x5f,0xfd,0xaa,0x5b}, {0xdf,0x3d,0x6f,0x14}, {0x78,0x44,0xdb,0x86}, + {0xca,0xaf,0xf3,0x81}, {0xb9,0x68,0xc4,0x3e}, {0x38,0x24,0x34,0x2c}, {0xc2,0xa3,0x40,0x5f}, + {0x16,0x1d,0xc3,0x72}, {0xbc,0xe2,0x25,0x0c}, {0x28,0x3c,0x49,0x8b}, {0xff,0x0d,0x95,0x41}, + {0x39,0xa8,0x01,0x71}, {0x08,0x0c,0xb3,0xde}, {0xd8,0xb4,0xe4,0x9c}, {0x64,0x56,0xc1,0x90}, + {0x7b,0xcb,0x84,0x61}, {0xd5,0x32,0xb6,0x70}, {0x48,0x6c,0x5c,0x74}, {0xd0,0xb8,0x57,0x42} +}; + +static UINT8 T6[256][4]= +{ + {0x50,0x51,0xf4,0xa7}, {0x53,0x7e,0x41,0x65}, {0xc3,0x1a,0x17,0xa4}, {0x96,0x3a,0x27,0x5e}, + {0xcb,0x3b,0xab,0x6b}, {0xf1,0x1f,0x9d,0x45}, {0xab,0xac,0xfa,0x58}, {0x93,0x4b,0xe3,0x03}, + {0x55,0x20,0x30,0xfa}, {0xf6,0xad,0x76,0x6d}, {0x91,0x88,0xcc,0x76}, {0x25,0xf5,0x02,0x4c}, + {0xfc,0x4f,0xe5,0xd7}, {0xd7,0xc5,0x2a,0xcb}, {0x80,0x26,0x35,0x44}, {0x8f,0xb5,0x62,0xa3}, + {0x49,0xde,0xb1,0x5a}, {0x67,0x25,0xba,0x1b}, {0x98,0x45,0xea,0x0e}, {0xe1,0x5d,0xfe,0xc0}, + {0x02,0xc3,0x2f,0x75}, {0x12,0x81,0x4c,0xf0}, {0xa3,0x8d,0x46,0x97}, {0xc6,0x6b,0xd3,0xf9}, + {0xe7,0x03,0x8f,0x5f}, {0x95,0x15,0x92,0x9c}, {0xeb,0xbf,0x6d,0x7a}, {0xda,0x95,0x52,0x59}, + {0x2d,0xd4,0xbe,0x83}, {0xd3,0x58,0x74,0x21}, {0x29,0x49,0xe0,0x69}, {0x44,0x8e,0xc9,0xc8}, + {0x6a,0x75,0xc2,0x89}, {0x78,0xf4,0x8e,0x79}, {0x6b,0x99,0x58,0x3e}, {0xdd,0x27,0xb9,0x71}, + {0xb6,0xbe,0xe1,0x4f}, {0x17,0xf0,0x88,0xad}, {0x66,0xc9,0x20,0xac}, {0xb4,0x7d,0xce,0x3a}, + {0x18,0x63,0xdf,0x4a}, {0x82,0xe5,0x1a,0x31}, {0x60,0x97,0x51,0x33}, {0x45,0x62,0x53,0x7f}, + {0xe0,0xb1,0x64,0x77}, {0x84,0xbb,0x6b,0xae}, {0x1c,0xfe,0x81,0xa0}, {0x94,0xf9,0x08,0x2b}, + {0x58,0x70,0x48,0x68}, {0x19,0x8f,0x45,0xfd}, {0x87,0x94,0xde,0x6c}, {0xb7,0x52,0x7b,0xf8}, + {0x23,0xab,0x73,0xd3}, {0xe2,0x72,0x4b,0x02}, {0x57,0xe3,0x1f,0x8f}, {0x2a,0x66,0x55,0xab}, + {0x07,0xb2,0xeb,0x28}, {0x03,0x2f,0xb5,0xc2}, {0x9a,0x86,0xc5,0x7b}, {0xa5,0xd3,0x37,0x08}, + {0xf2,0x30,0x28,0x87}, {0xb2,0x23,0xbf,0xa5}, {0xba,0x02,0x03,0x6a}, {0x5c,0xed,0x16,0x82}, + {0x2b,0x8a,0xcf,0x1c}, {0x92,0xa7,0x79,0xb4}, {0xf0,0xf3,0x07,0xf2}, {0xa1,0x4e,0x69,0xe2}, + {0xcd,0x65,0xda,0xf4}, {0xd5,0x06,0x05,0xbe}, {0x1f,0xd1,0x34,0x62}, {0x8a,0xc4,0xa6,0xfe}, + {0x9d,0x34,0x2e,0x53}, {0xa0,0xa2,0xf3,0x55}, {0x32,0x05,0x8a,0xe1}, {0x75,0xa4,0xf6,0xeb}, + {0x39,0x0b,0x83,0xec}, {0xaa,0x40,0x60,0xef}, {0x06,0x5e,0x71,0x9f}, {0x51,0xbd,0x6e,0x10}, + {0xf9,0x3e,0x21,0x8a}, {0x3d,0x96,0xdd,0x06}, {0xae,0xdd,0x3e,0x05}, {0x46,0x4d,0xe6,0xbd}, + {0xb5,0x91,0x54,0x8d}, {0x05,0x71,0xc4,0x5d}, {0x6f,0x04,0x06,0xd4}, {0xff,0x60,0x50,0x15}, + {0x24,0x19,0x98,0xfb}, {0x97,0xd6,0xbd,0xe9}, {0xcc,0x89,0x40,0x43}, {0x77,0x67,0xd9,0x9e}, + {0xbd,0xb0,0xe8,0x42}, {0x88,0x07,0x89,0x8b}, {0x38,0xe7,0x19,0x5b}, {0xdb,0x79,0xc8,0xee}, + {0x47,0xa1,0x7c,0x0a}, {0xe9,0x7c,0x42,0x0f}, {0xc9,0xf8,0x84,0x1e}, {0x00,0x00,0x00,0x00}, + {0x83,0x09,0x80,0x86}, {0x48,0x32,0x2b,0xed}, {0xac,0x1e,0x11,0x70}, {0x4e,0x6c,0x5a,0x72}, + {0xfb,0xfd,0x0e,0xff}, {0x56,0x0f,0x85,0x38}, {0x1e,0x3d,0xae,0xd5}, {0x27,0x36,0x2d,0x39}, + {0x64,0x0a,0x0f,0xd9}, {0x21,0x68,0x5c,0xa6}, {0xd1,0x9b,0x5b,0x54}, {0x3a,0x24,0x36,0x2e}, + {0xb1,0x0c,0x0a,0x67}, {0x0f,0x93,0x57,0xe7}, {0xd2,0xb4,0xee,0x96}, {0x9e,0x1b,0x9b,0x91}, + {0x4f,0x80,0xc0,0xc5}, {0xa2,0x61,0xdc,0x20}, {0x69,0x5a,0x77,0x4b}, {0x16,0x1c,0x12,0x1a}, + {0x0a,0xe2,0x93,0xba}, {0xe5,0xc0,0xa0,0x2a}, {0x43,0x3c,0x22,0xe0}, {0x1d,0x12,0x1b,0x17}, + {0x0b,0x0e,0x09,0x0d}, {0xad,0xf2,0x8b,0xc7}, {0xb9,0x2d,0xb6,0xa8}, {0xc8,0x14,0x1e,0xa9}, + {0x85,0x57,0xf1,0x19}, {0x4c,0xaf,0x75,0x07}, {0xbb,0xee,0x99,0xdd}, {0xfd,0xa3,0x7f,0x60}, + {0x9f,0xf7,0x01,0x26}, {0xbc,0x5c,0x72,0xf5}, {0xc5,0x44,0x66,0x3b}, {0x34,0x5b,0xfb,0x7e}, + {0x76,0x8b,0x43,0x29}, {0xdc,0xcb,0x23,0xc6}, {0x68,0xb6,0xed,0xfc}, {0x63,0xb8,0xe4,0xf1}, + {0xca,0xd7,0x31,0xdc}, {0x10,0x42,0x63,0x85}, {0x40,0x13,0x97,0x22}, {0x20,0x84,0xc6,0x11}, + {0x7d,0x85,0x4a,0x24}, {0xf8,0xd2,0xbb,0x3d}, {0x11,0xae,0xf9,0x32}, {0x6d,0xc7,0x29,0xa1}, + {0x4b,0x1d,0x9e,0x2f}, {0xf3,0xdc,0xb2,0x30}, {0xec,0x0d,0x86,0x52}, {0xd0,0x77,0xc1,0xe3}, + {0x6c,0x2b,0xb3,0x16}, {0x99,0xa9,0x70,0xb9}, {0xfa,0x11,0x94,0x48}, {0x22,0x47,0xe9,0x64}, + {0xc4,0xa8,0xfc,0x8c}, {0x1a,0xa0,0xf0,0x3f}, {0xd8,0x56,0x7d,0x2c}, {0xef,0x22,0x33,0x90}, + {0xc7,0x87,0x49,0x4e}, {0xc1,0xd9,0x38,0xd1}, {0xfe,0x8c,0xca,0xa2}, {0x36,0x98,0xd4,0x0b}, + {0xcf,0xa6,0xf5,0x81}, {0x28,0xa5,0x7a,0xde}, {0x26,0xda,0xb7,0x8e}, {0xa4,0x3f,0xad,0xbf}, + {0xe4,0x2c,0x3a,0x9d}, {0x0d,0x50,0x78,0x92}, {0x9b,0x6a,0x5f,0xcc}, {0x62,0x54,0x7e,0x46}, + {0xc2,0xf6,0x8d,0x13}, {0xe8,0x90,0xd8,0xb8}, {0x5e,0x2e,0x39,0xf7}, {0xf5,0x82,0xc3,0xaf}, + {0xbe,0x9f,0x5d,0x80}, {0x7c,0x69,0xd0,0x93}, {0xa9,0x6f,0xd5,0x2d}, {0xb3,0xcf,0x25,0x12}, + {0x3b,0xc8,0xac,0x99}, {0xa7,0x10,0x18,0x7d}, {0x6e,0xe8,0x9c,0x63}, {0x7b,0xdb,0x3b,0xbb}, + {0x09,0xcd,0x26,0x78}, {0xf4,0x6e,0x59,0x18}, {0x01,0xec,0x9a,0xb7}, {0xa8,0x83,0x4f,0x9a}, + {0x65,0xe6,0x95,0x6e}, {0x7e,0xaa,0xff,0xe6}, {0x08,0x21,0xbc,0xcf}, {0xe6,0xef,0x15,0xe8}, + {0xd9,0xba,0xe7,0x9b}, {0xce,0x4a,0x6f,0x36}, {0xd4,0xea,0x9f,0x09}, {0xd6,0x29,0xb0,0x7c}, + {0xaf,0x31,0xa4,0xb2}, {0x31,0x2a,0x3f,0x23}, {0x30,0xc6,0xa5,0x94}, {0xc0,0x35,0xa2,0x66}, + {0x37,0x74,0x4e,0xbc}, {0xa6,0xfc,0x82,0xca}, {0xb0,0xe0,0x90,0xd0}, {0x15,0x33,0xa7,0xd8}, + {0x4a,0xf1,0x04,0x98}, {0xf7,0x41,0xec,0xda}, {0x0e,0x7f,0xcd,0x50}, {0x2f,0x17,0x91,0xf6}, + {0x8d,0x76,0x4d,0xd6}, {0x4d,0x43,0xef,0xb0}, {0x54,0xcc,0xaa,0x4d}, {0xdf,0xe4,0x96,0x04}, + {0xe3,0x9e,0xd1,0xb5}, {0x1b,0x4c,0x6a,0x88}, {0xb8,0xc1,0x2c,0x1f}, {0x7f,0x46,0x65,0x51}, + {0x04,0x9d,0x5e,0xea}, {0x5d,0x01,0x8c,0x35}, {0x73,0xfa,0x87,0x74}, {0x2e,0xfb,0x0b,0x41}, + {0x5a,0xb3,0x67,0x1d}, {0x52,0x92,0xdb,0xd2}, {0x33,0xe9,0x10,0x56}, {0x13,0x6d,0xd6,0x47}, + {0x8c,0x9a,0xd7,0x61}, {0x7a,0x37,0xa1,0x0c}, {0x8e,0x59,0xf8,0x14}, {0x89,0xeb,0x13,0x3c}, + {0xee,0xce,0xa9,0x27}, {0x35,0xb7,0x61,0xc9}, {0xed,0xe1,0x1c,0xe5}, {0x3c,0x7a,0x47,0xb1}, + {0x59,0x9c,0xd2,0xdf}, {0x3f,0x55,0xf2,0x73}, {0x79,0x18,0x14,0xce}, {0xbf,0x73,0xc7,0x37}, + {0xea,0x53,0xf7,0xcd}, {0x5b,0x5f,0xfd,0xaa}, {0x14,0xdf,0x3d,0x6f}, {0x86,0x78,0x44,0xdb}, + {0x81,0xca,0xaf,0xf3}, {0x3e,0xb9,0x68,0xc4}, {0x2c,0x38,0x24,0x34}, {0x5f,0xc2,0xa3,0x40}, + {0x72,0x16,0x1d,0xc3}, {0x0c,0xbc,0xe2,0x25}, {0x8b,0x28,0x3c,0x49}, {0x41,0xff,0x0d,0x95}, + {0x71,0x39,0xa8,0x01}, {0xde,0x08,0x0c,0xb3}, {0x9c,0xd8,0xb4,0xe4}, {0x90,0x64,0x56,0xc1}, + {0x61,0x7b,0xcb,0x84}, {0x70,0xd5,0x32,0xb6}, {0x74,0x48,0x6c,0x5c}, {0x42,0xd0,0xb8,0x57} +}; + +static UINT8 T7[256][4]= +{ + {0xa7,0x50,0x51,0xf4}, {0x65,0x53,0x7e,0x41}, {0xa4,0xc3,0x1a,0x17}, {0x5e,0x96,0x3a,0x27}, + {0x6b,0xcb,0x3b,0xab}, {0x45,0xf1,0x1f,0x9d}, {0x58,0xab,0xac,0xfa}, {0x03,0x93,0x4b,0xe3}, + {0xfa,0x55,0x20,0x30}, {0x6d,0xf6,0xad,0x76}, {0x76,0x91,0x88,0xcc}, {0x4c,0x25,0xf5,0x02}, + {0xd7,0xfc,0x4f,0xe5}, {0xcb,0xd7,0xc5,0x2a}, {0x44,0x80,0x26,0x35}, {0xa3,0x8f,0xb5,0x62}, + {0x5a,0x49,0xde,0xb1}, {0x1b,0x67,0x25,0xba}, {0x0e,0x98,0x45,0xea}, {0xc0,0xe1,0x5d,0xfe}, + {0x75,0x02,0xc3,0x2f}, {0xf0,0x12,0x81,0x4c}, {0x97,0xa3,0x8d,0x46}, {0xf9,0xc6,0x6b,0xd3}, + {0x5f,0xe7,0x03,0x8f}, {0x9c,0x95,0x15,0x92}, {0x7a,0xeb,0xbf,0x6d}, {0x59,0xda,0x95,0x52}, + {0x83,0x2d,0xd4,0xbe}, {0x21,0xd3,0x58,0x74}, {0x69,0x29,0x49,0xe0}, {0xc8,0x44,0x8e,0xc9}, + {0x89,0x6a,0x75,0xc2}, {0x79,0x78,0xf4,0x8e}, {0x3e,0x6b,0x99,0x58}, {0x71,0xdd,0x27,0xb9}, + {0x4f,0xb6,0xbe,0xe1}, {0xad,0x17,0xf0,0x88}, {0xac,0x66,0xc9,0x20}, {0x3a,0xb4,0x7d,0xce}, + {0x4a,0x18,0x63,0xdf}, {0x31,0x82,0xe5,0x1a}, {0x33,0x60,0x97,0x51}, {0x7f,0x45,0x62,0x53}, + {0x77,0xe0,0xb1,0x64}, {0xae,0x84,0xbb,0x6b}, {0xa0,0x1c,0xfe,0x81}, {0x2b,0x94,0xf9,0x08}, + {0x68,0x58,0x70,0x48}, {0xfd,0x19,0x8f,0x45}, {0x6c,0x87,0x94,0xde}, {0xf8,0xb7,0x52,0x7b}, + {0xd3,0x23,0xab,0x73}, {0x02,0xe2,0x72,0x4b}, {0x8f,0x57,0xe3,0x1f}, {0xab,0x2a,0x66,0x55}, + {0x28,0x07,0xb2,0xeb}, {0xc2,0x03,0x2f,0xb5}, {0x7b,0x9a,0x86,0xc5}, {0x08,0xa5,0xd3,0x37}, + {0x87,0xf2,0x30,0x28}, {0xa5,0xb2,0x23,0xbf}, {0x6a,0xba,0x02,0x03}, {0x82,0x5c,0xed,0x16}, + {0x1c,0x2b,0x8a,0xcf}, {0xb4,0x92,0xa7,0x79}, {0xf2,0xf0,0xf3,0x07}, {0xe2,0xa1,0x4e,0x69}, + {0xf4,0xcd,0x65,0xda}, {0xbe,0xd5,0x06,0x05}, {0x62,0x1f,0xd1,0x34}, {0xfe,0x8a,0xc4,0xa6}, + {0x53,0x9d,0x34,0x2e}, {0x55,0xa0,0xa2,0xf3}, {0xe1,0x32,0x05,0x8a}, {0xeb,0x75,0xa4,0xf6}, + {0xec,0x39,0x0b,0x83}, {0xef,0xaa,0x40,0x60}, {0x9f,0x06,0x5e,0x71}, {0x10,0x51,0xbd,0x6e}, + {0x8a,0xf9,0x3e,0x21}, {0x06,0x3d,0x96,0xdd}, {0x05,0xae,0xdd,0x3e}, {0xbd,0x46,0x4d,0xe6}, + {0x8d,0xb5,0x91,0x54}, {0x5d,0x05,0x71,0xc4}, {0xd4,0x6f,0x04,0x06}, {0x15,0xff,0x60,0x50}, + {0xfb,0x24,0x19,0x98}, {0xe9,0x97,0xd6,0xbd}, {0x43,0xcc,0x89,0x40}, {0x9e,0x77,0x67,0xd9}, + {0x42,0xbd,0xb0,0xe8}, {0x8b,0x88,0x07,0x89}, {0x5b,0x38,0xe7,0x19}, {0xee,0xdb,0x79,0xc8}, + {0x0a,0x47,0xa1,0x7c}, {0x0f,0xe9,0x7c,0x42}, {0x1e,0xc9,0xf8,0x84}, {0x00,0x00,0x00,0x00}, + {0x86,0x83,0x09,0x80}, {0xed,0x48,0x32,0x2b}, {0x70,0xac,0x1e,0x11}, {0x72,0x4e,0x6c,0x5a}, + {0xff,0xfb,0xfd,0x0e}, {0x38,0x56,0x0f,0x85}, {0xd5,0x1e,0x3d,0xae}, {0x39,0x27,0x36,0x2d}, + {0xd9,0x64,0x0a,0x0f}, {0xa6,0x21,0x68,0x5c}, {0x54,0xd1,0x9b,0x5b}, {0x2e,0x3a,0x24,0x36}, + {0x67,0xb1,0x0c,0x0a}, {0xe7,0x0f,0x93,0x57}, {0x96,0xd2,0xb4,0xee}, {0x91,0x9e,0x1b,0x9b}, + {0xc5,0x4f,0x80,0xc0}, {0x20,0xa2,0x61,0xdc}, {0x4b,0x69,0x5a,0x77}, {0x1a,0x16,0x1c,0x12}, + {0xba,0x0a,0xe2,0x93}, {0x2a,0xe5,0xc0,0xa0}, {0xe0,0x43,0x3c,0x22}, {0x17,0x1d,0x12,0x1b}, + {0x0d,0x0b,0x0e,0x09}, {0xc7,0xad,0xf2,0x8b}, {0xa8,0xb9,0x2d,0xb6}, {0xa9,0xc8,0x14,0x1e}, + {0x19,0x85,0x57,0xf1}, {0x07,0x4c,0xaf,0x75}, {0xdd,0xbb,0xee,0x99}, {0x60,0xfd,0xa3,0x7f}, + {0x26,0x9f,0xf7,0x01}, {0xf5,0xbc,0x5c,0x72}, {0x3b,0xc5,0x44,0x66}, {0x7e,0x34,0x5b,0xfb}, + {0x29,0x76,0x8b,0x43}, {0xc6,0xdc,0xcb,0x23}, {0xfc,0x68,0xb6,0xed}, {0xf1,0x63,0xb8,0xe4}, + {0xdc,0xca,0xd7,0x31}, {0x85,0x10,0x42,0x63}, {0x22,0x40,0x13,0x97}, {0x11,0x20,0x84,0xc6}, + {0x24,0x7d,0x85,0x4a}, {0x3d,0xf8,0xd2,0xbb}, {0x32,0x11,0xae,0xf9}, {0xa1,0x6d,0xc7,0x29}, + {0x2f,0x4b,0x1d,0x9e}, {0x30,0xf3,0xdc,0xb2}, {0x52,0xec,0x0d,0x86}, {0xe3,0xd0,0x77,0xc1}, + {0x16,0x6c,0x2b,0xb3}, {0xb9,0x99,0xa9,0x70}, {0x48,0xfa,0x11,0x94}, {0x64,0x22,0x47,0xe9}, + {0x8c,0xc4,0xa8,0xfc}, {0x3f,0x1a,0xa0,0xf0}, {0x2c,0xd8,0x56,0x7d}, {0x90,0xef,0x22,0x33}, + {0x4e,0xc7,0x87,0x49}, {0xd1,0xc1,0xd9,0x38}, {0xa2,0xfe,0x8c,0xca}, {0x0b,0x36,0x98,0xd4}, + {0x81,0xcf,0xa6,0xf5}, {0xde,0x28,0xa5,0x7a}, {0x8e,0x26,0xda,0xb7}, {0xbf,0xa4,0x3f,0xad}, + {0x9d,0xe4,0x2c,0x3a}, {0x92,0x0d,0x50,0x78}, {0xcc,0x9b,0x6a,0x5f}, {0x46,0x62,0x54,0x7e}, + {0x13,0xc2,0xf6,0x8d}, {0xb8,0xe8,0x90,0xd8}, {0xf7,0x5e,0x2e,0x39}, {0xaf,0xf5,0x82,0xc3}, + {0x80,0xbe,0x9f,0x5d}, {0x93,0x7c,0x69,0xd0}, {0x2d,0xa9,0x6f,0xd5}, {0x12,0xb3,0xcf,0x25}, + {0x99,0x3b,0xc8,0xac}, {0x7d,0xa7,0x10,0x18}, {0x63,0x6e,0xe8,0x9c}, {0xbb,0x7b,0xdb,0x3b}, + {0x78,0x09,0xcd,0x26}, {0x18,0xf4,0x6e,0x59}, {0xb7,0x01,0xec,0x9a}, {0x9a,0xa8,0x83,0x4f}, + {0x6e,0x65,0xe6,0x95}, {0xe6,0x7e,0xaa,0xff}, {0xcf,0x08,0x21,0xbc}, {0xe8,0xe6,0xef,0x15}, + {0x9b,0xd9,0xba,0xe7}, {0x36,0xce,0x4a,0x6f}, {0x09,0xd4,0xea,0x9f}, {0x7c,0xd6,0x29,0xb0}, + {0xb2,0xaf,0x31,0xa4}, {0x23,0x31,0x2a,0x3f}, {0x94,0x30,0xc6,0xa5}, {0x66,0xc0,0x35,0xa2}, + {0xbc,0x37,0x74,0x4e}, {0xca,0xa6,0xfc,0x82}, {0xd0,0xb0,0xe0,0x90}, {0xd8,0x15,0x33,0xa7}, + {0x98,0x4a,0xf1,0x04}, {0xda,0xf7,0x41,0xec}, {0x50,0x0e,0x7f,0xcd}, {0xf6,0x2f,0x17,0x91}, + {0xd6,0x8d,0x76,0x4d}, {0xb0,0x4d,0x43,0xef}, {0x4d,0x54,0xcc,0xaa}, {0x04,0xdf,0xe4,0x96}, + {0xb5,0xe3,0x9e,0xd1}, {0x88,0x1b,0x4c,0x6a}, {0x1f,0xb8,0xc1,0x2c}, {0x51,0x7f,0x46,0x65}, + {0xea,0x04,0x9d,0x5e}, {0x35,0x5d,0x01,0x8c}, {0x74,0x73,0xfa,0x87}, {0x41,0x2e,0xfb,0x0b}, + {0x1d,0x5a,0xb3,0x67}, {0xd2,0x52,0x92,0xdb}, {0x56,0x33,0xe9,0x10}, {0x47,0x13,0x6d,0xd6}, + {0x61,0x8c,0x9a,0xd7}, {0x0c,0x7a,0x37,0xa1}, {0x14,0x8e,0x59,0xf8}, {0x3c,0x89,0xeb,0x13}, + {0x27,0xee,0xce,0xa9}, {0xc9,0x35,0xb7,0x61}, {0xe5,0xed,0xe1,0x1c}, {0xb1,0x3c,0x7a,0x47}, + {0xdf,0x59,0x9c,0xd2}, {0x73,0x3f,0x55,0xf2}, {0xce,0x79,0x18,0x14}, {0x37,0xbf,0x73,0xc7}, + {0xcd,0xea,0x53,0xf7}, {0xaa,0x5b,0x5f,0xfd}, {0x6f,0x14,0xdf,0x3d}, {0xdb,0x86,0x78,0x44}, + {0xf3,0x81,0xca,0xaf}, {0xc4,0x3e,0xb9,0x68}, {0x34,0x2c,0x38,0x24}, {0x40,0x5f,0xc2,0xa3}, + {0xc3,0x72,0x16,0x1d}, {0x25,0x0c,0xbc,0xe2}, {0x49,0x8b,0x28,0x3c}, {0x95,0x41,0xff,0x0d}, + {0x01,0x71,0x39,0xa8}, {0xb3,0xde,0x08,0x0c}, {0xe4,0x9c,0xd8,0xb4}, {0xc1,0x90,0x64,0x56}, + {0x84,0x61,0x7b,0xcb}, {0xb6,0x70,0xd5,0x32}, {0x5c,0x74,0x48,0x6c}, {0x57,0x42,0xd0,0xb8} +}; + +static UINT8 T8[256][4]= +{ + {0xf4,0xa7,0x50,0x51}, {0x41,0x65,0x53,0x7e}, {0x17,0xa4,0xc3,0x1a}, {0x27,0x5e,0x96,0x3a}, + {0xab,0x6b,0xcb,0x3b}, {0x9d,0x45,0xf1,0x1f}, {0xfa,0x58,0xab,0xac}, {0xe3,0x03,0x93,0x4b}, + {0x30,0xfa,0x55,0x20}, {0x76,0x6d,0xf6,0xad}, {0xcc,0x76,0x91,0x88}, {0x02,0x4c,0x25,0xf5}, + {0xe5,0xd7,0xfc,0x4f}, {0x2a,0xcb,0xd7,0xc5}, {0x35,0x44,0x80,0x26}, {0x62,0xa3,0x8f,0xb5}, + {0xb1,0x5a,0x49,0xde}, {0xba,0x1b,0x67,0x25}, {0xea,0x0e,0x98,0x45}, {0xfe,0xc0,0xe1,0x5d}, + {0x2f,0x75,0x02,0xc3}, {0x4c,0xf0,0x12,0x81}, {0x46,0x97,0xa3,0x8d}, {0xd3,0xf9,0xc6,0x6b}, + {0x8f,0x5f,0xe7,0x03}, {0x92,0x9c,0x95,0x15}, {0x6d,0x7a,0xeb,0xbf}, {0x52,0x59,0xda,0x95}, + {0xbe,0x83,0x2d,0xd4}, {0x74,0x21,0xd3,0x58}, {0xe0,0x69,0x29,0x49}, {0xc9,0xc8,0x44,0x8e}, + {0xc2,0x89,0x6a,0x75}, {0x8e,0x79,0x78,0xf4}, {0x58,0x3e,0x6b,0x99}, {0xb9,0x71,0xdd,0x27}, + {0xe1,0x4f,0xb6,0xbe}, {0x88,0xad,0x17,0xf0}, {0x20,0xac,0x66,0xc9}, {0xce,0x3a,0xb4,0x7d}, + {0xdf,0x4a,0x18,0x63}, {0x1a,0x31,0x82,0xe5}, {0x51,0x33,0x60,0x97}, {0x53,0x7f,0x45,0x62}, + {0x64,0x77,0xe0,0xb1}, {0x6b,0xae,0x84,0xbb}, {0x81,0xa0,0x1c,0xfe}, {0x08,0x2b,0x94,0xf9}, + {0x48,0x68,0x58,0x70}, {0x45,0xfd,0x19,0x8f}, {0xde,0x6c,0x87,0x94}, {0x7b,0xf8,0xb7,0x52}, + {0x73,0xd3,0x23,0xab}, {0x4b,0x02,0xe2,0x72}, {0x1f,0x8f,0x57,0xe3}, {0x55,0xab,0x2a,0x66}, + {0xeb,0x28,0x07,0xb2}, {0xb5,0xc2,0x03,0x2f}, {0xc5,0x7b,0x9a,0x86}, {0x37,0x08,0xa5,0xd3}, + {0x28,0x87,0xf2,0x30}, {0xbf,0xa5,0xb2,0x23}, {0x03,0x6a,0xba,0x02}, {0x16,0x82,0x5c,0xed}, + {0xcf,0x1c,0x2b,0x8a}, {0x79,0xb4,0x92,0xa7}, {0x07,0xf2,0xf0,0xf3}, {0x69,0xe2,0xa1,0x4e}, + {0xda,0xf4,0xcd,0x65}, {0x05,0xbe,0xd5,0x06}, {0x34,0x62,0x1f,0xd1}, {0xa6,0xfe,0x8a,0xc4}, + {0x2e,0x53,0x9d,0x34}, {0xf3,0x55,0xa0,0xa2}, {0x8a,0xe1,0x32,0x05}, {0xf6,0xeb,0x75,0xa4}, + {0x83,0xec,0x39,0x0b}, {0x60,0xef,0xaa,0x40}, {0x71,0x9f,0x06,0x5e}, {0x6e,0x10,0x51,0xbd}, + {0x21,0x8a,0xf9,0x3e}, {0xdd,0x06,0x3d,0x96}, {0x3e,0x05,0xae,0xdd}, {0xe6,0xbd,0x46,0x4d}, + {0x54,0x8d,0xb5,0x91}, {0xc4,0x5d,0x05,0x71}, {0x06,0xd4,0x6f,0x04}, {0x50,0x15,0xff,0x60}, + {0x98,0xfb,0x24,0x19}, {0xbd,0xe9,0x97,0xd6}, {0x40,0x43,0xcc,0x89}, {0xd9,0x9e,0x77,0x67}, + {0xe8,0x42,0xbd,0xb0}, {0x89,0x8b,0x88,0x07}, {0x19,0x5b,0x38,0xe7}, {0xc8,0xee,0xdb,0x79}, + {0x7c,0x0a,0x47,0xa1}, {0x42,0x0f,0xe9,0x7c}, {0x84,0x1e,0xc9,0xf8}, {0x00,0x00,0x00,0x00}, + {0x80,0x86,0x83,0x09}, {0x2b,0xed,0x48,0x32}, {0x11,0x70,0xac,0x1e}, {0x5a,0x72,0x4e,0x6c}, + {0x0e,0xff,0xfb,0xfd}, {0x85,0x38,0x56,0x0f}, {0xae,0xd5,0x1e,0x3d}, {0x2d,0x39,0x27,0x36}, + {0x0f,0xd9,0x64,0x0a}, {0x5c,0xa6,0x21,0x68}, {0x5b,0x54,0xd1,0x9b}, {0x36,0x2e,0x3a,0x24}, + {0x0a,0x67,0xb1,0x0c}, {0x57,0xe7,0x0f,0x93}, {0xee,0x96,0xd2,0xb4}, {0x9b,0x91,0x9e,0x1b}, + {0xc0,0xc5,0x4f,0x80}, {0xdc,0x20,0xa2,0x61}, {0x77,0x4b,0x69,0x5a}, {0x12,0x1a,0x16,0x1c}, + {0x93,0xba,0x0a,0xe2}, {0xa0,0x2a,0xe5,0xc0}, {0x22,0xe0,0x43,0x3c}, {0x1b,0x17,0x1d,0x12}, + {0x09,0x0d,0x0b,0x0e}, {0x8b,0xc7,0xad,0xf2}, {0xb6,0xa8,0xb9,0x2d}, {0x1e,0xa9,0xc8,0x14}, + {0xf1,0x19,0x85,0x57}, {0x75,0x07,0x4c,0xaf}, {0x99,0xdd,0xbb,0xee}, {0x7f,0x60,0xfd,0xa3}, + {0x01,0x26,0x9f,0xf7}, {0x72,0xf5,0xbc,0x5c}, {0x66,0x3b,0xc5,0x44}, {0xfb,0x7e,0x34,0x5b}, + {0x43,0x29,0x76,0x8b}, {0x23,0xc6,0xdc,0xcb}, {0xed,0xfc,0x68,0xb6}, {0xe4,0xf1,0x63,0xb8}, + {0x31,0xdc,0xca,0xd7}, {0x63,0x85,0x10,0x42}, {0x97,0x22,0x40,0x13}, {0xc6,0x11,0x20,0x84}, + {0x4a,0x24,0x7d,0x85}, {0xbb,0x3d,0xf8,0xd2}, {0xf9,0x32,0x11,0xae}, {0x29,0xa1,0x6d,0xc7}, + {0x9e,0x2f,0x4b,0x1d}, {0xb2,0x30,0xf3,0xdc}, {0x86,0x52,0xec,0x0d}, {0xc1,0xe3,0xd0,0x77}, + {0xb3,0x16,0x6c,0x2b}, {0x70,0xb9,0x99,0xa9}, {0x94,0x48,0xfa,0x11}, {0xe9,0x64,0x22,0x47}, + {0xfc,0x8c,0xc4,0xa8}, {0xf0,0x3f,0x1a,0xa0}, {0x7d,0x2c,0xd8,0x56}, {0x33,0x90,0xef,0x22}, + {0x49,0x4e,0xc7,0x87}, {0x38,0xd1,0xc1,0xd9}, {0xca,0xa2,0xfe,0x8c}, {0xd4,0x0b,0x36,0x98}, + {0xf5,0x81,0xcf,0xa6}, {0x7a,0xde,0x28,0xa5}, {0xb7,0x8e,0x26,0xda}, {0xad,0xbf,0xa4,0x3f}, + {0x3a,0x9d,0xe4,0x2c}, {0x78,0x92,0x0d,0x50}, {0x5f,0xcc,0x9b,0x6a}, {0x7e,0x46,0x62,0x54}, + {0x8d,0x13,0xc2,0xf6}, {0xd8,0xb8,0xe8,0x90}, {0x39,0xf7,0x5e,0x2e}, {0xc3,0xaf,0xf5,0x82}, + {0x5d,0x80,0xbe,0x9f}, {0xd0,0x93,0x7c,0x69}, {0xd5,0x2d,0xa9,0x6f}, {0x25,0x12,0xb3,0xcf}, + {0xac,0x99,0x3b,0xc8}, {0x18,0x7d,0xa7,0x10}, {0x9c,0x63,0x6e,0xe8}, {0x3b,0xbb,0x7b,0xdb}, + {0x26,0x78,0x09,0xcd}, {0x59,0x18,0xf4,0x6e}, {0x9a,0xb7,0x01,0xec}, {0x4f,0x9a,0xa8,0x83}, + {0x95,0x6e,0x65,0xe6}, {0xff,0xe6,0x7e,0xaa}, {0xbc,0xcf,0x08,0x21}, {0x15,0xe8,0xe6,0xef}, + {0xe7,0x9b,0xd9,0xba}, {0x6f,0x36,0xce,0x4a}, {0x9f,0x09,0xd4,0xea}, {0xb0,0x7c,0xd6,0x29}, + {0xa4,0xb2,0xaf,0x31}, {0x3f,0x23,0x31,0x2a}, {0xa5,0x94,0x30,0xc6}, {0xa2,0x66,0xc0,0x35}, + {0x4e,0xbc,0x37,0x74}, {0x82,0xca,0xa6,0xfc}, {0x90,0xd0,0xb0,0xe0}, {0xa7,0xd8,0x15,0x33}, + {0x04,0x98,0x4a,0xf1}, {0xec,0xda,0xf7,0x41}, {0xcd,0x50,0x0e,0x7f}, {0x91,0xf6,0x2f,0x17}, + {0x4d,0xd6,0x8d,0x76}, {0xef,0xb0,0x4d,0x43}, {0xaa,0x4d,0x54,0xcc}, {0x96,0x04,0xdf,0xe4}, + {0xd1,0xb5,0xe3,0x9e}, {0x6a,0x88,0x1b,0x4c}, {0x2c,0x1f,0xb8,0xc1}, {0x65,0x51,0x7f,0x46}, + {0x5e,0xea,0x04,0x9d}, {0x8c,0x35,0x5d,0x01}, {0x87,0x74,0x73,0xfa}, {0x0b,0x41,0x2e,0xfb}, + {0x67,0x1d,0x5a,0xb3}, {0xdb,0xd2,0x52,0x92}, {0x10,0x56,0x33,0xe9}, {0xd6,0x47,0x13,0x6d}, + {0xd7,0x61,0x8c,0x9a}, {0xa1,0x0c,0x7a,0x37}, {0xf8,0x14,0x8e,0x59}, {0x13,0x3c,0x89,0xeb}, + {0xa9,0x27,0xee,0xce}, {0x61,0xc9,0x35,0xb7}, {0x1c,0xe5,0xed,0xe1}, {0x47,0xb1,0x3c,0x7a}, + {0xd2,0xdf,0x59,0x9c}, {0xf2,0x73,0x3f,0x55}, {0x14,0xce,0x79,0x18}, {0xc7,0x37,0xbf,0x73}, + {0xf7,0xcd,0xea,0x53}, {0xfd,0xaa,0x5b,0x5f}, {0x3d,0x6f,0x14,0xdf}, {0x44,0xdb,0x86,0x78}, + {0xaf,0xf3,0x81,0xca}, {0x68,0xc4,0x3e,0xb9}, {0x24,0x34,0x2c,0x38}, {0xa3,0x40,0x5f,0xc2}, + {0x1d,0xc3,0x72,0x16}, {0xe2,0x25,0x0c,0xbc}, {0x3c,0x49,0x8b,0x28}, {0x0d,0x95,0x41,0xff}, + {0xa8,0x01,0x71,0x39}, {0x0c,0xb3,0xde,0x08}, {0xb4,0xe4,0x9c,0xd8}, {0x56,0xc1,0x90,0x64}, + {0xcb,0x84,0x61,0x7b}, {0x32,0xb6,0x70,0xd5}, {0x6c,0x5c,0x74,0x48}, {0xb8,0x57,0x42,0xd0} +}; + +static UINT8 S5[256]= +{ + 0x52,0x09,0x6a,0xd5, + 0x30,0x36,0xa5,0x38, + 0xbf,0x40,0xa3,0x9e, + 0x81,0xf3,0xd7,0xfb, + 0x7c,0xe3,0x39,0x82, + 0x9b,0x2f,0xff,0x87, + 0x34,0x8e,0x43,0x44, + 0xc4,0xde,0xe9,0xcb, + 0x54,0x7b,0x94,0x32, + 0xa6,0xc2,0x23,0x3d, + 0xee,0x4c,0x95,0x0b, + 0x42,0xfa,0xc3,0x4e, + 0x08,0x2e,0xa1,0x66, + 0x28,0xd9,0x24,0xb2, + 0x76,0x5b,0xa2,0x49, + 0x6d,0x8b,0xd1,0x25, + 0x72,0xf8,0xf6,0x64, + 0x86,0x68,0x98,0x16, + 0xd4,0xa4,0x5c,0xcc, + 0x5d,0x65,0xb6,0x92, + 0x6c,0x70,0x48,0x50, + 0xfd,0xed,0xb9,0xda, + 0x5e,0x15,0x46,0x57, + 0xa7,0x8d,0x9d,0x84, + 0x90,0xd8,0xab,0x00, + 0x8c,0xbc,0xd3,0x0a, + 0xf7,0xe4,0x58,0x05, + 0xb8,0xb3,0x45,0x06, + 0xd0,0x2c,0x1e,0x8f, + 0xca,0x3f,0x0f,0x02, + 0xc1,0xaf,0xbd,0x03, + 0x01,0x13,0x8a,0x6b, + 0x3a,0x91,0x11,0x41, + 0x4f,0x67,0xdc,0xea, + 0x97,0xf2,0xcf,0xce, + 0xf0,0xb4,0xe6,0x73, + 0x96,0xac,0x74,0x22, + 0xe7,0xad,0x35,0x85, + 0xe2,0xf9,0x37,0xe8, + 0x1c,0x75,0xdf,0x6e, + 0x47,0xf1,0x1a,0x71, + 0x1d,0x29,0xc5,0x89, + 0x6f,0xb7,0x62,0x0e, + 0xaa,0x18,0xbe,0x1b, + 0xfc,0x56,0x3e,0x4b, + 0xc6,0xd2,0x79,0x20, + 0x9a,0xdb,0xc0,0xfe, + 0x78,0xcd,0x5a,0xf4, + 0x1f,0xdd,0xa8,0x33, + 0x88,0x07,0xc7,0x31, + 0xb1,0x12,0x10,0x59, + 0x27,0x80,0xec,0x5f, + 0x60,0x51,0x7f,0xa9, + 0x19,0xb5,0x4a,0x0d, + 0x2d,0xe5,0x7a,0x9f, + 0x93,0xc9,0x9c,0xef, + 0xa0,0xe0,0x3b,0x4d, + 0xae,0x2a,0xf5,0xb0, + 0xc8,0xeb,0xbb,0x3c, + 0x83,0x53,0x99,0x61, + 0x17,0x2b,0x04,0x7e, + 0xba,0x77,0xd6,0x26, + 0xe1,0x69,0x14,0x63, + 0x55,0x21,0x0c,0x7d +}; + +static UINT8 U1[256][4]= +{ + {0x00,0x00,0x00,0x00}, {0x0e,0x09,0x0d,0x0b}, {0x1c,0x12,0x1a,0x16}, {0x12,0x1b,0x17,0x1d}, + {0x38,0x24,0x34,0x2c}, {0x36,0x2d,0x39,0x27}, {0x24,0x36,0x2e,0x3a}, {0x2a,0x3f,0x23,0x31}, + {0x70,0x48,0x68,0x58}, {0x7e,0x41,0x65,0x53}, {0x6c,0x5a,0x72,0x4e}, {0x62,0x53,0x7f,0x45}, + {0x48,0x6c,0x5c,0x74}, {0x46,0x65,0x51,0x7f}, {0x54,0x7e,0x46,0x62}, {0x5a,0x77,0x4b,0x69}, + {0xe0,0x90,0xd0,0xb0}, {0xee,0x99,0xdd,0xbb}, {0xfc,0x82,0xca,0xa6}, {0xf2,0x8b,0xc7,0xad}, + {0xd8,0xb4,0xe4,0x9c}, {0xd6,0xbd,0xe9,0x97}, {0xc4,0xa6,0xfe,0x8a}, {0xca,0xaf,0xf3,0x81}, + {0x90,0xd8,0xb8,0xe8}, {0x9e,0xd1,0xb5,0xe3}, {0x8c,0xca,0xa2,0xfe}, {0x82,0xc3,0xaf,0xf5}, + {0xa8,0xfc,0x8c,0xc4}, {0xa6,0xf5,0x81,0xcf}, {0xb4,0xee,0x96,0xd2}, {0xba,0xe7,0x9b,0xd9}, + {0xdb,0x3b,0xbb,0x7b}, {0xd5,0x32,0xb6,0x70}, {0xc7,0x29,0xa1,0x6d}, {0xc9,0x20,0xac,0x66}, + {0xe3,0x1f,0x8f,0x57}, {0xed,0x16,0x82,0x5c}, {0xff,0x0d,0x95,0x41}, {0xf1,0x04,0x98,0x4a}, + {0xab,0x73,0xd3,0x23}, {0xa5,0x7a,0xde,0x28}, {0xb7,0x61,0xc9,0x35}, {0xb9,0x68,0xc4,0x3e}, + {0x93,0x57,0xe7,0x0f}, {0x9d,0x5e,0xea,0x04}, {0x8f,0x45,0xfd,0x19}, {0x81,0x4c,0xf0,0x12}, + {0x3b,0xab,0x6b,0xcb}, {0x35,0xa2,0x66,0xc0}, {0x27,0xb9,0x71,0xdd}, {0x29,0xb0,0x7c,0xd6}, + {0x03,0x8f,0x5f,0xe7}, {0x0d,0x86,0x52,0xec}, {0x1f,0x9d,0x45,0xf1}, {0x11,0x94,0x48,0xfa}, + {0x4b,0xe3,0x03,0x93}, {0x45,0xea,0x0e,0x98}, {0x57,0xf1,0x19,0x85}, {0x59,0xf8,0x14,0x8e}, + {0x73,0xc7,0x37,0xbf}, {0x7d,0xce,0x3a,0xb4}, {0x6f,0xd5,0x2d,0xa9}, {0x61,0xdc,0x20,0xa2}, + {0xad,0x76,0x6d,0xf6}, {0xa3,0x7f,0x60,0xfd}, {0xb1,0x64,0x77,0xe0}, {0xbf,0x6d,0x7a,0xeb}, + {0x95,0x52,0x59,0xda}, {0x9b,0x5b,0x54,0xd1}, {0x89,0x40,0x43,0xcc}, {0x87,0x49,0x4e,0xc7}, + {0xdd,0x3e,0x05,0xae}, {0xd3,0x37,0x08,0xa5}, {0xc1,0x2c,0x1f,0xb8}, {0xcf,0x25,0x12,0xb3}, + {0xe5,0x1a,0x31,0x82}, {0xeb,0x13,0x3c,0x89}, {0xf9,0x08,0x2b,0x94}, {0xf7,0x01,0x26,0x9f}, + {0x4d,0xe6,0xbd,0x46}, {0x43,0xef,0xb0,0x4d}, {0x51,0xf4,0xa7,0x50}, {0x5f,0xfd,0xaa,0x5b}, + {0x75,0xc2,0x89,0x6a}, {0x7b,0xcb,0x84,0x61}, {0x69,0xd0,0x93,0x7c}, {0x67,0xd9,0x9e,0x77}, + {0x3d,0xae,0xd5,0x1e}, {0x33,0xa7,0xd8,0x15}, {0x21,0xbc,0xcf,0x08}, {0x2f,0xb5,0xc2,0x03}, + {0x05,0x8a,0xe1,0x32}, {0x0b,0x83,0xec,0x39}, {0x19,0x98,0xfb,0x24}, {0x17,0x91,0xf6,0x2f}, + {0x76,0x4d,0xd6,0x8d}, {0x78,0x44,0xdb,0x86}, {0x6a,0x5f,0xcc,0x9b}, {0x64,0x56,0xc1,0x90}, + {0x4e,0x69,0xe2,0xa1}, {0x40,0x60,0xef,0xaa}, {0x52,0x7b,0xf8,0xb7}, {0x5c,0x72,0xf5,0xbc}, + {0x06,0x05,0xbe,0xd5}, {0x08,0x0c,0xb3,0xde}, {0x1a,0x17,0xa4,0xc3}, {0x14,0x1e,0xa9,0xc8}, + {0x3e,0x21,0x8a,0xf9}, {0x30,0x28,0x87,0xf2}, {0x22,0x33,0x90,0xef}, {0x2c,0x3a,0x9d,0xe4}, + {0x96,0xdd,0x06,0x3d}, {0x98,0xd4,0x0b,0x36}, {0x8a,0xcf,0x1c,0x2b}, {0x84,0xc6,0x11,0x20}, + {0xae,0xf9,0x32,0x11}, {0xa0,0xf0,0x3f,0x1a}, {0xb2,0xeb,0x28,0x07}, {0xbc,0xe2,0x25,0x0c}, + {0xe6,0x95,0x6e,0x65}, {0xe8,0x9c,0x63,0x6e}, {0xfa,0x87,0x74,0x73}, {0xf4,0x8e,0x79,0x78}, + {0xde,0xb1,0x5a,0x49}, {0xd0,0xb8,0x57,0x42}, {0xc2,0xa3,0x40,0x5f}, {0xcc,0xaa,0x4d,0x54}, + {0x41,0xec,0xda,0xf7}, {0x4f,0xe5,0xd7,0xfc}, {0x5d,0xfe,0xc0,0xe1}, {0x53,0xf7,0xcd,0xea}, + {0x79,0xc8,0xee,0xdb}, {0x77,0xc1,0xe3,0xd0}, {0x65,0xda,0xf4,0xcd}, {0x6b,0xd3,0xf9,0xc6}, + {0x31,0xa4,0xb2,0xaf}, {0x3f,0xad,0xbf,0xa4}, {0x2d,0xb6,0xa8,0xb9}, {0x23,0xbf,0xa5,0xb2}, + {0x09,0x80,0x86,0x83}, {0x07,0x89,0x8b,0x88}, {0x15,0x92,0x9c,0x95}, {0x1b,0x9b,0x91,0x9e}, + {0xa1,0x7c,0x0a,0x47}, {0xaf,0x75,0x07,0x4c}, {0xbd,0x6e,0x10,0x51}, {0xb3,0x67,0x1d,0x5a}, + {0x99,0x58,0x3e,0x6b}, {0x97,0x51,0x33,0x60}, {0x85,0x4a,0x24,0x7d}, {0x8b,0x43,0x29,0x76}, + {0xd1,0x34,0x62,0x1f}, {0xdf,0x3d,0x6f,0x14}, {0xcd,0x26,0x78,0x09}, {0xc3,0x2f,0x75,0x02}, + {0xe9,0x10,0x56,0x33}, {0xe7,0x19,0x5b,0x38}, {0xf5,0x02,0x4c,0x25}, {0xfb,0x0b,0x41,0x2e}, + {0x9a,0xd7,0x61,0x8c}, {0x94,0xde,0x6c,0x87}, {0x86,0xc5,0x7b,0x9a}, {0x88,0xcc,0x76,0x91}, + {0xa2,0xf3,0x55,0xa0}, {0xac,0xfa,0x58,0xab}, {0xbe,0xe1,0x4f,0xb6}, {0xb0,0xe8,0x42,0xbd}, + {0xea,0x9f,0x09,0xd4}, {0xe4,0x96,0x04,0xdf}, {0xf6,0x8d,0x13,0xc2}, {0xf8,0x84,0x1e,0xc9}, + {0xd2,0xbb,0x3d,0xf8}, {0xdc,0xb2,0x30,0xf3}, {0xce,0xa9,0x27,0xee}, {0xc0,0xa0,0x2a,0xe5}, + {0x7a,0x47,0xb1,0x3c}, {0x74,0x4e,0xbc,0x37}, {0x66,0x55,0xab,0x2a}, {0x68,0x5c,0xa6,0x21}, + {0x42,0x63,0x85,0x10}, {0x4c,0x6a,0x88,0x1b}, {0x5e,0x71,0x9f,0x06}, {0x50,0x78,0x92,0x0d}, + {0x0a,0x0f,0xd9,0x64}, {0x04,0x06,0xd4,0x6f}, {0x16,0x1d,0xc3,0x72}, {0x18,0x14,0xce,0x79}, + {0x32,0x2b,0xed,0x48}, {0x3c,0x22,0xe0,0x43}, {0x2e,0x39,0xf7,0x5e}, {0x20,0x30,0xfa,0x55}, + {0xec,0x9a,0xb7,0x01}, {0xe2,0x93,0xba,0x0a}, {0xf0,0x88,0xad,0x17}, {0xfe,0x81,0xa0,0x1c}, + {0xd4,0xbe,0x83,0x2d}, {0xda,0xb7,0x8e,0x26}, {0xc8,0xac,0x99,0x3b}, {0xc6,0xa5,0x94,0x30}, + {0x9c,0xd2,0xdf,0x59}, {0x92,0xdb,0xd2,0x52}, {0x80,0xc0,0xc5,0x4f}, {0x8e,0xc9,0xc8,0x44}, + {0xa4,0xf6,0xeb,0x75}, {0xaa,0xff,0xe6,0x7e}, {0xb8,0xe4,0xf1,0x63}, {0xb6,0xed,0xfc,0x68}, + {0x0c,0x0a,0x67,0xb1}, {0x02,0x03,0x6a,0xba}, {0x10,0x18,0x7d,0xa7}, {0x1e,0x11,0x70,0xac}, + {0x34,0x2e,0x53,0x9d}, {0x3a,0x27,0x5e,0x96}, {0x28,0x3c,0x49,0x8b}, {0x26,0x35,0x44,0x80}, + {0x7c,0x42,0x0f,0xe9}, {0x72,0x4b,0x02,0xe2}, {0x60,0x50,0x15,0xff}, {0x6e,0x59,0x18,0xf4}, + {0x44,0x66,0x3b,0xc5}, {0x4a,0x6f,0x36,0xce}, {0x58,0x74,0x21,0xd3}, {0x56,0x7d,0x2c,0xd8}, + {0x37,0xa1,0x0c,0x7a}, {0x39,0xa8,0x01,0x71}, {0x2b,0xb3,0x16,0x6c}, {0x25,0xba,0x1b,0x67}, + {0x0f,0x85,0x38,0x56}, {0x01,0x8c,0x35,0x5d}, {0x13,0x97,0x22,0x40}, {0x1d,0x9e,0x2f,0x4b}, + {0x47,0xe9,0x64,0x22}, {0x49,0xe0,0x69,0x29}, {0x5b,0xfb,0x7e,0x34}, {0x55,0xf2,0x73,0x3f}, + {0x7f,0xcd,0x50,0x0e}, {0x71,0xc4,0x5d,0x05}, {0x63,0xdf,0x4a,0x18}, {0x6d,0xd6,0x47,0x13}, + {0xd7,0x31,0xdc,0xca}, {0xd9,0x38,0xd1,0xc1}, {0xcb,0x23,0xc6,0xdc}, {0xc5,0x2a,0xcb,0xd7}, + {0xef,0x15,0xe8,0xe6}, {0xe1,0x1c,0xe5,0xed}, {0xf3,0x07,0xf2,0xf0}, {0xfd,0x0e,0xff,0xfb}, + {0xa7,0x79,0xb4,0x92}, {0xa9,0x70,0xb9,0x99}, {0xbb,0x6b,0xae,0x84}, {0xb5,0x62,0xa3,0x8f}, + {0x9f,0x5d,0x80,0xbe}, {0x91,0x54,0x8d,0xb5}, {0x83,0x4f,0x9a,0xa8}, {0x8d,0x46,0x97,0xa3} +}; + +static UINT8 U2[256][4]= +{ + {0x00,0x00,0x00,0x00}, {0x0b,0x0e,0x09,0x0d}, {0x16,0x1c,0x12,0x1a}, {0x1d,0x12,0x1b,0x17}, + {0x2c,0x38,0x24,0x34}, {0x27,0x36,0x2d,0x39}, {0x3a,0x24,0x36,0x2e}, {0x31,0x2a,0x3f,0x23}, + {0x58,0x70,0x48,0x68}, {0x53,0x7e,0x41,0x65}, {0x4e,0x6c,0x5a,0x72}, {0x45,0x62,0x53,0x7f}, + {0x74,0x48,0x6c,0x5c}, {0x7f,0x46,0x65,0x51}, {0x62,0x54,0x7e,0x46}, {0x69,0x5a,0x77,0x4b}, + {0xb0,0xe0,0x90,0xd0}, {0xbb,0xee,0x99,0xdd}, {0xa6,0xfc,0x82,0xca}, {0xad,0xf2,0x8b,0xc7}, + {0x9c,0xd8,0xb4,0xe4}, {0x97,0xd6,0xbd,0xe9}, {0x8a,0xc4,0xa6,0xfe}, {0x81,0xca,0xaf,0xf3}, + {0xe8,0x90,0xd8,0xb8}, {0xe3,0x9e,0xd1,0xb5}, {0xfe,0x8c,0xca,0xa2}, {0xf5,0x82,0xc3,0xaf}, + {0xc4,0xa8,0xfc,0x8c}, {0xcf,0xa6,0xf5,0x81}, {0xd2,0xb4,0xee,0x96}, {0xd9,0xba,0xe7,0x9b}, + {0x7b,0xdb,0x3b,0xbb}, {0x70,0xd5,0x32,0xb6}, {0x6d,0xc7,0x29,0xa1}, {0x66,0xc9,0x20,0xac}, + {0x57,0xe3,0x1f,0x8f}, {0x5c,0xed,0x16,0x82}, {0x41,0xff,0x0d,0x95}, {0x4a,0xf1,0x04,0x98}, + {0x23,0xab,0x73,0xd3}, {0x28,0xa5,0x7a,0xde}, {0x35,0xb7,0x61,0xc9}, {0x3e,0xb9,0x68,0xc4}, + {0x0f,0x93,0x57,0xe7}, {0x04,0x9d,0x5e,0xea}, {0x19,0x8f,0x45,0xfd}, {0x12,0x81,0x4c,0xf0}, + {0xcb,0x3b,0xab,0x6b}, {0xc0,0x35,0xa2,0x66}, {0xdd,0x27,0xb9,0x71}, {0xd6,0x29,0xb0,0x7c}, + {0xe7,0x03,0x8f,0x5f}, {0xec,0x0d,0x86,0x52}, {0xf1,0x1f,0x9d,0x45}, {0xfa,0x11,0x94,0x48}, + {0x93,0x4b,0xe3,0x03}, {0x98,0x45,0xea,0x0e}, {0x85,0x57,0xf1,0x19}, {0x8e,0x59,0xf8,0x14}, + {0xbf,0x73,0xc7,0x37}, {0xb4,0x7d,0xce,0x3a}, {0xa9,0x6f,0xd5,0x2d}, {0xa2,0x61,0xdc,0x20}, + {0xf6,0xad,0x76,0x6d}, {0xfd,0xa3,0x7f,0x60}, {0xe0,0xb1,0x64,0x77}, {0xeb,0xbf,0x6d,0x7a}, + {0xda,0x95,0x52,0x59}, {0xd1,0x9b,0x5b,0x54}, {0xcc,0x89,0x40,0x43}, {0xc7,0x87,0x49,0x4e}, + {0xae,0xdd,0x3e,0x05}, {0xa5,0xd3,0x37,0x08}, {0xb8,0xc1,0x2c,0x1f}, {0xb3,0xcf,0x25,0x12}, + {0x82,0xe5,0x1a,0x31}, {0x89,0xeb,0x13,0x3c}, {0x94,0xf9,0x08,0x2b}, {0x9f,0xf7,0x01,0x26}, + {0x46,0x4d,0xe6,0xbd}, {0x4d,0x43,0xef,0xb0}, {0x50,0x51,0xf4,0xa7}, {0x5b,0x5f,0xfd,0xaa}, + {0x6a,0x75,0xc2,0x89}, {0x61,0x7b,0xcb,0x84}, {0x7c,0x69,0xd0,0x93}, {0x77,0x67,0xd9,0x9e}, + {0x1e,0x3d,0xae,0xd5}, {0x15,0x33,0xa7,0xd8}, {0x08,0x21,0xbc,0xcf}, {0x03,0x2f,0xb5,0xc2}, + {0x32,0x05,0x8a,0xe1}, {0x39,0x0b,0x83,0xec}, {0x24,0x19,0x98,0xfb}, {0x2f,0x17,0x91,0xf6}, + {0x8d,0x76,0x4d,0xd6}, {0x86,0x78,0x44,0xdb}, {0x9b,0x6a,0x5f,0xcc}, {0x90,0x64,0x56,0xc1}, + {0xa1,0x4e,0x69,0xe2}, {0xaa,0x40,0x60,0xef}, {0xb7,0x52,0x7b,0xf8}, {0xbc,0x5c,0x72,0xf5}, + {0xd5,0x06,0x05,0xbe}, {0xde,0x08,0x0c,0xb3}, {0xc3,0x1a,0x17,0xa4}, {0xc8,0x14,0x1e,0xa9}, + {0xf9,0x3e,0x21,0x8a}, {0xf2,0x30,0x28,0x87}, {0xef,0x22,0x33,0x90}, {0xe4,0x2c,0x3a,0x9d}, + {0x3d,0x96,0xdd,0x06}, {0x36,0x98,0xd4,0x0b}, {0x2b,0x8a,0xcf,0x1c}, {0x20,0x84,0xc6,0x11}, + {0x11,0xae,0xf9,0x32}, {0x1a,0xa0,0xf0,0x3f}, {0x07,0xb2,0xeb,0x28}, {0x0c,0xbc,0xe2,0x25}, + {0x65,0xe6,0x95,0x6e}, {0x6e,0xe8,0x9c,0x63}, {0x73,0xfa,0x87,0x74}, {0x78,0xf4,0x8e,0x79}, + {0x49,0xde,0xb1,0x5a}, {0x42,0xd0,0xb8,0x57}, {0x5f,0xc2,0xa3,0x40}, {0x54,0xcc,0xaa,0x4d}, + {0xf7,0x41,0xec,0xda}, {0xfc,0x4f,0xe5,0xd7}, {0xe1,0x5d,0xfe,0xc0}, {0xea,0x53,0xf7,0xcd}, + {0xdb,0x79,0xc8,0xee}, {0xd0,0x77,0xc1,0xe3}, {0xcd,0x65,0xda,0xf4}, {0xc6,0x6b,0xd3,0xf9}, + {0xaf,0x31,0xa4,0xb2}, {0xa4,0x3f,0xad,0xbf}, {0xb9,0x2d,0xb6,0xa8}, {0xb2,0x23,0xbf,0xa5}, + {0x83,0x09,0x80,0x86}, {0x88,0x07,0x89,0x8b}, {0x95,0x15,0x92,0x9c}, {0x9e,0x1b,0x9b,0x91}, + {0x47,0xa1,0x7c,0x0a}, {0x4c,0xaf,0x75,0x07}, {0x51,0xbd,0x6e,0x10}, {0x5a,0xb3,0x67,0x1d}, + {0x6b,0x99,0x58,0x3e}, {0x60,0x97,0x51,0x33}, {0x7d,0x85,0x4a,0x24}, {0x76,0x8b,0x43,0x29}, + {0x1f,0xd1,0x34,0x62}, {0x14,0xdf,0x3d,0x6f}, {0x09,0xcd,0x26,0x78}, {0x02,0xc3,0x2f,0x75}, + {0x33,0xe9,0x10,0x56}, {0x38,0xe7,0x19,0x5b}, {0x25,0xf5,0x02,0x4c}, {0x2e,0xfb,0x0b,0x41}, + {0x8c,0x9a,0xd7,0x61}, {0x87,0x94,0xde,0x6c}, {0x9a,0x86,0xc5,0x7b}, {0x91,0x88,0xcc,0x76}, + {0xa0,0xa2,0xf3,0x55}, {0xab,0xac,0xfa,0x58}, {0xb6,0xbe,0xe1,0x4f}, {0xbd,0xb0,0xe8,0x42}, + {0xd4,0xea,0x9f,0x09}, {0xdf,0xe4,0x96,0x04}, {0xc2,0xf6,0x8d,0x13}, {0xc9,0xf8,0x84,0x1e}, + {0xf8,0xd2,0xbb,0x3d}, {0xf3,0xdc,0xb2,0x30}, {0xee,0xce,0xa9,0x27}, {0xe5,0xc0,0xa0,0x2a}, + {0x3c,0x7a,0x47,0xb1}, {0x37,0x74,0x4e,0xbc}, {0x2a,0x66,0x55,0xab}, {0x21,0x68,0x5c,0xa6}, + {0x10,0x42,0x63,0x85}, {0x1b,0x4c,0x6a,0x88}, {0x06,0x5e,0x71,0x9f}, {0x0d,0x50,0x78,0x92}, + {0x64,0x0a,0x0f,0xd9}, {0x6f,0x04,0x06,0xd4}, {0x72,0x16,0x1d,0xc3}, {0x79,0x18,0x14,0xce}, + {0x48,0x32,0x2b,0xed}, {0x43,0x3c,0x22,0xe0}, {0x5e,0x2e,0x39,0xf7}, {0x55,0x20,0x30,0xfa}, + {0x01,0xec,0x9a,0xb7}, {0x0a,0xe2,0x93,0xba}, {0x17,0xf0,0x88,0xad}, {0x1c,0xfe,0x81,0xa0}, + {0x2d,0xd4,0xbe,0x83}, {0x26,0xda,0xb7,0x8e}, {0x3b,0xc8,0xac,0x99}, {0x30,0xc6,0xa5,0x94}, + {0x59,0x9c,0xd2,0xdf}, {0x52,0x92,0xdb,0xd2}, {0x4f,0x80,0xc0,0xc5}, {0x44,0x8e,0xc9,0xc8}, + {0x75,0xa4,0xf6,0xeb}, {0x7e,0xaa,0xff,0xe6}, {0x63,0xb8,0xe4,0xf1}, {0x68,0xb6,0xed,0xfc}, + {0xb1,0x0c,0x0a,0x67}, {0xba,0x02,0x03,0x6a}, {0xa7,0x10,0x18,0x7d}, {0xac,0x1e,0x11,0x70}, + {0x9d,0x34,0x2e,0x53}, {0x96,0x3a,0x27,0x5e}, {0x8b,0x28,0x3c,0x49}, {0x80,0x26,0x35,0x44}, + {0xe9,0x7c,0x42,0x0f}, {0xe2,0x72,0x4b,0x02}, {0xff,0x60,0x50,0x15}, {0xf4,0x6e,0x59,0x18}, + {0xc5,0x44,0x66,0x3b}, {0xce,0x4a,0x6f,0x36}, {0xd3,0x58,0x74,0x21}, {0xd8,0x56,0x7d,0x2c}, + {0x7a,0x37,0xa1,0x0c}, {0x71,0x39,0xa8,0x01}, {0x6c,0x2b,0xb3,0x16}, {0x67,0x25,0xba,0x1b}, + {0x56,0x0f,0x85,0x38}, {0x5d,0x01,0x8c,0x35}, {0x40,0x13,0x97,0x22}, {0x4b,0x1d,0x9e,0x2f}, + {0x22,0x47,0xe9,0x64}, {0x29,0x49,0xe0,0x69}, {0x34,0x5b,0xfb,0x7e}, {0x3f,0x55,0xf2,0x73}, + {0x0e,0x7f,0xcd,0x50}, {0x05,0x71,0xc4,0x5d}, {0x18,0x63,0xdf,0x4a}, {0x13,0x6d,0xd6,0x47}, + {0xca,0xd7,0x31,0xdc}, {0xc1,0xd9,0x38,0xd1}, {0xdc,0xcb,0x23,0xc6}, {0xd7,0xc5,0x2a,0xcb}, + {0xe6,0xef,0x15,0xe8}, {0xed,0xe1,0x1c,0xe5}, {0xf0,0xf3,0x07,0xf2}, {0xfb,0xfd,0x0e,0xff}, + {0x92,0xa7,0x79,0xb4}, {0x99,0xa9,0x70,0xb9}, {0x84,0xbb,0x6b,0xae}, {0x8f,0xb5,0x62,0xa3}, + {0xbe,0x9f,0x5d,0x80}, {0xb5,0x91,0x54,0x8d}, {0xa8,0x83,0x4f,0x9a}, {0xa3,0x8d,0x46,0x97} +}; + +static UINT8 U3[256][4]= +{ + {0x00,0x00,0x00,0x00}, {0x0d,0x0b,0x0e,0x09}, {0x1a,0x16,0x1c,0x12}, {0x17,0x1d,0x12,0x1b}, + {0x34,0x2c,0x38,0x24}, {0x39,0x27,0x36,0x2d}, {0x2e,0x3a,0x24,0x36}, {0x23,0x31,0x2a,0x3f}, + {0x68,0x58,0x70,0x48}, {0x65,0x53,0x7e,0x41}, {0x72,0x4e,0x6c,0x5a}, {0x7f,0x45,0x62,0x53}, + {0x5c,0x74,0x48,0x6c}, {0x51,0x7f,0x46,0x65}, {0x46,0x62,0x54,0x7e}, {0x4b,0x69,0x5a,0x77}, + {0xd0,0xb0,0xe0,0x90}, {0xdd,0xbb,0xee,0x99}, {0xca,0xa6,0xfc,0x82}, {0xc7,0xad,0xf2,0x8b}, + {0xe4,0x9c,0xd8,0xb4}, {0xe9,0x97,0xd6,0xbd}, {0xfe,0x8a,0xc4,0xa6}, {0xf3,0x81,0xca,0xaf}, + {0xb8,0xe8,0x90,0xd8}, {0xb5,0xe3,0x9e,0xd1}, {0xa2,0xfe,0x8c,0xca}, {0xaf,0xf5,0x82,0xc3}, + {0x8c,0xc4,0xa8,0xfc}, {0x81,0xcf,0xa6,0xf5}, {0x96,0xd2,0xb4,0xee}, {0x9b,0xd9,0xba,0xe7}, + {0xbb,0x7b,0xdb,0x3b}, {0xb6,0x70,0xd5,0x32}, {0xa1,0x6d,0xc7,0x29}, {0xac,0x66,0xc9,0x20}, + {0x8f,0x57,0xe3,0x1f}, {0x82,0x5c,0xed,0x16}, {0x95,0x41,0xff,0x0d}, {0x98,0x4a,0xf1,0x04}, + {0xd3,0x23,0xab,0x73}, {0xde,0x28,0xa5,0x7a}, {0xc9,0x35,0xb7,0x61}, {0xc4,0x3e,0xb9,0x68}, + {0xe7,0x0f,0x93,0x57}, {0xea,0x04,0x9d,0x5e}, {0xfd,0x19,0x8f,0x45}, {0xf0,0x12,0x81,0x4c}, + {0x6b,0xcb,0x3b,0xab}, {0x66,0xc0,0x35,0xa2}, {0x71,0xdd,0x27,0xb9}, {0x7c,0xd6,0x29,0xb0}, + {0x5f,0xe7,0x03,0x8f}, {0x52,0xec,0x0d,0x86}, {0x45,0xf1,0x1f,0x9d}, {0x48,0xfa,0x11,0x94}, + {0x03,0x93,0x4b,0xe3}, {0x0e,0x98,0x45,0xea}, {0x19,0x85,0x57,0xf1}, {0x14,0x8e,0x59,0xf8}, + {0x37,0xbf,0x73,0xc7}, {0x3a,0xb4,0x7d,0xce}, {0x2d,0xa9,0x6f,0xd5}, {0x20,0xa2,0x61,0xdc}, + {0x6d,0xf6,0xad,0x76}, {0x60,0xfd,0xa3,0x7f}, {0x77,0xe0,0xb1,0x64}, {0x7a,0xeb,0xbf,0x6d}, + {0x59,0xda,0x95,0x52}, {0x54,0xd1,0x9b,0x5b}, {0x43,0xcc,0x89,0x40}, {0x4e,0xc7,0x87,0x49}, + {0x05,0xae,0xdd,0x3e}, {0x08,0xa5,0xd3,0x37}, {0x1f,0xb8,0xc1,0x2c}, {0x12,0xb3,0xcf,0x25}, + {0x31,0x82,0xe5,0x1a}, {0x3c,0x89,0xeb,0x13}, {0x2b,0x94,0xf9,0x08}, {0x26,0x9f,0xf7,0x01}, + {0xbd,0x46,0x4d,0xe6}, {0xb0,0x4d,0x43,0xef}, {0xa7,0x50,0x51,0xf4}, {0xaa,0x5b,0x5f,0xfd}, + {0x89,0x6a,0x75,0xc2}, {0x84,0x61,0x7b,0xcb}, {0x93,0x7c,0x69,0xd0}, {0x9e,0x77,0x67,0xd9}, + {0xd5,0x1e,0x3d,0xae}, {0xd8,0x15,0x33,0xa7}, {0xcf,0x08,0x21,0xbc}, {0xc2,0x03,0x2f,0xb5}, + {0xe1,0x32,0x05,0x8a}, {0xec,0x39,0x0b,0x83}, {0xfb,0x24,0x19,0x98}, {0xf6,0x2f,0x17,0x91}, + {0xd6,0x8d,0x76,0x4d}, {0xdb,0x86,0x78,0x44}, {0xcc,0x9b,0x6a,0x5f}, {0xc1,0x90,0x64,0x56}, + {0xe2,0xa1,0x4e,0x69}, {0xef,0xaa,0x40,0x60}, {0xf8,0xb7,0x52,0x7b}, {0xf5,0xbc,0x5c,0x72}, + {0xbe,0xd5,0x06,0x05}, {0xb3,0xde,0x08,0x0c}, {0xa4,0xc3,0x1a,0x17}, {0xa9,0xc8,0x14,0x1e}, + {0x8a,0xf9,0x3e,0x21}, {0x87,0xf2,0x30,0x28}, {0x90,0xef,0x22,0x33}, {0x9d,0xe4,0x2c,0x3a}, + {0x06,0x3d,0x96,0xdd}, {0x0b,0x36,0x98,0xd4}, {0x1c,0x2b,0x8a,0xcf}, {0x11,0x20,0x84,0xc6}, + {0x32,0x11,0xae,0xf9}, {0x3f,0x1a,0xa0,0xf0}, {0x28,0x07,0xb2,0xeb}, {0x25,0x0c,0xbc,0xe2}, + {0x6e,0x65,0xe6,0x95}, {0x63,0x6e,0xe8,0x9c}, {0x74,0x73,0xfa,0x87}, {0x79,0x78,0xf4,0x8e}, + {0x5a,0x49,0xde,0xb1}, {0x57,0x42,0xd0,0xb8}, {0x40,0x5f,0xc2,0xa3}, {0x4d,0x54,0xcc,0xaa}, + {0xda,0xf7,0x41,0xec}, {0xd7,0xfc,0x4f,0xe5}, {0xc0,0xe1,0x5d,0xfe}, {0xcd,0xea,0x53,0xf7}, + {0xee,0xdb,0x79,0xc8}, {0xe3,0xd0,0x77,0xc1}, {0xf4,0xcd,0x65,0xda}, {0xf9,0xc6,0x6b,0xd3}, + {0xb2,0xaf,0x31,0xa4}, {0xbf,0xa4,0x3f,0xad}, {0xa8,0xb9,0x2d,0xb6}, {0xa5,0xb2,0x23,0xbf}, + {0x86,0x83,0x09,0x80}, {0x8b,0x88,0x07,0x89}, {0x9c,0x95,0x15,0x92}, {0x91,0x9e,0x1b,0x9b}, + {0x0a,0x47,0xa1,0x7c}, {0x07,0x4c,0xaf,0x75}, {0x10,0x51,0xbd,0x6e}, {0x1d,0x5a,0xb3,0x67}, + {0x3e,0x6b,0x99,0x58}, {0x33,0x60,0x97,0x51}, {0x24,0x7d,0x85,0x4a}, {0x29,0x76,0x8b,0x43}, + {0x62,0x1f,0xd1,0x34}, {0x6f,0x14,0xdf,0x3d}, {0x78,0x09,0xcd,0x26}, {0x75,0x02,0xc3,0x2f}, + {0x56,0x33,0xe9,0x10}, {0x5b,0x38,0xe7,0x19}, {0x4c,0x25,0xf5,0x02}, {0x41,0x2e,0xfb,0x0b}, + {0x61,0x8c,0x9a,0xd7}, {0x6c,0x87,0x94,0xde}, {0x7b,0x9a,0x86,0xc5}, {0x76,0x91,0x88,0xcc}, + {0x55,0xa0,0xa2,0xf3}, {0x58,0xab,0xac,0xfa}, {0x4f,0xb6,0xbe,0xe1}, {0x42,0xbd,0xb0,0xe8}, + {0x09,0xd4,0xea,0x9f}, {0x04,0xdf,0xe4,0x96}, {0x13,0xc2,0xf6,0x8d}, {0x1e,0xc9,0xf8,0x84}, + {0x3d,0xf8,0xd2,0xbb}, {0x30,0xf3,0xdc,0xb2}, {0x27,0xee,0xce,0xa9}, {0x2a,0xe5,0xc0,0xa0}, + {0xb1,0x3c,0x7a,0x47}, {0xbc,0x37,0x74,0x4e}, {0xab,0x2a,0x66,0x55}, {0xa6,0x21,0x68,0x5c}, + {0x85,0x10,0x42,0x63}, {0x88,0x1b,0x4c,0x6a}, {0x9f,0x06,0x5e,0x71}, {0x92,0x0d,0x50,0x78}, + {0xd9,0x64,0x0a,0x0f}, {0xd4,0x6f,0x04,0x06}, {0xc3,0x72,0x16,0x1d}, {0xce,0x79,0x18,0x14}, + {0xed,0x48,0x32,0x2b}, {0xe0,0x43,0x3c,0x22}, {0xf7,0x5e,0x2e,0x39}, {0xfa,0x55,0x20,0x30}, + {0xb7,0x01,0xec,0x9a}, {0xba,0x0a,0xe2,0x93}, {0xad,0x17,0xf0,0x88}, {0xa0,0x1c,0xfe,0x81}, + {0x83,0x2d,0xd4,0xbe}, {0x8e,0x26,0xda,0xb7}, {0x99,0x3b,0xc8,0xac}, {0x94,0x30,0xc6,0xa5}, + {0xdf,0x59,0x9c,0xd2}, {0xd2,0x52,0x92,0xdb}, {0xc5,0x4f,0x80,0xc0}, {0xc8,0x44,0x8e,0xc9}, + {0xeb,0x75,0xa4,0xf6}, {0xe6,0x7e,0xaa,0xff}, {0xf1,0x63,0xb8,0xe4}, {0xfc,0x68,0xb6,0xed}, + {0x67,0xb1,0x0c,0x0a}, {0x6a,0xba,0x02,0x03}, {0x7d,0xa7,0x10,0x18}, {0x70,0xac,0x1e,0x11}, + {0x53,0x9d,0x34,0x2e}, {0x5e,0x96,0x3a,0x27}, {0x49,0x8b,0x28,0x3c}, {0x44,0x80,0x26,0x35}, + {0x0f,0xe9,0x7c,0x42}, {0x02,0xe2,0x72,0x4b}, {0x15,0xff,0x60,0x50}, {0x18,0xf4,0x6e,0x59}, + {0x3b,0xc5,0x44,0x66}, {0x36,0xce,0x4a,0x6f}, {0x21,0xd3,0x58,0x74}, {0x2c,0xd8,0x56,0x7d}, + {0x0c,0x7a,0x37,0xa1}, {0x01,0x71,0x39,0xa8}, {0x16,0x6c,0x2b,0xb3}, {0x1b,0x67,0x25,0xba}, + {0x38,0x56,0x0f,0x85}, {0x35,0x5d,0x01,0x8c}, {0x22,0x40,0x13,0x97}, {0x2f,0x4b,0x1d,0x9e}, + {0x64,0x22,0x47,0xe9}, {0x69,0x29,0x49,0xe0}, {0x7e,0x34,0x5b,0xfb}, {0x73,0x3f,0x55,0xf2}, + {0x50,0x0e,0x7f,0xcd}, {0x5d,0x05,0x71,0xc4}, {0x4a,0x18,0x63,0xdf}, {0x47,0x13,0x6d,0xd6}, + {0xdc,0xca,0xd7,0x31}, {0xd1,0xc1,0xd9,0x38}, {0xc6,0xdc,0xcb,0x23}, {0xcb,0xd7,0xc5,0x2a}, + {0xe8,0xe6,0xef,0x15}, {0xe5,0xed,0xe1,0x1c}, {0xf2,0xf0,0xf3,0x07}, {0xff,0xfb,0xfd,0x0e}, + {0xb4,0x92,0xa7,0x79}, {0xb9,0x99,0xa9,0x70}, {0xae,0x84,0xbb,0x6b}, {0xa3,0x8f,0xb5,0x62}, + {0x80,0xbe,0x9f,0x5d}, {0x8d,0xb5,0x91,0x54}, {0x9a,0xa8,0x83,0x4f}, {0x97,0xa3,0x8d,0x46} +}; + +static UINT8 U4[256][4]= +{ + {0x00,0x00,0x00,0x00}, {0x09,0x0d,0x0b,0x0e}, {0x12,0x1a,0x16,0x1c}, {0x1b,0x17,0x1d,0x12}, + {0x24,0x34,0x2c,0x38}, {0x2d,0x39,0x27,0x36}, {0x36,0x2e,0x3a,0x24}, {0x3f,0x23,0x31,0x2a}, + {0x48,0x68,0x58,0x70}, {0x41,0x65,0x53,0x7e}, {0x5a,0x72,0x4e,0x6c}, {0x53,0x7f,0x45,0x62}, + {0x6c,0x5c,0x74,0x48}, {0x65,0x51,0x7f,0x46}, {0x7e,0x46,0x62,0x54}, {0x77,0x4b,0x69,0x5a}, + {0x90,0xd0,0xb0,0xe0}, {0x99,0xdd,0xbb,0xee}, {0x82,0xca,0xa6,0xfc}, {0x8b,0xc7,0xad,0xf2}, + {0xb4,0xe4,0x9c,0xd8}, {0xbd,0xe9,0x97,0xd6}, {0xa6,0xfe,0x8a,0xc4}, {0xaf,0xf3,0x81,0xca}, + {0xd8,0xb8,0xe8,0x90}, {0xd1,0xb5,0xe3,0x9e}, {0xca,0xa2,0xfe,0x8c}, {0xc3,0xaf,0xf5,0x82}, + {0xfc,0x8c,0xc4,0xa8}, {0xf5,0x81,0xcf,0xa6}, {0xee,0x96,0xd2,0xb4}, {0xe7,0x9b,0xd9,0xba}, + {0x3b,0xbb,0x7b,0xdb}, {0x32,0xb6,0x70,0xd5}, {0x29,0xa1,0x6d,0xc7}, {0x20,0xac,0x66,0xc9}, + {0x1f,0x8f,0x57,0xe3}, {0x16,0x82,0x5c,0xed}, {0x0d,0x95,0x41,0xff}, {0x04,0x98,0x4a,0xf1}, + {0x73,0xd3,0x23,0xab}, {0x7a,0xde,0x28,0xa5}, {0x61,0xc9,0x35,0xb7}, {0x68,0xc4,0x3e,0xb9}, + {0x57,0xe7,0x0f,0x93}, {0x5e,0xea,0x04,0x9d}, {0x45,0xfd,0x19,0x8f}, {0x4c,0xf0,0x12,0x81}, + {0xab,0x6b,0xcb,0x3b}, {0xa2,0x66,0xc0,0x35}, {0xb9,0x71,0xdd,0x27}, {0xb0,0x7c,0xd6,0x29}, + {0x8f,0x5f,0xe7,0x03}, {0x86,0x52,0xec,0x0d}, {0x9d,0x45,0xf1,0x1f}, {0x94,0x48,0xfa,0x11}, + {0xe3,0x03,0x93,0x4b}, {0xea,0x0e,0x98,0x45}, {0xf1,0x19,0x85,0x57}, {0xf8,0x14,0x8e,0x59}, + {0xc7,0x37,0xbf,0x73}, {0xce,0x3a,0xb4,0x7d}, {0xd5,0x2d,0xa9,0x6f}, {0xdc,0x20,0xa2,0x61}, + {0x76,0x6d,0xf6,0xad}, {0x7f,0x60,0xfd,0xa3}, {0x64,0x77,0xe0,0xb1}, {0x6d,0x7a,0xeb,0xbf}, + {0x52,0x59,0xda,0x95}, {0x5b,0x54,0xd1,0x9b}, {0x40,0x43,0xcc,0x89}, {0x49,0x4e,0xc7,0x87}, + {0x3e,0x05,0xae,0xdd}, {0x37,0x08,0xa5,0xd3}, {0x2c,0x1f,0xb8,0xc1}, {0x25,0x12,0xb3,0xcf}, + {0x1a,0x31,0x82,0xe5}, {0x13,0x3c,0x89,0xeb}, {0x08,0x2b,0x94,0xf9}, {0x01,0x26,0x9f,0xf7}, + {0xe6,0xbd,0x46,0x4d}, {0xef,0xb0,0x4d,0x43}, {0xf4,0xa7,0x50,0x51}, {0xfd,0xaa,0x5b,0x5f}, + {0xc2,0x89,0x6a,0x75}, {0xcb,0x84,0x61,0x7b}, {0xd0,0x93,0x7c,0x69}, {0xd9,0x9e,0x77,0x67}, + {0xae,0xd5,0x1e,0x3d}, {0xa7,0xd8,0x15,0x33}, {0xbc,0xcf,0x08,0x21}, {0xb5,0xc2,0x03,0x2f}, + {0x8a,0xe1,0x32,0x05}, {0x83,0xec,0x39,0x0b}, {0x98,0xfb,0x24,0x19}, {0x91,0xf6,0x2f,0x17}, + {0x4d,0xd6,0x8d,0x76}, {0x44,0xdb,0x86,0x78}, {0x5f,0xcc,0x9b,0x6a}, {0x56,0xc1,0x90,0x64}, + {0x69,0xe2,0xa1,0x4e}, {0x60,0xef,0xaa,0x40}, {0x7b,0xf8,0xb7,0x52}, {0x72,0xf5,0xbc,0x5c}, + {0x05,0xbe,0xd5,0x06}, {0x0c,0xb3,0xde,0x08}, {0x17,0xa4,0xc3,0x1a}, {0x1e,0xa9,0xc8,0x14}, + {0x21,0x8a,0xf9,0x3e}, {0x28,0x87,0xf2,0x30}, {0x33,0x90,0xef,0x22}, {0x3a,0x9d,0xe4,0x2c}, + {0xdd,0x06,0x3d,0x96}, {0xd4,0x0b,0x36,0x98}, {0xcf,0x1c,0x2b,0x8a}, {0xc6,0x11,0x20,0x84}, + {0xf9,0x32,0x11,0xae}, {0xf0,0x3f,0x1a,0xa0}, {0xeb,0x28,0x07,0xb2}, {0xe2,0x25,0x0c,0xbc}, + {0x95,0x6e,0x65,0xe6}, {0x9c,0x63,0x6e,0xe8}, {0x87,0x74,0x73,0xfa}, {0x8e,0x79,0x78,0xf4}, + {0xb1,0x5a,0x49,0xde}, {0xb8,0x57,0x42,0xd0}, {0xa3,0x40,0x5f,0xc2}, {0xaa,0x4d,0x54,0xcc}, + {0xec,0xda,0xf7,0x41}, {0xe5,0xd7,0xfc,0x4f}, {0xfe,0xc0,0xe1,0x5d}, {0xf7,0xcd,0xea,0x53}, + {0xc8,0xee,0xdb,0x79}, {0xc1,0xe3,0xd0,0x77}, {0xda,0xf4,0xcd,0x65}, {0xd3,0xf9,0xc6,0x6b}, + {0xa4,0xb2,0xaf,0x31}, {0xad,0xbf,0xa4,0x3f}, {0xb6,0xa8,0xb9,0x2d}, {0xbf,0xa5,0xb2,0x23}, + {0x80,0x86,0x83,0x09}, {0x89,0x8b,0x88,0x07}, {0x92,0x9c,0x95,0x15}, {0x9b,0x91,0x9e,0x1b}, + {0x7c,0x0a,0x47,0xa1}, {0x75,0x07,0x4c,0xaf}, {0x6e,0x10,0x51,0xbd}, {0x67,0x1d,0x5a,0xb3}, + {0x58,0x3e,0x6b,0x99}, {0x51,0x33,0x60,0x97}, {0x4a,0x24,0x7d,0x85}, {0x43,0x29,0x76,0x8b}, + {0x34,0x62,0x1f,0xd1}, {0x3d,0x6f,0x14,0xdf}, {0x26,0x78,0x09,0xcd}, {0x2f,0x75,0x02,0xc3}, + {0x10,0x56,0x33,0xe9}, {0x19,0x5b,0x38,0xe7}, {0x02,0x4c,0x25,0xf5}, {0x0b,0x41,0x2e,0xfb}, + {0xd7,0x61,0x8c,0x9a}, {0xde,0x6c,0x87,0x94}, {0xc5,0x7b,0x9a,0x86}, {0xcc,0x76,0x91,0x88}, + {0xf3,0x55,0xa0,0xa2}, {0xfa,0x58,0xab,0xac}, {0xe1,0x4f,0xb6,0xbe}, {0xe8,0x42,0xbd,0xb0}, + {0x9f,0x09,0xd4,0xea}, {0x96,0x04,0xdf,0xe4}, {0x8d,0x13,0xc2,0xf6}, {0x84,0x1e,0xc9,0xf8}, + {0xbb,0x3d,0xf8,0xd2}, {0xb2,0x30,0xf3,0xdc}, {0xa9,0x27,0xee,0xce}, {0xa0,0x2a,0xe5,0xc0}, + {0x47,0xb1,0x3c,0x7a}, {0x4e,0xbc,0x37,0x74}, {0x55,0xab,0x2a,0x66}, {0x5c,0xa6,0x21,0x68}, + {0x63,0x85,0x10,0x42}, {0x6a,0x88,0x1b,0x4c}, {0x71,0x9f,0x06,0x5e}, {0x78,0x92,0x0d,0x50}, + {0x0f,0xd9,0x64,0x0a}, {0x06,0xd4,0x6f,0x04}, {0x1d,0xc3,0x72,0x16}, {0x14,0xce,0x79,0x18}, + {0x2b,0xed,0x48,0x32}, {0x22,0xe0,0x43,0x3c}, {0x39,0xf7,0x5e,0x2e}, {0x30,0xfa,0x55,0x20}, + {0x9a,0xb7,0x01,0xec}, {0x93,0xba,0x0a,0xe2}, {0x88,0xad,0x17,0xf0}, {0x81,0xa0,0x1c,0xfe}, + {0xbe,0x83,0x2d,0xd4}, {0xb7,0x8e,0x26,0xda}, {0xac,0x99,0x3b,0xc8}, {0xa5,0x94,0x30,0xc6}, + {0xd2,0xdf,0x59,0x9c}, {0xdb,0xd2,0x52,0x92}, {0xc0,0xc5,0x4f,0x80}, {0xc9,0xc8,0x44,0x8e}, + {0xf6,0xeb,0x75,0xa4}, {0xff,0xe6,0x7e,0xaa}, {0xe4,0xf1,0x63,0xb8}, {0xed,0xfc,0x68,0xb6}, + {0x0a,0x67,0xb1,0x0c}, {0x03,0x6a,0xba,0x02}, {0x18,0x7d,0xa7,0x10}, {0x11,0x70,0xac,0x1e}, + {0x2e,0x53,0x9d,0x34}, {0x27,0x5e,0x96,0x3a}, {0x3c,0x49,0x8b,0x28}, {0x35,0x44,0x80,0x26}, + {0x42,0x0f,0xe9,0x7c}, {0x4b,0x02,0xe2,0x72}, {0x50,0x15,0xff,0x60}, {0x59,0x18,0xf4,0x6e}, + {0x66,0x3b,0xc5,0x44}, {0x6f,0x36,0xce,0x4a}, {0x74,0x21,0xd3,0x58}, {0x7d,0x2c,0xd8,0x56}, + {0xa1,0x0c,0x7a,0x37}, {0xa8,0x01,0x71,0x39}, {0xb3,0x16,0x6c,0x2b}, {0xba,0x1b,0x67,0x25}, + {0x85,0x38,0x56,0x0f}, {0x8c,0x35,0x5d,0x01}, {0x97,0x22,0x40,0x13}, {0x9e,0x2f,0x4b,0x1d}, + {0xe9,0x64,0x22,0x47}, {0xe0,0x69,0x29,0x49}, {0xfb,0x7e,0x34,0x5b}, {0xf2,0x73,0x3f,0x55}, + {0xcd,0x50,0x0e,0x7f}, {0xc4,0x5d,0x05,0x71}, {0xdf,0x4a,0x18,0x63}, {0xd6,0x47,0x13,0x6d}, + {0x31,0xdc,0xca,0xd7}, {0x38,0xd1,0xc1,0xd9}, {0x23,0xc6,0xdc,0xcb}, {0x2a,0xcb,0xd7,0xc5}, + {0x15,0xe8,0xe6,0xef}, {0x1c,0xe5,0xed,0xe1}, {0x07,0xf2,0xf0,0xf3}, {0x0e,0xff,0xfb,0xfd}, + {0x79,0xb4,0x92,0xa7}, {0x70,0xb9,0x99,0xa9}, {0x6b,0xae,0x84,0xbb}, {0x62,0xa3,0x8f,0xb5}, + {0x5d,0x80,0xbe,0x9f}, {0x54,0x8d,0xb5,0x91}, {0x4f,0x9a,0xa8,0x83}, {0x46,0x97,0xa3,0x8d} +}; + +static UINT32 rcon[30]= +{ + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, + 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, + 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, + 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, + 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 +}; + +/* +////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// API +////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +*/ + +SQLITE_PRIVATE +void RijndaelCreate(Rijndael* rijndael) +{ + rijndael->m_state = RIJNDAEL_State_Invalid; +} + +SQLITE_PRIVATE +int RijndaelInit(Rijndael* rijndael, int mode, int dir, UINT8* key, int keyLen, UINT8* initVector) +{ + UINT32 uKeyLenInBytes; + UINT8 keyMatrix[_MAX_KEY_COLUMNS][4]; + UINT32 i; +#ifdef TEST_AES_HW + UINT8 aesKeySched[15*16]; +#endif + + /* Not initialized yet */ + rijndael->m_state = RIJNDAEL_State_Invalid; + + /* Check the mode */ + if ((mode != RIJNDAEL_Direction_Mode_CBC) && (mode != RIJNDAEL_Direction_Mode_ECB) && (mode != RIJNDAEL_Direction_Mode_CFB1)) return RIJNDAEL_UNSUPPORTED_MODE; + rijndael->m_mode = mode; + + /* And the direction */ + if ((dir != RIJNDAEL_Direction_Encrypt) && (dir != RIJNDAEL_Direction_Decrypt)) return RIJNDAEL_UNSUPPORTED_DIRECTION; + rijndael->m_direction = dir; + + /* Allow to set an init vector */ + if (initVector) + { + /* specified init vector */ + for(i = 0;i < MAX_IV_SIZE;i++) + { + rijndael->m_initVector[i] = initVector[i]; + } + } else { + /* zero init vector */ + for(i = 0;i < MAX_IV_SIZE;i++) + { + rijndael->m_initVector[i] = 0; + } + } + + /* And check the key length */ + switch (keyLen) + { + case RIJNDAEL_Direction_KeyLength_Key16Bytes: + uKeyLenInBytes = 16; + rijndael->m_uRounds = 10; + break; + case RIJNDAEL_Direction_KeyLength_Key24Bytes: + uKeyLenInBytes = 24; + rijndael->m_uRounds = 12; + break; + case RIJNDAEL_Direction_KeyLength_Key32Bytes: + uKeyLenInBytes = 32; + rijndael->m_uRounds = 14; + break; + default: + return RIJNDAEL_UNSUPPORTED_KEY_LENGTH; + break; + } + /* The number of rounds is calculated as */ + /* m_uRounds = (m_uKeyLenInBits / 32) + 6; */ + + if (!key) return RIJNDAEL_BAD_KEY; + +#if HAS_AES_HARDWARE + if (aesHardwareAvailable()) + { + if (rijndael->m_direction == RIJNDAEL_Direction_Encrypt) + { +#ifndef TEST_AES_HW + aesGenKeyEncrypt(key, uKeyLenInBytes*8, (unsigned char*) rijndael->m_expandedKey); +#else + TEST_AES_HW_DEBUG_LOG("aes gen key enc: hw enabled\n"); + aesGenKeyEncrypt(key, uKeyLenInBytes*8, (unsigned char*) aesKeySched); + TEST_AES_HW_DEBUG_LOG("aes gen key enc: ready\n"); +#endif + } + else + { +#ifndef TEST_AES_HW + aesGenKeyDecrypt(key, uKeyLenInBytes*8, (unsigned char*) rijndael->m_expandedKey); +#else + TEST_AES_HW_DEBUG_LOG("aes gen key dec: hw enabled\n"); + aesGenKeyDecrypt(key, uKeyLenInBytes*8, (unsigned char*) aesKeySched); + TEST_AES_HW_DEBUG_LOG("aes gen key dec: ready\n"); +#endif + } + } +#ifndef TEST_AES_HW + else +#endif +#endif + { + for (i = 0; i < uKeyLenInBytes; i++) keyMatrix[i >> 2][i & 3] = key[i]; + + RijndaelKeySched(rijndael, keyMatrix); + + if (rijndael->m_direction == RIJNDAEL_Direction_Decrypt) RijndaelKeyEncToDec(rijndael); + } + +#ifdef TEST_AES_HW + { + int cmpkeyexp = memcmp((unsigned char*) rijndael->m_expandedKey, aesKeySched, (rijndael->m_uRounds+1)*16); + int datalen = (rijndael->m_uRounds + 1) * 16; + TEST_AES_HW_DEBUG_LOG("aes gen key: cmp=%d\n", cmpkeyexp); + TEST_AES_HW_DEBUG_HEX("aes gen key SW:", (unsigned char*) rijndael->m_expandedKey, datalen); + TEST_AES_HW_DEBUG_HEX("aes gen key HW:", aesKeySched, datalen); + } +#endif + + rijndael->m_state = RIJNDAEL_State_Valid; + return RIJNDAEL_SUCCESS; +} + +int RijndaelBlockEncrypt(Rijndael* rijndael, UINT8* input, int inputLen, UINT8* outBuffer) +{ + int i, k, numBlocks, lenFrag; + UINT8 block[16], iv[4][4]; + UINT8* outOrig = outBuffer; +#ifdef TEST_AES_HW + UINT8 outBuffer2[70000]; +#endif + + if (rijndael->m_state != RIJNDAEL_State_Valid) return RIJNDAEL_NOT_INITIALIZED; + if (rijndael->m_direction != RIJNDAEL_Direction_Encrypt) return RIJNDAEL_BAD_DIRECTION; + + if (input == 0 || inputLen <= 0) return 0; + + numBlocks = inputLen/128; + lenFrag = (inputLen % 128) / 8; + + switch (rijndael->m_mode) + { + case RIJNDAEL_Direction_Mode_ECB: + for(i = numBlocks;i > 0;i--) + { + RijndaelEncrypt(rijndael, input, outBuffer); + input += 16; + outBuffer += 16; + } + break; + case RIJNDAEL_Direction_Mode_CBC: +#if HAS_AES_HARDWARE + if (aesHardwareAvailable()) + { +#ifndef TEST_AES_HW + aesEncryptCBC(input, outBuffer, rijndael->m_initVector, inputLen/8, (unsigned char*) (rijndael->m_expandedKey), rijndael->m_uRounds); +#else + TEST_AES_HW_DEBUG_LOG("aes enc: hw enabled\n"); + aesEncryptCBC(input, outBuffer2, rijndael->m_initVector, inputLen/8, (unsigned char*) (rijndael->m_expandedKey), rijndael->m_uRounds); +#endif + } +#ifndef TEST_AES_HW + else +#endif +#endif + { + ((UINT32*)block)[0] = ((UINT32*)rijndael->m_initVector)[0] ^ ((UINT32*)input)[0]; + ((UINT32*)block)[1] = ((UINT32*)rijndael->m_initVector)[1] ^ ((UINT32*)input)[1]; + ((UINT32*)block)[2] = ((UINT32*)rijndael->m_initVector)[2] ^ ((UINT32*)input)[2]; + ((UINT32*)block)[3] = ((UINT32*)rijndael->m_initVector)[3] ^ ((UINT32*)input)[3]; + RijndaelEncrypt(rijndael, block,outBuffer); + input += 16; + for(i = numBlocks - 1;i > 0;i--) + { + ((UINT32*)block)[0] = ((UINT32*)outBuffer)[0] ^ ((UINT32*)input)[0]; + ((UINT32*)block)[1] = ((UINT32*)outBuffer)[1] ^ ((UINT32*)input)[1]; + ((UINT32*)block)[2] = ((UINT32*)outBuffer)[2] ^ ((UINT32*)input)[2]; + ((UINT32*)block)[3] = ((UINT32*)outBuffer)[3] ^ ((UINT32*)input)[3]; + outBuffer += 16; + RijndaelEncrypt(rijndael, block,outBuffer); + input += 16; + } + /**/ + if (lenFrag > 0) + { + UINT8 lastblock[16]; + /* Adjust the second last plain block. */ + memcpy(lastblock, outBuffer, lenFrag); + /* Encrypt the last plain block. */ + memcpy(block, outBuffer, 16); + for (i = 0; i < lenFrag; i++) + { + block[i] ^= input[i]; + } + RijndaelEncrypt(rijndael, block, outBuffer); + memcpy(outBuffer + 16, lastblock, lenFrag); + } + } + break; + case RIJNDAEL_Direction_Mode_CFB1: +#if STRICT_ALIGN + memcpy(iv,rijndael->m_initVector,16); +#else /* !STRICT_ALIGN */ + *((UINT32*)iv[0]) = *((UINT32*)(rijndael->m_initVector )); + *((UINT32*)iv[1]) = *((UINT32*)(rijndael->m_initVector + 4)); + *((UINT32*)iv[2]) = *((UINT32*)(rijndael->m_initVector + 8)); + *((UINT32*)iv[3]) = *((UINT32*)(rijndael->m_initVector +12)); +#endif /* ?STRICT_ALIGN */ + for(i = numBlocks; i > 0; i--) + { + memcpy(outBuffer, input, 16); + for(k = 0; k < 128; k++) + { + *((UINT32*) block ) = *((UINT32*)iv[0]); + *((UINT32*)(block+ 4)) = *((UINT32*)iv[1]); + *((UINT32*)(block+ 8)) = *((UINT32*)iv[2]); + *((UINT32*)(block+12)) = *((UINT32*)iv[3]); + RijndaelEncrypt(rijndael, block, block); + outBuffer[k/8] ^= (block[0] & 0x80) >> (k & 7); + iv[0][0] = (UINT8) ((iv[0][0] << 1) | (iv[0][1] >> 7)); + iv[0][1] = (UINT8) ((iv[0][1] << 1) | (iv[0][2] >> 7)); + iv[0][2] = (UINT8) ((iv[0][2] << 1) | (iv[0][3] >> 7)); + iv[0][3] = (UINT8) ((iv[0][3] << 1) | (iv[1][0] >> 7)); + iv[1][0] = (UINT8) ((iv[1][0] << 1) | (iv[1][1] >> 7)); + iv[1][1] = (UINT8) ((iv[1][1] << 1) | (iv[1][2] >> 7)); + iv[1][2] = (UINT8) ((iv[1][2] << 1) | (iv[1][3] >> 7)); + iv[1][3] = (UINT8) ((iv[1][3] << 1) | (iv[2][0] >> 7)); + iv[2][0] = (UINT8) ((iv[2][0] << 1) | (iv[2][1] >> 7)); + iv[2][1] = (UINT8) ((iv[2][1] << 1) | (iv[2][2] >> 7)); + iv[2][2] = (UINT8) ((iv[2][2] << 1) | (iv[2][3] >> 7)); + iv[2][3] = (UINT8) ((iv[2][3] << 1) | (iv[3][0] >> 7)); + iv[3][0] = (UINT8) ((iv[3][0] << 1) | (iv[3][1] >> 7)); + iv[3][1] = (UINT8) ((iv[3][1] << 1) | (iv[3][2] >> 7)); + iv[3][2] = (UINT8) ((iv[3][2] << 1) | (iv[3][3] >> 7)); + iv[3][3] = (UINT8) ((iv[3][3] << 1) | ((outBuffer[k/8] >> (7-(k&7))) & 1)); + } + outBuffer += 16; + input += 16; + } + break; + default: + return -1; + break; + } + +#ifdef TEST_AES_HW + { + int cmpdata = memcmp((unsigned char*) outOrig, outBuffer2, inputLen/8); + TEST_AES_HW_DEBUG_LOG("aes enc: cmp=%d\n", cmpdata); + TEST_AES_HW_DEBUG_HEX("aes enc SW:", outOrig, 16); + TEST_AES_HW_DEBUG_HEX("aes enc HW:", outBuffer2, 16); + } +#endif + + return 128 * numBlocks; +} + +SQLITE_PRIVATE +int RijndaelPadEncrypt(Rijndael* rijndael, UINT8 *input, int inputOctets, UINT8 *outBuffer) +{ + int i, numBlocks, padLen; + UINT8 block[16], *iv; + + if (rijndael->m_state != RIJNDAEL_State_Valid) return RIJNDAEL_NOT_INITIALIZED; + if (rijndael->m_direction != RIJNDAEL_Direction_Encrypt) return RIJNDAEL_NOT_INITIALIZED; + + if (input == 0 || inputOctets <= 0) return 0; + + numBlocks = inputOctets/16; + + switch (rijndael->m_mode) + { + case RIJNDAEL_Direction_Mode_ECB: + for(i = numBlocks; i > 0; i--) + { + RijndaelEncrypt(rijndael, input, outBuffer); + input += 16; + outBuffer += 16; + } + padLen = 16 - (inputOctets - 16*numBlocks); +/* assert(padLen > 0 && padLen <= 16); */ + memcpy(block, input, 16 - padLen); + memset(block + 16 - padLen, padLen, padLen); + RijndaelEncrypt(rijndael, block,outBuffer); + break; + case RIJNDAEL_Direction_Mode_CBC: + iv = rijndael->m_initVector; + for(i = numBlocks; i > 0; i--) + { + ((UINT32*)block)[0] = ((UINT32*)input)[0] ^ ((UINT32*)iv)[0]; + ((UINT32*)block)[1] = ((UINT32*)input)[1] ^ ((UINT32*)iv)[1]; + ((UINT32*)block)[2] = ((UINT32*)input)[2] ^ ((UINT32*)iv)[2]; + ((UINT32*)block)[3] = ((UINT32*)input)[3] ^ ((UINT32*)iv)[3]; + RijndaelEncrypt(rijndael, block, outBuffer); + iv = outBuffer; + input += 16; + outBuffer += 16; + } + padLen = 16 - (inputOctets - 16*numBlocks); +/* assert(padLen > 0 && padLen <= 16); // DO SOMETHING HERE ? */ + for (i = 0; i < 16 - padLen; i++) { + block[i] = (UINT8) (input[i] ^ iv[i]); + } + for (i = 16 - padLen; i < 16; i++) { + block[i] = (UINT8) ((UINT8) padLen ^ iv[i]); + } + RijndaelEncrypt(rijndael, block,outBuffer); + break; + default: + return -1; + break; + } + + return 16*(numBlocks + 1); +} + +SQLITE_PRIVATE +int RijndaelBlockDecrypt(Rijndael* rijndael, UINT8* input, int inputLen, UINT8* outBuffer) +{ + int i, k, numBlocks, lenFrag; + UINT8 block[16], iv[4][4]; + UINT8* outOrig = outBuffer; +#ifdef TEST_AES_HW + UINT8 outBuffer2[70000]; +#endif + + if (rijndael->m_state != RIJNDAEL_State_Valid) return RIJNDAEL_NOT_INITIALIZED; + if ((rijndael->m_mode != RIJNDAEL_Direction_Mode_CFB1) && (rijndael->m_direction == RIJNDAEL_Direction_Encrypt)) return RIJNDAEL_BAD_DIRECTION; + + if (input == 0 || inputLen <= 0)return 0; + + numBlocks = inputLen/128; + lenFrag = (inputLen % 128) / 8; + + switch (rijndael->m_mode) + { + case RIJNDAEL_Direction_Mode_ECB: + for (i = numBlocks; i > 0; i--) + { + RijndaelDecrypt(rijndael, input, outBuffer); + input += 16; + outBuffer += 16; + } + break; + case RIJNDAEL_Direction_Mode_CBC: +#if HAS_AES_HARDWARE + if (aesHardwareAvailable()) + { +#ifndef TEST_AES_HW + aesDecryptCBC(input, outBuffer, rijndael->m_initVector, inputLen/8, (unsigned char*) (rijndael->m_expandedKey), rijndael->m_uRounds); +#else + TEST_AES_HW_DEBUG_LOG("aes dec: hw enabled\n"); + aesDecryptCBC(input, outBuffer2, rijndael->m_initVector, inputLen/8, (unsigned char*) (rijndael->m_expandedKey), rijndael->m_uRounds); +#endif + } +#ifndef TEST_AES_HW + else +#endif +#endif + { + if (lenFrag > 0) + { + UINT8 lastblock[16]; + int offset; + --numBlocks; + offset = numBlocks * 16; + /* Decrypt the last plain block. */ + RijndaelDecrypt(rijndael, input + offset, block); + for (i = 0; i < lenFrag; i++) + { + lastblock[i] = block[i] ^ (input + offset + 16)[i]; + } + /* Decrypt the second last block. */ + memcpy(block, input + offset + 16, lenFrag); + RijndaelDecrypt(rijndael, block, outBuffer + offset); + memcpy(outBuffer + offset + 16, lastblock, lenFrag); + if (offset == 0) + { + for (i = 0; i < 16; i++) + { + (outBuffer + offset)[i] ^= rijndael->m_initVector[i]; + } + } + else + { + for (i = 0; i < 16; i++) + { + (outBuffer + offset)[i] ^= (input + offset - 16)[i]; + } + } + } +#if STRICT_ALIGN + memcpy(iv,rijndael->m_initVector,16); +#else + *((UINT32*)iv[0]) = *((UINT32*)(rijndael->m_initVector )); + *((UINT32*)iv[1]) = *((UINT32*)(rijndael->m_initVector+ 4)); + *((UINT32*)iv[2]) = *((UINT32*)(rijndael->m_initVector+ 8)); + *((UINT32*)iv[3]) = *((UINT32*)(rijndael->m_initVector+12)); +#endif + for (i = numBlocks; i > 0; i--) + { + RijndaelDecrypt(rijndael, input, block); + ((UINT32*)block)[0] ^= *((UINT32*)iv[0]); + ((UINT32*)block)[1] ^= *((UINT32*)iv[1]); + ((UINT32*)block)[2] ^= *((UINT32*)iv[2]); + ((UINT32*)block)[3] ^= *((UINT32*)iv[3]); +#if STRICT_ALIGN + memcpy(iv, input, 16); + memcpy(outBuf, block, 16); +#else + *((UINT32*)iv[0]) = ((UINT32*)input)[0]; ((UINT32*)outBuffer)[0] = ((UINT32*)block)[0]; + *((UINT32*)iv[1]) = ((UINT32*)input)[1]; ((UINT32*)outBuffer)[1] = ((UINT32*)block)[1]; + *((UINT32*)iv[2]) = ((UINT32*)input)[2]; ((UINT32*)outBuffer)[2] = ((UINT32*)block)[2]; + *((UINT32*)iv[3]) = ((UINT32*)input)[3]; ((UINT32*)outBuffer)[3] = ((UINT32*)block)[3]; +#endif + input += 16; + outBuffer += 16; + } + } + break; + case RIJNDAEL_Direction_Mode_CFB1: +#if STRICT_ALIGN + memcpy(iv, rijndael->m_initVector, 16); +#else + *((UINT32*)iv[0]) = *((UINT32*)(rijndael->m_initVector)); + *((UINT32*)iv[1]) = *((UINT32*)(rijndael->m_initVector+ 4)); + *((UINT32*)iv[2]) = *((UINT32*)(rijndael->m_initVector+ 8)); + *((UINT32*)iv[3]) = *((UINT32*)(rijndael->m_initVector+12)); +#endif + for(i = numBlocks; i > 0; i--) + { + memcpy(outBuffer, input, 16); + for(k = 0; k < 128; k++) + { + *((UINT32*) block ) = *((UINT32*)iv[0]); + *((UINT32*)(block+ 4)) = *((UINT32*)iv[1]); + *((UINT32*)(block+ 8)) = *((UINT32*)iv[2]); + *((UINT32*)(block+12)) = *((UINT32*)iv[3]); + RijndaelEncrypt(rijndael, block, block); + iv[0][0] = (UINT8) ((iv[0][0] << 1) | (iv[0][1] >> 7)); + iv[0][1] = (UINT8) ((iv[0][1] << 1) | (iv[0][2] >> 7)); + iv[0][2] = (UINT8) ((iv[0][2] << 1) | (iv[0][3] >> 7)); + iv[0][3] = (UINT8) ((iv[0][3] << 1) | (iv[1][0] >> 7)); + iv[1][0] = (UINT8) ((iv[1][0] << 1) | (iv[1][1] >> 7)); + iv[1][1] = (UINT8) ((iv[1][1] << 1) | (iv[1][2] >> 7)); + iv[1][2] = (UINT8) ((iv[1][2] << 1) | (iv[1][3] >> 7)); + iv[1][3] = (UINT8) ((iv[1][3] << 1) | (iv[2][0] >> 7)); + iv[2][0] = (UINT8) ((iv[2][0] << 1) | (iv[2][1] >> 7)); + iv[2][1] = (UINT8) ((iv[2][1] << 1) | (iv[2][2] >> 7)); + iv[2][2] = (UINT8) ((iv[2][2] << 1) | (iv[2][3] >> 7)); + iv[2][3] = (UINT8) ((iv[2][3] << 1) | (iv[3][0] >> 7)); + iv[3][0] = (UINT8) ((iv[3][0] << 1) | (iv[3][1] >> 7)); + iv[3][1] = (UINT8) ((iv[3][1] << 1) | (iv[3][2] >> 7)); + iv[3][2] = (UINT8) ((iv[3][2] << 1) | (iv[3][3] >> 7)); + iv[3][3] = (UINT8) ((iv[3][3] << 1) | ((input[k/8] >> (7-(k&7))) & 1)); + outBuffer[k/8] ^= (block[0] & 0x80) >> (k & 7); + } + outBuffer += 16; + input += 16; + } + break; + default: + return -1; + break; + } + +#ifdef TEST_AES_HW + { + int cmpdata = memcmp((unsigned char*) outOrig, outBuffer2, inputLen/8); + TEST_AES_HW_DEBUG_LOG("aes dec: cmp=%d\n", cmpdata); + TEST_AES_HW_DEBUG_HEX("aes dec SW:", outOrig, 16); + TEST_AES_HW_DEBUG_HEX("aes dec HW:", outBuffer2, 16); + } +#endif + + return 128*numBlocks; +} + +SQLITE_PRIVATE +int RijndaelPadDecrypt(Rijndael* rijndael, UINT8 *input, int inputOctets, UINT8 *outBuffer) +{ + int i, numBlocks, padLen; + UINT8 block[16]; + UINT32 iv[4]; + + if (rijndael->m_state != RIJNDAEL_State_Valid) return RIJNDAEL_NOT_INITIALIZED; + if (rijndael->m_direction != RIJNDAEL_Direction_Decrypt) return RIJNDAEL_BAD_DIRECTION; + + if (input == 0 || inputOctets <= 0) return 0; + + if ((inputOctets % 16) != 0) return RIJNDAEL_CORRUPTED_DATA; + + numBlocks = inputOctets/16; + + switch (rijndael->m_mode) + { + case RIJNDAEL_Direction_Mode_ECB: + for (i = numBlocks - 1; i > 0; i--) + { + RijndaelDecrypt(rijndael, input, outBuffer); + input += 16; + outBuffer += 16; + } + + RijndaelDecrypt(rijndael, input, block); + padLen = block[15]; + if (padLen >= 16) return RIJNDAEL_CORRUPTED_DATA; + for(i = 16 - padLen; i < 16; i++) + { + if (block[i] != padLen) return RIJNDAEL_CORRUPTED_DATA; + } + memcpy(outBuffer, block, 16 - padLen); + break; + case RIJNDAEL_Direction_Mode_CBC: + memcpy(iv, rijndael->m_initVector, 16); + /* all blocks but last */ + for (i = numBlocks - 1; i > 0; i--) + { + RijndaelDecrypt(rijndael, input, block); + ((UINT32*)block)[0] ^= iv[0]; + ((UINT32*)block)[1] ^= iv[1]; + ((UINT32*)block)[2] ^= iv[2]; + ((UINT32*)block)[3] ^= iv[3]; + memcpy(iv, input, 16); + memcpy(outBuffer, block, 16); + input += 16; + outBuffer += 16; + } + /* last block */ + RijndaelDecrypt(rijndael, input, block); + ((UINT32*)block)[0] ^= iv[0]; + ((UINT32*)block)[1] ^= iv[1]; + ((UINT32*)block)[2] ^= iv[2]; + ((UINT32*)block)[3] ^= iv[3]; + padLen = block[15]; + if(padLen <= 0 || padLen > 16)return RIJNDAEL_CORRUPTED_DATA; + for(i = 16 - padLen; i < 16; i++) + { + if(block[i] != padLen)return RIJNDAEL_CORRUPTED_DATA; + } + memcpy(outBuffer, block, 16 - padLen); + break; + + default: + return -1; + break; + } + + return 16*numBlocks - padLen; +} + +/* +////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ALGORITHM +////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +*/ + +SQLITE_PRIVATE +void RijndaelKeySched(Rijndael* rijndael, UINT8 key[_MAX_KEY_COLUMNS][4]) +{ + int j,rconpointer = 0; + + /* Calculate the necessary round keys */ + /* The number of calculations depends on keyBits and blockBits */ + int uKeyColumns = rijndael->m_uRounds - 6; + + UINT8 tempKey[_MAX_KEY_COLUMNS][4]; + + UINT32 r = 0; + int t = 0; + + /* Copy the input key to the temporary key matrix */ + + for(j = 0;j < uKeyColumns;j++) + { + *((UINT32*)(tempKey[j])) = *((UINT32*)(key[j])); + } + + + /* copy values into round key array */ + for(j = 0;(j < uKeyColumns) && (r <= rijndael->m_uRounds); ) + { + for(;(j < uKeyColumns) && (t < 4); j++, t++) + { + *((UINT32*)rijndael->m_expandedKey[r][t]) = *((UINT32*)tempKey[j]); + } + + + if(t == 4) + { + r++; + t = 0; + } + } + + while(r <= rijndael->m_uRounds) + { + tempKey[0][0] ^= S[tempKey[uKeyColumns-1][1]]; + tempKey[0][1] ^= S[tempKey[uKeyColumns-1][2]]; + tempKey[0][2] ^= S[tempKey[uKeyColumns-1][3]]; + tempKey[0][3] ^= S[tempKey[uKeyColumns-1][0]]; + tempKey[0][0] ^= rcon[rconpointer++]; + + if (uKeyColumns != 8) + { + for(j = 1; j < uKeyColumns; j++) + { + *((UINT32*)tempKey[j]) ^= *((UINT32*)tempKey[j-1]); + } + } else { + for(j = 1; j < uKeyColumns/2; j++) + { + *((UINT32*)tempKey[j]) ^= *((UINT32*)tempKey[j-1]); + } + tempKey[uKeyColumns/2][0] ^= S[tempKey[uKeyColumns/2 - 1][0]]; + tempKey[uKeyColumns/2][1] ^= S[tempKey[uKeyColumns/2 - 1][1]]; + tempKey[uKeyColumns/2][2] ^= S[tempKey[uKeyColumns/2 - 1][2]]; + tempKey[uKeyColumns/2][3] ^= S[tempKey[uKeyColumns/2 - 1][3]]; + for(j = uKeyColumns/2 + 1; j < uKeyColumns; j++) + { + *((UINT32*)tempKey[j]) ^= *((UINT32*)tempKey[j-1]); + } + } + for(j = 0; (j < uKeyColumns) && (r <= rijndael->m_uRounds); ) + { + for(; (j < uKeyColumns) && (t < 4); j++, t++) + { + *((UINT32*)rijndael->m_expandedKey[r][t]) = *((UINT32*)tempKey[j]); + } + if(t == 4) + { + r++; + t = 0; + } + } + } +} + +SQLITE_PRIVATE +void RijndaelKeyEncToDec(Rijndael* rijndael) +{ + UINT32 r; + UINT8 *w; + + for(r = 1; r < rijndael->m_uRounds; r++) + { + w = rijndael->m_expandedKey[r][0]; + *((UINT32*)w) = *((UINT32*)U1[w[0]]) ^ *((UINT32*)U2[w[1]]) ^ *((UINT32*)U3[w[2]]) ^ *((UINT32*)U4[w[3]]); + w = rijndael->m_expandedKey[r][1]; + *((UINT32*)w) = *((UINT32*)U1[w[0]]) ^ *((UINT32*)U2[w[1]]) ^ *((UINT32*)U3[w[2]]) ^ *((UINT32*)U4[w[3]]); + w = rijndael->m_expandedKey[r][2]; + *((UINT32*)w) = *((UINT32*)U1[w[0]]) ^ *((UINT32*)U2[w[1]]) ^ *((UINT32*)U3[w[2]]) ^ *((UINT32*)U4[w[3]]); + w = rijndael->m_expandedKey[r][3]; + *((UINT32*)w) = *((UINT32*)U1[w[0]]) ^ *((UINT32*)U2[w[1]]) ^ *((UINT32*)U3[w[2]]) ^ *((UINT32*)U4[w[3]]); + } +} + +SQLITE_PRIVATE +void RijndaelEncrypt(Rijndael* rijndael, UINT8 a[16], UINT8 b[16]) +{ + UINT32 r; + UINT8 temp[4][4]; + + *((UINT32*)temp[0]) = *((UINT32*)(a )) ^ *((UINT32*)rijndael->m_expandedKey[0][0]); + *((UINT32*)temp[1]) = *((UINT32*)(a+ 4)) ^ *((UINT32*)rijndael->m_expandedKey[0][1]); + *((UINT32*)temp[2]) = *((UINT32*)(a+ 8)) ^ *((UINT32*)rijndael->m_expandedKey[0][2]); + *((UINT32*)temp[3]) = *((UINT32*)(a+12)) ^ *((UINT32*)rijndael->m_expandedKey[0][3]); + *((UINT32*)(b )) = *((UINT32*)T1[temp[0][0]]) + ^ *((UINT32*)T2[temp[1][1]]) + ^ *((UINT32*)T3[temp[2][2]]) + ^ *((UINT32*)T4[temp[3][3]]); + *((UINT32*)(b + 4)) = *((UINT32*)T1[temp[1][0]]) + ^ *((UINT32*)T2[temp[2][1]]) + ^ *((UINT32*)T3[temp[3][2]]) + ^ *((UINT32*)T4[temp[0][3]]); + *((UINT32*)(b + 8)) = *((UINT32*)T1[temp[2][0]]) + ^ *((UINT32*)T2[temp[3][1]]) + ^ *((UINT32*)T3[temp[0][2]]) + ^ *((UINT32*)T4[temp[1][3]]); + *((UINT32*)(b +12)) = *((UINT32*)T1[temp[3][0]]) + ^ *((UINT32*)T2[temp[0][1]]) + ^ *((UINT32*)T3[temp[1][2]]) + ^ *((UINT32*)T4[temp[2][3]]); + for(r = 1; r < rijndael->m_uRounds-1; r++) + { + *((UINT32*)temp[0]) = *((UINT32*)(b )) ^ *((UINT32*)rijndael->m_expandedKey[r][0]); + *((UINT32*)temp[1]) = *((UINT32*)(b+ 4)) ^ *((UINT32*)rijndael->m_expandedKey[r][1]); + *((UINT32*)temp[2]) = *((UINT32*)(b+ 8)) ^ *((UINT32*)rijndael->m_expandedKey[r][2]); + *((UINT32*)temp[3]) = *((UINT32*)(b+12)) ^ *((UINT32*)rijndael->m_expandedKey[r][3]); + + *((UINT32*)(b )) = *((UINT32*)T1[temp[0][0]]) + ^ *((UINT32*)T2[temp[1][1]]) + ^ *((UINT32*)T3[temp[2][2]]) + ^ *((UINT32*)T4[temp[3][3]]); + *((UINT32*)(b + 4)) = *((UINT32*)T1[temp[1][0]]) + ^ *((UINT32*)T2[temp[2][1]]) + ^ *((UINT32*)T3[temp[3][2]]) + ^ *((UINT32*)T4[temp[0][3]]); + *((UINT32*)(b + 8)) = *((UINT32*)T1[temp[2][0]]) + ^ *((UINT32*)T2[temp[3][1]]) + ^ *((UINT32*)T3[temp[0][2]]) + ^ *((UINT32*)T4[temp[1][3]]); + *((UINT32*)(b +12)) = *((UINT32*)T1[temp[3][0]]) + ^ *((UINT32*)T2[temp[0][1]]) + ^ *((UINT32*)T3[temp[1][2]]) + ^ *((UINT32*)T4[temp[2][3]]); + } + *((UINT32*)temp[0]) = *((UINT32*)(b )) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds-1][0]); + *((UINT32*)temp[1]) = *((UINT32*)(b+ 4)) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds-1][1]); + *((UINT32*)temp[2]) = *((UINT32*)(b+ 8)) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds-1][2]); + *((UINT32*)temp[3]) = *((UINT32*)(b+12)) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds-1][3]); + b[ 0] = T1[temp[0][0]][1]; + b[ 1] = T1[temp[1][1]][1]; + b[ 2] = T1[temp[2][2]][1]; + b[ 3] = T1[temp[3][3]][1]; + b[ 4] = T1[temp[1][0]][1]; + b[ 5] = T1[temp[2][1]][1]; + b[ 6] = T1[temp[3][2]][1]; + b[ 7] = T1[temp[0][3]][1]; + b[ 8] = T1[temp[2][0]][1]; + b[ 9] = T1[temp[3][1]][1]; + b[10] = T1[temp[0][2]][1]; + b[11] = T1[temp[1][3]][1]; + b[12] = T1[temp[3][0]][1]; + b[13] = T1[temp[0][1]][1]; + b[14] = T1[temp[1][2]][1]; + b[15] = T1[temp[2][3]][1]; + *((UINT32*)(b )) ^= *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][0]); + *((UINT32*)(b+ 4)) ^= *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][1]); + *((UINT32*)(b+ 8)) ^= *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][2]); + *((UINT32*)(b+12)) ^= *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][3]); +} + +SQLITE_PRIVATE +void RijndaelDecrypt(Rijndael* rijndael, UINT8 a[16], UINT8 b[16]) +{ + int r; + UINT8 temp[4][4]; + + *((UINT32*)temp[0]) = *((UINT32*)(a )) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][0]); + *((UINT32*)temp[1]) = *((UINT32*)(a+ 4)) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][1]); + *((UINT32*)temp[2]) = *((UINT32*)(a+ 8)) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][2]); + *((UINT32*)temp[3]) = *((UINT32*)(a+12)) ^ *((UINT32*)rijndael->m_expandedKey[rijndael->m_uRounds][3]); + + *((UINT32*)(b )) = *((UINT32*)T5[temp[0][0]]) + ^ *((UINT32*)T6[temp[3][1]]) + ^ *((UINT32*)T7[temp[2][2]]) + ^ *((UINT32*)T8[temp[1][3]]); + *((UINT32*)(b+ 4)) = *((UINT32*)T5[temp[1][0]]) + ^ *((UINT32*)T6[temp[0][1]]) + ^ *((UINT32*)T7[temp[3][2]]) + ^ *((UINT32*)T8[temp[2][3]]); + *((UINT32*)(b+ 8)) = *((UINT32*)T5[temp[2][0]]) + ^ *((UINT32*)T6[temp[1][1]]) + ^ *((UINT32*)T7[temp[0][2]]) + ^ *((UINT32*)T8[temp[3][3]]); + *((UINT32*)(b+12)) = *((UINT32*)T5[temp[3][0]]) + ^ *((UINT32*)T6[temp[2][1]]) + ^ *((UINT32*)T7[temp[1][2]]) + ^ *((UINT32*)T8[temp[0][3]]); + for(r = rijndael->m_uRounds-1; r > 1; r--) + { + *((UINT32*)temp[0]) = *((UINT32*)(b )) ^ *((UINT32*)rijndael->m_expandedKey[r][0]); + *((UINT32*)temp[1]) = *((UINT32*)(b+ 4)) ^ *((UINT32*)rijndael->m_expandedKey[r][1]); + *((UINT32*)temp[2]) = *((UINT32*)(b+ 8)) ^ *((UINT32*)rijndael->m_expandedKey[r][2]); + *((UINT32*)temp[3]) = *((UINT32*)(b+12)) ^ *((UINT32*)rijndael->m_expandedKey[r][3]); + *((UINT32*)(b )) = *((UINT32*)T5[temp[0][0]]) + ^ *((UINT32*)T6[temp[3][1]]) + ^ *((UINT32*)T7[temp[2][2]]) + ^ *((UINT32*)T8[temp[1][3]]); + *((UINT32*)(b+ 4)) = *((UINT32*)T5[temp[1][0]]) + ^ *((UINT32*)T6[temp[0][1]]) + ^ *((UINT32*)T7[temp[3][2]]) + ^ *((UINT32*)T8[temp[2][3]]); + *((UINT32*)(b+ 8)) = *((UINT32*)T5[temp[2][0]]) + ^ *((UINT32*)T6[temp[1][1]]) + ^ *((UINT32*)T7[temp[0][2]]) + ^ *((UINT32*)T8[temp[3][3]]); + *((UINT32*)(b+12)) = *((UINT32*)T5[temp[3][0]]) + ^ *((UINT32*)T6[temp[2][1]]) + ^ *((UINT32*)T7[temp[1][2]]) + ^ *((UINT32*)T8[temp[0][3]]); + } + + *((UINT32*)temp[0]) = *((UINT32*)(b )) ^ *((UINT32*)rijndael->m_expandedKey[1][0]); + *((UINT32*)temp[1]) = *((UINT32*)(b+ 4)) ^ *((UINT32*)rijndael->m_expandedKey[1][1]); + *((UINT32*)temp[2]) = *((UINT32*)(b+ 8)) ^ *((UINT32*)rijndael->m_expandedKey[1][2]); + *((UINT32*)temp[3]) = *((UINT32*)(b+12)) ^ *((UINT32*)rijndael->m_expandedKey[1][3]); + b[ 0] = S5[temp[0][0]]; + b[ 1] = S5[temp[3][1]]; + b[ 2] = S5[temp[2][2]]; + b[ 3] = S5[temp[1][3]]; + b[ 4] = S5[temp[1][0]]; + b[ 5] = S5[temp[0][1]]; + b[ 6] = S5[temp[3][2]]; + b[ 7] = S5[temp[2][3]]; + b[ 8] = S5[temp[2][0]]; + b[ 9] = S5[temp[1][1]]; + b[10] = S5[temp[0][2]]; + b[11] = S5[temp[3][3]]; + b[12] = S5[temp[3][0]]; + b[13] = S5[temp[2][1]]; + b[14] = S5[temp[1][2]]; + b[15] = S5[temp[0][3]]; + *((UINT32*)(b )) ^= *((UINT32*)rijndael->m_expandedKey[0][0]); + *((UINT32*)(b+ 4)) ^= *((UINT32*)rijndael->m_expandedKey[0][1]); + *((UINT32*)(b+ 8)) ^= *((UINT32*)rijndael->m_expandedKey[0][2]); + *((UINT32*)(b+12)) ^= *((UINT32*)rijndael->m_expandedKey[0][3]); +} + +SQLITE_PRIVATE +void RijndaelInvalidate(Rijndael* rijndael) +{ + rijndael->m_state = RIJNDAEL_State_Invalid; +} +/*** End of #include "rijndael.c" ***/ + +#endif + +#if HAVE_CIPHER_AEGIS + +/* Incremental encryption/decryption not needed */ +#define AEGIS_OMIT_INCREMENTAL +/* API for generating MAC not needed */ +#define AEGIS_OMIT_MAC_API + +/* #include "aegis/libaegis.c" */ +/*** Begin of #include "aegis/libaegis.c" ***/ +/* +** Name: libaegis.c +** Purpose: Amalgamation of the AEGIS library +** Copyright: (c) 2024-2024 Ulrich Telle +** SPDX-License-Identifier: MIT +*/ + +/* +** AEGIS library source code +*/ + +#ifndef AEGIS_API +#define AEGIS_API +#endif +#ifndef AEGIS_PRIVATE +#define AEGIS_PRIVATE static +#endif + +/* #include "common/cpu.h" */ +/*** Begin of #include "common/cpu.h" ***/ +/* +** Name: cpu.h +** Purpose: Header for CPU identification and AES hardware support detection +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS_CPU_H +#define AEGIS_CPU_H + +/* #include "aeshardware.h" */ +/*** Begin of #include "aeshardware.h" ***/ +/* +** Name: aeshardware.h +** Purpose: Header for AES hardware support detection +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS_AES_HARDWARE_H +#define AEGIS_AES_HARDWARE_H + +#define AEGIS_AES_HARDWARE_NONE 0 +#define AEGIS_AES_HARDWARE_NI 1 +#define AEGIS_AES_HARDWARE_NEON 2 +#define AEGIS_AES_HARDWARE_ALTIVEC 3 + +#ifndef AEGIS_OMIT_AES_HARDWARE_SUPPORT + +#if defined __ARM_FEATURE_CRYPTO +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NEON + + +/* --- CLang --- */ +#elif defined(__clang__) + +#if __has_attribute(target) && __has_include() && (defined(__x86_64__) || defined(__i386)) +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NI + +#elif __has_attribute(target) && __has_include() && (defined(__aarch64__)) +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NEON + +#endif + + +/* --- GNU C/C++ */ +#elif defined(__GNUC__) + +#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) && (defined(__x86_64__) || defined(__i386)) +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NI +#elif defined(__aarch64__) || (defined(__arm__) && defined(__ARM_NEON)) +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NEON +#endif + + +/* --- Visual C/C++ --- */ +#elif defined (_MSC_VER) + +/* Architecture: x86 or x86_64 */ +#if (defined(_M_X64) || defined(_M_IX86)) && _MSC_FULL_VER >= 150030729 +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NI + +/* Architecture: ARM 64-bit */ +#elif defined(_M_ARM64) +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NEON + +/* Use header instead of */ +#ifndef USE_ARM64_NEON_H +#define USE_ARM64_NEON_H +#endif + +/* Architecture: ARM 32-bit */ +#elif defined _M_ARM +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NEON + +/* The following #define is required to enable intrinsic definitions + that do not omit one of the parameters for vaes[ed]q_u8 */ +#ifndef _ARM_USE_NEW_NEON_INTRINSICS +#define _ARM_USE_NEW_NEON_INTRINSICS +#endif + +#endif + +#else + +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NONE + +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NONE + +/* Original checks of libaegis */ +#if defined(__ARM_FEATURE_CRYPTO) && defined(__ARM_FEATURE_AES) && defined(__ARM_NEON) +# define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NEON +#elif defined(__AES__) && defined(__AVX__) +# define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NI +#elif defined(__ALTIVEC__) && defined(__CRYPTO__) +# define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_ALTIVEC +#endif + +#endif + +#else /* AEGIS_OMIT_AES_HARDWARE_SUPPORT defined */ + +/* Omit AES hardware support */ +#define HAS_AEGIS_AES_HARDWARE AEGIS_AES_HARDWARE_NONE + +#endif /* SQLITE3MC_OMIT_AES_HARDWARE_SUPPORT */ + +#endif /* AEGIS_AES_HARDWARE_H */ +/*** End of #include "aeshardware.h" ***/ + + +AEGIS_PRIVATE +int aegis_runtime_get_cpu_features(void); + +AEGIS_PRIVATE +int aegis_runtime_has_neon(void); + +AEGIS_PRIVATE +int aegis_runtime_has_armcrypto(void); + +AEGIS_PRIVATE +int aegis_runtime_has_avx(void); + +AEGIS_PRIVATE +int aegis_runtime_has_avx2(void); + +AEGIS_PRIVATE +int aegis_runtime_has_avx512f(void); + +AEGIS_PRIVATE +int aegis_runtime_has_aesni(void); + +AEGIS_PRIVATE +int aegis_runtime_has_vaes(void); + +AEGIS_PRIVATE +int aegis_runtime_has_altivec(void); + +#endif /* AEGIS_CPU_H */ +/*** End of #include "common/cpu.h" ***/ + + +/* AEGIS common functions */ +/* #include "common/common.c" */ +/*** Begin of #include "common/common.c" ***/ +/* +** Name: common.c +** Purpose: Implementation of common utility functions +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include + +/* #include "common.h" */ +/*** Begin of #include "common.h" ***/ +/* +** Name: common.h +** Purpose: Common header for AEGIS implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS_COMMON_H +#define AEGIS_COMMON_H + +#include +#include +#include +#include + +/* #include "../include/aegis.h" */ +/*** Begin of #include "../include/aegis.h" ***/ +/* +** Name: aegis.h +** Purpose: Header for AEGIS API +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS_H +#define AEGIS_H + +#include + +#if !defined(__clang__) && !defined(__GNUC__) +# ifdef __attribute__ +# undef __attribute__ +# endif +# define __attribute__(a) +#endif + +#ifndef CRYPTO_ALIGN +# if defined(__INTEL_COMPILER) || defined(_MSC_VER) +# define CRYPTO_ALIGN(x) __declspec(align(x)) +# else +# define CRYPTO_ALIGN(x) __attribute__((aligned(x))) +# endif +#endif + +#ifndef AEGIS_API +#define AEGIS_API +#endif +#ifndef AEGIS_PRIVATE +#define AEGIS_PRIVATE static +#endif + +/* #include "aegis128l.h" */ +/*** Begin of #include "aegis128l.h" ***/ +/* +** Name: aegis128l.h +** Purpose: Header for AEGIS-128L API +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128L_H +#define AEGIS128L_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* The length of an AEGIS key, in bytes */ +#define aegis128l_KEYBYTES 16 + +/* The length of an AEGIS nonce, in bytes */ +#define aegis128l_NPUBBYTES 16 + +/* The minimum length of an AEGIS authentication tag, in bytes */ +#define aegis128l_ABYTES_MIN 16 + +/* The maximum length of an AEGIS authentication tag, in bytes */ +#define aegis128l_ABYTES_MAX 32 + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +#define aegis128l_TAILBYTES_MAX 31 + +/* An AEGIS state, for incremental updates */ +typedef struct aegis128l_state { + CRYPTO_ALIGN(32) uint8_t opaque[256]; +} aegis128l_state; + +/* An AEGIS state, only for MAC updates */ +typedef struct aegis128l_mac_state { + CRYPTO_ALIGN(32) uint8_t opaque[384]; +} aegis128l_mac_state; + + +/* The length of an AEGIS key, in bytes */ +AEGIS_API +size_t aegis128l_keybytes(void); + +/* The length of an AEGIS nonce, in bytes */ +AEGIS_API +size_t aegis128l_npubbytes(void); + +/* The minimum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis128l_abytes_min(void); + +/* The maximum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis128l_abytes_max(void); + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +AEGIS_API +size_t aegis128l_tailbytes_max(void); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * c: ciphertext output buffer + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +int aegis128l_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, + size_t mlen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128l_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) __attribute__((warn_unused_result)); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * c: ciphertext output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +int aegis128l_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128l_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) + __attribute__((warn_unused_result)); + +#ifndef AEGIS_OMIT_INCREMENTAL + +/* + * Initialize a state for incremental encryption or decryption. + * + * st_: state to initialize + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128l_state_init(aegis128l_state *st_, const uint8_t *ad, size_t adlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message chunk. + * The same function can be used regardless of whether the tag will be attached or not. + * + * st_: state to update + * c: ciphertext output buffer + * clen_max: length of the ciphertext chunk buffer (must be >= mlen) + * written: number of ciphertext bytes actually written + * m: plaintext input buffer + * mlen: length of the plaintext + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128l_state_encrypt_update(aegis128l_state *st_, uint8_t *c, size_t clen_max, + size_t *written, const uint8_t *m, size_t mlen); + +/* + * Finalize the incremental encryption and generate the authentication tag. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes) + * written: number of ciphertext bytes actually written + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128l_state_encrypt_detached_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + +/* + * Finalize the incremental encryption and attach the authentication tag + * to the final ciphertext chunk. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes+maclen) + * written: number of ciphertext bytes actually written + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128l_state_encrypt_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, + size_t *written, size_t maclen); + +/* + * Decrypt a message chunk. + * + * The output should never be released to the caller until the tag has been verified. + * + * st_: state to update + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= clen) + * written: number of plaintext bytes actually written + * c: ciphertext chunk input buffer + * clen: length of the ciphertext chunk + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128l_state_decrypt_detached_update(aegis128l_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) + __attribute__((warn_unused_result)); + +/* + * Decrypt the final message chunk and verify the authentication tag. + * + * st_: state to finalize + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= remaining bytes) + * written: number of plaintext bytes actually written + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128l_state_decrypt_detached_final(aegis128l_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) + __attribute__((warn_unused_result)); + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +/* + * Return a deterministic pseudo-random byte sequence. + * + * out: output buffer + * len: number of bytes to generate + * npub: nonce input buffer (16 bytes) - Can be set to `NULL` if only one sequence has to be + * generated from a given key. + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128l_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * c: ciphertext output buffer + * m: plaintext input buffer + * mlen: length of the plaintext + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128l_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128l_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, + const uint8_t *npub, const uint8_t *k); + +#ifndef AEGIS_OMIT_MAC_API + +/* + * Initialize a state for generating a MAC. + * + * st_: state to initialize + * k: key input buffer (16 bytes) + * + * - The same key MUST NOT be used both for MAC and encryption. + * - If the key is secret, the MAC is secure against forgery. + * - However, if the key is known, arbitrary inputs matching a tag can be efficiently computed. + * + * The recommended way to use the MAC mode is to generate a random key and keep it secret. + * + * After initialization, the state can be reused to generate multiple MACs by cloning it + * with `aegis128l_mac_state_clone()`. It is only safe to copy a state directly without using + * the clone function if the state is guaranteed to be properly aligned. + * + * A state can also be reset for reuse without cloning with `aegis128l_mac_reset()`. + */ +AEGIS_API +void aegis128l_mac_init(aegis128l_mac_state *st_, const uint8_t *k, const uint8_t *npub); + +/* + * Update the MAC state with input data. + * + * st_: state to update + * m: input data + * mlen: length of the input data + * + * This function can be called multiple times. + * + * Once the full input has been absorb, call either `_mac_final` or `_mac_verify`. + */ +AEGIS_API +int aegis128l_mac_update(aegis128l_mac_state *st_, const uint8_t *m, size_t mlen); + +/* + * Finalize the MAC and generate the authentication tag. + * + * st_: state to finalize + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32. 32 is recommended). + */ +AEGIS_API +int aegis128l_mac_final(aegis128l_mac_state *st_, uint8_t *mac, size_t maclen); + +/* + * Verify a MAC in constant time. + * + * st_: state to verify + * mac: authentication tag to verify + * maclen: length of the authentication tag (16 or 32) + * + * Returns 0 if the tag is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128l_mac_verify(aegis128l_mac_state *st_, const uint8_t *mac, size_t maclen); + +/* + * Reset an AEGIS_MAC state. + */ +AEGIS_API +void aegis128l_mac_reset(aegis128l_mac_state *st_); + +/* + * Clone an AEGIS-MAC state. + * + * dst: destination state + * src: source state + * + * This function MUST be used in order to clone states. + */ +AEGIS_API +void aegis128l_mac_state_clone(aegis128l_mac_state *dst, const aegis128l_mac_state *src); + +#endif /* AEGIS_OMIT_MAC_API */ + +#ifdef __cplusplus +} +#endif + +#endif /* AEGIS128L_H */ +/*** End of #include "aegis128l.h" ***/ + +/* #include "aegis128x2.h" */ +/*** Begin of #include "aegis128x2.h" ***/ +/* +** Name: aegis128x2.h +** Purpose: Header for AEGIS-128x2 API +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X2_H +#define AEGIS128X2_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* The length of an AEGIS key, in bytes */ +#define aegis128x2_KEYBYTES 16 + +/* The length of an AEGIS nonce, in bytes */ +#define aegis128x2_NPUBBYTES 16 + +/* The minimum length of an AEGIS authentication tag, in bytes */ +#define aegis128x2_ABYTES_MIN 16 + +/* The maximum length of an AEGIS authentication tag, in bytes */ +#define aegis128x2_ABYTES_MAX 32 + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +#define aegis128x2_TAILBYTES_MAX 63 + +/* An AEGIS state, for incremental updates */ +typedef struct aegis128x2_state { + CRYPTO_ALIGN(64) uint8_t opaque[448]; +} aegis128x2_state; + +/* An AEGIS state, only for MAC updates */ +typedef struct aegis128x2_mac_state { + CRYPTO_ALIGN(64) uint8_t opaque[704]; +} aegis128x2_mac_state; + +/* The length of an AEGIS key, in bytes */ +AEGIS_API +size_t aegis128x2_keybytes(void); + +/* The length of an AEGIS nonce, in bytes */ +AEGIS_API +size_t aegis128x2_npubbytes(void); + +/* The minimum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis128x2_abytes_min(void); + +/* The maximum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis128x2_abytes_max(void); + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +AEGIS_API +size_t aegis128x2_tailbytes_max(void); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * c: ciphertext output buffer + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +int aegis128x2_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, + size_t mlen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128x2_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) __attribute__((warn_unused_result)); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * c: ciphertext output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +int aegis128x2_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128x2_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) + __attribute__((warn_unused_result)); + +#ifndef AEGIS_OMIT_INCREMENTAL + +/* + * Initialize a state for incremental encryption or decryption. + * + * st_: state to initialize + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x2_state_init(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message chunk. + * The same function can be used regardless of whether the tag will be attached or not. + * + * st_: state to update + * c: ciphertext output buffer + * clen_max: length of the ciphertext chunk buffer (must be >= mlen) + * written: number of ciphertext bytes actually written + * m: plaintext input buffer + * mlen: length of the plaintext + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x2_state_encrypt_update(aegis128x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, const uint8_t *m, size_t mlen); + +/* + * Finalize the incremental encryption and generate the authentication tag. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes) + * written: number of ciphertext bytes actually written + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x2_state_encrypt_detached_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + +/* + * Finalize the incremental encryption and attach the authentication tag + * to the final ciphertext chunk. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes+maclen) + * written: number of ciphertext bytes actually written + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x2_state_encrypt_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, size_t maclen); + +/* + * Decrypt a message chunk. + * + * The output should never be released to the caller until the tag has been verified. + * + * st_: state to update + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= clen) + * written: number of plaintext bytes actually written + * c: ciphertext chunk input buffer + * clen: length of the ciphertext chunk + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x2_state_decrypt_detached_update(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) + __attribute__((warn_unused_result)); + +/* + * Decrypt the final message chunk and verify the authentication tag. + * + * st_: state to finalize + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= remaining bytes) + * written: number of plaintext bytes actually written + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x2_state_decrypt_detached_final(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) + __attribute__((warn_unused_result)); + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +/* + * Return a deterministic pseudo-random byte sequence. + * + * out: output buffer + * len: number of bytes to generate + * npub: nonce input buffer (16 bytes) - Can be set to `NULL` if only one sequence has to be + * generated from a given key. + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x2_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * c: ciphertext output buffer + * m: plaintext input buffer + * mlen: length of the plaintext + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x2_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x2_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, + const uint8_t *npub, const uint8_t *k); + +#ifndef AEGIS_OMIT_MAC_API + +/* + * Initialize a state for generating a MAC. + * + * st_: state to initialize + * k: key input buffer (16 bytes) + * + * - The same key MUST NOT be used both for MAC and encryption. + * - If the key is secret, the MAC is secure against forgery. + * - However, if the key is known, arbitrary inputs matching a tag can be efficiently computed. + * + * The recommended way to use the MAC mode is to generate a random key and keep it secret. + * + * After initialization, the state can be reused to generate multiple MACs by cloning it + * with `aegis128x2_mac_state_clone()`. It is only safe to copy a state directly without using + * the clone function if the state is guaranteed to be properly aligned. + * + * A state can also be reset for reuse without cloning with `aegis128x2_mac_reset()`. + */ +AEGIS_API +void aegis128x2_mac_init(aegis128x2_mac_state *st_, const uint8_t *k, const uint8_t *npub); + +/* + * Update the MAC state with input data. + * + * st_: state to update + * m: input data + * mlen: length of the input data + * + * This function can be called multiple times. + * + * Once the full input has been absorb, call either `_mac_final` or `_mac_verify`. + */ +AEGIS_API +int aegis128x2_mac_update(aegis128x2_mac_state *st_, const uint8_t *m, size_t mlen); + +/* + * Finalize the MAC and generate the authentication tag. + * + * st_: state to finalize + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32. 32 is recommended). + */ +AEGIS_API +int aegis128x2_mac_final(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen); + +/* + * Verify a MAC in constant time. + * + * st_: state to verify + * mac: authentication tag to verify + * maclen: length of the authentication tag (16 or 32) + * + * Returns 0 if the tag is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128x2_mac_verify(aegis128x2_mac_state *st_, const uint8_t *mac, size_t maclen); + +/* + * Reset an AEGIS_MAC state. + */ +AEGIS_API +void aegis128x2_mac_reset(aegis128x2_mac_state *st_); + +/* + * Clone an AEGIS-MAC state. + * + * dst: destination state + * src: source state + * + * This function MUST be used in order to clone states. + */ +AEGIS_API +void aegis128x2_mac_state_clone(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src); + +#endif /* AEGIS_OMIT_MAC_API */ + +#ifdef __cplusplus +} +#endif + +#endif /* AEGIS128X2_H */ +/*** End of #include "aegis128x2.h" ***/ + +/* #include "aegis128x4.h" */ +/*** Begin of #include "aegis128x4.h" ***/ +/* +** Name: aegis128x4.h +** Purpose: Header for AEGIS-128x4 API +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_H +#define AEGIS128X4_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* The length of an AEGIS key, in bytes */ +#define aegis128x4_KEYBYTES 16 + +/* The length of an AEGIS nonce, in bytes */ +#define aegis128x4_NPUBBYTES 16 + +/* The minimum length of an AEGIS authentication tag, in bytes */ +#define aegis128x4_ABYTES_MIN 16 + +/* The maximum length of an AEGIS authentication tag, in bytes */ +#define aegis128x4_ABYTES_MAX 32 + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +#define aegis128x4_TAILBYTES_MAX 127 + +/* An AEGIS state, for incremental updates */ +typedef struct aegis128x4_state { + CRYPTO_ALIGN(64) uint8_t opaque[832]; +} aegis128x4_state; + +/* An AEGIS state, only for MAC updates */ +typedef struct aegis128x4_mac_state { + CRYPTO_ALIGN(64) uint8_t opaque[1344]; +} aegis128x4_mac_state; + + +/* The length of an AEGIS key, in bytes */ +AEGIS_API +size_t aegis128x4_keybytes(void); + +/* The length of an AEGIS nonce, in bytes */ +AEGIS_API +size_t aegis128x4_npubbytes(void); + +/* The minimum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis128x4_abytes_min(void); + +/* The maximum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis128x4_abytes_max(void); + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +AEGIS_API +size_t aegis128x4_tailbytes_max(void); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * c: ciphertext output buffer + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +int aegis128x4_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, + size_t mlen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128x4_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) __attribute__((warn_unused_result)); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * c: ciphertext output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +int aegis128x4_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128x4_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) + __attribute__((warn_unused_result)); + +#ifndef AEGIS_OMIT_INCREMENTAL + +/* + * Initialize a state for incremental encryption or decryption. + * + * st_: state to initialize + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x4_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message chunk. + * The same function can be used regardless of whether the tag will be attached or not. + * + * st_: state to update + * c: ciphertext output buffer + * clen_max: length of the ciphertext chunk buffer (must be >= mlen) + * written: number of ciphertext bytes actually written + * m: plaintext input buffer + * mlen: length of the plaintext + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x4_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, const uint8_t *m, size_t mlen); + +/* + * Finalize the incremental encryption and generate the authentication tag. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes) + * written: number of ciphertext bytes actually written + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x4_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + +/* + * Finalize the incremental encryption and attach the authentication tag + * to the final ciphertext chunk. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes+maclen) + * written: number of ciphertext bytes actually written + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x4_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, size_t maclen); + +/* + * Decrypt a message chunk. + * + * The output should never be released to the caller until the tag has been verified. + * + * st_: state to update + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= clen) + * written: number of plaintext bytes actually written + * c: ciphertext chunk input buffer + * clen: length of the ciphertext chunk + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x4_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) + __attribute__((warn_unused_result)); + +/* + * Decrypt the final message chunk and verify the authentication tag. + * + * st_: state to finalize + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= remaining bytes) + * written: number of plaintext bytes actually written + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis128x4_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) + __attribute__((warn_unused_result)); + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +/* + * Return a deterministic pseudo-random byte sequence. + * + * out: output buffer + * len: number of bytes to generate + * npub: nonce input buffer (16 bytes) - Can be set to `NULL` if only one sequence has to be + * generated from a given key. + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x4_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * c: ciphertext output buffer + * m: plaintext input buffer + * mlen: length of the plaintext + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x4_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * npub: nonce input buffer (16 bytes) + * k: key input buffer (16 bytes) + */ +AEGIS_API +void aegis128x4_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, + const uint8_t *npub, const uint8_t *k); + +#ifndef AEGIS_OMIT_MAC_API + +/* + * Initialize a state for generating a MAC. + * + * st_: state to initialize + * k: key input buffer (16 bytes) + * + * - The same key MUST NOT be used both for MAC and encryption. + * - If the key is secret, the MAC is secure against forgery. + * - However, if the key is known, arbitrary inputs matching a tag can be efficiently computed. + * + * The recommended way to use the MAC mode is to generate a random key and keep it secret. + * + * After initialization, the state can be reused to generate multiple MACs by cloning it + * with `aegis128x4_mac_state_clone()`. It is only safe to copy a state directly without using + * the clone function if the state is guaranteed to be properly aligned. + * + * A state can also be reset for reuse without cloning with `aegis128x4_mac_reset()`. + */ +AEGIS_API +void aegis128x4_mac_init(aegis128x4_mac_state *st_, const uint8_t *k, const uint8_t *npub); + +/* + * Update the MAC state with input data. + * + * st_: state to update + * m: input data + * mlen: length of the input data + * + * This function can be called multiple times. + * + * Once the full input has been absorb, call either `_mac_final` or `_mac_verify`. + */ +AEGIS_API +int aegis128x4_mac_update(aegis128x4_mac_state *st_, const uint8_t *m, size_t mlen); + +/* + * Finalize the MAC and generate the authentication tag. + * + * st_: state to finalize + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32. 32 is recommended). + */ +AEGIS_API +int aegis128x4_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen); + +/* + * Verify a MAC in constant time. + * + * st_: state to verify + * mac: authentication tag to verify + * maclen: length of the authentication tag (16 or 32) + * + * Returns 0 if the tag is authentic, -1 otherwise. + */ +AEGIS_API +int aegis128x4_mac_verify(aegis128x4_mac_state *st_, const uint8_t *mac, size_t maclen); + +/* + * Reset an AEGIS_MAC state. + */ +AEGIS_API +void aegis128x4_mac_reset(aegis128x4_mac_state *st_); + +/* + * Clone an AEGIS-MAC state. + * + * dst: destination state + * src: source state + * + * This function MUST be used in order to clone states. + */ +AEGIS_API +void aegis128x4_mac_state_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src); + +#endif /* AEGIS_OMIT_MAC_API */ + +#ifdef __cplusplus +} +#endif + +#endif /* AEGIS128X4_H */ +/*** End of #include "aegis128x4.h" ***/ + +/* #include "aegis256.h" */ +/*** Begin of #include "aegis256.h" ***/ +/* +** Name: aegis256.h +** Purpose: Header for AEGIS-256 API +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256_H +#define AEGIS256_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* The length of an AEGIS key, in bytes */ +#define aegis256_KEYBYTES 32 + +/* The length of an AEGIS nonce, in bytes */ +#define aegis256_NPUBBYTES 32 + +/* The minimum length of an AEGIS authentication tag, in bytes */ +#define aegis256_ABYTES_MIN 16 + +/* The maximum length of an AEGIS authentication tag, in bytes */ +#define aegis256_ABYTES_MAX 32 + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +#define aegis256_TAILBYTES_MAX 15 + +/* An AEGIS state, for incremental updates */ +typedef struct aegis256_state { + CRYPTO_ALIGN(16) uint8_t opaque[192]; +} aegis256_state; + +/* An AEGIS state, only for MAC updates */ +typedef struct aegis256_mac_state { + CRYPTO_ALIGN(16) uint8_t opaque[288]; +} aegis256_mac_state; + +/* The length of an AEGIS key, in bytes */ +AEGIS_API +size_t aegis256_keybytes(void); + +/* The length of an AEGIS nonce, in bytes */ +AEGIS_API +size_t aegis256_npubbytes(void); + +/* The minimum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis256_abytes_min(void); + +/* The maximum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis256_abytes_max(void); + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +AEGIS_API +size_t aegis256_tailbytes_max(void); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * c: ciphertext output buffer + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +int aegis256_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, + size_t mlen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) __attribute__((warn_unused_result)); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * c: ciphertext output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +int aegis256_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) + __attribute__((warn_unused_result)); + +#ifndef AEGIS_OMIT_INCREMENTAL + +/* + * Initialize a state for incremental encryption or decryption. + * + * st_: state to initialize + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256_state_init(aegis256_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + +/* + * Encrypt a message chunk. + * The same function can be used regardless of whether the tag will be attached or not. + * + * st_: state to update + * c: ciphertext output buffer + * clen_max: length of the ciphertext chunk buffer (must be >= mlen) + * written: number of ciphertext bytes actually written + * m: plaintext input buffer + * mlen: length of the plaintext + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256_state_encrypt_update(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen); + +/* + * Finalize the incremental encryption and generate the authentication tag. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes) + * written: number of ciphertext bytes actually written + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256_state_encrypt_detached_final(aegis256_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + +/* + * Finalize the incremental encryption and attach the authentication tag + * to the final ciphertext chunk. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes+maclen) + * written: number of ciphertext bytes actually written + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256_state_encrypt_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen); + +/* + * Decrypt a message chunk. + * + * The output should never be released to the caller until the tag has been verified. + * + * st_: state to update + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= clen) + * written: number of plaintext bytes actually written + * c: ciphertext chunk input buffer + * clen: length of the ciphertext chunk + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256_state_decrypt_detached_update(aegis256_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) + __attribute__((warn_unused_result)); + +/* + * Decrypt the final message chunk and verify the authentication tag. + * + * st_: state to finalize + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= remaining bytes) + * written: number of plaintext bytes actually written + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256_state_decrypt_detached_final(aegis256_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) + __attribute__((warn_unused_result)); + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +/* + * Return a deterministic pseudo-random byte sequence. + * + * out: output buffer + * len: number of bytes to generate + * npub: nonce input buffer (32 bytes) - Can be set to `NULL` if only one sequence has to be + * generated from a given key. + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * c: ciphertext output buffer + * m: plaintext input buffer + * mlen: length of the plaintext + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, + const uint8_t *npub, const uint8_t *k); + +#ifndef AEGIS_OMIT_MAC_API + +/* + * Initialize a state for generating a MAC. + * + * st_: state to initialize + * k: key input buffer (32 bytes) + * + * - The same key MUST NOT be used both for MAC and encryption. + * - If the key is secret, the MAC is secure against forgery. + * - However, if the key is known, arbitrary inputs matching a tag can be efficiently computed. + * + * The recommended way to use the MAC mode is to generate a random key and keep it secret. + * + * After initialization, the state can be reused to generate multiple MACs by cloning it + * with `aegis256_mac_state_clone()`. It is only safe to copy a state directly without using + * the clone function if the state is guaranteed to be properly aligned. + * + * A state can also be reset for reuse without cloning with `aegis256_mac_reset()`. + */ +AEGIS_API +void aegis256_mac_init(aegis256_mac_state *st_, const uint8_t *k, const uint8_t *npub); + +/* + * Update the MAC state with input data. + * + * st_: state to update + * m: input data + * mlen: length of the input data + * + * This function can be called multiple times. + * + * Once the full input has been absorb, call either `_mac_final` or `_mac_verify`. + */ +AEGIS_API +int aegis256_mac_update(aegis256_mac_state *st_, const uint8_t *m, size_t mlen); + +/* + * Finalize the MAC and generate the authentication tag. + * + * st_: state to finalize + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32. 32 is recommended). + */ +AEGIS_API +int aegis256_mac_final(aegis256_mac_state *st_, uint8_t *mac, size_t maclen); + +/* + * Verify a MAC in constant time. + * + * st_: state to verify + * mac: authentication tag to verify + * maclen: length of the authentication tag (16 or 32) + * + * Returns 0 if the tag is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256_mac_verify(aegis256_mac_state *st_, const uint8_t *mac, size_t maclen); + +/* + * Reset an AEGIS_MAC state. + */ +AEGIS_API +void aegis256_mac_reset(aegis256_mac_state *st_); + +/* + * Clone an AEGIS-MAC state. + * + * dst: destination state + * src: source state + * + * This function MUST be used in order to clone states. + */ +AEGIS_API +void aegis256_mac_state_clone(aegis256_mac_state *dst, const aegis256_mac_state *src); + +#endif /* AEGIS_OMIT_MAC_API */ + +#ifdef __cplusplus +} +#endif + +#endif /* AEGIS256_H */ +/*** End of #include "aegis256.h" ***/ + +/* #include "aegis256x2.h" */ +/*** Begin of #include "aegis256x2.h" ***/ +/* +** Name: aegis256x2.h +** Purpose: Header for AEGIS-256x2 API +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X2_H +#define AEGIS256X2_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* The length of an AEGIS key, in bytes */ +#define aegis256x2_KEYBYTES 32 + +/* The length of an AEGIS nonce, in bytes */ +#define aegis256x2_NPUBBYTES 32 + +/* The minimum length of an AEGIS authentication tag, in bytes */ +#define aegis256x2_ABYTES_MIN 16 + +/* The maximum length of an AEGIS authentication tag, in bytes */ +#define aegis256x2_ABYTES_MAX 32 + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +#define aegis256x2_TAILBYTES_MAX 31 + +/* An AEGIS state, for incremental updates */ +typedef struct aegis256x2_state { + CRYPTO_ALIGN(32) uint8_t opaque[320]; +} aegis256x2_state; + +/* An AEGIS state, only for MAC updates */ +typedef struct aegis256x2_mac_state { + CRYPTO_ALIGN(32) uint8_t opaque[512]; +} aegis256x2_mac_state; + +/* The length of an AEGIS key, in bytes */ +AEGIS_API +size_t aegis256x2_keybytes(void); + +/* The length of an AEGIS nonce, in bytes */ +AEGIS_API +size_t aegis256x2_npubbytes(void); + +/* The minimum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis256x2_abytes_min(void); + +/* The maximum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis256x2_abytes_max(void); + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +AEGIS_API +size_t aegis256x2_tailbytes_max(void); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * c: ciphertext output buffer + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +int aegis256x2_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, + size_t mlen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256x2_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) __attribute__((warn_unused_result)); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * c: ciphertext output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +int aegis256x2_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256x2_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) + __attribute__((warn_unused_result)); + +#ifndef AEGIS_OMIT_INCREMENTAL + +/* + * Initialize a state for incremental encryption or decryption. + * + * st_: state to initialize + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x2_state_init(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message chunk. + * The same function can be used regardless of whether the tag will be attached or not. + * + * st_: state to update + * c: ciphertext output buffer + * clen_max: length of the ciphertext chunk buffer (must be >= mlen) + * written: number of ciphertext bytes actually written + * m: plaintext input buffer + * mlen: length of the plaintext + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x2_state_encrypt_update(aegis256x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, const uint8_t *m, size_t mlen); + +/* + * Finalize the incremental encryption and generate the authentication tag. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes) + * written: number of ciphertext bytes actually written + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x2_state_encrypt_detached_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + +/* + * Finalize the incremental encryption and attach the authentication tag + * to the final ciphertext chunk. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes+maclen) + * written: number of ciphertext bytes actually written + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x2_state_encrypt_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, size_t maclen); + +/* + * Decrypt a message chunk. + * + * The output should never be released to the caller until the tag has been verified. + * + * st_: state to update + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= clen) + * written: number of plaintext bytes actually written + * c: ciphertext chunk input buffer + * clen: length of the ciphertext chunk + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x2_state_decrypt_detached_update(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) + __attribute__((warn_unused_result)); + +/* + * Decrypt the final message chunk and verify the authentication tag. + * + * st_: state to finalize + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= remaining bytes) + * written: number of plaintext bytes actually written + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x2_state_decrypt_detached_final(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) + __attribute__((warn_unused_result)); + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +/* + * Return a deterministic pseudo-random byte sequence. + * + * out: output buffer + * len: number of bytes to generate + * npub: nonce input buffer (32 bytes) - Can be set to `NULL` if only one sequence has to be + * generated from a given key. + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x2_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * c: ciphertext output buffer + * m: plaintext input buffer + * mlen: length of the plaintext + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x2_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x2_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, + const uint8_t *npub, const uint8_t *k); + +#ifndef AEGIS_OMIT_MAC_API + +/* + * Initialize a state for generating a MAC. + * + * st_: state to initialize + * k: key input buffer (32 bytes) + * + * - The same key MUST NOT be used both for MAC and encryption. + * - If the key is secret, the MAC is secure against forgery. + * - However, if the key is known, arbitrary inputs matching a tag can be efficiently computed. + * + * The recommended way to use the MAC mode is to generate a random key and keep it secret. + * + * After initialization, the state can be reused to generate multiple MACs by cloning it + * with `aegis256x2_mac_state_clone()`. It is only safe to copy a state directly without using + * the clone function if the state is guaranteed to be properly aligned. + * + * A state can also be reset for reuse without cloning with `aegis256x2_mac_reset()`. + */ +AEGIS_API +void aegis256x2_mac_init(aegis256x2_mac_state *st_, const uint8_t *k, const uint8_t *npub); + +/* + * Update the MAC state with input data. + * + * st_: state to update + * m: input data + * mlen: length of the input data + * + * This function can be called multiple times. + * + * Once the full input has been absorb, call either `_mac_final` or `_mac_verify`. + */ +AEGIS_API +int aegis256x2_mac_update(aegis256x2_mac_state *st_, const uint8_t *m, size_t mlen); + +/* + * Finalize the MAC and generate the authentication tag. + * + * st_: state to finalize + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32. 32 is recommended). + */ +AEGIS_API +int aegis256x2_mac_final(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen); + +/* + * Verify a MAC in constant time. + * + * st_: state to verify + * mac: authentication tag to verify + * maclen: length of the authentication tag (16 or 32) + * + * Returns 0 if the tag is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256x2_mac_verify(aegis256x2_mac_state *st_, const uint8_t *mac, size_t maclen); + +/* + * Reset an AEGIS_MAC state. + */ +AEGIS_API +void aegis256x2_mac_reset(aegis256x2_mac_state *st_); + +/* + * Clone an AEGIS-MAC state. + * + * dst: destination state + * src: source state + * + * This function MUST be used in order to clone states. + */ +AEGIS_API +void aegis256x2_mac_state_clone(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src); + +#endif /* AEGIS_OMIT_MAC_API */ + +#ifdef __cplusplus +} +#endif + +#endif /* AEGIS256X2_H */ +/*** End of #include "aegis256x2.h" ***/ + +/* #include "aegis256x4.h" */ +/*** Begin of #include "aegis256x4.h" ***/ +/* +** Name: aegis256x4.h +** Purpose: Header for AEGIS-256x4 API +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_H +#define AEGIS256X4_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* The length of an AEGIS key, in bytes */ +#define aegis256x4_KEYBYTES 32 + +/* The length of an AEGIS nonce, in bytes */ +#define aegis256x4_NPUBBYTES 32 + +/* The minimum length of an AEGIS authentication tag, in bytes */ +#define aegis256x4_ABYTES_MIN 16 + +/* The maximum length of an AEGIS authentication tag, in bytes */ +#define aegis256x4_ABYTES_MAX 32 + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +#define aegis256x4_TAILBYTES_MAX 63 + +/* An AEGIS state, for incremental updates */ +typedef struct aegis256x4_state { + CRYPTO_ALIGN(64) uint8_t opaque[576]; +} aegis256x4_state; + +/* An AEGIS state, only for MAC updates */ +typedef struct aegis256x4_mac_state { + CRYPTO_ALIGN(64) uint8_t opaque[960]; +} aegis256x4_mac_state; + +/* The length of an AEGIS key, in bytes */ +AEGIS_API +size_t aegis256x4_keybytes(void); + +/* The length of an AEGIS nonce, in bytes */ +AEGIS_API +size_t aegis256x4_npubbytes(void); + +/* The minimum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis256x4_abytes_min(void); + +/* The maximum length of an AEGIS authentication tag, in bytes */ +AEGIS_API +size_t aegis256x4_abytes_max(void); + +/* + * When using AEGIS in incremental mode, this is the maximum number + * of leftover ciphertext bytes that can be returned at finalization. + */ +AEGIS_API +size_t aegis256x4_tailbytes_max(void); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * c: ciphertext output buffer + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +int aegis256x4_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, + size_t mlen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext separately. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256x4_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) __attribute__((warn_unused_result)); + +/* + * Encrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * c: ciphertext output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * m: plaintext input buffer + * mlen: length of the plaintext + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +int aegis256x4_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message with AEGIS in one shot mode, returning the tag and the ciphertext together. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * maclen: length of the authentication tag (16 or 32) + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + * + * Returns 0 if the ciphertext is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256x4_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) + __attribute__((warn_unused_result)); + +#ifndef AEGIS_OMIT_INCREMENTAL + +/* + * Initialize a state for incremental encryption or decryption. + * + * st_: state to initialize + * ad: additional data input buffer + * adlen: length of the additional data + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x4_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message chunk. + * The same function can be used regardless of whether the tag will be attached or not. + * + * st_: state to update + * c: ciphertext output buffer + * clen_max: length of the ciphertext chunk buffer (must be >= mlen) + * written: number of ciphertext bytes actually written + * m: plaintext input buffer + * mlen: length of the plaintext + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x4_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, const uint8_t *m, size_t mlen); + +/* + * Finalize the incremental encryption and generate the authentication tag. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes) + * written: number of ciphertext bytes actually written + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x4_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + +/* + * Finalize the incremental encryption and attach the authentication tag + * to the final ciphertext chunk. + * + * st_: state to finalize + * c: output buffer for the final ciphertext chunk + * clen_max: length of the ciphertext chunk buffer (must be >= remaining bytes+maclen) + * written: number of ciphertext bytes actually written + * maclen: length of the authentication tag to generate (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x4_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, size_t maclen); + +/* + * Decrypt a message chunk. + * + * The output should never be released to the caller until the tag has been verified. + * + * st_: state to update + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= clen) + * written: number of plaintext bytes actually written + * c: ciphertext chunk input buffer + * clen: length of the ciphertext chunk + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x4_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) + __attribute__((warn_unused_result)); + +/* + * Decrypt the final message chunk and verify the authentication tag. + * + * st_: state to finalize + * m: plaintext output buffer + * mlen_max: length of the plaintext chunk buffer (must be >= remaining bytes) + * written: number of plaintext bytes actually written + * mac: authentication tag input buffer + * maclen: length of the authentication tag (16 or 32) + * + * Return 0 on success, -1 on failure. + */ +AEGIS_API +int aegis256x4_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) + __attribute__((warn_unused_result)); + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +/* + * Return a deterministic pseudo-random byte sequence. + * + * out: output buffer + * len: number of bytes to generate + * npub: nonce input buffer (32 bytes) - Can be set to `NULL` if only one sequence has to be + * generated from a given key. + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x4_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + +/* + * Encrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * c: ciphertext output buffer + * m: plaintext input buffer + * mlen: length of the plaintext + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x4_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, + const uint8_t *npub, const uint8_t *k); + +/* + * Decrypt a message WITHOUT AUTHENTICATION, similar to AES-CTR. + * + * WARNING: this is an insecure mode of operation, provided for compatibility with specific + * protocols that bring their own authentication scheme. + * + * m: plaintext output buffer + * c: ciphertext input buffer + * clen: length of the ciphertext + * npub: nonce input buffer (32 bytes) + * k: key input buffer (32 bytes) + */ +AEGIS_API +void aegis256x4_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, + const uint8_t *npub, const uint8_t *k); + +#ifndef AEGIS_OMIT_MAC_API + +/* + * Initialize a state for generating a MAC. + * + * st_: state to initialize + * k: key input buffer (32 bytes) + * + * - The same key MUST NOT be used both for MAC and encryption. + * - If the key is secret, the MAC is secure against forgery. + * - However, if the key is known, arbitrary inputs matching a tag can be efficiently computed. + * + * The recommended way to use the MAC mode is to generate a random key and keep it secret. + * + * After initialization, the state can be reused to generate multiple MACs by cloning it + * with `aegis256x4_mac_state_clone()`. It is only safe to copy a state directly without using + * the clone function if the state is guaranteed to be properly aligned. + * + * A state can also be reset for reuse without cloning with `aegis256x4_mac_reset()`. + */ +AEGIS_API +void aegis256x4_mac_init(aegis256x4_mac_state *st_, const uint8_t *k, const uint8_t *npub); + +/* + * Update the MAC state with input data. + * + * st_: state to update + * m: input data + * mlen: length of the input data + * + * This function can be called multiple times. + * + * Once the full input has been absorb, call either `_mac_final` or `_mac_verify`. + */ +AEGIS_API +int aegis256x4_mac_update(aegis256x4_mac_state *st_, const uint8_t *m, size_t mlen); + +/* + * Finalize the MAC and generate the authentication tag. + * + * st_: state to finalize + * mac: authentication tag output buffer + * maclen: length of the authentication tag to generate (16 or 32. 32 is recommended). + */ +AEGIS_API +int aegis256x4_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen); + +/* + * Verify a MAC in constant time. + * + * st_: state to verify + * mac: authentication tag to verify + * maclen: length of the authentication tag (16 or 32) + * + * Returns 0 if the tag is authentic, -1 otherwise. + */ +AEGIS_API +int aegis256x4_mac_verify(aegis256x4_mac_state *st_, const uint8_t *mac, size_t maclen); + +/* + * Reset an AEGIS_MAC state. + */ +AEGIS_API +void aegis256x4_mac_reset(aegis256x4_mac_state *st_); + +/* + * Clone an AEGIS-MAC state. + * + * dst: destination state + * src: source state + * + * This function MUST be used in order to clone states. + */ +AEGIS_API +void aegis256x4_mac_state_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src); + +#endif /* AEGIS_OMIT_MAC_API */ + +#ifdef __cplusplus +} +#endif + +#endif /* AEGIS256X4_H */ +/*** End of #include "aegis256x4.h" ***/ + + +#ifdef __cplusplus +extern "C" { +#endif + +/* Initialize the AEGIS library. + * + * This function does runtime CPU capability detection, and must be called once + * in your application before doing anything else with the library. + * + * If you don't, AEGIS will still work, but it may be much slower. + * + * The function can be called multiple times but is not thread-safe. + */ +AEGIS_API +int aegis_init(void); + +/* Compare two 16-byte blocks for equality. + * + * This function is designed to be used in constant-time code. + * + * Returns 0 if the blocks are equal, -1 otherwise. + */ +AEGIS_API +int aegis_verify_16(const uint8_t *x, const uint8_t *y) __attribute__((warn_unused_result)); + +/* Compare two 32-byte blocks for equality. + * + * This function is designed to be used in constant-time code. + * + * Returns 0 if the blocks are equal, -1 otherwise. + */ +AEGIS_API +int aegis_verify_32(const uint8_t *x, const uint8_t *y) __attribute__((warn_unused_result)); + +#ifdef __cplusplus +} +#endif + +#endif /* AEGIS_H */ +/*** End of #include "../include/aegis.h" ***/ + +/* #include "cpu.h" */ + + +#ifdef __linux__ +# define HAVE_SYS_AUXV_H +# define HAVE_GETAUXVAL +#endif +#ifdef __ANDROID_API__ +# if __ANDROID_API__ < 18 +# undef HAVE_GETAUXVAL +# endif +# if defined(__clang__) || defined(__GNUC__) +# if __has_include() +# define HAVE_ANDROID_GETCPUFEATURES +# endif +# endif +#endif +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) + +# define HAVE_CPUID +# define NATIVE_LITTLE_ENDIAN +# if defined(__clang__) || defined(__GNUC__) +# define HAVE_AVX_ASM +# endif +#endif +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +# define HAVE_AVXINTRIN_H +# define HAVE_AVX2INTRIN_H +# define HAVE_AVX512FINTRIN_H +# define HAVE_TMMINTRIN_H +# define HAVE_WMMINTRIN_H +# define HAVE_VAESINTRIN_H +# ifdef __GNUC__ +# if !__has_include() +# undef HAVE_VAESINTRIN_H +# endif +# endif +#endif + +#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# ifndef NATIVE_LITTLE_ENDIAN +# define NATIVE_LITTLE_ENDIAN +# endif +#endif + +#if defined(__INTEL_COMPILER) || defined(_MSC_VER) +# define CRYPTO_ALIGN(x) __declspec(align(x)) +#else +# define CRYPTO_ALIGN(x) __attribute__((aligned(x))) +#endif + +#define AEGIS_LOAD32_LE(SRC) aegis_load32_le(SRC) +static inline uint32_t +aegis_load32_le(const uint8_t src[4]) +{ +#ifdef NATIVE_LITTLE_ENDIAN + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + uint32_t w = (uint32_t) src[0]; + w |= (uint32_t) src[1] << 8; + w |= (uint32_t) src[2] << 16; + w |= (uint32_t) src[3] << 24; + return w; +#endif +} + +#define AEGIS_STORE32_LE(DST, W) aegis_store32_le((DST), (W)) +static inline void +aegis_store32_le(uint8_t dst[4], uint32_t w) +{ +#ifdef NATIVE_LITTLE_ENDIAN + memcpy(dst, &w, sizeof w); +#else + dst[0] = (uint8_t) w; + w >>= 8; + dst[1] = (uint8_t) w; + w >>= 8; + dst[2] = (uint8_t) w; + w >>= 8; + dst[3] = (uint8_t) w; +#endif +} + +#define AEGIS_ROTL32(X, B) aegis_rotl32((X), (B)) +static inline uint32_t +aegis_rotl32(const uint32_t x, const int b) +{ + return (x << b) | (x >> (32 - b)); +} + +#define COMPILER_ASSERT(X) (void) sizeof(char[(X) ? 1 : -1]) + +#ifndef ERANGE +# define ERANGE 34 +#endif +#ifndef EINVAL +# define EINVAL 22 +#endif + +#define AEGIS_CONCAT(A,B) AEGIS_CONCAT_(A,B) +#define AEGIS_CONCAT_(A,B) A##B +#define AEGIS_FUNC(name) AEGIS_CONCAT(AEGIS_FUNC_PREFIX,AEGIS_CONCAT(_,name)) + +#define AEGIS_API_IMPL_LIST_STD \ + .encrypt_detached = AEGIS_encrypt_detached, \ + .decrypt_detached = AEGIS_decrypt_detached, \ + .encrypt_unauthenticated = AEGIS_encrypt_unauthenticated, \ + .decrypt_unauthenticated = AEGIS_decrypt_unauthenticated, \ + .stream = AEGIS_stream, +#define AEGIS_API_IMPL_LIST_INC \ + .state_init = AEGIS_state_init, \ + .state_encrypt_update = AEGIS_state_encrypt_update, \ + .state_encrypt_detached_final = AEGIS_state_encrypt_detached_final, \ + .state_encrypt_final = AEGIS_state_encrypt_final, \ + .state_decrypt_detached_update = AEGIS_state_decrypt_detached_update, \ + .state_decrypt_detached_final = AEGIS_state_decrypt_detached_final, +#define AEGIS_API_IMPL_LIST_MAC \ + .state_mac_init = AEGIS_state_mac_init, \ + .state_mac_update = AEGIS_state_mac_update, \ + .state_mac_final = AEGIS_state_mac_final, \ + .state_mac_reset = AEGIS_state_mac_reset, \ + .state_mac_clone = AEGIS_state_mac_clone, + +#if 0 +#define AEGIS_API_IMPL_LIST \ + .encrypt_detached = AEGIS_encrypt_detached, \ + .decrypt_detached = AEGIS_decrypt_detached, \ + .encrypt_unauthenticated = AEGIS_encrypt_unauthenticated, \ + .decrypt_unauthenticated = AEGIS_decrypt_unauthenticated, \ + .stream = AEGIS_stream, \ + .state_init = AEGIS_state_init, \ + .state_encrypt_update = AEGIS_state_encrypt_update, \ + .state_encrypt_detached_final = AEGIS_state_encrypt_detached_final, \ + .state_encrypt_final = AEGIS_state_encrypt_final, \ + .state_decrypt_detached_update = AEGIS_state_decrypt_detached_update, \ + .state_decrypt_detached_final = AEGIS_state_decrypt_detached_final, \ + .state_mac_init = AEGIS_state_mac_init, \ + .state_mac_update = AEGIS_state_mac_update, \ + .state_mac_final = AEGIS_state_mac_final, \ + .state_mac_reset = AEGIS_state_mac_reset, \ + .state_mac_clone = AEGIS_state_mac_clone, +#endif + +#endif /* AEGIS_COMMON_H */ +/*** End of #include "common.h" ***/ + +/* #include "cpu.h" */ + + +static volatile uint16_t optblocker_u16; + +static inline int +aegis_verify_n(const uint8_t *x_, const uint8_t *y_, const int n) +{ + const volatile uint8_t *volatile x = (const volatile uint8_t *volatile) x_; + const volatile uint8_t *volatile y = (const volatile uint8_t *volatile) y_; + volatile uint16_t d = 0U; + int i; + + for (i = 0; i < n; i++) { + d |= x[i] ^ y[i]; + } +#if defined(__GNUC__) || defined(__clang__) + __asm__("" : "+r"(d) :); +#endif + d--; + d = ((d >> 13) ^ optblocker_u16) >> 2; + + return (int) d - 1; +} + +AEGIS_API +int +aegis_verify_16(const uint8_t *x, const uint8_t *y) +{ + return aegis_verify_n(x, y, 16); +} + +AEGIS_API +int +aegis_verify_32(const uint8_t *x, const uint8_t *y) +{ + return aegis_verify_n(x, y, 32); +} + +AEGIS_PRIVATE int aegis128l_pick_best_implementation(void); +AEGIS_PRIVATE int aegis128x2_pick_best_implementation(void); +AEGIS_PRIVATE int aegis128x4_pick_best_implementation(void); +AEGIS_PRIVATE int aegis256_pick_best_implementation(void); +AEGIS_PRIVATE int aegis256x2_pick_best_implementation(void); +AEGIS_PRIVATE int aegis256x4_pick_best_implementation(void); + +AEGIS_API +int +aegis_init(void) +{ + static int initialized = 0; + + if (initialized) { + return 0; + } + if (aegis_runtime_get_cpu_features() != 0) { + return 0; + } + if (aegis128l_pick_best_implementation() != 0 || aegis128x2_pick_best_implementation() != 0 || + aegis128x4_pick_best_implementation() != 0 || aegis256_pick_best_implementation() != 0 || + aegis256x2_pick_best_implementation() != 0 || aegis256x4_pick_best_implementation() != 0) { + return -1; + } + initialized = 1; + + return 0; +} + +#if 0 +#if defined(_MSC_VER) +# pragma section(".CRT$XCU", read) +static void __cdecl _do_aegis_init(void); +__declspec(allocate(".CRT$XCU")) void (*aegis_init_constructor)(void) = _do_aegis_init; +#else +static void _do_aegis_init(void) __attribute__((constructor)); +#endif + +static void +_do_aegis_init(void) +{ + (void) aegis_init(); +} +#endif +/*** End of #include "common/common.c" ***/ + +/* #include "common/cpu.c" */ +/*** Begin of #include "common/cpu.c" ***/ +/* +** Name: cpu.c +** Purpose: Implementation of CPU feature identification +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* #include "cpu.h" */ + +/* #include "common.h" */ + + +#include +#include +#include + +#ifdef HAVE_ANDROID_GETCPUFEATURES +# include +#endif +#ifdef __APPLE__ +# include +# include +# include +#endif +#ifdef HAVE_SYS_AUXV_H +# include +#endif +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) +# include +#endif + +typedef struct CPUFeatures_ { + int initialized; + int has_neon; + int has_armcrypto; + int has_avx; + int has_avx2; + int has_avx512f; + int has_aesni; + int has_vaes; + int has_altivec; +} CPUFeatures; + +static CPUFeatures _cpu_features; + +#define CPUID_EBX_AVX2 0x00000020 +#define CPUID_EBX_AVX512F 0x00010000 + +#define CPUID_ECX_AESNI 0x02000000 +#define CPUID_ECX_XSAVE 0x04000000 +#define CPUID_ECX_OSXSAVE 0x08000000 +#define CPUID_ECX_AVX 0x10000000 +#define CPUID_ECX_VAES 0x00000200 + +#define XCR0_SSE 0x00000002 +#define XCR0_AVX 0x00000004 +#define XCR0_OPMASK 0x00000020 +#define XCR0_ZMM_HI256 0x00000040 +#define XCR0_HI16_ZMM 0x00000080 + +static int +_runtime_arm_cpu_features(CPUFeatures *const cpu_features) +{ +#ifndef __ARM_ARCH + return -1; /* LCOV_EXCL_LINE */ +#endif + +#if defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64) + cpu_features->has_neon = 1; +#elif defined(HAVE_ANDROID_GETCPUFEATURES) && defined(ANDROID_CPU_ARM_FEATURE_NEON) + cpu_features->has_neon = (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0x0; +#elif (defined(__aarch64__) || defined(_M_ARM64)) && defined(AT_HWCAP) +# ifdef HAVE_GETAUXVAL + cpu_features->has_neon = (getauxval(AT_HWCAP) & (1L << 1)) != 0; +# elif defined(HAVE_ELF_AUX_INFO) + { + unsigned long buf; + if (elf_aux_info(AT_HWCAP, (void *) &buf, (int) sizeof buf) == 0) { + cpu_features->has_neon = (buf & (1L << 1)) != 0; + } + } +# endif +#elif defined(__arm__) && defined(AT_HWCAP) +# ifdef HAVE_GETAUXVAL + cpu_features->has_neon = (getauxval(AT_HWCAP) & (1L << 12)) != 0; +# elif defined(HAVE_ELF_AUX_INFO) + { + unsigned long buf; + if (elf_aux_info(AT_HWCAP, (void *) &buf, (int) sizeof buf) == 0) { + cpu_features->has_neon = (buf & (1L << 12)) != 0; + } + } +# endif +#endif + + if (cpu_features->has_neon == 0) { + return 0; + } + +#if __ARM_FEATURE_CRYPTO + cpu_features->has_armcrypto = 1; +#elif defined(_M_ARM64) + cpu_features->has_armcrypto = + 1; /* assuming all CPUs supported by ARM Windows have the crypto extensions */ +#elif defined(__APPLE__) && defined(CPU_TYPE_ARM64) && defined(CPU_SUBTYPE_ARM64E) + { + cpu_type_t cpu_type; + cpu_subtype_t cpu_subtype; + size_t cpu_type_len = sizeof cpu_type; + size_t cpu_subtype_len = sizeof cpu_subtype; + + if (sysctlbyname("hw.cputype", &cpu_type, &cpu_type_len, NULL, 0) == 0 && + cpu_type == CPU_TYPE_ARM64 && + sysctlbyname("hw.cpusubtype", &cpu_subtype, &cpu_subtype_len, NULL, 0) == 0 && + (cpu_subtype == CPU_SUBTYPE_ARM64E || cpu_subtype == CPU_SUBTYPE_ARM64_V8)) { + cpu_features->has_armcrypto = 1; + } + } +#elif defined(HAVE_ANDROID_GETCPUFEATURES) && defined(ANDROID_CPU_ARM_FEATURE_AES) + cpu_features->has_armcrypto = (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_AES) != 0x0; +#elif (defined(__aarch64__) || defined(_M_ARM64)) && defined(AT_HWCAP) +# ifdef HAVE_GETAUXVAL + cpu_features->has_armcrypto = (getauxval(AT_HWCAP) & (1L << 3)) != 0; +# elif defined(HAVE_ELF_AUX_INFO) + { + unsigned long buf; + if (elf_aux_info(AT_HWCAP, (void *) &buf, (int) sizeof buf) == 0) { + cpu_features->has_armcrypto = (buf & (1L << 3)) != 0; + } + } +# endif +#elif defined(__arm__) && defined(AT_HWCAP2) +# ifdef HAVE_GETAUXVAL + cpu_features->has_armcrypto = (getauxval(AT_HWCAP2) & (1L << 0)) != 0; +# elif defined(HAVE_ELF_AUX_INFO) + { + unsigned long buf; + if (elf_aux_info(AT_HWCAP2, (void *) &buf, (int) sizeof buf) == 0) { + cpu_features->has_armcrypto = (buf & (1L << 0)) != 0; + } + } +# endif +#endif + + return 0; +} + +static void +_cpuid(unsigned int cpu_info[4U], const unsigned int cpu_info_type) +{ +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + (__cpuid)((int *) cpu_info, cpu_info_type); +#elif defined(HAVE_CPUID) + cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0; +# ifdef __i386__ + __asm__ __volatile__( + "pushfl; pushfl; " + "popl %0; " + "movl %0, %1; xorl %2, %0; " + "pushl %0; " + "popfl; pushfl; popl %0; popfl" + : "=&r"(cpu_info[0]), "=&r"(cpu_info[1]) + : "i"(0x200000)); + if (((cpu_info[0] ^ cpu_info[1]) & 0x200000) == 0x0) { + return; /* LCOV_EXCL_LINE */ + } +# endif +# ifdef __i386__ + __asm__ __volatile__("xchgl %%ebx, %k1; cpuid; xchgl %%ebx, %k1" + : "=a"(cpu_info[0]), "=&r"(cpu_info[1]), "=c"(cpu_info[2]), + "=d"(cpu_info[3]) + : "0"(cpu_info_type), "2"(0U)); +# elif defined(__x86_64__) + __asm__ __volatile__("xchgq %%rbx, %q1; cpuid; xchgq %%rbx, %q1" + : "=a"(cpu_info[0]), "=&r"(cpu_info[1]), "=c"(cpu_info[2]), + "=d"(cpu_info[3]) + : "0"(cpu_info_type), "2"(0U)); +# else + __asm__ __volatile__("cpuid" + : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]), + "=d"(cpu_info[3]) + : "0"(cpu_info_type), "2"(0U)); +# endif +#else + (void) cpu_info_type; + cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0; +#endif +} + +static int +_runtime_intel_cpu_features(CPUFeatures *const cpu_features) +{ + unsigned int cpu_info[4]; + uint32_t xcr0 = 0U; + + _cpuid(cpu_info, 0x0); + if (cpu_info[0] == 0U) { + return -1; /* LCOV_EXCL_LINE */ + } + _cpuid(cpu_info, 0x00000001); + + (void) xcr0; +#ifdef HAVE_AVXINTRIN_H + if ((cpu_info[2] & (CPUID_ECX_AVX | CPUID_ECX_XSAVE | CPUID_ECX_OSXSAVE)) == + (CPUID_ECX_AVX | CPUID_ECX_XSAVE | CPUID_ECX_OSXSAVE)) { + xcr0 = 0U; +# if defined(HAVE__XGETBV) || \ + (defined(_MSC_VER) && defined(_XCR_XFEATURE_ENABLED_MASK) && _MSC_FULL_VER >= 160040219) + xcr0 = (uint32_t) _xgetbv(0); +# elif defined(_MSC_VER) && defined(_M_IX86) + /* + * Visual Studio documentation states that eax/ecx/edx don't need to + * be preserved in inline assembly code. But that doesn't seem to + * always hold true on Visual Studio 2010. + */ + __asm { + push eax + push ecx + push edx + xor ecx, ecx + _asm _emit 0x0f _asm _emit 0x01 _asm _emit 0xd0 + mov xcr0, eax + pop edx + pop ecx + pop eax + } +# elif defined(HAVE_AVX_ASM) + __asm__ __volatile__(".byte 0x0f, 0x01, 0xd0" /* XGETBV */ + : "=a"(xcr0) + : "c"((uint32_t) 0U) + : "%edx"); +# endif + if ((xcr0 & (XCR0_SSE | XCR0_AVX)) == (XCR0_SSE | XCR0_AVX)) { + cpu_features->has_avx = 1; + } + } +#endif + +#ifdef HAVE_WMMINTRIN_H + cpu_features->has_aesni = ((cpu_info[2] & CPUID_ECX_AESNI) != 0x0); +#endif + +#ifdef HAVE_AVX2INTRIN_H + if (cpu_features->has_avx) { + unsigned int cpu_info7[4]; + + _cpuid(cpu_info7, 0x00000007); + cpu_features->has_avx2 = ((cpu_info7[1] & CPUID_EBX_AVX2) != 0x0); + cpu_features->has_vaes = + cpu_features->has_aesni && ((cpu_info7[2] & CPUID_ECX_VAES) != 0x0); + } +#endif + + cpu_features->has_avx512f = 0; +#ifdef HAVE_AVX512FINTRIN_H + if (cpu_features->has_avx2) { + unsigned int cpu_info7[4]; + + _cpuid(cpu_info7, 0x00000007); + /* LCOV_EXCL_START */ + if ((cpu_info7[1] & CPUID_EBX_AVX512F) == CPUID_EBX_AVX512F && + (xcr0 & (XCR0_OPMASK | XCR0_ZMM_HI256 | XCR0_HI16_ZMM)) == + (XCR0_OPMASK | XCR0_ZMM_HI256 | XCR0_HI16_ZMM)) { + cpu_features->has_avx512f = 1; + } + /* LCOV_EXCL_STOP */ + } +#endif + + return 0; +} + +static int +_runtime_powerpc_cpu_features(CPUFeatures *const cpu_features) +{ + cpu_features->has_altivec = 0; +#if defined(__ALTIVEC__) && defined(__CRYPTO__) + cpu_features->has_altivec = 1; +#endif + return 0; +} + +AEGIS_PRIVATE +int +aegis_runtime_get_cpu_features(void) +{ + int ret = -1; + + memset(&_cpu_features, 0, sizeof _cpu_features); + + ret &= _runtime_arm_cpu_features(&_cpu_features); + ret &= _runtime_intel_cpu_features(&_cpu_features); + ret &= _runtime_powerpc_cpu_features(&_cpu_features); + _cpu_features.initialized = 1; + + return ret; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_neon(void) +{ + return _cpu_features.has_neon; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_armcrypto(void) +{ + return _cpu_features.has_armcrypto; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_avx(void) +{ + return _cpu_features.has_avx; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_avx2(void) +{ + return _cpu_features.has_avx2; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_avx512f(void) +{ + return _cpu_features.has_avx512f; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_aesni(void) +{ + return _cpu_features.has_aesni; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_vaes(void) +{ + return _cpu_features.has_vaes; +} + +AEGIS_PRIVATE +int +aegis_runtime_has_altivec(void) +{ + return _cpu_features.has_altivec; +} +/*** End of #include "common/cpu.c" ***/ + +/* #include "common/softaes.c" */ +/*** Begin of #include "common/softaes.c" ***/ +/* +** Name: softaes.c +** Purpose: Implementation of AES via software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include + +/* #include "common.h" */ + +/* #include "softaes.h" */ +/*** Begin of #include "softaes.h" ***/ +/* +** Name: softaes.h +** Purpose: Header for API of AES software implementation +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS_SOFTAES_H +#define AEGIS_SOFTAES_H + +#include + +/* #include "common.h" */ + + +typedef struct SoftAesBlock { + uint32_t w0; + uint32_t w1; + uint32_t w2; + uint32_t w3; +} SoftAesBlock; + +static SoftAesBlock +softaes_block_encrypt(const SoftAesBlock block, const SoftAesBlock rk); + +static inline SoftAesBlock +softaes_block_load(const uint8_t in[16]) +{ +#ifdef NATIVE_LITTLE_ENDIAN + SoftAesBlock out; + memcpy(&out, in, 16); +#else + const SoftAesBlock out = { AEGIS_LOAD32_LE(in + 0), AEGIS_LOAD32_LE(in + 4), AEGIS_LOAD32_LE(in + 8), + AEGIS_LOAD32_LE(in + 12) }; +#endif + return out; +} + +static inline SoftAesBlock +softaes_block_load64x2(const uint64_t a, const uint64_t b) +{ + const SoftAesBlock out = { (uint32_t) b, (uint32_t) (b >> 32), (uint32_t) a, + (uint32_t) (a >> 32) }; + return out; +} + +static inline void +softaes_block_store(uint8_t out[16], const SoftAesBlock in) +{ +#ifdef NATIVE_LITTLE_ENDIAN + memcpy(out, &in, 16); +#else + AEGIS_STORE32_LE(out + 0, in.w0); + AEGIS_STORE32_LE(out + 4, in.w1); + AEGIS_STORE32_LE(out + 8, in.w2); + AEGIS_STORE32_LE(out + 12, in.w3); +#endif +} + +static inline SoftAesBlock +softaes_block_xor(const SoftAesBlock a, const SoftAesBlock b) +{ + const SoftAesBlock out = { a.w0 ^ b.w0, a.w1 ^ b.w1, a.w2 ^ b.w2, a.w3 ^ b.w3 }; + return out; +} + +static inline SoftAesBlock +softaes_block_and(const SoftAesBlock a, const SoftAesBlock b) +{ + const SoftAesBlock out = { a.w0 & b.w0, a.w1 & b.w1, a.w2 & b.w2, a.w3 & b.w3 }; + return out; +} + +#endif /* AEGIS_SOFTAES_H */ +/*** End of #include "softaes.h" ***/ + + +#if defined(__wasm__) && !defined(FAVOR_PERFORMANCE) +# define FAVOR_PERFORMANCE +#endif + +#ifndef SOFTAES_STRIDE +# define SOFTAES_STRIDE 16 +#endif + +#ifdef FAVOR_PERFORMANCE +static const uint32_t _aes_lut[1024] = { + 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, + 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, + 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, + 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, + 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, + 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, + 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, + 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, + 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, + 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, + 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, + 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, + 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, + 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, + 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, + 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, + 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, + 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, + 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, + 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, + 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, + 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, + 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, + 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, + 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, + 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, + 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, + 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, + 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, + 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, + 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, + 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c, + 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, + 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, + 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, + 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, + 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, + 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, + 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, + 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, + 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, + 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, + 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, + 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, + 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, + 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, + 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, + 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, + 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, + 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, + 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, + 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, + 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, + 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, + 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, + 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, + 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, + 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, + 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, + 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, + 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, + 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, + 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, + 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a, + 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, + 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, + 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, + 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, + 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, + 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, + 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, + 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, + 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, + 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, + 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, + 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, + 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, + 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, + 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, + 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, + 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, + 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, + 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, + 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, + 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, + 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, + 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, + 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, + 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, + 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, + 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, + 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, + 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, + 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, + 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, + 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16, + 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, + 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, + 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, + 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, + 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, + 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, + 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, + 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, + 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, + 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, + 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, + 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, + 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, + 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, + 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, + 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, + 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, + 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, + 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, + 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, + 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, + 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, + 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, + 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, + 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, + 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, + 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, + 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, + 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, + 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, + 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, + 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616 +}; + +static const uint32_t* const LUT0 = _aes_lut + 0 * 256; +static const uint32_t* const LUT1 = _aes_lut + 1 * 256; +static const uint32_t* const LUT2 = _aes_lut + 2 * 256; +static const uint32_t* const LUT3 = _aes_lut + 3 * 256; + +SoftAesBlock +softaes_block_encrypt(const SoftAesBlock block, const SoftAesBlock rk) +{ + SoftAesBlock out; + uint8_t ix0[4], ix1[4], ix2[4], ix3[4]; + const uint32_t s0 = block.w0; + const uint32_t s1 = block.w1; + const uint32_t s2 = block.w2; + const uint32_t s3 = block.w3; + + ix0[0] = (uint8_t) s0; + ix0[1] = (uint8_t) s1; + ix0[2] = (uint8_t) s2; + ix0[3] = (uint8_t) s3; + + ix1[0] = (uint8_t) (s1 >> 8); + ix1[1] = (uint8_t) (s2 >> 8); + ix1[2] = (uint8_t) (s3 >> 8); + ix1[3] = (uint8_t) (s0 >> 8); + + ix2[0] = (uint8_t) (s2 >> 16); + ix2[1] = (uint8_t) (s3 >> 16); + ix2[2] = (uint8_t) (s0 >> 16); + ix2[3] = (uint8_t) (s1 >> 16); + + ix3[0] = (uint8_t) (s3 >> 24); + ix3[1] = (uint8_t) (s0 >> 24); + ix3[2] = (uint8_t) (s1 >> 24); + ix3[3] = (uint8_t) (s2 >> 24); + + out.w0 = LUT0[ix0[0]]; + out.w1 = LUT0[ix0[1]]; + out.w2 = LUT0[ix0[2]]; + out.w3 = LUT0[ix0[3]]; + + out.w0 ^= LUT1[ix1[0]]; + out.w1 ^= LUT1[ix1[1]]; + out.w2 ^= LUT1[ix1[2]]; + out.w3 ^= LUT1[ix1[3]]; + + out.w0 ^= LUT2[ix2[0]]; + out.w1 ^= LUT2[ix2[1]]; + out.w2 ^= LUT2[ix2[2]]; + out.w3 ^= LUT2[ix2[3]]; + + out.w0 ^= LUT3[ix3[0]]; + out.w1 ^= LUT3[ix3[1]]; + out.w2 ^= LUT3[ix3[2]]; + out.w3 ^= LUT3[ix3[3]]; + + out.w0 ^= rk.w0; + out.w1 ^= rk.w1; + out.w2 ^= rk.w2; + out.w3 ^= rk.w3; + + return out; +} +#else + +uint32_t _aes_lut[256] __attribute__((visibility("hidden"))) = { + 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, + 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, + 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, + 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, + 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, + 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, + 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, + 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, + 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, + 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, + 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, + 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, + 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, + 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, + 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, + 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, + 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, + 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, + 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, + 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, + 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, + 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, + 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, + 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, + 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, + 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, + 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, + 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, + 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, + 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, + 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, + 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c +}; + +static const uint32_t* const LUT = _aes_lut; + +static SoftAesBlock +_encrypt(const uint8_t ix0[4], const uint8_t ix1[4], const uint8_t ix2[4], const uint8_t ix3[4]) +{ + CRYPTO_ALIGN(64) uint32_t t[4][4][256 / SOFTAES_STRIDE]; + CRYPTO_ALIGN(64) uint8_t of[4][4]; + CRYPTO_ALIGN(64) SoftAesBlock out; + size_t i; + size_t j; + + for (j = 0; j < 4; j++) { + of[j][0] = ix0[j] % SOFTAES_STRIDE; + of[j][1] = ix1[j] % SOFTAES_STRIDE; + of[j][2] = ix2[j] % SOFTAES_STRIDE; + of[j][3] = ix3[j] % SOFTAES_STRIDE; + } + for (i = 0; i < 256 / SOFTAES_STRIDE; i++) { + for (j = 0; j < 4; j++) { + t[j][0][i] = LUT[(i * SOFTAES_STRIDE) | of[j][0]]; + t[j][1][i] = LUT[(i * SOFTAES_STRIDE) | of[j][1]]; + t[j][2][i] = LUT[(i * SOFTAES_STRIDE) | of[j][2]]; + t[j][3][i] = LUT[(i * SOFTAES_STRIDE) | of[j][3]]; + } + } + +# if defined(__GNUC__) || defined(__clang__) + __asm__ __volatile__("" : : "r"(t) : "memory"); +# endif + + out.w0 = t[0][0][ix0[0] / SOFTAES_STRIDE]; + out.w0 ^= AEGIS_ROTL32(t[0][1][ix1[0] / SOFTAES_STRIDE], 8); + out.w0 ^= AEGIS_ROTL32(t[0][2][ix2[0] / SOFTAES_STRIDE], 16); + out.w0 ^= AEGIS_ROTL32(t[0][3][ix3[0] / SOFTAES_STRIDE], 24); + + out.w1 = t[1][0][ix0[1] / SOFTAES_STRIDE]; + out.w1 ^= AEGIS_ROTL32(t[1][1][ix1[1] / SOFTAES_STRIDE], 8); + out.w1 ^= AEGIS_ROTL32(t[1][2][ix2[1] / SOFTAES_STRIDE], 16); + out.w1 ^= AEGIS_ROTL32(t[1][3][ix3[1] / SOFTAES_STRIDE], 24); + + out.w2 = t[2][0][ix0[2] / SOFTAES_STRIDE]; + out.w2 ^= AEGIS_ROTL32(t[2][1][ix1[2] / SOFTAES_STRIDE], 8); + out.w2 ^= AEGIS_ROTL32(t[2][2][ix2[2] / SOFTAES_STRIDE], 16); + out.w2 ^= AEGIS_ROTL32(t[2][3][ix3[2] / SOFTAES_STRIDE], 24); + + out.w3 = t[3][0][ix0[3] / SOFTAES_STRIDE]; + out.w3 ^= AEGIS_ROTL32(t[3][1][ix1[3] / SOFTAES_STRIDE], 8); + out.w3 ^= AEGIS_ROTL32(t[3][2][ix2[3] / SOFTAES_STRIDE], 16); + out.w3 ^= AEGIS_ROTL32(t[3][3][ix3[3] / SOFTAES_STRIDE], 24); + + return out; +} + +SoftAesBlock +softaes_block_encrypt(const SoftAesBlock block, const SoftAesBlock rk) +{ + CRYPTO_ALIGN(64) SoftAesBlock out; + CRYPTO_ALIGN(64) uint8_t ix0[4], ix1[4], ix2[4], ix3[4]; + const uint32_t s0 = block.w0; + const uint32_t s1 = block.w1; + const uint32_t s2 = block.w2; + const uint32_t s3 = block.w3; + + ix0[0] = (uint8_t) s0; + ix0[1] = (uint8_t) s1; + ix0[2] = (uint8_t) s2; + ix0[3] = (uint8_t) s3; + + ix1[0] = (uint8_t) (s1 >> 8); + ix1[1] = (uint8_t) (s2 >> 8); + ix1[2] = (uint8_t) (s3 >> 8); + ix1[3] = (uint8_t) (s0 >> 8); + + ix2[0] = (uint8_t) (s2 >> 16); + ix2[1] = (uint8_t) (s3 >> 16); + ix2[2] = (uint8_t) (s0 >> 16); + ix2[3] = (uint8_t) (s1 >> 16); + + ix3[0] = (uint8_t) (s3 >> 24); + ix3[1] = (uint8_t) (s0 >> 24); + ix3[2] = (uint8_t) (s1 >> 24); + ix3[3] = (uint8_t) (s2 >> 24); + + out = _encrypt(ix0, ix1, ix2, ix3); + + out.w0 ^= rk.w0; + out.w1 ^= rk.w1; + out.w2 ^= rk.w2; + out.w3 ^= rk.w3; + + return out; +} +#endif +/*** End of #include "common/softaes.c" ***/ + + +#if defined(__GNUC__) +# pragma GCC push_options +#endif + +/* AEGIS 128 L */ +/* #include "aegis128l/implementations.h" */ +/*** Begin of #include "aegis128l/implementations.h" ***/ +/* +** Name: implementations.h +** Purpose: Header for implementation structure of AEGIS-128L +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128L_IMPLEMENTATIONS_H +#define AEGIS128L_IMPLEMENTATIONS_H + +#include +#include + +/* #include "aegis128l.h" */ + + +typedef struct aegis128l_implementation { + int (*encrypt_detached)(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k); + int (*decrypt_detached)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + void (*stream)(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + void (*encrypt_unauthenticated)(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k); + void (*decrypt_unauthenticated)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k); +#ifndef AEGIS_OMIT_INCREMENTAL + void (*state_init)(aegis128l_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + int (*state_encrypt_update)(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen); + int (*state_encrypt_detached_final)(aegis128l_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + int (*state_encrypt_final)(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen); + int (*state_decrypt_detached_update)(aegis128l_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen); + int (*state_decrypt_detached_final)(aegis128l_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen); +#endif /* AEGIS_OMIT_INCREMENTAL */ +#ifndef AEGIS_OMIT_MAC_API + void (*state_mac_init)(aegis128l_mac_state *st_, const uint8_t *npub, const uint8_t *k); + int (*state_mac_update)(aegis128l_mac_state *st_, const uint8_t *ad, size_t adlen); + int (*state_mac_final)(aegis128l_mac_state *st_, uint8_t *mac, size_t maclen); + void (*state_mac_reset)(aegis128l_mac_state *st); + void (*state_mac_clone)(aegis128l_mac_state *dst, const aegis128l_mac_state *src); +#endif /* AEGIS_OMIT_MAC_API */ +} aegis128l_implementation; + +#endif /* AEGIS128L_IMPLEMENTATIONS_H */ +/*** End of #include "aegis128l/implementations.h" ***/ + +/* #include "aegis128l/aegis128l_aesni.c" */ +/*** Begin of #include "aegis128l/aegis128l_aesni.c" ***/ +/* +** Name: aegis128l_aesni.c +** Purpose: Implementation of AEGIS-128L - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128l.h" */ + +/* #include "aegis128l_aesni.h" */ +/*** Begin of #include "aegis128l_aesni.h" ***/ +/* +** Name: aegis128l_aesni.h +** Purpose: Header for implementation structure of AEGIS-128L - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128L_AESNI_H +#define AEGIS128L_AESNI_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128l_implementation aegis128l_aesni_implementation; + +#endif /* AEGIS128L_AESNI_H */ +/*** End of #include "aegis128l_aesni.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("aes,avx"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("aes,avx") +#endif + +#include +#include + +#define AES_BLOCK_LENGTH 16 + +typedef __m128i aegis128l_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128l_aes_block_t +#define AEGIS_BLOCKS aegis128l_blocks +#define AEGIS_STATE _aegis128l_state +#define AEGIS_MAC_STATE _aegis128l_mac_state + +#define AEGIS_FUNC_PREFIX aegis128l_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm_xor_si128(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm_and_si128(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return _mm_loadu_si128((const AEGIS_AES_BLOCK_T *) (const void *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return _mm_set_epi64x((long long) a, (long long) b); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm_storeu_si128((AEGIS_AES_BLOCK_T *) (void *) a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm_aesenc_si128(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128l_common.h" */ +/*** Begin of #include "aegis128l_common.h" ***/ +/* +** Name: aegis128l_common.h +** Purpose: Common implementation for AEGIS-128L +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + k = AEGIS_AES_BLOCK_LOAD(key); + n = AEGIS_AES_BLOCK_LOAD(nonce); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128l_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128l_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128l_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128l_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128l_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128l_mac_state *dst, const aegis128l_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128l_common.h" ***/ + + +struct aegis128l_implementation aegis128l_aesni_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128l/aegis128l_aesni.c" ***/ + +/* #include "aegis128l/aegis128l_altivec.c" */ +/*** Begin of #include "aegis128l/aegis128l_altivec.c" ***/ +/* +** Name: aegis128l_altivec.c +** Purpose: Implementation of AEGIS-128L - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__ALTIVEC__) && defined(__CRYPTO__) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128l.h" */ + +/* #include "aegis128l_altivec.h" */ +/*** Begin of #include "aegis128l_altivec.h" ***/ +/* +** Name: aegis128l_altivec.h +** Purpose: Header for implementation structure of AEGIS-128L - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128L_ALTIVEC_H +#define AEGIS128L_ALTIVEC_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128l_implementation aegis128l_altivec_implementation; + +#endif /* AEGIS128L_ALTIVEC_H */ +/*** End of #include "aegis128l_altivec.h" ***/ + + +#include + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("altivec,crypto"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("altivec,crypto") +#endif + +#define AES_BLOCK_LENGTH 16 + +typedef vector unsigned char aegis128l_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128l_aes_block_t +#define AEGIS_BLOCKS aegis128l_blocks +#define AEGIS_STATE _aegis128l_state +#define AEGIS_MAC_STATE _aegis128l_mac_state + +#define AEGIS_FUNC_PREFIX aegis128l_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return vec_xor(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return vec_and(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return vec_xl_be(0, (const unsigned char *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return (AEGIS_AES_BLOCK_T) vec_revb(vec_insert(a, vec_promote((unsigned long long) b, 1), 0)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vec_xst_be(b, 0, (unsigned char *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) vec_cipher_be(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(state[3], state[4]), d2); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d1); +} + +/* #include "aegis128l_common.h" */ +/*** Begin of #include "aegis128l_common.h" ***/ +/* +** Name: aegis128l_common.h +** Purpose: Common implementation for AEGIS-128L +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + k = AEGIS_AES_BLOCK_LOAD(key); + n = AEGIS_AES_BLOCK_LOAD(nonce); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128l_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128l_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128l_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128l_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128l_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128l_mac_state *dst, const aegis128l_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128l_common.h" ***/ + + +struct aegis128l_implementation aegis128l_altivec_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128l/aegis128l_altivec.c" ***/ + +/* #include "aegis128l/aegis128l_armcrypto.c" */ +/*** Begin of #include "aegis128l/aegis128l_armcrypto.c" ***/ +/* +** Name: aegis128l_armcrypto.c +** Purpose: Implementation of AEGIS-128L - ARM-Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* #include "../common/aeshardware.h" */ + + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128l.h" */ + +/* #include "aegis128l_armcrypto.h" */ +/*** Begin of #include "aegis128l_armcrypto.h" ***/ +/* +** Name: aegis128l_armcrypto.h +** Purpose: Header for implementation structure of AEGIS-128L - ARM Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128L_ARMCRYPTO_H +#define AEGIS128L_ARMCRYPTO_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128l_implementation aegis128l_armcrypto_implementation; + +#endif /* AEGIS128L_ARMCRYPTO_H */ +/*** End of #include "aegis128l_armcrypto.h" ***/ + + +#ifndef __ARM_FEATURE_CRYPTO +# define __ARM_FEATURE_CRYPTO 1 +#endif +#ifndef __ARM_FEATURE_AES +# define __ARM_FEATURE_AES 1 +#endif + +#ifdef USE_ARM64_NEON_H +#include +#else +#include +#endif + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("neon,crypto,aes"))), \ + apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("+simd+crypto") +#endif + +#define AES_BLOCK_LENGTH 16 + +typedef uint8x16_t aegis128l_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128l_aes_block_t +#define AEGIS_BLOCKS aegis128l_blocks +#define AEGIS_STATE _aegis128l_state +#define AEGIS_MAC_STATE _aegis128l_mac_state + +#define AEGIS_FUNC_PREFIX aegis128l_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return veorq_u8(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return vandq_u8(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return vld1q_u8(a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return vreinterpretq_u8_u64(vsetq_lane_u64(a, vmovq_n_u64(b), 1)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vst1q_u8(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return veorq_u8(vaesmcq_u8(vaeseq_u8(a, vmovq_n_u8(0))), b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(state[3], state[4]), d2); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d1); +} + +/* #include "aegis128l_common.h" */ +/*** Begin of #include "aegis128l_common.h" ***/ +/* +** Name: aegis128l_common.h +** Purpose: Common implementation for AEGIS-128L +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + k = AEGIS_AES_BLOCK_LOAD(key); + n = AEGIS_AES_BLOCK_LOAD(nonce); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128l_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128l_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128l_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128l_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128l_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128l_mac_state *dst, const aegis128l_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128l_common.h" ***/ + + +struct aegis128l_implementation aegis128l_armcrypto_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128l/aegis128l_armcrypto.c" ***/ + +/* #include "aegis128l/aegis128l_soft.c" */ +/*** Begin of #include "aegis128l/aegis128l_soft.c" ***/ +/* +** Name: aegis128l_soft.c +** Purpose: Implementation of AEGIS-128L - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + + +/* #include "../common/softaes.h" */ + +/* #include "aegis128l.h" */ + +/* #include "aegis128l_soft.h" */ +/*** Begin of #include "aegis128l_soft.h" ***/ +/* +** Name: aegis128l_soft.h +** Purpose: Header for implementation structure of AEGIS-128L - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128L_SOFT_H +#define AEGIS128L_SOFT_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128l_implementation aegis128l_soft_implementation; + +#endif /* AEGIS128L_SOFT_H */ +/*** End of #include "aegis128l_soft.h" ***/ + + +#define AES_BLOCK_LENGTH 16 + +typedef SoftAesBlock aegis128l_soft_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128l_soft_aes_block_t +#define AEGIS_BLOCKS aegis128l_soft_blocks +#define AEGIS_STATE _aegis128l_soft_state +#define AEGIS_MAC_STATE _aegis128l_soft_mac_state + +#define AEGIS_FUNC_PREFIX aegis128l_soft_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return softaes_block_xor(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return softaes_block_and(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return softaes_block_load(a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return softaes_block_load64x2(a, b); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + softaes_block_store(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return softaes_block_encrypt(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128l_common.h" */ +/*** Begin of #include "aegis128l_common.h" ***/ +/* +** Name: aegis128l_common.h +** Purpose: Common implementation for AEGIS-128L +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + k = AEGIS_AES_BLOCK_LOAD(key); + n = AEGIS_AES_BLOCK_LOAD(nonce); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128l_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128l_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128l_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128l_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128l_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128l_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128l_mac_state *dst, const aegis128l_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128l_common.h" ***/ + + +struct aegis128l_implementation aegis128l_soft_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + +/*** End of #include "aegis128l/aegis128l_soft.c" ***/ + +/* #include "aegis128l/aegis128l.c" */ +/*** Begin of #include "aegis128l/aegis128l.c" ***/ +/* +** Name: aegis128l.c +** Purpose: Implementation of AEGIS-128L +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + +/* #include "../include/aegis128l.h" */ + +#if 0 +/* #include "aegis128l_aesni.h" */ + +/* #include "aegis128l_altivec.h" */ + +/* #include "aegis128l_armcrypto.h" */ + +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NONE +/* #include "aegis128l_soft.h" */ + +static const aegis128l_implementation *implementation_128l = &aegis128l_soft_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON +static const aegis128l_implementation *implementation_128l = &aegis128l_armcrypto_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +static const aegis128l_implementation *implementation_128l = &aegis128l_aesni_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC +static const aegis128l_implementation *implementation_128l = &aegis128l_altivec_implementation; +#else +#error "Unsupported architecture" +#endif + +AEGIS_API +size_t +aegis128l_keybytes(void) +{ + return aegis128l_KEYBYTES; +} + +AEGIS_API +size_t +aegis128l_npubbytes(void) +{ + return aegis128l_NPUBBYTES; +} + +AEGIS_API +size_t +aegis128l_abytes_min(void) +{ + return aegis128l_ABYTES_MIN; +} + +AEGIS_API +size_t +aegis128l_abytes_max(void) +{ + return aegis128l_ABYTES_MAX; +} + +AEGIS_API +size_t +aegis128l_tailbytes_max(void) +{ + return aegis128l_TAILBYTES_MAX; +} + +AEGIS_API +int +aegis128l_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128l->encrypt_detached(c, mac, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128l_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128l->decrypt_detached(m, c, clen, mac, maclen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128l_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + return aegis128l_encrypt_detached(c, c + mlen, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128l_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + int ret = -1; + + if (clen >= maclen) { + ret = aegis128l_decrypt_detached(m, c, clen - maclen, c + clen - maclen, maclen, ad, adlen, + npub, k); + } + return ret; +} + +#ifndef AEGIS_OMIT_INCREMENTAL + +AEGIS_API +void +aegis128l_state_init(aegis128l_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + memset(st_, 0, sizeof *st_); + implementation_128l->state_init(st_, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128l_state_encrypt_update(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + return implementation_128l->state_encrypt_update(st_, c, clen_max, written, m, mlen); +} + +AEGIS_API +int +aegis128l_state_encrypt_detached_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128l->state_encrypt_detached_final(st_, c, clen_max, written, mac, maclen); +} + +AEGIS_API +int +aegis128l_state_encrypt_final(aegis128l_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128l->state_encrypt_final(st_, c, clen_max, written, maclen); +} + +AEGIS_API +int +aegis128l_state_decrypt_detached_update(aegis128l_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) +{ + return implementation_128l->state_decrypt_detached_update(st_, m, mlen_max, written, c, clen); +} + +AEGIS_API +int +aegis128l_state_decrypt_detached_final(aegis128l_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128l->state_decrypt_detached_final(st_, m, mlen_max, written, mac, maclen); +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +AEGIS_API +void +aegis128l_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + implementation_128l->stream(out, len, npub, k); +} + +AEGIS_API +void +aegis128l_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_128l->encrypt_unauthenticated(c, m, mlen, npub, k); +} + +AEGIS_API +void +aegis128l_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_128l->decrypt_unauthenticated(m, c, clen, npub, k); +} + +#ifndef AEGIS_OMIT_MAC_API + +AEGIS_API +void +aegis128l_mac_init(aegis128l_mac_state *st_, const uint8_t *k, const uint8_t *npub) +{ +#if 0 + memset(st_, 0, sizeof *st_); +#endif + implementation_128l->state_mac_init(st_, npub, k); +} + +AEGIS_API +int +aegis128l_mac_update(aegis128l_mac_state *st_, const uint8_t *m, size_t mlen) +{ + return implementation_128l->state_mac_update(st_, m, mlen); +} + +AEGIS_API +int +aegis128l_mac_final(aegis128l_mac_state *st_, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128l->state_mac_final(st_, mac, maclen); +} + +AEGIS_API +int +aegis128l_mac_verify(aegis128l_mac_state *st_, const uint8_t *mac, size_t maclen) +{ + uint8_t expected_mac[32]; + + switch (maclen) { + case 16: + implementation_128l->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_16(expected_mac, mac); + case 32: + implementation_128l->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_32(expected_mac, mac); + default: + errno = EINVAL; + return -1; + } +} + +AEGIS_API +void +aegis128l_mac_reset(aegis128l_mac_state *st_) +{ + implementation_128l->state_mac_reset(st_); +} + +AEGIS_API +void +aegis128l_mac_state_clone(aegis128l_mac_state *dst, const aegis128l_mac_state *src) +{ + implementation_128l->state_mac_clone(dst, src); +} + +#endif /* AEGIS_OMIT_MAC_API */ + +AEGIS_PRIVATE +int +aegis128l_pick_best_implementation(void) +{ + implementation_128l = &aegis128l_soft_implementation; + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + if (aegis_runtime_has_armcrypto()) { + implementation_128l = &aegis128l_armcrypto_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI + if (aegis_runtime_has_aesni() && aegis_runtime_has_avx()) { + implementation_128l = &aegis128l_aesni_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC + if (aegis_runtime_has_altivec()) { + implementation_128l = &aegis128l_altivec_implementation; + return 0; + } +#endif + + return 0; /* LCOV_EXCL_LINE */ +} +/*** End of #include "aegis128l/aegis128l.c" ***/ + + +/* AEGIS 128 x2 */ +/* #include "aegis128x2/implementations.h" */ +/*** Begin of #include "aegis128x2/implementations.h" ***/ +/* +** Name: implementations.h +** Purpose: Header for implementation structure of AEGIS-128x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X2_IMPLEMENTATIONS_H +#define AEGIS128X2_IMPLEMENTATIONS_H + +#include +#include + +/* #include "aegis128x2.h" */ + + +typedef struct aegis128x2_implementation { + int (*encrypt_detached)(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k); + int (*decrypt_detached)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + void (*stream)(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + void (*encrypt_unauthenticated)(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k); + void (*decrypt_unauthenticated)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k); +#ifndef AEGIS_OMIT_INCREMENTAL + void (*state_init)(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + int (*state_encrypt_update)(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen); + int (*state_encrypt_detached_final)(aegis128x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + int (*state_encrypt_final)(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen); + int (*state_decrypt_detached_update)(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen); + int (*state_decrypt_detached_final)(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen); +#endif /* AEGIS_OMIT_INCREMENTAL */ +#ifndef AEGIS_OMIT_MAC_API + void (*state_mac_init)(aegis128x2_mac_state *st_, const uint8_t *npub, const uint8_t *k); + int (*state_mac_update)(aegis128x2_mac_state *st_, const uint8_t *ad, size_t adlen); + int (*state_mac_final)(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen); + void (*state_mac_reset)(aegis128x2_mac_state *st); + void (*state_mac_clone)(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src); +#endif /* AEGIS_OMIT_MAC_API */ +} aegis128x2_implementation; + +#endif /* AEGIS128X2_IMPLEMENTATIONS_H */ +/*** End of #include "aegis128x2/implementations.h" ***/ + +/* #include "aegis128x2/aegis128x2_aesni.c" */ +/*** Begin of #include "aegis128x2/aegis128x2_aesni.c" ***/ +/* +** Name: aegis128x2_aesni.c +** Purpose: Implementation of AEGIS-128x2 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x2.h" */ + +/* #include "aegis128x2_aesni.h" */ +/*** Begin of #include "aegis128x2_aesni.h" ***/ +/* +** Name: aegis128x2_aesni.h +** Purpose: Header for implementation structure of AEGIS-128x2 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X2_AESNI_H +#define AEGIS128X2_AESNI_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x2_implementation aegis128x2_aesni_implementation; + +#endif /* AEGIS128X2_AESNI_H */ +/*** End of #include "aegis128x2_aesni.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("aes,avx"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("aes,avx") +#endif + +#include +#include + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + __m128i b0; + __m128i b1; +} aegis128x2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x2_aes_block_t +#define AEGIS_BLOCKS aegis128x2_blocks +#define AEGIS_STATE _aegis128x2_state +#define AEGIS_MAC_STATE _aegis128x2_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_xor_si128(a.b0, b.b0), _mm_xor_si128(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_and_si128(a.b0, b.b0), _mm_and_si128(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { _mm_loadu_si128((const __m128i *) (const void *) a), + _mm_loadu_si128((const __m128i *) (const void *) (a + 16)) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const __m128i t = _mm_set_epi64x((long long) a, (long long) b); + return (AEGIS_AES_BLOCK_T) { t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm_storeu_si128((__m128i *) (void *) a, b.b0); + _mm_storeu_si128((__m128i *) (void *) (a + 16), b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_aesenc_si128(a.b0, b.b0), _mm_aesenc_si128(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128x2_common.h" */ +/*** Begin of #include "aegis128x2_common.h" ***/ +/* +** Name: aegis128x2_common.h +** Purpose: Common implementation for AEGIS-128x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T*state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); + +} + +static void +AEGIS_state_mac_clone(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE*const src_ = + (const AEGIS_MAC_STATE*) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x2_common.h" ***/ + + +struct aegis128x2_implementation aegis128x2_aesni_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128x2/aegis128x2_aesni.c" ***/ + +/* #include "aegis128x2/aegis128x2_altivec.c" */ +/*** Begin of #include "aegis128x2/aegis128x2_altivec.c" ***/ +/* +** Name: aegis128x2_altivec.c +** Purpose: Implementation of AEGIS-128x2 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__ALTIVEC__) && defined(__CRYPTO__) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x2.h" */ + +/* #include "aegis128x2_altivec.h" */ +/*** Begin of #include "aegis128x2_altivec.h" ***/ +/* +** Name: aegis128x2_altivec.h +** Purpose: Header for implementation structure of AEGIS-128x2 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X2_ALTIVEC_H +#define AEGIS128X2_ALTIVEC_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x2_implementation aegis128x2_altivec_implementation; + +#endif /* AEGIS128X2_ALTIVEC_H */ +/*** End of #include "aegis128x2_altivec.h" ***/ + + +#include + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("altivec,crypto"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("altivec,crypto") +#endif + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + vector unsigned char b0; + vector unsigned char b1; +} aegis128x2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x2_aes_block_t +#define AEGIS_BLOCKS aegis128x2_blocks +#define AEGIS_STATE _aegis128x2_state +#define AEGIS_MAC_STATE _aegis128x2_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_xor(a.b0, b.b0), vec_xor(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_and(a.b0, b.b0), vec_and(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vec_xl_be(0, a), vec_xl_be(0, a + 16) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const vector unsigned char t = + (vector unsigned char) vec_revb(vec_insert(a, vec_promote((unsigned long long) (b), 1), 0)); + return (AEGIS_AES_BLOCK_T) { t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vec_xst_be(b.b0, 0, a); + vec_xst_be(b.b1, 0, a + 16); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_cipher_be(a.b0, b.b0), vec_cipher_be(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(state[3], state[4]), d2); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d1); +} + +/* #include "aegis128x2_common.h" */ +/*** Begin of #include "aegis128x2_common.h" ***/ +/* +** Name: aegis128x2_common.h +** Purpose: Common implementation for AEGIS-128x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T*state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); + +} + +static void +AEGIS_state_mac_clone(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE*const src_ = + (const AEGIS_MAC_STATE*) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x2_common.h" ***/ + + +struct aegis128x2_implementation aegis128x2_altivec_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128x2/aegis128x2_altivec.c" ***/ + +/* #include "aegis128x2/aegis128x2_armcrypto.c" */ +/*** Begin of #include "aegis128x2/aegis128x2_armcrypto.c" ***/ +/* +** Name: aegis128x2_armcrypto.c +** Purpose: Implementation of AEGIS-128x2 - ARM-Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* #include "../common/aeshardware.h" */ + + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x2.h" */ + +/* #include "aegis128x2_armcrypto.h" */ +/*** Begin of #include "aegis128x2_armcrypto.h" ***/ +/* +** Name: aegis128x2_armcrypto.h +** Purpose: Header for implementation structure of AEGIS-128x2 - ARM Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X2_ARMCRYPTO_H +#define AEGIS128X2_ARMCRYPTO_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x2_implementation aegis128x2_armcrypto_implementation; + +#endif /* AEGIS128X2_ARMCRYPTO_H */ +/*** End of #include "aegis128x2_armcrypto.h" ***/ + + +#ifndef __ARM_FEATURE_CRYPTO +# define __ARM_FEATURE_CRYPTO 1 +#endif +#ifndef __ARM_FEATURE_AES +# define __ARM_FEATURE_AES 1 +#endif + +#ifdef USE_ARM64_NEON_H +#include +#else +#include +#endif + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("neon,crypto,aes"))), \ + apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("+simd+crypto") +#endif + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + uint8x16_t b0; + uint8x16_t b1; +} aegis128x2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x2_aes_block_t +#define AEGIS_BLOCKS aegis128x2_blocks +#define AEGIS_STATE _aegis128x2_state +#define AEGIS_MAC_STATE _aegis128x2_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(a.b0, b.b0), veorq_u8(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vandq_u8(a.b0, b.b0), vandq_u8(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vld1q_u8(a), vld1q_u8(a + 16) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const uint8x16_t t = vreinterpretq_u8_u64(vsetq_lane_u64((a), vmovq_n_u64(b), 1)); + return (AEGIS_AES_BLOCK_T) { t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vst1q_u8(a, b.b0); + vst1q_u8(a + 16, b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(vaesmcq_u8(vaeseq_u8((a.b0), vmovq_n_u8(0))), (b.b0)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b1), vmovq_n_u8(0))), (b.b1)) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(state[3], state[4]), d2); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d1); +} + +/* #include "aegis128x2_common.h" */ +/*** Begin of #include "aegis128x2_common.h" ***/ +/* +** Name: aegis128x2_common.h +** Purpose: Common implementation for AEGIS-128x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T*state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); + +} + +static void +AEGIS_state_mac_clone(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE*const src_ = + (const AEGIS_MAC_STATE*) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x2_common.h" ***/ + + +struct aegis128x2_implementation aegis128x2_armcrypto_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128x2/aegis128x2_armcrypto.c" ***/ + +/* #include "aegis128x2/aegis128x2_avx2.c" */ +/*** Begin of #include "aegis128x2/aegis128x2_avx2.c" ***/ +/* +** Name: aegis128x2_avx2.c +** Purpose: Implementation of AEGIS-128x2 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x2.h" */ + +/* #include "aegis128x2_avx2.h" */ +/*** Begin of #include "aegis128x2_avx2.h" ***/ +/* +** Name: aegis128x2_avx2.h +** Purpose: Header for implementation structure of AEGIS-128x2 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X2_AVX2_H +#define AEGIS128X2_AVX2_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +#ifdef HAVE_VAESINTRIN_H +extern struct aegis128x2_implementation aegis128x2_avx2_implementation; +#endif + +#endif /* AEGIS128X2_AVX2_H */ +/*** End of #include "aegis128x2_avx2.h" ***/ + + +#ifdef HAVE_VAESINTRIN_H + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("vaes,avx2"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("vaes,avx2") +#endif + +#include + +#define AES_BLOCK_LENGTH 32 + +typedef __m256i aegis128x2_avx2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x2_avx2_aes_block_t +#define AEGIS_BLOCKS aegis128x2_avx2_blocks +#define AEGIS_STATE _aegis128x2_avx2_state +#define AEGIS_MAC_STATE _aegis128x2_avx2_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x2_avx2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm256_xor_si256(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm256_and_si256(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return _mm256_loadu_si256((const AEGIS_AES_BLOCK_T *) (const void *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return _mm256_broadcastsi128_si256(_mm_set_epi64x(a, b)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm256_storeu_si256((AEGIS_AES_BLOCK_T *) (void *) a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm256_aesenc_epi128(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128x2_common.h" */ +/*** Begin of #include "aegis128x2_common.h" ***/ +/* +** Name: aegis128x2_common.h +** Purpose: Common implementation for AEGIS-128x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T*state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); + +} + +static void +AEGIS_state_mac_clone(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE*const src_ = + (const AEGIS_MAC_STATE*) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x2_common.h" ***/ + + +struct aegis128x2_implementation aegis128x2_avx2_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif /* HAVE_VAESINTRIN_H */ + +#endif +/*** End of #include "aegis128x2/aegis128x2_avx2.c" ***/ + +/* #include "aegis128x2/aegis128x2_soft.c" */ +/*** Begin of #include "aegis128x2/aegis128x2_soft.c" ***/ +/* +** Name: aegis128x2_soft.c +** Purpose: Implementation of AEGIS-128x2 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + + +/* #include "../common/softaes.h" */ + +/* #include "aegis128x2.h" */ + +/* #include "aegis128x2_soft.h" */ +/*** Begin of #include "aegis128x2_soft.h" ***/ +/* +** Name: aegis128x2_soft.h +** Purpose: Header for implementation structure of AEGIS-128x2 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X2_SOFT_H +#define AEGIS128X2_SOFT_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x2_implementation aegis128x2_soft_implementation; + +#endif /* AEGIS128X2_SOFT_H */ +/*** End of #include "aegis128x2_soft.h" ***/ + + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + SoftAesBlock b0; + SoftAesBlock b1; +} aegis128x2_soft_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x2_soft_aes_block_t +#define AEGIS_BLOCKS aegis128x2_soft_blocks +#define AEGIS_STATE _aegis128x2_soft_state +#define AEGIS_MAC_STATE _aegis128x2_soft_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x2_soft_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_xor(a.b0, b.b0), softaes_block_xor(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_and(a.b0, b.b0), softaes_block_and(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_load(a), softaes_block_load(a + 16) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const SoftAesBlock t = softaes_block_load64x2(a, b); + return (AEGIS_AES_BLOCK_T) { t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + softaes_block_store(a, b.b0); + softaes_block_store(a + 16, b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_encrypt(a.b0, b.b0), softaes_block_encrypt(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128x2_common.h" */ +/*** Begin of #include "aegis128x2_common.h" ***/ +/* +** Name: aegis128x2_common.h +** Purpose: Common implementation for AEGIS-128x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T*state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); + +} + +static void +AEGIS_state_mac_clone(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE*const src_ = + (const AEGIS_MAC_STATE*) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x2_common.h" ***/ + + +struct aegis128x2_implementation aegis128x2_soft_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + +/*** End of #include "aegis128x2/aegis128x2_soft.c" ***/ + +/* #include "aegis128x2/aegis128x2.c" */ +/*** Begin of #include "aegis128x2/aegis128x2.c" ***/ +/* +** Name: aegis128x2.c +** Purpose: Implementation of AEGIS-128x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + +/* #include "../include/aegis128x2.h" */ + +#if 0 +/* #include "aegis128x2_aesni.h" */ + +/* #include "aegis128x2_altivec.h" */ + +/* #include "aegis128x2_armcrypto.h" */ + +/* #include "aegis128x2_avx2.h" */ + +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NONE +/* #include "aegis128x2_soft.h" */ + +static const aegis128x2_implementation* implementation_128x2 = &aegis128x2_soft_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON +static const aegis128x2_implementation* implementation_128x2 = &aegis128x2_armcrypto_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +static const aegis128x2_implementation* implementation_128x2 = &aegis128x2_aesni_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC +static const aegis128x2_implementation* implementation_128x2 = &aegis128x2_altivec_implementation; +#else +#error "Unsupported architecture" +#endif + +AEGIS_API +size_t +aegis128x2_keybytes(void) +{ + return aegis128x2_KEYBYTES; +} + +AEGIS_API +size_t +aegis128x2_npubbytes(void) +{ + return aegis128x2_NPUBBYTES; +} + +AEGIS_API +size_t +aegis128x2_abytes_min(void) +{ + return aegis128x2_ABYTES_MIN; +} + +AEGIS_API +size_t +aegis128x2_abytes_max(void) +{ + return aegis128x2_ABYTES_MAX; +} + +AEGIS_API +size_t +aegis128x2_tailbytes_max(void) +{ + return aegis128x2_TAILBYTES_MAX; +} + +AEGIS_API +int +aegis128x2_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x2->encrypt_detached(c, mac, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x2_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x2->decrypt_detached(m, c, clen, mac, maclen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x2_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + return aegis128x2_encrypt_detached(c, c + mlen, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x2_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + int ret = -1; + + if (clen >= maclen) { + ret = aegis128x2_decrypt_detached(m, c, clen - maclen, c + clen - maclen, maclen, ad, adlen, + npub, k); + } + return ret; +} + +#ifndef AEGIS_OMIT_INCREMENTAL + +AEGIS_API +void +aegis128x2_state_init(aegis128x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + memset(st_, 0, sizeof *st_); + implementation_128x2->state_init(st_, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x2_state_encrypt_update(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + return implementation_128x2->state_encrypt_update(st_, c, clen_max, written, m, mlen); +} + +AEGIS_API +int +aegis128x2_state_encrypt_detached_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x2->state_encrypt_detached_final(st_, c, clen_max, written, mac, maclen); +} + +AEGIS_API +int +aegis128x2_state_encrypt_final(aegis128x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x2->state_encrypt_final(st_, c, clen_max, written, maclen); +} + +AEGIS_API +int +aegis128x2_state_decrypt_detached_update(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) +{ + return implementation_128x2->state_decrypt_detached_update(st_, m, mlen_max, written, c, clen); +} + +AEGIS_API +int +aegis128x2_state_decrypt_detached_final(aegis128x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x2->state_decrypt_detached_final(st_, m, mlen_max, written, mac, maclen); +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +AEGIS_API +void +aegis128x2_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + implementation_128x2->stream(out, len, npub, k); +} + +AEGIS_API +void +aegis128x2_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_128x2->encrypt_unauthenticated(c, m, mlen, npub, k); +} + +AEGIS_API +void +aegis128x2_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_128x2->decrypt_unauthenticated(m, c, clen, npub, k); +} + +#ifndef AEGIS_OMIT_MAC_API + +AEGIS_API +void +aegis128x2_mac_init(aegis128x2_mac_state *st_, const uint8_t *k, const uint8_t *npub) +{ + implementation_128x2->state_mac_init(st_, npub, k); +} + +AEGIS_API +int +aegis128x2_mac_update(aegis128x2_mac_state *st_, const uint8_t *m, size_t mlen) +{ + return implementation_128x2->state_mac_update(st_, m, mlen); +} + +AEGIS_API +int +aegis128x2_mac_final(aegis128x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x2->state_mac_final(st_, mac, maclen); +} + +AEGIS_API +int +aegis128x2_mac_verify(aegis128x2_mac_state *st_, const uint8_t *mac, size_t maclen) +{ + uint8_t expected_mac[32]; + + switch (maclen) { + case 16: + implementation_128x2->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_16(expected_mac, mac); + case 32: + implementation_128x2->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_32(expected_mac, mac); + default: + errno = EINVAL; + return -1; + } +} + +AEGIS_API +void +aegis128x2_mac_reset(aegis128x2_mac_state *st_) +{ + implementation_128x2->state_mac_reset(st_); +} + +AEGIS_API +void +aegis128x2_mac_state_clone(aegis128x2_mac_state *dst, const aegis128x2_mac_state *src) +{ + implementation_128x2->state_mac_clone(dst, src); +} + +#endif /* AEGIS_OMIT_MAC_API */ + +AEGIS_PRIVATE +int +aegis128x2_pick_best_implementation(void) +{ + implementation_128x2 = &aegis128x2_soft_implementation; + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + if (aegis_runtime_has_armcrypto()) { + implementation_128x2 = &aegis128x2_armcrypto_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +# ifdef HAVE_VAESINTRIN_H + if (aegis_runtime_has_vaes() && aegis_runtime_has_avx2()) { + implementation_128x2 = &aegis128x2_avx2_implementation; + return 0; + } +# endif + if (aegis_runtime_has_aesni() && aegis_runtime_has_avx()) { + implementation_128x2 = &aegis128x2_aesni_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC + if (aegis_runtime_has_altivec()) { + implementation_128x2 = &aegis128x2_altivec_implementation; + return 0; + } +#endif + + return 0; /* LCOV_EXCL_LINE */ +} +/*** End of #include "aegis128x2/aegis128x2.c" ***/ + + +/* AEGIS 128 x4 */ +/* #include "aegis128x4/implementations.h" */ +/*** Begin of #include "aegis128x4/implementations.h" ***/ +/* +** Name: implementations.h +** Purpose: Header for implementation structure of AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_IMPLEMENTATIONS_H +#define AEGIS128X4_IMPLEMENTATIONS_H + +#include +#include + +/* #include "aegis128x4.h" */ + + +typedef struct aegis128x4_implementation { + int (*encrypt_detached)(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k); + int (*decrypt_detached)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + void (*stream)(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + void (*encrypt_unauthenticated)(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k); + void (*decrypt_unauthenticated)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k); +#ifndef AEGIS_OMIT_INCREMENTAL + void (*state_init)(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + int (*state_encrypt_update)(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen); + int (*state_encrypt_detached_final)(aegis128x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + int (*state_encrypt_final)(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen); + int (*state_decrypt_detached_update)(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen); + int (*state_decrypt_detached_final)(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen); +#endif /* AEGIS_OMIT_INCREMENTAL */ +#ifndef AEGIS_OMIT_MAC_API + void (*state_mac_init)(aegis128x4_mac_state *st_, const uint8_t *npub, const uint8_t *k); + int (*state_mac_update)(aegis128x4_mac_state *st_, const uint8_t *ad, size_t adlen); + int (*state_mac_final)(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen); + void (*state_mac_reset)(aegis128x4_mac_state *st); + void (*state_mac_clone)(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src); +#endif /* AEGIS_OMIT_MAC_API */ +} aegis128x4_implementation; + +#endif /* AEGIS128X4_IMPLEMENTATIONS_H */ +/*** End of #include "aegis128x4/implementations.h" ***/ + +/* #include "aegis128x4/aegis128x4_aesni.c" */ +/*** Begin of #include "aegis128x4/aegis128x4_aesni.c" ***/ +/* +** Name: aegis128x4_aesni.c +** Purpose: Implementation of AEGIS-128x4 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x4.h" */ + +/* #include "aegis128x4_aesni.h" */ +/*** Begin of #include "aegis128x4_aesni.h" ***/ +/* +** Name: aegis128x4_aesni.h +** Purpose: Header for implementation structure of AEGIS-128x4 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_AESNI_H +#define AEGIS128X4_AESNI_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x4_implementation aegis128x4_aesni_implementation; + +#endif /* AEGIS128X4_AESNI_H */ +/*** End of #include "aegis128x4_aesni.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("aes,avx"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("aes,avx") +#endif + +#include +#include + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + __m128i b0; + __m128i b1; + __m128i b2; + __m128i b3; +} aegis128x4_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x4_aes_block_t +#define AEGIS_BLOCKS aegis128x4_blocks +#define AEGIS_STATE _aegis128x4_state +#define AEGIS_MAC_STATE _aegis128x4_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x4_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_xor_si128(a.b0, b.b0), _mm_xor_si128(a.b1, b.b1), + _mm_xor_si128(a.b2, b.b2), _mm_xor_si128(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_and_si128(a.b0, b.b0), _mm_and_si128(a.b1, b.b1), + _mm_and_si128(a.b2, b.b2), _mm_and_si128(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { _mm_loadu_si128((const __m128i *) (const void *) a), + _mm_loadu_si128((const __m128i *) (const void *) (a + 16)), + _mm_loadu_si128((const __m128i *) (const void *) (a + 32)), + _mm_loadu_si128((const __m128i *) (const void *) (a + 48)) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const __m128i t = _mm_set_epi64x((long long) a, (long long) b); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm_storeu_si128((__m128i *) (void *) a, b.b0); + _mm_storeu_si128((__m128i *) (void *) (a + 16), b.b1); + _mm_storeu_si128((__m128i *) (void *) (a + 32), b.b2); + _mm_storeu_si128((__m128i *) (void *) (a + 48), b.b3); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_aesenc_si128(a.b0, b.b0), _mm_aesenc_si128(a.b1, b.b1), + _mm_aesenc_si128(a.b2, b.b2), _mm_aesenc_si128(a.b3, b.b3) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128x4_common.h" */ +/*** Begin of #include "aegis128x4_common.h" ***/ +/* +** Name: aegis128x4_common.h +** Purpose: Common implementation for AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 128 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x4_common.h" ***/ + + +struct aegis128x4_implementation aegis128x4_aesni_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128x4/aegis128x4_aesni.c" ***/ + +/* #include "aegis128x4/aegis128x4_altivec.c" */ +/*** Begin of #include "aegis128x4/aegis128x4_altivec.c" ***/ +/* +** Name: aegis128x4_altivec.c +** Purpose: Implementation of AEGIS-128x4 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__ALTIVEC__) && defined(__CRYPTO__) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x4.h" */ + +/* #include "aegis128x4_altivec.h" */ +/*** Begin of #include "aegis128x4_altivec.h" ***/ +/* +** Name: aegis128x4_altivec.h +** Purpose: Header for implementation structure of AEGIS-128x4 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_ALTIVEC_H +#define AEGIS128X4_ALTIVEC_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x4_implementation aegis128x4_altivec_implementation; + +#endif /* AEGIS128X4_ALTIVEC_H */ +/*** End of #include "aegis128x4_altivec.h" ***/ + + +#include + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("altivec,crypto"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("altivec,crypto") +#endif + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + vector unsigned char b0; + vector unsigned char b1; + vector unsigned char b2; + vector unsigned char b3; +} aegis128x4_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x4_aes_block_t +#define AEGIS_BLOCKS aegis128x4_blocks +#define AEGIS_STATE _aegis128x4_state +#define AEGIS_MAC_STATE _aegis128x4_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x4_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_xor(a.b0, b.b0), vec_xor(a.b1, b.b1), + vec_xor(a.b2, b.b2), vec_xor(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_and(a.b0, b.b0), vec_and(a.b1, b.b1), + vec_and(a.b2, b.b2), vec_and(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vec_xl_be(0, a), vec_xl_be(0, a + 16), + vec_xl_be(0, a + 32), vec_xl_be(0, a + 48) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const vector unsigned char t = + (vector unsigned char) vec_revb(vec_insert(a, vec_promote((unsigned long long) (b), 1), 0)); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vec_xst_be(b.b0, 0, a); + vec_xst_be(b.b1, 0, a + 16); + vec_xst_be(b.b2, 0, a + 32); + vec_xst_be(b.b3, 0, a + 48); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_cipher_be(a.b0, b.b0), vec_cipher_be(a.b1, b.b1), + vec_cipher_be(a.b2, b.b2), vec_cipher_be(a.b3, b.b3) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(state[3], state[4]), d2); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d1); +} + +/* #include "aegis128x4_common.h" */ +/*** Begin of #include "aegis128x4_common.h" ***/ +/* +** Name: aegis128x4_common.h +** Purpose: Common implementation for AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 128 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x4_common.h" ***/ + + +struct aegis128x4_implementation aegis128x4_altivec_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128x4/aegis128x4_altivec.c" ***/ + +/* #include "aegis128x4/aegis128x4_armcrypto.c" */ +/*** Begin of #include "aegis128x4/aegis128x4_armcrypto.c" ***/ +/* +** Name: aegis128x4_armcrypto.c +** Purpose: Implementation of AEGIS-128x4 - ARM-Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* #include "../common/aeshardware.h" */ + + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x4.h" */ + +/* #include "aegis128x4_armcrypto.h" */ +/*** Begin of #include "aegis128x4_armcrypto.h" ***/ +/* +** Name: aegis128x4_armcrypto.h +** Purpose: Header for implementation structure of AEGIS-128x4 - ARM Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_ARMCRYPTO_H +#define AEGIS128X4_ARMCRYPTO_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x4_implementation aegis128x4_armcrypto_implementation; + +#endif /* AEGIS128X4_ARMCRYPTO_H */ +/*** End of #include "aegis128x4_armcrypto.h" ***/ + + +#ifndef __ARM_FEATURE_CRYPTO +# define __ARM_FEATURE_CRYPTO 1 +#endif +#ifndef __ARM_FEATURE_AES +# define __ARM_FEATURE_AES 1 +#endif + +#ifdef USE_ARM64_NEON_H +#include +#else +#include +#endif + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("neon,crypto,aes"))), \ + apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("+simd+crypto") +#endif + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + uint8x16_t b0; + uint8x16_t b1; + uint8x16_t b2; + uint8x16_t b3; +} aegis128x4_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x4_aes_block_t +#define AEGIS_BLOCKS aegis128x4_blocks +#define AEGIS_STATE _aegis128x4_state +#define AEGIS_MAC_STATE _aegis128x4_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x4_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(a.b0, b.b0), veorq_u8(a.b1, b.b1), veorq_u8(a.b2, b.b2), + veorq_u8(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vandq_u8(a.b0, b.b0), vandq_u8(a.b1, b.b1), vandq_u8(a.b2, b.b2), + vandq_u8(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vld1q_u8(a), vld1q_u8(a + 16), vld1q_u8(a + 32), vld1q_u8(a + 48) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const uint8x16_t t = vreinterpretq_u8_u64(vsetq_lane_u64((a), vmovq_n_u64(b), 1)); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vst1q_u8(a, b.b0); + vst1q_u8(a + 16, b.b1); + vst1q_u8(a + 32, b.b2); + vst1q_u8(a + 48, b.b3); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(vaesmcq_u8(vaeseq_u8((a.b0), vmovq_n_u8(0))), (b.b0)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b1), vmovq_n_u8(0))), (b.b1)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b2), vmovq_n_u8(0))), (b.b2)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b3), vmovq_n_u8(0))), (b.b3)) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(state[3], state[4]), d2); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d1); +} + +/* #include "aegis128x4_common.h" */ +/*** Begin of #include "aegis128x4_common.h" ***/ +/* +** Name: aegis128x4_common.h +** Purpose: Common implementation for AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 128 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x4_common.h" ***/ + + +struct aegis128x4_implementation aegis128x4_armcrypto_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis128x4/aegis128x4_armcrypto.c" ***/ + +/* #include "aegis128x4/aegis128x4_avx2.c" */ +/*** Begin of #include "aegis128x4/aegis128x4_avx2.c" ***/ +/* +** Name: aegis128x4_avx2.c +** Purpose: Implementation of AEGIS-128x4 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x4.h" */ + +/* #include "aegis128x4_avx2.h" */ +/*** Begin of #include "aegis128x4_avx2.h" ***/ +/* +** Name: aegis128x4_avx2.h +** Purpose: Header for implementation structure of AEGIS-128x4 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_AVX2_H +#define AEGIS128X4_AVX2_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +#ifdef HAVE_VAESINTRIN_H +extern struct aegis128x4_implementation aegis128x4_avx2_implementation; +#endif + +#endif /* AEGIS128X4_AVX2_H */ +/*** End of #include "aegis128x4_avx2.h" ***/ + + +#ifdef HAVE_VAESINTRIN_H + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("vaes,avx2"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("vaes,avx2") +#endif + +#include + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + __m256i b0; + __m256i b1; +} aegis128x4_avx2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x4_avx2_aes_block_t +#define AEGIS_BLOCKS aegis128x4_avx2_blocks +#define AEGIS_STATE _aegis128x4_avx2_state +#define AEGIS_MAC_STATE _aegis128x4_avx2_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x4_avx2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_xor_si256(a.b0, b.b0), _mm256_xor_si256(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_and_si256(a.b0, b.b0), _mm256_and_si256(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_loadu_si256((const __m256i *) (const void *) a), + _mm256_loadu_si256((const __m256i *) (const void *) (a + 32)) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const __m256i t = _mm256_broadcastsi128_si256(_mm_set_epi64x((long long) a, (long long) b)); + return (AEGIS_AES_BLOCK_T) { t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm256_storeu_si256((__m256i *) (void *) a, b.b0); + _mm256_storeu_si256((__m256i *) (void *) (a + 32), b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_aesenc_epi128(a.b0, b.b0), _mm256_aesenc_epi128(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128x4_common.h" */ +/*** Begin of #include "aegis128x4_common.h" ***/ +/* +** Name: aegis128x4_common.h +** Purpose: Common implementation for AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 128 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x4_common.h" ***/ + + +struct aegis128x4_implementation aegis128x4_avx2_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif /* HAVE_VAESINTRIN_H */ + +#endif +/*** End of #include "aegis128x4/aegis128x4_avx2.c" ***/ + +/* #include "aegis128x4/aegis128x4_avx512.c" */ +/*** Begin of #include "aegis128x4/aegis128x4_avx512.c" ***/ +/* +** Name: aegis128x4_avx512.c +** Purpose: Implementation of AEGIS-128x4 - AES-NI AVX512 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis128x4.h" */ + +/* #include "aegis128x4_avx512.h" */ +/*** Begin of #include "aegis128x4_avx512.h" ***/ +/* +** Name: aegis128x4_avx512.h +** Purpose: Header for implementation structure of AEGIS-128x4 - AES-NI AVX512 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_AVX512_H +#define AEGIS128X4_AVX512_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +#ifdef HAVE_VAESINTRIN_H +extern struct aegis128x4_implementation aegis128x4_avx512_implementation; +#endif + +#endif /* AEGIS128X4_AVX512_H */ +/*** End of #include "aegis128x4_avx512.h" ***/ + + +#ifdef HAVE_VAESINTRIN_H + +#ifdef __clang__ +# if __clang_major__ >= 18 +# pragma clang attribute push(__attribute__((target("vaes,avx512f,evex512"))), \ + apply_to = function) +# else +# pragma clang attribute push(__attribute__((target("vaes,avx512f"))), \ + apply_to = function) +# endif +#elif defined(__GNUC__) +# pragma GCC target("vaes,avx512f") +#endif + +#include + +#define AES_BLOCK_LENGTH 64 + +typedef __m512i aegis128x4_avx512_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x4_avx512_aes_block_t +#define AEGIS_BLOCKS aegis128x4_avx512_blocks +#define AEGIS_STATE _aegis128x4_avx512_state +#define AEGIS_MAC_STATE _aegis128x4_avx512_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x4_avx512_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm512_xor_si512(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm512_and_si512(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return _mm512_loadu_si512((const AEGIS_AES_BLOCK_T *) (const void *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return _mm512_broadcast_i32x4(_mm_set_epi64x(a, b)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm512_storeu_si512((AEGIS_AES_BLOCK_T *) (void *) a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm512_aesenc_epi128(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128x4_common.h" */ +/*** Begin of #include "aegis128x4_common.h" ***/ +/* +** Name: aegis128x4_common.h +** Purpose: Common implementation for AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 128 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x4_common.h" ***/ + + +struct aegis128x4_implementation aegis128x4_avx512_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif /* HAVE_VAESINTRIN_H */ + +#endif +/*** End of #include "aegis128x4/aegis128x4_avx512.c" ***/ + +/* #include "aegis128x4/aegis128x4_soft.c" */ +/*** Begin of #include "aegis128x4/aegis128x4_soft.c" ***/ +/* +** Name: aegis128x4_soft.c +** Purpose: Implementation of AEGIS-128x4 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + + +/* #include "../common/softaes.h" */ + +/* #include "aegis128x4.h" */ + +/* #include "aegis128x4_soft.h" */ +/*** Begin of #include "aegis128x4_soft.h" ***/ +/* +** Name: aegis128x4_soft.h +** Purpose: Header for implementation structure of AEGIS-128x4 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS128X4_SOFT_H +#define AEGIS128X4_SOFT_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis128x4_implementation aegis128x4_soft_implementation; + +#endif /* AEGIS128X4_SOFT_H */ +/*** End of #include "aegis128x4_soft.h" ***/ + + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + SoftAesBlock b0; + SoftAesBlock b1; + SoftAesBlock b2; + SoftAesBlock b3; +} aegis128x4_soft_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis128x4_soft_aes_block_t +#define AEGIS_BLOCKS aegis128x4_soft_blocks +#define AEGIS_STATE _aegis128x4_soft_state +#define AEGIS_MAC_STATE _aegis128x4_soft_mac_state + +#define AEGIS_FUNC_PREFIX aegis128x4_soft_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_xor(a.b0, b.b0), softaes_block_xor(a.b1, b.b1), + softaes_block_xor(a.b2, b.b2), softaes_block_xor(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_and(a.b0, b.b0), softaes_block_and(a.b1, b.b1), + softaes_block_and(a.b2, b.b2), softaes_block_and(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_load(a), softaes_block_load(a + 16), + softaes_block_load(a + 32), softaes_block_load(a + 48) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const SoftAesBlock t = softaes_block_load64x2(a, b); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + softaes_block_store(a, b.b0); + softaes_block_store(a + 16, b.b1); + softaes_block_store(a + 32, b.b2); + softaes_block_store(a + 48, b.b3); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_encrypt(a.b0, b.b0), softaes_block_encrypt(a.b1, b.b1), + softaes_block_encrypt(a.b2, b.b2), softaes_block_encrypt(a.b3, b.b3) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d1, const AEGIS_AES_BLOCK_T d2) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[7]; + state[7] = AEGIS_AES_ENC(state[6], state[7]); + state[6] = AEGIS_AES_ENC(state[5], state[6]); + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_ENC(tmp, state[0]); + + state[0] = AEGIS_AES_BLOCK_XOR(state[0], d1); + state[4] = AEGIS_AES_BLOCK_XOR(state[4], d2); +} + +/* #include "aegis128x4_common.h" */ +/*** Begin of #include "aegis128x4_common.h" ***/ +/* +** Name: aegis128x4_common.h +** Purpose: Common implementation for AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 128 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[8]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k; + AEGIS_AES_BLOCK_T n; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n = AEGIS_AES_BLOCK_LOAD(tmp); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = AEGIS_AES_BLOCK_XOR(k, n); + state[1] = c1; + state[2] = c0; + state[3] = c1; + state[4] = AEGIS_AES_BLOCK_XOR(k, n); + state[5] = AEGIS_AES_BLOCK_XOR(k, c0); + state[6] = AEGIS_AES_BLOCK_XOR(k, c1); + state[7] = AEGIS_AES_BLOCK_XOR(k, c0); + for (i = 0; i < 10; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[7] = AEGIS_AES_BLOCK_XOR(state[7], context); + AEGIS_update(state, n, k); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + AEGIS_AES_BLOCK_T tmp0, tmp1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + tmp0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, state[1]); + tmp1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, state[2]); + tmp0 = AEGIS_AES_BLOCK_XOR(tmp0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + tmp1 = AEGIS_AES_BLOCK_XOR(tmp1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, tmp0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, tmp1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(src); + msg1 = AEGIS_AES_BLOCK_LOAD(src + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(dst, msg0); + AEGIS_AES_BLOCK_STORE(dst + AES_BLOCK_LENGTH, msg1); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg0, msg1; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[6]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, state[1]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[5]); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, state[2]); + msg0 = AEGIS_AES_BLOCK_XOR(msg0, AEGIS_AES_BLOCK_AND(state[2], state[3])); + msg1 = AEGIS_AES_BLOCK_XOR(msg1, AEGIS_AES_BLOCK_AND(state[6], state[7])); + AEGIS_AES_BLOCK_STORE(pad, msg0); + AEGIS_AES_BLOCK_STORE(pad + AES_BLOCK_LENGTH, msg1); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg0 = AEGIS_AES_BLOCK_LOAD(pad); + msg1 = AEGIS_AES_BLOCK_LOAD(pad + AES_BLOCK_LENGTH); + + AEGIS_update(state, msg0, msg1); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + for (i = 0; i < d / 2; i++) { + memcpy(r, t + i * 32, 16); + memcpy(r + AEGIS_RATE / 2, t + i * 32 + 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[6], AEGIS_AES_BLOCK_XOR(state[5], state[4])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + memcpy(r + AEGIS_RATE / 2, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[2]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[3], state[2]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[7], state[6]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[5], state[4])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis128x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis128x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1, msg2, msg3; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + msg2 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 2); + msg3 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 3); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 4 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0, msg1); + AEGIS_update(blocks, msg2, msg3); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis128x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis128x4_common.h" ***/ + + +struct aegis128x4_implementation aegis128x4_soft_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + +/*** End of #include "aegis128x4/aegis128x4_soft.c" ***/ + +/* #include "aegis128x4/aegis128x4.c" */ +/*** Begin of #include "aegis128x4/aegis128x4.c" ***/ +/* +** Name: aegis128x4.c +** Purpose: Implementation of AEGIS-128x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + +/* #include "../include/aegis128x4.h" */ + + +#if 0 +/* #include "aegis128x4_aesni.h" */ + +/* #include "aegis128x4_altivec.h" */ + +/* #include "aegis128x4_armcrypto.h" */ + +/* #include "aegis128x4_avx2.h" */ + +/* #include "aegis128x4_avx512.h" */ + +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NONE +/* #include "aegis128x4_soft.h" */ + +static const aegis128x4_implementation* implementation_128x4 = &aegis128x4_soft_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON +static const aegis128x4_implementation* implementation_128x4 = &aegis128x4_armcrypto_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +static const aegis128x4_implementation* implementation_128x4 = &aegis128x4_aesni_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC +static const aegis128x4_implementation* implementation_128x4 = &aegis128x4_altivec_implementation; +#else +#error "Unsupported architecture" +#endif + +AEGIS_API +size_t +aegis128x4_keybytes(void) +{ + return aegis128x4_KEYBYTES; +} + +AEGIS_API +size_t +aegis128x4_npubbytes(void) +{ + return aegis128x4_NPUBBYTES; +} + +AEGIS_API +size_t +aegis128x4_abytes_min(void) +{ + return aegis128x4_ABYTES_MIN; +} + +AEGIS_API +size_t +aegis128x4_abytes_max(void) +{ + return aegis128x4_ABYTES_MAX; +} + +AEGIS_API +size_t +aegis128x4_tailbytes_max(void) +{ + return aegis128x4_TAILBYTES_MAX; +} + +AEGIS_API +int +aegis128x4_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x4->encrypt_detached(c, mac, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x4_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x4->decrypt_detached(m, c, clen, mac, maclen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x4_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + return aegis128x4_encrypt_detached(c, c + mlen, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x4_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + int ret = -1; + + if (clen >= maclen) { + ret = aegis128x4_decrypt_detached(m, c, clen - maclen, c + clen - maclen, maclen, ad, adlen, + npub, k); + } + return ret; +} + +#ifndef AEGIS_OMIT_INCREMENTAL + +AEGIS_API +void +aegis128x4_state_init(aegis128x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + memset(st_, 0, sizeof *st_); + implementation_128x4->state_init(st_, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis128x4_state_encrypt_update(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + return implementation_128x4->state_encrypt_update(st_, c, clen_max, written, m, mlen); +} + +AEGIS_API +int +aegis128x4_state_encrypt_detached_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x4->state_encrypt_detached_final(st_, c, clen_max, written, mac, maclen); +} + +AEGIS_API +int +aegis128x4_state_encrypt_final(aegis128x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x4->state_encrypt_final(st_, c, clen_max, written, maclen); +} + +AEGIS_API +int +aegis128x4_state_decrypt_detached_update(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) +{ + return implementation_128x4->state_decrypt_detached_update(st_, m, mlen_max, written, c, clen); +} + +AEGIS_API +int +aegis128x4_state_decrypt_detached_final(aegis128x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x4->state_decrypt_detached_final(st_, m, mlen_max, written, mac, maclen); +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +AEGIS_API +void +aegis128x4_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + implementation_128x4->stream(out, len, npub, k); +} + +AEGIS_API +void +aegis128x4_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_128x4->encrypt_unauthenticated(c, m, mlen, npub, k); +} + +AEGIS_API +void +aegis128x4_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_128x4->decrypt_unauthenticated(m, c, clen, npub, k); +} + +#ifndef AEGIS_OMIT_MAC_API + +AEGIS_API +void +aegis128x4_mac_init(aegis128x4_mac_state *st_, const uint8_t *k, const uint8_t *npub) +{ + implementation_128x4->state_mac_init(st_, npub, k); +} + +AEGIS_API +int +aegis128x4_mac_update(aegis128x4_mac_state *st_, const uint8_t *m, size_t mlen) +{ + return implementation_128x4->state_mac_update(st_, m, mlen); +} + +AEGIS_API +int +aegis128x4_mac_final(aegis128x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_128x4->state_mac_final(st_, mac, maclen); +} + +AEGIS_API +int +aegis128x4_mac_verify(aegis128x4_mac_state *st_, const uint8_t *mac, size_t maclen) +{ + uint8_t expected_mac[32]; + + switch (maclen) { + case 16: + implementation_128x4->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_16(expected_mac, mac); + case 32: + implementation_128x4->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_32(expected_mac, mac); + default: + errno = EINVAL; + return -1; + } +} + +AEGIS_API +void +aegis128x4_mac_reset(aegis128x4_mac_state *st_) +{ + implementation_128x4->state_mac_reset(st_); +} + +AEGIS_API +void +aegis128x4_mac_state_clone(aegis128x4_mac_state *dst, const aegis128x4_mac_state *src) +{ + implementation_128x4->state_mac_clone(dst, src); +} + +#endif /* AEGIS_OMIT_MAC_API */ + +AEGIS_PRIVATE +int +aegis128x4_pick_best_implementation(void) +{ + implementation_128x4 = &aegis128x4_soft_implementation; + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + if (aegis_runtime_has_armcrypto()) { + implementation_128x4 = &aegis128x4_armcrypto_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +# ifdef HAVE_VAESINTRIN_H + if (aegis_runtime_has_vaes() && aegis_runtime_has_avx512f()) { + implementation_128x4 = &aegis128x4_avx512_implementation; + return 0; + } + if (aegis_runtime_has_vaes() && aegis_runtime_has_avx2()) { + implementation_128x4 = &aegis128x4_avx2_implementation; + return 0; + } +# endif + if (aegis_runtime_has_aesni() && aegis_runtime_has_avx()) { + implementation_128x4 = &aegis128x4_aesni_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC + if (aegis_runtime_has_altivec()) { + implementation_128x4 = &aegis128x4_altivec_implementation; + return 0; + } +#endif + + return 0; /* LCOV_EXCL_LINE */ +} +/*** End of #include "aegis128x4/aegis128x4.c" ***/ + + +/* AEGIS 256 */ +/* #include "aegis256/implementations.h" */ +/*** Begin of #include "aegis256/implementations.h" ***/ +/* +** Name: implementations.h +** Purpose: Header for implementation structure of AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256_IMPLEMENTATIONS_H +#define AEGIS256_IMPLEMENTATIONS_H + +#include +#include + +/* #include "aegis256.h" */ + + +typedef struct aegis256_implementation { + int (*encrypt_detached)(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k); + int (*decrypt_detached)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + void (*stream)(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + void (*encrypt_unauthenticated)(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k); + void (*decrypt_unauthenticated)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k); +#ifndef AEGIS_OMIT_INCREMENTAL + void (*state_init)(aegis256_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + int (*state_encrypt_update)(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen); + int (*state_encrypt_detached_final)(aegis256_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + int (*state_encrypt_final)(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen); + int (*state_decrypt_detached_update)(aegis256_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen); + int (*state_decrypt_detached_final)(aegis256_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen); +#endif /* AEGIS_OMIT_INCREMENTAL */ +#ifndef AEGIS_OMIT_MAC_API + void (*state_mac_init)(aegis256_mac_state *st_, const uint8_t *npub, const uint8_t *k); + int (*state_mac_update)(aegis256_mac_state *st_, const uint8_t *ad, size_t adlen); + int (*state_mac_final)(aegis256_mac_state *st_, uint8_t *mac, size_t maclen); + void (*state_mac_reset)(aegis256_mac_state *st); + void (*state_mac_clone)(aegis256_mac_state *dst, const aegis256_mac_state *src); +#endif /* AEGIS_OMIT_MAC_API */ +} aegis256_implementation; + +#endif /* AEGIS256_IMPLEMENTATIONS_H */ +/*** End of #include "aegis256/implementations.h" ***/ + +/* #include "aegis256/aegis256_aesni.c" */ +/*** Begin of #include "aegis256/aegis256_aesni.c" ***/ +/* +** Name: aegis256_aesni.c +** Purpose: Implementation of AEGIS-256 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256.h" */ + +/* #include "aegis256_aesni.h" */ +/*** Begin of #include "aegis256_aesni.h" ***/ +/* +** Name: aegis256_aesni.h +** Purpose: Header for implementation structure of AEGIS-256 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256_AESNI_H +#define AEGIS256_AESNI_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256_implementation aegis256_aesni_implementation; + +#endif /* AEGIS256_AESNI_H */ +/*** End of #include "aegis256_aesni.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("aes,avx"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("aes,avx") +#endif + +#include +#include + +#define AES_BLOCK_LENGTH 16 + +typedef __m128i aegis256_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256_aes_block_t +#define AEGIS_BLOCKS aegis256_blocks +#define AEGIS_STATE _aegis256_state +#define AEGIS_MAC_STATE _aegis256_mac_state + +#define AEGIS_FUNC_PREFIX aegis256_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm_xor_si128(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm_and_si128(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return _mm_loadu_si128((const AEGIS_AES_BLOCK_T *) (const void *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return _mm_set_epi64x((long long) a, (long long) b); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm_storeu_si128((AEGIS_AES_BLOCK_T *) (void *) a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm_aesenc_si128(a, b); +} + + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256_common.h" */ +/*** Begin of #include "aegis256_common.h" ***/ +/* +** Name: aegis256_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 16 +#define AEGIS_ALIGNMENT 16 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + const AEGIS_AES_BLOCK_T k0 = AEGIS_AES_BLOCK_LOAD(key); + const AEGIS_AES_BLOCK_T k1 = AEGIS_AES_BLOCK_LOAD(key + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T n0 = AEGIS_AES_BLOCK_LOAD(nonce); + const AEGIS_AES_BLOCK_T n1 = AEGIS_AES_BLOCK_LOAD(nonce + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + const AEGIS_AES_BLOCK_T k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + int i; + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + AEGIS_update(state, k0); + AEGIS_update(state, k1); + AEGIS_update(state, k0_n0); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[2], state[1]), state[0]); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[5], state[4]), state[3]); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memset(st->buf, 0, sizeof st->buf); + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256_mac_state *dst, const aegis256_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256_common.h" ***/ + + +struct aegis256_implementation aegis256_aesni_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256/aegis256_aesni.c" ***/ + +/* #include "aegis256/aegis256_altivec.c" */ +/*** Begin of #include "aegis256/aegis256_altivec.c" ***/ +/* +** Name: aegis256_altivec.c +** Purpose: Implementation of AEGIS-256 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__ALTIVEC__) && defined(__CRYPTO__) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256.h" */ + +/* #include "aegis256_altivec.h" */ +/*** Begin of #include "aegis256_altivec.h" ***/ +/* +** Name: aegis256_altivec.h +** Purpose: Header for implementation structure of AEGIS-256 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256_ALTIVEC_H +#define AEGIS256_ALTIVEC_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256_implementation aegis256_altivec_implementation; + +#endif /* AEGIS256_ALTIVEC_H */ +/*** End of #include "aegis256_altivec.h" ***/ + + +#include + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("altivec,crypto"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("altivec,crypto") +#endif + +#define AES_BLOCK_LENGTH 16 + +typedef vector unsigned char aegis256_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256_aes_block_t +#define AEGIS_BLOCKS aegis256_blocks +#define AEGIS_STATE _aegis256_state +#define AEGIS_MAC_STATE _aegis256_mac_state + +#define AEGIS_FUNC_PREFIX aegis256_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return vec_xor(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return vec_and(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return vec_xl_be(0, (const unsigned char *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return (AEGIS_AES_BLOCK_T) vec_revb(vec_insert(a, vec_promote((unsigned long long) b, 1), 0)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vec_xst_be(b, 0, (unsigned char *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) vec_cipher_be(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256_common.h" */ +/*** Begin of #include "aegis256_common.h" ***/ +/* +** Name: aegis256_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 16 +#define AEGIS_ALIGNMENT 16 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + const AEGIS_AES_BLOCK_T k0 = AEGIS_AES_BLOCK_LOAD(key); + const AEGIS_AES_BLOCK_T k1 = AEGIS_AES_BLOCK_LOAD(key + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T n0 = AEGIS_AES_BLOCK_LOAD(nonce); + const AEGIS_AES_BLOCK_T n1 = AEGIS_AES_BLOCK_LOAD(nonce + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + const AEGIS_AES_BLOCK_T k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + int i; + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + AEGIS_update(state, k0); + AEGIS_update(state, k1); + AEGIS_update(state, k0_n0); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[2], state[1]), state[0]); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[5], state[4]), state[3]); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memset(st->buf, 0, sizeof st->buf); + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256_mac_state *dst, const aegis256_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256_common.h" ***/ + + +struct aegis256_implementation aegis256_altivec_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256/aegis256_altivec.c" ***/ + +/* #include "aegis256/aegis256_armcrypto.c" */ +/*** Begin of #include "aegis256/aegis256_armcrypto.c" ***/ +/* +** Name: aegis256_armcrypto.c +** Purpose: Implementation of AEGIS-256 - ARM-Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* #include "../common/aeshardware.h" */ + + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256.h" */ + +/* #include "aegis256_armcrypto.h" */ +/*** Begin of #include "aegis256_armcrypto.h" ***/ +/* +** Name: aegis256_armcrypto.h +** Purpose: Header for implementation structure of AEGIS-256 - ARM Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256_ARMCRYPTO_H +#define AEGIS256_ARMCRYPTO_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256_implementation aegis256_armcrypto_implementation; + +#endif /* AEGIS256_ARMCRYPTO_H */ +/*** End of #include "aegis256_armcrypto.h" ***/ + + +#ifndef __ARM_FEATURE_CRYPTO +# define __ARM_FEATURE_CRYPTO 1 +#endif +#ifndef __ARM_FEATURE_AES +# define __ARM_FEATURE_AES 1 +#endif + +#ifdef USE_ARM64_NEON_H +#include +#else +#include +#endif + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("neon,crypto,aes"))), \ + apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("+simd+crypto") +#endif + +#define AES_BLOCK_LENGTH 16 + +typedef uint8x16_t aegis256_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256_aes_block_t +#define AEGIS_BLOCKS aegis256_blocks +#define AEGIS_STATE _aegis256_state +#define AEGIS_MAC_STATE _aegis256_mac_state + +#define AEGIS_FUNC_PREFIX aegis256_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return veorq_u8(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return vandq_u8(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return vld1q_u8(a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return vreinterpretq_u8_u64(vsetq_lane_u64(a, vmovq_n_u64(b), 1)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vst1q_u8(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return veorq_u8(vaesmcq_u8(vaeseq_u8(a, vmovq_n_u8(0))), b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256_common.h" */ +/*** Begin of #include "aegis256_common.h" ***/ +/* +** Name: aegis256_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 16 +#define AEGIS_ALIGNMENT 16 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + const AEGIS_AES_BLOCK_T k0 = AEGIS_AES_BLOCK_LOAD(key); + const AEGIS_AES_BLOCK_T k1 = AEGIS_AES_BLOCK_LOAD(key + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T n0 = AEGIS_AES_BLOCK_LOAD(nonce); + const AEGIS_AES_BLOCK_T n1 = AEGIS_AES_BLOCK_LOAD(nonce + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + const AEGIS_AES_BLOCK_T k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + int i; + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + AEGIS_update(state, k0); + AEGIS_update(state, k1); + AEGIS_update(state, k0_n0); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[2], state[1]), state[0]); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[5], state[4]), state[3]); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memset(st->buf, 0, sizeof st->buf); + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256_mac_state *dst, const aegis256_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256_common.h" ***/ + + +struct aegis256_implementation aegis256_armcrypto_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256/aegis256_armcrypto.c" ***/ + +/* #include "aegis256/aegis256_soft.c" */ +/*** Begin of #include "aegis256/aegis256_soft.c" ***/ +/* +** Name: aegis256_soft.c +** Purpose: Implementation of AEGIS-256 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + + +/* #include "../common/softaes.h" */ + +/* #include "aegis256.h" */ + +/* #include "aegis256_soft.h" */ +/*** Begin of #include "aegis256_soft.h" ***/ +/* +** Name: aegis256_soft.h +** Purpose: Header for implementation structure of AEGIS-256 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256_SOFT_H +#define AEGIS256_SOFT_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256_implementation aegis256_soft_implementation; + +#endif /* AEGIS256_SOFT_H */ +/*** End of #include "aegis256_soft.h" ***/ + + +#define AES_BLOCK_LENGTH 16 + +typedef SoftAesBlock aegis256_soft_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256_soft_aes_block_t +#define AEGIS_BLOCKS aegis256_soft_blocks +#define AEGIS_STATE _aegis256_soft_state +#define AEGIS_MAC_STATE _aegis256_soft_mac_state + +#define AEGIS_FUNC_PREFIX aegis256_soft_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return softaes_block_xor(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return softaes_block_and(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return softaes_block_load(a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return softaes_block_load64x2(a, b); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + softaes_block_store(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return softaes_block_encrypt(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256_common.h" */ +/*** Begin of #include "aegis256_common.h" ***/ +/* +** Name: aegis256_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 16 +#define AEGIS_ALIGNMENT 16 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c0_[AES_BLOCK_LENGTH] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, + 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62 }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) + const uint8_t c1_[AES_BLOCK_LENGTH] = { 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, + 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + const AEGIS_AES_BLOCK_T k0 = AEGIS_AES_BLOCK_LOAD(key); + const AEGIS_AES_BLOCK_T k1 = AEGIS_AES_BLOCK_LOAD(key + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T n0 = AEGIS_AES_BLOCK_LOAD(nonce); + const AEGIS_AES_BLOCK_T n1 = AEGIS_AES_BLOCK_LOAD(nonce + AES_BLOCK_LENGTH); + const AEGIS_AES_BLOCK_T k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + const AEGIS_AES_BLOCK_T k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + int i; + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + AEGIS_update(state, k0); + AEGIS_update(state, k1); + AEGIS_update(state, k0_n0); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac, tmp); + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[2], state[1]), state[0]); + AEGIS_AES_BLOCK_STORE(mac, tmp); + tmp = AEGIS_AES_BLOCK_XOR(AEGIS_AES_BLOCK_XOR(state[5], state[4]), state[3]); + AEGIS_AES_BLOCK_STORE(mac + 16, tmp); + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memset(st->buf, 0, sizeof st->buf); + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac(mac, maclen, st->adlen, maclen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256_mac_state *dst, const aegis256_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256_common.h" ***/ + + +struct aegis256_implementation aegis256_soft_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + +/*** End of #include "aegis256/aegis256_soft.c" ***/ + +/* #include "aegis256/aegis256.c" */ +/*** Begin of #include "aegis256/aegis256.c" ***/ +/* +** Name: aegis256.c +** Purpose: Implementation of AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + +/* #include "aegis256.h" */ + +#if 0 +/* #include "aegis256_aesni.h" */ + +/* #include "aegis256_altivec.h" */ + +/* #include "aegis256_armcrypto.h" */ + +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NONE +/* #include "aegis256_soft.h" */ + +static const aegis256_implementation *implementation_256 = &aegis256_soft_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON +static const aegis256_implementation *implementation_256 = &aegis256_armcrypto_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +static const aegis256_implementation *implementation_256 = &aegis256_aesni_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC +static const aegis256_implementation *implementation_256 = &aegis256_altivec_implementation; +#else +#error "Unsupported architecture" +#endif + +AEGIS_API +size_t +aegis256_keybytes(void) +{ + return aegis256_KEYBYTES; +} + +AEGIS_API +size_t +aegis256_npubbytes(void) +{ + return aegis256_NPUBBYTES; +} + +AEGIS_API +size_t +aegis256_abytes_min(void) +{ + return aegis256_ABYTES_MIN; +} + +AEGIS_API +size_t +aegis256_abytes_max(void) +{ + return aegis256_ABYTES_MAX; +} + +AEGIS_API +size_t +aegis256_tailbytes_max(void) +{ + return aegis256_TAILBYTES_MAX; +} + +AEGIS_API +int +aegis256_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256->encrypt_detached(c, mac, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256->decrypt_detached(m, c, clen, mac, maclen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + return aegis256_encrypt_detached(c, c + mlen, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + int ret = -1; + + if (clen >= maclen) { + ret = aegis256_decrypt_detached(m, c, clen - maclen, c + clen - maclen, maclen, ad, adlen, + npub, k); + } + return ret; +} + +#ifndef AEGIS_OMIT_INCREMENTAL + +AEGIS_API +void +aegis256_state_init(aegis256_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + memset(st_, 0, sizeof *st_); + implementation_256->state_init(st_, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256_state_encrypt_update(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + return implementation_256->state_encrypt_update(st_, c, clen_max, written, m, mlen); +} + +AEGIS_API +int +aegis256_state_encrypt_detached_final(aegis256_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256->state_encrypt_detached_final(st_, c, clen_max, written, mac, maclen); +} + +AEGIS_API +int +aegis256_state_encrypt_final(aegis256_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256->state_encrypt_final(st_, c, clen_max, written, maclen); +} + +AEGIS_API +int +aegis256_state_decrypt_detached_update(aegis256_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) +{ + return implementation_256->state_decrypt_detached_update(st_, m, mlen_max, written, c, clen); +} + +AEGIS_API +int +aegis256_state_decrypt_detached_final(aegis256_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256->state_decrypt_detached_final(st_, m, mlen_max, written, mac, maclen); +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +AEGIS_API +void +aegis256_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + implementation_256->stream(out, len, npub, k); +} + +AEGIS_API +void +aegis256_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_256->encrypt_unauthenticated(c, m, mlen, npub, k); +} + +AEGIS_API +void +aegis256_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_256->decrypt_unauthenticated(m, c, clen, npub, k); +} + +#ifndef AEGIS_OMIT_MAC_API + +AEGIS_API +void +aegis256_mac_init(aegis256_mac_state *st_, const uint8_t *k, const uint8_t *npub) +{ + implementation_256->state_mac_init(st_, npub, k); +} + +AEGIS_API +int +aegis256_mac_update(aegis256_mac_state *st_, const uint8_t *m, size_t mlen) +{ + return implementation_256->state_mac_update(st_, m, mlen); +} + +AEGIS_API +int +aegis256_mac_final(aegis256_mac_state *st_, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256->state_mac_final(st_, mac, maclen); +} + +AEGIS_API +int +aegis256_mac_verify(aegis256_mac_state *st_, const uint8_t *mac, size_t maclen) +{ + uint8_t expected_mac[32]; + + switch (maclen) { + case 16: + implementation_256->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_16(expected_mac, mac); + case 32: + implementation_256->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_32(expected_mac, mac); + default: + errno = EINVAL; + return -1; + } +} + +AEGIS_API +void +aegis256_mac_reset(aegis256_mac_state *st_) +{ + implementation_256->state_mac_reset(st_); +} + +AEGIS_API +void +aegis256_mac_state_clone(aegis256_mac_state *dst, const aegis256_mac_state *src) +{ + implementation_256->state_mac_clone(dst, src); +} + +#endif /* AEGIS_OMIT_MAC_API */ + +AEGIS_PRIVATE +int +aegis256_pick_best_implementation(void) +{ + implementation_256 = &aegis256_soft_implementation; + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + if (aegis_runtime_has_armcrypto()) { + implementation_256 = &aegis256_armcrypto_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI + if (aegis_runtime_has_aesni() && aegis_runtime_has_avx()) { + implementation_256 = &aegis256_aesni_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC + if (aegis_runtime_has_altivec()) { + implementation_256 = &aegis256_altivec_implementation; + return 0; + } +#endif + + return 0; /* LCOV_EXCL_LINE */ +} +/*** End of #include "aegis256/aegis256.c" ***/ + + +/* AEGIS 256 x2 */ +/* #include "aegis256x2/implementations.h" */ +/*** Begin of #include "aegis256x2/implementations.h" ***/ +/* +** Name: implementations.h +** Purpose: Header for implementation structure of AEGIS-256x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X2_IMPLEMENTATIONS_H +#define AEGIS256X2_IMPLEMENTATIONS_H + +#include +#include + +/* #include "aegis256x2.h" */ + + +typedef struct aegis256x2_implementation { + int (*encrypt_detached)(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k); + int (*decrypt_detached)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + void (*stream)(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + void (*encrypt_unauthenticated)(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k); + void (*decrypt_unauthenticated)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k); +#ifndef AEGIS_OMIT_INCREMENTAL + void (*state_init)(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + int (*state_encrypt_update)(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen); + int (*state_encrypt_detached_final)(aegis256x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + int (*state_encrypt_final)(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen); + int (*state_decrypt_detached_update)(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen); + int (*state_decrypt_detached_final)(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen); +#endif /* AEGIS_OMIT_INCREMENTAL */ +#ifndef AEGIS_OMIT_MAC_API + void (*state_mac_init)(aegis256x2_mac_state *st_, const uint8_t *npub, const uint8_t *k); + int (*state_mac_update)(aegis256x2_mac_state *st_, const uint8_t *ad, size_t adlen); + int (*state_mac_final)(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen); + void (*state_mac_reset)(aegis256x2_mac_state *st); + void (*state_mac_clone)(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src); +#endif /* AEGIS_OMIT_MAC_API */ +} aegis256x2_implementation; + +#endif /* AEGIS256X2_IMPLEMENTATIONS_H */ +/*** End of #include "aegis256x2/implementations.h" ***/ + +/* #include "aegis256x2/aegis256x2_aesni.c" */ +/*** Begin of #include "aegis256x2/aegis256x2_aesni.c" ***/ +/* +** Name: aegis256x2_aesni.c +** Purpose: Implementation of AEGIS-256x2 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x2.h" */ + +/* #include "aegis256x2_aesni.h" */ +/*** Begin of #include "aegis256x2_aesni.h" ***/ +/* +** Name: aegis256x2_aesni.h +** Purpose: Header for implementation structure of AEGIS-256x2 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X2_AESNI_H +#define AEGIS256X2_AESNI_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x2_implementation aegis256x2_aesni_implementation; + +#endif /* AEGIS256X2_AESNI_H */ +/*** End of #include "aegis256x2_aesni.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("aes,avx"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("aes,avx") +#endif + +#include +#include + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + __m128i b0; + __m128i b1; +} aegis256x2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x2_aes_block_t +#define AEGIS_BLOCKS aegis256x2_blocks +#define AEGIS_STATE _aegis256x2_state +#define AEGIS_MAC_STATE _aegis256x2_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_xor_si128(a.b0, b.b0), _mm_xor_si128(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_and_si128(a.b0, b.b0), _mm_and_si128(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { _mm_loadu_si128((const __m128i *) (const void *) a), + _mm_loadu_si128((const __m128i *) (const void *) (a + 16)) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const __m128i t = _mm_set_epi64x((long long) a, (long long) b); + return (AEGIS_AES_BLOCK_T) { t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm_storeu_si128((__m128i *) (void *) a, b.b0); + _mm_storeu_si128((__m128i *) (void *) (a + 16), b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_aesenc_si128(a.b0, b.b0), _mm_aesenc_si128(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x2_common.h" */ +/*** Begin of #include "aegis256x2_common.h" ***/ +/* +** Name: aegis256x2_common.h +** Purpose: Common implementation for AEGIS-256x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x2_common.h" ***/ + + +struct aegis256x2_implementation aegis256x2_aesni_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256x2/aegis256x2_aesni.c" ***/ + +/* #include "aegis256x2/aegis256x2_altivec.c" */ +/*** Begin of #include "aegis256x2/aegis256x2_altivec.c" ***/ +/* +** Name: aegis256x2_altivec.c +** Purpose: Implementation of AEGIS-256x2 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__ALTIVEC__) && defined(__CRYPTO__) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x2.h" */ + +/* #include "aegis256x2_altivec.h" */ +/*** Begin of #include "aegis256x2_altivec.h" ***/ +/* +** Name: aegis256x2_altivec.h +** Purpose: Header for implementation structure of AEGIS-256x2 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X2_ALTIVEC_H +#define AEGIS256X2_ALTIVEC_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x2_implementation aegis256x2_altivec_implementation; + +#endif /* AEGIS256X2_ALTIVEC_H */ +/*** End of #include "aegis256x2_altivec.h" ***/ + + +#include + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("altivec,crypto"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("altivec,crypto") +#endif + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + vector unsigned char b0; + vector unsigned char b1; +} aegis256x2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x2_aes_block_t +#define AEGIS_BLOCKS aegis256x2_blocks +#define AEGIS_STATE _aegis256x2_state +#define AEGIS_MAC_STATE _aegis256x2_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_xor(a.b0, b.b0), vec_xor(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_and(a.b0, b.b0), vec_and(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vec_xl_be(0, a), vec_xl_be(0, a + 16) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const vector unsigned char t = + (vector unsigned char) vec_revb(vec_insert(a, vec_promote((unsigned long long) (b), 1), 0)); + return (AEGIS_AES_BLOCK_T) { t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vec_xst_be(b.b0, 0, a); + vec_xst_be(b.b1, 0, a + 16); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_cipher_be(a.b0, b.b0), vec_cipher_be(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x2_common.h" */ +/*** Begin of #include "aegis256x2_common.h" ***/ +/* +** Name: aegis256x2_common.h +** Purpose: Common implementation for AEGIS-256x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x2_common.h" ***/ + + +struct aegis256x2_implementation aegis256x2_altivec_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256x2/aegis256x2_altivec.c" ***/ + +/* #include "aegis256x2/aegis256x2_armcrypto.c" */ +/*** Begin of #include "aegis256x2/aegis256x2_armcrypto.c" ***/ +/* +** Name: aegis256x2_armcrypto.c +** Purpose: Implementation of AEGIS-256x2 - ARM-Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* #include "../common/aeshardware.h" */ + + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x2.h" */ + +/* #include "aegis256x2_armcrypto.h" */ +/*** Begin of #include "aegis256x2_armcrypto.h" ***/ +/* +** Name: aegis256x2_armcrypto.h +** Purpose: Header for implementation structure of AEGIS-256x2 - ARM Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X2_ARMCRYPTO_H +#define AEGIS256X2_ARMCRYPTO_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x2_implementation aegis256x2_armcrypto_implementation; + +#endif /* AEGIS256X2_ARMCRYPTO_H */ +/*** End of #include "aegis256x2_armcrypto.h" ***/ + + +#ifndef __ARM_FEATURE_CRYPTO +# define __ARM_FEATURE_CRYPTO 1 +#endif +#ifndef __ARM_FEATURE_AES +# define __ARM_FEATURE_AES 1 +#endif + +#ifdef USE_ARM64_NEON_H +#include +#else +#include +#endif + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("neon,crypto,aes"))), \ + apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("+simd+crypto") +#endif + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + uint8x16_t b0; + uint8x16_t b1; +} aegis256x2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x2_aes_block_t +#define AEGIS_BLOCKS aegis256x2_blocks +#define AEGIS_STATE _aegis256x2_state +#define AEGIS_MAC_STATE _aegis256x2_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(a.b0, b.b0), veorq_u8(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vandq_u8(a.b0, b.b0), vandq_u8(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vld1q_u8(a), vld1q_u8(a + 16) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const uint8x16_t t = vreinterpretq_u8_u64(vsetq_lane_u64((a), vmovq_n_u64(b), 1)); + return (AEGIS_AES_BLOCK_T) { t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vst1q_u8(a, b.b0); + vst1q_u8(a + 16, b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(vaesmcq_u8(vaeseq_u8((a.b0), vmovq_n_u8(0))), (b.b0)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b1), vmovq_n_u8(0))), (b.b1)) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x2_common.h" */ +/*** Begin of #include "aegis256x2_common.h" ***/ +/* +** Name: aegis256x2_common.h +** Purpose: Common implementation for AEGIS-256x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x2_common.h" ***/ + + +struct aegis256x2_implementation aegis256x2_armcrypto_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256x2/aegis256x2_armcrypto.c" ***/ + +/* #include "aegis256x2/aegis256x2_avx2.c" */ +/*** Begin of #include "aegis256x2/aegis256x2_avx2.c" ***/ +/* +** Name: aegis256x2_avx2.c +** Purpose: Implementation of AEGIS-256x2 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x2.h" */ + +/* #include "aegis256x2_avx2.h" */ +/*** Begin of #include "aegis256x2_avx2.h" ***/ +/* +** Name: aegis256x2_avx2.h +** Purpose: Header for implementation structure of AEGIS-256x2 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X2_AVX2_H +#define AEGIS256X2_AVX2_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +#ifdef HAVE_VAESINTRIN_H +extern struct aegis256x2_implementation aegis256x2_avx2_implementation; +#endif + +#endif /* AEGIS256X2_AVX2_H */ +/*** End of #include "aegis256x2_avx2.h" ***/ + + +#ifdef HAVE_VAESINTRIN_H + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("vaes,avx2"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("vaes,avx2") +#endif + +#include + +#define AES_BLOCK_LENGTH 32 + +typedef __m256i aegis256x2_avx2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x2_avx2_aes_block_t +#define AEGIS_BLOCKS aegis256x2_avx2_blocks +#define AEGIS_STATE _aegis256x2_avx2_state +#define AEGIS_MAC_STATE _aegis256x2_avx2_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x2_avx2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm256_xor_si256(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm256_and_si256(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return _mm256_loadu_si256((const AEGIS_AES_BLOCK_T *) (const void *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return _mm256_broadcastsi128_si256(_mm_set_epi64x(a, b)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm256_storeu_si256((AEGIS_AES_BLOCK_T *) (void *) a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm256_aesenc_epi128(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x2_common.h" */ +/*** Begin of #include "aegis256x2_common.h" ***/ +/* +** Name: aegis256x2_common.h +** Purpose: Common implementation for AEGIS-256x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x2_common.h" ***/ + + +struct aegis256x2_implementation aegis256x2_avx2_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif /* HAVE_VAESINTRIN_H */ + +#endif +/*** End of #include "aegis256x2/aegis256x2_avx2.c" ***/ + +/* #include "aegis256x2/aegis256x2_soft.c" */ +/*** Begin of #include "aegis256x2/aegis256x2_soft.c" ***/ +/* +** Name: aegis256x2_soft.c +** Purpose: Implementation of AEGIS-256x2 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + + +/* #include "../common/softaes.h" */ + +/* #include "aegis256x2.h" */ + +/* #include "aegis256x2_soft.h" */ +/*** Begin of #include "aegis256x2_soft.h" ***/ +/* +** Name: aegis256x2_soft.h +** Purpose: Header for implementation structure of AEGIS-256x2 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X2_SOFT_H +#define AEGIS256X2_SOFT_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x2_implementation aegis256x2_soft_implementation; + +#endif /* AEGIS256X2_SOFT_H */ +/*** End of #include "aegis256x2_soft.h" ***/ + + +#define AES_BLOCK_LENGTH 32 + +typedef struct { + SoftAesBlock b0; + SoftAesBlock b1; +} aegis256x2_soft_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x2_soft_aes_block_t +#define AEGIS_BLOCKS aegis256x2_soft_blocks +#define AEGIS_STATE _aegis256x2_soft_state +#define AEGIS_MAC_STATE _aegis256x2_soft_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x2_soft_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_xor(a.b0, b.b0), softaes_block_xor(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_and(a.b0, b.b0), softaes_block_and(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_load(a), softaes_block_load(a + 16) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const SoftAesBlock t = softaes_block_load64x2(a, b); + return (AEGIS_AES_BLOCK_T) { t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + softaes_block_store(a, b.b0); + softaes_block_store(a + 16, b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_encrypt(a.b0, b.b0), softaes_block_encrypt(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x2_common.h" */ +/*** Begin of #include "aegis256x2_common.h" ***/ +/* +** Name: aegis256x2_common.h +** Purpose: Common implementation for AEGIS-256x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 32 +#define AEGIS_ALIGNMENT 32 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, + 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, + 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, + 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, + 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[2 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x01; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x01; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x2_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x2_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x2_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x2_common.h" ***/ + + +struct aegis256x2_implementation aegis256x2_soft_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + +/*** End of #include "aegis256x2/aegis256x2_soft.c" ***/ + +/* #include "aegis256x2/aegis256x2.c" */ +/*** Begin of #include "aegis256x2/aegis256x2.c" ***/ +/* +** Name: aegis256x2.c +** Purpose: Implementation of AEGIS-256x2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + +/* #include "aegis256x2.h" */ + +#if 0 +/* #include "aegis256x2_aesni.h" */ + +/* #include "aegis256x2_altivec.h" */ + +/* #include "aegis256x2_armcrypto.h" */ + +/* #include "aegis256x2_avx2.h" */ + +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NONE +/* #include "aegis256x2_soft.h" */ + +static const aegis256x2_implementation *implementation_256x2 = &aegis256x2_soft_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON +static const aegis256x2_implementation *implementation_256x2 = &aegis256x2_armcrypto_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +static const aegis256x2_implementation *implementation_256x2 = &aegis256x2_aesni_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC +static const aegis256x2_implementation *implementation_256x2 = &aegis256x2_altivec_implementation; +#else +#error "Unsupported architecture" +#endif + +AEGIS_API +size_t +aegis256x2_keybytes(void) +{ + return aegis256x2_KEYBYTES; +} + +AEGIS_API +size_t +aegis256x2_npubbytes(void) +{ + return aegis256x2_NPUBBYTES; +} + +AEGIS_API +size_t +aegis256x2_abytes_min(void) +{ + return aegis256x2_ABYTES_MIN; +} + +AEGIS_API +size_t +aegis256x2_abytes_max(void) +{ + return aegis256x2_ABYTES_MAX; +} + +AEGIS_API +size_t +aegis256x2_tailbytes_max(void) +{ + return aegis256x2_TAILBYTES_MAX; +} + +AEGIS_API +int +aegis256x2_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x2->encrypt_detached(c, mac, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x2_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x2->decrypt_detached(m, c, clen, mac, maclen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x2_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + return aegis256x2_encrypt_detached(c, c + mlen, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x2_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + int ret = -1; + + if (clen >= maclen) { + ret = aegis256x2_decrypt_detached(m, c, clen - maclen, c + clen - maclen, maclen, ad, adlen, + npub, k); + } + return ret; +} + +#ifndef AEGIS_OMIT_INCREMENTAL + +AEGIS_API +void +aegis256x2_state_init(aegis256x2_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + memset(st_, 0, sizeof *st_); + implementation_256x2->state_init(st_, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x2_state_encrypt_update(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + return implementation_256x2->state_encrypt_update(st_, c, clen_max, written, m, mlen); +} + +AEGIS_API +int +aegis256x2_state_encrypt_detached_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x2->state_encrypt_detached_final(st_, c, clen_max, written, mac, maclen); +} + +AEGIS_API +int +aegis256x2_state_encrypt_final(aegis256x2_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x2->state_encrypt_final(st_, c, clen_max, written, maclen); +} + +AEGIS_API +int +aegis256x2_state_decrypt_detached_update(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) +{ + return implementation_256x2->state_decrypt_detached_update(st_, m, mlen_max, written, c, clen); +} + +AEGIS_API +int +aegis256x2_state_decrypt_detached_final(aegis256x2_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x2->state_decrypt_detached_final(st_, m, mlen_max, written, mac, maclen); +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +AEGIS_API +void +aegis256x2_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + implementation_256x2->stream(out, len, npub, k); +} + +AEGIS_API +void +aegis256x2_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_256x2->encrypt_unauthenticated(c, m, mlen, npub, k); +} + +AEGIS_API +void +aegis256x2_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_256x2->decrypt_unauthenticated(m, c, clen, npub, k); +} + +#ifndef AEGIS_OMIT_MAC_API + +AEGIS_API +void +aegis256x2_mac_init(aegis256x2_mac_state *st_, const uint8_t *k, const uint8_t *npub) +{ + implementation_256x2->state_mac_init(st_, npub, k); +} + +AEGIS_API +int +aegis256x2_mac_update(aegis256x2_mac_state *st_, const uint8_t *m, size_t mlen) +{ + return implementation_256x2->state_mac_update(st_, m, mlen); +} + +AEGIS_API +int +aegis256x2_mac_final(aegis256x2_mac_state *st_, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x2->state_mac_final(st_, mac, maclen); +} + +AEGIS_API +int +aegis256x2_mac_verify(aegis256x2_mac_state *st_, const uint8_t *mac, size_t maclen) +{ + uint8_t expected_mac[32]; + + switch (maclen) { + case 16: + implementation_256x2->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_16(expected_mac, mac); + case 32: + implementation_256x2->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_32(expected_mac, mac); + default: + errno = EINVAL; + return -1; + } +} + +AEGIS_API +void +aegis256x2_mac_reset(aegis256x2_mac_state *st_) +{ + implementation_256x2->state_mac_reset(st_); +} + +AEGIS_API +void +aegis256x2_mac_state_clone(aegis256x2_mac_state *dst, const aegis256x2_mac_state *src) +{ + implementation_256x2->state_mac_clone(dst, src); +} + +#endif /* AEGIS_OMIT_MAC_API */ + +AEGIS_PRIVATE +int +aegis256x2_pick_best_implementation(void) +{ + implementation_256x2 = &aegis256x2_soft_implementation; + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + if (aegis_runtime_has_armcrypto()) { + implementation_256x2 = &aegis256x2_armcrypto_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +# ifdef HAVE_VAESINTRIN_H + if (aegis_runtime_has_vaes() && aegis_runtime_has_avx2()) { + implementation_256x2 = &aegis256x2_avx2_implementation; + return 0; + } +# endif + if (aegis_runtime_has_aesni() && aegis_runtime_has_avx()) { + implementation_256x2 = &aegis256x2_aesni_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC + if (aegis_runtime_has_altivec()) { + implementation_256x2 = &aegis256x2_altivec_implementation; + return 0; + } +#endif + + return 0; /* LCOV_EXCL_LINE */ +} +/*** End of #include "aegis256x2/aegis256x2.c" ***/ + + +/* AEGIS 256 x4 */ +/* #include "aegis256x4/implementations.h" */ +/*** Begin of #include "aegis256x4/implementations.h" ***/ +/* +** Name: implementations.h +** Purpose: Header for implementation structure of AEGIS-256x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_IMPLEMENTATIONS_H +#define AEGIS256X4_IMPLEMENTATIONS_H + +#include +#include + +/* #include "aegis256x4.h" */ + + +typedef struct aegis256x4_implementation { + int (*encrypt_detached)(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k); + int (*decrypt_detached)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + void (*stream)(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k); + void (*encrypt_unauthenticated)(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k); + void (*decrypt_unauthenticated)(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k); +#ifndef AEGIS_OMIT_INCREMENTAL + void (*state_init)(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k); + int (*state_encrypt_update)(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen); + int (*state_encrypt_detached_final)(aegis256x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen); + int (*state_encrypt_final)(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen); + int (*state_decrypt_detached_update)(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen); + int (*state_decrypt_detached_final)(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen); +#endif /* AEGIS_OMIT_INCREMENTAL */ +#ifndef AEGIS_OMIT_MAC_API + void (*state_mac_init)(aegis256x4_mac_state *st_, const uint8_t *npub, const uint8_t *k); + int (*state_mac_update)(aegis256x4_mac_state *st_, const uint8_t *ad, size_t adlen); + int (*state_mac_final)(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen); + void (*state_mac_reset)(aegis256x4_mac_state *st); + void (*state_mac_clone)(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src); +#endif /* AEGIS_OMIT_MAC_API */ +} aegis256x4_implementation; + +#endif /* AEGIS256X4_IMPLEMENTATIONS_H */ +/*** End of #include "aegis256x4/implementations.h" ***/ + +/* #include "aegis256x4/aegis256x4_aesni.c" */ +/*** Begin of #include "aegis256x4/aegis256x4_aesni.c" ***/ +/* +** Name: aegis256x4_aesni.c +** Purpose: Implementation of AEGIS-256x4 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x4.h" */ + +/* #include "aegis256x4_aesni.h" */ +/*** Begin of #include "aegis256x4_aesni.h" ***/ +/* +** Name: aegis256x4_aesni.h +** Purpose: Header for implementation structure of AEGIS-256x4 - AES-NI +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_AESNI_H +#define AEGIS256X4_AESNI_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x4_implementation aegis256x4_aesni_implementation; + +#endif /* AEGIS256X4_AESNI_H */ +/*** End of #include "aegis256x4_aesni.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("aes,avx"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("aes,avx") +#endif + +#include +#include + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + __m128i b0; + __m128i b1; + __m128i b2; + __m128i b3; +} aegis256x4_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x4_aes_block_t +#define AEGIS_BLOCKS aegis256x4_blocks +#define AEGIS_STATE _aegis256x4_state +#define AEGIS_MAC_STATE _aegis256x4_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x4_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_xor_si128(a.b0, b.b0), _mm_xor_si128(a.b1, b.b1), + _mm_xor_si128(a.b2, b.b2), _mm_xor_si128(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_and_si128(a.b0, b.b0), _mm_and_si128(a.b1, b.b1), + _mm_and_si128(a.b2, b.b2), _mm_and_si128(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { _mm_loadu_si128((const __m128i *) (const void *) a), + _mm_loadu_si128((const __m128i *) (const void *) (a + 16)), + _mm_loadu_si128((const __m128i *) (const void *) (a + 32)), + _mm_loadu_si128((const __m128i *) (const void *) (a + 48)) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const __m128i t = _mm_set_epi64x((long long) a, (long long) b); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm_storeu_si128((__m128i *) (void *) a, b.b0); + _mm_storeu_si128((__m128i *) (void *) (a + 16), b.b1); + _mm_storeu_si128((__m128i *) (void *) (a + 32), b.b2); + _mm_storeu_si128((__m128i *) (void *) (a + 48), b.b3); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm_aesenc_si128(a.b0, b.b0), _mm_aesenc_si128(a.b1, b.b1), + _mm_aesenc_si128(a.b2, b.b2), _mm_aesenc_si128(a.b3, b.b3) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x4_common.h" */ +/*** Begin of #include "aegis256x4_common.h" ***/ +/* +** Name: aegis256x4_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + memcpy(tmp + 32, key + 16, 16); + memcpy(tmp + 48, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + memcpy(tmp + 32, nonce + 16, 16); + memcpy(tmp + 48, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x4_common.h" ***/ + + +struct aegis256x4_implementation aegis256x4_aesni_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256x4/aegis256x4_aesni.c" ***/ + +/* #include "aegis256x4/aegis256x4_altivec.c" */ +/*** Begin of #include "aegis256x4/aegis256x4_altivec.c" ***/ +/* +** Name: aegis256x4_altivec.c +** Purpose: Implementation of AEGIS-256x4 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__ALTIVEC__) && defined(__CRYPTO__) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x4.h" */ + +/* #include "aegis256x4_altivec.h" */ +/*** Begin of #include "aegis256x4_altivec.h" ***/ +/* +** Name: aegis256x4_altivec.h +** Purpose: Header for implementation structure of AEGIS-256x4 - AltiVec +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_ALTIVEC_H +#define AEGIS256X4_ALTIVEC_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x4_implementation aegis256x4_altivec_implementation; + +#endif /* AEGIS256X4_ALTIVEC_H */ +/*** End of #include "aegis256x4_altivec.h" ***/ + + +#include + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("altivec,crypto"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("altivec,crypto") +#endif + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + vector unsigned char b0; + vector unsigned char b1; + vector unsigned char b2; + vector unsigned char b3; +} aegis256x4_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x4_aes_block_t +#define AEGIS_BLOCKS aegis256x4_blocks +#define AEGIS_STATE _aegis256x4_state +#define AEGIS_MAC_STATE _aegis256x4_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x4_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_xor(a.b0, b.b0), vec_xor(a.b1, b.b1), vec_xor(a.b2, b.b2), + vec_xor(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_and(a.b0, b.b0), vec_and(a.b1, b.b1), vec_and(a.b2, b.b2), + vec_and(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vec_xl_be(0, a), vec_xl_be(0, a + 16), vec_xl_be(0, a + 32), + vec_xl_be(0, a + 48) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const vector unsigned char t = + (vector unsigned char) vec_revb(vec_insert(a, vec_promote((unsigned long long) (b), 1), 0)); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vec_xst_be(b.b0, 0, a); + vec_xst_be(b.b1, 0, a + 16); + vec_xst_be(b.b2, 0, a + 32); + vec_xst_be(b.b3, 0, a + 48); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vec_cipher_be(a.b0, b.b0), vec_cipher_be(a.b1, b.b1), + vec_cipher_be(a.b2, b.b2), vec_cipher_be(a.b3, b.b3) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x4_common.h" */ +/*** Begin of #include "aegis256x4_common.h" ***/ +/* +** Name: aegis256x4_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + memcpy(tmp + 32, key + 16, 16); + memcpy(tmp + 48, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + memcpy(tmp + 32, nonce + 16, 16); + memcpy(tmp + 48, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x4_common.h" ***/ + + +struct aegis256x4_implementation aegis256x4_altivec_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256x4/aegis256x4_altivec.c" ***/ + +/* #include "aegis256x4/aegis256x4_armcrypto.c" */ +/*** Begin of #include "aegis256x4/aegis256x4_armcrypto.c" ***/ +/* +** Name: aegis256x4_armcrypto.c +** Purpose: Implementation of AEGIS-256x4 - ARM-Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* #include "../common/aeshardware.h" */ + + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x4.h" */ + +/* #include "aegis256x4_armcrypto.h" */ +/*** Begin of #include "aegis256x4_armcrypto.h" ***/ +/* +** Name: aegis256x4_armcrypto.h +** Purpose: Header for implementation structure of AEGIS-256x4 - ARM Crypto +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_ARMCRYPTO_H +#define AEGIS256X4_ARMCRYPTO_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x4_implementation aegis256x4_armcrypto_implementation; + +#endif /* AEGIS256X4_ARMCRYPTO_H */ +/*** End of #include "aegis256x4_armcrypto.h" ***/ + + +#ifndef __ARM_FEATURE_CRYPTO +# define __ARM_FEATURE_CRYPTO 1 +#endif +#ifndef __ARM_FEATURE_AES +# define __ARM_FEATURE_AES 1 +#endif + +#ifdef USE_ARM64_NEON_H +#include +#else +#include +#endif + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("neon,crypto,aes"))), \ + apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("+simd+crypto") +#endif + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + uint8x16_t b0; + uint8x16_t b1; + uint8x16_t b2; + uint8x16_t b3; +} aegis256x4_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x4_aes_block_t +#define AEGIS_BLOCKS aegis256x4_blocks +#define AEGIS_STATE _aegis256x4_state +#define AEGIS_MAC_STATE _aegis256x4_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x4_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(a.b0, b.b0), veorq_u8(a.b1, b.b1), veorq_u8(a.b2, b.b2), + veorq_u8(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { vandq_u8(a.b0, b.b0), vandq_u8(a.b1, b.b1), vandq_u8(a.b2, b.b2), + vandq_u8(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { vld1q_u8(a), vld1q_u8(a + 16), vld1q_u8(a + 32), vld1q_u8(a + 48) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const uint8x16_t t = vreinterpretq_u8_u64(vsetq_lane_u64((a), vmovq_n_u64(b), 1)); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + vst1q_u8(a, b.b0); + vst1q_u8(a + 16, b.b1); + vst1q_u8(a + 32, b.b2); + vst1q_u8(a + 48, b.b3); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { veorq_u8(vaesmcq_u8(vaeseq_u8((a.b0), vmovq_n_u8(0))), (b.b0)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b1), vmovq_n_u8(0))), (b.b1)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b2), vmovq_n_u8(0))), (b.b2)), + veorq_u8(vaesmcq_u8(vaeseq_u8((a.b3), vmovq_n_u8(0))), (b.b3)) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x4_common.h" */ +/*** Begin of #include "aegis256x4_common.h" ***/ +/* +** Name: aegis256x4_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + memcpy(tmp + 32, key + 16, 16); + memcpy(tmp + 48, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + memcpy(tmp + 32, nonce + 16, 16); + memcpy(tmp + 48, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x4_common.h" ***/ + + +struct aegis256x4_implementation aegis256x4_armcrypto_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif +/*** End of #include "aegis256x4/aegis256x4_armcrypto.c" ***/ + +/* #include "aegis256x4/aegis256x4_avx2.c" */ +/*** Begin of #include "aegis256x4/aegis256x4_avx2.c" ***/ +/* +** Name: aegis256x4_avx2.c +** Purpose: Implementation of AEGIS-256x4 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x4.h" */ + +/* #include "aegis256x4_avx2.h" */ +/*** Begin of #include "aegis256x4_avx2.h" ***/ +/* +** Name: aegis256x4_avx2.h +** Purpose: Header for implementation structure of AEGIS-256x4 - AES-NI AVX2 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_AVX2_H +#define AEGIS256X4_AVX2_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +#ifdef HAVE_VAESINTRIN_H +extern struct aegis256x4_implementation aegis256x4_avx2_implementation; +#endif + +#endif /* AEGIS256X4_AVX2_H */ +/*** End of #include "aegis256x4_avx2.h" ***/ + + +#ifdef HAVE_VAESINTRIN_H + +#ifdef __clang__ +# pragma clang attribute push(__attribute__((target("vaes,avx2"))), apply_to = function) +#elif defined(__GNUC__) +# pragma GCC target("vaes,avx2") +#endif + +#include + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + __m256i b0; + __m256i b1; +} aegis256_avx2_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256_avx2_aes_block_t +#define AEGIS_BLOCKS aegis256x4_avx2_blocks +#define AEGIS_STATE _aegis256x4_avx2_state +#define AEGIS_MAC_STATE _aegis256x4_avx2_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x4_avx2_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_xor_si256(a.b0, b.b0), _mm256_xor_si256(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_and_si256(a.b0, b.b0), _mm256_and_si256(a.b1, b.b1) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_loadu_si256((const __m256i *) (const void *) a), + _mm256_loadu_si256((const __m256i *) (const void *) (a + 32)) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const __m256i t = _mm256_broadcastsi128_si256(_mm_set_epi64x((long long) a, (long long) b)); + return (AEGIS_AES_BLOCK_T) { t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm256_storeu_si256((__m256i *) (void *) a, b.b0); + _mm256_storeu_si256((__m256i *) (void *) (a + 32), b.b1); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { _mm256_aesenc_epi128(a.b0, b.b0), _mm256_aesenc_epi128(a.b1, b.b1) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x4_common.h" */ +/*** Begin of #include "aegis256x4_common.h" ***/ +/* +** Name: aegis256x4_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + memcpy(tmp + 32, key + 16, 16); + memcpy(tmp + 48, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + memcpy(tmp + 32, nonce + 16, 16); + memcpy(tmp + 48, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x4_common.h" ***/ + + +struct aegis256x4_implementation aegis256x4_avx2_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif /* HAVE_VAESINTRIN_H */ + +#endif +/*** End of #include "aegis256x4/aegis256x4_avx2.c" ***/ + +/* #include "aegis256x4/aegis256x4_avx512.c" */ +/*** Begin of #include "aegis256x4/aegis256x4_avx512.c" ***/ +/* +** Name: aegis256x4_avx512.c +** Purpose: Implementation of AEGIS-256x4 - AES-NI AVX512 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_AMD64) + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "aegis256x4.h" */ + +/* #include "aegis256x4_avx512.h" */ +/*** Begin of #include "aegis256x4_avx512.h" ***/ +/* +** Name: aegis256x4_avx512.h +** Purpose: Header for implementation structure of AEGIS-256x4 - AES-NI AVX512 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_AVX512_H +#define AEGIS256X4_AVX512_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +#ifdef HAVE_VAESINTRIN_H +extern struct aegis256x4_implementation aegis256x4_avx512_implementation; +#endif + +#endif /* AEGIS256X4_AVX512_H */ +/*** End of #include "aegis256x4_avx512.h" ***/ + + +#ifdef HAVE_VAESINTRIN_H + +#ifdef __clang__ +# if __clang_major__ >= 18 +# pragma clang attribute push(__attribute__((target("vaes,avx512f,evex512"))), \ + apply_to = function) +# else +# pragma clang attribute push(__attribute__((target("vaes,avx512f"))), \ + apply_to = function) +# endif +#elif defined(__GNUC__) +# pragma GCC target("vaes,avx512f") +#endif + +#include + +#define AES_BLOCK_LENGTH 64 + +typedef __m512i aegis256_avx512_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256_avx512_aes_block_t +#define AEGIS_BLOCKS aegis256x4_avx512_blocks +#define AEGIS_STATE _aegis256x4_avx512_state +#define AEGIS_MAC_STATE _aegis256x4_avx512_mac_state + +#define AEGIS_FUNC_PREFIX aegis256_avx512_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm512_xor_si512(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm512_and_si512(a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return _mm512_loadu_si512((const AEGIS_AES_BLOCK_T *) (const void *) a); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + return _mm512_broadcast_i32x4(_mm_set_epi64x(a, b)); +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + _mm512_storeu_si512((AEGIS_AES_BLOCK_T *) (void *) a, b); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return _mm512_aesenc_epi128(a, b); +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x4_common.h" */ +/*** Begin of #include "aegis256x4_common.h" ***/ +/* +** Name: aegis256x4_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + memcpy(tmp + 32, key + 16, 16); + memcpy(tmp + 48, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + memcpy(tmp + 32, nonce + 16, 16); + memcpy(tmp + 48, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x4_common.h" ***/ + + +struct aegis256x4_implementation aegis256x4_avx512_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + + +#ifdef __clang__ +# pragma clang attribute pop +#endif + +#endif /* HAVE_VAESINTRIN_H */ + +#endif +/*** End of #include "aegis256x4/aegis256x4_avx512.c" ***/ + +/* #include "aegis256x4/aegis256x4_soft.c" */ +/*** Begin of #include "aegis256x4/aegis256x4_soft.c" ***/ +/* +** Name: aegis256x4_soft.c +** Purpose: Implementation of AEGIS-256x4 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + + +/* #include "../common/softaes.h" */ + +/* #include "aegis256x4.h" */ + +/* #include "aegis256x4_soft.h" */ +/*** Begin of #include "aegis256x4_soft.h" ***/ +/* +** Name: aegis256x4_soft.h +** Purpose: Header for implementation structure of AEGIS-256x4 - Software +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#ifndef AEGIS256X4_SOFT_H +#define AEGIS256X4_SOFT_H + +/* #include "../common/common.h" */ + +/* #include "implementations.h" */ + + +extern struct aegis256x4_implementation aegis256x4_soft_implementation; + +#endif /* AEGIS256X4_SOFT_H */ +/*** End of #include "aegis256x4_soft.h" ***/ + + +#define AES_BLOCK_LENGTH 64 + +typedef struct { + SoftAesBlock b0; + SoftAesBlock b1; + SoftAesBlock b2; + SoftAesBlock b3; +} aegis256x4_soft_aes_block_t; + +#define AEGIS_AES_BLOCK_T aegis256x4_soft_aes_block_t +#define AEGIS_BLOCKS aegis256x4_soft_blocks +#define AEGIS_STATE _aegis256x4_soft_state +#define AEGIS_MAC_STATE _aegis256x4_soft_mac_state + +#define AEGIS_FUNC_PREFIX aegis256x4_soft_impl + +/* #include "../common/func_names_define.h" */ +/*** Begin of #include "../common/func_names_define.h" ***/ +/* +** Name: func_names_define.h +** Purpose: Defines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +#define AEGIS_AES_BLOCK_XOR AEGIS_FUNC(aes_block_xor) +#define AEGIS_AES_BLOCK_AND AEGIS_FUNC(aes_block_and) +#define AEGIS_AES_BLOCK_LOAD AEGIS_FUNC(aes_block_load) +#define AEGIS_AES_BLOCK_LOAD_64x2 AEGIS_FUNC(aes_block_load_64x2) +#define AEGIS_AES_BLOCK_STORE AEGIS_FUNC(aes_block_store) +#define AEGIS_AES_ENC AEGIS_FUNC(aes_enc) +#define AEGIS_update AEGIS_FUNC(update) +#define AEGIS_encrypt_detached AEGIS_FUNC(encrypt_detached) +#define AEGIS_decrypt_detached AEGIS_FUNC(decrypt_detached) +#define AEGIS_encrypt_unauthenticated AEGIS_FUNC(encrypt_unauthenticated) +#define AEGIS_decrypt_unauthenticated AEGIS_FUNC(decrypt_unauthenticated) +#define AEGIS_stream AEGIS_FUNC(stream) +#define AEGIS_state_init AEGIS_FUNC(state_init) +#define AEGIS_state_encrypt_update AEGIS_FUNC(state_encrypt_update) +#define AEGIS_state_encrypt_detached_final AEGIS_FUNC(state_encrypt_detached_final) +#define AEGIS_state_encrypt_final AEGIS_FUNC(state_encrypt_final) +#define AEGIS_state_decrypt_detached_update AEGIS_FUNC(state_decrypt_detached_update) +#define AEGIS_state_decrypt_detached_final AEGIS_FUNC(state_decrypt_detached_final) +#define AEGIS_state_mac_init AEGIS_FUNC(state_mac_init) +#define AEGIS_state_mac_update AEGIS_FUNC(state_mac_update) +#define AEGIS_state_mac_final AEGIS_FUNC(state_mac_final) +#define AEGIS_state_mac_reset AEGIS_FUNC(state_mac_reset) +#define AEGIS_state_mac_clone AEGIS_FUNC(state_mac_clone) +/*** End of #include "../common/func_names_define.h" ***/ + + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_XOR(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_xor(a.b0, b.b0), softaes_block_xor(a.b1, b.b1), + softaes_block_xor(a.b2, b.b2), softaes_block_xor(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_AND(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_and(a.b0, b.b0), softaes_block_and(a.b1, b.b1), + softaes_block_and(a.b2, b.b2), softaes_block_and(a.b3, b.b3) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD(const uint8_t *a) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_load(a), softaes_block_load(a + 16), + softaes_block_load(a + 32), softaes_block_load(a + 48) }; +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_BLOCK_LOAD_64x2(uint64_t a, uint64_t b) +{ + const SoftAesBlock t = softaes_block_load64x2(a, b); + return (AEGIS_AES_BLOCK_T) { t, t, t, t }; +} + +static inline void +AEGIS_AES_BLOCK_STORE(uint8_t *a, const AEGIS_AES_BLOCK_T b) +{ + softaes_block_store(a, b.b0); + softaes_block_store(a + 16, b.b1); + softaes_block_store(a + 32, b.b2); + softaes_block_store(a + 48, b.b3); +} + +static inline AEGIS_AES_BLOCK_T +AEGIS_AES_ENC(const AEGIS_AES_BLOCK_T a, const AEGIS_AES_BLOCK_T b) +{ + return (AEGIS_AES_BLOCK_T) { softaes_block_encrypt(a.b0, b.b0), softaes_block_encrypt(a.b1, b.b1), + softaes_block_encrypt(a.b2, b.b2), softaes_block_encrypt(a.b3, b.b3) }; +} + +static inline void +AEGIS_update(AEGIS_AES_BLOCK_T *const state, const AEGIS_AES_BLOCK_T d) +{ + AEGIS_AES_BLOCK_T tmp; + + tmp = state[5]; + state[5] = AEGIS_AES_ENC(state[4], state[5]); + state[4] = AEGIS_AES_ENC(state[3], state[4]); + state[3] = AEGIS_AES_ENC(state[2], state[3]); + state[2] = AEGIS_AES_ENC(state[1], state[2]); + state[1] = AEGIS_AES_ENC(state[0], state[1]); + state[0] = AEGIS_AES_BLOCK_XOR(AEGIS_AES_ENC(tmp, state[0]), d); +} + +/* #include "aegis256x4_common.h" */ +/*** Begin of #include "aegis256x4_common.h" ***/ +/* +** Name: aegis256x4_common.h +** Purpose: Common implementation for AEGIS-256 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#define AEGIS_RATE 64 +#define AEGIS_ALIGNMENT 64 + +typedef AEGIS_AES_BLOCK_T AEGIS_BLOCKS[6]; + +#define AEGIS_init AEGIS_FUNC(init) +#define AEGIS_mac AEGIS_FUNC(mac) +#define AEGIS_mac_nr AEGIS_FUNC(mac_nr) +#define AEGIS_absorb AEGIS_FUNC(absorb) +#define AEGIS_enc AEGIS_FUNC(enc) +#define AEGIS_dec AEGIS_FUNC(dec) +#define AEGIS_declast AEGIS_FUNC(declast) + +static void +AEGIS_init(const uint8_t *key, const uint8_t *nonce, AEGIS_AES_BLOCK_T *const state) +{ + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c0_[AES_BLOCK_LENGTH] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, + 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, + 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, + 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, 0x00, 0x01, 0x01, 0x02, + 0x03, 0x05, 0x08, 0x0d, 0x15, 0x22, 0x37, 0x59, 0x90, 0xe9, 0x79, 0x62, + }; + static CRYPTO_ALIGN(AES_BLOCK_LENGTH) const uint8_t c1_[AES_BLOCK_LENGTH] = { + 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, + 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, + 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, 0x6d, 0xc2, 0x2f, + 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, 0xdb, 0x3d, 0x18, 0x55, + 0x6d, 0xc2, 0x2f, 0xf1, 0x20, 0x11, 0x31, 0x42, 0x73, 0xb5, 0x28, 0xdd, + }; + + const AEGIS_AES_BLOCK_T c0 = AEGIS_AES_BLOCK_LOAD(c0_); + const AEGIS_AES_BLOCK_T c1 = AEGIS_AES_BLOCK_LOAD(c1_); + uint8_t tmp[4 * 16]; + uint8_t context_bytes[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T context; + AEGIS_AES_BLOCK_T k0, k1; + AEGIS_AES_BLOCK_T n0, n1; + AEGIS_AES_BLOCK_T k0_n0, k1_n1; + int i; + + memcpy(tmp, key, 16); + memcpy(tmp + 16, key, 16); + memcpy(tmp + 32, key, 16); + memcpy(tmp + 48, key, 16); + k0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, key + 16, 16); + memcpy(tmp + 16, key + 16, 16); + memcpy(tmp + 32, key + 16, 16); + memcpy(tmp + 48, key + 16, 16); + k1 = AEGIS_AES_BLOCK_LOAD(tmp); + + memcpy(tmp, nonce, 16); + memcpy(tmp + 16, nonce, 16); + memcpy(tmp + 32, nonce, 16); + memcpy(tmp + 48, nonce, 16); + n0 = AEGIS_AES_BLOCK_LOAD(tmp); + memcpy(tmp, nonce + 16, 16); + memcpy(tmp + 16, nonce + 16, 16); + memcpy(tmp + 32, nonce + 16, 16); + memcpy(tmp + 48, nonce + 16, 16); + n1 = AEGIS_AES_BLOCK_LOAD(tmp); + + k0_n0 = AEGIS_AES_BLOCK_XOR(k0, n0); + k1_n1 = AEGIS_AES_BLOCK_XOR(k1, n1); + + memset(context_bytes, 0, sizeof context_bytes); + context_bytes[0 * 16] = 0x00; + context_bytes[0 * 16 + 1] = 0x03; + context_bytes[1 * 16] = 0x01; + context_bytes[1 * 16 + 1] = 0x03; + context_bytes[2 * 16] = 0x02; + context_bytes[2 * 16 + 1] = 0x03; + context_bytes[3 * 16] = 0x03; + context_bytes[3 * 16 + 1] = 0x03; + context = AEGIS_AES_BLOCK_LOAD(context_bytes); + + state[0] = k0_n0; + state[1] = k1_n1; + state[2] = c1; + state[3] = c0; + state[4] = AEGIS_AES_BLOCK_XOR(k0, c0); + state[5] = AEGIS_AES_BLOCK_XOR(k1, c1); + for (i = 0; i < 4; i++) { + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k0_n0); + state[3] = AEGIS_AES_BLOCK_XOR(state[3], context); + state[5] = AEGIS_AES_BLOCK_XOR(state[5], context); + AEGIS_update(state, k1_n1); + } +} + +static void +AEGIS_mac(uint8_t *mac, size_t maclen, uint64_t adlen, uint64_t mlen, AEGIS_AES_BLOCK_T *const state) +{ + uint8_t mac_multi_0[AES_BLOCK_LENGTH]; + uint8_t mac_multi_1[AES_BLOCK_LENGTH]; + AEGIS_AES_BLOCK_T tmp; + int i; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(mlen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + if (maclen == 16) { + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + } else if (maclen == 32) { + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(mac_multi_0, tmp); + for (i = 0; i < 16; i++) { + mac[i] = mac_multi_0[i] ^ mac_multi_0[1 * 16 + i] ^ mac_multi_0[2 * 16 + i] ^ + mac_multi_0[3 * 16 + i]; + } + + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(mac_multi_1, tmp); + for (i = 0; i < 16; i++) { + mac[i + 16] = mac_multi_1[i] ^ mac_multi_1[1 * 16 + i] ^ mac_multi_1[2 * 16 + i] ^ + mac_multi_1[3 * 16 + i]; + } + } else { + memset(mac, 0, maclen); + } +} + +static inline void +AEGIS_absorb(const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + AEGIS_update(state, msg); +} + +static void +AEGIS_enc(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + AEGIS_AES_BLOCK_T tmp; + + msg = AEGIS_AES_BLOCK_LOAD(src); + tmp = AEGIS_AES_BLOCK_XOR(msg, state[5]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[1]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, tmp); + + AEGIS_update(state, msg); +} + +static void +AEGIS_dec(uint8_t *const dst, const uint8_t *const src, AEGIS_AES_BLOCK_T *const state) +{ + AEGIS_AES_BLOCK_T msg; + + msg = AEGIS_AES_BLOCK_LOAD(src); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(dst, msg); + + AEGIS_update(state, msg); +} + +static void +AEGIS_declast(uint8_t *const dst, const uint8_t *const src, size_t len, + AEGIS_AES_BLOCK_T *const state) +{ + uint8_t pad[AEGIS_RATE]; + AEGIS_AES_BLOCK_T msg; + + memset(pad, 0, sizeof pad); + memcpy(pad, src, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + msg = AEGIS_AES_BLOCK_XOR(msg, state[5]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[4]); + msg = AEGIS_AES_BLOCK_XOR(msg, state[1]); + msg = AEGIS_AES_BLOCK_XOR(msg, AEGIS_AES_BLOCK_AND(state[2], state[3])); + AEGIS_AES_BLOCK_STORE(pad, msg); + + memset(pad + len, 0, sizeof pad - len); + memcpy(dst, pad, len); + + msg = AEGIS_AES_BLOCK_LOAD(pad); + + AEGIS_update(state, msg); +} + +static void +AEGIS_mac_nr(uint8_t *mac, size_t maclen, uint64_t adlen, AEGIS_AES_BLOCK_T *state) +{ + uint8_t t[2 * AES_BLOCK_LENGTH]; + uint8_t r[AEGIS_RATE]; + AEGIS_AES_BLOCK_T tmp; + int i; + const int d = AES_BLOCK_LENGTH / 16; + + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, adlen << 3); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } + + memset(r, 0, sizeof r); + if (maclen == 16) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[5], state[4]); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[3], state[2])); + tmp = AEGIS_AES_BLOCK_XOR(tmp, AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + } else if (maclen == 32) { +#if AES_BLOCK_LENGTH > 16 + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t + AES_BLOCK_LENGTH, tmp); + for (i = 1; i < d; i++) { + memcpy(r, t + i * 16, 16); + AEGIS_absorb(r, state); + memcpy(r, t + AES_BLOCK_LENGTH + i * 16, 16); + AEGIS_absorb(r, state); + } + tmp = AEGIS_AES_BLOCK_LOAD_64x2(maclen << 3, d); + tmp = AEGIS_AES_BLOCK_XOR(tmp, state[3]); + for (i = 0; i < 7; i++) { + AEGIS_update(state, tmp); + } +#endif + tmp = AEGIS_AES_BLOCK_XOR(state[2], AEGIS_AES_BLOCK_XOR(state[1], state[0])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac, t, 16); + tmp = AEGIS_AES_BLOCK_XOR(state[5], AEGIS_AES_BLOCK_XOR(state[4], state[3])); + AEGIS_AES_BLOCK_STORE(t, tmp); + memcpy(mac + 16, t, 16); + } else { + memset(mac, 0, maclen); + } +} + +static int +AEGIS_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } + + AEGIS_mac(mac, maclen, adlen, mlen, state); + + return 0; +} + +static int +AEGIS_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, size_t maclen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + const size_t mlen = clen; + size_t i; + int ret; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, state); + } + if (adlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(src, state); + } + if (m != NULL) { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + } else { + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, state); + } + } + if (mlen % AEGIS_RATE) { + if (m != NULL) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } else { + AEGIS_declast(dst, c + i, mlen % AEGIS_RATE, state); + } + } + + COMPILER_ASSERT(sizeof computed_mac >= 32); + AEGIS_mac(computed_mac, maclen, adlen, mlen, state); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret != 0 && m != NULL) { + memset(m, 0, mlen); + } + return ret; +} + +static void +AEGIS_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + memset(src, 0, sizeof src); + if (npub == NULL) { + npub = src; + } + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= len; i += AEGIS_RATE) { + AEGIS_enc(out + i, src, state); + } + if (len % AEGIS_RATE) { + AEGIS_enc(dst, src, state); + memcpy(out + i, dst, len % AEGIS_RATE); + } +} + +static void +AEGIS_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, state); + } + if (mlen % AEGIS_RATE) { + memset(src, 0, AEGIS_RATE); + memcpy(src, m + i, mlen % AEGIS_RATE); + AEGIS_enc(dst, src, state); + memcpy(c + i, dst, mlen % AEGIS_RATE); + } +} + +static void +AEGIS_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS state; + const size_t mlen = clen; + size_t i; + + AEGIS_init(k, npub, state); + + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, state); + } + if (mlen % AEGIS_RATE) { + AEGIS_declast(m + i, c + i, mlen % AEGIS_RATE, state); + } +} + +typedef struct AEGIS_STATE { + AEGIS_BLOCKS blocks; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + uint64_t mlen; + size_t pos; +} AEGIS_STATE; + +typedef struct AEGIS_MAC_STATE { + AEGIS_BLOCKS blocks; + AEGIS_BLOCKS blocks0; + uint8_t buf[AEGIS_RATE]; + uint64_t adlen; + size_t pos; +} AEGIS_MAC_STATE; + +#ifndef AEGIS_OMIT_INCREMENTAL + +static void +AEGIS_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + + memcpy(blocks, st->blocks, sizeof blocks); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->mlen = 0; + st->pos = 0; + + AEGIS_init(k, npub, blocks); + for (i = 0; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (adlen % AEGIS_RATE) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen % AEGIS_RATE); + AEGIS_absorb(st->buf, blocks); + } + st->adlen = adlen; + + memcpy(st->blocks, blocks, sizeof blocks); +} + +static int +AEGIS_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += mlen; + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = mlen < available ? mlen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, m + i, n); + m += n; + mlen -= n; + st->pos += n; + } + if (st->pos == sizeof st->buf) { + if (clen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + clen_max -= AEGIS_RATE; + AEGIS_enc(c, st->buf, blocks); + *written += AEGIS_RATE; + c += AEGIS_RATE; + st->pos = 0; + } else { + return 0; + } + } + if (clen_max < (mlen & ~(size_t) (AEGIS_RATE - 1))) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= mlen; i += AEGIS_RATE) { + AEGIS_enc(c + i, m + i, blocks); + } + *written += i; + left = mlen % AEGIS_RATE; + if (left != 0) { + memcpy(st->buf, m + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(mac, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t src[AEGIS_RATE]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (clen_max < st->pos + maclen) { + errno = ERANGE; + return -1; + } + if (st->pos != 0) { + memset(src, 0, sizeof src); + memcpy(src, st->buf, st->pos); + AEGIS_enc(dst, src, blocks); + memcpy(c, dst, st->pos); + } + AEGIS_mac(c + st->pos, maclen, st->adlen, st->mlen, blocks); + + *written = st->pos + maclen; + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *c, size_t clen) +{ + AEGIS_BLOCKS blocks; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + size_t i = 0; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + st->mlen += clen; + + if (st->pos != 0) { + const size_t available = (sizeof st->buf) - st->pos; + const size_t n = clen < available ? clen : available; + + if (n != 0) { + memcpy(st->buf + st->pos, c, n); + c += n; + clen -= n; + st->pos += n; + } + if (st->pos < (sizeof st->buf)) { + return 0; + } + st->pos = 0; + if (m != NULL) { + if (mlen_max < AEGIS_RATE) { + errno = ERANGE; + return -1; + } + mlen_max -= AEGIS_RATE; + AEGIS_dec(m, st->buf, blocks); + m += AEGIS_RATE; + } else { + AEGIS_dec(dst, st->buf, blocks); + } + *written += AEGIS_RATE; + } + + if (m != NULL) { + if (mlen_max < (clen % AEGIS_RATE)) { + errno = ERANGE; + return -1; + } + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(m + i, c + i, blocks); + } + } else { + for (i = 0; i + AEGIS_RATE <= clen; i += AEGIS_RATE) { + AEGIS_dec(dst, c + i, blocks); + } + } + *written += i; + left = clen % AEGIS_RATE; + if (left) { + memcpy(st->buf, c + i, left); + st->pos = left; + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, size_t *written, + const uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + CRYPTO_ALIGN(16) uint8_t computed_mac[32]; + CRYPTO_ALIGN(AEGIS_ALIGNMENT) uint8_t dst[AEGIS_RATE]; + AEGIS_STATE *const st = + (AEGIS_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + int ret; + + memcpy(blocks, st->blocks, sizeof blocks); + + *written = 0; + if (st->pos != 0) { + if (m != NULL) { + if (mlen_max < st->pos) { + errno = ERANGE; + return -1; + } + AEGIS_declast(m, st->buf, st->pos, blocks); + } else { + AEGIS_declast(dst, st->buf, st->pos, blocks); + } + } + AEGIS_mac(computed_mac, maclen, st->adlen, st->mlen, blocks); + ret = -1; + if (maclen == 16) { + ret = aegis_verify_16(computed_mac, mac); + } else if (maclen == 32) { + ret = aegis_verify_32(computed_mac, mac); + } + if (ret == 0) { + *written = st->pos; + } else { + memset(m, 0, st->pos); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return ret; +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +#ifndef AEGIS_OMIT_MAC_API + +static void +AEGIS_state_mac_init(aegis256x4_mac_state *st_, const uint8_t *npub, const uint8_t *k) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + + COMPILER_ASSERT((sizeof *st) + AEGIS_ALIGNMENT <= sizeof *st_); + st->pos = 0; + + memcpy(blocks, st->blocks, sizeof blocks); + + AEGIS_init(k, npub, blocks); + + memcpy(st->blocks0, blocks, sizeof blocks); + memcpy(st->blocks, blocks, sizeof blocks); + st->adlen = 0; +} + +static int +AEGIS_state_mac_update(aegis256x4_mac_state *st_, const uint8_t *ad, size_t adlen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t i; + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + st->adlen += adlen; + if (left != 0) { + if (left + adlen < AEGIS_RATE) { + memcpy(st->buf + left, ad, adlen); + return 0; + } + memcpy(st->buf + left, ad, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + ad += AEGIS_RATE - left; + adlen -= AEGIS_RATE - left; + } + for (i = 0; i + AEGIS_RATE * 2 <= adlen; i += AEGIS_RATE * 2) { + AEGIS_AES_BLOCK_T msg0, msg1; + + msg0 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 0); + msg1 = AEGIS_AES_BLOCK_LOAD(ad + i + AES_BLOCK_LENGTH * 1); + COMPILER_ASSERT(AES_BLOCK_LENGTH * 2 == AEGIS_RATE * 2); + + AEGIS_update(blocks, msg0); + AEGIS_update(blocks, msg1); + } + for (; i + AEGIS_RATE <= adlen; i += AEGIS_RATE) { + AEGIS_absorb(ad + i, blocks); + } + if (i < adlen) { + memset(st->buf, 0, AEGIS_RATE); + memcpy(st->buf, ad + i, adlen - i); + } + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static int +AEGIS_state_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + AEGIS_BLOCKS blocks; + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + size_t left; + + memcpy(blocks, st->blocks, sizeof blocks); + + left = st->adlen % AEGIS_RATE; + if (left != 0) { + memset(st->buf + left, 0, AEGIS_RATE - left); + AEGIS_absorb(st->buf, blocks); + } + AEGIS_mac_nr(mac, maclen, st->adlen, blocks); + + memcpy(st->blocks, blocks, sizeof blocks); + + return 0; +} + +static void +AEGIS_state_mac_reset(aegis256x4_mac_state *st_) +{ + AEGIS_MAC_STATE *const st = + (AEGIS_MAC_STATE *) ((((uintptr_t) &st_->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + st->adlen = 0; + st->pos = 0; + memcpy(st->blocks, st->blocks0, sizeof(AEGIS_BLOCKS)); +} + +static void +AEGIS_state_mac_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src) +{ + AEGIS_MAC_STATE *const dst_ = + (AEGIS_MAC_STATE *) ((((uintptr_t) &dst->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + const AEGIS_MAC_STATE *const src_ = + (const AEGIS_MAC_STATE *) ((((uintptr_t) &src->opaque) + (AEGIS_ALIGNMENT - 1)) & + ~(uintptr_t) (AEGIS_ALIGNMENT - 1)); + *dst_ = *src_; +} + +#endif /* AEGIS_OMIT_MAC_API */ + +#undef AEGIS_RATE +#undef AEGIS_ALIGNMENT + +#undef AEGIS_init +#undef AEGIS_mac +#undef AEGIS_mac_nr +#undef AEGIS_absorb +#undef AEGIS_enc +#undef AEGIS_dec +#undef AEGIS_declast +/*** End of #include "aegis256x4_common.h" ***/ + + +struct aegis256x4_implementation aegis256x4_soft_implementation = { +/* #include "../common/func_table.h" */ +/*** Begin of #include "../common/func_table.h" ***/ +/* +** Name: func_table.h +** Purpose: Table of AEGIS API function implementations +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +AEGIS_API_IMPL_LIST_STD +#ifndef AEGIS_OMIT_INCREMENTAL +AEGIS_API_IMPL_LIST_INC +#endif +#ifndef AEGIS_OMIT_MAC_API +AEGIS_API_IMPL_LIST_MAC +#endif + +/*** End of #include "../common/func_table.h" ***/ + +}; + +/* #include "../common/type_names_undefine.h" */ +/*** Begin of #include "../common/type_names_undefine.h" ***/ +/* +** Name: type_names_undefine.h +** Purpose: Undefines for AEGIS type names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine AES block length */ +#undef AES_BLOCK_LENGTH + +/* Undefine type names */ +#undef AEGIS_AES_BLOCK_T +#undef AEGIS_BLOCKS +#undef AEGIS_STATE +#undef AEGIS_MAC_STATE +/*** End of #include "../common/type_names_undefine.h" ***/ + +/* #include "../common/func_names_undefine.h" */ +/*** Begin of #include "../common/func_names_undefine.h" ***/ +/* +** Name: func_names_undefine.h +** Purpose: Undefines for AEGIS function names +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +/* +** NOTE: +** Do NOT use include guards, because including this header +** multiple times is intended behaviour. +*/ + +/* Undefine function name prefix */ +#undef AEGIS_FUNC_PREFIX + +/* Undefine all function names */ +#undef AEGIS_AES_BLOCK_XOR +#undef AEGIS_AES_BLOCK_AND +#undef AEGIS_AES_BLOCK_LOAD +#undef AEGIS_AES_BLOCK_LOAD_64x2 +#undef AEGIS_AES_BLOCK_STORE +#undef AEGIS_AES_ENC +#undef AEGIS_update +#undef AEGIS_encrypt_detached +#undef AEGIS_decrypt_detached +#undef AEGIS_encrypt_unauthenticated +#undef AEGIS_decrypt_unauthenticated +#undef AEGIS_stream +#undef AEGIS_state_init +#undef AEGIS_state_encrypt_update +#undef AEGIS_state_encrypt_detached_final +#undef AEGIS_state_encrypt_final +#undef AEGIS_state_decrypt_detached_update +#undef AEGIS_state_decrypt_detached_final +#undef AEGIS_state_mac_init +#undef AEGIS_state_mac_update +#undef AEGIS_state_mac_final +#undef AEGIS_state_mac_reset +#undef AEGIS_state_mac_clone +/*** End of #include "../common/func_names_undefine.h" ***/ + +/*** End of #include "aegis256x4/aegis256x4_soft.c" ***/ + +/* #include "aegis256x4/aegis256x4.c" */ +/*** Begin of #include "aegis256x4/aegis256x4.c" ***/ +/* +** Name: aegis256x4.c +** Purpose: Implementation of AEGIS-256x4 +** Copyright: (c) 2023-2024 Frank Denis +** SPDX-License-Identifier: MIT +*/ + +#include +#include +#include +#include +#include + +/* #include "../common/common.h" */ + +/* #include "../common/cpu.h" */ + +/* #include "aegis256x4.h" */ + +#if 0 +/* #include "aegis256x4_aesni.h" */ + +/* #include "aegis256x4_altivec.h" */ + +/* #include "aegis256x4_armcrypto.h" */ + +/* #include "aegis256x4_avx2.h" */ + +/* #include "aegis256x4_avx512.h" */ + +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NONE +/* #include "aegis256x4_soft.h" */ + +static const aegis256x4_implementation *implementation_256x4 = &aegis256x4_soft_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON +static const aegis256x4_implementation *implementation_256x4 = &aegis256x4_armcrypto_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +static const aegis256x4_implementation *implementation_256x4 = &aegis256x4_aesni_implementation; +#elif HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC +static const aegis256x4_implementation *implementation_256x4 = &aegis256x4_altivec_implementation; +#else +#error "Unsupported architecture" +#endif + +AEGIS_API +size_t +aegis256x4_keybytes(void) +{ + return aegis256x4_KEYBYTES; +} + +AEGIS_API +size_t +aegis256x4_npubbytes(void) +{ + return aegis256x4_NPUBBYTES; +} + +AEGIS_API +size_t +aegis256x4_abytes_min(void) +{ + return aegis256x4_ABYTES_MIN; +} + +AEGIS_API +size_t +aegis256x4_abytes_max(void) +{ + return aegis256x4_ABYTES_MAX; +} + +AEGIS_API +size_t +aegis256x4_tailbytes_max(void) +{ + return aegis256x4_TAILBYTES_MAX; +} + +AEGIS_API +int +aegis256x4_encrypt_detached(uint8_t *c, uint8_t *mac, size_t maclen, const uint8_t *m, size_t mlen, + const uint8_t *ad, size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x4->encrypt_detached(c, mac, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x4_decrypt_detached(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *mac, + size_t maclen, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x4->decrypt_detached(m, c, clen, mac, maclen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x4_encrypt(uint8_t *c, size_t maclen, const uint8_t *m, size_t mlen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + return aegis256x4_encrypt_detached(c, c + mlen, maclen, m, mlen, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x4_decrypt(uint8_t *m, const uint8_t *c, size_t clen, size_t maclen, const uint8_t *ad, + size_t adlen, const uint8_t *npub, const uint8_t *k) +{ + int ret = -1; + + if (clen >= maclen) { + ret = aegis256x4_decrypt_detached(m, c, clen - maclen, c + clen - maclen, maclen, ad, adlen, + npub, k); + } + return ret; +} + +#ifndef AEGIS_OMIT_INCREMENTAL + +AEGIS_API +void +aegis256x4_state_init(aegis256x4_state *st_, const uint8_t *ad, size_t adlen, const uint8_t *npub, + const uint8_t *k) +{ + memset(st_, 0, sizeof *st_); + implementation_256x4->state_init(st_, ad, adlen, npub, k); +} + +AEGIS_API +int +aegis256x4_state_encrypt_update(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + const uint8_t *m, size_t mlen) +{ + return implementation_256x4->state_encrypt_update(st_, c, clen_max, written, m, mlen); +} + +AEGIS_API +int +aegis256x4_state_encrypt_detached_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, + size_t *written, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x4->state_encrypt_detached_final(st_, c, clen_max, written, mac, maclen); +} + +AEGIS_API +int +aegis256x4_state_encrypt_final(aegis256x4_state *st_, uint8_t *c, size_t clen_max, size_t *written, + size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x4->state_encrypt_final(st_, c, clen_max, written, maclen); +} + +AEGIS_API +int +aegis256x4_state_decrypt_detached_update(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *c, size_t clen) +{ + return implementation_256x4->state_decrypt_detached_update(st_, m, mlen_max, written, c, clen); +} + +AEGIS_API +int +aegis256x4_state_decrypt_detached_final(aegis256x4_state *st_, uint8_t *m, size_t mlen_max, + size_t *written, const uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x4->state_decrypt_detached_final(st_, m, mlen_max, written, mac, maclen); +} + +#endif /* AEGIS_OMIT_INCREMENTAL */ + +AEGIS_API +void +aegis256x4_stream(uint8_t *out, size_t len, const uint8_t *npub, const uint8_t *k) +{ + implementation_256x4->stream(out, len, npub, k); +} + +AEGIS_API +void +aegis256x4_encrypt_unauthenticated(uint8_t *c, const uint8_t *m, size_t mlen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_256x4->encrypt_unauthenticated(c, m, mlen, npub, k); +} + +AEGIS_API +void +aegis256x4_decrypt_unauthenticated(uint8_t *m, const uint8_t *c, size_t clen, const uint8_t *npub, + const uint8_t *k) +{ + implementation_256x4->decrypt_unauthenticated(m, c, clen, npub, k); +} + +#ifndef AEGIS_OMIT_MAC_API + +AEGIS_API +void +aegis256x4_mac_init(aegis256x4_mac_state *st_, const uint8_t *k, const uint8_t *npub) +{ + implementation_256x4->state_mac_init(st_, npub, k); +} + +AEGIS_API +int +aegis256x4_mac_update(aegis256x4_mac_state *st_, const uint8_t *m, size_t mlen) +{ + return implementation_256x4->state_mac_update(st_, m, mlen); +} + +AEGIS_API +int +aegis256x4_mac_final(aegis256x4_mac_state *st_, uint8_t *mac, size_t maclen) +{ + if (maclen != 16 && maclen != 32) { + errno = EINVAL; + return -1; + } + return implementation_256x4->state_mac_final(st_, mac, maclen); +} + +AEGIS_API +int +aegis256x4_mac_verify(aegis256x4_mac_state *st_, const uint8_t *mac, size_t maclen) +{ + uint8_t expected_mac[32]; + + switch (maclen) { + case 16: + implementation_256x4->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_16(expected_mac, mac); + case 32: + implementation_256x4->state_mac_final(st_, expected_mac, maclen); + return aegis_verify_32(expected_mac, mac); + default: + errno = EINVAL; + return -1; + } +} + +AEGIS_API +void +aegis256x4_mac_reset(aegis256x4_mac_state *st_) +{ + implementation_256x4->state_mac_reset(st_); +} + +AEGIS_API +void +aegis256x4_mac_state_clone(aegis256x4_mac_state *dst, const aegis256x4_mac_state *src) +{ + implementation_256x4->state_mac_clone(dst, src); +} + +#endif /* AEGIS_OMIT_MAC_API */ + +AEGIS_PRIVATE +int +aegis256x4_pick_best_implementation(void) +{ + implementation_256x4 = &aegis256x4_soft_implementation; + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NEON + if (aegis_runtime_has_armcrypto()) { + implementation_256x4 = &aegis256x4_armcrypto_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_NI +# ifdef HAVE_VAESINTRIN_H + if (aegis_runtime_has_vaes() && aegis_runtime_has_avx512f()) { + implementation_256x4 = &aegis256x4_avx512_implementation; + return 0; + } + if (aegis_runtime_has_vaes() && aegis_runtime_has_avx2()) { + implementation_256x4 = &aegis256x4_avx2_implementation; + return 0; + } +# endif + if (aegis_runtime_has_aesni() && aegis_runtime_has_avx()) { + implementation_256x4 = &aegis256x4_aesni_implementation; + return 0; + } +#endif + +#if HAS_AEGIS_AES_HARDWARE == AEGIS_AES_HARDWARE_ALTIVEC + if (aegis_runtime_has_altivec()) { + implementation_256x4 = &aegis256x4_altivec_implementation; + return 0; + } +#endif + + return 0; /* LCOV_EXCL_LINE */ +} +/*** End of #include "aegis256x4/aegis256x4.c" ***/ + + +#if defined(__GNUC__) +# pragma GCC pop_options +#endif +/*** End of #include "aegis/libaegis.c" ***/ + +/* #include "argon2/libargon2.c" */ +/*** Begin of #include "argon2/libargon2.c" ***/ +#ifndef ARGON2_API +#define ARGON2_API static +#endif + +#ifndef ARGON2_PRIVATE +#define ARGON2_PRIVATE static +#endif + +#ifndef ARGON2_PUBLIC +#define ARGON2_PUBLIC static +#endif + +#ifndef ARGON2_LOCAL +#define ARGON2_LOCAL static +#endif + +#ifndef BLAKE2B_API +#define BLAKE2B_API static +#endif + +/* #include "src/blake2/blake2b.c" */ +/*** Begin of #include "src/blake2/blake2b.c" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include +#include +#include + +/* #include "blake2.h" */ +/*** Begin of #include "blake2.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef PORTABLE_BLAKE2_H +#define PORTABLE_BLAKE2_H + +/* #include "argon2.h" */ +/*** Begin of #include "argon2.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_H +#define ARGON2_H + +#include +#include +#include + +#if defined(__cplusplus) +extern "C" { +#endif + +/* Symbols visibility control */ +#ifdef A2_VISCTL +#define ARGON2_PUBLIC __attribute__((visibility("default"))) +#define ARGON2_LOCAL __attribute__ ((visibility ("hidden"))) +#elif defined(_MSC_VER) +#ifndef ARGON2_PUBLIC +#define ARGON2_PUBLIC __declspec(dllexport) +#endif +#ifndef ARGON2_LOCAL +#define ARGON2_LOCAL +#endif +#else +#ifndef ARGON2_PUBLIC +#define ARGON2_PUBLIC +#endif +#ifndef ARGON2_LOCAL +#define ARGON2_LOCAL +#endif +#endif + +/* + * Argon2 input parameter restrictions + */ + +/* Minimum and maximum number of lanes (degree of parallelism) */ +#define ARGON2_MIN_LANES UINT32_C(1) +#define ARGON2_MAX_LANES UINT32_C(0xFFFFFF) + +/* Minimum and maximum number of threads */ +#define ARGON2_MIN_THREADS UINT32_C(1) +#define ARGON2_MAX_THREADS UINT32_C(0xFFFFFF) + +/* Number of synchronization points between lanes per pass */ +#define ARGON2_SYNC_POINTS UINT32_C(4) + +/* Minimum and maximum digest size in bytes */ +#define ARGON2_MIN_OUTLEN UINT32_C(4) +#define ARGON2_MAX_OUTLEN UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum number of memory blocks (each of BLOCK_SIZE bytes) */ +#define ARGON2_MIN_MEMORY (2 * ARGON2_SYNC_POINTS) /* 2 blocks per slice */ + +#define ARGON2_MIN(a, b) ((a) < (b) ? (a) : (b)) +/* Max memory size is addressing-space/2, topping at 2^32 blocks (4 TB) */ +#define ARGON2_MAX_MEMORY_BITS \ + ARGON2_MIN(UINT32_C(32), (sizeof(void *) * CHAR_BIT - 10 - 1)) +#define ARGON2_MAX_MEMORY \ + ARGON2_MIN(UINT32_C(0xFFFFFFFF), UINT64_C(1) << ARGON2_MAX_MEMORY_BITS) + +/* Minimum and maximum number of passes */ +#define ARGON2_MIN_TIME UINT32_C(1) +#define ARGON2_MAX_TIME UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum password length in bytes */ +#define ARGON2_MIN_PWD_LENGTH UINT32_C(0) +#define ARGON2_MAX_PWD_LENGTH UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum associated data length in bytes */ +#define ARGON2_MIN_AD_LENGTH UINT32_C(0) +#define ARGON2_MAX_AD_LENGTH UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum salt length in bytes */ +#define ARGON2_MIN_SALT_LENGTH UINT32_C(8) +#define ARGON2_MAX_SALT_LENGTH UINT32_C(0xFFFFFFFF) + +/* Minimum and maximum key length in bytes */ +#define ARGON2_MIN_SECRET UINT32_C(0) +#define ARGON2_MAX_SECRET UINT32_C(0xFFFFFFFF) + +/* Flags to determine which fields are securely wiped (default = no wipe). */ +#define ARGON2_DEFAULT_FLAGS UINT32_C(0) +#define ARGON2_FLAG_CLEAR_PASSWORD (UINT32_C(1) << 0) +#define ARGON2_FLAG_CLEAR_SECRET (UINT32_C(1) << 1) + +/* Global flag to determine if we are wiping internal memory buffers. This flag + * is defined in core.c and defaults to 1 (wipe internal memory). */ +extern int FLAG_clear_internal_memory; + +/* Error codes */ +typedef enum Argon2_ErrorCodes { + ARGON2_OK = 0, + + ARGON2_OUTPUT_PTR_NULL = -1, + + ARGON2_OUTPUT_TOO_SHORT = -2, + ARGON2_OUTPUT_TOO_LONG = -3, + + ARGON2_PWD_TOO_SHORT = -4, + ARGON2_PWD_TOO_LONG = -5, + + ARGON2_SALT_TOO_SHORT = -6, + ARGON2_SALT_TOO_LONG = -7, + + ARGON2_AD_TOO_SHORT = -8, + ARGON2_AD_TOO_LONG = -9, + + ARGON2_SECRET_TOO_SHORT = -10, + ARGON2_SECRET_TOO_LONG = -11, + + ARGON2_TIME_TOO_SMALL = -12, + ARGON2_TIME_TOO_LARGE = -13, + + ARGON2_MEMORY_TOO_LITTLE = -14, + ARGON2_MEMORY_TOO_MUCH = -15, + + ARGON2_LANES_TOO_FEW = -16, + ARGON2_LANES_TOO_MANY = -17, + + ARGON2_PWD_PTR_MISMATCH = -18, /* NULL ptr with non-zero length */ + ARGON2_SALT_PTR_MISMATCH = -19, /* NULL ptr with non-zero length */ + ARGON2_SECRET_PTR_MISMATCH = -20, /* NULL ptr with non-zero length */ + ARGON2_AD_PTR_MISMATCH = -21, /* NULL ptr with non-zero length */ + + ARGON2_MEMORY_ALLOCATION_ERROR = -22, + + ARGON2_FREE_MEMORY_CBK_NULL = -23, + ARGON2_ALLOCATE_MEMORY_CBK_NULL = -24, + + ARGON2_INCORRECT_PARAMETER = -25, + ARGON2_INCORRECT_TYPE = -26, + + ARGON2_OUT_PTR_MISMATCH = -27, + + ARGON2_THREADS_TOO_FEW = -28, + ARGON2_THREADS_TOO_MANY = -29, + + ARGON2_MISSING_ARGS = -30, + + ARGON2_ENCODING_FAIL = -31, + + ARGON2_DECODING_FAIL = -32, + + ARGON2_THREAD_FAIL = -33, + + ARGON2_DECODING_LENGTH_FAIL = -34, + + ARGON2_VERIFY_MISMATCH = -35 +} argon2_error_codes; + +/* Memory allocator types --- for external allocation */ +typedef int (*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate); +typedef void (*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate); + +/* Argon2 external data structures */ + +/* + ***** + * Context: structure to hold Argon2 inputs: + * output array and its length, + * password and its length, + * salt and its length, + * secret and its length, + * associated data and its length, + * number of passes, amount of used memory (in KBytes, can be rounded up a bit) + * number of parallel threads that will be run. + * All the parameters above affect the output hash value. + * Additionally, two function pointers can be provided to allocate and + * deallocate the memory (if NULL, memory will be allocated internally). + * Also, three flags indicate whether to erase password, secret as soon as they + * are pre-hashed (and thus not needed anymore), and the entire memory + ***** + * Simplest situation: you have output array out[8], password is stored in + * pwd[32], salt is stored in salt[16], you do not have keys nor associated + * data. You need to spend 1 GB of RAM and you run 5 passes of Argon2d with + * 4 parallel lanes. + * You want to erase the password, but you're OK with last pass not being + * erased. You want to use the default memory allocator. + * Then you initialize: + Argon2_Context(out,8,pwd,32,salt,16,NULL,0,NULL,0,5,1<<20,4,4,NULL,NULL,true,false,false,false) + */ +typedef struct Argon2_Context { + uint8_t *out; /* output array */ + uint32_t outlen; /* digest length */ + + uint8_t *pwd; /* password array */ + uint32_t pwdlen; /* password length */ + + uint8_t *salt; /* salt array */ + uint32_t saltlen; /* salt length */ + + uint8_t *secret; /* key array */ + uint32_t secretlen; /* key length */ + + uint8_t *ad; /* associated data array */ + uint32_t adlen; /* associated data length */ + + uint32_t t_cost; /* number of passes */ + uint32_t m_cost; /* amount of memory requested (KB) */ + uint32_t lanes; /* number of lanes */ + uint32_t threads; /* maximum number of threads */ + + uint32_t version; /* version number */ + + allocate_fptr allocate_cbk; /* pointer to memory allocator */ + deallocate_fptr free_cbk; /* pointer to memory deallocator */ + + uint32_t flags; /* array of bool options */ +} argon2_context; + +/* Argon2 primitive type */ +typedef enum Argon2_type { + Argon2_d = 0, + Argon2_i = 1, + Argon2_id = 2 +} argon2_type; + +/* Version of the algorithm */ +typedef enum Argon2_version { + ARGON2_VERSION_10 = 0x10, + ARGON2_VERSION_13 = 0x13, + ARGON2_VERSION_NUMBER = ARGON2_VERSION_13 +} argon2_version; + +/* + * Function that gives the string representation of an argon2_type. + * @param type The argon2_type that we want the string for + * @param uppercase Whether the string should have the first letter uppercase + * @return NULL if invalid type, otherwise the string representation. + */ +ARGON2_PUBLIC const char *argon2_type2string(argon2_type type, int uppercase); + +/* + * Function that performs memory-hard hashing with certain degree of parallelism + * @param context Pointer to the Argon2 internal structure + * @return Error code if smth is wrong, ARGON2_OK otherwise + */ +ARGON2_PUBLIC int argon2_ctx(argon2_context *context, argon2_type type); + +/** + * Hashes a password with Argon2i, producing an encoded hash + * @param t_cost Number of iterations + * @param m_cost Sets memory usage to m_cost kibibytes + * @param parallelism Number of threads and compute lanes + * @param pwd Pointer to password + * @param pwdlen Password size in bytes + * @param salt Pointer to salt + * @param saltlen Salt size in bytes + * @param hashlen Desired length of the hash in bytes + * @param encoded Buffer where to write the encoded hash + * @param encodedlen Size of the buffer (thus max size of the encoded hash) + * @pre Different parallelism levels will give different results + * @pre Returns ARGON2_OK if successful + */ +ARGON2_PUBLIC int argon2i_hash_encoded(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, + const void *pwd, const size_t pwdlen, + const void *salt, const size_t saltlen, + const size_t hashlen, char *encoded, + const size_t encodedlen); + +/** + * Hashes a password with Argon2i, producing a raw hash at @hash + * @param t_cost Number of iterations + * @param m_cost Sets memory usage to m_cost kibibytes + * @param parallelism Number of threads and compute lanes + * @param pwd Pointer to password + * @param pwdlen Password size in bytes + * @param salt Pointer to salt + * @param saltlen Salt size in bytes + * @param hash Buffer where to write the raw hash - updated by the function + * @param hashlen Desired length of the hash in bytes + * @pre Different parallelism levels will give different results + * @pre Returns ARGON2_OK if successful + */ +ARGON2_PUBLIC int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen); + +ARGON2_PUBLIC int argon2d_hash_encoded(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, + const void *pwd, const size_t pwdlen, + const void *salt, const size_t saltlen, + const size_t hashlen, char *encoded, + const size_t encodedlen); + +ARGON2_PUBLIC int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen); + +ARGON2_PUBLIC int argon2id_hash_encoded(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, + const void *pwd, const size_t pwdlen, + const void *salt, const size_t saltlen, + const size_t hashlen, char *encoded, + const size_t encodedlen); + +ARGON2_PUBLIC int argon2id_hash_raw(const uint32_t t_cost, + const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen); + +/* generic function underlying the above ones */ +ARGON2_PUBLIC int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen, char *encoded, + const size_t encodedlen, argon2_type type, + const uint32_t version); + +/** + * Verifies a password against an encoded string + * Encoded string is restricted as in validate_inputs() + * @param encoded String encoding parameters, salt, hash + * @param pwd Pointer to password + * @pre Returns ARGON2_OK if successful + */ +ARGON2_PUBLIC int argon2i_verify(const char *encoded, const void *pwd, + const size_t pwdlen); + +ARGON2_PUBLIC int argon2d_verify(const char *encoded, const void *pwd, + const size_t pwdlen); + +ARGON2_PUBLIC int argon2id_verify(const char *encoded, const void *pwd, + const size_t pwdlen); + +/* generic function underlying the above ones */ +ARGON2_PUBLIC int argon2_verify(const char *encoded, const void *pwd, + const size_t pwdlen, argon2_type type); + +/** + * Argon2d: Version of Argon2 that picks memory blocks depending + * on the password and salt. Only for side-channel-free + * environment!! + ***** + * @param context Pointer to current Argon2 context + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2d_ctx(argon2_context *context); + +/** + * Argon2i: Version of Argon2 that picks memory blocks + * independent on the password and salt. Good for side-channels, + * but worse w.r.t. tradeoff attacks if only one pass is used. + ***** + * @param context Pointer to current Argon2 context + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2i_ctx(argon2_context *context); + +/** + * Argon2id: Version of Argon2 where the first half-pass over memory is + * password-independent, the rest are password-dependent (on the password and + * salt). OK against side channels (they reduce to 1/2-pass Argon2i), and + * better with w.r.t. tradeoff attacks (similar to Argon2d). + ***** + * @param context Pointer to current Argon2 context + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2id_ctx(argon2_context *context); + +/** + * Verify if a given password is correct for Argon2d hashing + * @param context Pointer to current Argon2 context + * @param hash The password hash to verify. The length of the hash is + * specified by the context outlen member + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2d_verify_ctx(argon2_context *context, const char *hash); + +/** + * Verify if a given password is correct for Argon2i hashing + * @param context Pointer to current Argon2 context + * @param hash The password hash to verify. The length of the hash is + * specified by the context outlen member + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2i_verify_ctx(argon2_context *context, const char *hash); + +/** + * Verify if a given password is correct for Argon2id hashing + * @param context Pointer to current Argon2 context + * @param hash The password hash to verify. The length of the hash is + * specified by the context outlen member + * @return Zero if successful, a non zero error code otherwise + */ +ARGON2_PUBLIC int argon2id_verify_ctx(argon2_context *context, + const char *hash); + +/* generic function underlying the above ones */ +ARGON2_PUBLIC int argon2_verify_ctx(argon2_context *context, const char *hash, + argon2_type type); + +/** + * Get the associated error message for given error code + * @return The error message associated with the given error code + */ +ARGON2_PUBLIC const char *argon2_error_message(int error_code); + +/** + * Returns the encoded hash length for the given input parameters + * @param t_cost Number of iterations + * @param m_cost Memory usage in kibibytes + * @param parallelism Number of threads; used to compute lanes + * @param saltlen Salt size in bytes + * @param hashlen Hash size in bytes + * @param type The argon2_type that we want the encoded length for + * @return The encoded hash length in bytes + */ +ARGON2_PUBLIC size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, + uint32_t parallelism, uint32_t saltlen, + uint32_t hashlen, argon2_type type); + +#if defined(__cplusplus) +} +#endif + +#endif +/*** End of #include "argon2.h" ***/ + + +#if defined(__cplusplus) +extern "C" { +#endif + +enum blake2b_constant { + BLAKE2B_BLOCKBYTES = 128, + BLAKE2B_OUTBYTES = 64, + BLAKE2B_KEYBYTES = 64, + BLAKE2B_SALTBYTES = 16, + BLAKE2B_PERSONALBYTES = 16 +}; + +#pragma pack(push, 1) +typedef struct __blake2b_param { + uint8_t digest_length; /* 1 */ + uint8_t key_length; /* 2 */ + uint8_t fanout; /* 3 */ + uint8_t depth; /* 4 */ + uint32_t leaf_length; /* 8 */ + uint64_t node_offset; /* 16 */ + uint8_t node_depth; /* 17 */ + uint8_t inner_length; /* 18 */ + uint8_t reserved[14]; /* 32 */ + uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */ + uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */ +} blake2b_param; +#pragma pack(pop) + +typedef struct __blake2b_state { + uint64_t h[8]; + uint64_t t[2]; + uint64_t f[2]; + uint8_t buf[BLAKE2B_BLOCKBYTES]; + unsigned buflen; + unsigned outlen; + uint8_t last_node; +} blake2b_state; + +/* Ensure param structs have not been wrongly padded */ +/* Poor man's static_assert */ +enum { + blake2_size_check_0 = 1 / !!(CHAR_BIT == 8), + blake2_size_check_2 = + 1 / !!(sizeof(blake2b_param) == sizeof(uint64_t) * CHAR_BIT) +}; + +/* Streaming API */ +ARGON2_LOCAL int blake2b_init(blake2b_state *S, size_t outlen); +ARGON2_LOCAL int blake2b_init_key(blake2b_state *S, size_t outlen, const void *key, + size_t keylen); +ARGON2_LOCAL int blake2b_init_param(blake2b_state *S, const blake2b_param *P); +ARGON2_LOCAL int blake2b_update(blake2b_state *S, const void *in, size_t inlen); +ARGON2_LOCAL int blake2b_final(blake2b_state *S, void *out, size_t outlen); + +/* Simple API */ +ARGON2_LOCAL int blake2b(void *out, size_t outlen, const void *in, size_t inlen, + const void *key, size_t keylen); + +/* Argon2 Team - Begin Code */ +ARGON2_LOCAL int blake2b_long(void *out, size_t outlen, const void *in, size_t inlen); +/* Argon2 Team - End Code */ + +#if defined(__cplusplus) +} +#endif + +#endif +/*** End of #include "blake2.h" ***/ + +/* #include "blake2-impl.h" */ +/*** Begin of #include "blake2-impl.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef PORTABLE_BLAKE2_IMPL_H +#define PORTABLE_BLAKE2_IMPL_H + +#include +#include + +#ifdef _WIN32 +#define BLAKE2_INLINE __inline +#elif defined(__GNUC__) || defined(__clang__) +#define BLAKE2_INLINE __inline__ +#else +#define BLAKE2_INLINE +#endif + +/* Argon2 Team - Begin Code */ +/* + Not an exhaustive list, but should cover the majority of modern platforms + Additionally, the code will always be correct---this is only a performance + tweak. +*/ +#if (defined(__BYTE_ORDER__) && \ + (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ + defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || defined(__MIPSEL__) || \ + defined(__AARCH64EL__) || defined(__amd64__) || defined(__i386__) || \ + defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || \ + defined(_M_ARM) +#define NATIVE_LITTLE_ENDIAN +#endif +/* Argon2 Team - End Code */ + +static BLAKE2_INLINE uint32_t _blake2b_load32(const void *src) { +#if defined(NATIVE_LITTLE_ENDIAN) + uint32_t w; + memcpy(&w, src, sizeof w); + return w; +#else + const uint8_t *p = (const uint8_t *)src; + uint32_t w = *p++; + w |= (uint32_t)(*p++) << 8; + w |= (uint32_t)(*p++) << 16; + w |= (uint32_t)(*p++) << 24; + return w; +#endif +} + +static BLAKE2_INLINE uint64_t _blake2b_load64(const void *src) { +#if defined(NATIVE_LITTLE_ENDIAN) + uint64_t w; + memcpy(&w, src, sizeof w); + return w; +#else + const uint8_t *p = (const uint8_t *)src; + uint64_t w = *p++; + w |= (uint64_t)(*p++) << 8; + w |= (uint64_t)(*p++) << 16; + w |= (uint64_t)(*p++) << 24; + w |= (uint64_t)(*p++) << 32; + w |= (uint64_t)(*p++) << 40; + w |= (uint64_t)(*p++) << 48; + w |= (uint64_t)(*p++) << 56; + return w; +#endif +} + +static BLAKE2_INLINE void _blake2b_store32(void *dst, uint32_t w) { +#if defined(NATIVE_LITTLE_ENDIAN) + memcpy(dst, &w, sizeof w); +#else + uint8_t *p = (uint8_t *)dst; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; +#endif +} + +static BLAKE2_INLINE void _blake2b_store64(void *dst, uint64_t w) { +#if defined(NATIVE_LITTLE_ENDIAN) + memcpy(dst, &w, sizeof w); +#else + uint8_t *p = (uint8_t *)dst; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; +#endif +} + +static BLAKE2_INLINE uint64_t _blake2b_load48(const void *src) { + const uint8_t *p = (const uint8_t *)src; + uint64_t w = *p++; + w |= (uint64_t)(*p++) << 8; + w |= (uint64_t)(*p++) << 16; + w |= (uint64_t)(*p++) << 24; + w |= (uint64_t)(*p++) << 32; + w |= (uint64_t)(*p++) << 40; + return w; +} + +static BLAKE2_INLINE void _blake2b_store48(void *dst, uint64_t w) { + uint8_t *p = (uint8_t *)dst; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; + w >>= 8; + *p++ = (uint8_t)w; +} + +static BLAKE2_INLINE uint32_t _blake2b_rotr32(const uint32_t w, const unsigned c) { + return (w >> c) | (w << (32 - c)); +} + +static BLAKE2_INLINE uint64_t _blake2b_rotr64(const uint64_t w, const unsigned c) { + return (w >> c) | (w << (64 - c)); +} + +ARGON2_PRIVATE +void _argon2_clear_internal_memory(void *v, size_t n); + +#endif +/*** End of #include "blake2-impl.h" ***/ + + +static const uint64_t blake2b_IV[8] = { + UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b), + UINT64_C(0x3c6ef372fe94f82b), UINT64_C(0xa54ff53a5f1d36f1), + UINT64_C(0x510e527fade682d1), UINT64_C(0x9b05688c2b3e6c1f), + UINT64_C(0x1f83d9abfb41bd6b), UINT64_C(0x5be0cd19137e2179)}; + +static const unsigned int blake2b_sigma[12][16] = { + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3}, + {11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4}, + {7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8}, + {9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13}, + {2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9}, + {12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11}, + {13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10}, + {6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5}, + {10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3}, +}; + +static BLAKE2_INLINE void blake2b_set_lastnode(blake2b_state *BS) { + BS->f[1] = (uint64_t)-1; +} + +static BLAKE2_INLINE void blake2b_set_lastblock(blake2b_state *BS) { + if (BS->last_node) { + blake2b_set_lastnode(BS); + } + BS->f[0] = (uint64_t)-1; +} + +static BLAKE2_INLINE void blake2b_increment_counter(blake2b_state *BS, + uint64_t inc) { + BS->t[0] += inc; + BS->t[1] += (BS->t[0] < inc); +} + +static BLAKE2_INLINE void blake2b_invalidate_state(blake2b_state *BS) { + _argon2_clear_internal_memory(BS, sizeof(*BS)); /* wipe */ + blake2b_set_lastblock(BS); /* invalidate for further use */ +} + +static BLAKE2_INLINE void blake2b_init0(blake2b_state *BS) { + memset(BS, 0, sizeof(*BS)); + memcpy(BS->h, blake2b_IV, sizeof(BS->h)); +} + +BLAKE2B_API +int blake2b_init_param(blake2b_state *BS, const blake2b_param *BP) { + const unsigned char *p = (const unsigned char *)BP; + unsigned int i; + + if (NULL == BP || NULL == BS) { + return -1; + } + + blake2b_init0(BS); + /* IV XOR Parameter Block */ + for (i = 0; i < 8; ++i) { + BS->h[i] ^= _blake2b_load64(&p[i * sizeof(BS->h[i])]); + } + BS->outlen = BP->digest_length; + return 0; +} + +/* Sequential blake2b initialization */ +BLAKE2B_API +int blake2b_init(blake2b_state *BS, size_t outlen) { + blake2b_param BP; + + if (BS == NULL) { + return -1; + } + + if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) { + blake2b_invalidate_state(BS); + return -1; + } + + /* Setup Parameter Block for unkeyed BLAKE2 */ + BP.digest_length = (uint8_t)outlen; + BP.key_length = 0; + BP.fanout = 1; + BP.depth = 1; + BP.leaf_length = 0; + BP.node_offset = 0; + BP.node_depth = 0; + BP.inner_length = 0; + memset(BP.reserved, 0, sizeof(BP.reserved)); + memset(BP.salt, 0, sizeof(BP.salt)); + memset(BP.personal, 0, sizeof(BP.personal)); + + return blake2b_init_param(BS, &BP); +} + +BLAKE2B_API +int blake2b_init_key(blake2b_state *BS, size_t outlen, const void *key, + size_t keylen) { + blake2b_param BP; + + if (BS == NULL) { + return -1; + } + + if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) { + blake2b_invalidate_state(BS); + return -1; + } + + if ((key == 0) || (keylen == 0) || (keylen > BLAKE2B_KEYBYTES)) { + blake2b_invalidate_state(BS); + return -1; + } + + /* Setup Parameter Block for keyed BLAKE2 */ + BP.digest_length = (uint8_t)outlen; + BP.key_length = (uint8_t)keylen; + BP.fanout = 1; + BP.depth = 1; + BP.leaf_length = 0; + BP.node_offset = 0; + BP.node_depth = 0; + BP.inner_length = 0; + memset(BP.reserved, 0, sizeof(BP.reserved)); + memset(BP.salt, 0, sizeof(BP.salt)); + memset(BP.personal, 0, sizeof(BP.personal)); + + if (blake2b_init_param(BS, &BP) < 0) { + blake2b_invalidate_state(BS); + return -1; + } + + { + uint8_t block[BLAKE2B_BLOCKBYTES]; + memset(block, 0, BLAKE2B_BLOCKBYTES); + memcpy(block, key, keylen); + blake2b_update(BS, block, BLAKE2B_BLOCKBYTES); + /* Burn the key from stack */ + _argon2_clear_internal_memory(block, BLAKE2B_BLOCKBYTES); + } + return 0; +} + +static void blake2b_compress(blake2b_state *BS, const uint8_t *block) { + uint64_t m[16]; + uint64_t v[16]; + unsigned int i, r; + + for (i = 0; i < 16; ++i) { + m[i] = _blake2b_load64(block + i * sizeof(m[i])); + } + + for (i = 0; i < 8; ++i) { + v[i] = BS->h[i]; + } + + v[8] = blake2b_IV[0]; + v[9] = blake2b_IV[1]; + v[10] = blake2b_IV[2]; + v[11] = blake2b_IV[3]; + v[12] = blake2b_IV[4] ^ BS->t[0]; + v[13] = blake2b_IV[5] ^ BS->t[1]; + v[14] = blake2b_IV[6] ^ BS->f[0]; + v[15] = blake2b_IV[7] ^ BS->f[1]; + +#define BLAKE2B_G(r, i, a, b, c, d) \ + do { \ + a = a + b + m[blake2b_sigma[r][2 * i + 0]]; \ + d = _blake2b_rotr64(d ^ a, 32); \ + c = c + d; \ + b = _blake2b_rotr64(b ^ c, 24); \ + a = a + b + m[blake2b_sigma[r][2 * i + 1]]; \ + d = _blake2b_rotr64(d ^ a, 16); \ + c = c + d; \ + b = _blake2b_rotr64(b ^ c, 63); \ + } while ((void)0, 0) + +#define BLAKE2B_ROUND(r) \ + do { \ + BLAKE2B_G(r, 0, v[0], v[4], v[8], v[12]); \ + BLAKE2B_G(r, 1, v[1], v[5], v[9], v[13]); \ + BLAKE2B_G(r, 2, v[2], v[6], v[10], v[14]); \ + BLAKE2B_G(r, 3, v[3], v[7], v[11], v[15]); \ + BLAKE2B_G(r, 4, v[0], v[5], v[10], v[15]); \ + BLAKE2B_G(r, 5, v[1], v[6], v[11], v[12]); \ + BLAKE2B_G(r, 6, v[2], v[7], v[8], v[13]); \ + BLAKE2B_G(r, 7, v[3], v[4], v[9], v[14]); \ + } while ((void)0, 0) + + for (r = 0; r < 12; ++r) { + BLAKE2B_ROUND(r); + } + + for (i = 0; i < 8; ++i) { + BS->h[i] = BS->h[i] ^ v[i] ^ v[i + 8]; + } + +#undef BLAKE2B_G +#undef BLAKE2B_ROUND +} + +BLAKE2B_API +int blake2b_update(blake2b_state *BS, const void *in, size_t inlen) { + const uint8_t *pin = (const uint8_t *)in; + + if (inlen == 0) { + return 0; + } + + /* Sanity check */ + if (BS == NULL || in == NULL) { + return -1; + } + + /* Is this a reused state? */ + if (BS->f[0] != 0) { + return -1; + } + + if (BS->buflen + inlen > BLAKE2B_BLOCKBYTES) { + /* Complete current block */ + size_t left = BS->buflen; + size_t fill = BLAKE2B_BLOCKBYTES - left; + memcpy(&BS->buf[left], pin, fill); + blake2b_increment_counter(BS, BLAKE2B_BLOCKBYTES); + blake2b_compress(BS, BS->buf); + BS->buflen = 0; + inlen -= fill; + pin += fill; + /* Avoid buffer copies when possible */ + while (inlen > BLAKE2B_BLOCKBYTES) { + blake2b_increment_counter(BS, BLAKE2B_BLOCKBYTES); + blake2b_compress(BS, pin); + inlen -= BLAKE2B_BLOCKBYTES; + pin += BLAKE2B_BLOCKBYTES; + } + } + memcpy(&BS->buf[BS->buflen], pin, inlen); + BS->buflen += (unsigned int)inlen; + return 0; +} + +BLAKE2B_API +int blake2b_final(blake2b_state *BS, void *out, size_t outlen) { + uint8_t buffer[BLAKE2B_OUTBYTES] = {0}; + unsigned int i; + + /* Sanity checks */ + if (BS == NULL || out == NULL || outlen < BS->outlen) { + return -1; + } + + /* Is this a reused state? */ + if (BS->f[0] != 0) { + return -1; + } + + blake2b_increment_counter(BS, BS->buflen); + blake2b_set_lastblock(BS); + memset(&BS->buf[BS->buflen], 0, BLAKE2B_BLOCKBYTES - BS->buflen); /* Padding */ + blake2b_compress(BS, BS->buf); + + for (i = 0; i < 8; ++i) { /* Output full hash to temp buffer */ + _blake2b_store64(buffer + sizeof(BS->h[i]) * i, BS->h[i]); + } + + memcpy(out, buffer, BS->outlen); + _argon2_clear_internal_memory(buffer, sizeof(buffer)); + _argon2_clear_internal_memory(BS->buf, sizeof(BS->buf)); + _argon2_clear_internal_memory(BS->h, sizeof(BS->h)); + return 0; +} + +BLAKE2B_API +int blake2b(void *out, size_t outlen, const void *in, size_t inlen, + const void *key, size_t keylen) { + blake2b_state BS; + int ret = -1; + + /* Verify parameters */ + if (NULL == in && inlen > 0) { + goto fail; + } + + if (NULL == out || outlen == 0 || outlen > BLAKE2B_OUTBYTES) { + goto fail; + } + + if ((NULL == key && keylen > 0) || keylen > BLAKE2B_KEYBYTES) { + goto fail; + } + + if (keylen > 0) { + if (blake2b_init_key(&BS, outlen, key, keylen) < 0) { + goto fail; + } + } else { + if (blake2b_init(&BS, outlen) < 0) { + goto fail; + } + } + + if (blake2b_update(&BS, in, inlen) < 0) { + goto fail; + } + ret = blake2b_final(&BS, out, outlen); + +fail: + _argon2_clear_internal_memory(&BS, sizeof(BS)); + return ret; +} + +/* Argon2 Team - Begin Code */ +BLAKE2B_API +int blake2b_long(void *pout, size_t outlen, const void *in, size_t inlen) { + uint8_t *out = (uint8_t *)pout; + blake2b_state blake_state; + uint8_t outlen_bytes[sizeof(uint32_t)] = {0}; + int ret = -1; + + if (outlen > UINT32_MAX) { + goto fail; + } + + /* Ensure little-endian byte order! */ + _blake2b_store32(outlen_bytes, (uint32_t)outlen); + +#define BLAKE2B_TRY(statement) \ + do { \ + ret = statement; \ + if (ret < 0) { \ + goto fail; \ + } \ + } while ((void)0, 0) + + if (outlen <= BLAKE2B_OUTBYTES) { + BLAKE2B_TRY(blake2b_init(&blake_state, outlen)); + BLAKE2B_TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes))); + BLAKE2B_TRY(blake2b_update(&blake_state, in, inlen)); + BLAKE2B_TRY(blake2b_final(&blake_state, out, outlen)); + } else { + uint32_t toproduce; + uint8_t out_buffer[BLAKE2B_OUTBYTES]; + uint8_t in_buffer[BLAKE2B_OUTBYTES]; + BLAKE2B_TRY(blake2b_init(&blake_state, BLAKE2B_OUTBYTES)); + BLAKE2B_TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes))); + BLAKE2B_TRY(blake2b_update(&blake_state, in, inlen)); + BLAKE2B_TRY(blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES)); + memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2); + out += BLAKE2B_OUTBYTES / 2; + toproduce = (uint32_t)outlen - BLAKE2B_OUTBYTES / 2; + + while (toproduce > BLAKE2B_OUTBYTES) { + memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES); + BLAKE2B_TRY(blake2b(out_buffer, BLAKE2B_OUTBYTES, in_buffer, + BLAKE2B_OUTBYTES, NULL, 0)); + memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2); + out += BLAKE2B_OUTBYTES / 2; + toproduce -= BLAKE2B_OUTBYTES / 2; + } + + memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES); + BLAKE2B_TRY(blake2b(out_buffer, toproduce, in_buffer, BLAKE2B_OUTBYTES, NULL, + 0)); + memcpy(out, out_buffer, toproduce); + } +fail: + _argon2_clear_internal_memory(&blake_state, sizeof(blake_state)); + return ret; +#undef BLAKE2B_TRY +} +/* Argon2 Team - End Code */ +/*** End of #include "src/blake2/blake2b.c" ***/ + +/* #include "src/argon2.c" */ +/*** Begin of #include "src/argon2.c" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include +#include +#include + +/* #include "argon2.h" */ + +/* #include "encoding.h" */ +/*** Begin of #include "encoding.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_ENCODING_H +#define ARGON2_ENCODING_H +/* #include "argon2.h" */ + + +#define ARGON2_MAX_DECODED_LANES UINT32_C(255) +#define ARGON2_MIN_DECODED_SALT_LEN UINT32_C(8) +#define ARGON2_MIN_DECODED_OUT_LEN UINT32_C(12) + +/* +* encode an Argon2 hash string into the provided buffer. 'dst_len' +* contains the size, in characters, of the 'dst' buffer; if 'dst_len' +* is less than the number of required characters (including the +* terminating 0), then this function returns ARGON2_ENCODING_ERROR. +* +* on success, ARGON2_OK is returned. +*/ +ARGON2_PRIVATE +int _argon2_encode_string(char *dst, size_t dst_len, argon2_context *ctx, + argon2_type type); + +/* +* Decodes an Argon2 hash string into the provided structure 'ctx'. +* The only fields that must be set prior to this call are ctx.saltlen and +* ctx.outlen (which must be the maximal salt and out length values that are +* allowed), ctx.salt and ctx.out (which must be buffers of the specified +* length), and ctx.pwd and ctx.pwdlen which must hold a valid password. +* +* Invalid input string causes an error. On success, the ctx is valid and all +* fields have been initialized. +* +* Returned value is ARGON2_OK on success, other ARGON2_ codes on error. +*/ +ARGON2_PRIVATE +int _argon2_decode_string(argon2_context *ctx, const char *str, argon2_type type); + +/* Returns the length of the encoded byte stream with length len */ +ARGON2_PRIVATE +size_t _argon2_b64len(uint32_t len); + +/* Returns the length of the encoded number num */ +ARGON2_PRIVATE +size_t _argon2_numlen(uint32_t num); + +#endif +/*** End of #include "encoding.h" ***/ + +/* #include "core.h" */ +/*** Begin of #include "core.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_CORE_H +#define ARGON2_CORE_H + +/* #include "argon2.h" */ + + +#define CONST_CAST(x) (x)(uintptr_t) + +/**********************Argon2 internal constants*******************************/ + +enum argon2_core_constants { + /* Memory block size in bytes */ + ARGON2_BLOCK_SIZE = 1024, + ARGON2_QWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 8, + ARGON2_OWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 16, + ARGON2_HWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 32, + ARGON2_512BIT_WORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 64, + + /* Number of pseudo-random values generated by one call to Blake in Argon2i + to + generate reference block positions */ + ARGON2_ADDRESSES_IN_BLOCK = 128, + + /* Pre-hashing digest length and its extension*/ + ARGON2_PREHASH_DIGEST_LENGTH = 64, + ARGON2_PREHASH_SEED_LENGTH = 72 +}; + +/*************************Argon2 internal data types***********************/ + +/* + * Structure for the (1KB) memory block implemented as 128 64-bit words. + * Memory blocks can be copied, XORed. Internal words can be accessed by [] (no + * bounds checking). + */ +typedef struct block_ { uint64_t v[ARGON2_QWORDS_IN_BLOCK]; } block; + +/*****************Functions that work with the block******************/ + +/* Initialize each byte of the block with @in */ +ARGON2_PRIVATE +void _argon2_init_block_value(block *b, uint8_t in); + +/* Copy block @src to block @dst */ +ARGON2_PRIVATE +void _argon2_copy_block(block *dst, const block *src); + +/* XOR @src onto @dst bytewise */ +ARGON2_PRIVATE +void _argon2_xor_block(block *dst, const block *src); + +/* + * Argon2 instance: memory pointer, number of passes, amount of memory, type, + * and derived values. + * Used to evaluate the number and location of blocks to construct in each + * thread + */ +typedef struct Argon2_instance_t { + block *memory; /* Memory pointer */ + uint32_t version; + uint32_t passes; /* Number of passes */ + uint32_t memory_blocks; /* Number of blocks in memory */ + uint32_t segment_length; + uint32_t lane_length; + uint32_t lanes; + uint32_t threads; + argon2_type type; + int print_internals; /* whether to print the memory blocks */ + argon2_context *context_ptr; /* points back to original context */ +} argon2_instance_t; + +/* + * Argon2 position: where we construct the block right now. Used to distribute + * work between threads. + */ +typedef struct Argon2_position_t { + uint32_t pass; + uint32_t lane; + uint8_t slice; + uint32_t index; +} argon2_position_t; + +/*Struct that holds the inputs for thread handling FillSegment*/ +typedef struct Argon2_thread_data { + argon2_instance_t *instance_ptr; + argon2_position_t pos; +} argon2_thread_data; + +/*************************Argon2 core functions********************************/ + +/* Allocates memory to the given pointer, uses the appropriate allocator as + * specified in the context. Total allocated memory is num*size. + * @param context argon2_context which specifies the allocator + * @param memory pointer to the pointer to the memory + * @param size the size in bytes for each element to be allocated + * @param num the number of elements to be allocated + * @return ARGON2_OK if @memory is a valid pointer and memory is allocated + */ +ARGON2_PRIVATE +int _argon2_allocate_memory(const argon2_context *context, uint8_t **memory, + size_t num, size_t size); + +/* + * Frees memory at the given pointer, uses the appropriate deallocator as + * specified in the context. Also cleans the memory using clear_internal_memory. + * @param context argon2_context which specifies the deallocator + * @param memory pointer to buffer to be freed + * @param size the size in bytes for each element to be deallocated + * @param num the number of elements to be deallocated + */ +ARGON2_PRIVATE +void _argon2_free_memory(const argon2_context *context, uint8_t *memory, + size_t num, size_t size); + +/* Function that securely cleans the memory. This ignores any flags set + * regarding clearing memory. Usually one just calls clear_internal_memory. + * @param mem Pointer to the memory + * @param s Memory size in bytes + */ +ARGON2_PRIVATE +void _argon2_secure_wipe_memory(void *v, size_t n); + +/* Function that securely clears the memory if FLAG_clear_internal_memory is + * set. If the flag isn't set, this function does nothing. + * @param mem Pointer to the memory + * @param s Memory size in bytes + */ +ARGON2_PRIVATE +void _argon2_clear_internal_memory(void *v, size_t n); + +/* + * Computes absolute position of reference block in the lane following a skewed + * distribution and using a pseudo-random value as input + * @param instance Pointer to the current instance + * @param position Pointer to the current position + * @param pseudo_rand 32-bit pseudo-random value used to determine the position + * @param same_lane Indicates if the block will be taken from the current lane. + * If so we can reference the current segment + * @pre All pointers must be valid + */ +ARGON2_PRIVATE +uint32_t _argon2_index_alpha(const argon2_instance_t *instance, + const argon2_position_t *position, uint32_t pseudo_rand, + int same_lane); + +/* + * Function that validates all inputs against predefined restrictions and return + * an error code + * @param context Pointer to current Argon2 context + * @return ARGON2_OK if everything is all right, otherwise one of error codes + * (all defined in + */ +ARGON2_PRIVATE +int _argon2_validate_inputs(const argon2_context *context); + +/* + * Hashes all the inputs into @a blockhash[PREHASH_DIGEST_LENGTH], clears + * password and secret if needed + * @param context Pointer to the Argon2 internal structure containing memory + * pointer, and parameters for time and space requirements. + * @param blockhash Buffer for pre-hashing digest + * @param type Argon2 type + * @pre @a blockhash must have at least @a PREHASH_DIGEST_LENGTH bytes + * allocated + */ +ARGON2_PRIVATE +void _argon2_initial_hash(uint8_t *blockhash, argon2_context *context, + argon2_type type); + +/* + * Function creates first 2 blocks per lane + * @param instance Pointer to the current instance + * @param blockhash Pointer to the pre-hashing digest + * @pre blockhash must point to @a PREHASH_SEED_LENGTH allocated values + */ +ARGON2_PRIVATE +void _argon2_fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance); + +/* + * Function allocates memory, hashes the inputs with Blake, and creates first + * two blocks. Returns the pointer to the main memory with 2 blocks per lane + * initialized + * @param context Pointer to the Argon2 internal structure containing memory + * pointer, and parameters for time and space requirements. + * @param instance Current Argon2 instance + * @return Zero if successful, -1 if memory failed to allocate. @context->state + * will be modified if successful. + */ +ARGON2_PRIVATE +int _argon2_initialize(argon2_instance_t *instance, argon2_context *context); + +/* + * XORing the last block of each lane, hashing it, making the tag. Deallocates + * the memory. + * @param context Pointer to current Argon2 context (use only the out parameters + * from it) + * @param instance Pointer to current instance of Argon2 + * @pre instance->state must point to necessary amount of memory + * @pre context->out must point to outlen bytes of memory + * @pre if context->free_cbk is not NULL, it should point to a function that + * deallocates memory + */ +ARGON2_PRIVATE +void _argon2_finalize(const argon2_context *context, argon2_instance_t *instance); + +/* + * Function that fills the segment using previous segments also from other + * threads + * @param context current context + * @param instance Pointer to the current instance + * @param position Current position + * @pre all block pointers must be valid + */ +ARGON2_PRIVATE +void _argon2_fill_segment(const argon2_instance_t *instance, + argon2_position_t position); + +/* + * Function that fills the entire memory t_cost times based on the first two + * blocks in each lane + * @param instance Pointer to the current instance + * @return ARGON2_OK if successful, @context->state + */ +ARGON2_PRIVATE +int _argon2_fill_memory_blocks(argon2_instance_t *instance); + +#endif +/*** End of #include "core.h" ***/ + + +const char *argon2_type2string(argon2_type type, int uppercase) { + switch (type) { + case Argon2_d: + return uppercase ? "Argon2d" : "argon2d"; + case Argon2_i: + return uppercase ? "Argon2i" : "argon2i"; + case Argon2_id: + return uppercase ? "Argon2id" : "argon2id"; + } + + return NULL; +} + +int argon2_ctx(argon2_context *context, argon2_type type) { + /* 1. Validate all inputs */ + int result = _argon2_validate_inputs(context); + uint32_t memory_blocks, segment_length; + argon2_instance_t instance; + + if (ARGON2_OK != result) { + return result; + } + + if (Argon2_d != type && Argon2_i != type && Argon2_id != type) { + return ARGON2_INCORRECT_TYPE; + } + + /* 2. Align memory size */ + /* Minimum memory_blocks = 8L blocks, where L is the number of lanes */ + memory_blocks = context->m_cost; + + if (memory_blocks < 2 * ARGON2_SYNC_POINTS * context->lanes) { + memory_blocks = 2 * ARGON2_SYNC_POINTS * context->lanes; + } + + segment_length = memory_blocks / (context->lanes * ARGON2_SYNC_POINTS); + /* Ensure that all segments have equal length */ + memory_blocks = segment_length * (context->lanes * ARGON2_SYNC_POINTS); + + instance.version = context->version; + instance.memory = NULL; + instance.passes = context->t_cost; + instance.memory_blocks = memory_blocks; + instance.segment_length = segment_length; + instance.lane_length = segment_length * ARGON2_SYNC_POINTS; + instance.lanes = context->lanes; + instance.threads = context->threads; + instance.type = type; + + if (instance.threads > instance.lanes) { + instance.threads = instance.lanes; + } + + /* 3. Initialization: Hashing inputs, allocating memory, filling first + * blocks + */ + result = _argon2_initialize(&instance, context); + + if (ARGON2_OK != result) { + return result; + } + + /* 4. Filling memory */ + result = _argon2_fill_memory_blocks(&instance); + + if (ARGON2_OK != result) { + return result; + } + /* 5. Finalization */ + _argon2_finalize(context, &instance); + + return ARGON2_OK; +} + +int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, const size_t saltlen, + void *hash, const size_t hashlen, char *encoded, + const size_t encodedlen, argon2_type type, + const uint32_t version){ + + argon2_context context; + int result; + uint8_t *out; + + if (pwdlen > ARGON2_MAX_PWD_LENGTH) { + return ARGON2_PWD_TOO_LONG; + } + + if (saltlen > ARGON2_MAX_SALT_LENGTH) { + return ARGON2_SALT_TOO_LONG; + } + + if (hashlen > ARGON2_MAX_OUTLEN) { + return ARGON2_OUTPUT_TOO_LONG; + } + + if (hashlen < ARGON2_MIN_OUTLEN) { + return ARGON2_OUTPUT_TOO_SHORT; + } + + out = malloc(hashlen); + if (!out) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + context.out = (uint8_t *)out; + context.outlen = (uint32_t)hashlen; + context.pwd = CONST_CAST(uint8_t *)pwd; + context.pwdlen = (uint32_t)pwdlen; + context.salt = CONST_CAST(uint8_t *)salt; + context.saltlen = (uint32_t)saltlen; + context.secret = NULL; + context.secretlen = 0; + context.ad = NULL; + context.adlen = 0; + context.t_cost = t_cost; + context.m_cost = m_cost; + context.lanes = parallelism; + context.threads = parallelism; + context.allocate_cbk = NULL; + context.free_cbk = NULL; + context.flags = ARGON2_DEFAULT_FLAGS; + context.version = version; + + result = argon2_ctx(&context, type); + + if (result != ARGON2_OK) { + _argon2_clear_internal_memory(out, hashlen); + free(out); + return result; + } + + /* if raw hash requested, write it */ + if (hash) { + memcpy(hash, out, hashlen); + } + + /* if encoding requested, write it */ + if (encoded && encodedlen) { + if (_argon2_encode_string(encoded, encodedlen, &context, type) != ARGON2_OK) { + _argon2_clear_internal_memory(out, hashlen); /* wipe buffers if error */ + _argon2_clear_internal_memory(encoded, encodedlen); + free(out); + return ARGON2_ENCODING_FAIL; + } + } + _argon2_clear_internal_memory(out, hashlen); + free(out); + + return ARGON2_OK; +} + +int argon2i_hash_encoded(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, const size_t hashlen, + char *encoded, const size_t encodedlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + NULL, hashlen, encoded, encodedlen, Argon2_i, + ARGON2_VERSION_NUMBER); +} + +int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, const size_t hashlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + hash, hashlen, NULL, 0, Argon2_i, ARGON2_VERSION_NUMBER); +} + +int argon2d_hash_encoded(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, const size_t hashlen, + char *encoded, const size_t encodedlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + NULL, hashlen, encoded, encodedlen, Argon2_d, + ARGON2_VERSION_NUMBER); +} + +int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, const size_t hashlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + hash, hashlen, NULL, 0, Argon2_d, ARGON2_VERSION_NUMBER); +} + +int argon2id_hash_encoded(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, const size_t hashlen, + char *encoded, const size_t encodedlen) { + + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + NULL, hashlen, encoded, encodedlen, Argon2_id, + ARGON2_VERSION_NUMBER); +} + +int argon2id_hash_raw(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, const size_t hashlen) { + return argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, + hash, hashlen, NULL, 0, Argon2_id, + ARGON2_VERSION_NUMBER); +} + +static int argon2_compare(const uint8_t *b1, const uint8_t *b2, size_t len) { + size_t i; + uint8_t d = 0U; + + for (i = 0U; i < len; i++) { + d |= b1[i] ^ b2[i]; + } + return (int)((1 & ((d - 1) >> 8)) - 1); +} + +int argon2_verify(const char *encoded, const void *pwd, const size_t pwdlen, + argon2_type type) { + + argon2_context ctx; + uint8_t *desired_result = NULL; + + int ret = ARGON2_OK; + + size_t encoded_len; + uint32_t max_field_len; + + if (pwdlen > ARGON2_MAX_PWD_LENGTH) { + return ARGON2_PWD_TOO_LONG; + } + + if (encoded == NULL) { + return ARGON2_DECODING_FAIL; + } + + encoded_len = strlen(encoded); + if (encoded_len > UINT32_MAX) { + return ARGON2_DECODING_FAIL; + } + + /* No field can be longer than the encoded length */ + max_field_len = (uint32_t)encoded_len; + + ctx.saltlen = max_field_len; + ctx.outlen = max_field_len; + + ctx.salt = malloc(ctx.saltlen); + ctx.out = malloc(ctx.outlen); + if (!ctx.salt || !ctx.out) { + ret = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + ctx.pwd = (uint8_t *)pwd; + ctx.pwdlen = (uint32_t)pwdlen; + + ret = _argon2_decode_string(&ctx, encoded, type); + if (ret != ARGON2_OK) { + goto fail; + } + + /* Set aside the desired result, and get a new buffer. */ + desired_result = ctx.out; + ctx.out = malloc(ctx.outlen); + if (!ctx.out) { + ret = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + ret = argon2_verify_ctx(&ctx, (char *)desired_result, type); + if (ret != ARGON2_OK) { + goto fail; + } + +fail: + free(ctx.salt); + free(ctx.out); + free(desired_result); + + return ret; +} + +int argon2i_verify(const char *encoded, const void *pwd, const size_t pwdlen) { + + return argon2_verify(encoded, pwd, pwdlen, Argon2_i); +} + +int argon2d_verify(const char *encoded, const void *pwd, const size_t pwdlen) { + + return argon2_verify(encoded, pwd, pwdlen, Argon2_d); +} + +int argon2id_verify(const char *encoded, const void *pwd, const size_t pwdlen) { + + return argon2_verify(encoded, pwd, pwdlen, Argon2_id); +} + +int argon2d_ctx(argon2_context *context) { + return argon2_ctx(context, Argon2_d); +} + +int argon2i_ctx(argon2_context *context) { + return argon2_ctx(context, Argon2_i); +} + +int argon2id_ctx(argon2_context *context) { + return argon2_ctx(context, Argon2_id); +} + +int argon2_verify_ctx(argon2_context *context, const char *hash, + argon2_type type) { + int ret = argon2_ctx(context, type); + if (ret != ARGON2_OK) { + return ret; + } + + if (argon2_compare((uint8_t *)hash, context->out, context->outlen)) { + return ARGON2_VERIFY_MISMATCH; + } + + return ARGON2_OK; +} + +int argon2d_verify_ctx(argon2_context *context, const char *hash) { + return argon2_verify_ctx(context, hash, Argon2_d); +} + +int argon2i_verify_ctx(argon2_context *context, const char *hash) { + return argon2_verify_ctx(context, hash, Argon2_i); +} + +int argon2id_verify_ctx(argon2_context *context, const char *hash) { + return argon2_verify_ctx(context, hash, Argon2_id); +} + +const char *argon2_error_message(int error_code) { + switch (error_code) { + case ARGON2_OK: + return "OK"; + case ARGON2_OUTPUT_PTR_NULL: + return "Output pointer is NULL"; + case ARGON2_OUTPUT_TOO_SHORT: + return "Output is too short"; + case ARGON2_OUTPUT_TOO_LONG: + return "Output is too long"; + case ARGON2_PWD_TOO_SHORT: + return "Password is too short"; + case ARGON2_PWD_TOO_LONG: + return "Password is too long"; + case ARGON2_SALT_TOO_SHORT: + return "Salt is too short"; + case ARGON2_SALT_TOO_LONG: + return "Salt is too long"; + case ARGON2_AD_TOO_SHORT: + return "Associated data is too short"; + case ARGON2_AD_TOO_LONG: + return "Associated data is too long"; + case ARGON2_SECRET_TOO_SHORT: + return "Secret is too short"; + case ARGON2_SECRET_TOO_LONG: + return "Secret is too long"; + case ARGON2_TIME_TOO_SMALL: + return "Time cost is too small"; + case ARGON2_TIME_TOO_LARGE: + return "Time cost is too large"; + case ARGON2_MEMORY_TOO_LITTLE: + return "Memory cost is too small"; + case ARGON2_MEMORY_TOO_MUCH: + return "Memory cost is too large"; + case ARGON2_LANES_TOO_FEW: + return "Too few lanes"; + case ARGON2_LANES_TOO_MANY: + return "Too many lanes"; + case ARGON2_PWD_PTR_MISMATCH: + return "Password pointer is NULL, but password length is not 0"; + case ARGON2_SALT_PTR_MISMATCH: + return "Salt pointer is NULL, but salt length is not 0"; + case ARGON2_SECRET_PTR_MISMATCH: + return "Secret pointer is NULL, but secret length is not 0"; + case ARGON2_AD_PTR_MISMATCH: + return "Associated data pointer is NULL, but ad length is not 0"; + case ARGON2_MEMORY_ALLOCATION_ERROR: + return "Memory allocation error"; + case ARGON2_FREE_MEMORY_CBK_NULL: + return "The free memory callback is NULL"; + case ARGON2_ALLOCATE_MEMORY_CBK_NULL: + return "The allocate memory callback is NULL"; + case ARGON2_INCORRECT_PARAMETER: + return "Argon2_Context context is NULL"; + case ARGON2_INCORRECT_TYPE: + return "There is no such version of Argon2"; + case ARGON2_OUT_PTR_MISMATCH: + return "Output pointer mismatch"; + case ARGON2_THREADS_TOO_FEW: + return "Not enough threads"; + case ARGON2_THREADS_TOO_MANY: + return "Too many threads"; + case ARGON2_MISSING_ARGS: + return "Missing arguments"; + case ARGON2_ENCODING_FAIL: + return "Encoding failed"; + case ARGON2_DECODING_FAIL: + return "Decoding failed"; + case ARGON2_THREAD_FAIL: + return "Threading failure"; + case ARGON2_DECODING_LENGTH_FAIL: + return "Some of encoded parameters are too long or too short"; + case ARGON2_VERIFY_MISMATCH: + return "The password does not match the supplied hash"; + default: + return "Unknown error code"; + } +} + +size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, uint32_t parallelism, + uint32_t saltlen, uint32_t hashlen, argon2_type type) { + return strlen("$$v=$m=,t=,p=$$") + strlen(argon2_type2string(type, 0)) + + _argon2_numlen(t_cost) + _argon2_numlen(m_cost) + _argon2_numlen(parallelism) + + _argon2_b64len(saltlen) + _argon2_b64len(hashlen) + _argon2_numlen(ARGON2_VERSION_NUMBER) + 1; +} +/*** End of #include "src/argon2.c" ***/ + +/* #include "src/core.c" */ +/*** Begin of #include "src/core.c" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +/*For memory wiping*/ +#ifdef _WIN32 +#include +#include /* For SecureZeroMemory */ +#endif +#if defined __STDC_LIB_EXT1__ +#define __STDC_WANT_LIB_EXT1__ 1 +#endif +#define VC_GE_2005(version) (version >= 1400) + +/* for explicit_bzero() on glibc */ +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif + +#include +#include +#include + +/* #include "core.h" */ + +/* #include "thread.h" */ +/*** Begin of #include "thread.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_THREAD_H +#define ARGON2_THREAD_H + +#if !defined(ARGON2_NO_THREADS) + +/* + Here we implement an abstraction layer for the simple requirements + of the Argon2 code. We only require 3 primitives---thread creation, + joining, and termination---so full emulation of the pthreads API + is unwarranted. Currently we wrap pthreads and Win32 threads. + + The API defines 2 types: the function pointer type, + argon2_thread_func_t, + and the type of the thread handle---argon2_thread_handle_t. +*/ +#if defined(_WIN32) +#include +typedef unsigned(__stdcall *argon2_thread_func_t)(void *); +typedef uintptr_t argon2_thread_handle_t; +#else +#include +typedef void *(*argon2_thread_func_t)(void *); +typedef pthread_t argon2_thread_handle_t; +#endif + +/* Creates a thread + * @param handle pointer to a thread handle, which is the output of this + * function. Must not be NULL. + * @param func A function pointer for the thread's entry point. Must not be + * NULL. + * @param args Pointer that is passed as an argument to @func. May be NULL. + * @return 0 if @handle and @func are valid pointers and a thread is successfully + * created. + */ +ARGON2_PRIVATE +int argon2_thread_create(argon2_thread_handle_t *handle, + argon2_thread_func_t func, void *args); + +/* Waits for a thread to terminate + * @param handle Handle to a thread created with argon2_thread_create. + * @return 0 if @handle is a valid handle, and joining completed successfully. +*/ +ARGON2_PRIVATE +int argon2_thread_join(argon2_thread_handle_t handle); + +/* Terminate the current thread. Must be run inside a thread created by + * argon2_thread_create. +*/ +ARGON2_PRIVATE +void argon2_thread_exit(void); + +#endif /* ARGON2_NO_THREADS */ +#endif +/*** End of #include "thread.h" ***/ + +/* #include "blake2/blake2.h" */ + +/* #include "blake2/blake2-impl.h" */ + + +#ifdef GENKAT +/* #include "genkat.h" */ +/*** Begin of #include "genkat.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef ARGON2_KAT_H +#define ARGON2_KAT_H + +/* #include "core.h" */ + + +/* + * Initial KAT function that prints the inputs to the file + * @param blockhash Array that contains pre-hashing digest + * @param context Holds inputs + * @param type Argon2 type + * @pre blockhash must point to INPUT_INITIAL_HASH_LENGTH bytes + * @pre context member pointers must point to allocated memory of size according + * to the length values + */ +void initial_kat(const uint8_t *blockhash, const argon2_context *context, + argon2_type type); + +/* + * Function that prints the output tag + * @param out output array pointer + * @param outlen digest length + * @pre out must point to @a outlen bytes + **/ +void print_tag(const void *out, uint32_t outlen); + +/* + * Function that prints the internal state at given moment + * @param instance pointer to the current instance + * @param pass current pass number + * @pre instance must have necessary memory allocated + **/ +void internal_kat(const argon2_instance_t *instance, uint32_t pass); + +#endif +/*** End of #include "genkat.h" ***/ + +#endif + +#if defined(__clang__) +#if __has_attribute(optnone) +#define NOT_OPTIMIZED __attribute__((optnone)) +#endif +#elif defined(__GNUC__) +#ifndef GCC_VERSION +#define GCC_VERSION \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif +#if GCC_VERSION >= 40400 +#define NOT_OPTIMIZED __attribute__((optimize("O0"))) +#endif +#endif +#ifndef NOT_OPTIMIZED +#define NOT_OPTIMIZED +#endif + +/***************Instance and Position constructors**********/ +ARGON2_PRIVATE +void _argon2_init_block_value(block *b, uint8_t in) { memset(b->v, in, sizeof(b->v)); } + +ARGON2_PRIVATE +void _argon2_copy_block(block *dst, const block *src) { + memcpy(dst->v, src->v, sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK); +} + +ARGON2_PRIVATE +void _argon2_xor_block(block *dst, const block *src) { + int i; + for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) { + dst->v[i] ^= src->v[i]; + } +} + +static void _argon2_load_block(block *dst, const void *input) { + unsigned i; + for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) { + dst->v[i] = _blake2b_load64((const uint8_t *)input + i * sizeof(dst->v[i])); + } +} + +static void _argon2_store_block(void *output, const block *src) { + unsigned i; + for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) { + _blake2b_store64((uint8_t *)output + i * sizeof(src->v[i]), src->v[i]); + } +} + +/***************Memory functions*****************/ + +ARGON2_PRIVATE +int _argon2_allocate_memory(const argon2_context *context, uint8_t **memory, + size_t num, size_t size) { + size_t memory_size = num*size; + if (memory == NULL) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + /* 1. Check for multiplication overflow */ + if (size != 0 && memory_size / size != num) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + /* 2. Try to allocate with appropriate allocator */ + if (context->allocate_cbk) { + (context->allocate_cbk)(memory, memory_size); + } else { + *memory = malloc(memory_size); + } + + if (*memory == NULL) { + return ARGON2_MEMORY_ALLOCATION_ERROR; + } + + return ARGON2_OK; +} + +ARGON2_PRIVATE +void _argon2_free_memory(const argon2_context *context, uint8_t *memory, + size_t num, size_t size) { + size_t memory_size = num*size; + _argon2_clear_internal_memory(memory, memory_size); + if (context->free_cbk) { + (context->free_cbk)(memory, memory_size); + } else { + free(memory); + } +} + +#if defined(__OpenBSD__) +#define HAVE_EXPLICIT_BZERO 1 +#elif defined(__GLIBC__) && defined(__GLIBC_PREREQ) +#if __GLIBC_PREREQ(2,25) +#define HAVE_EXPLICIT_BZERO 1 +#endif +#endif + +ARGON2_PRIVATE +void NOT_OPTIMIZED _argon2_secure_wipe_memory(void *v, size_t n) { +#if defined(_MSC_VER) && VC_GE_2005(_MSC_VER) || defined(__MINGW32__) + SecureZeroMemory(v, n); +#elif defined memset_s + memset_s(v, n, 0, n); +#elif defined(HAVE_EXPLICIT_BZERO) + explicit_bzero(v, n); +#else + static void *(*const volatile memset_sec)(void *, int, size_t) = &memset; + memset_sec(v, 0, n); +#endif +} + +/* Memory clear flag defaults to true. */ +int FLAG_clear_internal_memory = 1; + +ARGON2_PRIVATE +void _argon2_clear_internal_memory(void *v, size_t n) { + if (FLAG_clear_internal_memory && v) { + _argon2_secure_wipe_memory(v, n); + } +} + +ARGON2_PRIVATE +void _argon2_finalize(const argon2_context *context, argon2_instance_t *instance) { + if (context != NULL && instance != NULL) { + block blockhash; + uint32_t l; + + _argon2_copy_block(&blockhash, instance->memory + instance->lane_length - 1); + + /* XOR the last blocks */ + for (l = 1; l < instance->lanes; ++l) { + uint32_t last_block_in_lane = + l * instance->lane_length + (instance->lane_length - 1); + _argon2_xor_block(&blockhash, instance->memory + last_block_in_lane); + } + + /* Hash the result */ + { + uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE]; + _argon2_store_block(blockhash_bytes, &blockhash); + blake2b_long(context->out, context->outlen, blockhash_bytes, + ARGON2_BLOCK_SIZE); + /* clear blockhash and blockhash_bytes */ + _argon2_clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE); + _argon2_clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); + } + +#ifdef GENKAT + print_tag(context->out, context->outlen); +#endif + + _argon2_free_memory(context, (uint8_t *)instance->memory, + instance->memory_blocks, sizeof(block)); + } +} + +ARGON2_PRIVATE +uint32_t _argon2_index_alpha(const argon2_instance_t *instance, + const argon2_position_t *position, uint32_t pseudo_rand, + int same_lane) { + /* + * Pass 0: + * This lane : all already finished segments plus already constructed + * blocks in this segment + * Other lanes : all already finished segments + * Pass 1+: + * This lane : (SYNC_POINTS - 1) last segments plus already constructed + * blocks in this segment + * Other lanes : (SYNC_POINTS - 1) last segments + */ + uint32_t reference_area_size; + uint64_t relative_position; + uint32_t start_position, absolute_position; + + if (0 == position->pass) { + /* First pass */ + if (0 == position->slice) { + /* First slice */ + reference_area_size = + position->index - 1; /* all but the previous */ + } else { + if (same_lane) { + /* The same lane => add current segment */ + reference_area_size = + position->slice * instance->segment_length + + position->index - 1; + } else { + reference_area_size = + position->slice * instance->segment_length + + ((position->index == 0) ? (-1) : 0); + } + } + } else { + /* Second pass */ + if (same_lane) { + reference_area_size = instance->lane_length - + instance->segment_length + position->index - + 1; + } else { + reference_area_size = instance->lane_length - + instance->segment_length + + ((position->index == 0) ? (-1) : 0); + } + } + + /* 1.2.4. Mapping pseudo_rand to 0.. and produce + * relative position */ + relative_position = pseudo_rand; + relative_position = relative_position * relative_position >> 32; + relative_position = reference_area_size - 1 - + (reference_area_size * relative_position >> 32); + + /* 1.2.5 Computing starting position */ + start_position = 0; + + if (0 != position->pass) { + start_position = (position->slice == ARGON2_SYNC_POINTS - 1) + ? 0 + : (position->slice + 1) * instance->segment_length; + } + + /* 1.2.6. Computing absolute position */ + absolute_position = (start_position + relative_position) % + instance->lane_length; /* absolute position */ + return absolute_position; +} + +/* Single-threaded version for p=1 case */ +static int _argon2_fill_memory_blocks_st(argon2_instance_t *instance) { + uint32_t r, s, l; + + for (r = 0; r < instance->passes; ++r) { + for (s = 0; s < ARGON2_SYNC_POINTS; ++s) { + for (l = 0; l < instance->lanes; ++l) { + argon2_position_t position = {r, l, (uint8_t)s, 0}; + _argon2_fill_segment(instance, position); + } + } +#ifdef GENKAT + internal_kat(instance, r); /* Print all memory blocks */ +#endif + } + return ARGON2_OK; +} + +#if !defined(ARGON2_NO_THREADS) + +#ifdef _WIN32 +static unsigned __stdcall _argon2_fill_segment_thr(void *thread_data) +#else +static void *_argon2_fill_segment_thr(void *thread_data) +#endif +{ + argon2_thread_data *my_data = thread_data; + _argon2_fill_segment(my_data->instance_ptr, my_data->pos); + argon2_thread_exit(); + return 0; +} + +/* Multi-threaded version for p > 1 case */ +static int _argon2_fill_memory_blocks_mt(argon2_instance_t *instance) { + uint32_t r, s; + argon2_thread_handle_t *thread = NULL; + argon2_thread_data *thr_data = NULL; + int rc = ARGON2_OK; + + /* 1. Allocating space for threads */ + thread = calloc(instance->lanes, sizeof(argon2_thread_handle_t)); + if (thread == NULL) { + rc = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + thr_data = calloc(instance->lanes, sizeof(argon2_thread_data)); + if (thr_data == NULL) { + rc = ARGON2_MEMORY_ALLOCATION_ERROR; + goto fail; + } + + for (r = 0; r < instance->passes; ++r) { + for (s = 0; s < ARGON2_SYNC_POINTS; ++s) { + uint32_t l, ll; + + /* 2. Calling threads */ + for (l = 0; l < instance->lanes; ++l) { + argon2_position_t position; + + /* 2.1 Join a thread if limit is exceeded */ + if (l >= instance->threads) { + if (argon2_thread_join(thread[l - instance->threads])) { + rc = ARGON2_THREAD_FAIL; + goto fail; + } + } + + /* 2.2 Create thread */ + position.pass = r; + position.lane = l; + position.slice = (uint8_t)s; + position.index = 0; + thr_data[l].instance_ptr = + instance; /* preparing the thread input */ + memcpy(&(thr_data[l].pos), &position, + sizeof(argon2_position_t)); + if (argon2_thread_create(&thread[l], &_argon2_fill_segment_thr, + (void *)&thr_data[l])) { + /* Wait for already running threads */ + for (ll = 0; ll < l; ++ll) + argon2_thread_join(thread[ll]); + rc = ARGON2_THREAD_FAIL; + goto fail; + } + + /* fill_segment(instance, position); */ + /*Non-thread equivalent of the lines above */ + } + + /* 3. Joining remaining threads */ + for (l = instance->lanes - instance->threads; l < instance->lanes; + ++l) { + if (argon2_thread_join(thread[l])) { + rc = ARGON2_THREAD_FAIL; + goto fail; + } + } + } + +#ifdef GENKAT + internal_kat(instance, r); /* Print all memory blocks */ +#endif + } + +fail: + if (thread != NULL) { + free(thread); + } + if (thr_data != NULL) { + free(thr_data); + } + return rc; +} + +#endif /* ARGON2_NO_THREADS */ + +ARGON2_PRIVATE +int _argon2_fill_memory_blocks(argon2_instance_t *instance) { + if (instance == NULL || instance->lanes == 0) { + return ARGON2_INCORRECT_PARAMETER; + } +#if defined(ARGON2_NO_THREADS) + return _argon2_fill_memory_blocks_st(instance); +#else + return instance->threads == 1 ? + _argon2_fill_memory_blocks_st(instance) : _argon2_fill_memory_blocks_mt(instance); +#endif +} + +ARGON2_PRIVATE +int _argon2_validate_inputs(const argon2_context *context) { + if (NULL == context) { + return ARGON2_INCORRECT_PARAMETER; + } + + if (NULL == context->out) { + return ARGON2_OUTPUT_PTR_NULL; + } + + /* Validate output length */ + if (ARGON2_MIN_OUTLEN > context->outlen) { + return ARGON2_OUTPUT_TOO_SHORT; + } + + if (ARGON2_MAX_OUTLEN < context->outlen) { + return ARGON2_OUTPUT_TOO_LONG; + } + + /* Validate password (required param) */ + if (NULL == context->pwd) { + if (0 != context->pwdlen) { + return ARGON2_PWD_PTR_MISMATCH; + } + } + + if (ARGON2_MIN_PWD_LENGTH > context->pwdlen) { + return ARGON2_PWD_TOO_SHORT; + } + + if (ARGON2_MAX_PWD_LENGTH < context->pwdlen) { + return ARGON2_PWD_TOO_LONG; + } + + /* Validate salt (required param) */ + if (NULL == context->salt) { + if (0 != context->saltlen) { + return ARGON2_SALT_PTR_MISMATCH; + } + } + + if (ARGON2_MIN_SALT_LENGTH > context->saltlen) { + return ARGON2_SALT_TOO_SHORT; + } + + if (ARGON2_MAX_SALT_LENGTH < context->saltlen) { + return ARGON2_SALT_TOO_LONG; + } + + /* Validate secret (optional param) */ + if (NULL == context->secret) { + if (0 != context->secretlen) { + return ARGON2_SECRET_PTR_MISMATCH; + } + } else { + if (ARGON2_MIN_SECRET > context->secretlen) { + return ARGON2_SECRET_TOO_SHORT; + } + if (ARGON2_MAX_SECRET < context->secretlen) { + return ARGON2_SECRET_TOO_LONG; + } + } + + /* Validate associated data (optional param) */ + if (NULL == context->ad) { + if (0 != context->adlen) { + return ARGON2_AD_PTR_MISMATCH; + } + } else { + if (ARGON2_MIN_AD_LENGTH > context->adlen) { + return ARGON2_AD_TOO_SHORT; + } + if (ARGON2_MAX_AD_LENGTH < context->adlen) { + return ARGON2_AD_TOO_LONG; + } + } + + /* Validate memory cost */ + if (ARGON2_MIN_MEMORY > context->m_cost) { + return ARGON2_MEMORY_TOO_LITTLE; + } + + if (ARGON2_MAX_MEMORY < context->m_cost) { + return ARGON2_MEMORY_TOO_MUCH; + } + + if (context->m_cost < 8 * context->lanes) { + return ARGON2_MEMORY_TOO_LITTLE; + } + + /* Validate time cost */ + if (ARGON2_MIN_TIME > context->t_cost) { + return ARGON2_TIME_TOO_SMALL; + } + + if (ARGON2_MAX_TIME < context->t_cost) { + return ARGON2_TIME_TOO_LARGE; + } + + /* Validate lanes */ + if (ARGON2_MIN_LANES > context->lanes) { + return ARGON2_LANES_TOO_FEW; + } + + if (ARGON2_MAX_LANES < context->lanes) { + return ARGON2_LANES_TOO_MANY; + } + + /* Validate threads */ + if (ARGON2_MIN_THREADS > context->threads) { + return ARGON2_THREADS_TOO_FEW; + } + + if (ARGON2_MAX_THREADS < context->threads) { + return ARGON2_THREADS_TOO_MANY; + } + + if (NULL != context->allocate_cbk && NULL == context->free_cbk) { + return ARGON2_FREE_MEMORY_CBK_NULL; + } + + if (NULL == context->allocate_cbk && NULL != context->free_cbk) { + return ARGON2_ALLOCATE_MEMORY_CBK_NULL; + } + + return ARGON2_OK; +} + +ARGON2_PRIVATE +void _argon2_fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance) { + uint32_t l; + /* Make the first and second block in each lane as G(H0||0||i) or + G(H0||1||i) */ + uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE]; + for (l = 0; l < instance->lanes; ++l) { + + _blake2b_store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 0); + _blake2b_store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH + 4, l); + blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, + ARGON2_PREHASH_SEED_LENGTH); + _argon2_load_block(&instance->memory[l * instance->lane_length + 0], + blockhash_bytes); + + _blake2b_store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 1); + blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash, + ARGON2_PREHASH_SEED_LENGTH); + _argon2_load_block(&instance->memory[l * instance->lane_length + 1], + blockhash_bytes); + } + _argon2_clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE); +} + +ARGON2_PRIVATE +void _argon2_initial_hash(uint8_t *blockhash, argon2_context *context, + argon2_type type) { + blake2b_state BlakeHash; + uint8_t value[sizeof(uint32_t)]; + + if (NULL == context || NULL == blockhash) { + return; + } + + blake2b_init(&BlakeHash, ARGON2_PREHASH_DIGEST_LENGTH); + + _blake2b_store32(&value, context->lanes); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + _blake2b_store32(&value, context->outlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + _blake2b_store32(&value, context->m_cost); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + _blake2b_store32(&value, context->t_cost); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + _blake2b_store32(&value, context->version); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + _blake2b_store32(&value, (uint32_t)type); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + _blake2b_store32(&value, context->pwdlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->pwd != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->pwd, + context->pwdlen); + + if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) { + _argon2_secure_wipe_memory(context->pwd, context->pwdlen); + context->pwdlen = 0; + } + } + + _blake2b_store32(&value, context->saltlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->salt != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->salt, + context->saltlen); + } + + _blake2b_store32(&value, context->secretlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->secret != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->secret, + context->secretlen); + + if (context->flags & ARGON2_FLAG_CLEAR_SECRET) { + _argon2_secure_wipe_memory(context->secret, context->secretlen); + context->secretlen = 0; + } + } + + _blake2b_store32(&value, context->adlen); + blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value)); + + if (context->ad != NULL) { + blake2b_update(&BlakeHash, (const uint8_t *)context->ad, + context->adlen); + } + + blake2b_final(&BlakeHash, blockhash, ARGON2_PREHASH_DIGEST_LENGTH); +} + +ARGON2_PRIVATE +int _argon2_initialize(argon2_instance_t *instance, argon2_context *context) { + uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; + int result = ARGON2_OK; + + if (instance == NULL || context == NULL) + return ARGON2_INCORRECT_PARAMETER; + instance->context_ptr = context; + + /* 1. Memory allocation */ + result = _argon2_allocate_memory(context, (uint8_t **)&(instance->memory), + instance->memory_blocks, sizeof(block)); + if (result != ARGON2_OK) { + return result; + } + + /* 2. Initial hashing */ + /* H_0 + 8 extra bytes to produce the first blocks */ + /* uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; */ + /* Hashing all inputs */ + _argon2_initial_hash(blockhash, context, instance->type); + /* Zeroing 8 extra bytes */ + _argon2_clear_internal_memory(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, + ARGON2_PREHASH_SEED_LENGTH - + ARGON2_PREHASH_DIGEST_LENGTH); + +#ifdef GENKAT + initial_kat(blockhash, context, instance->type); +#endif + + /* 3. Creating first blocks, we always have at least two blocks in a slice + */ + _argon2_fill_first_blocks(blockhash, instance); + /* Clearing the hash */ + _argon2_clear_internal_memory(blockhash, ARGON2_PREHASH_SEED_LENGTH); + + return ARGON2_OK; +} +/*** End of #include "src/core.c" ***/ + +/* #include "src/encoding.c" */ +/*** Begin of #include "src/encoding.c" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include +#include +#include +#include +/* #include "encoding.h" */ + +/* #include "core.h" */ + + +/* + * Example code for a decoder and encoder of "hash strings", with Argon2 + * parameters. + * + * This code comprises three sections: + * + * -- The first section contains generic Base64 encoding and decoding + * functions. It is conceptually applicable to any hash function + * implementation that uses Base64 to encode and decode parameters, + * salts and outputs. It could be made into a library, provided that + * the relevant functions are made public (non-static) and be given + * reasonable names to avoid collisions with other functions. + * + * -- The second section is specific to Argon2. It encodes and decodes + * the parameters, salts and outputs. It does not compute the hash + * itself. + * + * The code was originally written by Thomas Pornin , + * to whom comments and remarks may be sent. It is released under what + * should amount to Public Domain or its closest equivalent; the + * following mantra is supposed to incarnate that fact with all the + * proper legal rituals: + * + * --------------------------------------------------------------------- + * This file is provided under the terms of Creative Commons CC0 1.0 + * Public Domain Dedication. To the extent possible under law, the + * author (Thomas Pornin) has waived all copyright and related or + * neighboring rights to this file. This work is published from: Canada. + * --------------------------------------------------------------------- + * + * Copyright (c) 2015 Thomas Pornin + */ + +/* ==================================================================== */ +/* + * Common code; could be shared between different hash functions. + * + * Note: the Base64 functions below assume that uppercase letters (resp. + * lowercase letters) have consecutive numerical codes, that fit on 8 + * bits. All modern systems use ASCII-compatible charsets, where these + * properties are true. If you are stuck with a dinosaur of a system + * that still defaults to EBCDIC then you already have much bigger + * interoperability issues to deal with. + */ + +/* + * Some macros for constant-time comparisons. These work over values in + * the 0..255 range. Returned value is 0x00 on "false", 0xFF on "true". + */ +#define ARGON2_EQ(x, y) ((((0U - ((unsigned)(x) ^ (unsigned)(y))) >> 8) & 0xFF) ^ 0xFF) +#define ARGON2_GT(x, y) ((((unsigned)(y) - (unsigned)(x)) >> 8) & 0xFF) +#define ARGON2_GE(x, y) (ARGON2_GT(y, x) ^ 0xFF) +#define ARGON2_LT(x, y) ARGON2_GT(y, x) +#define ARGON2_LE(x, y) ARGON2_GE(y, x) + +/* + * Convert value x (0..63) to corresponding Base64 character. + */ +static int _argon2_b64_byte_to_char(unsigned x) { + return (ARGON2_LT(x, 26) & (x + 'A')) | + (ARGON2_GE(x, 26) & ARGON2_LT(x, 52) & (x + ('a' - 26))) | + (ARGON2_GE(x, 52) & ARGON2_LT(x, 62) & (x + ('0' - 52))) | (ARGON2_EQ(x, 62) & '+') | + (ARGON2_EQ(x, 63) & '/'); +} + +/* + * Convert character c to the corresponding 6-bit value. If character c + * is not a Base64 character, then 0xFF (255) is returned. + */ +static unsigned _argon2_b64_char_to_byte(int c) { + unsigned x; + + x = (ARGON2_GE(c, 'A') & ARGON2_LE(c, 'Z') & (c - 'A')) | + (ARGON2_GE(c, 'a') & ARGON2_LE(c, 'z') & (c - ('a' - 26))) | + (ARGON2_GE(c, '0') & ARGON2_LE(c, '9') & (c - ('0' - 52))) | (ARGON2_EQ(c, '+') & 62) | + (ARGON2_EQ(c, '/') & 63); + return x | (ARGON2_EQ(x, 0) & (ARGON2_EQ(c, 'A') ^ 0xFF)); +} + +/* + * Convert some bytes to Base64. 'dst_len' is the length (in characters) + * of the output buffer 'dst'; if that buffer is not large enough to + * receive the result (including the terminating 0), then (size_t)-1 + * is returned. Otherwise, the zero-terminated Base64 string is written + * in the buffer, and the output length (counted WITHOUT the terminating + * zero) is returned. + */ +static size_t _argon2_to_base64(char *dst, size_t dst_len, const void *src, + size_t src_len) { + size_t olen; + const unsigned char *buf; + unsigned acc, acc_len; + + olen = (src_len / 3) << 2; + switch (src_len % 3) { + case 2: + olen++; + /* fall through */ + case 1: + olen += 2; + break; + } + if (dst_len <= olen) { + return (size_t)-1; + } + acc = 0; + acc_len = 0; + buf = (const unsigned char *)src; + while (src_len-- > 0) { + acc = (acc << 8) + (*buf++); + acc_len += 8; + while (acc_len >= 6) { + acc_len -= 6; + *dst++ = (char)_argon2_b64_byte_to_char((acc >> acc_len) & 0x3F); + } + } + if (acc_len > 0) { + *dst++ = (char)_argon2_b64_byte_to_char((acc << (6 - acc_len)) & 0x3F); + } + *dst++ = 0; + return olen; +} + +/* + * Decode Base64 chars into bytes. The '*dst_len' value must initially + * contain the length of the output buffer '*dst'; when the decoding + * ends, the actual number of decoded bytes is written back in + * '*dst_len'. + * + * Decoding stops when a non-Base64 character is encountered, or when + * the output buffer capacity is exceeded. If an error occurred (output + * buffer is too small, invalid last characters leading to unprocessed + * buffered bits), then NULL is returned; otherwise, the returned value + * points to the first non-Base64 character in the source stream, which + * may be the terminating zero. + */ +static const char *_argon2_from_base64(void *dst, size_t *dst_len, const char *src) { + size_t len; + unsigned char *buf; + unsigned acc, acc_len; + + buf = (unsigned char *)dst; + len = 0; + acc = 0; + acc_len = 0; + for (;;) { + unsigned d; + + d = _argon2_b64_char_to_byte(*src); + if (d == 0xFF) { + break; + } + src++; + acc = (acc << 6) + d; + acc_len += 6; + if (acc_len >= 8) { + acc_len -= 8; + if ((len++) >= *dst_len) { + return NULL; + } + *buf++ = (acc >> acc_len) & 0xFF; + } + } + + /* + * If the input length is equal to 1 modulo 4 (which is + * invalid), then there will remain 6 unprocessed bits; + * otherwise, only 0, 2 or 4 bits are buffered. The buffered + * bits must also all be zero. + */ + if (acc_len > 4 || (acc & (((unsigned)1 << acc_len) - 1)) != 0) { + return NULL; + } + *dst_len = len; + return src; +} + +/* + * Decode decimal integer from 'str'; the value is written in '*v'. + * Returned value is a pointer to the next non-decimal character in the + * string. If there is no digit at all, or the value encoding is not + * minimal (extra leading zeros), or the value does not fit in an + * 'unsigned long', then NULL is returned. + */ +static const char *_argon2_decode_decimal(const char *str, unsigned long *v) { + const char *orig; + unsigned long acc; + + acc = 0; + for (orig = str;; str++) { + int c; + + c = *str; + if (c < '0' || c > '9') { + break; + } + c -= '0'; + if (acc > (ULONG_MAX / 10)) { + return NULL; + } + acc *= 10; + if ((unsigned long)c > (ULONG_MAX - acc)) { + return NULL; + } + acc += (unsigned long)c; + } + if (str == orig || (*orig == '0' && str != (orig + 1))) { + return NULL; + } + *v = acc; + return str; +} + +/* ==================================================================== */ +/* + * Code specific to Argon2. + * + * The code below applies the following format: + * + * $argon2[$v=]$m=,t=,p=$$ + * + * where is either 'd', 'id', or 'i', is a decimal integer (positive, + * fits in an 'unsigned long'), and is Base64-encoded data (no '=' padding + * characters, no newline or whitespace). + * + * The last two binary chunks (encoded in Base64) are, in that order, + * the salt and the output. Both are required. The binary salt length and the + * output length must be in the allowed ranges defined in argon2.h. + * + * The ctx struct must contain buffers large enough to hold the salt and pwd + * when it is fed into decode_string. + */ + +ARGON2_PRIVATE +int _argon2_decode_string(argon2_context *ctx, const char *str, argon2_type type) { + +/* check for prefix */ +#define ARGON2_CC(prefix) \ + do { \ + size_t cc_len = strlen(prefix); \ + if (strncmp(str, prefix, cc_len) != 0) { \ + return ARGON2_DECODING_FAIL; \ + } \ + str += cc_len; \ + } while ((void)0, 0) + +/* optional prefix checking with supplied code */ +#define ARGON2_CC_opt(prefix, code) \ + do { \ + size_t cc_len = strlen(prefix); \ + if (strncmp(str, prefix, cc_len) == 0) { \ + str += cc_len; \ + { code; } \ + } \ + } while ((void)0, 0) + +/* Decoding prefix into decimal */ +#define ARGON2_DECIMAL(x) \ + do { \ + unsigned long dec_x; \ + str = _argon2_decode_decimal(str, &dec_x); \ + if (str == NULL) { \ + return ARGON2_DECODING_FAIL; \ + } \ + (x) = dec_x; \ + } while ((void)0, 0) + + +/* Decoding prefix into uint32_t decimal */ +#define ARGON2_DECIMAL_U32(x) \ + do { \ + unsigned long dec_x; \ + str = _argon2_decode_decimal(str, &dec_x); \ + if (str == NULL || dec_x > UINT32_MAX) { \ + return ARGON2_DECODING_FAIL; \ + } \ + (x) = (uint32_t)dec_x; \ + } while ((void)0, 0) + + +/* Decoding base64 into a binary buffer */ +#define ARGON2_BIN(buf, max_len, len) \ + do { \ + size_t bin_len = (max_len); \ + str = _argon2_from_base64(buf, &bin_len, str); \ + if (str == NULL || bin_len > UINT32_MAX) { \ + return ARGON2_DECODING_FAIL; \ + } \ + (len) = (uint32_t)bin_len; \ + } while ((void)0, 0) + + size_t maxsaltlen = ctx->saltlen; + size_t maxoutlen = ctx->outlen; + int validation_result; + const char* type_string; + + /* We should start with the argon2_type we are using */ + type_string = argon2_type2string(type, 0); + if (!type_string) { + return ARGON2_INCORRECT_TYPE; + } + + ARGON2_CC("$"); + ARGON2_CC(type_string); + + /* Reading the version number if the default is suppressed */ + ctx->version = ARGON2_VERSION_10; + ARGON2_CC_opt("$v=", ARGON2_DECIMAL_U32(ctx->version)); + + ARGON2_CC("$m="); + ARGON2_DECIMAL_U32(ctx->m_cost); + ARGON2_CC(",t="); + ARGON2_DECIMAL_U32(ctx->t_cost); + ARGON2_CC(",p="); + ARGON2_DECIMAL_U32(ctx->lanes); + ctx->threads = ctx->lanes; + + ARGON2_CC("$"); + ARGON2_BIN(ctx->salt, maxsaltlen, ctx->saltlen); + ARGON2_CC("$"); + ARGON2_BIN(ctx->out, maxoutlen, ctx->outlen); + + /* The rest of the fields get the default values */ + ctx->secret = NULL; + ctx->secretlen = 0; + ctx->ad = NULL; + ctx->adlen = 0; + ctx->allocate_cbk = NULL; + ctx->free_cbk = NULL; + ctx->flags = ARGON2_DEFAULT_FLAGS; + + /* On return, must have valid context */ + validation_result = _argon2_validate_inputs(ctx); + if (validation_result != ARGON2_OK) { + return validation_result; + } + + /* Can't have any additional characters */ + if (*str == 0) { + return ARGON2_OK; + } else { + return ARGON2_DECODING_FAIL; + } +#undef ARGON2_CC +#undef ARGON2_CC_opt +#undef ARGON2_DECIMAL +#undef ARGON2_DECIMAL_U32 +#undef ARGON2_BIN +} + +ARGON2_PRIVATE +int _argon2_encode_string(char *dst, size_t dst_len, argon2_context *ctx, + argon2_type type) { +#define ARGON2_SS(str) \ + do { \ + size_t pp_len = strlen(str); \ + if (pp_len >= dst_len) { \ + return ARGON2_ENCODING_FAIL; \ + } \ + memcpy(dst, str, pp_len + 1); \ + dst += pp_len; \ + dst_len -= pp_len; \ + } while ((void)0, 0) + +#define ARGON2_SX(x) \ + do { \ + char tmp[30]; \ + sprintf(tmp, "%lu", (unsigned long)(x)); \ + ARGON2_SS(tmp); \ + } while ((void)0, 0) + +#define ARGON2_SB(buf, len) \ + do { \ + size_t sb_len = _argon2_to_base64(dst, dst_len, buf, len); \ + if (sb_len == (size_t)-1) { \ + return ARGON2_ENCODING_FAIL; \ + } \ + dst += sb_len; \ + dst_len -= sb_len; \ + } while ((void)0, 0) + + const char* type_string = argon2_type2string(type, 0); + int validation_result = _argon2_validate_inputs(ctx); + + if (!type_string) { + return ARGON2_ENCODING_FAIL; + } + + if (validation_result != ARGON2_OK) { + return validation_result; + } + + + ARGON2_SS("$"); + ARGON2_SS(type_string); + + ARGON2_SS("$v="); + ARGON2_SX(ctx->version); + + ARGON2_SS("$m="); + ARGON2_SX(ctx->m_cost); + ARGON2_SS(",t="); + ARGON2_SX(ctx->t_cost); + ARGON2_SS(",p="); + ARGON2_SX(ctx->lanes); + + ARGON2_SS("$"); + ARGON2_SB(ctx->salt, ctx->saltlen); + + ARGON2_SS("$"); + ARGON2_SB(ctx->out, ctx->outlen); + return ARGON2_OK; + +#undef ARGON2_SS +#undef ARGON2_SX +#undef ARGON2_SB +} + +ARGON2_PRIVATE +size_t _argon2_b64len(uint32_t len) { + size_t olen = ((size_t)len / 3) << 2; + + switch (len % 3) { + case 2: + olen++; + /* fall through */ + case 1: + olen += 2; + break; + } + + return olen; +} + +ARGON2_PRIVATE +size_t _argon2_numlen(uint32_t num) { + size_t len = 1; + while (num >= 10) { + ++len; + num = num / 10; + } + return len; +} + +/*** End of #include "src/encoding.c" ***/ + +/* #include "src/ref.c" */ +/*** Begin of #include "src/ref.c" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#include +#include +#include + +/* #include "argon2.h" */ + +/* #include "core.h" */ + + +/* #include "blake2/blamka-round-ref.h" */ +/*** Begin of #include "blake2/blamka-round-ref.h" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#ifndef BLAKE_ROUND_MKA_H +#define BLAKE_ROUND_MKA_H + +/* #include "blake2.h" */ + +/* #include "blake2-impl.h" */ + + +/* designed by the Lyra PHC team */ +static BLAKE2_INLINE uint64_t fBlaMka(uint64_t x, uint64_t y) { + const uint64_t m = UINT64_C(0xFFFFFFFF); + const uint64_t xy = (x & m) * (y & m); + return x + y + 2 * xy; +} + +#define BLAKE2_G(a, b, c, d) \ + do { \ + a = fBlaMka(a, b); \ + d = _blake2b_rotr64(d ^ a, 32); \ + c = fBlaMka(c, d); \ + b = _blake2b_rotr64(b ^ c, 24); \ + a = fBlaMka(a, b); \ + d = _blake2b_rotr64(d ^ a, 16); \ + c = fBlaMka(c, d); \ + b = _blake2b_rotr64(b ^ c, 63); \ + } while ((void)0, 0) + +#define BLAKE2_ROUND_NOMSG(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, \ + v12, v13, v14, v15) \ + do { \ + BLAKE2_G(v0, v4, v8, v12); \ + BLAKE2_G(v1, v5, v9, v13); \ + BLAKE2_G(v2, v6, v10, v14); \ + BLAKE2_G(v3, v7, v11, v15); \ + BLAKE2_G(v0, v5, v10, v15); \ + BLAKE2_G(v1, v6, v11, v12); \ + BLAKE2_G(v2, v7, v8, v13); \ + BLAKE2_G(v3, v4, v9, v14); \ + } while ((void)0, 0) + +#endif +/*** End of #include "blake2/blamka-round-ref.h" ***/ + +/* #include "blake2/blake2-impl.h" */ + +/* #include "blake2/blake2.h" */ + + + +/* + * Function fills a new memory block and optionally XORs the old block over the new one. + * @next_block must be initialized. + * @param prev_block Pointer to the previous block + * @param ref_block Pointer to the reference block + * @param next_block Pointer to the block to be constructed + * @param with_xor Whether to XOR into the new block (1) or just overwrite (0) + * @pre all block pointers must be valid + */ +static void _argon2_fill_block(const block *prev_block, const block *ref_block, + block *next_block, int with_xor) { + block blockR, block_tmp; + unsigned i; + + _argon2_copy_block(&blockR, ref_block); + _argon2_xor_block(&blockR, prev_block); + _argon2_copy_block(&block_tmp, &blockR); + /* Now blockR = ref_block + prev_block and block_tmp = ref_block + prev_block */ + if (with_xor) { + /* Saving the next block contents for XOR over: */ + _argon2_xor_block(&block_tmp, next_block); + /* Now blockR = ref_block + prev_block and + block_tmp = ref_block + prev_block + next_block */ + } + + /* Apply Blake2 on columns of 64-bit words: (0,1,...,15) , then + (16,17,..31)... finally (112,113,...127) */ + for (i = 0; i < 8; ++i) { + BLAKE2_ROUND_NOMSG( + blockR.v[16 * i], blockR.v[16 * i + 1], blockR.v[16 * i + 2], + blockR.v[16 * i + 3], blockR.v[16 * i + 4], blockR.v[16 * i + 5], + blockR.v[16 * i + 6], blockR.v[16 * i + 7], blockR.v[16 * i + 8], + blockR.v[16 * i + 9], blockR.v[16 * i + 10], blockR.v[16 * i + 11], + blockR.v[16 * i + 12], blockR.v[16 * i + 13], blockR.v[16 * i + 14], + blockR.v[16 * i + 15]); + } + + /* Apply Blake2 on rows of 64-bit words: (0,1,16,17,...112,113), then + (2,3,18,19,...,114,115).. finally (14,15,30,31,...,126,127) */ + for (i = 0; i < 8; i++) { + BLAKE2_ROUND_NOMSG( + blockR.v[2 * i], blockR.v[2 * i + 1], blockR.v[2 * i + 16], + blockR.v[2 * i + 17], blockR.v[2 * i + 32], blockR.v[2 * i + 33], + blockR.v[2 * i + 48], blockR.v[2 * i + 49], blockR.v[2 * i + 64], + blockR.v[2 * i + 65], blockR.v[2 * i + 80], blockR.v[2 * i + 81], + blockR.v[2 * i + 96], blockR.v[2 * i + 97], blockR.v[2 * i + 112], + blockR.v[2 * i + 113]); + } + + _argon2_copy_block(next_block, &block_tmp); + _argon2_xor_block(next_block, &blockR); +} + +static void _argon2_next_addresses(block *address_block, block *input_block, + const block *zero_block) { + input_block->v[6]++; + _argon2_fill_block(zero_block, input_block, address_block, 0); + _argon2_fill_block(zero_block, address_block, address_block, 0); +} + +ARGON2_PRIVATE +void _argon2_fill_segment(const argon2_instance_t *instance, + argon2_position_t position) { + block *ref_block = NULL, *curr_block = NULL; + block address_block, input_block, zero_block; + uint64_t pseudo_rand, ref_index, ref_lane; + uint32_t prev_offset, curr_offset; + uint32_t starting_index; + uint32_t i; + int data_independent_addressing; + + if (instance == NULL) { + return; + } + + data_independent_addressing = + (instance->type == Argon2_i) || + (instance->type == Argon2_id && (position.pass == 0) && + (position.slice < ARGON2_SYNC_POINTS / 2)); + + if (data_independent_addressing) { + _argon2_init_block_value(&zero_block, 0); + _argon2_init_block_value(&input_block, 0); + + input_block.v[0] = position.pass; + input_block.v[1] = position.lane; + input_block.v[2] = position.slice; + input_block.v[3] = instance->memory_blocks; + input_block.v[4] = instance->passes; + input_block.v[5] = instance->type; + } + + starting_index = 0; + + if ((0 == position.pass) && (0 == position.slice)) { + starting_index = 2; /* we have already generated the first two blocks */ + + /* Don't forget to generate the first block of addresses: */ + if (data_independent_addressing) { + _argon2_next_addresses(&address_block, &input_block, &zero_block); + } + } + + /* Offset of the current block */ + curr_offset = position.lane * instance->lane_length + + position.slice * instance->segment_length + starting_index; + + if (0 == curr_offset % instance->lane_length) { + /* Last block in this lane */ + prev_offset = curr_offset + instance->lane_length - 1; + } else { + /* Previous block */ + prev_offset = curr_offset - 1; + } + + for (i = starting_index; i < instance->segment_length; + ++i, ++curr_offset, ++prev_offset) { + /*1.1 Rotating prev_offset if needed */ + if (curr_offset % instance->lane_length == 1) { + prev_offset = curr_offset - 1; + } + + /* 1.2 Computing the index of the reference block */ + /* 1.2.1 Taking pseudo-random value from the previous block */ + if (data_independent_addressing) { + if (i % ARGON2_ADDRESSES_IN_BLOCK == 0) { + _argon2_next_addresses(&address_block, &input_block, &zero_block); + } + pseudo_rand = address_block.v[i % ARGON2_ADDRESSES_IN_BLOCK]; + } else { + pseudo_rand = instance->memory[prev_offset].v[0]; + } + + /* 1.2.2 Computing the lane of the reference block */ + ref_lane = ((pseudo_rand >> 32)) % instance->lanes; + + if ((position.pass == 0) && (position.slice == 0)) { + /* Can not reference other lanes yet */ + ref_lane = position.lane; + } + + /* 1.2.3 Computing the number of possible reference block within the + * lane. + */ + position.index = i; + ref_index = _argon2_index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, + ref_lane == position.lane); + + /* 2 Creating a new block */ + ref_block = + instance->memory + instance->lane_length * ref_lane + ref_index; + curr_block = instance->memory + curr_offset; + if (ARGON2_VERSION_10 == instance->version) { + /* version 1.2.1 and earlier: overwrite, not XOR */ + _argon2_fill_block(instance->memory + prev_offset, ref_block, curr_block, 0); + } else { + if(0 == position.pass) { + _argon2_fill_block(instance->memory + prev_offset, ref_block, + curr_block, 0); + } else { + _argon2_fill_block(instance->memory + prev_offset, ref_block, + curr_block, 1); + } + } + } +} +/*** End of #include "src/ref.c" ***/ + +/* #include "src/thread.c" */ +/*** Begin of #include "src/thread.c" ***/ +/* + * Argon2 reference source code package - reference C implementations + * + * Copyright 2015 + * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves + * + * You may use this work under the terms of a Creative Commons CC0 1.0 + * License/Waiver or the Apache Public License 2.0, at your option. The terms of + * these licenses can be found at: + * + * - CC0 1.0 Universal : https://creativecommons.org/publicdomain/zero/1.0 + * - Apache 2.0 : https://www.apache.org/licenses/LICENSE-2.0 + * + * You should have received a copy of both of these licenses along with this + * software. If not, they may be obtained at the above URLs. + */ + +#if !defined(ARGON2_NO_THREADS) + +/* #include "thread.h" */ + +#if defined(_WIN32) +#include +#endif + +ARGON2_PRIVATE +int argon2_thread_create(argon2_thread_handle_t *handle, + argon2_thread_func_t func, void *args) { + if (NULL == handle || func == NULL) { + return -1; + } +#if defined(_WIN32) + *handle = _beginthreadex(NULL, 0, func, args, 0, NULL); + return *handle != 0 ? 0 : -1; +#else + return pthread_create(handle, NULL, func, args); +#endif +} + +ARGON2_PRIVATE +int argon2_thread_join(argon2_thread_handle_t handle) { +#if defined(_WIN32) + if (WaitForSingleObject((HANDLE)handle, INFINITE) == WAIT_OBJECT_0) { + return CloseHandle((HANDLE)handle) != 0 ? 0 : -1; + } + return -1; +#else + return pthread_join(handle, NULL); +#endif +} + +ARGON2_PRIVATE +void argon2_thread_exit(void) { +#if defined(_WIN32) + _endthreadex(0); +#else + pthread_exit(NULL); +#endif +} + +#endif /* ARGON2_NO_THREADS */ +/*** End of #include "src/thread.c" ***/ + +/*** End of #include "argon2/libargon2.c" ***/ + +#endif + +/* #include "codec_algos.c" */ +/*** Begin of #include "codec_algos.c" ***/ +/* +** Name: codec_algos.c +** Purpose: Implementation of SQLite codec algorithms +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2020 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ +/*** Begin of #include "cipher_common.h" ***/ +/* +** Name: cipher_common.h +** Purpose: Header for the ciphers of SQLite3 Multiple Ciphers +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2022 Ulrich Telle +** License: MIT +*/ + +#ifndef CIPHER_COMMON_H_ +#define CIPHER_COMMON_H_ + +/* #include "sqlite3mc.h" */ + + +/* +// ATTENTION: Macro similar to that in pager.c +// TODO: Check in case of new version of SQLite +*/ +#define WX_PAGER_MJ_PGNO(x) ((PENDING_BYTE/(x))+1) + +#define CODEC_TYPE_DEFAULT CODEC_TYPE_CHACHA20 + +#ifndef CODEC_TYPE +#define CODEC_TYPE CODEC_TYPE_DEFAULT +#endif + +#if CODEC_TYPE < 1 || CODEC_TYPE > CODEC_TYPE_MAX_BUILTIN +#error "Invalid codec type selected" +#endif + +/* +** Define the maximum number of ciphers that can be registered +*/ + +/* Use a reasonable upper limit for the maximum number of ciphers */ +#define CODEC_COUNT_LIMIT 16 + +#ifdef SQLITE3MC_MAX_CODEC_COUNT +/* Allow at least to register all built-in ciphers, but use a reasonable upper limit */ +#if SQLITE3MC_MAX_CODEC_COUNT >= CODEC_TYPE_MAX_BUILTIN && SQLITE3MC_MAX_CODEC_COUNT <= CODEC_COUNT_LIMIT +#define CODEC_COUNT_MAX SQLITE3MC_MAX_CODEC_COUNT +#else +#error "Maximum cipher count not in range [CODEC_TYPE_MAX_BUILTIN .. CODEC_COUNT_LIMIT]" +#endif +#else +#define CODEC_COUNT_MAX CODEC_COUNT_LIMIT +#endif + +#define CIPHER_NAME_MAXLEN 32 +#define CIPHER_PARAMS_COUNT_MAX 64 + +#define MAXKEYLENGTH 32 +#define KEYLENGTH_AES128 16 +#define KEYLENGTH_AES256 32 +#define KEYSALT_LENGTH 16 + +#define CODEC_SHA_ITER 4001 + +typedef struct _CodecParameter +{ + char* m_name; + int m_id; + CipherParams* m_params; +} CodecParameter; + +typedef struct _Codec +{ + int m_isEncrypted; + int m_hmacCheck; + int m_walLegacy; + /* Read cipher */ + int m_hasReadCipher; + int m_readCipherType; + void* m_readCipher; + int m_readReserved; + /* Write cipher */ + int m_hasWriteCipher; + int m_writeCipherType; + void* m_writeCipher; + int m_writeReserved; + + sqlite3* m_db; /* Pointer to DB */ +#if 0 + Btree* m_bt; /* Pointer to B-tree used by DB */ +#endif + BtShared* m_btShared; /* Pointer to shared B-tree used by DB */ + unsigned char m_page[SQLITE_MAX_PAGE_SIZE + 24]; + int m_pageSize; + int m_reserved; + int m_lastError; + int m_hasKeySalt; + unsigned char m_keySalt[KEYSALT_LENGTH]; +} Codec; + +#define CIPHER_PARAMS_SENTINEL { "", 0, 0, 0, 0 } +#define CIPHER_PAGE1_OFFSET 24 + +SQLITE_PRIVATE int sqlite3mcGetCipherParameter(CipherParams* cipherParams, const char* paramName); + +SQLITE_PRIVATE int sqlite3mcGetCipherType(sqlite3* db); + +SQLITE_PRIVATE CipherParams* sqlite3mcGetCipherParams(sqlite3* db, const char* cipherName); + +SQLITE_PRIVATE int sqlite3mcCodecInit(Codec* codec); + +SQLITE_PRIVATE void sqlite3mcCodecTerm(Codec* codec); + +SQLITE_PRIVATE void sqlite3mcClearKeySalt(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcCodecSetup(Codec* codec, int cipherType, char* userPassword, int passwordLength); + +SQLITE_PRIVATE int sqlite3mcSetupWriteCipher(Codec* codec, int cipherType, char* userPassword, int passwordLength); + +SQLITE_PRIVATE void sqlite3mcSetIsEncrypted(Codec* codec, int isEncrypted); + +SQLITE_PRIVATE void sqlite3mcSetReadCipherType(Codec* codec, int cipherType); + +SQLITE_PRIVATE void sqlite3mcSetWriteCipherType(Codec* codec, int cipherType); + +SQLITE_PRIVATE void sqlite3mcSetHasReadCipher(Codec* codec, int hasReadCipher); + +SQLITE_PRIVATE void sqlite3mcSetHasWriteCipher(Codec* codec, int hasWriteCipher); + +SQLITE_PRIVATE void sqlite3mcSetDb(Codec* codec, sqlite3* db); + +SQLITE_PRIVATE void sqlite3mcSetBtree(Codec* codec, Btree* bt); + +SQLITE_PRIVATE void sqlite3mcSetReadReserved(Codec* codec, int reserved); + +SQLITE_PRIVATE void sqlite3mcSetWriteReserved(Codec* codec, int reserved); + +SQLITE_PRIVATE int sqlite3mcIsEncrypted(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcHasReadCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcHasWriteCipher(Codec* codec); + +SQLITE_PRIVATE BtShared* sqlite3mcGetBtShared(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetPageSize(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetReadReserved(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetWriteReserved(Codec* codec); + +SQLITE_PRIVATE unsigned char* sqlite3mcGetPageBuffer(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetLegacyReadCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetLegacyWriteCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetPageSizeReadCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetPageSizeWriteCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetReservedReadCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcGetReservedWriteCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcReservedEqual(Codec* codec); + +SQLITE_PRIVATE void sqlite3mcSetCodecLastError(Codec* codec, int error); +SQLITE_PRIVATE int sqlite3mcGetCodecLastError(Codec* codec); + +SQLITE_PRIVATE unsigned char* sqlite3mcGetSaltWriteCipher(Codec* codec); + +SQLITE_PRIVATE int sqlite3mcCodecCopy(Codec* codec, Codec* other); + +SQLITE_PRIVATE void sqlite3mcGenerateReadKey(Codec* codec, char* userPassword, int passwordLength, unsigned char* cipherSalt); + +SQLITE_PRIVATE void sqlite3mcGenerateWriteKey(Codec* codec, char* userPassword, int passwordLength, unsigned char* cipherSalt); + +SQLITE_PRIVATE int sqlite3mcEncrypt(Codec* codec, int page, unsigned char* data, int len, int useWriteKey); + +SQLITE_PRIVATE int sqlite3mcDecrypt(Codec* codec, int page, unsigned char* data, int len); + +SQLITE_PRIVATE int sqlite3mcCopyCipher(Codec* codec, int read2write); + +SQLITE_PRIVATE void sqlite3mcPadPassword(char* password, int pswdlen, unsigned char pswd[32]); + +SQLITE_PRIVATE void sqlite3mcRC4(unsigned char* key, int keylen, unsigned char* textin, int textlen, unsigned char* textout); + +SQLITE_PRIVATE void sqlite3mcGetMD5Binary(unsigned char* data, int length, unsigned char* digest); + +SQLITE_PRIVATE void sqlite3mcGetSHABinary(unsigned char* data, int length, unsigned char* digest); + +SQLITE_PRIVATE void sqlite3mcGenerateInitialVector(int seed, unsigned char iv[16]); + +SQLITE_PRIVATE int sqlite3mcIsHexKey(const unsigned char* hex, int len); + +SQLITE_PRIVATE int sqlite3mcConvertHex2Int(char c); + +SQLITE_PRIVATE void sqlite3mcConvertHex2Bin(const unsigned char* hex, int len, unsigned char* bin); + +SQLITE_PRIVATE int sqlite3mcConfigureFromUri(sqlite3* db, const char *zDbName, int configDefault); + +SQLITE_PRIVATE void sqlite3mcConfigureSQLCipherVersion(sqlite3* db, int configDefault, int legacyVersion); + +SQLITE_PRIVATE int sqlite3mcCodecAttach(sqlite3* db, int nDb, const char* zPath, const void* zKey, int nKey); + +SQLITE_PRIVATE void sqlite3mcCodecGetKey(sqlite3* db, int nDb, void** zKey, int* nKey); + +SQLITE_PRIVATE void sqlite3mcSecureZeroMemory(void* v, size_t n); + +/* Debugging */ + +#if 0 +#define SQLITE3MC_DEBUG +#define SQLITE3MC_DEBUG_DATA +#endif + +#ifdef SQLITE3MC_DEBUG +#define SQLITE3MC_DEBUG_LOG(...) { fprintf(stdout, __VA_ARGS__); fflush(stdout); } +#else +#define SQLITE3MC_DEBUG_LOG(...) +#endif + +#ifdef SQLITE3MC_DEBUG_DATA +#define SQLITE3MC_DEBUG_HEX(DESC,BUFFER,LEN) \ + { \ + int count; \ + printf(DESC); \ + for (count = 0; count < LEN; ++count) \ + { \ + if (count % 16 == 0) printf("\n%05x: ", count); \ + printf("%02x ", ((unsigned char*) BUFFER)[count]); \ + } \ + printf("\n"); \ + fflush(stdout); \ + } +#else +#define SQLITE3MC_DEBUG_HEX(DESC,BUFFER,LEN) +#endif + +/* +** If encryption was enabled and WAL journal mode was used, +** SQLite3 Multiple Ciphers encrypted the WAL journal frames up to version 1.2.5 +** within the VFS implementation. As a consequence the WAL journal file was not +** compatible with legacy encryption implementations (for example, System.Data.SQLite +** or SQLCipher). Additionally, the implementation of the WAL journal encryption +** was broken, because reading and writing of complete WAL frames was not handled +** correctly. Usually, operating in WAL journal mode worked nevertheless, but after +** crashes the WAL journal file could be corrupted leading to data loss. +** +** Version 1.3.0 introduced a new way to handle WAL journal encryption. The advantage +** is that the WAL journal file is now compatible with legacy encryption implementations. +** Unfortunately the new implementation is not compatible with that used up to version +** 1.2.5. To be able to access WAL journals created by prior versions, the configuration +** parameter 'mc_legacy_wal' was introduced. If the parameter is set to 1, then the +** prior WAL journal encryption mode is used. The default of this parameter can be set +** at compile time by setting the symbol SQLITE3MC_LEGACY_WAL accordingly, but the actual +** value can also be set at runtime using the pragma or the URI parameter 'mc_legacy_wal'. +** +** In principle, operating generally in WAL legacy mode is possible, but it is strongly +** recommended to use the WAL legacy mode only to recover WAL journals left behind by +** prior versions without data loss. +*/ +#ifndef SQLITE3MC_LEGACY_WAL +#define SQLITE3MC_LEGACY_WAL 0 +#endif + +#endif +/*** End of #include "cipher_common.h" ***/ + +#if HAVE_CIPHER_AES_128_CBC || HAVE_CIPHER_AES_256_CBC || HAVE_CIPHER_SQLCIPHER +/* #include "rijndael.h" */ + +#endif + +/* +** RC4 implementation +*/ + +SQLITE_PRIVATE void +sqlite3mcRC4(unsigned char* key, int keylen, + unsigned char* textin, int textlen, + unsigned char* textout) +{ + int i; + int j; + int t; + unsigned char rc4[256]; + + int a = 0; + int b = 0; + unsigned char k; + + for (i = 0; i < 256; i++) + { + rc4[i] = i; + } + j = 0; + for (i = 0; i < 256; i++) + { + t = rc4[i]; + j = (j + t + key[i % keylen]) % 256; + rc4[i] = rc4[j]; + rc4[j] = t; + } + + for (i = 0; i < textlen; i++) + { + a = (a + 1) % 256; + t = rc4[a]; + b = (b + t) % 256; + rc4[a] = rc4[b]; + rc4[b] = t; + k = rc4[(rc4[a] + rc4[b]) % 256]; + textout[i] = textin[i] ^ k; + } +} + +SQLITE_PRIVATE void +sqlite3mcGetMD5Binary(unsigned char* data, int length, unsigned char* digest) +{ + MD5_CTX ctx; + MD5_Init(&ctx); + MD5_Update(&ctx, data, length); + MD5_Final(digest,&ctx); +} + +SQLITE_PRIVATE void +sqlite3mcGetSHABinary(unsigned char* data, int length, unsigned char* digest) +{ + sha256(data, (unsigned int) length, digest); +} + +#define MODMULT(a, b, c, m, s) q = s / a; s = b * (s - a * q) - c * q; if (s < 0) s += m + +SQLITE_PRIVATE void +sqlite3mcGenerateInitialVector(int seed, unsigned char iv[16]) +{ + unsigned char initkey[16]; + int j, q; + int z = seed + 1; + for (j = 0; j < 4; j++) + { + MODMULT(52774, 40692, 3791, 2147483399L, z); + initkey[4*j+0] = 0xff & z; + initkey[4*j+1] = 0xff & (z >> 8); + initkey[4*j+2] = 0xff & (z >> 16); + initkey[4*j+3] = 0xff & (z >> 24); + } + sqlite3mcGetMD5Binary((unsigned char*) initkey, 16, iv); +} + +#if HAVE_CIPHER_AES_128_CBC + +SQLITE_PRIVATE int +sqlite3mcAES128(Rijndael* aesCtx, int page, int encrypt, unsigned char encryptionKey[KEYLENGTH_AES128], + unsigned char* datain, int datalen, unsigned char* dataout) +{ + int rc = SQLITE_OK; + unsigned char initial[16]; + unsigned char pagekey[KEYLENGTH_AES128]; + unsigned char nkey[KEYLENGTH_AES128+4+4]; + int keyLength = KEYLENGTH_AES128; + int nkeylen = keyLength + 4 + 4; + int j; + int direction = (encrypt) ? RIJNDAEL_Direction_Encrypt : RIJNDAEL_Direction_Decrypt; + int len = 0; + + for (j = 0; j < keyLength; j++) + { + nkey[j] = encryptionKey[j]; + } + nkey[keyLength+0] = 0xff & page; + nkey[keyLength+1] = 0xff & (page >> 8); + nkey[keyLength+2] = 0xff & (page >> 16); + nkey[keyLength+3] = 0xff & (page >> 24); + + /* AES encryption needs some 'salt' */ + nkey[keyLength+4] = 0x73; + nkey[keyLength+5] = 0x41; + nkey[keyLength+6] = 0x6c; + nkey[keyLength+7] = 0x54; + + sqlite3mcGetMD5Binary(nkey, nkeylen, pagekey); + sqlite3mcGenerateInitialVector(page, initial); + RijndaelInit(aesCtx, RIJNDAEL_Direction_Mode_CBC, direction, pagekey, RIJNDAEL_Direction_KeyLength_Key16Bytes, initial); + if (encrypt) + { + len = RijndaelBlockEncrypt(aesCtx, datain, datalen*8, dataout); + } + else + { + len = RijndaelBlockDecrypt(aesCtx, datain, datalen*8, dataout); + } + + /* It is a good idea to check the error code */ + if (len < 0) + { + /* AES: Error on encrypting. */ + rc = SQLITE_ERROR; + } + return rc; +} + +#endif + +#if HAVE_CIPHER_AES_256_CBC + +SQLITE_PRIVATE int +sqlite3mcAES256(Rijndael* aesCtx, int page, int encrypt, unsigned char encryptionKey[KEYLENGTH_AES256], + unsigned char* datain, int datalen, unsigned char* dataout) +{ + int rc = SQLITE_OK; + unsigned char initial[16]; + unsigned char pagekey[KEYLENGTH_AES256]; + unsigned char nkey[KEYLENGTH_AES256+4+4]; + int keyLength = KEYLENGTH_AES256; + int nkeylen = keyLength + 4 + 4; + int j; + int direction = (encrypt) ? RIJNDAEL_Direction_Encrypt : RIJNDAEL_Direction_Decrypt; + int len = 0; + + for (j = 0; j < keyLength; j++) + { + nkey[j] = encryptionKey[j]; + } + nkey[keyLength+0] = 0xff & page; + nkey[keyLength+1] = 0xff & (page >> 8); + nkey[keyLength+2] = 0xff & (page >> 16); + nkey[keyLength+3] = 0xff & (page >> 24); + + /* AES encryption needs some 'salt' */ + nkey[keyLength+4] = 0x73; + nkey[keyLength+5] = 0x41; + nkey[keyLength+6] = 0x6c; + nkey[keyLength+7] = 0x54; + + sqlite3mcGetSHABinary(nkey, nkeylen, pagekey); + sqlite3mcGenerateInitialVector(page, initial); + RijndaelInit(aesCtx, RIJNDAEL_Direction_Mode_CBC, direction, pagekey, RIJNDAEL_Direction_KeyLength_Key32Bytes, initial); + if (encrypt) + { + len = RijndaelBlockEncrypt(aesCtx, datain, datalen*8, dataout); + } + else + { + len = RijndaelBlockDecrypt(aesCtx, datain, datalen*8, dataout); + } + + /* It is a good idea to check the error code */ + if (len < 0) + { + /* AES: Error on encrypting. */ + rc = SQLITE_ERROR; + } + return rc; +} + +#endif + +/* Check hex encoding */ +SQLITE_PRIVATE int +sqlite3mcIsHexKey(const unsigned char* hex, int len) +{ + int j; + for (j = 0; j < len; ++j) + { + unsigned char c = hex[j]; + if ((c < '0' || c > '9') && (c < 'A' || c > 'F') && (c < 'a' || c > 'f')) + { + return 0; + } + } + return 1; +} + +/* Convert single hex digit */ +SQLITE_PRIVATE int +sqlite3mcConvertHex2Int(char c) +{ + return (c >= '0' && c <= '9') ? (c)-'0' : + (c >= 'A' && c <= 'F') ? (c)-'A' + 10 : + (c >= 'a' && c <= 'f') ? (c)-'a' + 10 : 0; +} + +/* Convert hex encoded string to binary */ +SQLITE_PRIVATE void +sqlite3mcConvertHex2Bin(const unsigned char* hex, int len, unsigned char* bin) +{ + int j; + for (j = 0; j < len; j += 2) + { + bin[j / 2] = (sqlite3mcConvertHex2Int(hex[j]) << 4) | sqlite3mcConvertHex2Int(hex[j + 1]); + } +} +/*** End of #include "codec_algos.c" ***/ + + +/* #include "cipher_wxaes128.c" */ +/*** Begin of #include "cipher_wxaes128.c" ***/ +/* +** Name: cipher_wxaes128.c +** Purpose: Implementation of cipher wxSQLite3 AES 128-bit +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +/* --- AES 128-bit cipher (wxSQLite3) --- */ +#if HAVE_CIPHER_AES_128_CBC + +#define CIPHER_NAME_AES128 "aes128cbc" + +/* +** Configuration parameters for "aes128cbc" +** +** - legacy mode : compatibility with first version (page 1 encrypted) +** possible values: 1 = yes, 0 = no (default) +*/ + +#ifdef WXSQLITE3_USE_OLD_ENCRYPTION_SCHEME +#define AES128_LEGACY_DEFAULT 1 +#else +#define AES128_LEGACY_DEFAULT 0 +#endif + +SQLITE_PRIVATE CipherParams mcAES128Params[] = +{ + { "legacy", AES128_LEGACY_DEFAULT, AES128_LEGACY_DEFAULT, 0, 1 }, + { "legacy_page_size", 0, 0, 0, SQLITE_MAX_PAGE_SIZE }, + CIPHER_PARAMS_SENTINEL +}; + +typedef struct _AES128Cipher +{ + int m_legacy; + int m_legacyPageSize; + int m_keyLength; + uint8_t m_key[KEYLENGTH_AES128]; + Rijndael* m_aes; +} AES128Cipher; + +static void* +AllocateAES128Cipher(sqlite3* db) +{ + AES128Cipher* aesCipher = (AES128Cipher*) sqlite3_malloc(sizeof(AES128Cipher)); + if (aesCipher != NULL) + { + aesCipher->m_aes = (Rijndael*) sqlite3_malloc(sizeof(Rijndael)); + if (aesCipher->m_aes != NULL) + { + aesCipher->m_keyLength = KEYLENGTH_AES128; + memset(aesCipher->m_key, 0, KEYLENGTH_AES128); + RijndaelCreate(aesCipher->m_aes); + } + else + { + sqlite3_free(aesCipher); + aesCipher = NULL; + } + } + if (aesCipher != NULL) + { + CipherParams* cipherParams = sqlite3mcGetCipherParams(db, CIPHER_NAME_AES128); + aesCipher->m_legacy = sqlite3mcGetCipherParameter(cipherParams, "legacy"); + aesCipher->m_legacyPageSize = sqlite3mcGetCipherParameter(cipherParams, "legacy_page_size"); + } + return aesCipher; +} + +static void +FreeAES128Cipher(void* cipher) +{ + AES128Cipher* localCipher = (AES128Cipher*) cipher; + memset(localCipher->m_aes, 0, sizeof(Rijndael)); + sqlite3_free(localCipher->m_aes); + memset(localCipher, 0, sizeof(AES128Cipher)); + sqlite3_free(localCipher); +} + +static void +CloneAES128Cipher(void* cipherTo, void* cipherFrom) +{ + AES128Cipher* aesCipherTo = (AES128Cipher*) cipherTo; + AES128Cipher* aesCipherFrom = (AES128Cipher*) cipherFrom; + aesCipherTo->m_legacy = aesCipherFrom->m_legacy; + aesCipherTo->m_legacyPageSize = aesCipherFrom->m_legacyPageSize; + aesCipherTo->m_keyLength = aesCipherFrom->m_keyLength; + memcpy(aesCipherTo->m_key, aesCipherFrom->m_key, KEYLENGTH_AES128); + RijndaelInvalidate(aesCipherTo->m_aes); + RijndaelInvalidate(aesCipherFrom->m_aes); +} + +static int +GetLegacyAES128Cipher(void* cipher) +{ + AES128Cipher* aesCipher = (AES128Cipher*)cipher; + return aesCipher->m_legacy; +} + +static int +GetPageSizeAES128Cipher(void* cipher) +{ + AES128Cipher* aesCipher = (AES128Cipher*) cipher; + int pageSize = 0; + if (aesCipher->m_legacy != 0) + { + pageSize = aesCipher->m_legacyPageSize; + if ((pageSize < 512) || (pageSize > SQLITE_MAX_PAGE_SIZE) || (((pageSize - 1) & pageSize) != 0)) + { + pageSize = 0; + } + } + return pageSize; +} + +static int +GetReservedAES128Cipher(void* cipher) +{ + return 0; +} + +static unsigned char* +GetSaltAES128Cipher(void* cipher) +{ + return NULL; +} + +static void +GenerateKeyAES128Cipher(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt) +{ + AES128Cipher* aesCipher = (AES128Cipher*) cipher; + unsigned char userPad[32]; + unsigned char ownerPad[32]; + unsigned char ownerKey[32]; + + unsigned char mkey[MD5_HASHBYTES]; + unsigned char digest[MD5_HASHBYTES]; + int keyLength = MD5_HASHBYTES; + int i, j, k; + MD5_CTX ctx; + + /* Pad passwords */ + sqlite3mcPadPassword(userPassword, passwordLength, userPad); + sqlite3mcPadPassword("", 0, ownerPad); + + /* Compute owner key */ + + MD5_Init(&ctx); + MD5_Update(&ctx, ownerPad, 32); + MD5_Final(digest, &ctx); + + /* only use for the input as many bit as the key consists of */ + for (k = 0; k < 50; ++k) + { + MD5_Init(&ctx); + MD5_Update(&ctx, digest, keyLength); + MD5_Final(digest, &ctx); + } + memcpy(ownerKey, userPad, 32); + for (i = 0; i < 20; ++i) + { + for (j = 0; j < keyLength; ++j) + { + mkey[j] = (digest[j] ^ i); + } + sqlite3mcRC4(mkey, keyLength, ownerKey, 32, ownerKey); + } + + /* Compute encryption key */ + + MD5_Init(&ctx); + MD5_Update(&ctx, userPad, 32); + MD5_Update(&ctx, ownerKey, 32); + MD5_Final(digest, &ctx); + + /* only use the really needed bits as input for the hash */ + for (k = 0; k < 50; ++k) + { + MD5_Init(&ctx); + MD5_Update(&ctx, digest, keyLength); + MD5_Final(digest, &ctx); + } + memcpy(aesCipher->m_key, digest, aesCipher->m_keyLength); +} + +static int +EncryptPageAES128Cipher(void* cipher, int page, unsigned char* data, int len, int reserved) +{ + AES128Cipher* aesCipher = (AES128Cipher*) cipher; + int rc = SQLITE_OK; + if (aesCipher->m_legacy != 0) + { + /* Use the legacy encryption scheme */ + unsigned char* key = aesCipher->m_key; + rc = sqlite3mcAES128(aesCipher->m_aes, page, 1, key, data, len, data); + } + else + { + unsigned char dbHeader[8]; + int offset = 0; + unsigned char* key = aesCipher->m_key; + if (page == 1) + { + /* Save the header bytes remaining unencrypted */ + memcpy(dbHeader, data + 16, 8); + offset = 16; + sqlite3mcAES128(aesCipher->m_aes, page, 1, key, data, 16, data); + } + rc = sqlite3mcAES128(aesCipher->m_aes, page, 1, key, data + offset, len - offset, data + offset); + if (page == 1) + { + /* Move the encrypted header bytes 16..23 to a safe position */ + memcpy(data + 8, data + 16, 8); + /* Restore the unencrypted header bytes 16..23 */ + memcpy(data + 16, dbHeader, 8); + } + } + return rc; +} + +static int +DecryptPageAES128Cipher(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck) +{ + AES128Cipher* aesCipher = (AES128Cipher*) cipher; + int rc = SQLITE_OK; + if (aesCipher->m_legacy != 0) + { + /* Use the legacy encryption scheme */ + rc = sqlite3mcAES128(aesCipher->m_aes, page, 0, aesCipher->m_key, data, len, data); + } + else + { + unsigned char dbHeader[8]; + int dbPageSize; + int offset = 0; + if (page == 1) + { + /* Save (unencrypted) header bytes 16..23 */ + memcpy(dbHeader, data + 16, 8); + /* Determine page size */ + dbPageSize = (dbHeader[0] << 8) | (dbHeader[1] << 16); + /* Check whether the database header is valid */ + /* If yes, the database follows the new encryption scheme, otherwise use the previous encryption scheme */ + if ((dbPageSize >= 512) && (dbPageSize <= SQLITE_MAX_PAGE_SIZE) && (((dbPageSize - 1) & dbPageSize) == 0) && + (dbHeader[5] == 0x40) && (dbHeader[6] == 0x20) && (dbHeader[7] == 0x20)) + { + /* Restore encrypted bytes 16..23 for new encryption scheme */ + memcpy(data + 16, data + 8, 8); + offset = 16; + } + } + rc = sqlite3mcAES128(aesCipher->m_aes, page, 0, aesCipher->m_key, data + offset, len - offset, data + offset); + if (page == 1 && offset != 0) + { + /* Verify the database header */ + if (memcmp(dbHeader, data + 16, 8) == 0) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + } + return rc; +} + +SQLITE_PRIVATE const CipherDescriptor mcAES128Descriptor = +{ + CIPHER_NAME_AES128, + AllocateAES128Cipher, + FreeAES128Cipher, + CloneAES128Cipher, + GetLegacyAES128Cipher, + GetPageSizeAES128Cipher, + GetReservedAES128Cipher, + GetSaltAES128Cipher, + GenerateKeyAES128Cipher, + EncryptPageAES128Cipher, + DecryptPageAES128Cipher +}; +#endif +/*** End of #include "cipher_wxaes128.c" ***/ + +/* #include "cipher_wxaes256.c" */ +/*** Begin of #include "cipher_wxaes256.c" ***/ +/* +** Name: cipher_wxaes256.c +** Purpose: Implementation of cipher wxSQLite3 AES 256-bit +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +/* --- AES 256-bit cipher (wxSQLite3) --- */ +#if HAVE_CIPHER_AES_256_CBC + +#define CIPHER_NAME_AES256 "aes256cbc" + +/* +** Configuration parameters for "aes256cbc" +** +** - legacy mode : compatibility with first version (page 1 encrypted) +** possible values: 1 = yes, 0 = no (default) +** - kdf_iter : number of iterations for key derivation +*/ + +#ifdef WXSQLITE3_USE_OLD_ENCRYPTION_SCHEME +#define AES256_LEGACY_DEFAULT 1 +#else +#define AES256_LEGACY_DEFAULT 0 +#endif + +SQLITE_PRIVATE CipherParams mcAES256Params[] = +{ + { "legacy", AES256_LEGACY_DEFAULT, AES256_LEGACY_DEFAULT, 0, 1 }, + { "legacy_page_size", 0, 0, 0, SQLITE_MAX_PAGE_SIZE }, + { "kdf_iter", CODEC_SHA_ITER, CODEC_SHA_ITER, 1, 0x7fffffff }, + CIPHER_PARAMS_SENTINEL +}; + + +typedef struct _AES256Cipher +{ + int m_legacy; + int m_legacyPageSize; + int m_kdfIter; + int m_keyLength; + uint8_t m_key[KEYLENGTH_AES256]; + Rijndael* m_aes; +} AES256Cipher; + +static void* +AllocateAES256Cipher(sqlite3* db) +{ + AES256Cipher* aesCipher = (AES256Cipher*) sqlite3_malloc(sizeof(AES256Cipher)); + if (aesCipher != NULL) + { + aesCipher->m_aes = (Rijndael*) sqlite3_malloc(sizeof(Rijndael)); + if (aesCipher->m_aes != NULL) + { + aesCipher->m_keyLength = KEYLENGTH_AES256; + memset(aesCipher->m_key, 0, KEYLENGTH_AES256); + RijndaelCreate(aesCipher->m_aes); + } + else + { + sqlite3_free(aesCipher); + aesCipher = NULL; + } + } + if (aesCipher != NULL) + { + CipherParams* cipherParams = sqlite3mcGetCipherParams(db, CIPHER_NAME_AES256); + aesCipher->m_legacy = sqlite3mcGetCipherParameter(cipherParams, "legacy"); + aesCipher->m_legacyPageSize = sqlite3mcGetCipherParameter(cipherParams, "legacy_page_size"); + aesCipher->m_kdfIter = sqlite3mcGetCipherParameter(cipherParams, "kdf_iter"); + } + return aesCipher; +} + +static void +FreeAES256Cipher(void* cipher) +{ + AES256Cipher* aesCipher = (AES256Cipher*) cipher; + memset(aesCipher->m_aes, 0, sizeof(Rijndael)); + sqlite3_free(aesCipher->m_aes); + memset(aesCipher, 0, sizeof(AES256Cipher)); + sqlite3_free(aesCipher); +} + +static void +CloneAES256Cipher(void* cipherTo, void* cipherFrom) +{ + AES256Cipher* aesCipherTo = (AES256Cipher*) cipherTo; + AES256Cipher* aesCipherFrom = (AES256Cipher*) cipherFrom; + aesCipherTo->m_legacy = aesCipherFrom->m_legacy; + aesCipherTo->m_legacyPageSize = aesCipherFrom->m_legacyPageSize; + aesCipherTo->m_kdfIter = aesCipherFrom->m_kdfIter; + aesCipherTo->m_keyLength = aesCipherFrom->m_keyLength; + memcpy(aesCipherTo->m_key, aesCipherFrom->m_key, KEYLENGTH_AES256); + RijndaelInvalidate(aesCipherTo->m_aes); + RijndaelInvalidate(aesCipherFrom->m_aes); +} + +static int +GetLegacyAES256Cipher(void* cipher) +{ + AES256Cipher* aesCipher = (AES256Cipher*)cipher; + return aesCipher->m_legacy; +} + +static int +GetPageSizeAES256Cipher(void* cipher) +{ + AES256Cipher* aesCipher = (AES256Cipher*) cipher; + int pageSize = 0; + if (aesCipher->m_legacy != 0) + { + pageSize = aesCipher->m_legacyPageSize; + if ((pageSize < 512) || (pageSize > SQLITE_MAX_PAGE_SIZE) || (((pageSize - 1) & pageSize) != 0)) + { + pageSize = 0; + } + } + return pageSize; +} + +static int +GetReservedAES256Cipher(void* cipher) +{ + return 0; +} + +static unsigned char* +GetSaltAES256Cipher(void* cipher) +{ + return NULL; +} + +static void +GenerateKeyAES256Cipher(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt) +{ + AES256Cipher* aesCipher = (AES256Cipher*) cipher; + unsigned char userPad[32]; + unsigned char digest[KEYLENGTH_AES256]; + int keyLength = KEYLENGTH_AES256; + int k; + + /* Pad password */ + sqlite3mcPadPassword(userPassword, passwordLength, userPad); + + sha256(userPad, 32, digest); + for (k = 0; k < CODEC_SHA_ITER; ++k) + { + sha256(digest, KEYLENGTH_AES256, digest); + } + memcpy(aesCipher->m_key, digest, aesCipher->m_keyLength); +} + +static int +EncryptPageAES256Cipher(void* cipher, int page, unsigned char* data, int len, int reserved) +{ + AES256Cipher* aesCipher = (AES256Cipher*) cipher; + int rc = SQLITE_OK; + if (aesCipher->m_legacy != 0) + { + /* Use the legacy encryption scheme */ + unsigned char* key = aesCipher->m_key; + rc = sqlite3mcAES256(aesCipher->m_aes, page, 1, key, data, len, data); + } + else + { + unsigned char dbHeader[8]; + int offset = 0; + unsigned char* key = aesCipher->m_key; + if (page == 1) + { + /* Save the header bytes remaining unencrypted */ + memcpy(dbHeader, data + 16, 8); + offset = 16; + sqlite3mcAES256(aesCipher->m_aes, page, 1, key, data, 16, data); + } + rc = sqlite3mcAES256(aesCipher->m_aes, page, 1, key, data + offset, len - offset, data + offset); + if (page == 1) + { + /* Move the encrypted header bytes 16..23 to a safe position */ + memcpy(data + 8, data + 16, 8); + /* Restore the unencrypted header bytes 16..23 */ + memcpy(data + 16, dbHeader, 8); + } + } + return rc; +} + +static int +DecryptPageAES256Cipher(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck) +{ + AES256Cipher* aesCipher = (AES256Cipher*) cipher; + int rc = SQLITE_OK; + if (aesCipher->m_legacy != 0) + { + /* Use the legacy encryption scheme */ + rc = sqlite3mcAES256(aesCipher->m_aes, page, 0, aesCipher->m_key, data, len, data); + } + else + { + unsigned char dbHeader[8]; + int dbPageSize; + int offset = 0; + if (page == 1) + { + /* Save (unencrypted) header bytes 16..23 */ + memcpy(dbHeader, data + 16, 8); + /* Determine page size */ + dbPageSize = (dbHeader[0] << 8) | (dbHeader[1] << 16); + /* Check whether the database header is valid */ + /* If yes, the database follows the new encryption scheme, otherwise use the previous encryption scheme */ + if ((dbPageSize >= 512) && (dbPageSize <= SQLITE_MAX_PAGE_SIZE) && (((dbPageSize - 1) & dbPageSize) == 0) && + (dbHeader[5] == 0x40) && (dbHeader[6] == 0x20) && (dbHeader[7] == 0x20)) + { + /* Restore encrypted bytes 16..23 for new encryption scheme */ + memcpy(data + 16, data + 8, 8); + offset = 16; + } + } + rc = sqlite3mcAES256(aesCipher->m_aes, page, 0, aesCipher->m_key, data + offset, len - offset, data + offset); + if (page == 1 && offset != 0) + { + /* Verify the database header */ + if (memcmp(dbHeader, data + 16, 8) == 0) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + } + return rc; +} + +SQLITE_PRIVATE const CipherDescriptor mcAES256Descriptor = +{ + CIPHER_NAME_AES256, + AllocateAES256Cipher, + FreeAES256Cipher, + CloneAES256Cipher, + GetLegacyAES256Cipher, + GetPageSizeAES256Cipher, + GetReservedAES256Cipher, + GetSaltAES256Cipher, + GenerateKeyAES256Cipher, + EncryptPageAES256Cipher, + DecryptPageAES256Cipher +}; +#endif +/*** End of #include "cipher_wxaes256.c" ***/ + +/* #include "cipher_chacha20.c" */ +/*** Begin of #include "cipher_chacha20.c" ***/ +/* +** Name: cipher_chacha20.c +** Purpose: Implementation of cipher ChaCha20 - Poly1305 +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +/* --- ChaCha20-Poly1305 cipher (plus sqleet variant) --- */ +#if HAVE_CIPHER_CHACHA20 + +#define CIPHER_NAME_CHACHA20 "chacha20" + +/* +** Configuration parameters for "chacha20" +** +** - legacy mode : compatibility with original sqleet +** (page 1 encrypted, kdf_iter = 12345) +** possible values: 1 = yes, 0 = no +** - kdf_iter : number of iterations for key derivation +*/ + +#ifdef SQLITE3MC_USE_SQLEET_LEGACY +#define CHACHA20_LEGACY_DEFAULT 1 +#else +#define CHACHA20_LEGACY_DEFAULT 0 +#endif + +#define CHACHA20_KDF_ITER_DEFAULT 64007 +#define SQLEET_KDF_ITER 12345 +#define CHACHA20_LEGACY_PAGE_SIZE 4096 + +SQLITE_PRIVATE CipherParams mcChaCha20Params[] = +{ + { "legacy", CHACHA20_LEGACY_DEFAULT, CHACHA20_LEGACY_DEFAULT, 0, 1 }, + { "legacy_page_size", CHACHA20_LEGACY_PAGE_SIZE, CHACHA20_LEGACY_PAGE_SIZE, 0, SQLITE_MAX_PAGE_SIZE }, + { "kdf_iter", CHACHA20_KDF_ITER_DEFAULT, CHACHA20_KDF_ITER_DEFAULT, 1, 0x7fffffff }, + CIPHER_PARAMS_SENTINEL +}; + +#define KEYLENGTH_CHACHA20 32 +#define SALTLENGTH_CHACHA20 16 +#define PAGE_NONCE_LEN_CHACHA20 16 +#define PAGE_TAG_LEN_CHACHA20 16 +#define PAGE_RESERVED_CHACHA20 (PAGE_NONCE_LEN_CHACHA20 + PAGE_TAG_LEN_CHACHA20) + +typedef struct _chacha20Cipher +{ + int m_legacy; + int m_legacyPageSize; + int m_kdfIter; + int m_keyLength; + uint8_t m_key[KEYLENGTH_CHACHA20]; + uint8_t m_salt[SALTLENGTH_CHACHA20]; +} ChaCha20Cipher; + +static void* +AllocateChaCha20Cipher(sqlite3* db) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*) sqlite3_malloc(sizeof(ChaCha20Cipher)); + if (chacha20Cipher != NULL) + { + memset(chacha20Cipher, 0, sizeof(ChaCha20Cipher)); + chacha20Cipher->m_keyLength = KEYLENGTH_CHACHA20; + memset(chacha20Cipher->m_key, 0, KEYLENGTH_CHACHA20); + memset(chacha20Cipher->m_salt, 0, SALTLENGTH_CHACHA20); + } + if (chacha20Cipher != NULL) + { + CipherParams* cipherParams = sqlite3mcGetCipherParams(db, CIPHER_NAME_CHACHA20); + chacha20Cipher->m_legacy = sqlite3mcGetCipherParameter(cipherParams, "legacy"); + chacha20Cipher->m_legacyPageSize = sqlite3mcGetCipherParameter(cipherParams, "legacy_page_size"); + chacha20Cipher->m_kdfIter = sqlite3mcGetCipherParameter(cipherParams, "kdf_iter"); + if (chacha20Cipher->m_legacy != 0) + { + chacha20Cipher->m_kdfIter = SQLEET_KDF_ITER; + } + } + return chacha20Cipher; +} + +static void +FreeChaCha20Cipher(void* cipher) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*) cipher; + memset(chacha20Cipher, 0, sizeof(ChaCha20Cipher)); + sqlite3_free(chacha20Cipher); +} + +static void +CloneChaCha20Cipher(void* cipherTo, void* cipherFrom) +{ + ChaCha20Cipher* chacha20CipherTo = (ChaCha20Cipher*) cipherTo; + ChaCha20Cipher* chacha20CipherFrom = (ChaCha20Cipher*) cipherFrom; + chacha20CipherTo->m_legacy = chacha20CipherFrom->m_legacy; + chacha20CipherTo->m_legacyPageSize = chacha20CipherFrom->m_legacyPageSize; + chacha20CipherTo->m_kdfIter = chacha20CipherFrom->m_kdfIter; + chacha20CipherTo->m_keyLength = chacha20CipherFrom->m_keyLength; + memcpy(chacha20CipherTo->m_key, chacha20CipherFrom->m_key, KEYLENGTH_CHACHA20); + memcpy(chacha20CipherTo->m_salt, chacha20CipherFrom->m_salt, SALTLENGTH_CHACHA20); +} + +static int +GetLegacyChaCha20Cipher(void* cipher) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*)cipher; + return chacha20Cipher->m_legacy; +} + +static int +GetPageSizeChaCha20Cipher(void* cipher) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*) cipher; + int pageSize = 0; + if (chacha20Cipher->m_legacy != 0) + { + pageSize = chacha20Cipher->m_legacyPageSize; + if ((pageSize < 512) || (pageSize > SQLITE_MAX_PAGE_SIZE) || (((pageSize - 1) & pageSize) != 0)) + { + pageSize = 0; + } + } + return pageSize; +} + +static int +GetReservedChaCha20Cipher(void* cipher) +{ + return PAGE_RESERVED_CHACHA20; +} + +static unsigned char* +GetSaltChaCha20Cipher(void* cipher) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*) cipher; + return chacha20Cipher->m_salt; +} + +static void +GenerateKeyChaCha20Cipher(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*) cipher; + int bypass = 0; + + int keyOnly = 1; + if (rekey || cipherSalt == NULL) + { + chacha20_rng(chacha20Cipher->m_salt, SALTLENGTH_CHACHA20); + keyOnly = 0; + } + else + { + memcpy(chacha20Cipher->m_salt, cipherSalt, SALTLENGTH_CHACHA20); + } + + /* Bypass key derivation if the key string starts with "raw:" */ + if (passwordLength > 4 && !memcmp(userPassword, "raw:", 4)) + { + const int nRaw = passwordLength - 4; + const unsigned char* zRaw = (const unsigned char*) userPassword + 4; + switch (nRaw) + { + /* Binary key (and salt) */ + case KEYLENGTH_CHACHA20 + SALTLENGTH_CHACHA20: + if (!keyOnly) + { + memcpy(chacha20Cipher->m_salt, zRaw + KEYLENGTH_CHACHA20, SALTLENGTH_CHACHA20); + } + /* fall-through */ + case KEYLENGTH_CHACHA20: + memcpy(chacha20Cipher->m_key, zRaw, KEYLENGTH_CHACHA20); + bypass = 1; + break; + + /* Hex-encoded key */ + case 2 * KEYLENGTH_CHACHA20: + if (sqlite3mcIsHexKey(zRaw, nRaw) != 0) + { + sqlite3mcConvertHex2Bin(zRaw, nRaw, chacha20Cipher->m_key); + bypass = 1; + } + break; + + /* Hex-encoded key and salt */ + case 2 * (KEYLENGTH_CHACHA20 + SALTLENGTH_CHACHA20): + if (sqlite3mcIsHexKey(zRaw, nRaw) != 0) + { + sqlite3mcConvertHex2Bin(zRaw, 2 * KEYLENGTH_CHACHA20, chacha20Cipher->m_key); + if (!keyOnly) + { + sqlite3mcConvertHex2Bin(zRaw + 2 * KEYLENGTH_CHACHA20, 2 * SALTLENGTH_CHACHA20, chacha20Cipher->m_salt); + } + bypass = 1; + } + break; + + default: + break; + } + } + + if (!bypass) + { + fastpbkdf2_hmac_sha256((unsigned char*)userPassword, passwordLength, + chacha20Cipher->m_salt, SALTLENGTH_CHACHA20, + chacha20Cipher->m_kdfIter, + chacha20Cipher->m_key, KEYLENGTH_CHACHA20); + } + SQLITE3MC_DEBUG_LOG("generate: codec=%p pFile=%p\n", chacha20Cipher, fd); + SQLITE3MC_DEBUG_HEX("generate key:", chacha20Cipher->m_key, KEYLENGTH_CHACHA20); + SQLITE3MC_DEBUG_HEX("generate salt:", chacha20Cipher->m_salt, SALTLENGTH_CHACHA20); +} + +static int +EncryptPageChaCha20Cipher(void* cipher, int page, unsigned char* data, int len, int reserved) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*) cipher; + int rc = SQLITE_OK; + int legacy = chacha20Cipher->m_legacy; + int nReserved = (reserved == 0 && legacy == 0) ? 0 : GetReservedChaCha20Cipher(cipher); + int n = len - nReserved; + + /* Generate one-time keys */ + uint8_t otk[64]; + uint32_t counter; + int offset; + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if ((legacy == 0 && nReserved > reserved) || ((legacy != 0 && nReserved != reserved))) + { + return SQLITE_CORRUPT; + } + + if (nReserved > 0) + { + /* Encrypt and authenticate */ + memset(otk, 0, 64); + chacha20_rng(data + n, PAGE_NONCE_LEN_CHACHA20); + counter = LOAD32_LE(data + n + PAGE_NONCE_LEN_CHACHA20 - 4) ^ page; + chacha20_xor(otk, 64, chacha20Cipher->m_key, data + n, counter); + + offset = (page == 1) ? (chacha20Cipher->m_legacy != 0) ? 0 : CIPHER_PAGE1_OFFSET : 0; + chacha20_xor(data + offset, n - offset, otk + 32, data + n, counter + 1); + if (page == 1) + { + memcpy(data, chacha20Cipher->m_salt, SALTLENGTH_CHACHA20); + } + poly1305(data, n + PAGE_NONCE_LEN_CHACHA20, otk, data + n + PAGE_NONCE_LEN_CHACHA20); + } + else + { + /* Encrypt only */ + uint8_t nonce[PAGE_NONCE_LEN_CHACHA20]; + memset(otk, 0, 64); + sqlite3mcGenerateInitialVector(page, nonce); + counter = LOAD32_LE(&nonce[PAGE_NONCE_LEN_CHACHA20 - 4]) ^ page; + chacha20_xor(otk, 64, chacha20Cipher->m_key, nonce, counter); + + /* Encrypt */ + offset = (page == 1) ? (chacha20Cipher->m_legacy != 0) ? 0 : CIPHER_PAGE1_OFFSET : 0; + chacha20_xor(data + offset, n - offset, otk + 32, nonce, counter + 1); + if (page == 1) + { + memcpy(data, chacha20Cipher->m_salt, SALTLENGTH_CHACHA20); + } + } + + return rc; +} + +static int +chacha20_ismemset(const void* v, unsigned char value, int len) +{ + const unsigned char* a = v; + int i = 0, result = 0; + + for (i = 0; i < len; i++) { + result |= a[i] ^ value; + } + + return (result != 0); +} + +static int +DecryptPageChaCha20Cipher(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck) +{ + ChaCha20Cipher* chacha20Cipher = (ChaCha20Cipher*) cipher; + int rc = SQLITE_OK; + int legacy = chacha20Cipher->m_legacy; + int nReserved = (reserved == 0 && legacy == 0) ? 0 : GetReservedChaCha20Cipher(cipher); + int n = len - nReserved; + + /* Generate one-time keys */ + uint8_t otk[64]; + uint32_t counter; + uint8_t tag[16]; + int offset; + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if ((legacy == 0 && nReserved > reserved) || ((legacy != 0 && nReserved != reserved))) + { + return (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + + if (nReserved > 0) + { + int allzero = 0; + /* Decrypt and verify MAC */ + memset(otk, 0, 64); + counter = LOAD32_LE(data + n + PAGE_NONCE_LEN_CHACHA20 - 4) ^ page; + chacha20_xor(otk, 64, chacha20Cipher->m_key, data + n, counter); + + /* Determine MAC and decrypt */ + allzero = chacha20_ismemset(data, 0, n); + poly1305(data, n + PAGE_NONCE_LEN_CHACHA20, otk, tag); + offset = (page == 1) ? (chacha20Cipher->m_legacy != 0) ? 0 : CIPHER_PAGE1_OFFSET : 0; + chacha20_xor(data + offset, n - offset, otk + 32, data + n, counter + 1); + + if (hmacCheck != 0) + { + /* Verify the MAC */ + if (poly1305_tagcmp(data + n + PAGE_NONCE_LEN_CHACHA20, tag)) + { + SQLITE3MC_DEBUG_LOG("decrypt: codec=%p page=%d\n", chacha20Cipher, page); + SQLITE3MC_DEBUG_HEX("decrypt key:", chacha20Cipher->m_key, 32); + SQLITE3MC_DEBUG_HEX("decrypt otk:", otk, 64); + SQLITE3MC_DEBUG_HEX("decrypt data+00:", data, 16); + SQLITE3MC_DEBUG_HEX("decrypt data+24:", data + 24, 16); + SQLITE3MC_DEBUG_HEX("decrypt data+n:", data + n, 16); + SQLITE3MC_DEBUG_HEX("decrypt tag r:", data + n + PAGE_NONCE_LEN_CHACHA20, PAGE_TAG_LEN_CHACHA20); + SQLITE3MC_DEBUG_HEX("decrypt tag c:", tag, PAGE_TAG_LEN_CHACHA20); + /* Bad MAC */ + rc = (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + } + if (page == 1 && rc == SQLITE_OK) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + else + { + /* Decrypt only */ + uint8_t nonce[PAGE_NONCE_LEN_CHACHA20]; + memset(otk, 0, 64); + sqlite3mcGenerateInitialVector(page, nonce); + counter = LOAD32_LE(&nonce[PAGE_NONCE_LEN_CHACHA20 - 4]) ^ page; + chacha20_xor(otk, 64, chacha20Cipher->m_key, nonce, counter); + + /* Decrypt */ + offset = (page == 1) ? (chacha20Cipher->m_legacy != 0) ? 0 : CIPHER_PAGE1_OFFSET : 0; + chacha20_xor(data + offset, n - offset, otk + 32, nonce, counter + 1); + if (page == 1) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + + return rc; +} + +SQLITE_PRIVATE const CipherDescriptor mcChaCha20Descriptor = +{ + CIPHER_NAME_CHACHA20, + AllocateChaCha20Cipher, + FreeChaCha20Cipher, + CloneChaCha20Cipher, + GetLegacyChaCha20Cipher, + GetPageSizeChaCha20Cipher, + GetReservedChaCha20Cipher, + GetSaltChaCha20Cipher, + GenerateKeyChaCha20Cipher, + EncryptPageChaCha20Cipher, + DecryptPageChaCha20Cipher +}; +#endif +/*** End of #include "cipher_chacha20.c" ***/ + +/* #include "cipher_sqlcipher.c" */ +/*** Begin of #include "cipher_sqlcipher.c" ***/ +/* +** Name: cipher_sqlcipher.c +** Purpose: Implementation of cipher SQLCipher (version 1 to 4) +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +/* --- SQLCipher AES256CBC-HMAC cipher --- */ +#if HAVE_CIPHER_SQLCIPHER + +#define CIPHER_NAME_SQLCIPHER "sqlcipher" + +/* +** Configuration parameters for "sqlcipher" +** +** - kdf_iter : number of iterations for key derivation +** - fast_kdf_iter : number of iterations for hmac key +** - hmac_use : flag whether to use hmac +** - hmac_pgno : storage type for page number in hmac (native, le, be) +** - hmac_salt_mask : mask byte for hmac salt +*/ + +#define SQLCIPHER_FAST_KDF_ITER 2 +#define SQLCIPHER_HMAC_USE 1 +#define SQLCIPHER_HMAC_PGNO_LE 1 +#define SQLCIPHER_HMAC_PGNO_BE 2 +#define SQLCIPHER_HMAC_PGNO_NATIVE 0 +#define SQLCIPHER_HMAC_SALT_MASK 0x3a + +#define SQLCIPHER_ALGORITHM_SHA1 0 +#define SQLCIPHER_ALGORITHM_SHA256 1 +#define SQLCIPHER_ALGORITHM_SHA512 2 + +#define SQLCIPHER_HMAC_ALGO_COMPAT 1 + +#define SQLCIPHER_VERSION_1 1 +#define SQLCIPHER_VERSION_2 2 +#define SQLCIPHER_VERSION_3 3 +#define SQLCIPHER_VERSION_4 4 +#define SQLCIPHER_VERSION_MAX SQLCIPHER_VERSION_4 + +#ifndef SQLCIPHER_VERSION_DEFAULT +#define SQLCIPHER_VERSION_DEFAULT SQLCIPHER_VERSION_4 +#endif + +#ifdef SQLITE3MC_USE_SQLCIPHER_LEGACY +#define SQLCIPHER_LEGACY_DEFAULT SQLCIPHER_VERSION_DEFAULT +#else +#define SQLCIPHER_LEGACY_DEFAULT 0 +#endif + +#if SQLCIPHER_VERSION_DEFAULT < SQLCIPHER_VERSION_4 +#define SQLCIPHER_KDF_ITER 64000 +#define SQLCIPHER_LEGACY_PAGE_SIZE 1024 +#define SQLCIPHER_KDF_ALGORITHM SQLCIPHER_ALGORITHM_SHA1 +#define SQLCIPHER_HMAC_ALGORITHM SQLCIPHER_ALGORITHM_SHA1 +#else +#define SQLCIPHER_KDF_ITER 256000 +#define SQLCIPHER_LEGACY_PAGE_SIZE 4096 +#define SQLCIPHER_KDF_ALGORITHM SQLCIPHER_ALGORITHM_SHA512 +#define SQLCIPHER_HMAC_ALGORITHM SQLCIPHER_ALGORITHM_SHA512 +#endif + +SQLITE_PRIVATE CipherParams mcSQLCipherParams[] = +{ + { "legacy", SQLCIPHER_LEGACY_DEFAULT, SQLCIPHER_LEGACY_DEFAULT, 0, SQLCIPHER_VERSION_MAX }, + { "legacy_page_size", SQLCIPHER_LEGACY_PAGE_SIZE, SQLCIPHER_LEGACY_PAGE_SIZE, 0, SQLITE_MAX_PAGE_SIZE }, + { "kdf_iter", SQLCIPHER_KDF_ITER, SQLCIPHER_KDF_ITER, 1, 0x7fffffff }, + { "fast_kdf_iter", SQLCIPHER_FAST_KDF_ITER, SQLCIPHER_FAST_KDF_ITER, 1, 0x7fffffff }, + { "hmac_use", SQLCIPHER_HMAC_USE, SQLCIPHER_HMAC_USE, 0, 1 }, + { "hmac_pgno", SQLCIPHER_HMAC_PGNO_LE, SQLCIPHER_HMAC_PGNO_LE, 0, 2 }, + { "hmac_salt_mask", SQLCIPHER_HMAC_SALT_MASK, SQLCIPHER_HMAC_SALT_MASK, 0x00, 0xff }, + { "kdf_algorithm", SQLCIPHER_KDF_ALGORITHM, SQLCIPHER_KDF_ALGORITHM, 0, 2 }, + { "hmac_algorithm", SQLCIPHER_HMAC_ALGORITHM, SQLCIPHER_HMAC_ALGORITHM, 0, 2 }, + { "hmac_algorithm_compat", SQLCIPHER_HMAC_ALGO_COMPAT, SQLCIPHER_HMAC_ALGO_COMPAT, 0, 1 }, + { "plaintext_header_size", 0, 0, 0, 100 /* restrict to db header size */ }, + CIPHER_PARAMS_SENTINEL +}; + +#define KEYLENGTH_SQLCIPHER 32 +#define SALTLENGTH_SQLCIPHER 16 +#define MAX_HMAC_LENGTH_SQLCIPHER SHA512_DIGEST_SIZE +#define PAGE_NONCE_LEN_SQLCIPHER 16 + +typedef struct _sqlCipherCipher +{ + int m_legacy; + int m_legacyPageSize; + int m_kdfIter; + int m_fastKdfIter; + int m_hmacUse; + int m_hmacPgno; + int m_hmacSaltMask; + int m_kdfAlgorithm; + int m_hmacAlgorithm; + int m_hmacAlgorithmCompat; + int m_plaintextHeaderSize; + int m_keyLength; + uint8_t m_key[KEYLENGTH_SQLCIPHER]; + uint8_t m_salt[SALTLENGTH_SQLCIPHER]; + uint8_t m_hmacKey[KEYLENGTH_SQLCIPHER]; + Rijndael* m_aes; +} SQLCipherCipher; + +static void* +AllocateSQLCipherCipher(sqlite3* db) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) sqlite3_malloc(sizeof(SQLCipherCipher)); + if (sqlCipherCipher != NULL) + { + sqlCipherCipher->m_aes = (Rijndael*)sqlite3_malloc(sizeof(Rijndael)); + if (sqlCipherCipher->m_aes != NULL) + { + sqlCipherCipher->m_keyLength = KEYLENGTH_SQLCIPHER; + memset(sqlCipherCipher->m_key, 0, KEYLENGTH_SQLCIPHER); + memset(sqlCipherCipher->m_salt, 0, SALTLENGTH_SQLCIPHER); + memset(sqlCipherCipher->m_hmacKey, 0, KEYLENGTH_SQLCIPHER); + RijndaelCreate(sqlCipherCipher->m_aes); + } + else + { + sqlite3_free(sqlCipherCipher); + sqlCipherCipher = NULL; + } + } + if (sqlCipherCipher != NULL) + { + CipherParams* cipherParams = sqlite3mcGetCipherParams(db, CIPHER_NAME_SQLCIPHER); + sqlCipherCipher->m_legacy = sqlite3mcGetCipherParameter(cipherParams, "legacy"); + sqlCipherCipher->m_legacyPageSize = sqlite3mcGetCipherParameter(cipherParams, "legacy_page_size"); + sqlCipherCipher->m_kdfIter = sqlite3mcGetCipherParameter(cipherParams, "kdf_iter"); + sqlCipherCipher->m_fastKdfIter = sqlite3mcGetCipherParameter(cipherParams, "fast_kdf_iter"); + sqlCipherCipher->m_hmacUse = sqlite3mcGetCipherParameter(cipherParams, "hmac_use"); + sqlCipherCipher->m_hmacPgno = sqlite3mcGetCipherParameter(cipherParams, "hmac_pgno"); + sqlCipherCipher->m_hmacSaltMask = sqlite3mcGetCipherParameter(cipherParams, "hmac_salt_mask"); + sqlCipherCipher->m_kdfAlgorithm = sqlite3mcGetCipherParameter(cipherParams, "kdf_algorithm"); + sqlCipherCipher->m_hmacAlgorithm = sqlite3mcGetCipherParameter(cipherParams, "hmac_algorithm"); + sqlCipherCipher->m_hmacAlgorithmCompat = sqlite3mcGetCipherParameter(cipherParams, "hmac_algorithm_compat"); + if (sqlCipherCipher->m_legacy >= SQLCIPHER_VERSION_4) + { + int plaintextHeaderSize = sqlite3mcGetCipherParameter(cipherParams, "plaintext_header_size"); + sqlCipherCipher->m_plaintextHeaderSize = (plaintextHeaderSize >=0 && plaintextHeaderSize <= 100 && plaintextHeaderSize % 16 == 0) ? plaintextHeaderSize : 0; + } + else + { + sqlCipherCipher->m_plaintextHeaderSize = 0; + } + } + return sqlCipherCipher; +} + +static void +FreeSQLCipherCipher(void* cipher) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) cipher; + memset(sqlCipherCipher->m_aes, 0, sizeof(Rijndael)); + sqlite3_free(sqlCipherCipher->m_aes); + memset(sqlCipherCipher, 0, sizeof(SQLCipherCipher)); + sqlite3_free(sqlCipherCipher); +} + +static void +CloneSQLCipherCipher(void* cipherTo, void* cipherFrom) +{ + SQLCipherCipher* sqlCipherCipherTo = (SQLCipherCipher*) cipherTo; + SQLCipherCipher* sqlCipherCipherFrom = (SQLCipherCipher*) cipherFrom; + sqlCipherCipherTo->m_legacy = sqlCipherCipherFrom->m_legacy; + sqlCipherCipherTo->m_legacyPageSize = sqlCipherCipherFrom->m_legacyPageSize; + sqlCipherCipherTo->m_kdfIter = sqlCipherCipherFrom->m_kdfIter; + sqlCipherCipherTo->m_fastKdfIter = sqlCipherCipherFrom->m_fastKdfIter; + sqlCipherCipherTo->m_hmacUse = sqlCipherCipherFrom->m_hmacUse; + sqlCipherCipherTo->m_hmacPgno = sqlCipherCipherFrom->m_hmacPgno; + sqlCipherCipherTo->m_hmacSaltMask = sqlCipherCipherFrom->m_hmacSaltMask; + sqlCipherCipherTo->m_kdfAlgorithm = sqlCipherCipherFrom->m_kdfAlgorithm; + sqlCipherCipherTo->m_hmacAlgorithm = sqlCipherCipherFrom->m_hmacAlgorithm; + sqlCipherCipherTo->m_hmacAlgorithmCompat = sqlCipherCipherFrom->m_hmacAlgorithmCompat; + sqlCipherCipherTo->m_plaintextHeaderSize = sqlCipherCipherFrom->m_plaintextHeaderSize; + sqlCipherCipherTo->m_keyLength = sqlCipherCipherFrom->m_keyLength; + memcpy(sqlCipherCipherTo->m_key, sqlCipherCipherFrom->m_key, KEYLENGTH_SQLCIPHER); + memcpy(sqlCipherCipherTo->m_salt, sqlCipherCipherFrom->m_salt, SALTLENGTH_SQLCIPHER); + memcpy(sqlCipherCipherTo->m_hmacKey, sqlCipherCipherFrom->m_hmacKey, KEYLENGTH_SQLCIPHER); + RijndaelInvalidate(sqlCipherCipherTo->m_aes); + RijndaelInvalidate(sqlCipherCipherFrom->m_aes); +} + +static int +GetLegacySQLCipherCipher(void* cipher) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*)cipher; + return sqlCipherCipher->m_legacy; +} + +static int +GetPageSizeSQLCipherCipher(void* cipher) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) cipher; + int pageSize = 0; + if (sqlCipherCipher->m_legacy != 0) + { + pageSize = sqlCipherCipher->m_legacyPageSize; + if ((pageSize < 512) || (pageSize > SQLITE_MAX_PAGE_SIZE) || (((pageSize - 1) & pageSize) != 0)) + { + pageSize = 0; + } + } + return pageSize; +} + +static int +GetReservedSQLCipherCipher(void* cipher) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) cipher; + int reserved = SALTLENGTH_SQLCIPHER; + if (sqlCipherCipher->m_hmacUse != 0) + { + switch (sqlCipherCipher->m_hmacAlgorithm) + { + case SQLCIPHER_ALGORITHM_SHA1: + case SQLCIPHER_ALGORITHM_SHA256: + reserved += SHA256_DIGEST_SIZE; + break; + case SQLCIPHER_ALGORITHM_SHA512: + default: + reserved += SHA512_DIGEST_SIZE; + break; + } + } + return reserved; +} + +static unsigned char* +GetSaltSQLCipherCipher(void* cipher) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) cipher; + return sqlCipherCipher->m_salt; +} + +static void +GenerateKeySQLCipherCipher(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) cipher; + + if (rekey || cipherSalt == NULL) + { + chacha20_rng(sqlCipherCipher->m_salt, SALTLENGTH_SQLCIPHER); + } + else + { + memcpy(sqlCipherCipher->m_salt, cipherSalt, SALTLENGTH_SQLCIPHER); + } + + if (passwordLength == ((KEYLENGTH_SQLCIPHER * 2) + 3) && + sqlite3_strnicmp(userPassword, "x'", 2) == 0 && + sqlite3mcIsHexKey((unsigned char*) (userPassword + 2), KEYLENGTH_SQLCIPHER * 2) != 0) + { + sqlite3mcConvertHex2Bin((unsigned char*) (userPassword + 2), passwordLength - 3, sqlCipherCipher->m_key); + } + else if (passwordLength == (((KEYLENGTH_SQLCIPHER + SALTLENGTH_SQLCIPHER) * 2) + 3) && + sqlite3_strnicmp(userPassword, "x'", 2) == 0 && + sqlite3mcIsHexKey((unsigned char*) (userPassword + 2), (KEYLENGTH_SQLCIPHER + SALTLENGTH_SQLCIPHER) * 2) != 0) + { + sqlite3mcConvertHex2Bin((unsigned char*) (userPassword + 2), KEYLENGTH_SQLCIPHER * 2, sqlCipherCipher->m_key); + sqlite3mcConvertHex2Bin((unsigned char*) (userPassword + 2 + KEYLENGTH_SQLCIPHER * 2), SALTLENGTH_SQLCIPHER * 2, sqlCipherCipher->m_salt); + } + else + { + switch (sqlCipherCipher->m_kdfAlgorithm) + { + case SQLCIPHER_ALGORITHM_SHA1: + fastpbkdf2_hmac_sha1((unsigned char*) userPassword, passwordLength, + sqlCipherCipher->m_salt, SALTLENGTH_SQLCIPHER, + sqlCipherCipher->m_kdfIter, + sqlCipherCipher->m_key, KEYLENGTH_SQLCIPHER); + break; + case SQLCIPHER_ALGORITHM_SHA256: + fastpbkdf2_hmac_sha256((unsigned char*) userPassword, passwordLength, + sqlCipherCipher->m_salt, SALTLENGTH_SQLCIPHER, + sqlCipherCipher->m_kdfIter, + sqlCipherCipher->m_key, KEYLENGTH_SQLCIPHER); + break; + case SQLCIPHER_ALGORITHM_SHA512: + default: + fastpbkdf2_hmac_sha512((unsigned char*) userPassword, passwordLength, + sqlCipherCipher->m_salt, SALTLENGTH_SQLCIPHER, + sqlCipherCipher->m_kdfIter, + sqlCipherCipher->m_key, KEYLENGTH_SQLCIPHER); + break; + } + } + + if (sqlCipherCipher->m_hmacUse != 0) + { + int j; + int algorithm = (sqlCipherCipher->m_hmacAlgorithmCompat) ? sqlCipherCipher->m_kdfAlgorithm : sqlCipherCipher->m_hmacAlgorithm; + unsigned char hmacSaltMask = sqlCipherCipher->m_hmacSaltMask; + unsigned char hmacSalt[SALTLENGTH_SQLCIPHER]; + memcpy(hmacSalt, sqlCipherCipher->m_salt, SALTLENGTH_SQLCIPHER); + for (j = 0; j < SALTLENGTH_SQLCIPHER; ++j) + { + hmacSalt[j] ^= hmacSaltMask; + } + switch (algorithm) + { + case SQLCIPHER_ALGORITHM_SHA1: + fastpbkdf2_hmac_sha1(sqlCipherCipher->m_key, KEYLENGTH_SQLCIPHER, + hmacSalt, SALTLENGTH_SQLCIPHER, + sqlCipherCipher->m_fastKdfIter, + sqlCipherCipher->m_hmacKey, KEYLENGTH_SQLCIPHER); + break; + case SQLCIPHER_ALGORITHM_SHA256: + fastpbkdf2_hmac_sha256(sqlCipherCipher->m_key, KEYLENGTH_SQLCIPHER, + hmacSalt, SALTLENGTH_SQLCIPHER, + sqlCipherCipher->m_fastKdfIter, + sqlCipherCipher->m_hmacKey, KEYLENGTH_SQLCIPHER); + break; + case SQLCIPHER_ALGORITHM_SHA512: + default: + fastpbkdf2_hmac_sha512(sqlCipherCipher->m_key, KEYLENGTH_SQLCIPHER, + hmacSalt, SALTLENGTH_SQLCIPHER, + sqlCipherCipher->m_fastKdfIter, + sqlCipherCipher->m_hmacKey, KEYLENGTH_SQLCIPHER); + break; + } + } +} + +static int +GetHmacSizeSQLCipherCipher(int algorithm) +{ + int hmacSize = SHA512_DIGEST_SIZE; + switch (algorithm) + { + case SQLCIPHER_ALGORITHM_SHA1: + hmacSize = SHA1_DIGEST_SIZE; + break; + case SQLCIPHER_ALGORITHM_SHA256: + hmacSize = SHA256_DIGEST_SIZE; + break; + case SQLCIPHER_ALGORITHM_SHA512: + default: + hmacSize = SHA512_DIGEST_SIZE; + break; + } + return hmacSize; +} + +static int +EncryptPageSQLCipherCipher(void* cipher, int page, unsigned char* data, int len, int reserved) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) cipher; + int rc = SQLITE_OK; + int legacy = sqlCipherCipher->m_legacy; + int nReserved = (reserved == 0 && legacy == 0) ? 0 : GetReservedSQLCipherCipher(cipher); + int n = len - nReserved; + int offset = (page == 1) ? (sqlCipherCipher->m_legacy != 0) ? 16 : 24 : 0; + int blen; + unsigned char iv[128]; + int usePlaintextHeader = 0; + + /* Check whether a plaintext header should be used */ + if (page == 1 && sqlCipherCipher->m_legacy >= SQLCIPHER_VERSION_4 && sqlCipherCipher->m_plaintextHeaderSize > 0) + { + usePlaintextHeader = 1; + offset = sqlCipherCipher->m_plaintextHeaderSize; + } + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if ((legacy == 0 && nReserved > reserved) || ((legacy != 0 && nReserved != reserved))) + { + return SQLITE_CORRUPT; + } + + /* Generate nonce (64 bytes) */ + memset(iv, 0, 128); + if (nReserved > 0) + { + chacha20_rng(iv, 128); + } + else + { + sqlite3mcGenerateInitialVector(page, iv); + } + + RijndaelInit(sqlCipherCipher->m_aes, RIJNDAEL_Direction_Mode_CBC, RIJNDAEL_Direction_Encrypt, sqlCipherCipher->m_key, RIJNDAEL_Direction_KeyLength_Key32Bytes, iv); + blen = RijndaelBlockEncrypt(sqlCipherCipher->m_aes, data + offset, (n - offset) * 8, data + offset); + if (nReserved > 0) + { + memcpy(data + n, iv, nReserved); + } + if (page == 1 && usePlaintextHeader == 0) + { + memcpy(data, sqlCipherCipher->m_salt, SALTLENGTH_SQLCIPHER); + } + + /* hmac calculation */ + if (sqlCipherCipher->m_hmacUse == 1 && nReserved > 0) + { + unsigned char pgno_raw[4]; + unsigned char hmac_out[64]; + int hmac_size = GetHmacSizeSQLCipherCipher(sqlCipherCipher->m_hmacAlgorithm); + + if (sqlCipherCipher->m_hmacPgno == SQLCIPHER_HMAC_PGNO_LE) + { + STORE32_LE(pgno_raw, page); + } + else if (sqlCipherCipher->m_hmacPgno == SQLCIPHER_HMAC_PGNO_BE) + { + STORE32_BE(pgno_raw, page); + } + else + { + memcpy(pgno_raw, &page, 4); + } + sqlcipher_hmac(sqlCipherCipher->m_hmacAlgorithm, sqlCipherCipher->m_hmacKey, KEYLENGTH_SQLCIPHER, data + offset, n + PAGE_NONCE_LEN_SQLCIPHER - offset, pgno_raw, 4, hmac_out); + memcpy(data + n + PAGE_NONCE_LEN_SQLCIPHER, hmac_out, hmac_size); + } + + return rc; +} + +static int +DecryptPageSQLCipherCipher(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck) +{ + SQLCipherCipher* sqlCipherCipher = (SQLCipherCipher*) cipher; + int rc = SQLITE_OK; + int legacy = sqlCipherCipher->m_legacy; + int nReserved = (reserved == 0 && legacy == 0) ? 0 : GetReservedSQLCipherCipher(cipher); + int n = len - nReserved; + int offset = (page == 1) ? (sqlCipherCipher->m_legacy != 0) ? 16 : 24 : 0; + int hmacOk = 1; + int blen; + unsigned char iv[128]; + int usePlaintextHeader = 0; + + /* Check whether a plaintext header should be used */ + if (page == 1 && sqlCipherCipher->m_legacy >= SQLCIPHER_VERSION_4 && sqlCipherCipher->m_plaintextHeaderSize > 0) + { + usePlaintextHeader = 1; + offset = sqlCipherCipher->m_plaintextHeaderSize; + } + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if ((legacy == 0 && nReserved > reserved) || ((legacy != 0 && nReserved != reserved))) + { + return (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + + /* Get nonce from buffer */ + if (nReserved > 0) + { + memcpy(iv, data + n, nReserved); + } + else + { + sqlite3mcGenerateInitialVector(page, iv); + } + + /* hmac check */ + if (sqlCipherCipher->m_hmacUse == 1 && nReserved > 0 && hmacCheck != 0) + { + unsigned char pgno_raw[4]; + unsigned char hmac_out[64]; + int hmac_size = GetHmacSizeSQLCipherCipher(sqlCipherCipher->m_hmacAlgorithm); + if (sqlCipherCipher->m_hmacPgno == SQLCIPHER_HMAC_PGNO_LE) + { + STORE32_LE(pgno_raw, page); + } + else if (sqlCipherCipher->m_hmacPgno == SQLCIPHER_HMAC_PGNO_BE) + { + STORE32_BE(pgno_raw, page); + } + else + { + memcpy(pgno_raw, &page, 4); + } + sqlcipher_hmac(sqlCipherCipher->m_hmacAlgorithm, sqlCipherCipher->m_hmacKey, KEYLENGTH_SQLCIPHER, data + offset, n + PAGE_NONCE_LEN_SQLCIPHER - offset, pgno_raw, 4, hmac_out); + hmacOk = (memcmp(data + n + PAGE_NONCE_LEN_SQLCIPHER, hmac_out, hmac_size) == 0); + } + + if (hmacOk != 0) + { + RijndaelInit(sqlCipherCipher->m_aes, RIJNDAEL_Direction_Mode_CBC, RIJNDAEL_Direction_Decrypt, sqlCipherCipher->m_key, RIJNDAEL_Direction_KeyLength_Key32Bytes, iv); + blen = RijndaelBlockDecrypt(sqlCipherCipher->m_aes, data + offset, (n - offset) * 8, data + offset); + if (nReserved > 0) + { + memcpy(data + n, iv, nReserved); + } + if (page == 1 && usePlaintextHeader == 0) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + else + { + /* Bad MAC */ + rc = (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + + return rc; +} +SQLITE_PRIVATE const CipherDescriptor mcSQLCipherDescriptor = +{ + CIPHER_NAME_SQLCIPHER, + AllocateSQLCipherCipher, + FreeSQLCipherCipher, + CloneSQLCipherCipher, + GetLegacySQLCipherCipher, + GetPageSizeSQLCipherCipher, + GetReservedSQLCipherCipher, + GetSaltSQLCipherCipher, + GenerateKeySQLCipherCipher, + EncryptPageSQLCipherCipher, + DecryptPageSQLCipherCipher +}; +#endif +/*** End of #include "cipher_sqlcipher.c" ***/ + +/* #include "cipher_sds_rc4.c" */ +/*** Begin of #include "cipher_sds_rc4.c" ***/ +/* +** Name: cipher_sds_rc4.c +** Purpose: Implementation of cipher System.Data.SQLite3 RC4 +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +/* --- RC4 cipher (System.Data.SQLite) --- */ +#if HAVE_CIPHER_RC4 + +#define CIPHER_NAME_RC4 "rc4" + +/* +** Configuration parameters for "rc4" +** +** - legacy mode : compatibility with System.Data.SQLite encryption +** (page 1 fully encrypted) +** only legacy mode is supported +** possible value: 1 = yes +*/ + +#define RC4_LEGACY_DEFAULT 1 + +SQLITE_PRIVATE CipherParams mcRC4Params[] = +{ + { "legacy", RC4_LEGACY_DEFAULT, RC4_LEGACY_DEFAULT, RC4_LEGACY_DEFAULT, RC4_LEGACY_DEFAULT }, + { "legacy_page_size", 0, 0, 0, SQLITE_MAX_PAGE_SIZE }, + CIPHER_PARAMS_SENTINEL +}; + + +#define KEYLENGTH_RC4 16 + +typedef struct _RC4Cipher +{ + int m_legacy; + int m_legacyPageSize; + int m_keyLength; + uint8_t m_key[KEYLENGTH_RC4]; +} RC4Cipher; + +static void* +AllocateRC4Cipher(sqlite3* db) +{ + RC4Cipher* rc4Cipher = (RC4Cipher*) sqlite3_malloc(sizeof(RC4Cipher)); + if (rc4Cipher != NULL) + { + rc4Cipher->m_keyLength = KEYLENGTH_RC4; + memset(rc4Cipher->m_key, 0, KEYLENGTH_RC4); + } + if (rc4Cipher != NULL) + { + CipherParams* cipherParams = sqlite3mcGetCipherParams(db, CIPHER_NAME_RC4); + rc4Cipher->m_legacy = sqlite3mcGetCipherParameter(cipherParams, "legacy"); + rc4Cipher->m_legacyPageSize = sqlite3mcGetCipherParameter(cipherParams, "legacy_page_size"); + } + return rc4Cipher; +} + +static void +FreeRC4Cipher(void* cipher) +{ + RC4Cipher* localCipher = (RC4Cipher*) cipher; + memset(localCipher, 0, sizeof(RC4Cipher)); + sqlite3_free(localCipher); +} + +static void +CloneRC4Cipher(void* cipherTo, void* cipherFrom) +{ + RC4Cipher* rc4CipherTo = (RC4Cipher*) cipherTo; + RC4Cipher* rc4CipherFrom = (RC4Cipher*) cipherFrom; + rc4CipherTo->m_legacy = rc4CipherFrom->m_legacy; + rc4CipherTo->m_legacyPageSize = rc4CipherFrom->m_legacyPageSize; + rc4CipherTo->m_keyLength = rc4CipherFrom->m_keyLength; + memcpy(rc4CipherTo->m_key, rc4CipherFrom->m_key, KEYLENGTH_RC4); +} + +static int +GetLegacyRC4Cipher(void* cipher) +{ + RC4Cipher* rc4Cipher = (RC4Cipher*)cipher; + return rc4Cipher->m_legacy; +} + +static int +GetPageSizeRC4Cipher(void* cipher) +{ + RC4Cipher* rc4Cipher = (RC4Cipher*) cipher; + int pageSize = 0; + if (rc4Cipher->m_legacy != 0) + { + pageSize = rc4Cipher->m_legacyPageSize; + if ((pageSize < 512) || (pageSize > SQLITE_MAX_PAGE_SIZE) || (((pageSize - 1) & pageSize) != 0)) + { + pageSize = 0; + } + } + return pageSize; +} + +static int +GetReservedRC4Cipher(void* cipher) +{ + return 0; +} + +static unsigned char* +GetSaltRC4Cipher(void* cipher) +{ + return NULL; +} + +static void +GenerateKeyRC4Cipher(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt) +{ + RC4Cipher* rc4Cipher = (RC4Cipher*) cipher; + unsigned char digest[SHA1_DIGEST_SIZE]; + sha1_ctx ctx; + + sha1_init(&ctx); + sha1_update(&ctx, userPassword, passwordLength); + sha1_final(&ctx, digest); + + memcpy(rc4Cipher->m_key, digest, 16); +/* memset(rc4Cipher->m_key+5, 0, rc4Cipher->m_keyLength-5);*/ +} + +static int +EncryptPageRC4Cipher(void* cipher, int page, unsigned char* data, int len, int reserved) +{ + RC4Cipher* rc4Cipher = (RC4Cipher*) cipher; + int rc = SQLITE_OK; + + /* Use the legacy encryption scheme */ + unsigned char* key = rc4Cipher->m_key; + sqlite3mcRC4(key, rc4Cipher->m_keyLength, data, len, data); + + return rc; +} + +static int +DecryptPageRC4Cipher(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck) +{ + RC4Cipher* rc4Cipher = (RC4Cipher*) cipher; + int rc = SQLITE_OK; + + /* Use the legacy encryption scheme */ + sqlite3mcRC4(rc4Cipher->m_key, rc4Cipher->m_keyLength, data, len, data); + + return rc; +} + +SQLITE_PRIVATE const CipherDescriptor mcRC4Descriptor = +{ + CIPHER_NAME_RC4, + AllocateRC4Cipher, + FreeRC4Cipher, + CloneRC4Cipher, + GetLegacyRC4Cipher, + GetPageSizeRC4Cipher, + GetReservedRC4Cipher, + GetSaltRC4Cipher, + GenerateKeyRC4Cipher, + EncryptPageRC4Cipher, + DecryptPageRC4Cipher +}; +#endif +/*** End of #include "cipher_sds_rc4.c" ***/ + +/* #include "cipher_ascon.c" */ +/*** Begin of #include "cipher_ascon.c" ***/ +/* +** Name: cipher_ascon.c +** Purpose: Implementation of cipher Ascon +** Author: Ulrich Telle +** Created: 2023-11-13 +** Copyright: (c) 2023-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +/* --- Ascon --- */ +#if HAVE_CIPHER_ASCON128 + +#define CIPHER_NAME_ASCON128 "ascon128" + +/* +** Configuration parameters for "ascon128a" +** +** - kdf_iter : number of iterations for key derivation +*/ + +#define ASCON128_KDF_ITER_DEFAULT 64007 + +/* #include "ascon/prolog.h" */ +/*** Begin of #include "ascon/prolog.h" ***/ +/* +** Name: prolog.h +** Purpose: Include important header files, before +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Modified by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +#ifndef PROLOG_H +#define PROLOG_H + +/* #include "word.h" */ +/*** Begin of #include "word.h" ***/ +#ifndef WORD_H_ +#define WORD_H_ + +#include +#include + +/* #include "bendian.h" */ +/*** Begin of #include "bendian.h" ***/ +#ifndef ENDIAN_H_ +#define ENDIAN_H_ + +#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + +/* macros for big endian machines */ +#ifdef PRAGMA_ENDIAN +#pragma message("Using macros for big endian machines") +#endif +#define ASCON_U64BIG(x) (x) +#define ASCON_U32BIG(x) (x) +#define ASCON_U16BIG(x) (x) + +#elif defined(_MSC_VER) || \ + (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) + +/* macros for little endian machines */ +#ifdef PRAGMA_ENDIAN +#pragma message("Using macros for little endian machines") +#endif +#define ASCON_U64BIG(x) \ + (((0x00000000000000FFULL & (x)) << 56) | \ + ((0x000000000000FF00ULL & (x)) << 40) | \ + ((0x0000000000FF0000ULL & (x)) << 24) | \ + ((0x00000000FF000000ULL & (x)) << 8) | \ + ((0x000000FF00000000ULL & (x)) >> 8) | \ + ((0x0000FF0000000000ULL & (x)) >> 24) | \ + ((0x00FF000000000000ULL & (x)) >> 40) | \ + ((0xFF00000000000000ULL & (x)) >> 56)) +#define ASCON_U32BIG(x) \ + (((0x000000FF & (x)) << 24) | ((0x0000FF00 & (x)) << 8) | \ + ((0x00FF0000 & (x)) >> 8) | ((0xFF000000 & (x)) >> 24)) +#define ASCON_U16BIG(x) (((0x00FF & (x)) << 8) | ((0xFF00 & (x)) >> 8)) + +#else +#error "Ascon byte order macros not defined in bendian.h" +#endif + +#endif /* ENDIAN_H_ */ +/*** End of #include "bendian.h" ***/ + +/* #include "forceinline.h" */ +/*** Begin of #include "forceinline.h" ***/ +#ifndef FORCEINLINE_H_ +#define FORCEINLINE_H_ + +/* define forceinline macro */ +#ifdef _MSC_VER +#define forceinline __forceinline +#elif defined(__GNUC__) +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +#define forceinline inline __attribute__((__always_inline__)) +#else +#define forceinline static inline +#endif +#elif defined(__CLANG__) +#if __has_attribute(__always_inline__) +#define forceinline inline __attribute__((__always_inline__)) +#else +#define forceinline inline +#endif +#else +#define forceinline inline +#endif + +#endif /* FORCEINLINE_H_ */ +/*** End of #include "forceinline.h" ***/ + + +typedef union { + uint64_t x; + uint32_t w[2]; + uint8_t b[8]; +} word_t; + +#define ASCON_U64TOWORD(x) ASCON_U64BIG(x) +#define ASCON_WORDTOU64(x) ASCON_U64BIG(x) +#define ASCON_LOAD(b, n) ASCON_LOADBYTES(b, n) +#define ASCON_STORE(b, w, n) ASCON_STOREBYTES(b, w, n) + +forceinline uint64_t ASCON_ROR(uint64_t x, int n) { return x >> n | x << (-n & 63); } + +forceinline uint64_t ASCON_KEYROT(uint64_t lo2hi, uint64_t hi2lo) { + return lo2hi << 32 | hi2lo >> 32; +} + +forceinline int ASCON_NOTZERO(uint64_t a, uint64_t b) { + uint64_t result = a | b; + result |= result >> 32; + result |= result >> 16; + result |= result >> 8; + return ((((int)(result & 0xff) - 1) >> 8) & 1) - 1; +} + +forceinline uint64_t ASCON_PAD(int i) { return 0x80ull << (56 - 8 * i); } + +forceinline uint64_t ASCON_DSEP() { return 0x01; } + +forceinline uint64_t ASCON_PRFS_MLEN(uint64_t len) { return len << 51; } + +forceinline uint64_t ASCON_CLEAR(uint64_t w, int n) { + /* undefined for n == 0 */ + uint64_t mask = ~0ull >> (8 * n); + return w & mask; +} + +forceinline uint64_t ASCON_MASK(int n) { + /* undefined for n == 0 */ + return ~0ull >> (64 - 8 * n); +} + +forceinline uint64_t ASCON_LOADBYTES(const uint8_t* bytes, int n) { + uint64_t x = 0; + memcpy(&x, bytes, n); + return ASCON_U64TOWORD(x); +} + +forceinline void ASCON_STOREBYTES(uint8_t* bytes, uint64_t w, int n) { + uint64_t x = ASCON_WORDTOU64(w); + memcpy(bytes, &x, n); +} + +#endif /* WORD_H_ */ +/*** End of #include "word.h" ***/ + + +#endif +/*** End of #include "ascon/prolog.h" ***/ + +/* #include "ascon/aead.c" */ +/*** Begin of #include "ascon/aead.c" ***/ +/* +** Name: aead.c +** Purpose: Stream encryption/decryption with Ascon +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Modified by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +/* #include "api.h" */ +/*** Begin of #include "api.h" ***/ +/* +** Name: api.h +** Purpose: Definition of preprocessor symbols +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Combined symbols from AEAD and HASH +** Modified by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +#define CRYPTO_VERSION "1.2.7" +#define CRYPTO_KEYBYTES 16 +#define CRYPTO_NSECBYTES 0 +#define CRYPTO_NPUBBYTES 16 +#define CRYPTO_ABYTES 16 +#define CRYPTO_NOOVERLAP 1 +#define ASCON_AEAD_RATE 8 + +#define CRYPTO_BYTES 32 +#define ASCON_HASH_BYTES 32 /* HASH */ +#define ASCON_HASH_ROUNDS 12 + +#define ASCON_AEAD_KEY_LEN CRYPTO_KEYBYTES +#define ASCON_AEAD_NONCE_LEN CRYPTO_NPUBBYTES +#define ASCON_AEAD_TAG_LEN CRYPTO_ABYTES +#define ASCON_SALT_LEN CRYPTO_NPUBBYTES +/*** End of #include "api.h" ***/ + +/* #include "ascon.h" */ +/*** Begin of #include "ascon.h" ***/ +#ifndef ASCON_H_ +#define ASCON_H_ + +#include + +/* #include "api.h" */ + +/* #include "config.h" */ +/*** Begin of #include "config.h" ***/ +#ifndef CONFIG_H_ +#define CONFIG_H_ + +/* inline the ascon mode */ +#ifndef ASCON_INLINE_MODE +#define ASCON_INLINE_MODE 1 +#endif + +/* inline all permutations */ +#ifndef ASCON_INLINE_PERM +#define ASCON_INLINE_PERM 1 +#endif + +/* unroll permutation loops */ +#ifndef ASCON_UNROLL_LOOPS +#define ASCON_UNROLL_LOOPS 1 +#endif + +#endif /* CONFIG_H_ */ +/*** End of #include "config.h" ***/ + + +typedef union { + uint64_t x[5]; + uint32_t w[5][2]; + uint8_t b[5][8]; +} ascon_state_t; + +#ifdef ASCON_AEAD_RATE + +#define ASCON_KEYWORDS (CRYPTO_KEYBYTES + 7) / 8 + +typedef union { + uint64_t x[ASCON_KEYWORDS]; + uint32_t w[ASCON_KEYWORDS][2]; + uint8_t b[ASCON_KEYWORDS][8]; +} ascon_key_t; + +#if !ASCON_INLINE_MODE + +void ascon_loadkey(ascon_key_t* key, const uint8_t* k); +void ascon_initaead(ascon_state_t* s, const ascon_key_t* key, + const uint8_t* npub); +void ascon_adata(ascon_state_t* s, const uint8_t* ad, uint64_t adlen); +void ascon_encrypt(ascon_state_t* s, uint8_t* c, const uint8_t* m, + uint64_t mlen); +void ascon_decrypt(ascon_state_t* s, uint8_t* m, const uint8_t* c, + uint64_t clen); +void ascon_final(ascon_state_t* s, const ascon_key_t* k); + +#endif + +#endif + +#ifdef ASCON_HASH_BYTES + +#if !ASCON_INLINE_MODE + +void ascon_inithash(ascon_state_t* s); +void ascon_absorb(ascon_state_t* s, const uint8_t* in, uint64_t inlen); +void ascon_squeeze(ascon_state_t* s, uint8_t* out, uint64_t outlen); + +#endif + +#endif + +#endif /* ASCON_H_ */ +/*** End of #include "ascon.h" ***/ + +/* #include "crypto_aead.h" */ +/*** Begin of #include "crypto_aead.h" ***/ +/* +** Name: hash.c +** Purpose: API definition for Hash algorithm with Ascon +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Modified by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +#ifndef CRYPTO_AEAD_H +#define CRYPTO_AEAD_H + +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE +#endif + +#include + +/* +** Encryption using ASCON-AEAD. +** +** \param ctext Output buffer for encrypted text (same length as plain text) +** \param tag Output buffer for tag with fixed length of ASCON_AEAD_TAG_LEN +** \param mtext Input buffer with plain message text +** \param mlen Length of message text +** \param ad Input buffer with associated data +** \param adlen Length of associated data +** \param nonce Buffer with nonce data +** \param k Buffer with key data +*/ +SQLITE_PRIVATE +int ascon_aead_encrypt(uint8_t* ctext, uint8_t tag[ASCON_AEAD_TAG_LEN], + const uint8_t* mtext, uint64_t mlen, + const uint8_t* ad, uint64_t adlen, + const uint8_t nonce[ASCON_AEAD_NONCE_LEN], + const uint8_t k[ASCON_AEAD_KEY_LEN]); + +/* +** Encryption using ASCON-AEAD. +** +** \param mtext Output buffer with decrypted plain message text (same length as encrypted text) +** \param ctext Input buffer for encrypted text +** \param clen Length of encrypted text +** \param ad Input buffer with associated data +** \param adlen Length of associated data +** \param tag Input buffer for expected tag with fixed length of ASCON_AEAD_TAG_LEN +** \param nonce Buffer with nonce data +** \param k Buffer with key data +*/ +SQLITE_PRIVATE +int ascon_aead_decrypt(uint8_t* mtext, const uint8_t* ctext, uint64_t clen, + const uint8_t* ad, uint64_t adlen, + const uint8_t tag[ASCON_AEAD_TAG_LEN], + const uint8_t nonce[ASCON_AEAD_NONCE_LEN], + const uint8_t k[ASCON_AEAD_KEY_LEN]); + +#endif +/*** End of #include "crypto_aead.h" ***/ + +/* #include "permutations.h" */ +/*** Begin of #include "permutations.h" ***/ +#ifndef PERMUTATIONS_H_ +#define PERMUTATIONS_H_ + +#include + +/* #include "api.h" */ + +/* #include "ascon.h" */ + +/* #include "config.h" */ + +/* #include "constants.h" */ +/*** Begin of #include "constants.h" ***/ +#ifndef CONSTANTS_H_ +#define CONSTANTS_H_ + +#include + +#define ASCON_128_KEYBYTES 16 +#define ASCON_128A_KEYBYTES 16 +#define ASCON_80PQ_KEYBYTES 20 + +#define ASCON_128_RATE 8 +#define ASCON_128A_RATE 16 +#define ASCON_HASH_RATE 8 +#define ASCON_PRF_IN_RATE 32 +#define ASCON_PRFA_IN_RATE 40 +#define ASCON_PRF_OUT_RATE 16 + +#define ASCON_128_PA_ROUNDS 12 +#define ASCON_128_PB_ROUNDS 6 +#define ASCON_128A_PA_ROUNDS 12 +#define ASCON_128A_PB_ROUNDS 8 + +#define ASCON_HASH_PA_ROUNDS 12 +#define ASCON_HASH_PB_ROUNDS 12 +#define ASCON_HASHA_PA_ROUNDS 12 +#define ASCON_HASHA_PB_ROUNDS 8 + +#define ASCON_PRF_PA_ROUNDS 12 +#define ASCON_PRF_PB_ROUNDS 12 +#define ASCON_PRFA_PA_ROUNDS 12 +#define ASCON_PRFA_PB_ROUNDS 8 + +#define ASCON_128_IV 0x80400c0600000000ull +#define ASCON_128A_IV 0x80800c0800000000ull +#define ASCON_80PQ_IV 0xa0400c0600000000ull + +#define ASCON_HASH_IV 0x00400c0000000100ull +#define ASCON_HASHA_IV 0x00400c0400000100ull +#define ASCON_XOF_IV 0x00400c0000000000ull +#define ASCON_XOFA_IV 0x00400c0400000000ull + +#define ASCON_HASH_IV0 0xee9398aadb67f03dull +#define ASCON_HASH_IV1 0x8bb21831c60f1002ull +#define ASCON_HASH_IV2 0xb48a92db98d5da62ull +#define ASCON_HASH_IV3 0x43189921b8f8e3e8ull +#define ASCON_HASH_IV4 0x348fa5c9d525e140ull + +#define ASCON_HASHA_IV0 0x01470194fc6528a6ull +#define ASCON_HASHA_IV1 0x738ec38ac0adffa7ull +#define ASCON_HASHA_IV2 0x2ec8e3296c76384cull +#define ASCON_HASHA_IV3 0xd6f6a54d7f52377dull +#define ASCON_HASHA_IV4 0xa13c42a223be8d87ull + +#define ASCON_XOF_IV0 0xb57e273b814cd416ull +#define ASCON_XOF_IV1 0x2b51042562ae2420ull +#define ASCON_XOF_IV2 0x66a3a7768ddf2218ull +#define ASCON_XOF_IV3 0x5aad0a7a8153650cull +#define ASCON_XOF_IV4 0x4f3e0e32539493b6ull + +#define ASCON_XOFA_IV0 0x44906568b77b9832ull +#define ASCON_XOFA_IV1 0xcd8d6cae53455532ull +#define ASCON_XOFA_IV2 0xf7b5212756422129ull +#define ASCON_XOFA_IV3 0x246885e1de0d225bull +#define ASCON_XOFA_IV4 0xa8cb5ce33449973full + +#define ASCON_MAC_IV 0x80808c0000000080ull +#define ASCON_MACA_IV 0x80808c0400000080ull +#define ASCON_PRF_IV 0x80808c0000000000ull +#define ASCON_PRFA_IV 0x80808c0400000000ull +#define ASCON_PRFS_IV 0x80004c8000000000ull + +#define ASCON_RC0 0xf0 +#define ASCON_RC1 0xe1 +#define ASCON_RC2 0xd2 +#define ASCON_RC3 0xc3 +#define ASCON_RC4 0xb4 +#define ASCON_RC5 0xa5 +#define ASCON_RC6 0x96 +#define ASCON_RC7 0x87 +#define ASCON_RC8 0x78 +#define ASCON_RC9 0x69 +#define ASCON_RCa 0x5a +#define ASCON_RCb 0x4b + +#define ASCON_RC(i) (i) + +#define ASCON_START(n) ((3 + (n)) << 4 | (12 - (n))) +#define ASCON_INC -0x0f +#define ASCON_END 0x3c + +#endif /* CONSTANTS_H_ */ +/*** End of #include "constants.h" ***/ + +/* #include "printstate.h" */ +/*** Begin of #include "printstate.h" ***/ +#ifndef PRINTSTATE_H_ +#define PRINTSTATE_H_ + +#ifdef ASCON_PRINT_STATE + +/* #include "ascon.h" */ + +/* #include "word.h" */ + + +void ascon_printword(const char* text, const uint64_t x); +void ascon_printstate(const char* text, const ascon_state_t* s); + +#else + +#define ascon_printword(text, w) \ + do { \ + } while (0) + +#define ascon_printstate(text, s) \ + do { \ + } while (0) + +#endif + +#endif /* PRINTSTATE_H_ */ +/*** End of #include "printstate.h" ***/ + +/* #include "round.h" */ +/*** Begin of #include "round.h" ***/ +/* +** Name: round.h +** Purpose: Selector for Ascon implementation variant for 32- resp 64-bit +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Modified by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +#ifndef ROUND_H +#define ROUND_H + +/* #include "forceinline.h" */ + + +#if defined(__LP64__) || defined(_WIN64) +/* 64-bit machine, Windows or Linux or OS X */ +/* #include "round64.h" */ +/*** Begin of #include "round64.h" ***/ +#ifndef ROUND64_H_ +#define ROUND64_H_ + +/* #include "ascon.h" */ + +/* #include "constants.h" */ + +/* #include "forceinline.h" */ + +/* #include "printstate.h" */ + +/* #include "word.h" */ + + +forceinline void ASCON_ROUND(ascon_state_t* s, uint8_t C) { + ascon_state_t t; + /* round constant */ + s->x[2] ^= C; + /* s-box layer */ + s->x[0] ^= s->x[4]; + s->x[4] ^= s->x[3]; + s->x[2] ^= s->x[1]; + t.x[0] = s->x[0] ^ (~s->x[1] & s->x[2]); + t.x[2] = s->x[2] ^ (~s->x[3] & s->x[4]); + t.x[4] = s->x[4] ^ (~s->x[0] & s->x[1]); + t.x[1] = s->x[1] ^ (~s->x[2] & s->x[3]); + t.x[3] = s->x[3] ^ (~s->x[4] & s->x[0]); + t.x[1] ^= t.x[0]; + t.x[3] ^= t.x[2]; + t.x[0] ^= t.x[4]; + /* linear layer */ + s->x[2] = t.x[2] ^ ASCON_ROR(t.x[2], 6 - 1); + s->x[3] = t.x[3] ^ ASCON_ROR(t.x[3], 17 - 10); + s->x[4] = t.x[4] ^ ASCON_ROR(t.x[4], 41 - 7); + s->x[0] = t.x[0] ^ ASCON_ROR(t.x[0], 28 - 19); + s->x[1] = t.x[1] ^ ASCON_ROR(t.x[1], 61 - 39); + s->x[2] = t.x[2] ^ ASCON_ROR(s->x[2], 1); + s->x[3] = t.x[3] ^ ASCON_ROR(s->x[3], 10); + s->x[4] = t.x[4] ^ ASCON_ROR(s->x[4], 7); + s->x[0] = t.x[0] ^ ASCON_ROR(s->x[0], 19); + s->x[1] = t.x[1] ^ ASCON_ROR(s->x[1], 39); + s->x[2] = ~s->x[2]; + ascon_printstate(" round output", s); +} + +forceinline void ASCON_PROUNDS(ascon_state_t* s, int nr) { + int i = ASCON_START(nr); + do { + ASCON_ROUND(s, ASCON_RC(i)); + i += ASCON_INC; + } while (i != ASCON_END); +} + +#endif /* ROUND64_H_ */ +/*** End of #include "round64.h" ***/ + +#else +/* 32-bit machine, Windows or Linux or OS X */ +/* #include "round32.h" */ +/*** Begin of #include "round32.h" ***/ +#ifndef ROUND32_H_ +#define ROUND32_H_ + +/* #include "ascon.h" */ + +/* #include "constants.h" */ + +/* #include "forceinline.h" */ + +/* #include "printstate.h" */ + +/* #include "word.h" */ + + +forceinline void ASCON_ROUND(ascon_state_t* s, uint8_t C) { + uint64_t xtemp; + /* round constant */ + s->x[2] ^= C; + /* s-box layer */ + s->x[0] ^= s->x[4]; + s->x[4] ^= s->x[3]; + s->x[2] ^= s->x[1]; + xtemp = s->x[0] & ~s->x[4]; + s->x[0] ^= s->x[2] & ~s->x[1]; + s->x[2] ^= s->x[4] & ~s->x[3]; + s->x[4] ^= s->x[1] & ~s->x[0]; + s->x[1] ^= s->x[3] & ~s->x[2]; + s->x[3] ^= xtemp; + s->x[1] ^= s->x[0]; + s->x[3] ^= s->x[2]; + s->x[0] ^= s->x[4]; + s->x[2] = ~s->x[2]; + /* linear layer */ + s->x[0] ^= + (s->x[0] >> 19) ^ (s->x[0] << 45) ^ (s->x[0] >> 28) ^ (s->x[0] << 36); + s->x[1] ^= + (s->x[1] >> 61) ^ (s->x[1] << 3) ^ (s->x[1] >> 39) ^ (s->x[1] << 25); + s->x[2] ^= + (s->x[2] >> 1) ^ (s->x[2] << 63) ^ (s->x[2] >> 6) ^ (s->x[2] << 58); + s->x[3] ^= + (s->x[3] >> 10) ^ (s->x[3] << 54) ^ (s->x[3] >> 17) ^ (s->x[3] << 47); + s->x[4] ^= + (s->x[4] >> 7) ^ (s->x[4] << 57) ^ (s->x[4] >> 41) ^ (s->x[4] << 23); + ascon_printstate(" round output", s); +} + +forceinline void ASCON_PROUNDS(ascon_state_t* s, int nr) { + int i = ASCON_START(nr); + do { + ASCON_ROUND(s, ASCON_RC(i)); + i += ASCON_INC; + } while (i != ASCON_END); +} + +#endif /* ROUND32_H_ */ +/*** End of #include "round32.h" ***/ + +#endif + +#endif +/*** End of #include "round.h" ***/ + + +forceinline void ASCON_P12ROUNDS(ascon_state_t* s) { + ASCON_ROUND(s, ASCON_RC0); + ASCON_ROUND(s, ASCON_RC1); + ASCON_ROUND(s, ASCON_RC2); + ASCON_ROUND(s, ASCON_RC3); + ASCON_ROUND(s, ASCON_RC4); + ASCON_ROUND(s, ASCON_RC5); + ASCON_ROUND(s, ASCON_RC6); + ASCON_ROUND(s, ASCON_RC7); + ASCON_ROUND(s, ASCON_RC8); + ASCON_ROUND(s, ASCON_RC9); + ASCON_ROUND(s, ASCON_RCa); + ASCON_ROUND(s, ASCON_RCb); +} + +forceinline void ASCON_P8ROUNDS(ascon_state_t* s) { + ASCON_ROUND(s, ASCON_RC4); + ASCON_ROUND(s, ASCON_RC5); + ASCON_ROUND(s, ASCON_RC6); + ASCON_ROUND(s, ASCON_RC7); + ASCON_ROUND(s, ASCON_RC8); + ASCON_ROUND(s, ASCON_RC9); + ASCON_ROUND(s, ASCON_RCa); + ASCON_ROUND(s, ASCON_RCb); +} + +forceinline void ASCON_P6ROUNDS(ascon_state_t* s) { + ASCON_ROUND(s, ASCON_RC6); + ASCON_ROUND(s, ASCON_RC7); + ASCON_ROUND(s, ASCON_RC8); + ASCON_ROUND(s, ASCON_RC9); + ASCON_ROUND(s, ASCON_RCa); + ASCON_ROUND(s, ASCON_RCb); +} + +#if ASCON_INLINE_PERM && ASCON_UNROLL_LOOPS + +forceinline void ASCON_P(ascon_state_t* s, int nr) { + if (nr == 12) ASCON_P12ROUNDS(s); + if (nr == 8) ASCON_P8ROUNDS(s); + if (nr == 6) ASCON_P6ROUNDS(s); +} + +#elif !ASCON_INLINE_PERM && ASCON_UNROLL_LOOPS + +void ASCON_P12(ascon_state_t* s); +void ASCON_P8(ascon_state_t* s); +void ASCON_P6(ascon_state_t* s); + +forceinline void ASCON_P(ascon_state_t* s, int nr) { + if (nr == 12) ASCON_P12(s); + if (nr == 8) ASCON_P8(s); + if (nr == 6) ASCON_P6(s); +} + +#elif ASCON_INLINE_PERM && !ASCON_UNROLL_LOOPS + +forceinline void ASCON_P(ascon_state_t* s, int nr) { ASCON_PROUNDS(s, nr); } + +#else /* !ASCON_INLINE_PERM && !ASCON_UNROLL_LOOPS */ + +void ASCON_P(ascon_state_t* s, int nr); + +#endif + +#endif /* PERMUTATIONS_H_ */ +/*** End of #include "permutations.h" ***/ + +/* #include "printstate.h" */ + + +#if !ASCON_INLINE_MODE +#undef forceinline +#define forceinline +#endif + +#ifdef ASCON_AEAD_RATE + +forceinline void ascon_loadkey(ascon_key_t* key, const uint8_t* k) { +#if CRYPTO_KEYBYTES == 16 + key->x[0] = ASCON_LOAD(k, 8); + key->x[1] = ASCON_LOAD(k + 8, 8); +#else /* CRYPTO_KEYBYTES == 20 */ + key->x[0] = ASCON_KEYROT(0, ASCON_LOADBYTES(k, 4)); + key->x[1] = ASCON_LOADBYTES(k + 4, 8); + key->x[2] = ASCON_LOADBYTES(k + 12, 8); +#endif +} + +forceinline void ascon_initaead(ascon_state_t* s, const ascon_key_t* key, + const uint8_t* npub) { +#if CRYPTO_KEYBYTES == 16 + if (ASCON_AEAD_RATE == 8) s->x[0] = ASCON_128_IV; + if (ASCON_AEAD_RATE == 16) s->x[0] = ASCON_128A_IV; + s->x[1] = key->x[0]; + s->x[2] = key->x[1]; +#else /* CRYPTO_KEYBYTES == 20 */ + s->x[0] = key->x[0] ^ ASCON_80PQ_IV; + s->x[1] = key->x[1]; + s->x[2] = key->x[2]; +#endif + s->x[3] = ASCON_LOAD(npub, 8); + s->x[4] = ASCON_LOAD(npub + 8, 8); + ascon_printstate("init 1st key xor", s); + ASCON_P(s, 12); +#if CRYPTO_KEYBYTES == 16 + s->x[3] ^= key->x[0]; + s->x[4] ^= key->x[1]; +#else /* CRYPTO_KEYBYTES == 20 */ + s->x[2] ^= key->x[0]; + s->x[3] ^= key->x[1]; + s->x[4] ^= key->x[2]; +#endif + ascon_printstate("init 2nd key xor", s); +} + +forceinline void ascon_adata(ascon_state_t* s, const uint8_t* ad, + uint64_t adlen) { + const int nr = (ASCON_AEAD_RATE == 8) ? 6 : 8; + if (adlen) { + /* full associated data blocks */ + while (adlen >= ASCON_AEAD_RATE) { + s->x[0] ^= ASCON_LOAD(ad, 8); + if (ASCON_AEAD_RATE == 16) s->x[1] ^= ASCON_LOAD(ad + 8, 8); + ascon_printstate("absorb adata", s); + ASCON_P(s, nr); + ad += ASCON_AEAD_RATE; + adlen -= ASCON_AEAD_RATE; + } + /* final associated data block */ + uint64_t* px = &s->x[0]; + if (ASCON_AEAD_RATE == 16 && adlen >= 8) { + s->x[0] ^= ASCON_LOAD(ad, 8); + px = &s->x[1]; + ad += 8; + adlen -= 8; + } + *px ^= ASCON_PAD(adlen); + if (adlen) *px ^= ASCON_LOADBYTES(ad, adlen); + ascon_printstate("pad adata", s); + ASCON_P(s, nr); + } + /* domain separation */ + s->x[4] ^= ASCON_DSEP(); + ascon_printstate("domain separation", s); +} + +forceinline void ascon_encrypt(ascon_state_t* s, uint8_t* c, const uint8_t* m, + uint64_t mlen) { + const int nr = (ASCON_AEAD_RATE == 8) ? 6 : 8; + /* full plaintext blocks */ + while (mlen >= ASCON_AEAD_RATE) { + s->x[0] ^= ASCON_LOAD(m, 8); + ASCON_STORE(c, s->x[0], 8); + if (ASCON_AEAD_RATE == 16) { + s->x[1] ^= ASCON_LOAD(m + 8, 8); + ASCON_STORE(c + 8, s->x[1], 8); + } + ascon_printstate("absorb plaintext", s); + ASCON_P(s, nr); + m += ASCON_AEAD_RATE; + c += ASCON_AEAD_RATE; + mlen -= ASCON_AEAD_RATE; + } + /* final plaintext block */ + uint64_t* px = &s->x[0]; + if (ASCON_AEAD_RATE == 16 && mlen >= 8) { + s->x[0] ^= ASCON_LOAD(m, 8); + ASCON_STORE(c, s->x[0], 8); + px = &s->x[1]; + m += 8; + c += 8; + mlen -= 8; + } + *px ^= ASCON_PAD(mlen); + if (mlen) { + *px ^= ASCON_LOADBYTES(m, mlen); + ASCON_STOREBYTES(c, *px, mlen); + } + ascon_printstate("pad plaintext", s); +} + +forceinline void ascon_decrypt(ascon_state_t* s, uint8_t* m, const uint8_t* c, + uint64_t clen) { + const int nr = (ASCON_AEAD_RATE == 8) ? 6 : 8; + /* full ciphertext blocks */ + while (clen >= ASCON_AEAD_RATE) { + uint64_t cx = ASCON_LOAD(c, 8); + s->x[0] ^= cx; + ASCON_STORE(m, s->x[0], 8); + s->x[0] = cx; + if (ASCON_AEAD_RATE == 16) { + cx = ASCON_LOAD(c + 8, 8); + s->x[1] ^= cx; + ASCON_STORE(m + 8, s->x[1], 8); + s->x[1] = cx; + } + ascon_printstate("insert ciphertext", s); + ASCON_P(s, nr); + m += ASCON_AEAD_RATE; + c += ASCON_AEAD_RATE; + clen -= ASCON_AEAD_RATE; + } + /* final ciphertext block */ + uint64_t* px = &s->x[0]; + if (ASCON_AEAD_RATE == 16 && clen >= 8) { + uint64_t cx = ASCON_LOAD(c, 8); + s->x[0] ^= cx; + ASCON_STORE(m, s->x[0], 8); + s->x[0] = cx; + px = &s->x[1]; + m += 8; + c += 8; + clen -= 8; + } + *px ^= ASCON_PAD(clen); + if (clen) { + uint64_t cx = ASCON_LOADBYTES(c, clen); + *px ^= cx; + ASCON_STOREBYTES(m, *px, clen); + *px = ASCON_CLEAR(*px, clen); + *px ^= cx; + } + ascon_printstate("pad ciphertext", s); +} + +forceinline void ascon_final(ascon_state_t* s, const ascon_key_t* key) { +#if CRYPTO_KEYBYTES == 16 + if (ASCON_AEAD_RATE == 8) { + s->x[1] ^= key->x[0]; + s->x[2] ^= key->x[1]; + } else { + s->x[2] ^= key->x[0]; + s->x[3] ^= key->x[1]; + } +#else /* CRYPTO_KEYBYTES == 20 */ + s->x[1] ^= KEYROT(key->x[0], key->x[1]); + s->x[2] ^= KEYROT(key->x[1], key->x[2]); + s->x[3] ^= KEYROT(key->x[2], 0); +#endif + ascon_printstate("final 1st key xor", s); + ASCON_P(s, 12); +#if CRYPTO_KEYBYTES == 16 + s->x[3] ^= key->x[0]; + s->x[4] ^= key->x[1]; +#else /* CRYPTO_KEYBYTES == 20 */ + s->x[3] ^= key->x[1]; + s->x[4] ^= key->x[2]; +#endif + ascon_printstate("final 2nd key xor", s); +} + +SQLITE_PRIVATE +int ascon_aead_encrypt(uint8_t* ctext, + uint8_t tag[ASCON_AEAD_TAG_LEN], + const uint8_t* mtext, uint64_t mlen, + const uint8_t* ad, uint64_t adlen, + const uint8_t nonce[ASCON_AEAD_NONCE_LEN], + const uint8_t k[ASCON_AEAD_KEY_LEN]) +{ + ascon_state_t s; + /* perform ascon computation */ + ascon_key_t key; + ascon_loadkey(&key, k); + ascon_initaead(&s, &key, nonce); + ascon_adata(&s, ad, adlen); + ascon_encrypt(&s, ctext, mtext, mlen); + ascon_final(&s, &key); + /* set tag */ + ASCON_STOREBYTES(tag, s.x[3], 8); + ASCON_STOREBYTES(tag + 8, s.x[4], 8); + sqlite3mcSecureZeroMemory(&s, sizeof(ascon_state_t)); + sqlite3mcSecureZeroMemory(&key, sizeof(ascon_key_t)); + return 0; +} + +SQLITE_PRIVATE +int ascon_aead_decrypt(uint8_t* mtext, + const uint8_t* ctext, uint64_t clen, + const uint8_t* ad, uint64_t adlen, + const uint8_t tag[ASCON_AEAD_TAG_LEN], + const uint8_t nonce[ASCON_AEAD_NONCE_LEN], + const uint8_t k[ASCON_AEAD_KEY_LEN]) +{ + int rc = 0; + ascon_state_t s; + if (clen < CRYPTO_ABYTES) return -1; + /* perform ascon computation */ + ascon_key_t key; + ascon_loadkey(&key, k); + ascon_initaead(&s, &key, nonce); + ascon_adata(&s, ad, adlen); + ascon_decrypt(&s, mtext, ctext, clen); + ascon_final(&s, &key); + /* verify tag (should be constant time, check compiler output) */ + s.x[3] ^= ASCON_LOADBYTES(tag, 8); + s.x[4] ^= ASCON_LOADBYTES(tag + 8, 8); + rc = ASCON_NOTZERO(s.x[3], s.x[4]); + sqlite3mcSecureZeroMemory(&s, sizeof(ascon_state_t)); + sqlite3mcSecureZeroMemory(&key, sizeof(ascon_key_t)); + return rc; +} + +#endif +/*** End of #include "ascon/aead.c" ***/ + +/* #include "ascon/hash.c" */ +/*** Begin of #include "ascon/hash.c" ***/ +/* +** Name: hash.c +** Purpose: Hash algorithm with Ascon +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Modified by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +/* #include "api.h" */ + +/* #include "ascon.h" */ + +/* #include "crypto_hash.h" */ +/*** Begin of #include "crypto_hash.h" ***/ +/* +** Name: hash.c +** Purpose: API definition for Hash algorithm with Ascon +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Modified by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +#ifndef CRYPTO_HASH_H +#define CRYPTO_HASH_H + +#ifndef SQLITE_PRIVATE +#define SQLITE_PRIVATE +#endif + +#include + +/* +** Derives hash value using ASCON-HASH. +** +** \param out Output buffer for hash with fixed length of ASCON_HASH_BYTES +** \param in Buffer with input data +** \param passwordlen Length of input data in bytes +*/ +SQLITE_PRIVATE +int ascon_hash(uint8_t* out, const uint8_t* in, uint64_t inlen); + +#endif +/*** End of #include "crypto_hash.h" ***/ + +/* #include "permutations.h" */ + +/* #include "printstate.h" */ + + +#if !ASCON_INLINE_MODE +#undef forceinline +#define forceinline +#endif + +#ifdef ASCON_HASH_BYTES + +forceinline void ascon_inithash(ascon_state_t* s) { + int i; + /* initialize */ +#ifdef ASCON_PRINT_STATE +#if ASCON_HASH_BYTES == 32 && ASCON_HASH_ROUNDS == 12 + s->x[0] = ASCON_HASH_IV; +#elif ASCON_HASH_BYTES == 32 && ASCON_HASH_ROUNDS == 8 + s->x[0] = ASCON_HASHA_IV; +#elif ASCON_HASH_BYTES == 0 && ASCON_HASH_ROUNDS == 12 + s->x[0] = ASCON_XOF_IV; +#elif ASCON_HASH_BYTES == 0 && ASCON_HASH_ROUNDS == 8 + s->x[0] = ASCON_XOFA_IV; +#endif + for (i = 1; i < 5; ++i) s->x[i] = 0; + ascon_printstate("initial value", s); + ASCON_P(s, 12); +#endif +#if ASCON_HASH_BYTES == 32 && ASCON_HASH_ROUNDS == 12 + const uint64_t iv[5] = {ASCON_HASH_IV0, ASCON_HASH_IV1, ASCON_HASH_IV2, + ASCON_HASH_IV3, ASCON_HASH_IV4}; +#elif ASCON_HASH_BYTES == 32 && ASCON_HASH_ROUNDS == 8 + const uint64_t iv[5] = {ASCON_HASHA_IV0, ASCON_HASHA_IV1, ASCON_HASHA_IV2, + ASCON_HASHA_IV3, ASCON_HASHA_IV4}; +#elif ASCON_HASH_BYTES == 0 && ASCON_HASH_ROUNDS == 12 + const uint64_t iv[5] = {ASCON_XOF_IV0, ASCON_XOF_IV1, ASCON_XOF_IV2, + ASCON_XOF_IV3, ASCON_XOF_IV4}; +#elif ASCON_HASH_BYTES == 0 && ASCON_HASH_ROUNDS == 8 + const uint64_t iv[5] = {ASCON_XOFA_IV0, ASCON_XOFA_IV1, ASCON_XOFA_IV2, + ASCON_XOFA_IV3, ASCON_XOFA_IV4}; +#endif + for (i = 0; i < 5; ++i) s->x[i] = (iv[i]); + ascon_printstate("initialization", s); +} + +forceinline void ascon_absorb(ascon_state_t* s, const uint8_t* in, + uint64_t inlen) { + /* absorb full plaintext blocks */ + while (inlen >= ASCON_HASH_RATE) { + s->x[0] ^= ASCON_LOAD(in, 8); + ascon_printstate("absorb plaintext", s); + ASCON_P(s, ASCON_HASH_ROUNDS); + in += ASCON_HASH_RATE; + inlen -= ASCON_HASH_RATE; + } + /* absorb final plaintext block */ + s->x[0] ^= ASCON_LOADBYTES(in, inlen); + s->x[0] ^= ASCON_PAD(inlen); + ascon_printstate("pad plaintext", s); +} + +forceinline void ascon_squeeze(ascon_state_t* s, uint8_t* out, + uint64_t outlen) { + /* squeeze full output blocks */ + ASCON_P(s, 12); + while (outlen > ASCON_HASH_RATE) { + ASCON_STORE(out, s->x[0], 8); + ascon_printstate("squeeze output", s); + ASCON_P(s, ASCON_HASH_ROUNDS); + out += ASCON_HASH_RATE; + outlen -= ASCON_HASH_RATE; + } + /* squeeze final output block */ + ASCON_STOREBYTES(out, s->x[0], outlen); + ascon_printstate("squeeze output", s); +} + +SQLITE_PRIVATE +int ascon_hash(uint8_t* out, const uint8_t* in, uint64_t inlen) +{ + ascon_state_t s; + ascon_inithash(&s); + ascon_absorb(&s, in, inlen); + ascon_squeeze(&s, out, ASCON_HASH_BYTES); + sqlite3mcSecureZeroMemory(&s, sizeof(ascon_state_t)); + return 0; +} + +#endif +/*** End of #include "ascon/hash.c" ***/ + +/* #include "ascon/pbkdf2.c" */ +/*** Begin of #include "ascon/pbkdf2.c" ***/ +/* +** Name: pbkdf2.c +** Purpose: Implementation of PBKDF2 algoritm with Ascon +** Based on: Public domain Ascon reference implementation +** and optimized variants for 32- and 64-bit +** (see https://github.com/ascon/ascon-c) +** and the paper "Additional Modes for ASCON Version 1.1" +** by Rhys Weatherley, Southern Storm Software, Pty Ltd. +** Remarks: API functions adapted for use in SQLite3 Multiple Ciphers +** Created by: Ulrich Telle +** Copyright: (c) 2023-2023 Ulrich Telle +** License: MIT +*/ + +#define ASCON_HASH_SIZE 32 +#define ASCON_PBKDF2_SIZE 32 + +SQLITE_PRIVATE +void ascon_pbkdf2_init(ascon_state_t* state, const char* functionName, + const unsigned char* custom, uint32_t customlen, uint32_t outlen) +{ + /* Format the initial block with the function name and output length */ + uint8_t initial[ASCON_HASH_SIZE]; + size_t fnLength = functionName ? strlen(functionName) : 0; + + if (fnLength == 0) + { + /* No function name specified */ + memset(initial, 0, ASCON_HASH_SIZE); + } + else if (fnLength <= ASCON_HASH_SIZE) + { + /* Pad the function name with zeroes */ + memcpy(initial, functionName, fnLength); + memset(initial + fnLength, 0, ASCON_HASH_SIZE - fnLength); + } + else + { + ascon_hash(initial, (const uint8_t*) functionName, fnLength); + } + + state->x[0] = ASCON_HASH_IV; + state->x[1] = ASCON_LOAD(initial, 8); + state->x[2] = ASCON_LOAD(initial + 8, 8); + state->x[3] = ASCON_LOAD(initial + 16, 8); + state->x[4] = ASCON_LOAD(initial + 24, 8); + ASCON_P(state, 12); + + if (customlen > 0) + { + ascon_absorb(state, custom, customlen); + ASCON_P(state, 12); + /* domain separation */ + state->x[4] ^= 1; + } +} + +/* + * Implementation of the "F" function from RFC 8018, section 5.2 + * + * Note: Instead of HMAC like in RFC 8018, use the following PRF: + * PRF(P, X) = ASCON-cXOF(X, 256, "PBKDF2", P) + */ +static +void ascon_pbkdf2_f(ascon_state_t* state, + uint8_t* T, /*uint8_t* U,*/ + const uint8_t* salt, uint32_t saltlen, + uint32_t count, uint32_t blocknum) +{ + uint32_t asconSaltLen = (saltlen < ASCON_SALT_LEN) ? saltlen : ASCON_SALT_LEN; + uint8_t temp[ASCON_SALT_LEN+4]; + ascon_state_t state2; + int j; + + memset(temp, 0, ASCON_SALT_LEN); + memcpy(temp, salt, asconSaltLen); + STORE32_BE(temp+ASCON_SALT_LEN, blocknum); + + /* Copy initial state */ + for (j = 0; j < 5; ++j) state2.x[j] = state->x[j]; + + ascon_absorb(&state2, temp, ASCON_SALT_LEN+4); + ascon_squeeze(&state2, T, ASCON_PBKDF2_SIZE); + sqlite3mcSecureZeroMemory(temp, sizeof(temp)); + + if (count > 1) + { + uint8_t U[ASCON_PBKDF2_SIZE]; + memcpy(U, T, ASCON_PBKDF2_SIZE); + while (count > 1) + { + uint8_t* dst = T; + uint8_t* src = U; + uint32_t len = ASCON_PBKDF2_SIZE; + /* Copy initial state */ + for (j = 0; j < 5; ++j) state2.x[j] = state->x[j]; + /* Absorb U */ + ascon_absorb(&state2, U, ASCON_PBKDF2_SIZE); + /* Squeeze next U */ + ascon_squeeze(&state2, U, ASCON_PBKDF2_SIZE); + /* XOR T with U */ + while (len > 0) + { + *dst++ ^= *src++; + --len; + } + --count; + } + sqlite3mcSecureZeroMemory(U, sizeof(U)); + } + sqlite3mcSecureZeroMemory(&state2, sizeof(ascon_state_t)); +} + +SQLITE_PRIVATE +void ascon_pbkdf2(uint8_t* out, uint32_t outlen, + const uint8_t* password, uint32_t passwordlen, + const uint8_t* salt, uint32_t saltlen, uint32_t count) +{ + ascon_state_t state; + uint32_t blocknum = 1; + ascon_pbkdf2_init(&state, "PBKDF2", password, passwordlen, ASCON_PBKDF2_SIZE); + while (outlen > 0) + { + if (outlen >= ASCON_PBKDF2_SIZE) + { + ascon_pbkdf2_f(&state, out, /*U,*/ salt, saltlen, count, blocknum); + out += ASCON_PBKDF2_SIZE; + outlen -= ASCON_PBKDF2_SIZE; + } + else + { + uint8_t T[ASCON_PBKDF2_SIZE]; + ascon_pbkdf2_f(&state, T, /*U,*/ salt, saltlen, count, blocknum); + memcpy(out, T, outlen); + sqlite3mcSecureZeroMemory(T, sizeof(T)); + break; + } + ++blocknum; + } +} +/*** End of #include "ascon/pbkdf2.c" ***/ + + +SQLITE_PRIVATE CipherParams mcAscon128Params[] = +{ + { "kdf_iter", ASCON128_KDF_ITER_DEFAULT, ASCON128_KDF_ITER_DEFAULT, 1, 0x7fffffff }, + CIPHER_PARAMS_SENTINEL +}; + +#define KEYLENGTH_ASCON128 32 +#define SALTLENGTH_ASCON128 16 +#define PAGE_NONCE_LEN_ASCON128 16 +#define PAGE_TAG_LEN_ASCON128 16 +#define PAGE_RESERVED_ASCON128 (PAGE_NONCE_LEN_ASCON128 + PAGE_TAG_LEN_ASCON128) + +typedef struct _ascon128Cipher +{ + int m_kdfIter; + int m_keyLength; + uint8_t m_key[KEYLENGTH_ASCON128]; + uint8_t m_salt[SALTLENGTH_ASCON128]; +} Ascon128Cipher; + +static void* +AllocateAscon128Cipher(sqlite3* db) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*) sqlite3_malloc(sizeof(Ascon128Cipher)); + if (ascon128Cipher != NULL) + { + memset(ascon128Cipher, 0, sizeof(Ascon128Cipher)); + ascon128Cipher->m_keyLength = KEYLENGTH_ASCON128; + memset(ascon128Cipher->m_key, 0, KEYLENGTH_ASCON128); + memset(ascon128Cipher->m_salt, 0, SALTLENGTH_ASCON128); + } + if (ascon128Cipher != NULL) + { + CipherParams* cipherParams = sqlite3mcGetCipherParams(db, CIPHER_NAME_ASCON128); + ascon128Cipher->m_kdfIter = sqlite3mcGetCipherParameter(cipherParams, "kdf_iter"); + } + return ascon128Cipher; +} + +static void +FreeAscon128Cipher(void* cipher) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*) cipher; + memset(ascon128Cipher, 0, sizeof(Ascon128Cipher)); + sqlite3_free(ascon128Cipher); +} + +static void +CloneAscon128Cipher(void* cipherTo, void* cipherFrom) +{ + Ascon128Cipher* ascon128CipherTo = (Ascon128Cipher*) cipherTo; + Ascon128Cipher* ascon128CipherFrom = (Ascon128Cipher*) cipherFrom; + ascon128CipherTo->m_kdfIter = ascon128CipherFrom->m_kdfIter; + ascon128CipherTo->m_keyLength = ascon128CipherFrom->m_keyLength; + memcpy(ascon128CipherTo->m_key, ascon128CipherFrom->m_key, KEYLENGTH_ASCON128); + memcpy(ascon128CipherTo->m_salt, ascon128CipherFrom->m_salt, SALTLENGTH_ASCON128); +} + +static int +GetLegacyAscon128Cipher(void* cipher) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*)cipher; + return 0; +} + +static int +GetPageSizeAscon128Cipher(void* cipher) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*) cipher; + int pageSize = 0; + return pageSize; +} + +static int +GetReservedAscon128Cipher(void* cipher) +{ + return PAGE_RESERVED_ASCON128; +} + +static unsigned char* +GetSaltAscon128Cipher(void* cipher) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*) cipher; + return ascon128Cipher->m_salt; +} + +static void +GenerateKeyAscon128Cipher(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*) cipher; + int bypass = 0; + + int keyOnly = 1; + if (rekey || cipherSalt == NULL) + { + chacha20_rng(ascon128Cipher->m_salt, SALTLENGTH_ASCON128); + keyOnly = 0; + } + else + { + memcpy(ascon128Cipher->m_salt, cipherSalt, SALTLENGTH_ASCON128); + } + + /* Bypass key derivation if the key string starts with "raw:" */ + if (passwordLength > 4 && !memcmp(userPassword, "raw:", 4)) + { + const int nRaw = passwordLength - 4; + const unsigned char* zRaw = (const unsigned char*) userPassword + 4; + switch (nRaw) + { + /* Binary key (and salt) */ + case KEYLENGTH_ASCON128 + SALTLENGTH_ASCON128: + if (!keyOnly) + { + memcpy(ascon128Cipher->m_salt, zRaw + KEYLENGTH_ASCON128, SALTLENGTH_ASCON128); + } + /* fall-through */ + case KEYLENGTH_ASCON128: + memcpy(ascon128Cipher->m_key, zRaw, KEYLENGTH_ASCON128); + bypass = 1; + break; + + /* Hex-encoded key */ + case 2 * KEYLENGTH_ASCON128: + if (sqlite3mcIsHexKey(zRaw, nRaw) != 0) + { + sqlite3mcConvertHex2Bin(zRaw, nRaw, ascon128Cipher->m_key); + bypass = 1; + } + break; + + /* Hex-encoded key and salt */ + case 2 * (KEYLENGTH_ASCON128 + SALTLENGTH_ASCON128): + if (sqlite3mcIsHexKey(zRaw, nRaw) != 0) + { + sqlite3mcConvertHex2Bin(zRaw, 2 * KEYLENGTH_ASCON128, ascon128Cipher->m_key); + if (!keyOnly) + { + sqlite3mcConvertHex2Bin(zRaw + 2 * KEYLENGTH_ASCON128, 2 * SALTLENGTH_ASCON128, ascon128Cipher->m_salt); + } + bypass = 1; + } + break; + + default: + break; + } + } + + if (!bypass) + { + ascon_pbkdf2(ascon128Cipher->m_key, KEYLENGTH_ASCON128, + (const uint8_t*) userPassword, passwordLength, + ascon128Cipher->m_salt, SALTLENGTH_ASCON128, ascon128Cipher->m_kdfIter); + } + SQLITE3MC_DEBUG_LOG("generate: codec=%p pFile=%p\n", ascon128Cipher, fd); + SQLITE3MC_DEBUG_HEX("generate key:", ascon128Cipher->m_key, KEYLENGTH_ASCON128); + SQLITE3MC_DEBUG_HEX("generate salt:", ascon128Cipher->m_salt, SALTLENGTH_ASCON128); +} + +static int +AsconGenOtk(uint8_t* out, const uint8_t* key, const uint8_t* nonce, int page) +{ + ascon_state_t s; + uint8_t temp[KEYLENGTH_ASCON128+PAGE_NONCE_LEN_ASCON128+4]; + memcpy(temp, key, KEYLENGTH_ASCON128); + memcpy(temp+KEYLENGTH_ASCON128, nonce, PAGE_NONCE_LEN_ASCON128); + STORE32_BE(temp+KEYLENGTH_ASCON128+PAGE_NONCE_LEN_ASCON128, page); + ascon_inithash(&s); + ascon_absorb(&s, temp, KEYLENGTH_ASCON128+PAGE_NONCE_LEN_ASCON128+4); + ascon_squeeze(&s, out, ASCON_HASH_BYTES); + sqlite3mcSecureZeroMemory(temp, sizeof(temp)); + return 0; +} + +static int +EncryptPageAscon128Cipher(void* cipher, int page, unsigned char* data, int len, int reserved) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*) cipher; + int rc = SQLITE_OK; + int nReserved = (reserved == 0) ? 0 : GetReservedAscon128Cipher(cipher); + int n = len - nReserved; + uint64_t mlen = n; + + /* Generate one-time keys */ + uint8_t otk[ASCON_HASH_BYTES]; + int offset; + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if (nReserved > reserved) + { + return SQLITE_CORRUPT; + } + + if (nReserved > 0) + { + /* Encrypt and authenticate */ + memset(otk, 0, ASCON_HASH_BYTES); + /* Generate nonce */ + chacha20_rng(data + n + PAGE_TAG_LEN_ASCON128, PAGE_NONCE_LEN_ASCON128); + AsconGenOtk(otk, ascon128Cipher->m_key, data + n + PAGE_TAG_LEN_ASCON128, page); + + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + ascon_aead_encrypt(data + offset, data + n, data + offset, mlen - offset, + NULL /* ad */, 0 /* adlen*/, + data + n + PAGE_TAG_LEN_ASCON128, otk); + if (page == 1) + { + memcpy(data, ascon128Cipher->m_salt, SALTLENGTH_ASCON128); + } + } + else + { + /* Encrypt only */ + uint8_t nonce[PAGE_NONCE_LEN_ASCON128]; + uint8_t dummyTag[PAGE_TAG_LEN_ASCON128]; + memset(dummyTag, 0, PAGE_TAG_LEN_ASCON128); + memset(otk, 0, ASCON_HASH_BYTES); + sqlite3mcGenerateInitialVector(page, nonce); + AsconGenOtk(otk, ascon128Cipher->m_key, nonce, page); + + /* Encrypt */ + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + ascon_aead_encrypt(data + offset, dummyTag, data + offset, mlen - offset, + NULL /* ad */, 0 /* adlen*/, + nonce, otk); + if (page == 1) + { + memcpy(data, ascon128Cipher->m_salt, SALTLENGTH_ASCON128); + } + } + + return rc; +} + +static int +DecryptPageAscon128Cipher(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck) +{ + Ascon128Cipher* ascon128Cipher = (Ascon128Cipher*) cipher; + int rc = SQLITE_OK; + int nReserved = (reserved == 0) ? 0 : GetReservedAscon128Cipher(cipher); + int n = len - nReserved; + uint64_t clen = n; + int tagOk; + + /* Generate one-time keys */ + uint8_t otk[ASCON_HASH_BYTES]; + int offset; + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if (nReserved > reserved) + { + return (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + + if (nReserved > 0) + { + /* Decrypt and verify MAC */ + memset(otk, 0, ASCON_HASH_BYTES); + AsconGenOtk(otk, ascon128Cipher->m_key, data + n + PAGE_TAG_LEN_ASCON128, page); + + /* Determine MAC and decrypt */ + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + tagOk = ascon_aead_decrypt(data + offset, data + offset, clen - offset, + NULL /* ad */, 0 /* adlen */, + data + n, data + n + PAGE_TAG_LEN_ASCON128, otk); + if (hmacCheck != 0) + { + /* Verify the MAC */ + if (tagOk != 0) + { + SQLITE3MC_DEBUG_LOG("decrypt: codec=%p page=%d\n", ascon128Cipher, page); + SQLITE3MC_DEBUG_HEX("decrypt key:", ascon128Cipher->m_key, 32); + SQLITE3MC_DEBUG_HEX("decrypt otk:", otk, 64); + SQLITE3MC_DEBUG_HEX("decrypt data+00:", data, 16); + SQLITE3MC_DEBUG_HEX("decrypt data+24:", data + 24, 16); + SQLITE3MC_DEBUG_HEX("decrypt data+n:", data + n, 16); + SQLITE3MC_DEBUG_HEX("decrypt tag r:", data + n + PAGE_NONCE_LEN_ASCON128, PAGE_TAG_LEN_ASCON128); + SQLITE3MC_DEBUG_HEX("decrypt tag c:", tag, PAGE_TAG_LEN_ASCON128); + /* Bad MAC */ + rc = (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + } + if (page == 1 && rc == SQLITE_OK) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + else + { + /* Decrypt only */ + uint8_t nonce[PAGE_NONCE_LEN_ASCON128]; + uint8_t dummyTag[PAGE_TAG_LEN_ASCON128]; + memset(dummyTag, 0, PAGE_TAG_LEN_ASCON128); + memset(otk, 0, ASCON_HASH_BYTES); + sqlite3mcGenerateInitialVector(page, nonce); + AsconGenOtk(otk, ascon128Cipher->m_key, nonce, page); + + /* Decrypt */ + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + tagOk = ascon_aead_decrypt(data + offset, data + offset, clen - offset, + NULL /* ad */, 0 /* adlen */, + dummyTag, nonce, otk); + if (page == 1) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + + return rc; +} + +SQLITE_PRIVATE const CipherDescriptor mcAscon128Descriptor = +{ + CIPHER_NAME_ASCON128, + AllocateAscon128Cipher, + FreeAscon128Cipher, + CloneAscon128Cipher, + GetLegacyAscon128Cipher, + GetPageSizeAscon128Cipher, + GetReservedAscon128Cipher, + GetSaltAscon128Cipher, + GenerateKeyAscon128Cipher, + EncryptPageAscon128Cipher, + DecryptPageAscon128Cipher +}; +#endif +/*** End of #include "cipher_ascon.c" ***/ + +/* #include "cipher_aegis.c" */ +/*** Begin of #include "cipher_aegis.c" ***/ +/* +** Name: cipher_aegis.c +** Purpose: Implementation of cipher AEGIS +** Author: Ulrich Telle +** Created: 2024-12-10 +** Copyright: (c) 2024-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +/* --- Aegis --- */ +#if HAVE_CIPHER_AEGIS + +#define CIPHER_NAME_AEGIS "aegis" + +/* +** Configuration parameters for "aegis" +** +** - tcost : number of iterations for key derivation with Argon2 +** - mcost : amount of memory in kB for key derivation with Argon2 +** - pcost : parallelism, number of threads for key derivation with Argon2 +** - algorithm : AEGIS variant to be used for page encryption +*/ + +#define AEGIS_ALGORITHM_128L 1 +#define AEGIS_ALGORITHM_128X2 2 +#define AEGIS_ALGORITHM_128X4 3 +#define AEGIS_ALGORITHM_256 4 +#define AEGIS_ALGORITHM_256X2 5 +#define AEGIS_ALGORITHM_256X4 6 + +#define AEGIS_ALGORITHM_MIN AEGIS_ALGORITHM_128L +#define AEGIS_ALGORITHM_MAX AEGIS_ALGORITHM_256X4 +#define AEGIS_ALGORITHM_DEFAULT AEGIS_ALGORITHM_256 + +#define AEGIS_TCOST_DEFAULT 2 +#define AEGIS_MCOST_DEFAULT (19*1024) +#define AEGIS_PCOST_DEFAULT 1 + +SQLITE_PRIVATE const char* mcAegisAlgorithmNames[AEGIS_ALGORITHM_MAX+1] = +{ "", "aegis-128l", "aegis-128x2", "aegis-128x4", "aegis-256", "aegis-256x2", "aegis-256x4" }; + +SQLITE_PRIVATE int sqlite3mcAegisAlgorithmToIndex(const char* algorithmName) +{ + int j = 0; + for (j = AEGIS_ALGORITHM_MIN; j <= AEGIS_ALGORITHM_MAX; j++) + { + if (sqlite3_stricmp(algorithmName, mcAegisAlgorithmNames[j]) == 0) + break; + } + if (j <= AEGIS_ALGORITHM_MAX) + return j; + else + return -1; +} + +SQLITE_PRIVATE const char* sqlite3mcAegisAlgorithmToString(int algorithmIndex) +{ + if (algorithmIndex >= AEGIS_ALGORITHM_MIN && algorithmIndex <= AEGIS_ALGORITHM_MAX) + return mcAegisAlgorithmNames[algorithmIndex]; + else + return "unknown"; +} + +typedef int (*AegisEncryptDetached_t)(uint8_t* c, uint8_t* mac, size_t maclen, + const uint8_t* m, size_t mlen, + const uint8_t* ad, size_t adlen, + const uint8_t* npub, const uint8_t* k); + +typedef int (*AegisDecryptDetached_t)(uint8_t* m, const uint8_t* c, size_t clen, + const uint8_t* mac, size_t maclen, + const uint8_t* ad, size_t adlen, + const uint8_t* npub, const uint8_t* k); + +typedef void (*AegisEncryptUnauthenticated_t)(uint8_t* c, const uint8_t* m, size_t mlen, + const uint8_t* npub, const uint8_t* k); + +typedef void (*AegisDecryptUnauthenticated_t)(uint8_t* m, const uint8_t* c, size_t clen, + const uint8_t* npub, const uint8_t* k); + +typedef void (*AegisStream_t)(uint8_t* out, size_t len, const uint8_t* npub, const uint8_t* k); + +typedef struct _AegisCryptFunctions +{ + AegisEncryptDetached_t encrypt; + AegisDecryptDetached_t decrypt; + AegisEncryptUnauthenticated_t encryptNoTag; + AegisEncryptUnauthenticated_t decryptNoTag; + AegisStream_t stream; +} AegisCryptFunctions; + +SQLITE_PRIVATE const AegisCryptFunctions mcAegisCryptFunctions[] = +{ + { NULL, NULL }, /* Dummy entry */ + { aegis128l_encrypt_detached, aegis128l_decrypt_detached, + aegis128l_encrypt_unauthenticated, aegis128l_decrypt_unauthenticated, + aegis128l_stream }, + { aegis128x2_encrypt_detached, aegis128x2_decrypt_detached, + aegis128x2_encrypt_unauthenticated, aegis128x2_decrypt_unauthenticated, + aegis128x2_stream }, + { aegis128x4_encrypt_detached, aegis128x4_decrypt_detached, + aegis128x4_encrypt_unauthenticated, aegis128x4_decrypt_unauthenticated, + aegis128x4_stream }, + { aegis256_encrypt_detached, aegis256_decrypt_detached, + aegis256_encrypt_unauthenticated, aegis256_decrypt_unauthenticated, + aegis256_stream }, + { aegis256x2_encrypt_detached, aegis256x2_decrypt_detached, + aegis256x2_encrypt_unauthenticated, aegis256x2_decrypt_unauthenticated, + aegis256x2_stream }, + { aegis256x4_encrypt_detached, aegis256x4_decrypt_detached, + aegis256x4_encrypt_unauthenticated, aegis256x4_decrypt_unauthenticated, + aegis256x4_stream } +}; + +SQLITE_PRIVATE CipherParams mcAegisParams[] = +{ + { "tcost", AEGIS_TCOST_DEFAULT, AEGIS_TCOST_DEFAULT, 1, 0x7fffffff }, + { "mcost", AEGIS_MCOST_DEFAULT, AEGIS_MCOST_DEFAULT, 1, 0x7fffffff }, + { "pcost", AEGIS_PCOST_DEFAULT, AEGIS_PCOST_DEFAULT, 1, 0x7fffffff }, + { "algorithm", AEGIS_ALGORITHM_DEFAULT, AEGIS_ALGORITHM_DEFAULT, AEGIS_ALGORITHM_MIN, AEGIS_ALGORITHM_MAX }, + CIPHER_PARAMS_SENTINEL +}; + +#define KEYLENGTH_AEGIS_128 16 +#define KEYLENGTH_AEGIS_256 32 +#define KEYLENGTH_AEGIS_MAX 32 + +#define PAGE_NONCE_LEN_AEGIS_128 16 +#define PAGE_NONCE_LEN_AEGIS_256 32 +#define PAGE_NONCE_LEN_AEGIS_MAX 32 + +#if AEGIS_ALGORITHM_DEFAULT < AEGIS_ALGORITHM_256 +#define KEYLENGTH_AEGIS_DEFAULT KEYLENGTH_AEGIS_128 +#define PAGE_NONCE_LEN_AEGIS_DEFAULT PAGE_NONCE_LEN_AEGIS_128 +#else +#define KEYLENGTH_AEGIS_DEFAULT KEYLENGTH_AEGIS_256 +#define PAGE_NONCE_LEN_AEGIS_DEFAULT PAGE_NONCE_LEN_AEGIS_256 +#endif + +#define SALTLENGTH_AEGIS 16 + +#define PAGE_TAG_LEN_AEGIS 32 +#define PAGE_RESERVED_AEGIS (PAGE_NONCE_LEN_AEGIS + PAGE_TAG_LEN_AEGIS) + +#define OTK_LEN_MAX_AEGIS (PAGE_TAG_LEN_AEGIS + PAGE_NONCE_LEN_AEGIS_MAX + 4) + +typedef struct _aegisCipher +{ + int m_argon2Tcost; + int m_argon2Mcost; + int m_argon2Pcost; + int m_aegisAlgorithm; + int m_keyLength; + int m_nonceLength; + uint8_t m_key[KEYLENGTH_AEGIS_MAX]; + uint8_t m_salt[SALTLENGTH_AEGIS]; +} AegisCipher; + +static void* +AllocateAegisCipher(sqlite3* db) +{ + AegisCipher* aegisCipher = (AegisCipher*) sqlite3_malloc(sizeof(AegisCipher)); + if (aegisCipher != NULL) + { + memset(aegisCipher, 0, sizeof(AegisCipher)); + aegisCipher->m_keyLength = 0; + memset(aegisCipher->m_key, 0, KEYLENGTH_AEGIS_MAX); + memset(aegisCipher->m_salt, 0, SALTLENGTH_AEGIS); + } + if (aegisCipher != NULL) + { + CipherParams* cipherParams = sqlite3mcGetCipherParams(db, CIPHER_NAME_AEGIS); + aegisCipher->m_argon2Tcost = sqlite3mcGetCipherParameter(cipherParams, "tcost"); + aegisCipher->m_argon2Mcost = sqlite3mcGetCipherParameter(cipherParams, "mcost"); + aegisCipher->m_argon2Pcost = sqlite3mcGetCipherParameter(cipherParams, "pcost"); + aegisCipher->m_aegisAlgorithm = sqlite3mcGetCipherParameter(cipherParams, "algorithm"); + if (aegisCipher->m_aegisAlgorithm < AEGIS_ALGORITHM_256) + { + aegisCipher->m_keyLength = KEYLENGTH_AEGIS_128; + aegisCipher->m_nonceLength = PAGE_NONCE_LEN_AEGIS_128; + } + else + { + aegisCipher->m_keyLength = KEYLENGTH_AEGIS_256; + aegisCipher->m_nonceLength = PAGE_NONCE_LEN_AEGIS_256; + } + } + return aegisCipher; +} + +static void +FreeAegisCipher(void* cipher) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + memset(aegisCipher, 0, sizeof(AegisCipher)); + sqlite3_free(aegisCipher); +} + +static void +CloneAegisCipher(void* cipherTo, void* cipherFrom) +{ + AegisCipher* aegisCipherTo = (AegisCipher*) cipherTo; + AegisCipher* aegisCipherFrom = (AegisCipher*) cipherFrom; + + aegisCipherTo->m_argon2Tcost = aegisCipherFrom->m_argon2Tcost; + aegisCipherTo->m_argon2Mcost = aegisCipherFrom->m_argon2Mcost; + aegisCipherTo->m_argon2Pcost = aegisCipherFrom->m_argon2Pcost; + + aegisCipherTo->m_aegisAlgorithm = aegisCipherFrom->m_aegisAlgorithm; + aegisCipherTo->m_keyLength = aegisCipherFrom->m_keyLength; + aegisCipherTo->m_nonceLength = aegisCipherFrom->m_nonceLength; + + memcpy(aegisCipherTo->m_key, aegisCipherFrom->m_key, aegisCipherFrom->m_keyLength); + memcpy(aegisCipherTo->m_salt, aegisCipherFrom->m_salt, SALTLENGTH_AEGIS); +} + +static int +GetLegacyAegisCipher(void* cipher) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + return 0; +} + +static int +GetPageSizeAegisCipher(void* cipher) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + int pageSize = 0; + return pageSize; +} + +static int +GetReservedAegisCipher(void* cipher) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + return (aegisCipher->m_nonceLength + PAGE_TAG_LEN_AEGIS); +} + +static unsigned char* +GetSaltAegisCipher(void* cipher) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + return aegisCipher->m_salt; +} + +static void +GenerateKeyAegisCipher(void* cipher, char* userPassword, int passwordLength, int rekey, unsigned char* cipherSalt) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + int bypass = 0; + + int keyOnly = 1; + if (rekey || cipherSalt == NULL) + { + chacha20_rng(aegisCipher->m_salt, SALTLENGTH_AEGIS); + keyOnly = 0; + } + else + { + memcpy(aegisCipher->m_salt, cipherSalt, SALTLENGTH_AEGIS); + } + + /* Bypass key derivation if the key string starts with "raw:" */ + if (passwordLength > 4 && !memcmp(userPassword, "raw:", 4)) + { + const int nRaw = passwordLength - 4; + const unsigned char* zRaw = (const unsigned char*) userPassword + 4; + if (nRaw == aegisCipher->m_keyLength) + { + /* Binary key */ + memcpy(aegisCipher->m_key, zRaw, aegisCipher->m_keyLength); + bypass = 1; + } + else if (nRaw == aegisCipher->m_keyLength + SALTLENGTH_AEGIS) + { + /* Binary key and salt) */ + if (!keyOnly) + { + memcpy(aegisCipher->m_salt, zRaw + aegisCipher->m_keyLength, SALTLENGTH_AEGIS); + } + memcpy(aegisCipher->m_key, zRaw, aegisCipher->m_keyLength); + bypass = 1; + } + else if (nRaw == 2 * aegisCipher->m_keyLength) + { + /* Hex-encoded key */ + if (sqlite3mcIsHexKey(zRaw, nRaw) != 0) + { + sqlite3mcConvertHex2Bin(zRaw, nRaw, aegisCipher->m_key); + bypass = 1; + } + } + else if (nRaw == 2 * (aegisCipher->m_keyLength + SALTLENGTH_AEGIS)) + { + /* Hex-encoded key and salt */ + if (sqlite3mcIsHexKey(zRaw, nRaw) != 0) + { + sqlite3mcConvertHex2Bin(zRaw, 2 * aegisCipher->m_keyLength, aegisCipher->m_key); + if (!keyOnly) + { + sqlite3mcConvertHex2Bin(zRaw + 2 * aegisCipher->m_keyLength, 2 * SALTLENGTH_AEGIS, aegisCipher->m_salt); + } + bypass = 1; + } + } + } + + if (!bypass) + { + int rc = argon2id_hash_raw((uint32_t) aegisCipher->m_argon2Tcost, + (uint32_t) aegisCipher->m_argon2Mcost, + (uint32_t) aegisCipher->m_argon2Pcost, + userPassword, passwordLength, + aegisCipher->m_salt, SALTLENGTH_AEGIS, + aegisCipher->m_key, aegisCipher->m_keyLength); + } + SQLITE3MC_DEBUG_LOG("generate: codec=%p pFile=%p\n", aegisCipher, fd); + SQLITE3MC_DEBUG_HEX("generate key:", aegisCipher->m_key, aegisCipher->m_keyLength); + SQLITE3MC_DEBUG_HEX("generate salt:", aegisCipher->m_salt, SALTLENGTH_AEGIS); +} + +static int +AegisGenNonce(AegisCipher* aegisCipher, uint8_t* out, int outLength, int page) +{ + uint8_t nonce[PAGE_NONCE_LEN_AEGIS_MAX]; + memset(nonce, 0, PAGE_NONCE_LEN_AEGIS_MAX); + STORE32_LE(out, page); + STORE32_LE(out + 4, page); + mcAegisCryptFunctions[aegisCipher->m_aegisAlgorithm].stream(out, outLength, nonce, aegisCipher->m_key); + return 0; +} + +static int +AegisGenOtk(AegisCipher* aegisCipher, uint8_t* out, int outLength, uint8_t* nonce, int nonceLength, int page) +{ + mcAegisCryptFunctions[aegisCipher->m_aegisAlgorithm].stream(out, outLength, nonce, aegisCipher->m_key); + STORE32_BE(out + (outLength - 4), page); + return 0; +} + +static int +EncryptPageAegisCipher(void* cipher, int page, unsigned char* data, int len, int reserved) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + int rc = SQLITE_OK; + int nReserved = (reserved == 0) ? 0 : GetReservedAegisCipher(cipher); + int n = len - nReserved; + uint64_t mlen = n; + + /* Generate one-time keys */ + uint8_t otk[OTK_LEN_MAX_AEGIS]; + int offset; + memset(otk, 0, OTK_LEN_MAX_AEGIS); + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if (nReserved > reserved) + { + return SQLITE_CORRUPT; + } + + if (nReserved > 0) + { + /* Encrypt and authenticate */ + + /* Generate nonce */ + chacha20_rng(data + n + PAGE_TAG_LEN_AEGIS, aegisCipher->m_nonceLength); + AegisGenOtk(aegisCipher, otk, aegisCipher->m_keyLength + aegisCipher->m_nonceLength, + data + n + PAGE_TAG_LEN_AEGIS, aegisCipher->m_nonceLength, page); + + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + mcAegisCryptFunctions[aegisCipher->m_aegisAlgorithm].encrypt( + data + offset, data + n, PAGE_TAG_LEN_AEGIS, + data + offset, mlen - offset, + NULL, 0, otk + aegisCipher->m_keyLength, otk); + + if (page == 1) + { + memcpy(data, aegisCipher->m_salt, SALTLENGTH_AEGIS); + } + } + else + { + /* Encrypt only */ + uint8_t nonce[PAGE_NONCE_LEN_AEGIS_MAX]; + AegisGenNonce(aegisCipher, nonce, aegisCipher->m_nonceLength, page); + AegisGenOtk(aegisCipher, otk, aegisCipher->m_keyLength + aegisCipher->m_nonceLength, + nonce, aegisCipher->m_nonceLength, page); + + /* Encrypt */ + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + mcAegisCryptFunctions[aegisCipher->m_aegisAlgorithm].encryptNoTag( + data + offset, + data + offset, mlen - offset, + otk + aegisCipher->m_keyLength, otk); + + if (page == 1) + { + memcpy(data, aegisCipher->m_salt, SALTLENGTH_AEGIS); + } + } + + return rc; +} + +static int +DecryptPageAegisCipher(void* cipher, int page, unsigned char* data, int len, int reserved, int hmacCheck) +{ + AegisCipher* aegisCipher = (AegisCipher*) cipher; + int rc = SQLITE_OK; + int nReserved = (reserved == 0) ? 0 : GetReservedAegisCipher(cipher); + int n = len - nReserved; + uint64_t clen = n; + int tagOk; + + /* Generate one-time keys */ + uint8_t otk[OTK_LEN_MAX_AEGIS]; + int offset; + memset(otk, 0, OTK_LEN_MAX_AEGIS); + + /* Check whether number of required reserved bytes and actually reserved bytes match */ + if (nReserved > reserved) + { + return (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + + if (nReserved > 0) + { + /* Decrypt and verify MAC */ + AegisGenOtk(aegisCipher, otk, aegisCipher->m_keyLength + aegisCipher->m_nonceLength, + data + n + PAGE_TAG_LEN_AEGIS, aegisCipher->m_nonceLength, page); + + /* Determine MAC and decrypt */ + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + + if (hmacCheck != 0) + { + /* Verify the MAC */ + tagOk = mcAegisCryptFunctions[aegisCipher->m_aegisAlgorithm].decrypt( + data + offset, + data + offset, clen - offset, + data + n, PAGE_TAG_LEN_AEGIS, + NULL, 0, otk + aegisCipher->m_keyLength, otk); + if (tagOk != 0) + { + SQLITE3MC_DEBUG_LOG("decrypt: codec=%p page=%d\n", aegisCipher, page); + SQLITE3MC_DEBUG_HEX("decrypt key:", aegisCipher->m_key, aegisCipher->m_keyLength); + SQLITE3MC_DEBUG_HEX("decrypt otk:", otk, 64); + SQLITE3MC_DEBUG_HEX("decrypt data+00:", data, 16); + SQLITE3MC_DEBUG_HEX("decrypt data+24:", data + 24, 16); + SQLITE3MC_DEBUG_HEX("decrypt data+n:", data + n, PAGE_TAG_LEN_AEGIS); + /* Bad MAC */ + rc = (page == 1) ? SQLITE_NOTADB : SQLITE_CORRUPT; + } + } + else + { + mcAegisCryptFunctions[aegisCipher->m_aegisAlgorithm].decryptNoTag( + data + offset, + data + offset, clen - offset, + otk + aegisCipher->m_keyLength, otk); + } + + if (page == 1 && rc == SQLITE_OK) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + else + { + /* Decrypt only */ + uint8_t nonce[PAGE_NONCE_LEN_AEGIS_MAX]; + AegisGenNonce(aegisCipher, nonce, aegisCipher->m_nonceLength, page); + AegisGenOtk(aegisCipher, otk, aegisCipher->m_keyLength + aegisCipher->m_nonceLength, + nonce, aegisCipher->m_nonceLength, page); + + /* Decrypt */ + offset = (page == 1) ? CIPHER_PAGE1_OFFSET : 0; + mcAegisCryptFunctions[aegisCipher->m_aegisAlgorithm].decryptNoTag( + data + offset, + data + offset, clen - offset, + otk + aegisCipher->m_keyLength, otk); + + if (page == 1) + { + memcpy(data, SQLITE_FILE_HEADER, 16); + } + } + + return rc; +} + +SQLITE_PRIVATE const CipherDescriptor mcAegisDescriptor = +{ + CIPHER_NAME_AEGIS, + AllocateAegisCipher, + FreeAegisCipher, + CloneAegisCipher, + GetLegacyAegisCipher, + GetPageSizeAegisCipher, + GetReservedAegisCipher, + GetSaltAegisCipher, + GenerateKeyAegisCipher, + EncryptPageAegisCipher, + DecryptPageAegisCipher +}; +#endif +/*** End of #include "cipher_aegis.c" ***/ + +/* #include "cipher_common.c" */ +/*** Begin of #include "cipher_common.c" ***/ +/* +** Name: cipher_common.c +** Purpose: Implementation of SQLite codecs +** Author: Ulrich Telle +** Created: 2020-02-02 +** Copyright: (c) 2006-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + + +static unsigned char padding[] = +"\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A"; + +/* --- Codec Descriptor Table --- */ + +/* +** Common configuration parameters +** +** - cipher : default cipher type +** - hmac_check : flag whether page hmac should be verified on read +*/ + +static CipherParams commonParams[] = +{ + { "cipher", CODEC_TYPE_UNKNOWN, CODEC_TYPE_UNKNOWN, 1, CODEC_COUNT_MAX }, + { "hmac_check", 1, 1, 0, 1 }, + { "mc_legacy_wal", SQLITE3MC_LEGACY_WAL, SQLITE3MC_LEGACY_WAL, 0, 1 }, + CIPHER_PARAMS_SENTINEL +}; + +#define CIPHER_NAME_GLOBAL "global" + +static CodecParameter globalCommonParams = { CIPHER_NAME_GLOBAL, CODEC_TYPE_UNKNOWN, commonParams }; +static CodecParameter globalSentinelParams = { "", CODEC_TYPE_UNKNOWN, NULL }; + +SQLITE_PRIVATE int +sqlite3mcGetCipherParameter(CipherParams* cipherParams, const char* paramName) +{ + int value = -1; + for (; cipherParams->m_name[0] != 0; ++cipherParams) + { + if (sqlite3_stricmp(paramName, cipherParams->m_name) == 0) break; + } + if (cipherParams->m_name[0] != 0) + { + value = cipherParams->m_value; + cipherParams->m_value = cipherParams->m_default; + } + return value; +} + +typedef struct _CipherName +{ + char m_name[CIPHER_NAME_MAXLEN]; +} CipherName; + +static char globalConfigTableName[CIPHER_NAME_MAXLEN] = ""; +static int globalCipherCount = 0; +static char* globalSentinelName = ""; +static CipherName globalCipherNameTable[CODEC_COUNT_LIMIT + 2] = { 0 }; +static CodecParameter globalCodecParameterTable[CODEC_COUNT_LIMIT + 2]; + +SQLITE_PRIVATE CodecParameter* +sqlite3mcCloneCodecParameterTable() +{ + /* Count number of codecs and cipher parameters */ + int nTables = 0; + int nParams = 0; + int j, k, n; + CipherParams* cloneCipherParams; + CodecParameter* cloneCodecParams; + + for (j = 0; globalCodecParameterTable[j].m_name[0] != 0; ++j) + { + CipherParams* params = globalCodecParameterTable[j].m_params; + for (k = 0; params[k].m_name[0] != 0; ++k); + nParams += k; + } + nTables = j; + + /* Allocate memory for cloned codec parameter tables (including sentinel for each table) */ + cloneCipherParams = (CipherParams*) sqlite3_malloc((nParams + nTables) * sizeof(CipherParams)); + cloneCodecParams = (CodecParameter*) sqlite3_malloc((nTables + 1) * sizeof(CodecParameter)); + + /* Create copy of tables */ + if (cloneCodecParams != NULL) + { + int offset = 0; + for (j = 0; j < nTables; ++j) + { + CipherParams* params = globalCodecParameterTable[j].m_params; + cloneCodecParams[j].m_name = globalCodecParameterTable[j].m_name; + cloneCodecParams[j].m_id = globalCodecParameterTable[j].m_id; + cloneCodecParams[j].m_params = &cloneCipherParams[offset]; + for (n = 0; params[n].m_name[0] != 0; ++n); + /* Copy all parameters of the current table (including sentinel) */ + for (k = 0; k <= n; ++k) + { + cloneCipherParams[offset + k].m_name = params[k].m_name; + cloneCipherParams[offset + k].m_value = params[k].m_value; + cloneCipherParams[offset + k].m_default = params[k].m_default; + cloneCipherParams[offset + k].m_minValue = params[k].m_minValue; + cloneCipherParams[offset + k].m_maxValue = params[k].m_maxValue; + } + offset += (n + 1); + } + cloneCodecParams[nTables].m_name = globalCodecParameterTable[nTables].m_name; + cloneCodecParams[nTables].m_id = globalCodecParameterTable[nTables].m_id; + cloneCodecParams[nTables].m_params = NULL; + } + else + { + sqlite3_free(cloneCipherParams); + } + return cloneCodecParams; +} + +SQLITE_PRIVATE void +sqlite3mcFreeCodecParameterTable(void* ptr) +{ + CodecParameter* codecParams = (CodecParameter*)ptr; + sqlite3_free(codecParams[0].m_params); + sqlite3_free(codecParams); +} + +static const CipherDescriptor mcSentinelDescriptor = +{ + "", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL +}; + +static const CipherDescriptor mcDummyDescriptor = +{ + "@dummy@", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL +}; + +static CipherDescriptor globalCodecDescriptorTable[CODEC_COUNT_MAX + 1]; + +/* --- Codec --- */ + +SQLITE_PRIVATE CodecParameter* +sqlite3mcGetCodecParams(sqlite3* db); + +SQLITE_PRIVATE int +sqlite3mcGetCipherType(sqlite3* db) +{ + CodecParameter* codecParams = (db != NULL) ? sqlite3mcGetCodecParams(db) : globalCodecParameterTable; + CipherParams* cipherParamTable = (codecParams != NULL) ? codecParams[0].m_params : commonParams; + int cipherType = CODEC_TYPE_UNKNOWN; + CipherParams* cipher = cipherParamTable; + for (; cipher->m_name[0] != 0; ++cipher) + { + if (sqlite3_stricmp("cipher", cipher->m_name) == 0) break; + } + if (cipher->m_name[0] != 0) + { + cipherType = cipher->m_value; + cipher->m_value = cipher->m_default; + } + return cipherType; +} + +SQLITE_PRIVATE CipherParams* +sqlite3mcGetCipherParams(sqlite3* db, const char* cipherName) +{ + int j = 0; + int cipherType = sqlite3mc_cipher_index(cipherName); + CodecParameter* codecParams = (db != NULL) ? sqlite3mcGetCodecParams(db) : globalCodecParameterTable; + if (codecParams == NULL) + { + codecParams = globalCodecParameterTable; + } + if (cipherType > 0) + { + for (j = 1; codecParams[j].m_id > 0; ++j) + { + if (cipherType == codecParams[j].m_id) break; + } + } + CipherParams* cipherParamTable = codecParams[j].m_params; + return cipherParamTable; +} + +SQLITE_PRIVATE int +sqlite3mcCodecInit(Codec* codec) +{ + int rc = SQLITE_OK; + if (codec != NULL) + { + codec->m_isEncrypted = 0; + codec->m_hmacCheck = 1; + codec->m_walLegacy = 0; + + codec->m_hasReadCipher = 0; + codec->m_readCipherType = CODEC_TYPE_UNKNOWN; + codec->m_readCipher = NULL; + codec->m_readReserved = -1; + + codec->m_hasWriteCipher = 0; + codec->m_writeCipherType = CODEC_TYPE_UNKNOWN; + codec->m_writeCipher = NULL; + codec->m_writeReserved = -1; + + codec->m_db = NULL; +#if 0 + codec->m_bt = NULL; +#endif + codec->m_btShared = NULL; + memset(codec->m_page, 0, sizeof(codec->m_page)); + codec->m_pageSize = 0; + codec->m_reserved = 0; + codec->m_lastError = SQLITE_OK; + codec->m_hasKeySalt = 0; + memset(codec->m_keySalt, 0, sizeof(codec->m_keySalt)); + } + else + { + rc = SQLITE_NOMEM; + } + return rc; +} + +SQLITE_PRIVATE void +sqlite3mcCodecTerm(Codec* codec) +{ + if (codec->m_readCipher != NULL) + { + globalCodecDescriptorTable[codec->m_readCipherType - 1].m_freeCipher(codec->m_readCipher); + codec->m_readCipher = NULL; + } + if (codec->m_writeCipher != NULL) + { + globalCodecDescriptorTable[codec->m_writeCipherType - 1].m_freeCipher(codec->m_writeCipher); + codec->m_writeCipher = NULL; + } + memset(codec, 0, sizeof(Codec)); +} + +SQLITE_PRIVATE void +sqlite3mcClearKeySalt(Codec* codec) +{ + codec->m_hasKeySalt = 0; + memset(codec->m_keySalt, 0, sizeof(codec->m_keySalt)); +} + +SQLITE_PRIVATE int +sqlite3mcCodecSetup(Codec* codec, int cipherType, char* userPassword, int passwordLength) +{ + int rc = SQLITE_OK; + CipherParams* globalParams = sqlite3mcGetCipherParams(codec->m_db, CIPHER_NAME_GLOBAL); + if (cipherType <= CODEC_TYPE_UNKNOWN) + { + return SQLITE_ERROR; + } + codec->m_isEncrypted = 1; + codec->m_hmacCheck = sqlite3mcGetCipherParameter(globalParams, "hmac_check"); + codec->m_walLegacy = sqlite3mcGetCipherParameter(globalParams, "mc_legacy_wal"); + codec->m_hasReadCipher = 1; + codec->m_hasWriteCipher = 1; + codec->m_readCipherType = cipherType; + codec->m_readCipher = globalCodecDescriptorTable[codec->m_readCipherType-1].m_allocateCipher(codec->m_db); + if (codec->m_readCipher != NULL) + { + unsigned char* keySalt = (codec->m_hasKeySalt != 0) ? codec->m_keySalt : NULL; + sqlite3mcGenerateReadKey(codec, userPassword, passwordLength, keySalt); + rc = sqlite3mcCopyCipher(codec, 1); + } + else + { + rc = SQLITE_NOMEM; + } + return rc; +} + +SQLITE_PRIVATE int +sqlite3mcSetupWriteCipher(Codec* codec, int cipherType, char* userPassword, int passwordLength) +{ + int rc = SQLITE_OK; + CipherParams* globalParams = sqlite3mcGetCipherParams(codec->m_db, CIPHER_NAME_GLOBAL); + if (cipherType <= CODEC_TYPE_UNKNOWN) + { + return SQLITE_ERROR; + } + if (codec->m_writeCipher != NULL) + { + globalCodecDescriptorTable[codec->m_writeCipherType-1].m_freeCipher(codec->m_writeCipher); + } + codec->m_isEncrypted = 1; + codec->m_hmacCheck = sqlite3mcGetCipherParameter(globalParams, "hmac_check"); + codec->m_walLegacy = sqlite3mcGetCipherParameter(globalParams, "mc_legacy_wal"); + codec->m_hasWriteCipher = 1; + codec->m_writeCipherType = cipherType; + codec->m_writeCipher = globalCodecDescriptorTable[codec->m_writeCipherType-1].m_allocateCipher(codec->m_db); + if (codec->m_writeCipher != NULL) + { + unsigned char* keySalt = (codec->m_hasKeySalt != 0) ? codec->m_keySalt : NULL; + sqlite3mcGenerateWriteKey(codec, userPassword, passwordLength, keySalt); + } + else + { + rc = SQLITE_NOMEM; + } + return rc; +} + +SQLITE_PRIVATE void +sqlite3mcSetIsEncrypted(Codec* codec, int isEncrypted) +{ + codec->m_isEncrypted = isEncrypted; +} + +SQLITE_PRIVATE void +sqlite3mcSetReadCipherType(Codec* codec, int cipherType) +{ + codec->m_readCipherType = cipherType; +} + +SQLITE_PRIVATE void +sqlite3mcSetWriteCipherType(Codec* codec, int cipherType) +{ + codec->m_writeCipherType = cipherType; +} + +SQLITE_PRIVATE void +sqlite3mcSetHasReadCipher(Codec* codec, int hasReadCipher) +{ + codec->m_hasReadCipher = hasReadCipher; +} + +SQLITE_PRIVATE void +sqlite3mcSetHasWriteCipher(Codec* codec, int hasWriteCipher) +{ + codec->m_hasWriteCipher = hasWriteCipher; +} + +SQLITE_PRIVATE void +sqlite3mcSetDb(Codec* codec, sqlite3* db) +{ + codec->m_db = db; +} + +SQLITE_PRIVATE void +sqlite3mcSetBtree(Codec* codec, Btree* bt) +{ +#if 0 + codec->m_bt = bt; +#endif + codec->m_btShared = bt->pBt; +} + +SQLITE_PRIVATE void +sqlite3mcSetReadReserved(Codec* codec, int reserved) +{ + codec->m_readReserved = reserved; +} + +SQLITE_PRIVATE void +sqlite3mcSetWriteReserved(Codec* codec, int reserved) +{ + codec->m_writeReserved = reserved; +} + +SQLITE_PRIVATE int +sqlite3mcIsEncrypted(Codec* codec) +{ + return codec->m_isEncrypted; +} + +SQLITE_PRIVATE int +sqlite3mcHasReadCipher(Codec* codec) +{ + return codec->m_hasReadCipher; +} + +SQLITE_PRIVATE int +sqlite3mcHasWriteCipher(Codec* codec) +{ + return codec->m_hasWriteCipher; +} + +SQLITE_PRIVATE BtShared* +sqlite3mcGetBtShared(Codec* codec) +{ + return codec->m_btShared; +} + +SQLITE_PRIVATE int +sqlite3mcGetPageSize(Codec* codec) +{ + return codec->m_btShared->pageSize; +} + +SQLITE_PRIVATE int +sqlite3mcGetReadReserved(Codec* codec) +{ + return codec->m_readReserved; +} + +SQLITE_PRIVATE int +sqlite3mcGetWriteReserved(Codec* codec) +{ + return codec->m_writeReserved; +} + +SQLITE_PRIVATE unsigned char* +sqlite3mcGetPageBuffer(Codec* codec) +{ + return &codec->m_page[4]; +} + +SQLITE_PRIVATE int +sqlite3mcGetLegacyReadCipher(Codec* codec) +{ + int legacy = (codec->m_hasReadCipher && codec->m_readCipher != NULL) ? globalCodecDescriptorTable[codec->m_readCipherType - 1].m_getLegacy(codec->m_readCipher) : 0; + return legacy; +} + +SQLITE_PRIVATE int +sqlite3mcGetLegacyWriteCipher(Codec* codec) +{ + int legacy = (codec->m_hasWriteCipher && codec->m_writeCipher != NULL) ? globalCodecDescriptorTable[codec->m_writeCipherType - 1].m_getLegacy(codec->m_writeCipher) : -1; + return legacy; +} + +SQLITE_PRIVATE int +sqlite3mcGetPageSizeReadCipher(Codec* codec) +{ + int pageSize = (codec->m_hasReadCipher && codec->m_readCipher != NULL) ? globalCodecDescriptorTable[codec->m_readCipherType - 1].m_getPageSize(codec->m_readCipher) : -1; + return pageSize; +} + +SQLITE_PRIVATE int +sqlite3mcGetPageSizeWriteCipher(Codec* codec) +{ + int pageSize = (codec->m_hasWriteCipher && codec->m_writeCipher != NULL) ? globalCodecDescriptorTable[codec->m_writeCipherType - 1].m_getPageSize(codec->m_writeCipher) : -1; + return pageSize; +} + +SQLITE_PRIVATE int +sqlite3mcGetReservedReadCipher(Codec* codec) +{ + int reserved = (codec->m_hasReadCipher && codec->m_readCipher != NULL) ? globalCodecDescriptorTable[codec->m_readCipherType-1].m_getReserved(codec->m_readCipher) : -1; + return reserved; +} + +SQLITE_PRIVATE int +sqlite3mcGetReservedWriteCipher(Codec* codec) +{ + int reserved = (codec->m_hasWriteCipher && codec->m_writeCipher != NULL) ? globalCodecDescriptorTable[codec->m_writeCipherType-1].m_getReserved(codec->m_writeCipher) : -1; + return reserved; +} + +SQLITE_PRIVATE int +sqlite3mcReservedEqual(Codec* codec) +{ + int readReserved = (codec->m_hasReadCipher && codec->m_readCipher != NULL) ? globalCodecDescriptorTable[codec->m_readCipherType-1].m_getReserved(codec->m_readCipher) : -1; + int writeReserved = (codec->m_hasWriteCipher && codec->m_writeCipher != NULL) ? globalCodecDescriptorTable[codec->m_writeCipherType-1].m_getReserved(codec->m_writeCipher) : -1; + return (readReserved == writeReserved); +} + +SQLITE_PRIVATE void +sqlite3mcSetCodecLastError(Codec* codec, int error) +{ + if (codec) + { + codec->m_lastError = error; + } +} + +SQLITE_PRIVATE int +sqlite3mcGetCodecLastError(Codec* codec) +{ + return codec ? codec->m_lastError : SQLITE_OK; +} + +SQLITE_PRIVATE unsigned char* +sqlite3mcGetSaltWriteCipher(Codec* codec) +{ + unsigned char* salt = (codec->m_hasWriteCipher && codec->m_writeCipher != NULL) ? globalCodecDescriptorTable[codec->m_writeCipherType - 1].m_getSalt(codec->m_writeCipher) : NULL; + return salt; +} + +SQLITE_PRIVATE int +sqlite3mcCodecCopy(Codec* codec, Codec* other) +{ + int rc = SQLITE_OK; + codec->m_isEncrypted = other->m_isEncrypted; + codec->m_hmacCheck = other->m_hmacCheck; + codec->m_walLegacy = other->m_walLegacy; + codec->m_hasReadCipher = other->m_hasReadCipher; + codec->m_hasWriteCipher = other->m_hasWriteCipher; + codec->m_readCipherType = other->m_readCipherType; + codec->m_writeCipherType = other->m_writeCipherType; + codec->m_readCipher = NULL; + codec->m_writeCipher = NULL; + codec->m_readReserved = other->m_readReserved; + codec->m_writeReserved = other->m_writeReserved; + + if (codec->m_hasReadCipher) + { + codec->m_readCipher = globalCodecDescriptorTable[codec->m_readCipherType - 1].m_allocateCipher(codec->m_db); + if (codec->m_readCipher != NULL) + { + globalCodecDescriptorTable[codec->m_readCipherType - 1].m_cloneCipher(codec->m_readCipher, other->m_readCipher); + } + else + { + rc = SQLITE_NOMEM; + } + } + + if (codec->m_hasWriteCipher) + { + codec->m_writeCipher = globalCodecDescriptorTable[codec->m_writeCipherType - 1].m_allocateCipher(codec->m_db); + if (codec->m_writeCipher != NULL) + { + globalCodecDescriptorTable[codec->m_writeCipherType - 1].m_cloneCipher(codec->m_writeCipher, other->m_writeCipher); + } + else + { + rc = SQLITE_NOMEM; + } + } + codec->m_db = other->m_db; +#if 0 + codec->m_bt = other->m_bt; +#endif + codec->m_btShared = other->m_btShared; + + codec->m_lastError = SQLITE_OK; + + return rc; +} + +SQLITE_PRIVATE int +sqlite3mcCopyCipher(Codec* codec, int read2write) +{ + int rc = SQLITE_OK; + if (read2write) + { + if (codec->m_writeCipher != NULL && codec->m_writeCipherType != codec->m_readCipherType) + { + globalCodecDescriptorTable[codec->m_writeCipherType-1].m_freeCipher(codec->m_writeCipher); + codec->m_writeCipher = NULL; + } + if (codec->m_writeCipher == NULL) + { + codec->m_writeCipherType = codec->m_readCipherType; + codec->m_writeCipher = globalCodecDescriptorTable[codec->m_writeCipherType-1].m_allocateCipher(codec->m_db); + } + if (codec->m_writeCipher != NULL) + { + globalCodecDescriptorTable[codec->m_writeCipherType-1].m_cloneCipher(codec->m_writeCipher, codec->m_readCipher); + } + else + { + rc = SQLITE_NOMEM; + } + } + else + { + if (codec->m_readCipher != NULL && codec->m_readCipherType != codec->m_writeCipherType) + { + globalCodecDescriptorTable[codec->m_readCipherType-1].m_freeCipher(codec->m_readCipher); + codec->m_readCipher = NULL; + } + if (codec->m_readCipher == NULL) + { + codec->m_readCipherType = codec->m_writeCipherType; + codec->m_readCipher = globalCodecDescriptorTable[codec->m_readCipherType-1].m_allocateCipher(codec->m_db); + } + if (codec->m_readCipher != NULL) + { + globalCodecDescriptorTable[codec->m_readCipherType-1].m_cloneCipher(codec->m_readCipher, codec->m_writeCipher); + } + else + { + rc = SQLITE_NOMEM; + } + } + return rc; +} + +SQLITE_PRIVATE void +sqlite3mcPadPassword(char* password, int pswdlen, unsigned char pswd[32]) +{ + int j; + int p = 0; + int m = pswdlen; + if (m > 32) m = 32; + + for (j = 0; j < m; j++) + { + pswd[p++] = (unsigned char) password[j]; + } + for (j = 0; p < 32 && j < 32; j++) + { + pswd[p++] = padding[j]; + } +} + +SQLITE_PRIVATE unsigned char* mcReadDatabaseHeader(Codec* codec, unsigned char* dbHeader) +{ + Pager* pPager = codec->m_btShared->pPager; + sqlite3_file* fd = (isOpen(pPager->fd)) ? pPager->fd : NULL; + if (fd == NULL || sqlite3OsRead(fd, dbHeader, KEYSALT_LENGTH, 0) != SQLITE_OK) + return NULL; + else + return dbHeader; +} + +SQLITE_PRIVATE void +sqlite3mcGenerateReadKey(Codec* codec, char* userPassword, int passwordLength, unsigned char* cipherSalt) +{ + unsigned char dbHeader[KEYSALT_LENGTH]; + unsigned char* pDbHeader = (cipherSalt == NULL) ? mcReadDatabaseHeader(codec, dbHeader) : cipherSalt; + globalCodecDescriptorTable[codec->m_readCipherType-1].m_generateKey(codec->m_readCipher, userPassword, passwordLength, 0, pDbHeader); +} + +SQLITE_PRIVATE void +sqlite3mcGenerateWriteKey(Codec* codec, char* userPassword, int passwordLength, unsigned char* cipherSalt) +{ + unsigned char dbHeader[KEYSALT_LENGTH]; + unsigned char* pDbHeader = (cipherSalt == NULL) ? mcReadDatabaseHeader(codec, dbHeader) : cipherSalt; + globalCodecDescriptorTable[codec->m_writeCipherType-1].m_generateKey(codec->m_writeCipher, userPassword, passwordLength, 1, pDbHeader); +} + +SQLITE_PRIVATE int +sqlite3mcEncrypt(Codec* codec, int page, unsigned char* data, int len, int useWriteKey) +{ + int cipherType = (useWriteKey) ? codec->m_writeCipherType : codec->m_readCipherType; + void* cipher = (useWriteKey) ? codec->m_writeCipher : codec->m_readCipher; + int reserved = (useWriteKey) ? (codec->m_writeReserved >= 0) ? codec->m_writeReserved : codec->m_reserved + : (codec->m_readReserved >= 0) ? codec->m_readReserved : codec->m_reserved; + return globalCodecDescriptorTable[cipherType-1].m_encryptPage(cipher, page, data, len, reserved); +} + +SQLITE_PRIVATE int +sqlite3mcDecrypt(Codec* codec, int page, unsigned char* data, int len) +{ + int cipherType = codec->m_readCipherType; + void* cipher = codec->m_readCipher; + int reserved = (codec->m_readReserved >= 0) ? codec->m_readReserved : codec->m_reserved; + return globalCodecDescriptorTable[cipherType-1].m_decryptPage(cipher, page, data, len, reserved, codec->m_hmacCheck); +} + +#if HAVE_CIPHER_SQLCIPHER + +SQLITE_PRIVATE void +sqlite3mcConfigureSQLCipherVersion(sqlite3* db, int configDefault, int legacyVersion) +{ + static char* stdNames[] = { "legacy_page_size", "kdf_iter", "hmac_use", "kdf_algorithm", "hmac_algorithm", NULL }; + static char* defNames[] = { "default:legacy_page_size", "default:kdf_iter", "default:hmac_use", "default:kdf_algorithm", "default:hmac_algorithm", NULL }; + static int versionParams[SQLCIPHER_VERSION_MAX][5] = + { + { 1024, 4000, 0, SQLCIPHER_ALGORITHM_SHA1, SQLCIPHER_ALGORITHM_SHA1 }, + { 1024, 4000, 1, SQLCIPHER_ALGORITHM_SHA1, SQLCIPHER_ALGORITHM_SHA1 }, + { 1024, 64000, 1, SQLCIPHER_ALGORITHM_SHA1, SQLCIPHER_ALGORITHM_SHA1 }, + { 4096, 256000, 1, SQLCIPHER_ALGORITHM_SHA512, SQLCIPHER_ALGORITHM_SHA512 } + }; + if (legacyVersion > 0 && legacyVersion <= SQLCIPHER_VERSION_MAX) + { + char** names = (configDefault != 0) ? defNames : stdNames; + int* values = &versionParams[legacyVersion - 1][0]; + int j; + for (j = 0; names[j] != NULL; ++j) + { + sqlite3mc_config_cipher(db, "sqlcipher", names[j], values[j]); + } + } +} + +#endif +/*** End of #include "cipher_common.c" ***/ + +/* #include "cipher_config.c" */ +/*** Begin of #include "cipher_config.c" ***/ +/* +** Name: cipher_config.c +** Purpose: Configuration of SQLite codecs +** Author: Ulrich Telle +** Created: 2020-03-02 +** Copyright: (c) 2006-2024 Ulrich Telle +** License: MIT +*/ + +/* #include "cipher_common.h" */ + +/* #include "cipher_config.h" */ +/*** Begin of #include "cipher_config.h" ***/ +/* +** Name: cipher_config.h +** Purpose: Header for the cipher configuration of SQLite3 Multiple Ciphers +** Author: Ulrich Telle +** Created: 2020-03-10 +** Copyright: (c) 2006-2020 Ulrich Telle +** License: MIT +*/ + +#ifndef CIPHER_CONFIG_H_ +#define CIPHER_CONFIG_H_ + +/* #include "sqlite3mc.h" */ + + +SQLITE_PRIVATE void sqlite3mcConfigTable(sqlite3_context* context, int argc, sqlite3_value** argv); +SQLITE_PRIVATE CodecParameter* sqlite3mcGetCodecParams(sqlite3* db); + +/* Forward declaration */ +SQLITE_PRIVATE unsigned char* sqlite3mcGetSaltWriteCipher(Codec* codec); + +SQLITE_PRIVATE void sqlite3mcCodecDataSql(sqlite3_context* context, int argc, sqlite3_value** argv); +SQLITE_PRIVATE void sqlite3mcConfigParams(sqlite3_context* context, int argc, sqlite3_value** argv); +SQLITE_PRIVATE int sqlite3mcConfigureFromUri(sqlite3* db, const char *zDbName, int configDefault); + +SQLITE_PRIVATE int sqlite3mcFileControlPragma(sqlite3* db, const char* zDbName, int op, void* pArg); +SQLITE_PRIVATE int sqlite3mcCodecQueryParameters(sqlite3* db, const char* zDb, const char* zUri); +SQLITE_PRIVATE int sqlite3mcHandleAttachKey(sqlite3* db, const char* zName, const char* zPath, sqlite3_value* pKey, char** zErrDyn); +SQLITE_PRIVATE int sqlite3mcHandleMainKey(sqlite3* db, const char* zPath); + +#endif +/*** End of #include "cipher_config.h" ***/ + + +/* --- Codec --- */ + +SQLITE_PRIVATE int +sqlite3mcGetGlobalCipherCount(); + +SQLITE_PRIVATE Codec* +sqlite3mcGetCodec(sqlite3* db, const char* zDbName); + +SQLITE_PRIVATE void +sqlite3mcConfigTable(sqlite3_context* context, int argc, sqlite3_value** argv) +{ + CodecParameter* codecParams = (CodecParameter*) sqlite3_user_data(context); + assert(argc == 0); + sqlite3_result_pointer(context, codecParams, "sqlite3mc_codec_params", 0); +} + +SQLITE_PRIVATE CodecParameter* +sqlite3mcGetCodecParams(sqlite3* db) +{ + CodecParameter* codecParams = (CodecParameter*) sqlite3_get_clientdata(db, globalConfigTableName); + return codecParams; +} + +SQLITE_API int +sqlite3mc_config(sqlite3* db, const char* paramName, int newValue) +{ + int value = -1; + CodecParameter* codecParams; + int hasDefaultPrefix = 0; + int hasMinPrefix = 0; + int hasMaxPrefix = 0; + CipherParams* param; + +#ifndef SQLITE_OMIT_AUTOINIT + if (sqlite3_initialize()) return value; +#endif + + if (paramName == NULL || (db == NULL && newValue >= 0)) + { + return value; + } + + codecParams = (db != NULL) ? sqlite3mcGetCodecParams(db) : globalCodecParameterTable; + if (codecParams == NULL) + { + return value; + } + + if (sqlite3_strnicmp(paramName, "default:", 8) == 0) + { + hasDefaultPrefix = 1; + paramName += 8; + } + if (sqlite3_strnicmp(paramName, "min:", 4) == 0) + { + hasMinPrefix = 1; + paramName += 4; + } + if (sqlite3_strnicmp(paramName, "max:", 4) == 0) + { + hasMaxPrefix = 1; + paramName += 4; + } + + param = codecParams[0].m_params; + for (; param->m_name[0] != 0; ++param) + { + if (sqlite3_stricmp(paramName, param->m_name) == 0) break; + } + if (param->m_name[0] != 0) + { + int cipherCount = sqlite3mcGetGlobalCipherCount(); + if (db != NULL) + { + sqlite3_mutex_enter(db->mutex); + } + else + { + sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN)); + } + value = (hasDefaultPrefix) ? param->m_default : (hasMinPrefix) ? param->m_minValue : (hasMaxPrefix) ? param->m_maxValue : param->m_value; + if (!hasMinPrefix && !hasMaxPrefix && newValue >= 0 && newValue >= param->m_minValue && newValue <= param->m_maxValue) + { + int allowChange = 1; + + /* Allow cipher change only if new cipher is actually available */ + if (sqlite3_stricmp(paramName, "cipher") == 0) + { + allowChange = newValue > 0 && newValue <= cipherCount; + } + + if (allowChange) + { + /* Do not allow to change the default value for parameter "hmac_check" */ + if (hasDefaultPrefix && (sqlite3_stricmp(paramName, "hmac_check") != 0)) + { + param->m_default = newValue; + } + param->m_value = newValue; + value = newValue; + } + } + if (db != NULL) + { + sqlite3_mutex_leave(db->mutex); + } + else + { + sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN)); + } + } + return value; +} + +SQLITE_API int +sqlite3mc_cipher_count() +{ +#ifndef SQLITE_OMIT_AUTOINIT + if (sqlite3_initialize()) return 0; +#endif + return sqlite3mcGetGlobalCipherCount(); +} + +SQLITE_API int +sqlite3mc_cipher_index(const char* cipherName) +{ + int count; + int j; +#ifndef SQLITE_OMIT_AUTOINIT + if (sqlite3_initialize()) return -1; +#endif + count = sqlite3mcGetGlobalCipherCount(); + j = 0; + for (j = 0; j < count && globalCodecDescriptorTable[j].m_name[0] != 0; ++j) + { + if (sqlite3_stricmp(cipherName, globalCodecDescriptorTable[j].m_name) == 0) break; + } + return (j < count && globalCodecDescriptorTable[j].m_name[0] != 0) ? j + 1 : -1; +} + +SQLITE_API const char* +sqlite3mc_cipher_name(int cipherIndex) +{ + static char cipherName[CIPHER_NAME_MAXLEN] = ""; + int count; + int j; +#ifndef SQLITE_OMIT_AUTOINIT + if( sqlite3_initialize() ) return cipherName; +#endif + count = sqlite3mcGetGlobalCipherCount(); + j = 0; + cipherName[0] = '\0'; + if (cipherIndex > 0 && cipherIndex <= count) + { + for (j = 0; j < count && globalCodecDescriptorTable[j].m_name[0] != 0; ++j) + { + if (cipherIndex == j + 1) break; + } + if (j < count && globalCodecDescriptorTable[j].m_name[0] != 0) + { + strncpy(cipherName, globalCodecDescriptorTable[j].m_name, CIPHER_NAME_MAXLEN - 1); + cipherName[CIPHER_NAME_MAXLEN - 1] = '\0'; + } + } + return cipherName; +} + +static +int checkParameterValue(const char* paramName, int value) +{ + int ok = 1; + if (sqlite3_stricmp(paramName, "legacy_page_size") == 0 && value > 0) + { + ok = value >= 512 && value <= SQLITE_MAX_PAGE_SIZE && ((value - 1) & value) == 0; + } + if (ok && sqlite3_stricmp(paramName, "plaintext_header_size") == 0 && value > 0) + { + ok = value % 16 == 0; + } + return ok; +} + +SQLITE_API int +sqlite3mc_config_cipher(sqlite3* db, const char* cipherName, const char* paramName, int newValue) +{ + int value = -1; + CodecParameter* codecParams; + CipherParams* cipherParamTable = NULL; + int j = 0; + +#ifndef SQLITE_OMIT_AUTOINIT + if (sqlite3_initialize()) return value; +#endif + + if (cipherName == NULL || paramName == NULL) + { + sqlite3_log(SQLITE_WARNING, + "sqlite3mc_config_cipher: cipher name ('%s*) or parameter ('%s*) missing", + (cipherName == NULL) ? "" : cipherName, (paramName == NULL) ? "" : paramName); + return value; + } + else if (db == NULL && newValue >= 0) + { + sqlite3_log(SQLITE_WARNING, + "sqlite3mc_config_cipher: global change of parameter '%s' for cipher '%s' not supported", + paramName, cipherName); + return value; + } + + codecParams = (db != NULL) ? sqlite3mcGetCodecParams(db) : globalCodecParameterTable; + if (codecParams == NULL) + { + sqlite3_log(SQLITE_WARNING, + "sqlite3mc_config_cipher: codec parameter table not found"); + return value; + } + + for (j = 0; codecParams[j].m_name[0] != 0; ++j) + { + if (sqlite3_stricmp(cipherName, codecParams[j].m_name) == 0) break; + } + if (codecParams[j].m_name[0] != 0) + { + cipherParamTable = codecParams[j].m_params; + } + + if (cipherParamTable != NULL) + { + int hasDefaultPrefix = 0; + int hasMinPrefix = 0; + int hasMaxPrefix = 0; + CipherParams* param = cipherParamTable; + + if (sqlite3_strnicmp(paramName, "default:", 8) == 0) + { + hasDefaultPrefix = 1; + paramName += 8; + } + if (sqlite3_strnicmp(paramName, "min:", 4) == 0) + { + hasMinPrefix = 1; + paramName += 4; + } + if (sqlite3_strnicmp(paramName, "max:", 4) == 0) + { + hasMaxPrefix = 1; + paramName += 4; + } + +#if HAVE_CIPHER_SQLCIPHER + /* Special handling for SQLCipher legacy mode */ + if (db != NULL && + sqlite3_stricmp(cipherName, "sqlcipher") == 0 && + sqlite3_stricmp(paramName, "legacy") == 0) + { + if (!hasMinPrefix && !hasMaxPrefix) + { + if (newValue > 0 && newValue <= SQLCIPHER_VERSION_MAX) + { + sqlite3mcConfigureSQLCipherVersion(db, hasDefaultPrefix, newValue); + } + else if (newValue != -1) + { + sqlite3_log(SQLITE_WARNING, + "sqlite3mc_config_cipher: SQLCipher legacy version %d out of range [%d..%d]", + newValue, 1, SQLCIPHER_VERSION_MAX); + } + } + } +#endif + + for (; param->m_name[0] != 0; ++param) + { + if (sqlite3_stricmp(paramName, param->m_name) == 0) break; + } + if (param->m_name[0] != 0) + { + if (db != NULL) + { + sqlite3_mutex_enter(db->mutex); + } + else + { + sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + } + value = (hasDefaultPrefix) ? param->m_default : (hasMinPrefix) ? param->m_minValue : (hasMaxPrefix) ? param->m_maxValue : param->m_value; + if (!hasMinPrefix && !hasMaxPrefix) + { + if (newValue >= 0 && newValue >= param->m_minValue && newValue <= param->m_maxValue && + checkParameterValue(paramName, newValue)) + { + if (hasDefaultPrefix) + { + param->m_default = newValue; + } + param->m_value = newValue; + value = newValue; + } + else if (newValue != -1) + { + sqlite3_log(SQLITE_WARNING, + "sqlite3mc_config_cipher: Value %d for parameter '%s' of cipher '%s' out of range [%d..%d]", + newValue, paramName, cipherName, param->m_minValue, param->m_maxValue); + } + } + if (db != NULL) + { + sqlite3_mutex_leave(db->mutex); + } + else + { + sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + } + } + } + return value; +} + +SQLITE_API unsigned char* +sqlite3mc_codec_data(sqlite3* db, const char* zDbName, const char* paramName) +{ + unsigned char* result = NULL; +#ifndef SQLITE_OMIT_AUTOINIT + if (sqlite3_initialize()) return NULL; +#endif + if (db != NULL && paramName != NULL) + { + int iDb = (zDbName != NULL) ? sqlite3FindDbName(db, zDbName) : 0; + int toRaw = 0; + if (sqlite3_strnicmp(paramName, "raw:", 4) == 0) + { + toRaw = 1; + paramName += 4; + } + if ((sqlite3_stricmp(paramName, "cipher_salt") == 0) && (iDb >= 0)) + { + /* Check whether database is encrypted */ + Codec* codec = sqlite3mcGetCodec(db, zDbName); + if (codec != NULL && sqlite3mcIsEncrypted(codec) && sqlite3mcHasWriteCipher(codec)) + { + unsigned char* salt = sqlite3mcGetSaltWriteCipher(codec); + if (salt != NULL) + { + if (!toRaw) + { + int j; + result = sqlite3_malloc(32 + 1); + for (j = 0; j < 16; ++j) + { + result[j * 2] = hexdigits[(salt[j] >> 4) & 0x0F]; + result[j * 2 + 1] = hexdigits[(salt[j]) & 0x0F]; + } + result[32] = '\0'; + } + else + { + result = sqlite3_malloc(16 + 1); + memcpy(result, salt, 16); + result[16] = '\0'; + } + } + } + } + } + return result; +} + +SQLITE_PRIVATE void +sqlite3mcCodecDataSql(sqlite3_context* context, int argc, sqlite3_value** argv) +{ + const char* nameParam1 = NULL; + const char* nameParam2 = NULL; + + assert(argc == 1 || argc == 2); + /* NULL values are not allowed for the first 2 arguments */ + if (SQLITE_NULL == sqlite3_value_type(argv[0]) || (argc > 1 && SQLITE_NULL == sqlite3_value_type(argv[1]))) + { + sqlite3_result_null(context); + return; + } + + /* Determine parameter name */ + nameParam1 = (const char*) sqlite3_value_text(argv[0]); + + /* Determine schema name if given */ + if (argc == 2) + { + nameParam2 = (const char*) sqlite3_value_text(argv[1]); + } + + /* Check for known parameter name(s) */ + if (sqlite3_stricmp(nameParam1, "cipher_salt") == 0) + { + /* Determine key salt */ + sqlite3* db = sqlite3_context_db_handle(context); + const char* salt = (const char*) sqlite3mc_codec_data(db, nameParam2, "cipher_salt"); + if (salt != NULL) + { + sqlite3_result_text(context, salt, -1, sqlite3_free); + } + else + { + sqlite3_result_null(context); + } + } + else + { + sqlite3_result_null(context); + } +} + +SQLITE_PRIVATE void +sqlite3mcConfigParams(sqlite3_context* context, int argc, sqlite3_value** argv) +{ + CodecParameter* codecParams; + const char* nameParam1; + int hasDefaultPrefix = 0; + int hasMinPrefix = 0; + int hasMaxPrefix = 0; + CipherParams* param1; + CipherParams* cipherParamTable = NULL; + int isCommonParam1; + int isCipherParam1 = 0; + + assert(argc == 1 || argc == 2 || argc == 3); + /* NULL values are not allowed for the first 2 arguments */ + if (SQLITE_NULL == sqlite3_value_type(argv[0]) || (argc > 1 && SQLITE_NULL == sqlite3_value_type(argv[1]))) + { + sqlite3_result_null(context); + return; + } + + codecParams = (CodecParameter*)sqlite3_user_data(context); + + /* Check first argument whether it is a common parameter */ + /* If the first argument is a common parameter, param1 will point to its parameter table entry */ + nameParam1 = (const char*)sqlite3_value_text(argv[0]); + if (sqlite3_strnicmp(nameParam1, "default:", 8) == 0) + { + hasDefaultPrefix = 1; + nameParam1 += 8; + } + if (sqlite3_strnicmp(nameParam1, "min:", 4) == 0) + { + hasMinPrefix = 1; + nameParam1 += 4; + } + if (sqlite3_strnicmp(nameParam1, "max:", 4) == 0) + { + hasMaxPrefix = 1; + nameParam1 += 4; + } + + param1 = codecParams[0].m_params; + cipherParamTable = NULL; + for (; param1->m_name[0] != 0; ++param1) + { + if (sqlite3_stricmp(nameParam1, param1->m_name) == 0) break; + } + isCommonParam1 = param1->m_name[0] != 0; + + /* Check first argument whether it is a cipher name, if it wasn't a common parameter */ + /* If the first argument is a cipher name, cipherParamTable will point to the corresponding cipher parameter table */ + if (!isCommonParam1) + { + if (!hasDefaultPrefix && !hasMinPrefix && !hasMaxPrefix) + { + int j = 0; + for (j = 0; codecParams[j].m_name[0] != 0; ++j) + { + if (sqlite3_stricmp(nameParam1, codecParams[j].m_name) == 0) break; + } + isCipherParam1 = codecParams[j].m_name[0] != 0; + if (isCipherParam1) + { + cipherParamTable = codecParams[j].m_params; + } + } + if (!isCipherParam1) + { + /* Prefix not allowed for cipher names or cipher name not found */ + sqlite3_result_null(context); + return; + } + } + + if (argc == 1) + { + /* Return value of param1 */ + if (isCommonParam1) + { + int value = (hasDefaultPrefix) ? param1->m_default : (hasMinPrefix) ? param1->m_minValue : (hasMaxPrefix) ? param1->m_maxValue : param1->m_value; + if (sqlite3_stricmp(nameParam1, "cipher") == 0) + { + sqlite3_result_text(context, globalCodecDescriptorTable[value - 1].m_name, -1, SQLITE_STATIC); + } + else + { + sqlite3_result_int(context, value); + } + } + else if (isCipherParam1) + { + /* Return a list of available parameters for the requested cipher */ + int nParams = 0; + int lenTotal = 0; + int j; + for (j = 0; cipherParamTable[j].m_name[0] != 0; ++j) + { + ++nParams; + lenTotal += (int) strlen(cipherParamTable[j].m_name); + } + if (nParams > 0) + { + char* paramList = (char*)sqlite3_malloc(lenTotal + nParams); + if (paramList != NULL) + { + char* p = paramList; + strcpy(paramList, cipherParamTable[0].m_name); + for (j = 1; j < nParams; ++j) + { + strcat(paramList, ","); + strcat(paramList, cipherParamTable[j].m_name); + } + sqlite3_result_text(context, paramList, -1, sqlite3_free); + } + else + { + /* Not enough memory to allocate the result */ + sqlite3_result_error_nomem(context); + } + } + else + { + /* Cipher has no parameters */ + sqlite3_result_null(context); + } + } + } + else + { + /* 2 or more arguments */ + int arg2Type = sqlite3_value_type(argv[1]); + if (argc == 2 && isCommonParam1) + { + /* Set value of common parameter */ + if (sqlite3_stricmp(nameParam1, "cipher") == 0) + { + /* 2nd argument is a cipher name */ + if (arg2Type == SQLITE_TEXT) + { + const char* nameCipher = (const char*)sqlite3_value_text(argv[1]); + int j = 0; + for (j = 0; globalCodecDescriptorTable[j].m_name[0] != 0; ++j) + { + if (sqlite3_stricmp(nameCipher, globalCodecDescriptorTable[j].m_name) == 0) break; + } + if (globalCodecDescriptorTable[j].m_name[0] != 0) + { + if (hasDefaultPrefix) + { + param1->m_default = j + 1; + } + param1->m_value = j + 1; + sqlite3_result_text(context, globalCodecDescriptorTable[j].m_name, -1, SQLITE_STATIC); + } + else + { + /* No match for cipher name found */ + sqlite3_result_null(context); + } + } + else + { + /* Invalid parameter type */ + sqlite3_result_null(context); + } + } + else if (arg2Type == SQLITE_INTEGER) + { + /* Check that parameter value is within allowed range */ + int value = sqlite3_value_int(argv[1]); + if (value >= param1->m_minValue && value <= param1->m_maxValue) + { + /* Do not allow to change the default value for parameter "hmac_check" */ + if (hasDefaultPrefix && (sqlite3_stricmp(nameParam1, "hmac_check") != 0)) + { + param1->m_default = value; + } + param1->m_value = value; + sqlite3_result_int(context, value); + } + else + { + /* Parameter value not within allowed range */ + sqlite3_result_null(context); + } + } + else + { + sqlite3_result_null(context); + } + } + else if (isCipherParam1 && arg2Type == SQLITE_TEXT) + { + /* get or set cipher parameter */ + const char* nameParam2 = (const char*)sqlite3_value_text(argv[1]); + CipherParams* param2 = cipherParamTable; + hasDefaultPrefix = 0; + if (sqlite3_strnicmp(nameParam2, "default:", 8) == 0) + { + hasDefaultPrefix = 1; + nameParam2 += 8; + } + hasMinPrefix = 0; + if (sqlite3_strnicmp(nameParam2, "min:", 4) == 0) + { + hasMinPrefix = 1; + nameParam2 += 4; + } + hasMaxPrefix = 0; + if (sqlite3_strnicmp(nameParam2, "max:", 4) == 0) + { + hasMaxPrefix = 1; + nameParam2 += 4; + } + for (; param2->m_name[0] != 0; ++param2) + { + if (sqlite3_stricmp(nameParam2, param2->m_name) == 0) break; + } + +#if HAVE_CIPHER_SQLCIPHER + /* Special handling for SQLCipher legacy mode */ + if (argc == 3 && + sqlite3_stricmp(nameParam1, "sqlcipher") == 0 && + sqlite3_stricmp(nameParam2, "legacy") == 0) + { + if (!hasMinPrefix && !hasMaxPrefix && sqlite3_value_type(argv[2]) == SQLITE_INTEGER) + { + int legacy = sqlite3_value_int(argv[2]); + if (legacy > 0 && legacy <= SQLCIPHER_VERSION_MAX) + { + sqlite3* db = sqlite3_context_db_handle(context); + sqlite3mcConfigureSQLCipherVersion(db, hasDefaultPrefix, legacy); + } + } + } +#endif + + if (param2->m_name[0] != 0) + { + if (argc == 2) + { + /* Return parameter value */ + int value = (hasDefaultPrefix) ? param2->m_default : (hasMinPrefix) ? param2->m_minValue : (hasMaxPrefix) ? param2->m_maxValue : param2->m_value; + sqlite3_result_int(context, value); + } + else if (!hasMinPrefix && !hasMaxPrefix && sqlite3_value_type(argv[2]) == SQLITE_INTEGER) + { + /* Change cipher parameter value */ + int value = sqlite3_value_int(argv[2]); + if (value >= param2->m_minValue && value <= param2->m_maxValue) + { + if (hasDefaultPrefix) + { + param2->m_default = value; + } + param2->m_value = value; + sqlite3_result_int(context, value); + } + else + { + /* Cipher parameter value not within allowed range */ + sqlite3_result_null(context); + } + } + else + { + /* Only current value and default value of a parameter can be changed */ + sqlite3_result_null(context); + } + } + else + { + /* Cipher parameter not found */ + sqlite3_result_null(context); + } + } + else + { + /* Cipher has no parameters */ + sqlite3_result_null(context); + } + } +} + +SQLITE_PRIVATE int +sqlite3mcConfigureFromUri(sqlite3* db, const char *zDbName, int configDefault) +{ + int rc = SQLITE_OK; + + /* Check URI parameters if database filename is available */ + const char* dbFileName = zDbName; + if (dbFileName != NULL) + { + /* Check whether cipher is specified */ + const char* cipherName = sqlite3_uri_parameter(dbFileName, "cipher"); + if (cipherName != NULL) + { + int j = 0; + CipherParams* cipherParams = NULL; + + /* Try to locate the cipher name */ + for (j = 1; globalCodecParameterTable[j].m_name[0] != 0; ++j) + { + if (sqlite3_stricmp(cipherName, globalCodecParameterTable[j].m_name) == 0) break; + } + + /* j is the index of the cipher name, if found */ + cipherParams = (globalCodecParameterTable[j].m_name[0] != 0) ? globalCodecParameterTable[j].m_params : NULL; + if (cipherParams != NULL) + { + /* + ** Flag whether to skip the legacy parameter + ** Currently enabled only in case of the SQLCipher scheme + */ + int skipLegacy = 0; + /* Set global parameters (cipher and hmac_check) */ + int hmacCheck = sqlite3_uri_boolean(dbFileName, "hmac_check", 1); + int walLegacy = sqlite3_uri_boolean(dbFileName, "mc_legacy_wal", 0); + if (configDefault) + { + sqlite3mc_config(db, "default:cipher", globalCodecParameterTable[j].m_id); + } + else + { + sqlite3mc_config(db, "cipher", globalCodecParameterTable[j].m_id); + } + if (!hmacCheck) + { + sqlite3mc_config(db, "hmac_check", hmacCheck); + } + sqlite3mc_config(db, "mc_legacy_wal", walLegacy); + +#if HAVE_CIPHER_SQLCIPHER + /* Special handling for SQLCipher */ + if (sqlite3_stricmp(cipherName, "sqlcipher") == 0) + { + int legacy = (int) sqlite3_uri_int64(dbFileName, "legacy", 0); + if (legacy > 0 && legacy <= SQLCIPHER_VERSION_MAX) + { + char* param = (configDefault) ? "default:legacy" : "legacy"; + sqlite3mc_config_cipher(db, cipherName, param, legacy); + skipLegacy = 1; + } + } +#endif + +#if HAVE_CIPHER_AEGIS + int hasAegisAlgorithm = 0; + int aegisAlgorithm = 0; + if (sqlite3_stricmp(cipherName, "aegis") == 0) + { + const char* algorithm = sqlite3_uri_parameter(dbFileName, "algorithm"); + if (algorithm != NULL && *algorithm != 0) + { + int intValue = -1; + int isIntValue = sqlite3GetInt32(algorithm, &intValue) != 0; + if (!isIntValue) + { + intValue = sqlite3mcAegisAlgorithmToIndex(algorithm); + } + if (intValue > 0) + { + hasAegisAlgorithm = 1; + aegisAlgorithm = intValue; + } + } + } +#endif + + /* Check all cipher specific parameters */ + for (j = 0; cipherParams[j].m_name[0] != 0; ++j) + { + int value = -1; + if (skipLegacy && sqlite3_stricmp(cipherParams[j].m_name, "legacy") == 0) continue; + +#if HAVE_CIPHER_AEGIS + if (hasAegisAlgorithm && sqlite3_stricmp(cipherParams[j].m_name, "algorithm") == 0) + { + value = aegisAlgorithm; + } + else +#endif + { + value = (int)sqlite3_uri_int64(dbFileName, cipherParams[j].m_name, -1); + } + if (value >= 0) + { + /* Configure cipher parameter if it was given in the URI */ + const char* param = (configDefault) ? sqlite3_mprintf("default:%s", cipherParams[j].m_name) : cipherParams[j].m_name; + sqlite3mc_config_cipher(db, cipherName, param, value); + if (configDefault) + { + sqlite3_free((char*) param); + } + } + } + } + else + { + rc = SQLITE_ERROR; + sqlite3ErrorWithMsg(db, rc, "unknown cipher '%s'", cipherName); + } + } + } + return rc; +} + +#ifdef SQLITE3MC_WXSQLITE3_COMPATIBLE +SQLITE_API int +wxsqlite3_config(sqlite3* db, const char* paramName, int newValue) +{ + return sqlite3mc_config(db, paramName, newValue); +} + +SQLITE_API int +wxsqlite3_config_cipher(sqlite3* db, const char* cipherName, const char* paramName, int newValue) +{ + return sqlite3mc_config_cipher(db, cipherName, paramName, newValue); +} + +SQLITE_API unsigned char* +wxsqlite3_codec_data(sqlite3* db, const char* zDbName, const char* paramName) +{ + return sqlite3mc_codec_data(db, zDbName, paramName); +} +#endif + +/* +** Functions called from patched SQLite version +*/ + +SQLITE_PRIVATE int +sqlite3mcFileControlPragma(sqlite3* db, const char* zDbName, int op, void* pArg) +{ + int rc = sqlite3_file_control(db, zDbName, op, pArg); + if (rc == SQLITE_NOTFOUND) + { + int configDefault; + char* pragmaName; + char* pragmaValue; + int dbIndex = (zDbName) ? sqlite3FindDbName(db, zDbName) : 0; + if (dbIndex < 0 && zDbName != NULL) + { + /* Unknown schema name */ + return rc; + } + + configDefault = (dbIndex <= 0); + pragmaName = ((char**) pArg)[1]; + pragmaValue = ((char**) pArg)[2]; + if (sqlite3StrICmp(pragmaName, "cipher") == 0) + { + int cipherId = -1; + if (pragmaValue != NULL) + { + int j = 1; + /* Try to locate the cipher name */ + for (j = 1; globalCodecParameterTable[j].m_name[0] != 0; ++j) + { + if (sqlite3_stricmp(pragmaValue, globalCodecParameterTable[j].m_name) == 0) break; + } + cipherId = (globalCodecParameterTable[j].m_name[0] != 0) ? globalCodecParameterTable[j].m_id : CODEC_TYPE_UNKNOWN; + } + + /* cipherId is the numeric id of the cipher name, if found */ + if ((cipherId == -1) || (cipherId > 0 && cipherId <= CODEC_COUNT_MAX)) + { + int value; + if (configDefault) + { + value = sqlite3mc_config(db, "default:cipher", cipherId); + } + else + { + value = sqlite3mc_config(db, "cipher", cipherId); + } + if (value > 0) + { + ((char**)pArg)[0] = sqlite3_mprintf("%s", globalCodecDescriptorTable[value - 1].m_name); + rc = SQLITE_OK; + } + else + { + ((char**)pArg)[0] = sqlite3_mprintf("Cipher '%s' could not be located.", pragmaValue); + rc = SQLITE_ERROR; + } + } + else + { + ((char**) pArg)[0] = sqlite3_mprintf("Cipher '%s' unknown.", pragmaValue); + rc = SQLITE_ERROR; + } + } + else if (sqlite3StrICmp(pragmaName, "hmac_check") == 0) + { + int hmacCheck = (pragmaValue != NULL) ? sqlite3GetBoolean(pragmaValue, 1) : -1; + int value = sqlite3mc_config(db, "hmac_check", hmacCheck); + ((char**)pArg)[0] = sqlite3_mprintf("%d", value); + rc = SQLITE_OK; + } + else if (sqlite3StrICmp(pragmaName, "mc_legacy_wal") == 0) + { + int walLegacy = (pragmaValue != NULL) ? sqlite3GetBoolean(pragmaValue, 0) : -1; + int value = sqlite3mc_config(db, "mc_legacy_wal", walLegacy); + ((char**)pArg)[0] = sqlite3_mprintf("%d", value); + rc = SQLITE_OK; + } + else if (sqlite3StrICmp(pragmaName, "key") == 0) + { + rc = sqlite3_key_v2(db, zDbName, pragmaValue, -1); + if (rc == SQLITE_OK) + { + ((char**)pArg)[0] = sqlite3_mprintf("ok"); + } + else + { + if (db->pErr) + { + const char* z = (const char*)sqlite3_value_text(db->pErr); + if (z && sqlite3Strlen30(z) > 0) + { + ((char**)pArg)[0] = sqlite3_mprintf(z); + } + } + } + } + else if (sqlite3StrICmp(pragmaName, "hexkey") == 0) + { + int nValue = sqlite3Strlen30(pragmaValue); + if (((nValue & 1) == 0) && (sqlite3mcIsHexKey((const unsigned char*) pragmaValue, nValue) != 0)) + { + unsigned char* zHexKey = sqlite3_malloc(nValue/2); + sqlite3mcConvertHex2Bin((const unsigned char*) pragmaValue, nValue, zHexKey); + rc = sqlite3_key_v2(db, zDbName, zHexKey, nValue/2); + sqlite3_free(zHexKey); + if (rc == SQLITE_OK) + { + ((char**)pArg)[0] = sqlite3_mprintf("ok"); + } + else + { + if (db->pErr) + { + const char* z = (const char*)sqlite3_value_text(db->pErr); + if (z && sqlite3Strlen30(z) > 0) + { + ((char**)pArg)[0] = sqlite3_mprintf(z); + } + } + } + } + else + { + rc = SQLITE_ERROR; + ((char**)pArg)[0] = sqlite3_mprintf("Malformed hex string"); + } + } + else if (sqlite3StrICmp(pragmaName, "rekey") == 0) + { + rc = sqlite3_rekey_v2(db, zDbName, pragmaValue, -1); + if (rc == SQLITE_OK) + { + ((char**)pArg)[0] = sqlite3_mprintf("ok"); + } + else + { + if (db->pErr) + { + const char* z = (const char*) sqlite3_value_text(db->pErr); + if (z && sqlite3Strlen30(z) > 0) + { + ((char**)pArg)[0] = sqlite3_mprintf(z); + } + } + } + } + else if (sqlite3StrICmp(pragmaName, "hexrekey") == 0) + { + int nValue = sqlite3Strlen30(pragmaValue); + if (((nValue & 1) == 0) && (sqlite3mcIsHexKey((const unsigned char*) pragmaValue, nValue) != 0)) + { + unsigned char* zHexKey = sqlite3_malloc(nValue/2); + sqlite3mcConvertHex2Bin((const unsigned char*) pragmaValue, nValue, zHexKey); + rc = sqlite3_rekey_v2(db, zDbName, zHexKey, nValue/2); + sqlite3_free(zHexKey); + if (rc == SQLITE_OK) + { + ((char**)pArg)[0] = sqlite3_mprintf("ok"); + } + else + { + if (db->pErr) + { + const char* z = (const char*)sqlite3_value_text(db->pErr); + if (z && sqlite3Strlen30(z) > 0) + { + ((char**)pArg)[0] = sqlite3_mprintf(z); + } + } + } + } + else + { + rc = SQLITE_ERROR; + ((char**)pArg)[0] = sqlite3_mprintf("Malformed hex string"); + } + } +#if SQLITE3MC_SECURE_MEMORY + else if (sqlite3StrICmp(pragmaName, "memory_security") == 0) + { + if (pragmaValue) + { + int intValue = -1; + if (0 == sqlite3StrICmp(pragmaValue, "none")) + { + intValue = SECURE_MEMORY_NONE; + } + else if (0 == sqlite3StrICmp(pragmaValue, "fill") ) + { + intValue = SECURE_MEMORY_FILL; + } +#if SQLITE3MC_ENABLE_MEMLOCK + else if (0 == sqlite3StrICmp(pragmaValue, "lock") ) + { + intValue = SECURE_MEMORY_LOCK; + } +#endif + else + { + intValue = sqlite3Atoi(pragmaValue); +#if SQLITE3MC_ENABLE_MEMLOCK + intValue = (intValue >=0 && intValue <= 2) ? intValue : -1; +#else + intValue = (intValue >=0 && intValue <= 1) ? intValue : -1; +#endif + } + if (intValue >= 0) + { + sqlite3mcSetMemorySecurity(intValue); + rc = SQLITE_OK; + ((char**)pArg)[0] = sqlite3_mprintf("%d", intValue); + } + else + { + rc = SQLITE_ERROR; + ((char**) pArg)[0] = sqlite3_mprintf("Secure memory option '%s' invalid.", pragmaValue); + } + } + else + { + rc = SQLITE_OK; + ((char**)pArg)[0] = sqlite3_mprintf("%d", sqlite3mcGetMemorySecurity()); + } + } +#endif /* SQLITE3MC_SECURE_MEMORY */ + else + { + int j; + int intValue = (pragmaValue != NULL) ? 0 : -1; + int isIntValue = (pragmaValue != NULL) ? (sqlite3GetInt32(pragmaValue, &intValue) != 0) : 1; + + /* Determine cipher */ + int cipher = sqlite3mc_config(db, "cipher", -1); + CipherParams* cipherParams = NULL; + + /* Try to locate the cipher name */ + for (j = 1; globalCodecParameterTable[j].m_name[0] != 0; ++j) + { + if (cipher == globalCodecParameterTable[j].m_id) break; + } + + /* j is the index of the cipher name, if found */ + cipherParams = (globalCodecParameterTable[j].m_name[0] != 0) ? globalCodecParameterTable[j].m_params : NULL; + if (cipherParams != NULL) + { + const char* cipherName = globalCodecParameterTable[j].m_name; +#if HAVE_CIPHER_AEGIS + int isAegisAlgorithm = 0; + if (sqlite3_stricmp(cipherName, "aegis") == 0 && + sqlite3_stricmp(pragmaName, "algorithm") == 0) + { + if (!isIntValue) + { + intValue = sqlite3mcAegisAlgorithmToIndex(pragmaValue); + isIntValue = 1; + } + isAegisAlgorithm = 1; + } +#endif + for (j = 0; cipherParams[j].m_name[0] != 0; ++j) + { + if (sqlite3_stricmp(pragmaName, cipherParams[j].m_name) == 0) break; + } + if (cipherParams[j].m_name[0] != 0) + { + char* param = (configDefault) ? sqlite3_mprintf("default:%s", pragmaName) : pragmaName; + if (isIntValue) + { + int value = sqlite3mc_config_cipher(db, cipherName, param, intValue); +#if HAVE_CIPHER_AEGIS + if (isAegisAlgorithm) + { + ((char**)pArg)[0] = sqlite3_mprintf("%s", sqlite3mcAegisAlgorithmToString(value)); + } + else +#endif + { + ((char**)pArg)[0] = sqlite3_mprintf("%d", value); + } + rc = SQLITE_OK; + } + else + { + ((char**) pArg)[0] = sqlite3_mprintf("Malformed integer value '%s'.", pragmaValue); + rc = SQLITE_ERROR; + } + if (configDefault) + { + sqlite3_free(param); + } + } + } + } + } + return rc; +} + +/* +** Process URI filename query parameters relevant to the SQLite Encryption +** Extension. Return true if any of the relevant query parameters are +** seen and return false if not. +*/ +SQLITE_PRIVATE int +sqlite3mcCodecQueryParameters(sqlite3* db, const char* zDb, const char* zUri) +{ + int rc = 1; + const char* zKey; + if ((zKey = sqlite3_uri_parameter(zUri, "hexkey")) != 0 && zKey[0]) + { + u8 iByte; + int i; + int nKey = sqlite3Strlen30(zKey); + char* zDecoded = sqlite3_malloc(nKey); + for (i = 0, iByte = 0; i < nKey && sqlite3Isxdigit(zKey[i]); i++) + { + iByte = (iByte << 4) + sqlite3HexToInt(zKey[i]); + if ((i & 1) != 0) zDecoded[i/2] = iByte; + } + sqlite3_key_v2(db, zDb, zDecoded, i/2); + sqlite3_free(zDecoded); + } + else if ((zKey = sqlite3_uri_parameter(zUri, "key")) != 0) + { + sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey)); + } + else if ((zKey = sqlite3_uri_parameter(zUri, "textkey")) != 0) + { + sqlite3_key_v2(db, zDb, zKey, -1); + } + else + { + rc = 0; + } + return rc; +} + +SQLITE_PRIVATE int +sqlite3mcHandleAttachKey(sqlite3* db, const char* zName, const char* zPath, sqlite3_value* pKey, char** zErrDyn) +{ + int rc = SQLITE_OK; + int nKey; + char* zKey; + int keyType = sqlite3_value_type(pKey); + switch (keyType) + { + case SQLITE_INTEGER: + case SQLITE_FLOAT: + /* Invalid data type for key */ + *zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); + rc = SQLITE_ERROR; + break; + + case SQLITE_TEXT: + case SQLITE_BLOB: + /* Key parameter specified in ATTACH statement */ + nKey = sqlite3_value_bytes(pKey); + zKey = (char*) sqlite3_value_blob(pKey); + rc = sqlite3mcCodecAttach(db, db->nDb - 1, zPath, zKey, nKey); + break; + + case SQLITE_NULL: + /* No key specified. Use the key from URI filename, or if none, + ** use the key from the main database. */ + if (sqlite3mcCodecQueryParameters(db, zName, zPath) == 0) + { + sqlite3mcCodecGetKey(db, 0, (void**) &zKey, &nKey); + if (nKey) + { + rc = sqlite3mcCodecAttach(db, db->nDb - 1, zPath, zKey, nKey); + } + } + break; + } + + return rc; +} + +SQLITE_PRIVATE int +sqlite3mcHandleMainKey(sqlite3* db, const char* zPath) +{ + int rc = sqlite3mcConfigureFromUri(db, zPath, 1); + if (rc == SQLITE_OK) + { + sqlite3mcCodecQueryParameters(db, "main", zPath); + } + return rc; +} +/*** End of #include "cipher_config.c" ***/ + + +/* #include "codecext.c" */ +/*** Begin of #include "codecext.c" ***/ +/* +** Name: codecext.c +** Purpose: Implementation of SQLite codec API +** Author: Ulrich Telle +** Created: 2006-12-06 +** Copyright: (c) 2006-2022 Ulrich Telle +** License: MIT +*/ + +/* +** "Special" version of function sqlite3BtreeSetPageSize +** This version allows to reduce the number of reserved bytes per page, +** while the original version allows only to increase it. +** Needed to reclaim reserved space on decrypting a database. +*/ +SQLITE_PRIVATE int +sqlite3mcBtreeSetPageSize(Btree* p, int pageSize, int nReserve, int iFix) +{ + int rc = SQLITE_OK; + int x; + BtShared* pBt = p->pBt; + assert(nReserve >= 0 && nReserve <= 255); + sqlite3BtreeEnter(p); + pBt->nReserveWanted = nReserve; + x = pBt->pageSize - pBt->usableSize; + if (nReserve < 0) nReserve = x; + if (pBt->btsFlags & BTS_PAGESIZE_FIXED) + { + sqlite3BtreeLeave(p); + return SQLITE_READONLY; + } + assert(nReserve >= 0 && nReserve <= 255); + if (pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE && + ((pageSize - 1) & pageSize) == 0) + { + assert((pageSize & 7) == 0); + assert(!pBt->pCursor); + pBt->pageSize = (u32)pageSize; + freeTempSpace(pBt); + } + rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); + pBt->usableSize = pBt->pageSize - (u16)nReserve; + if (iFix) pBt->btsFlags |= BTS_PAGESIZE_FIXED; + sqlite3BtreeLeave(p); + return rc; +} + +/* +** Include a "special" version of the VACUUM command +*/ +/* #include "rekeyvacuum.c" */ +/*** Begin of #include "rekeyvacuum.c" ***/ +/* +** 2020-11-14 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************ +** +** This file contains an adjusted version of function sqlite3RunVacuum +** to allow reducing or removing reserved page space. +** For this purpose the number of reserved bytes per page for the target +** database is passed as an extra parameter to the adjusted function. +** +** NOTE: When upgrading to a new version of SQLite3 it is strongly +** recommended to check the original function sqlite3RunVacuum of the +** new version for relevant changes, and to incorporate them in the +** adjusted function below. +** +** Change 0: Rename function to sqlite3mcRunVacuumForRekey() +** Change 1: Add parameter 'int nRes' +** Change 2: Remove local variable 'int nRes' +** Change 3: Remove initialization 'nRes = sqlite3BtreeGetOptimalReserve(pMain)' +** Change 4: Call sqlite3mcBtreeSetPageSize instead of sqlite3BtreeSetPageSize for main database +** (sqlite3mcBtreeSetPageSize allows to reduce the number of reserved bytes) +** +** This code is generated by the script rekeyvacuum.sh from SQLite version 3.50.1 amalgamation. +*/ +SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3mcRunVacuumForRekey( + char **pzErrMsg, /* Write error message here */ + sqlite3 *db, /* Database connection */ + int iDb, /* Which attached DB to vacuum */ + sqlite3_value *pOut /* Write results here, if not NULL. VACUUM INTO */ +, int nRes){ + int rc = SQLITE_OK; /* Return code from service routines */ + Btree *pMain; /* The database being vacuumed */ + Btree *pTemp; /* The temporary database we vacuum into */ + u32 saved_mDbFlags; /* Saved value of db->mDbFlags */ + u64 saved_flags; /* Saved value of db->flags */ + i64 saved_nChange; /* Saved value of db->nChange */ + i64 saved_nTotalChange; /* Saved value of db->nTotalChange */ + u32 saved_openFlags; /* Saved value of db->openFlags */ + u8 saved_mTrace; /* Saved trace settings */ + Db *pDb = 0; /* Database to detach at end of vacuum */ + int isMemDb; /* True if vacuuming a :memory: database */ + int nDb; /* Number of attached databases */ + const char *zDbMain; /* Schema name of database to vacuum */ + const char *zOut; /* Name of output file */ + u32 pgflags = PAGER_SYNCHRONOUS_OFF; /* sync flags for output db */ + u64 iRandom; /* Random value used for zDbVacuum[] */ + char zDbVacuum[42]; /* Name of the ATTACH-ed database used for vacuum */ + + + if( !db->autoCommit ){ + sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); + return SQLITE_ERROR; /* IMP: R-12218-18073 */ + } + if( db->nVdbeActive>1 ){ + sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); + return SQLITE_ERROR; /* IMP: R-15610-35227 */ + } + saved_openFlags = db->openFlags; + if( pOut ){ + if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){ + sqlite3SetString(pzErrMsg, db, "non-text filename"); + return SQLITE_ERROR; + } + zOut = (const char*)sqlite3_value_text(pOut); + db->openFlags &= ~SQLITE_OPEN_READONLY; + db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; + }else{ + zOut = ""; + } + + /* Save the current value of the database flags so that it can be + ** restored before returning. Then set the writable-schema flag, and + ** disable CHECK and foreign key constraints. */ + saved_flags = db->flags; + saved_mDbFlags = db->mDbFlags; + saved_nChange = db->nChange; + saved_nTotalChange = db->nTotalChange; + saved_mTrace = db->mTrace; + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_Comments; + db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum; + db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder + | SQLITE_Defensive | SQLITE_CountRows); + db->mTrace = 0; + + zDbMain = db->aDb[iDb].zDbSName; + pMain = db->aDb[iDb].pBt; + isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain)); + + /* Attach the temporary database as 'vacuum_XXXXXX'. The synchronous pragma + ** can be set to 'off' for this file, as it is not recovered if a crash + ** occurs anyway. The integrity of the database is maintained by a + ** (possibly synchronous) transaction opened on the main database before + ** sqlite3BtreeCopyFile() is called. + ** + ** An optimization would be to use a non-journaled pager. + ** (Later:) I tried setting "PRAGMA vacuum_XXXXXX.journal_mode=OFF" but + ** that actually made the VACUUM run slower. Very little journalling + ** actually occurs when doing a vacuum since the vacuum_db is initially + ** empty. Only the journal header is written. Apparently it takes more + ** time to parse and run the PRAGMA to turn journalling off than it does + ** to write the journal header file. + */ + sqlite3_randomness(sizeof(iRandom),&iRandom); + sqlite3_snprintf(sizeof(zDbVacuum), zDbVacuum, "vacuum_%016llx", iRandom); + nDb = db->nDb; + rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS %s", zOut, zDbVacuum); + db->openFlags = saved_openFlags; + if( rc!=SQLITE_OK ) goto end_of_vacuum; + assert( (db->nDb-1)==nDb ); + pDb = &db->aDb[nDb]; + assert( strcmp(pDb->zDbSName,zDbVacuum)==0 ); + pTemp = pDb->pBt; + if( pOut ){ + sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp)); + i64 sz = 0; + if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){ + rc = SQLITE_ERROR; + sqlite3SetString(pzErrMsg, db, "output file already exists"); + goto end_of_vacuum; + } + db->mDbFlags |= DBFLAG_VacuumInto; + + /* For a VACUUM INTO, the pager-flags are set to the same values as + ** they are for the database being vacuumed, except that PAGER_CACHESPILL + ** is always set. */ + pgflags = db->aDb[iDb].safety_level | (db->flags & PAGER_FLAGS_MASK); + } + + /* A VACUUM cannot change the pagesize of an encrypted database. */ + if( db->nextPagesize ){ + extern void sqlite3mcCodecGetKey(sqlite3*, int, void**, int*); + int nKey; + char *zKey; + sqlite3mcCodecGetKey(db, iDb, (void**)&zKey, &nKey); + if( nKey ) db->nextPagesize = 0; + } + + sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); + sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0)); + sqlite3BtreeSetPagerFlags(pTemp, pgflags|PAGER_CACHESPILL); + + /* Begin a transaction and take an exclusive lock on the main database + ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below, + ** to ensure that we do not try to change the page-size on a WAL database. + */ + rc = execSql(db, pzErrMsg, "BEGIN"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Do not attempt to change the page size for a WAL database */ + if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain)) + ==PAGER_JOURNALMODE_WAL + && pOut==0 + ){ + db->nextPagesize = 0; + } + + if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) + || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) + || NEVER(db->mallocFailed) + ){ + rc = SQLITE_NOMEM_BKPT; + goto end_of_vacuum; + } + +#ifndef SQLITE_OMIT_AUTOVACUUM + sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : + sqlite3BtreeGetAutoVacuum(pMain)); +#endif + + /* Query the schema of the main database. Create a mirror schema + ** in the temporary database. + */ + db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */ + rc = execSqlF(db, pzErrMsg, + "SELECT sql FROM \"%w\".sqlite_schema" + " WHERE type='table'AND name<>'sqlite_sequence'" + " AND coalesce(rootpage,1)>0", + zDbMain + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execSqlF(db, pzErrMsg, + "SELECT sql FROM \"%w\".sqlite_schema" + " WHERE type='index'", + zDbMain + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + db->init.iDb = 0; + + /* Loop through the tables in the main database. For each, do + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy + ** the contents to the temporary database. + */ + rc = execSqlF(db, pzErrMsg, + "SELECT'INSERT INTO %s.'||quote(name)" + "||' SELECT*FROM\"%w\".'||quote(name)" + "FROM %s.sqlite_schema " + "WHERE type='table'AND coalesce(rootpage,1)>0", + zDbVacuum, zDbMain, zDbVacuum + ); + assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 ); + db->mDbFlags &= ~DBFLAG_Vacuum; + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Copy the triggers, views, and virtual tables from the main database + ** over to the temporary database. None of these objects has any + ** associated storage, so all we have to do is copy their entries + ** from the schema table. + */ + rc = execSqlF(db, pzErrMsg, + "INSERT INTO %s.sqlite_schema" + " SELECT*FROM \"%w\".sqlite_schema" + " WHERE type IN('view','trigger')" + " OR(type='table'AND rootpage=0)", + zDbVacuum, zDbMain + ); + if( rc ) goto end_of_vacuum; + + /* At this point, there is a write transaction open on both the + ** vacuum database and the main database. Assuming no error occurs, + ** both transactions are closed by this block - the main database + ** transaction by sqlite3BtreeCopyFile() and the other by an explicit + ** call to sqlite3BtreeCommit(). + */ + { + u32 meta; + int i; + + /* This array determines which meta meta values are preserved in the + ** vacuum. Even entries are the meta value number and odd entries + ** are an increment to apply to the meta value after the vacuum. + ** The increment is used to increase the schema cookie so that other + ** connections to the same database will know to reread the schema. + */ + static const unsigned char aCopy[] = { + BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */ + BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */ + BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */ + BTREE_USER_VERSION, 0, /* Preserve the user version */ + BTREE_APPLICATION_ID, 0, /* Preserve the application id */ + }; + + assert( SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pTemp) ); + assert( pOut!=0 || SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pMain) ); + + /* Copy Btree meta values */ + for(i=0; iflags */ + db->init.iDb = 0; + db->mDbFlags = saved_mDbFlags; + db->flags = saved_flags; + db->nChange = saved_nChange; + db->nTotalChange = saved_nTotalChange; + db->mTrace = saved_mTrace; + sqlite3BtreeSetPageSize(pMain, -1, 0, 1); + + /* Currently there is an SQL level transaction open on the vacuum + ** database. No locks are held on any other files (since the main file + ** was committed at the btree level). So it safe to end the transaction + ** by manually setting the autoCommit flag to true and detaching the + ** vacuum database. The vacuum_db journal file is deleted when the pager + ** is closed by the DETACH. + */ + db->autoCommit = 1; + + if( pDb ){ + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + pDb->pSchema = 0; + } + + /* This both clears the schemas and reduces the size of the db->aDb[] + ** array. */ + sqlite3ResetAllSchemasOfConnection(db); + + return rc; +} +/*** End of #include "rekeyvacuum.c" ***/ + + +/* #include "cipher_common.h" */ + + +SQLITE_API void +sqlite3_activate_see(const char *info) +{ +} + +/* +** Free the encryption data structure associated with a pager instance. +** (called from the modified code in pager.c) +*/ +SQLITE_PRIVATE void +sqlite3mcCodecFree(void *pCodecArg) +{ + if (pCodecArg) + { + sqlite3mcCodecTerm(pCodecArg); + sqlite3_free(pCodecArg); + pCodecArg = NULL; + } +} + +SQLITE_PRIVATE void +sqlite3mcCodecSizeChange(void *pArg, int pageSize, int reservedSize) +{ + Codec* pCodec = (Codec*) pArg; + pCodec->m_pageSize = pageSize; + pCodec->m_reserved = reservedSize; +} + +static void +mcReportCodecError(BtShared* pBt, int error) +{ + pBt->db->errCode = error; + pBt->pPager->errCode = error; + if (error != SQLITE_OK) + { + pBt->pPager->eState = PAGER_ERROR; + } + if (error == SQLITE_OK) + { + /* Clear cache to force reread of database after a new passphrase has been set */ + sqlite3PagerClearCache(pBt->pPager); + /* unlock required? + pager_unlock(pBt->pPager); + */ + } + setGetterMethod(pBt->pPager); +} + +/* +// Encrypt/Decrypt functionality, called by pager.c +*/ +SQLITE_PRIVATE void* +sqlite3mcCodec(void* pCodecArg, void* data, Pgno nPageNum, int nMode) +{ + int rc = SQLITE_OK; + Codec* codec = NULL; + int pageSize; + if (pCodecArg == NULL) + { + return data; + } + codec = (Codec*) pCodecArg; + if (!sqlite3mcIsEncrypted(codec)) + { + sqlite3mcSetCodecLastError(codec, rc); + return data; + } + + pageSize = sqlite3mcGetPageSize(codec); + + switch(nMode) + { + case 0: /* Undo a "case 7" journal file encryption */ + case 2: /* Reload a page */ + case 3: /* Load a page */ + if (sqlite3mcHasReadCipher(codec)) + { + rc = sqlite3mcDecrypt(codec, nPageNum, (unsigned char*) data, pageSize); + if (rc != SQLITE_OK) + { + mcReportCodecError(sqlite3mcGetBtShared(codec), rc); + memset(data, 0, pageSize); + } + } + break; + + case 6: /* Encrypt a page for the main database file */ + if (sqlite3mcHasWriteCipher(codec)) + { + unsigned char* pageBuffer = sqlite3mcGetPageBuffer(codec); + memcpy(pageBuffer, data, pageSize); + data = pageBuffer; + rc = sqlite3mcEncrypt(codec, nPageNum, (unsigned char*) data, pageSize, 1); + if (rc != SQLITE_OK) mcReportCodecError(sqlite3mcGetBtShared(codec), rc); + } + break; + + case 7: /* Encrypt a page for the journal file */ + /* Under normal circumstances, the readkey is the same as the writekey. However, + when the database is being rekeyed, the readkey is not the same as the writekey. + The rollback journal must be written using the original key for the + database file because it is, by nature, a rollback journal. + Therefore, for case 7, when the rollback is being written, always encrypt using + the database's readkey, which is guaranteed to be the same key that was used to + read the original data. + */ + if (sqlite3mcHasReadCipher(codec)) + { + unsigned char* pageBuffer = sqlite3mcGetPageBuffer(codec); + memcpy(pageBuffer, data, pageSize); + data = pageBuffer; + rc = sqlite3mcEncrypt(codec, nPageNum, (unsigned char*) data, pageSize, 0); + if (rc != SQLITE_OK) mcReportCodecError(sqlite3mcGetBtShared(codec), rc); + } + break; + } + sqlite3mcSetCodecLastError(codec, rc); + return data; +} + +SQLITE_PRIVATE Codec* +sqlite3mcGetMainCodec(sqlite3* db); + +SQLITE_PRIVATE void +sqlite3mcSetCodec(sqlite3* db, const char* zDbName, const char* zFileName, Codec* codec); + +SQLITE_PRIVATE int +sqlite3mcIsEncryptionSupported(sqlite3* db, const char* zDbName); + +static int +mcAdjustBtree(Btree* pBt, int nPageSize, int nReserved, int isLegacy) +{ + int rc = SQLITE_OK; + Pager* pager = sqlite3BtreePager(pBt); + int pagesize = sqlite3BtreeGetPageSize(pBt); + sqlite3BtreeSecureDelete(pBt, 1); + if (nPageSize > 0) + { + pagesize = nPageSize; + } + + /* Adjust the page size and the reserved area */ + if (pager->pageSize != pagesize || pager->nReserve != nReserved) + { + int reserved = (nReserved >= 0) ? nReserved : 0; + if (isLegacy != 0) + { + pBt->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; + } + rc = sqlite3BtreeSetPageSize(pBt, pagesize, reserved, 0); + } + return rc; +} + +static int +sqlite3mcCodecAttach(sqlite3* db, int nDb, const char* zPath, const void* zKey, int nKey) +{ + /* Attach a key to a database. */ + const char* zDbName = db->aDb[nDb].zDbSName; + const char* dbFileName = sqlite3_db_filename(db, zDbName); + Codec* codec = (Codec*) sqlite3_malloc(sizeof(Codec)); + int rc = (codec != NULL) ? sqlite3mcCodecInit(codec) : SQLITE_NOMEM; + if (rc != SQLITE_OK) + { + /* Unable to allocate memory for the codec base structure */ + return rc; + } + + sqlite3_mutex_enter(db->mutex); + sqlite3mcSetDb(codec, db); + + /* No key specified, could mean either use the main db's encryption or no encryption */ + if (zKey == NULL || nKey <= 0) + { + /* No key specified */ + if (nDb != 0 && nKey > 0) + { + /* Main database possibly encrypted, no key explicitly given for attached database */ + Codec* mainCodec = sqlite3mcGetMainCodec(db); + /* Attached database, therefore use the key of main database, if main database is encrypted */ + if (mainCodec != NULL && sqlite3mcIsEncrypted(mainCodec)) + { + rc = sqlite3mcCodecCopy(codec, mainCodec); + if (rc == SQLITE_OK) + { + int pageSize = sqlite3mcGetPageSizeWriteCipher(codec); + int reserved = sqlite3mcGetReservedWriteCipher(codec); + sqlite3mcSetBtree(codec, db->aDb[nDb].pBt); + mcAdjustBtree(db->aDb[nDb].pBt, pageSize, reserved, sqlite3mcGetLegacyWriteCipher(codec)); + sqlite3mcCodecSizeChange(codec, pageSize, reserved); + sqlite3mcSetCodec(db, zDbName, dbFileName, codec); + } + else + { + /* Replicating main codec failed, do not attach incomplete codec */ + sqlite3mcCodecFree(codec); + } + } + else + { + /* Main database not encrypted */ + sqlite3mcCodecFree(codec); + } + } + else + { + /* Main database not encrypted, no key given for attached database */ + sqlite3mcCodecFree(codec); + /* Remove codec for main database */ + if (nDb == 0 && nKey == 0) + { + sqlite3mcSetCodec(db, zDbName, dbFileName, NULL); + } + } + } + else + { + if (dbFileName != NULL) + { + /* Check whether key salt is provided in URI */ + const unsigned char* cipherSalt = (const unsigned char*)sqlite3_uri_parameter(dbFileName, "cipher_salt"); + if ((cipherSalt != NULL) && (strlen((const char*)cipherSalt) >= 2 * KEYSALT_LENGTH) && sqlite3mcIsHexKey(cipherSalt, 2 * KEYSALT_LENGTH)) + { + codec->m_hasKeySalt = 1; + sqlite3mcConvertHex2Bin(cipherSalt, 2 * KEYSALT_LENGTH, codec->m_keySalt); + } + } + + /* Configure cipher from URI in case of attached database */ + if (nDb > 0) + { + rc = sqlite3mcConfigureFromUri(db, dbFileName, 0); + } + if (rc == SQLITE_OK) + { + /* Key specified, setup encryption key for database */ + sqlite3mcSetBtree(codec, db->aDb[nDb].pBt); + rc = sqlite3mcCodecSetup(codec, sqlite3mcGetCipherType(db), (char*) zKey, nKey); + sqlite3mcClearKeySalt(codec); + } + if (rc == SQLITE_OK) + { + int pageSize = sqlite3mcGetPageSizeWriteCipher(codec); + int reserved = sqlite3mcGetReservedWriteCipher(codec); + mcAdjustBtree(db->aDb[nDb].pBt, pageSize, reserved, sqlite3mcGetLegacyWriteCipher(codec)); + sqlite3mcCodecSizeChange(codec, pageSize, reserved); + sqlite3mcSetCodec(db, zDbName, dbFileName, codec); + } + else + { + /* Setting up codec failed, do not attach incomplete codec */ + sqlite3mcCodecFree(codec); + } + } + + sqlite3_mutex_leave(db->mutex); + + return rc; +} + +SQLITE_PRIVATE void +sqlite3mcCodecGetKey(sqlite3* db, int nDb, void** zKey, int* nKey) +{ + /* + ** The unencrypted password is not stored for security reasons + ** therefore always return NULL + ** If the main database is encrypted a key length of 1 is returned. + ** In that case an attached database will get the same encryption key + ** as the main database if no key was explicitly given for the attached database. + */ + Codec* codec = sqlite3mcGetCodec(db, db->aDb[nDb].zDbSName); + int keylen = (codec != NULL && sqlite3mcIsEncrypted(codec)) ? 1 : 0; + *zKey = NULL; + *nKey = keylen; +} + +SQLITE_API int +sqlite3_key(sqlite3 *db, const void *zKey, int nKey) +{ + /* The key is only set for the main database, not the temp database */ + return sqlite3_key_v2(db, "main", zKey, nKey); +} + +SQLITE_API int +sqlite3_key_v2(sqlite3* db, const char* zDbName, const void* zKey, int nKey) +{ + int rc = SQLITE_ERROR; + if (!sqlite3mcIsEncryptionSupported(db, zDbName)) + { + sqlite3ErrorWithMsg(db, rc, "Setting key failed. Encryption is not supported by the VFS."); + return rc; + } + if (zKey != NULL && nKey < 0) + { + /* Key is zero-terminated string */ + nKey = sqlite3Strlen30((const char*) zKey); + } + /* Database handle db and key must be given, but key length 0 is allowed */ + if ((db != NULL) && (zKey != NULL) && (nKey >= 0)) + { + int dbIndex; + const char* dbFileName = sqlite3_db_filename(db, zDbName); + if (dbFileName == NULL || dbFileName[0] == 0) + { + sqlite3ErrorWithMsg(db, rc, "Setting key not supported for in-memory or temporary databases."); + return rc; + } + /* Configure cipher from URI parameters if requested */ + void* codecParamTable = sqlite3_get_clientdata(db, globalConfigTableName); + if (codecParamTable == NULL) + { + /* + ** Encryption extension of database connection not yet initialized; + ** that is, sqlite3_key_v2 was called from the internal open function. + ** Therefore the URI should be checked for encryption configuration parameters. + */ + rc = sqlite3mcConfigureFromUri(db, dbFileName, 0); + } + + /* The key is only set for the main database, not the temp database */ + dbIndex = (zDbName) ? sqlite3FindDbName(db, zDbName) : 0; + if (dbIndex >= 0) + { + rc = sqlite3mcCodecAttach(db, dbIndex, dbFileName, zKey, nKey); + } + else + { + rc = SQLITE_ERROR; + sqlite3ErrorWithMsg(db, rc, "Setting key failed. Database '%s' not found.", zDbName); + } + } + return rc; +} + +SQLITE_API int +sqlite3_rekey_v2(sqlite3* db, const char* zDbName, const void* zKey, int nKey) +{ + /* Changes the encryption key for an existing database. */ + const char* dbFileName; + int dbIndex; + Btree* pBt; + int nPagesize; + int nReserved; + Pager* pPager; + Codec* codec; + int codecAllocated = 0; + int rc = SQLITE_ERROR; + char* err = NULL; + + if (!sqlite3mcIsEncryptionSupported(db, zDbName)) + { + sqlite3ErrorWithMsg(db, rc, "Rekeying failed. Encryption is not supported by the VFS."); + return rc; + } + if (zKey != NULL && nKey < 0) + { + /* Key is zero-terminated string */ + nKey = sqlite3Strlen30((const char*) zKey); + } + dbFileName = sqlite3_db_filename(db, zDbName); + dbIndex = (zDbName) ? sqlite3FindDbName(db, zDbName) : 0; + if (dbIndex < 0) + { + sqlite3ErrorWithMsg(db, rc, "Rekeying failed. Database '%s' not found.", zDbName); + return rc; + } + if (dbFileName == NULL || dbFileName[0] == 0) + { + sqlite3ErrorWithMsg(db, rc, "Rekeying not supported for in-memory or temporary databases."); + return rc; + } + pBt = db->aDb[dbIndex].pBt; + nPagesize = sqlite3BtreeGetPageSize(pBt); + + sqlite3BtreeEnter(pBt); + nReserved = sqlite3BtreeGetReserveNoMutex(pBt); + sqlite3BtreeLeave(pBt); + + pPager = sqlite3BtreePager(pBt); + codec = sqlite3mcGetCodec(db, zDbName); + + if (pagerUseWal(pPager)) + { + sqlite3ErrorWithMsg(db, rc, "Rekeying is not supported in WAL journal mode."); + return rc; + } + + if ((zKey == NULL || nKey == 0) && (codec == NULL || !sqlite3mcIsEncrypted(codec))) + { + /* Database not encrypted and key not specified, therefore do nothing */ + return SQLITE_OK; + } + + sqlite3_mutex_enter(db->mutex); + + if (codec == NULL || !sqlite3mcIsEncrypted(codec)) + { + /* Database not encrypted, but key specified, therefore encrypt database */ + if (codec == NULL) + { + codecAllocated = 1; + codec = (Codec*) sqlite3_malloc(sizeof(Codec)); + rc = (codec != NULL) ? sqlite3mcCodecInit(codec) : SQLITE_NOMEM; + } + if (rc == SQLITE_OK) + { + sqlite3mcSetDb(codec, db); + sqlite3mcSetBtree(codec, pBt); + rc = sqlite3mcSetupWriteCipher(codec, sqlite3mcGetCipherType(db), (char*) zKey, nKey); + } + if (rc == SQLITE_OK) + { + int nPagesizeWriteCipher = sqlite3mcGetPageSizeWriteCipher(codec); + if (nPagesizeWriteCipher <= 0 || nPagesize == nPagesizeWriteCipher) + { + int nReservedWriteCipher; + sqlite3mcSetHasReadCipher(codec, 0); /* Original database is not encrypted */ + mcAdjustBtree(pBt, sqlite3mcGetPageSizeWriteCipher(codec), sqlite3mcGetReservedWriteCipher(codec), sqlite3mcGetLegacyWriteCipher(codec)); + sqlite3mcSetCodec(db, zDbName, dbFileName, codec); + nReservedWriteCipher = sqlite3mcGetReservedWriteCipher(codec); + sqlite3mcCodecSizeChange(codec, nPagesize, nReservedWriteCipher); + if (nReserved != nReservedWriteCipher) + { + /* Use VACUUM to change the number of reserved bytes */ + sqlite3mcSetReadReserved(codec, nReserved); + sqlite3mcSetWriteReserved(codec, nReservedWriteCipher); + rc = sqlite3mcRunVacuumForRekey(&err, db, dbIndex, NULL, nReservedWriteCipher); + goto leave_rekey; + } + } + else + { + /* Pagesize cannot be changed for an encrypted database */ + rc = SQLITE_ERROR; + err = "Rekeying failed. Pagesize cannot be changed for an encrypted database."; + goto leave_rekey; + } + } + else + { + sqlite3_mutex_leave(db->mutex); + if (codecAllocated) + { + sqlite3mcCodecFree(codec); + } + return rc; + } + } + else if (zKey == NULL || nKey == 0) + { + /* Database encrypted, but key not specified, therefore decrypt database */ + /* Keep read key, drop write key */ + sqlite3mcSetHasWriteCipher(codec, 0); + if (nReserved > 0) + { + /* Use VACUUM to change the number of reserved bytes */ + err = NULL; + sqlite3mcSetReadReserved(codec, nReserved); + sqlite3mcSetWriteReserved(codec, 0); + rc = sqlite3mcRunVacuumForRekey(&err, db, dbIndex, NULL, 0); + goto leave_rekey; + } + } + else + { + /* Database encrypted and key specified, therefore re-encrypt database with new key */ + /* Keep read key, change write key to new key */ + rc = sqlite3mcSetupWriteCipher(codec, sqlite3mcGetCipherType(db), (char*) zKey, nKey); + if (rc == SQLITE_OK) + { + int nPagesizeWriteCipher = sqlite3mcGetPageSizeWriteCipher(codec); + if (nPagesizeWriteCipher <= 0 || nPagesize == nPagesizeWriteCipher) + { + int nReservedWriteCipher = sqlite3mcGetReservedWriteCipher(codec); + if (nReserved != nReservedWriteCipher) + { + /* Use VACUUM to change the number of reserved bytes */ + err = NULL; + sqlite3mcSetReadReserved(codec, nReserved); + sqlite3mcSetWriteReserved(codec, nReservedWriteCipher); + rc = sqlite3mcRunVacuumForRekey(&err, db, dbIndex, NULL, nReservedWriteCipher); + goto leave_rekey; + } + } + else + { + /* Pagesize cannot be changed for an encrypted database */ + rc = SQLITE_ERROR; + err = "Rekeying failed. Pagesize cannot be changed for an encrypted database."; + goto leave_rekey; + } + } + else + { + /* Setup of write cipher failed */ + err = "Rekeying failed. Setup of write cipher failed."; + goto leave_rekey; + } + } + + /* Start transaction */ + rc = sqlite3BtreeBeginTrans(pBt, 1, 0); + if (!rc) + { + int pageSize = sqlite3BtreeGetPageSize(pBt); + Pgno nSkip = WX_PAGER_MJ_PGNO(pageSize); + DbPage *pPage; + Pgno n; + /* Rewrite all pages using the new encryption key (if specified) */ + Pgno nPage; + int nPageCount = -1; + sqlite3PagerPagecount(pPager, &nPageCount); + nPage = nPageCount; + + for (n = 1; rc == SQLITE_OK && n <= nPage; n++) + { + if (n == nSkip) continue; + rc = sqlite3PagerGet(pPager, n, &pPage, 0); + if (!rc) + { + rc = sqlite3PagerWrite(pPage); + sqlite3PagerUnref(pPage); + } + } + } + + if (rc == SQLITE_OK) + { + /* Commit transaction if all pages could be rewritten */ + rc = sqlite3BtreeCommit(pBt); + } + if (rc != SQLITE_OK) + { + /* Rollback in case of error */ + sqlite3BtreeRollback(pBt, SQLITE_OK, 0); + } + +leave_rekey: + sqlite3_mutex_leave(db->mutex); + +/*leave_final:*/ + if (rc == SQLITE_OK) + { + /* Set read key equal to write key if necessary */ + if (sqlite3mcHasWriteCipher(codec)) + { + /* Set Read cipher equal to Write cipher */ + sqlite3mcCopyCipher(codec, 0); + sqlite3mcSetHasReadCipher(codec, 1); + + /* Enforce page size and number of reserved bytes per page */ + int pageSize = sqlite3mcGetPageSizeWriteCipher(codec); + int reserved = sqlite3mcGetReservedWriteCipher(codec); + mcAdjustBtree(pBt, pageSize, reserved, sqlite3mcGetLegacyWriteCipher(codec)); + sqlite3mcCodecSizeChange(codec, pageSize, reserved); + } + else + { + sqlite3mcSetIsEncrypted(codec, 0); + } + } + else + { + /* Restore write key if necessary */ + if (sqlite3mcHasReadCipher(codec)) + { + sqlite3mcCopyCipher(codec, 1); + } + else + { + sqlite3mcSetIsEncrypted(codec, 0); + } + } + /* Reset reserved for read and write key */ + sqlite3mcSetReadReserved(codec, -1); + sqlite3mcSetWriteReserved(codec, -1); + + if (!sqlite3mcIsEncrypted(codec)) + { + /* Remove codec for unencrypted database */ + sqlite3mcSetCodec(db, zDbName, dbFileName, NULL); + } + if (rc != SQLITE_OK && err != NULL) + { + sqlite3ErrorWithMsg(db, rc, err); + } + return rc; +} + +SQLITE_API int +sqlite3_rekey(sqlite3 *db, const void *zKey, int nKey) +{ + return sqlite3_rekey_v2(db, "main", zKey, nKey); +} +/*** End of #include "codecext.c" ***/ + + +/* +** Functions for securing allocated memory +*/ +/* #include "memory_secure.c" */ +/*** Begin of #include "memory_secure.c" ***/ +/* +** Name: mem_secure.c +** Purpose: Memory manager for SQLite3 Multiple Ciphers +** Author: Ulrich Telle +** Created: 2023-09-17 +** Copyright: (c) 2023 Ulrich Telle +** License: MIT +*/ + +/* For memset, memset_s */ +#include + +#ifdef _WIN32 +/* For SecureZeroMemory */ +#include +#include +#endif + +SQLITE_PRIVATE void sqlite3mcSecureZeroMemory(void* v, size_t n) +{ +#ifdef _WIN32 + SecureZeroMemory(v, n); +#elif defined(__DARWIN__) || defined(__STDC_LIB_EXT1__) + /* memset_s() is available since OS X 10.9, */ + /* and may be available on other platforms. */ + memset_s(v, n, 0, n); +#elif defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ >= 11) + /* Non-standard function */ + explicit_bzero(v, n); +#else + /* Generic implementation based on volatile pointers */ + static void* (* const volatile memset_sec)(void*, int, size_t) = &memset; + memset_sec(v, 0, n); +#endif +} + +#if SQLITE3MC_SECURE_MEMORY + +/* Flag indicating whether securing memory allocations is initialized */ +static volatile int mcSecureMemoryInitialized = 0; +/* Flag indicating whether memory allocations will be secured */ +static volatile int mcSecureMemoryFlag = 0; + +/* Map of default memory allocation methods */ +static volatile sqlite3_mem_methods mcDefaultMemoryMethods; + +/* +** Return the size of an allocation +*/ +static int mcMemorySize(void* pBuf) +{ + return mcDefaultMemoryMethods.xSize(pBuf); +} + +/* +** Memory allocation function +*/ +static void* mcMemoryAlloc(int nByte) +{ + return mcDefaultMemoryMethods.xMalloc(nByte); +} + +/* +** Free a prior allocation +*/ +static void mcMemoryFree(void* pPrior) +{ + if (mcSecureMemoryFlag) + { + int nSize = mcMemorySize(pPrior); + sqlite3mcSecureZeroMemory(pPrior, 0, nSize); + } + mcDefaultMemoryMethods.xFree(pPrior); +} + +/* +** Resize an allocation +*/ +static void* mcMemoryRealloc(void* pPrior, int nByte) +{ + void* pNew = NULL; + if (mcSecureMemoryFlag) + { + int nPriorSize = mcMemorySize(pPrior); + if (nByte == 0) + { + /* New size = 0, just free prior memory */ + mcMemoryFree(pPrior); + return NULL; + } + else if (!pPrior) + { + /* Prior size = 0, just allocate new memory */ + return mcMemoryAlloc(nByte); + } + else if(nByte <= nPriorSize) + { + /* New size less or equal prior size, do nothing - we do not shrink allocations */ + return pPrior; + } + else + { + /* New size greater than prior size, reallocate memory */ + pNew = mcMemoryAlloc(nByte); + if (pNew) + { + memcpy(pNew, pPrior, nPriorSize); + mcMemoryFree(pPrior); + } + return pNew; + } + } + else + { + return mcDefaultMemoryMethods.xRealloc(pPrior, nByte); + } +} + +/* +** Round up request size to allocation size +*/ +static int mcMemoryRoundup(int nByte) +{ + return mcDefaultMemoryMethods.xRoundup(nByte); +} + +/* +** Initialize the memory allocator +*/ +static int mcMemoryInit(void* pAppData) +{ + return mcDefaultMemoryMethods.xInit(pAppData); +} + +/* +** Deinitialize the memory allocator +*/ +static void mcMemoryShutdown(void* pAppData) +{ + mcDefaultMemoryMethods.xShutdown(pAppData); +} + +static sqlite3_mem_methods mcSecureMemoryMethods = +{ + mcMemoryAlloc, + mcMemoryFree, + mcMemoryRealloc, + mcMemorySize, + mcMemoryRoundup, + mcMemoryInit, + mcMemoryShutdown, + 0 +}; + +SQLITE_PRIVATE void sqlite3mcSetMemorySecurity(int value) +{ + /* memory security can be changed only, if locking is not enabled */ + if (mcSecureMemoryFlag < 2) + { + mcSecureMemoryFlag = (value >= 0 && value <= 2) ? value : 0; + } +} + +SQLITE_PRIVATE int sqlite3mcGetMemorySecurity() +{ + return mcSecureMemoryFlag; +} + +#endif /* SQLITE3MC_SECURE_MEMORY */ + +SQLITE_PRIVATE void sqlite3mcInitMemoryMethods() +{ +#if SQLITE3MC_SECURE_MEMORY + if (!mcSecureMemoryInitialized) + { + if (sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mcDefaultMemoryMethods) != SQLITE_OK || + sqlite3_config(SQLITE_CONFIG_MALLOC, &mcSecureMemoryMethods) != SQLITE_OK) + { + mcSecureMemoryFlag = mcSecureMemoryInitialized = 0; + } + else + { + mcSecureMemoryInitialized = 1; + } + } +#endif /* SQLITE3MC_SECURE_MEMORY */ +} + +/*** End of #include "memory_secure.c" ***/ + + +/* +** Extension functions +*/ +#ifdef SQLITE_ENABLE_EXTFUNC +/* Prototype for initialization function of EXTENSIONFUNCTIONS extension */ +int RegisterExtensionFunctions(sqlite3* db); +/* #include "extensionfunctions.c" */ +/*** Begin of #include "extensionfunctions.c" ***/ +/* +This library will provide common mathematical and string functions in +SQL queries using the operating system libraries or provided +definitions. It includes the following functions: + +Math: acos, asin, atan, atn2, atan2, acosh, asinh, atanh, difference, +degrees, radians, cos, sin, tan, cot, cosh, sinh, tanh, coth, exp, +log, log10, power, sign, sqrt, square, ceil, floor, pi. + +String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim, +replace, reverse, proper, padl, padr, padc, strfilter. + +Aggregate: stdev, variance, mode, median, lower_quartile, +upper_quartile. + +The string functions ltrim, rtrim, trim, replace are included in +recent versions of SQLite and so by default do not build. + +Compilation instructions: + Compile this C source file into a dynamic library as follows: + * Linux: + gcc -fPIC -lm -shared extension-functions.c -o libsqlitefunctions.so + * Mac OS X: + gcc -fno-common -dynamiclib extension-functions.c -o libsqlitefunctions.dylib + (You may need to add flags + -I /opt/local/include/ -L/opt/local/lib -lsqlite3 + if your sqlite3 is installed from Mac ports, or + -I /sw/include/ -L/sw/lib -lsqlite3 + if installed with Fink.) + * Windows: + 1. Install MinGW (http://www.mingw.org/) and you will get the gcc + (gnu compiler collection) + 2. add the path to your path variable (isn't done during the + installation!) + 3. compile: + gcc -shared -I "path" -o libsqlitefunctions.so extension-functions.c + (path = path of sqlite3ext.h; i.e. C:\programs\sqlite) + +Usage instructions for applications calling the sqlite3 API functions: + In your application, call sqlite3_enable_load_extension(db,1) to + allow loading external libraries. Then load the library libsqlitefunctions + using sqlite3_load_extension; the third argument should be 0. + See http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions. + Select statements may now use these functions, as in + SELECT cos(radians(inclination)) FROM satsum WHERE satnum = 25544; + +Usage instructions for the sqlite3 program: + If the program is built so that loading extensions is permitted, + the following will work: + sqlite> SELECT load_extension('./libsqlitefunctions.so'); + sqlite> select cos(radians(45)); + 0.707106781186548 + Note: Loading extensions is by default prohibited as a + security measure; see "Security Considerations" in + http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions. + If the sqlite3 program and library are built this + way, you cannot use these functions from the program, you + must write your own program using the sqlite3 API, and call + sqlite3_enable_load_extension as described above, or else + rebuilt the sqlite3 program to allow loadable extensions. + +Alterations: +The instructions are for Linux, Mac OS X, and Windows; users of other +OSes may need to modify this procedure. In particular, if your math +library lacks one or more of the needed trig or log functions, comment +out the appropriate HAVE_ #define at the top of file. If you do not +wish to make a loadable module, comment out the define for +COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE. If you are using a +version of SQLite without the trim functions and replace, comment out +the HAVE_TRIM #define. + +Liam Healy + +History: +2021-01-05 Disable math functions that are provided by the SQLite Math Extension since version 3.35.0 +2010-01-06 Correct check for argc in squareFunc, and add Windows +compilation instructions. +2009-06-24 Correct check for argc in properFunc. +2008-09-14 Add check that memory was actually allocated after +sqlite3_malloc or sqlite3StrDup, call sqlite3_result_error_nomem if +not. Thanks to Robert Simpson. +2008-06-13 Change to instructions to indicate use of the math library +and that program might work. +2007-10-01 Minor clarification to instructions. +2007-09-29 Compilation as loadable module is optional with +COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE. +2007-09-28 Use sqlite3_extension_init and macros +SQLITE_EXTENSION_INIT1, SQLITE_EXTENSION_INIT2, so that it works with +sqlite3_load_extension. Thanks to Eric Higashino and Joe Wilson. +New instructions for Mac compilation. +2007-09-17 With help from Joe Wilson and Nuno Luca, made use of +external interfaces so that compilation is no longer dependent on +SQLite source code. Merged source, header, and README into a single +file. Added casts so that Mac will compile without warnings (unsigned +and signed char). +2007-09-05 Included some definitions from sqlite 3.3.13 so that this +will continue to work in newer versions of sqlite. Completed +description of functions available. +2007-03-27 Revised description. +2007-03-23 Small cleanup and a bug fix on the code. This was mainly +letting errno flag errors encountered in the math library and checking +the result, rather than pre-checking. This fixes a bug in power that +would cause an error if any non-positive number was raised to any +power. +2007-02-07 posted by Mikey C to sqlite mailing list. +Original code 2006 June 05 by relicoder. + +*/ + +/* #include "config.h" */ + +/* #define COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE 1 */ +#if defined(_MSC_VER) && _MSC_VER <= 1700 +#else +#define HAVE_ACOSH 1 +#define HAVE_ASINH 1 +#define HAVE_ATANH 1 +#endif +#define HAVE_SINH 1 +#define HAVE_COSH 1 +#define HAVE_TANH 1 +#define HAVE_LOG10 1 +#if defined(_MSC_VER) && _MSC_VER <= 1700 +#else +#define HAVE_ISBLANK 1 +#endif +#define SQLITE_SOUNDEX 1 +#define HAVE_TRIM 1 /* LMH 2007-03-25 if sqlite has trim functions */ + +#ifdef COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE +/* #include "sqlite3ext.h" */ +/*** Begin of #include "sqlite3ext.h" ***/ +/* +** 2006 June 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the SQLite interface for use by +** shared libraries that want to be imported as extensions into +** an SQLite instance. Shared libraries that intend to be loaded +** as extensions by SQLite should #include this file instead of +** sqlite3.h. +*/ +#ifndef SQLITE3EXT_H +#define SQLITE3EXT_H +/* #include "sqlite3.h" */ + + +/* +** The following structure holds pointers to all of the SQLite API +** routines. +** +** WARNING: In order to maintain backwards compatibility, add new +** interfaces to the end of this structure only. If you insert new +** interfaces in the middle of this structure, then older different +** versions of SQLite will not be able to load each other's shared +** libraries! +*/ +struct sqlite3_api_routines { + void * (*aggregate_context)(sqlite3_context*,int nBytes); + int (*aggregate_count)(sqlite3_context*); + int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); + int (*bind_double)(sqlite3_stmt*,int,double); + int (*bind_int)(sqlite3_stmt*,int,int); + int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); + int (*bind_null)(sqlite3_stmt*,int); + int (*bind_parameter_count)(sqlite3_stmt*); + int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); + const char * (*bind_parameter_name)(sqlite3_stmt*,int); + int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); + int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); + int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); + int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); + int (*busy_timeout)(sqlite3*,int ms); + int (*changes)(sqlite3*); + int (*close)(sqlite3*); + int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const char*)); + int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, + int eTextRep,const void*)); + const void * (*column_blob)(sqlite3_stmt*,int iCol); + int (*column_bytes)(sqlite3_stmt*,int iCol); + int (*column_bytes16)(sqlite3_stmt*,int iCol); + int (*column_count)(sqlite3_stmt*pStmt); + const char * (*column_database_name)(sqlite3_stmt*,int); + const void * (*column_database_name16)(sqlite3_stmt*,int); + const char * (*column_decltype)(sqlite3_stmt*,int i); + const void * (*column_decltype16)(sqlite3_stmt*,int); + double (*column_double)(sqlite3_stmt*,int iCol); + int (*column_int)(sqlite3_stmt*,int iCol); + sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); + const char * (*column_name)(sqlite3_stmt*,int); + const void * (*column_name16)(sqlite3_stmt*,int); + const char * (*column_origin_name)(sqlite3_stmt*,int); + const void * (*column_origin_name16)(sqlite3_stmt*,int); + const char * (*column_table_name)(sqlite3_stmt*,int); + const void * (*column_table_name16)(sqlite3_stmt*,int); + const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); + const void * (*column_text16)(sqlite3_stmt*,int iCol); + int (*column_type)(sqlite3_stmt*,int iCol); + sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); + void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + int (*complete)(const char*sql); + int (*complete16)(const void*sql); + int (*create_collation)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_collation16)(sqlite3*,const void*,int,void*, + int(*)(void*,int,const void*,int,const void*)); + int (*create_function)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_function16)(sqlite3*,const void*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*)); + int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); + int (*data_count)(sqlite3_stmt*pStmt); + sqlite3 * (*db_handle)(sqlite3_stmt*); + int (*declare_vtab)(sqlite3*,const char*); + int (*enable_shared_cache)(int); + int (*errcode)(sqlite3*db); + const char * (*errmsg)(sqlite3*); + const void * (*errmsg16)(sqlite3*); + int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); + int (*expired)(sqlite3_stmt*); + int (*finalize)(sqlite3_stmt*pStmt); + void (*free)(void*); + void (*free_table)(char**result); + int (*get_autocommit)(sqlite3*); + void * (*get_auxdata)(sqlite3_context*,int); + int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + int (*global_recover)(void); + void (*interruptx)(sqlite3*); + sqlite_int64 (*last_insert_rowid)(sqlite3*); + const char * (*libversion)(void); + int (*libversion_number)(void); + void *(*malloc)(int); + char * (*mprintf)(const char*,...); + int (*open)(const char*,sqlite3**); + int (*open16)(const void*,sqlite3**); + int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); + void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + void *(*realloc)(void*,int); + int (*reset)(sqlite3_stmt*pStmt); + void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_double)(sqlite3_context*,double); + void (*result_error)(sqlite3_context*,const char*,int); + void (*result_error16)(sqlite3_context*,const void*,int); + void (*result_int)(sqlite3_context*,int); + void (*result_int64)(sqlite3_context*,sqlite_int64); + void (*result_null)(sqlite3_context*); + void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); + void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_value)(sqlite3_context*,sqlite3_value*); + void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, + const char*,const char*),void*); + void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); + char * (*xsnprintf)(int,char*,const char*,...); + int (*step)(sqlite3_stmt*); + int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, + char const**,char const**,int*,int*,int*); + void (*thread_cleanup)(void); + int (*total_changes)(sqlite3*); + void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); + int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); + void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, + sqlite_int64),void*); + void * (*user_data)(sqlite3_context*); + const void * (*value_blob)(sqlite3_value*); + int (*value_bytes)(sqlite3_value*); + int (*value_bytes16)(sqlite3_value*); + double (*value_double)(sqlite3_value*); + int (*value_int)(sqlite3_value*); + sqlite_int64 (*value_int64)(sqlite3_value*); + int (*value_numeric_type)(sqlite3_value*); + const unsigned char * (*value_text)(sqlite3_value*); + const void * (*value_text16)(sqlite3_value*); + const void * (*value_text16be)(sqlite3_value*); + const void * (*value_text16le)(sqlite3_value*); + int (*value_type)(sqlite3_value*); + char *(*vmprintf)(const char*,va_list); + /* Added ??? */ + int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + /* Added by 3.3.13 */ + int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + int (*clear_bindings)(sqlite3_stmt*); + /* Added by 3.4.1 */ + int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, + void (*xDestroy)(void *)); + /* Added by 3.5.0 */ + int (*bind_zeroblob)(sqlite3_stmt*,int,int); + int (*blob_bytes)(sqlite3_blob*); + int (*blob_close)(sqlite3_blob*); + int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, + int,sqlite3_blob**); + int (*blob_read)(sqlite3_blob*,void*,int,int); + int (*blob_write)(sqlite3_blob*,const void*,int,int); + int (*create_collation_v2)(sqlite3*,const char*,int,void*, + int(*)(void*,int,const void*,int,const void*), + void(*)(void*)); + int (*file_control)(sqlite3*,const char*,int,void*); + sqlite3_int64 (*memory_highwater)(int); + sqlite3_int64 (*memory_used)(void); + sqlite3_mutex *(*mutex_alloc)(int); + void (*mutex_enter)(sqlite3_mutex*); + void (*mutex_free)(sqlite3_mutex*); + void (*mutex_leave)(sqlite3_mutex*); + int (*mutex_try)(sqlite3_mutex*); + int (*open_v2)(const char*,sqlite3**,int,const char*); + int (*release_memory)(int); + void (*result_error_nomem)(sqlite3_context*); + void (*result_error_toobig)(sqlite3_context*); + int (*sleep)(int); + void (*soft_heap_limit)(int); + sqlite3_vfs *(*vfs_find)(const char*); + int (*vfs_register)(sqlite3_vfs*,int); + int (*vfs_unregister)(sqlite3_vfs*); + int (*xthreadsafe)(void); + void (*result_zeroblob)(sqlite3_context*,int); + void (*result_error_code)(sqlite3_context*,int); + int (*test_control)(int, ...); + void (*randomness)(int,void*); + sqlite3 *(*context_db_handle)(sqlite3_context*); + int (*extended_result_codes)(sqlite3*,int); + int (*limit)(sqlite3*,int,int); + sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); + const char *(*sql)(sqlite3_stmt*); + int (*status)(int,int*,int*,int); + int (*backup_finish)(sqlite3_backup*); + sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); + int (*backup_pagecount)(sqlite3_backup*); + int (*backup_remaining)(sqlite3_backup*); + int (*backup_step)(sqlite3_backup*,int); + const char *(*compileoption_get)(int); + int (*compileoption_used)(const char*); + int (*create_function_v2)(sqlite3*,const char*,int,int,void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*)); + int (*db_config)(sqlite3*,int,...); + sqlite3_mutex *(*db_mutex)(sqlite3*); + int (*db_status)(sqlite3*,int,int*,int*,int); + int (*extended_errcode)(sqlite3*); + void (*log)(int,const char*,...); + sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); + const char *(*sourceid)(void); + int (*stmt_status)(sqlite3_stmt*,int,int); + int (*strnicmp)(const char*,const char*,int); + int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); + int (*wal_autocheckpoint)(sqlite3*,int); + int (*wal_checkpoint)(sqlite3*,const char*); + void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); + int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); + int (*vtab_config)(sqlite3*,int op,...); + int (*vtab_on_conflict)(sqlite3*); + /* Version 3.7.16 and later */ + int (*close_v2)(sqlite3*); + const char *(*db_filename)(sqlite3*,const char*); + int (*db_readonly)(sqlite3*,const char*); + int (*db_release_memory)(sqlite3*); + const char *(*errstr)(int); + int (*stmt_busy)(sqlite3_stmt*); + int (*stmt_readonly)(sqlite3_stmt*); + int (*stricmp)(const char*,const char*); + int (*uri_boolean)(const char*,const char*,int); + sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); + const char *(*uri_parameter)(const char*,const char*); + char *(*xvsnprintf)(int,char*,const char*,va_list); + int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); + /* Version 3.8.7 and later */ + int (*auto_extension)(void(*)(void)); + int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, + void(*)(void*)); + int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, + void(*)(void*),unsigned char); + int (*cancel_auto_extension)(void(*)(void)); + int (*load_extension)(sqlite3*,const char*,const char*,char**); + void *(*malloc64)(sqlite3_uint64); + sqlite3_uint64 (*msize)(void*); + void *(*realloc64)(void*,sqlite3_uint64); + void (*reset_auto_extension)(void); + void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, + void(*)(void*)); + void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, + void(*)(void*), unsigned char); + int (*strglob)(const char*,const char*); + /* Version 3.8.11 and later */ + sqlite3_value *(*value_dup)(const sqlite3_value*); + void (*value_free)(sqlite3_value*); + int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); + int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); + /* Version 3.9.0 and later */ + unsigned int (*value_subtype)(sqlite3_value*); + void (*result_subtype)(sqlite3_context*,unsigned int); + /* Version 3.10.0 and later */ + int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); + int (*strlike)(const char*,const char*,unsigned int); + int (*db_cacheflush)(sqlite3*); + /* Version 3.12.0 and later */ + int (*system_errno)(sqlite3*); + /* Version 3.14.0 and later */ + int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); + char *(*expanded_sql)(sqlite3_stmt*); + /* Version 3.18.0 and later */ + void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64); + /* Version 3.20.0 and later */ + int (*prepare_v3)(sqlite3*,const char*,int,unsigned int, + sqlite3_stmt**,const char**); + int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int, + sqlite3_stmt**,const void**); + int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*)); + void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*)); + void *(*value_pointer)(sqlite3_value*,const char*); + int (*vtab_nochange)(sqlite3_context*); + int (*value_nochange)(sqlite3_value*); + const char *(*vtab_collation)(sqlite3_index_info*,int); + /* Version 3.24.0 and later */ + int (*keyword_count)(void); + int (*keyword_name)(int,const char**,int*); + int (*keyword_check)(const char*,int); + sqlite3_str *(*str_new)(sqlite3*); + char *(*str_finish)(sqlite3_str*); + void (*str_appendf)(sqlite3_str*, const char *zFormat, ...); + void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list); + void (*str_append)(sqlite3_str*, const char *zIn, int N); + void (*str_appendall)(sqlite3_str*, const char *zIn); + void (*str_appendchar)(sqlite3_str*, int N, char C); + void (*str_reset)(sqlite3_str*); + int (*str_errcode)(sqlite3_str*); + int (*str_length)(sqlite3_str*); + char *(*str_value)(sqlite3_str*); + /* Version 3.25.0 and later */ + int (*create_window_function)(sqlite3*,const char*,int,int,void*, + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void (*xValue)(sqlite3_context*), + void (*xInv)(sqlite3_context*,int,sqlite3_value**), + void(*xDestroy)(void*)); + /* Version 3.26.0 and later */ + const char *(*normalized_sql)(sqlite3_stmt*); + /* Version 3.28.0 and later */ + int (*stmt_isexplain)(sqlite3_stmt*); + int (*value_frombind)(sqlite3_value*); + /* Version 3.30.0 and later */ + int (*drop_modules)(sqlite3*,const char**); + /* Version 3.31.0 and later */ + sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64); + const char *(*uri_key)(const char*,int); + const char *(*filename_database)(const char*); + const char *(*filename_journal)(const char*); + const char *(*filename_wal)(const char*); + /* Version 3.32.0 and later */ + const char *(*create_filename)(const char*,const char*,const char*, + int,const char**); + void (*free_filename)(const char*); + sqlite3_file *(*database_file_object)(const char*); + /* Version 3.34.0 and later */ + int (*txn_state)(sqlite3*,const char*); + /* Version 3.36.1 and later */ + sqlite3_int64 (*changes64)(sqlite3*); + sqlite3_int64 (*total_changes64)(sqlite3*); + /* Version 3.37.0 and later */ + int (*autovacuum_pages)(sqlite3*, + unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int), + void*, void(*)(void*)); + /* Version 3.38.0 and later */ + int (*error_offset)(sqlite3*); + int (*vtab_rhs_value)(sqlite3_index_info*,int,sqlite3_value**); + int (*vtab_distinct)(sqlite3_index_info*); + int (*vtab_in)(sqlite3_index_info*,int,int); + int (*vtab_in_first)(sqlite3_value*,sqlite3_value**); + int (*vtab_in_next)(sqlite3_value*,sqlite3_value**); + /* Version 3.39.0 and later */ + int (*deserialize)(sqlite3*,const char*,unsigned char*, + sqlite3_int64,sqlite3_int64,unsigned); + unsigned char *(*serialize)(sqlite3*,const char *,sqlite3_int64*, + unsigned int); + const char *(*db_name)(sqlite3*,int); + /* Version 3.40.0 and later */ + int (*value_encoding)(sqlite3_value*); + /* Version 3.41.0 and later */ + int (*is_interrupted)(sqlite3*); + /* Version 3.43.0 and later */ + int (*stmt_explain)(sqlite3_stmt*,int); + /* Version 3.44.0 and later */ + void *(*get_clientdata)(sqlite3*,const char*); + int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*)); + /* Version 3.50.0 and later */ + int (*setlk_timeout)(sqlite3*,int,int); +}; + +/* +** This is the function signature used for all extension entry points. It +** is also defined in the file "loadext.c". +*/ +typedef int (*sqlite3_loadext_entry)( + sqlite3 *db, /* Handle to the database. */ + char **pzErrMsg, /* Used to set error string on failure. */ + const sqlite3_api_routines *pThunk /* Extension API function pointers. */ +); + +/* +** The following macros redefine the API routines so that they are +** redirected through the global sqlite3_api structure. +** +** This header file is also used by the loadext.c source file +** (part of the main SQLite library - not an extension) so that +** it can get access to the sqlite3_api_routines structure +** definition. But the main library does not want to redefine +** the API. So the redefinition macros are only valid if the +** SQLITE_CORE macros is undefined. +*/ +#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) +#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_aggregate_count sqlite3_api->aggregate_count +#endif +#define sqlite3_bind_blob sqlite3_api->bind_blob +#define sqlite3_bind_double sqlite3_api->bind_double +#define sqlite3_bind_int sqlite3_api->bind_int +#define sqlite3_bind_int64 sqlite3_api->bind_int64 +#define sqlite3_bind_null sqlite3_api->bind_null +#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count +#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index +#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name +#define sqlite3_bind_text sqlite3_api->bind_text +#define sqlite3_bind_text16 sqlite3_api->bind_text16 +#define sqlite3_bind_value sqlite3_api->bind_value +#define sqlite3_busy_handler sqlite3_api->busy_handler +#define sqlite3_busy_timeout sqlite3_api->busy_timeout +#define sqlite3_changes sqlite3_api->changes +#define sqlite3_close sqlite3_api->close +#define sqlite3_collation_needed sqlite3_api->collation_needed +#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 +#define sqlite3_column_blob sqlite3_api->column_blob +#define sqlite3_column_bytes sqlite3_api->column_bytes +#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 +#define sqlite3_column_count sqlite3_api->column_count +#define sqlite3_column_database_name sqlite3_api->column_database_name +#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 +#define sqlite3_column_decltype sqlite3_api->column_decltype +#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 +#define sqlite3_column_double sqlite3_api->column_double +#define sqlite3_column_int sqlite3_api->column_int +#define sqlite3_column_int64 sqlite3_api->column_int64 +#define sqlite3_column_name sqlite3_api->column_name +#define sqlite3_column_name16 sqlite3_api->column_name16 +#define sqlite3_column_origin_name sqlite3_api->column_origin_name +#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 +#define sqlite3_column_table_name sqlite3_api->column_table_name +#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 +#define sqlite3_column_text sqlite3_api->column_text +#define sqlite3_column_text16 sqlite3_api->column_text16 +#define sqlite3_column_type sqlite3_api->column_type +#define sqlite3_column_value sqlite3_api->column_value +#define sqlite3_commit_hook sqlite3_api->commit_hook +#define sqlite3_complete sqlite3_api->complete +#define sqlite3_complete16 sqlite3_api->complete16 +#define sqlite3_create_collation sqlite3_api->create_collation +#define sqlite3_create_collation16 sqlite3_api->create_collation16 +#define sqlite3_create_function sqlite3_api->create_function +#define sqlite3_create_function16 sqlite3_api->create_function16 +#define sqlite3_create_module sqlite3_api->create_module +#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 +#define sqlite3_data_count sqlite3_api->data_count +#define sqlite3_db_handle sqlite3_api->db_handle +#define sqlite3_declare_vtab sqlite3_api->declare_vtab +#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache +#define sqlite3_errcode sqlite3_api->errcode +#define sqlite3_errmsg sqlite3_api->errmsg +#define sqlite3_errmsg16 sqlite3_api->errmsg16 +#define sqlite3_exec sqlite3_api->exec +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_expired sqlite3_api->expired +#endif +#define sqlite3_finalize sqlite3_api->finalize +#define sqlite3_free sqlite3_api->free +#define sqlite3_free_table sqlite3_api->free_table +#define sqlite3_get_autocommit sqlite3_api->get_autocommit +#define sqlite3_get_auxdata sqlite3_api->get_auxdata +#define sqlite3_get_table sqlite3_api->get_table +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_global_recover sqlite3_api->global_recover +#endif +#define sqlite3_interrupt sqlite3_api->interruptx +#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid +#define sqlite3_libversion sqlite3_api->libversion +#define sqlite3_libversion_number sqlite3_api->libversion_number +#define sqlite3_malloc sqlite3_api->malloc +#define sqlite3_mprintf sqlite3_api->mprintf +#define sqlite3_open sqlite3_api->open +#define sqlite3_open16 sqlite3_api->open16 +#define sqlite3_prepare sqlite3_api->prepare +#define sqlite3_prepare16 sqlite3_api->prepare16 +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_profile sqlite3_api->profile +#define sqlite3_progress_handler sqlite3_api->progress_handler +#define sqlite3_realloc sqlite3_api->realloc +#define sqlite3_reset sqlite3_api->reset +#define sqlite3_result_blob sqlite3_api->result_blob +#define sqlite3_result_double sqlite3_api->result_double +#define sqlite3_result_error sqlite3_api->result_error +#define sqlite3_result_error16 sqlite3_api->result_error16 +#define sqlite3_result_int sqlite3_api->result_int +#define sqlite3_result_int64 sqlite3_api->result_int64 +#define sqlite3_result_null sqlite3_api->result_null +#define sqlite3_result_text sqlite3_api->result_text +#define sqlite3_result_text16 sqlite3_api->result_text16 +#define sqlite3_result_text16be sqlite3_api->result_text16be +#define sqlite3_result_text16le sqlite3_api->result_text16le +#define sqlite3_result_value sqlite3_api->result_value +#define sqlite3_rollback_hook sqlite3_api->rollback_hook +#define sqlite3_set_authorizer sqlite3_api->set_authorizer +#define sqlite3_set_auxdata sqlite3_api->set_auxdata +#define sqlite3_snprintf sqlite3_api->xsnprintf +#define sqlite3_step sqlite3_api->step +#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata +#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup +#define sqlite3_total_changes sqlite3_api->total_changes +#define sqlite3_trace sqlite3_api->trace +#ifndef SQLITE_OMIT_DEPRECATED +#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings +#endif +#define sqlite3_update_hook sqlite3_api->update_hook +#define sqlite3_user_data sqlite3_api->user_data +#define sqlite3_value_blob sqlite3_api->value_blob +#define sqlite3_value_bytes sqlite3_api->value_bytes +#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 +#define sqlite3_value_double sqlite3_api->value_double +#define sqlite3_value_int sqlite3_api->value_int +#define sqlite3_value_int64 sqlite3_api->value_int64 +#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type +#define sqlite3_value_text sqlite3_api->value_text +#define sqlite3_value_text16 sqlite3_api->value_text16 +#define sqlite3_value_text16be sqlite3_api->value_text16be +#define sqlite3_value_text16le sqlite3_api->value_text16le +#define sqlite3_value_type sqlite3_api->value_type +#define sqlite3_vmprintf sqlite3_api->vmprintf +#define sqlite3_vsnprintf sqlite3_api->xvsnprintf +#define sqlite3_overload_function sqlite3_api->overload_function +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_clear_bindings sqlite3_api->clear_bindings +#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob +#define sqlite3_blob_bytes sqlite3_api->blob_bytes +#define sqlite3_blob_close sqlite3_api->blob_close +#define sqlite3_blob_open sqlite3_api->blob_open +#define sqlite3_blob_read sqlite3_api->blob_read +#define sqlite3_blob_write sqlite3_api->blob_write +#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 +#define sqlite3_file_control sqlite3_api->file_control +#define sqlite3_memory_highwater sqlite3_api->memory_highwater +#define sqlite3_memory_used sqlite3_api->memory_used +#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc +#define sqlite3_mutex_enter sqlite3_api->mutex_enter +#define sqlite3_mutex_free sqlite3_api->mutex_free +#define sqlite3_mutex_leave sqlite3_api->mutex_leave +#define sqlite3_mutex_try sqlite3_api->mutex_try +#define sqlite3_open_v2 sqlite3_api->open_v2 +#define sqlite3_release_memory sqlite3_api->release_memory +#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem +#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig +#define sqlite3_sleep sqlite3_api->sleep +#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit +#define sqlite3_vfs_find sqlite3_api->vfs_find +#define sqlite3_vfs_register sqlite3_api->vfs_register +#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister +#define sqlite3_threadsafe sqlite3_api->xthreadsafe +#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob +#define sqlite3_result_error_code sqlite3_api->result_error_code +#define sqlite3_test_control sqlite3_api->test_control +#define sqlite3_randomness sqlite3_api->randomness +#define sqlite3_context_db_handle sqlite3_api->context_db_handle +#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes +#define sqlite3_limit sqlite3_api->limit +#define sqlite3_next_stmt sqlite3_api->next_stmt +#define sqlite3_sql sqlite3_api->sql +#define sqlite3_status sqlite3_api->status +#define sqlite3_backup_finish sqlite3_api->backup_finish +#define sqlite3_backup_init sqlite3_api->backup_init +#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount +#define sqlite3_backup_remaining sqlite3_api->backup_remaining +#define sqlite3_backup_step sqlite3_api->backup_step +#define sqlite3_compileoption_get sqlite3_api->compileoption_get +#define sqlite3_compileoption_used sqlite3_api->compileoption_used +#define sqlite3_create_function_v2 sqlite3_api->create_function_v2 +#define sqlite3_db_config sqlite3_api->db_config +#define sqlite3_db_mutex sqlite3_api->db_mutex +#define sqlite3_db_status sqlite3_api->db_status +#define sqlite3_extended_errcode sqlite3_api->extended_errcode +#define sqlite3_log sqlite3_api->log +#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 +#define sqlite3_sourceid sqlite3_api->sourceid +#define sqlite3_stmt_status sqlite3_api->stmt_status +#define sqlite3_strnicmp sqlite3_api->strnicmp +#define sqlite3_unlock_notify sqlite3_api->unlock_notify +#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint +#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint +#define sqlite3_wal_hook sqlite3_api->wal_hook +#define sqlite3_blob_reopen sqlite3_api->blob_reopen +#define sqlite3_vtab_config sqlite3_api->vtab_config +#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict +/* Version 3.7.16 and later */ +#define sqlite3_close_v2 sqlite3_api->close_v2 +#define sqlite3_db_filename sqlite3_api->db_filename +#define sqlite3_db_readonly sqlite3_api->db_readonly +#define sqlite3_db_release_memory sqlite3_api->db_release_memory +#define sqlite3_errstr sqlite3_api->errstr +#define sqlite3_stmt_busy sqlite3_api->stmt_busy +#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly +#define sqlite3_stricmp sqlite3_api->stricmp +#define sqlite3_uri_boolean sqlite3_api->uri_boolean +#define sqlite3_uri_int64 sqlite3_api->uri_int64 +#define sqlite3_uri_parameter sqlite3_api->uri_parameter +#define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf +#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 +/* Version 3.8.7 and later */ +#define sqlite3_auto_extension sqlite3_api->auto_extension +#define sqlite3_bind_blob64 sqlite3_api->bind_blob64 +#define sqlite3_bind_text64 sqlite3_api->bind_text64 +#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension +#define sqlite3_load_extension sqlite3_api->load_extension +#define sqlite3_malloc64 sqlite3_api->malloc64 +#define sqlite3_msize sqlite3_api->msize +#define sqlite3_realloc64 sqlite3_api->realloc64 +#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension +#define sqlite3_result_blob64 sqlite3_api->result_blob64 +#define sqlite3_result_text64 sqlite3_api->result_text64 +#define sqlite3_strglob sqlite3_api->strglob +/* Version 3.8.11 and later */ +#define sqlite3_value_dup sqlite3_api->value_dup +#define sqlite3_value_free sqlite3_api->value_free +#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 +#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 +/* Version 3.9.0 and later */ +#define sqlite3_value_subtype sqlite3_api->value_subtype +#define sqlite3_result_subtype sqlite3_api->result_subtype +/* Version 3.10.0 and later */ +#define sqlite3_status64 sqlite3_api->status64 +#define sqlite3_strlike sqlite3_api->strlike +#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush +/* Version 3.12.0 and later */ +#define sqlite3_system_errno sqlite3_api->system_errno +/* Version 3.14.0 and later */ +#define sqlite3_trace_v2 sqlite3_api->trace_v2 +#define sqlite3_expanded_sql sqlite3_api->expanded_sql +/* Version 3.18.0 and later */ +#define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid +/* Version 3.20.0 and later */ +#define sqlite3_prepare_v3 sqlite3_api->prepare_v3 +#define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3 +#define sqlite3_bind_pointer sqlite3_api->bind_pointer +#define sqlite3_result_pointer sqlite3_api->result_pointer +#define sqlite3_value_pointer sqlite3_api->value_pointer +/* Version 3.22.0 and later */ +#define sqlite3_vtab_nochange sqlite3_api->vtab_nochange +#define sqlite3_value_nochange sqlite3_api->value_nochange +#define sqlite3_vtab_collation sqlite3_api->vtab_collation +/* Version 3.24.0 and later */ +#define sqlite3_keyword_count sqlite3_api->keyword_count +#define sqlite3_keyword_name sqlite3_api->keyword_name +#define sqlite3_keyword_check sqlite3_api->keyword_check +#define sqlite3_str_new sqlite3_api->str_new +#define sqlite3_str_finish sqlite3_api->str_finish +#define sqlite3_str_appendf sqlite3_api->str_appendf +#define sqlite3_str_vappendf sqlite3_api->str_vappendf +#define sqlite3_str_append sqlite3_api->str_append +#define sqlite3_str_appendall sqlite3_api->str_appendall +#define sqlite3_str_appendchar sqlite3_api->str_appendchar +#define sqlite3_str_reset sqlite3_api->str_reset +#define sqlite3_str_errcode sqlite3_api->str_errcode +#define sqlite3_str_length sqlite3_api->str_length +#define sqlite3_str_value sqlite3_api->str_value +/* Version 3.25.0 and later */ +#define sqlite3_create_window_function sqlite3_api->create_window_function +/* Version 3.26.0 and later */ +#define sqlite3_normalized_sql sqlite3_api->normalized_sql +/* Version 3.28.0 and later */ +#define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain +#define sqlite3_value_frombind sqlite3_api->value_frombind +/* Version 3.30.0 and later */ +#define sqlite3_drop_modules sqlite3_api->drop_modules +/* Version 3.31.0 and later */ +#define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64 +#define sqlite3_uri_key sqlite3_api->uri_key +#define sqlite3_filename_database sqlite3_api->filename_database +#define sqlite3_filename_journal sqlite3_api->filename_journal +#define sqlite3_filename_wal sqlite3_api->filename_wal +/* Version 3.32.0 and later */ +#define sqlite3_create_filename sqlite3_api->create_filename +#define sqlite3_free_filename sqlite3_api->free_filename +#define sqlite3_database_file_object sqlite3_api->database_file_object +/* Version 3.34.0 and later */ +#define sqlite3_txn_state sqlite3_api->txn_state +/* Version 3.36.1 and later */ +#define sqlite3_changes64 sqlite3_api->changes64 +#define sqlite3_total_changes64 sqlite3_api->total_changes64 +/* Version 3.37.0 and later */ +#define sqlite3_autovacuum_pages sqlite3_api->autovacuum_pages +/* Version 3.38.0 and later */ +#define sqlite3_error_offset sqlite3_api->error_offset +#define sqlite3_vtab_rhs_value sqlite3_api->vtab_rhs_value +#define sqlite3_vtab_distinct sqlite3_api->vtab_distinct +#define sqlite3_vtab_in sqlite3_api->vtab_in +#define sqlite3_vtab_in_first sqlite3_api->vtab_in_first +#define sqlite3_vtab_in_next sqlite3_api->vtab_in_next +/* Version 3.39.0 and later */ +#ifndef SQLITE_OMIT_DESERIALIZE +#define sqlite3_deserialize sqlite3_api->deserialize +#define sqlite3_serialize sqlite3_api->serialize +#endif +#define sqlite3_db_name sqlite3_api->db_name +/* Version 3.40.0 and later */ +#define sqlite3_value_encoding sqlite3_api->value_encoding +/* Version 3.41.0 and later */ +#define sqlite3_is_interrupted sqlite3_api->is_interrupted +/* Version 3.43.0 and later */ +#define sqlite3_stmt_explain sqlite3_api->stmt_explain +/* Version 3.44.0 and later */ +#define sqlite3_get_clientdata sqlite3_api->get_clientdata +#define sqlite3_set_clientdata sqlite3_api->set_clientdata +/* Version 3.50.0 and later */ +#define sqlite3_setlk_timeout sqlite3_api->setlk_timeout +#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ + +#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) + /* This case when the file really is being compiled as a loadable + ** extension */ +# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; +# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; +# define SQLITE_EXTENSION_INIT3 \ + extern const sqlite3_api_routines *sqlite3_api; +#else + /* This case when the file is being statically linked into the + ** application */ +# define SQLITE_EXTENSION_INIT1 /*no-op*/ +# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ +# define SQLITE_EXTENSION_INIT3 /*no-op*/ +#endif + +#endif /* SQLITE3EXT_H */ +/*** End of #include "sqlite3ext.h" ***/ + +SQLITE_EXTENSION_INIT1 +#else +/* #include "sqlite3.h" */ + +#endif + +#include +/* relicoder */ +#include +#include +#include +#include /* LMH 2007-03-25 */ + +#include +#include + +#ifndef _MAP_H_ +#define _MAP_H_ + +#if 0 +#if !defined(SQLITE_OS_WIN) || !defined(_MSC_VER) +#include +#else +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed int int16_t; +typedef unsigned int uint16_t; +typedef signed long int int32_t; +typedef unsigned long int uint32_t; +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; +#endif +#endif + +/* +** Simple binary tree implementation to use in median, mode and quartile calculations +** Tree is not necessarily balanced. That would require something like red&black trees of AVL +*/ + +typedef int(*cmp_func)(const void *, const void *); +typedef void(*map_iterator)(void*, i64, void*); + +typedef struct node{ + struct node *l; + struct node *r; + void* data; + i64 count; +} node; + +typedef struct map{ + node *base; + cmp_func cmp; + short free; +} map; + +/* +** creates a map given a comparison function +*/ +map map_make(cmp_func cmp); + +/* +** inserts the element e into map m +*/ +void map_insert(map *m, void *e); + +/* +** executes function iter over all elements in the map, in key increasing order +*/ +void map_iterate(map *m, map_iterator iter, void* p); + +/* +** frees all memory used by a map +*/ +void map_destroy(map *m); + +/* +** compares 2 integers +** to use with map_make +*/ +int int_cmp(const void *a, const void *b); + +/* +** compares 2 doubles +** to use with map_make +*/ +int double_cmp(const void *a, const void *b); + +#endif /* _MAP_H_ */ + +static char *sqlite3StrDup( const char *z ) { + char *res = sqlite3_malloc( (int) (strlen(z)+1) ); + return strcpy( res, z ); +} + +/* +** These are copied verbatim from fun.c so as to not have the names exported +*/ + +/* LMH from sqlite3 3.3.13 */ +/* +** This table maps from the first byte of a UTF-8 character to the number +** of trailing bytes expected. A value '4' indicates that the table key +** is not a legal first byte for a UTF-8 character. +*/ +static const u8 xtra_utf8_bytes[256] = { +/* 0xxxxxxx */ +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + +/* 10wwwwww */ +4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, +4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, +4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, +4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + +/* 110yyyyy */ +1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + +/* 1110zzzz */ +2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + +/* 11110yyy */ +3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, +}; + + +/* +** This table maps from the number of trailing bytes in a UTF-8 character +** to an integer constant that is effectively calculated for each character +** read by a naive implementation of a UTF-8 character reader. The code +** in the READ_UTF8 macro explains things best. +*/ +static const int xtra_utf8_bits[] = { + 0, + 12416, /* (0xC0 << 6) + (0x80) */ + 925824, /* (0xE0 << 12) + (0x80 << 6) + (0x80) */ + 63447168 /* (0xF0 << 18) + (0x80 << 12) + (0x80 << 6) + 0x80 */ +}; + +/* +** If a UTF-8 character contains N bytes extra bytes (N bytes follow +** the initial byte so that the total character length is N+1) then +** masking the character with utf8_mask[N] must produce a non-zero +** result. Otherwise, we have an (illegal) overlong encoding. +*/ +static const int utf_mask[] = { + 0x00000000, + 0xffffff80, + 0xfffff800, + 0xffff0000, +}; + +/* LMH salvaged from sqlite3 3.3.13 source code src/utf.c */ +#define EXTFUNC_READ_UTF8(zIn, c) { \ + int xtra; \ + c = *(zIn)++; \ + xtra = xtra_utf8_bytes[c]; \ + switch( xtra ){ \ + case 4: c = (int)0xFFFD; break; \ + case 3: c = (c<<6) + *(zIn)++; \ + case 2: c = (c<<6) + *(zIn)++; \ + case 1: c = (c<<6) + *(zIn)++; \ + c -= xtra_utf8_bits[xtra]; \ + if( (utf_mask[xtra]&c)==0 \ + || (c&0xFFFFF800)==0xD800 \ + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ + } \ +} + +static int sqlite3ReadUtf8(const unsigned char *z){ + int c; + EXTFUNC_READ_UTF8(z, c); + return c; +} + +#define SKIP_UTF8(zIn) { \ + zIn += (xtra_utf8_bytes[*(u8 *)zIn] + 1); \ +} + +#if 0 +/* +** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, +** return the number of unicode characters in pZ up to (but not including) +** the first 0x00 byte. If nByte is not less than zero, return the +** number of unicode characters in the first nByte of pZ (or up to +** the first 0x00, whichever comes first). +*/ +static int sqlite3Utf8CharLen(const char *z, int nByte){ + int r = 0; + const char *zTerm; + if( nByte>=0 ){ + zTerm = &z[nByte]; + }else{ + zTerm = (const char *)(-1); + } + assert( z<=zTerm ); + while( *z!=0 && z 0) ? 1: ( iVal < 0 ) ? -1: 0; + sqlite3_result_int64(context, iVal); + break; + } + case SQLITE_NULL: { + sqlite3_result_null(context); + break; + } + default: { + /* 2nd change below. Line for abs was: if( rVal<0 ) rVal = rVal * -1.0; */ + + rVal = sqlite3_value_double(argv[0]); + rVal = ( rVal > 0) ? 1: ( rVal < 0 ) ? -1: 0; + sqlite3_result_double(context, rVal); + break; + } + } +} +#endif + +/* +** smallest integer value not less than argument +*/ +static void ceilFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + double rVal=0.0; + i64 iVal=0; + assert( argc==1 ); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_INTEGER: { + iVal = sqlite3_value_int64(argv[0]); + sqlite3_result_int64(context, iVal); + break; + } + case SQLITE_NULL: { + sqlite3_result_null(context); + break; + } + default: { + rVal = sqlite3_value_double(argv[0]); + sqlite3_result_int64(context, (i64) ceil(rVal)); + break; + } + } +} + +/* +** largest integer value not greater than argument +*/ +static void floorFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + double rVal=0.0; + i64 iVal=0; + assert( argc==1 ); + switch( sqlite3_value_type(argv[0]) ){ + case SQLITE_INTEGER: { + iVal = sqlite3_value_int64(argv[0]); + sqlite3_result_int64(context, iVal); + break; + } + case SQLITE_NULL: { + sqlite3_result_null(context); + break; + } + default: { + rVal = sqlite3_value_double(argv[0]); + sqlite3_result_int64(context, (i64) floor(rVal)); + break; + } + } +} + +#endif /* SQLITE_ENABLE_MATH_FUNCTIONS */ + +/* +** Given a string (s) in the first argument and an integer (n) in the second returns the +** string that constains s contatenated n times +*/ +static void replicateFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + unsigned char *z; /* input string */ + unsigned char *zo; /* result string */ + i64 iCount; /* times to repeat */ + i64 nLen; /* length of the input string (no multibyte considerations) */ + i64 nTLen; /* length of the result string (no multibyte considerations) */ + i64 i=0; + + if( argc!=2 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) + return; + + iCount = sqlite3_value_int64(argv[1]); + + if( iCount<0 ){ + sqlite3_result_error(context, "domain error", -1); + }else{ + + nLen = sqlite3_value_bytes(argv[0]); + nTLen = nLen*iCount; + z=sqlite3_malloc(nTLen+1); + zo=sqlite3_malloc(nLen+1); + if (!z || !zo){ + sqlite3_result_error_nomem(context); + if (z) sqlite3_free(z); + if (zo) sqlite3_free(zo); + return; + } + strcpy((char*)zo, (char*)sqlite3_value_text(argv[0])); + + for(i=0; i=n it's a NOP +** padl(NULL) = NULL +*/ +static void padlFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + i64 ilen; /* length to pad to */ + i64 zl; /* length of the input string (UTF-8 chars) */ + int i = 0; + const char *zi; /* input string */ + char *zo; /* output string */ + char *zt; + + assert( argc==2 ); + + if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){ + sqlite3_result_null(context); + }else{ + zi = (char *)sqlite3_value_text(argv[0]); + ilen = sqlite3_value_int64(argv[1]); + /* check domain */ + if(ilen<0){ + sqlite3_result_error(context, "domain error", -1); + return; + } + zl = sqlite3Utf8CharLen(zi, -1); + if( zl>=ilen ){ + /* string is longer than the requested pad length, return the same string (dup it) */ + zo = sqlite3StrDup(zi); + if (!zo){ + sqlite3_result_error_nomem(context); + return; + } + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + }else{ + zo = sqlite3_malloc((int) (strlen(zi)+ilen-zl+1)); + if (!zo){ + sqlite3_result_error_nomem(context); + return; + } + zt = zo; + for(i=1; i+zl<=ilen; ++i){ + *(zt++)=' '; + } + /* no need to take UTF-8 into consideration here */ + strcpy(zt,zi); + } + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + sqlite3_free(zo); + } +} + +/* +** given an input string (s) and an integer (n) appends spaces at the end of s +** until it has a length of n characters. +** When s has a length >=n it's a NOP +** padl(NULL) = NULL +*/ +static void padrFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + i64 ilen; /* length to pad to */ + i64 zl; /* length of the input string (UTF-8 chars) */ + i64 zll; /* length of the input string (bytes) */ + int i = 0; + const char *zi; /* input string */ + char *zo; /* output string */ + char *zt; + + assert( argc==2 ); + + if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){ + sqlite3_result_null(context); + }else{ + zi = (char *)sqlite3_value_text(argv[0]); + ilen = sqlite3_value_int64(argv[1]); + /* check domain */ + if(ilen<0){ + sqlite3_result_error(context, "domain error", -1); + return; + } + zl = sqlite3Utf8CharLen(zi, -1); + if( zl>=ilen ){ + /* string is longer than the requested pad length, return the same string (dup it) */ + zo = sqlite3StrDup(zi); + if (!zo){ + sqlite3_result_error_nomem(context); + return; + } + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + }else{ + zll = strlen(zi); + zo = sqlite3_malloc(zll+ilen-zl+1); + if (!zo){ + sqlite3_result_error_nomem(context); + return; + } + zt = strcpy(zo,zi)+zll; + for(i=1; i+zl<=ilen; ++i){ + *(zt++) = ' '; + } + *zt = '\0'; + } + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + sqlite3_free(zo); + } +} + +/* +** given an input string (s) and an integer (n) appends spaces at the end of s +** and adds spaces at the begining of s until it has a length of n characters. +** Tries to add has many characters at the left as at the right. +** When s has a length >=n it's a NOP +** padl(NULL) = NULL +*/ +static void padcFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + i64 ilen; /* length to pad to */ + i64 zl; /* length of the input string (UTF-8 chars) */ + i64 zll; /* length of the input string (bytes) */ + int i = 0; + const char *zi; /* input string */ + char *zo; /* output string */ + char *zt; + + assert( argc==2 ); + + if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){ + sqlite3_result_null(context); + }else{ + zi = (char *)sqlite3_value_text(argv[0]); + ilen = sqlite3_value_int64(argv[1]); + /* check domain */ + if(ilen<0){ + sqlite3_result_error(context, "domain error", -1); + return; + } + zl = sqlite3Utf8CharLen(zi, -1); + if( zl>=ilen ){ + /* string is longer than the requested pad length, return the same string (dup it) */ + zo = sqlite3StrDup(zi); + if (!zo){ + sqlite3_result_error_nomem(context); + return; + } + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + }else{ + zll = strlen(zi); + zo = sqlite3_malloc(zll+ilen-zl+1); + if (!zo){ + sqlite3_result_error_nomem(context); + return; + } + zt = zo; + for(i=1; 2*i+zl<=ilen; ++i){ + *(zt++) = ' '; + } + strcpy(zt, zi); + zt+=zll; + for(; i+zl<=ilen; ++i){ + *(zt++) = ' '; + } + *zt = '\0'; + } + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + sqlite3_free(zo); + } +} + +/* +** given 2 string (s1,s2) returns the string s1 with the characters NOT in s2 removed +** assumes strings are UTF-8 encoded +*/ +static void strfilterFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *zi1; /* first parameter string (searched string) */ + const char *zi2; /* second parameter string (vcontains valid characters) */ + const char *z1; + const char *z21; + const char *z22; + char *zo; /* output string */ + char *zot; + int c1 = 0; + int c2 = 0; + + assert( argc==2 ); + + if( sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL ){ + sqlite3_result_null(context); + }else{ + zi1 = (char *)sqlite3_value_text(argv[0]); + zi2 = (char *)sqlite3_value_text(argv[1]); + /* + ** maybe I could allocate less, but that would imply 2 passes, rather waste + ** (possibly) some memory + */ + zo = sqlite3_malloc((int) (strlen(zi1)+1)); + if (!zo){ + sqlite3_result_error_nomem(context); + return; + } + zot = zo; + z1 = zi1; + while( (c1=sqliteCharVal((unsigned char *)z1))!=0 ){ + z21=zi2; + while( (c2=sqliteCharVal((unsigned char *)z21))!=0 && c2!=c1 ){ + sqliteNextChar(z21); + } + if( c2!=0){ + z22=z21; + sqliteNextChar(z22); + strncpy(zot, z21, z22-z21); + zot+=z22-z21; + } + sqliteNextChar(z1); + } + *zot = '\0'; + + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + sqlite3_free(zo); + } +} + +/* +** Given a string z1, retutns the (0 based) index of it's first occurence +** in z2 after the first s characters. +** Returns -1 when there isn't a match. +** updates p to point to the character where the match occured. +** This is an auxiliary function. +*/ +static int _substr(const char* z1, const char* z2, int s, const char** p){ + int c = 0; + int rVal=-1; + const char* zt1; + const char* zt2; + int c1,c2; + + if( '\0'==*z1 ){ + return -1; + } + + while( (sqliteCharVal((unsigned char *)z2) != 0) && (c++)=0 ? rVal+s : rVal; +} + +/* +** given 2 input strings (s1,s2) and an integer (n) searches from the nth character +** for the string s1. Returns the position where the match occured. +** Characters are counted from 1. +** 0 is returned when no match occurs. +*/ + +static void charindexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + const u8 *z1; /* s1 string */ + u8 *z2; /* s2 string */ + int s=0; + int rVal=0; + + assert( argc==3 ||argc==2); + + if( SQLITE_NULL==sqlite3_value_type(argv[0]) || SQLITE_NULL==sqlite3_value_type(argv[1])){ + sqlite3_result_null(context); + return; + } + + z1 = sqlite3_value_text(argv[0]); + if( z1==0 ) return; + z2 = (u8*) sqlite3_value_text(argv[1]); + if(argc==3){ + s = sqlite3_value_int(argv[2])-1; + if(s<0){ + s=0; + } + }else{ + s = 0; + } + + rVal = _substr((char *)z1,(char *)z2,s,NULL); + sqlite3_result_int(context, rVal+1); +} + +/* +** given a string (s) and an integer (n) returns the n leftmost (UTF-8) characters +** if the string has a length<=n or is NULL this function is NOP +*/ +static void leftFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + int c=0; + int cc=0; + int l=0; + const unsigned char *z; /* input string */ + const unsigned char *zt; + unsigned char *rz; /* output string */ + + assert( argc==2); + + if( SQLITE_NULL==sqlite3_value_type(argv[0]) || SQLITE_NULL==sqlite3_value_type(argv[1])){ + sqlite3_result_null(context); + return; + } + + z = sqlite3_value_text(argv[0]); + l = sqlite3_value_int(argv[1]); + zt = z; + + while( sqliteCharVal(zt) && c++ 0 ){ + sqliteNextChar(zt); + } + + rz = sqlite3_malloc(ze-zt+1); + if (!rz){ + sqlite3_result_error_nomem(context); + return; + } + strcpy((char*) rz, (char*) (zt)); + sqlite3_result_text(context, (char*)rz, -1, SQLITE_TRANSIENT); + sqlite3_free(rz); +} + +#ifndef HAVE_TRIM +/* +** removes the whitespaces at the begining of a string. +*/ +const char* ltrim(const char* s){ + while( *s==' ' ) + ++s; + return s; +} + +/* +** removes the whitespaces at the end of a string. +** !mutates the input string! +*/ +void rtrim(char* s){ + char* ss = s+strlen(s)-1; + while( ss>=s && *ss==' ' ) + --ss; + *(ss+1)='\0'; +} + +/* +** Removes the whitespace at the begining of a string +*/ +static void ltrimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *z; + + assert( argc==1); + + if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){ + sqlite3_result_null(context); + return; + } + z = sqlite3_value_text(argv[0]); + sqlite3_result_text(context, ltrim(z), -1, SQLITE_TRANSIENT); +} + +/* +** Removes the whitespace at the end of a string +*/ +static void rtrimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *z; + char *rz; + /* try not to change data in argv */ + + assert( argc==1); + + if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){ + sqlite3_result_null(context); + return; + } + z = sqlite3_value_text(argv[0]); + rz = sqlite3StrDup(z); + rtrim(rz); + sqlite3_result_text(context, rz, -1, SQLITE_TRANSIENT); + sqlite3_free(rz); +} + +/* +** Removes the whitespace at the begining and end of a string +*/ +static void trimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *z; + char *rz; + /* try not to change data in argv */ + + assert( argc==1); + + if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){ + sqlite3_result_null(context); + return; + } + z = sqlite3_value_text(argv[0]); + rz = sqlite3StrDup(z); + rtrim(rz); + sqlite3_result_text(context, ltrim(rz), -1, SQLITE_TRANSIENT); + sqlite3_free(rz); +} +#endif + +/* +** given a pointer to a string s1, the length of that string (l1), a new string (s2) +** and it's length (l2) appends s2 to s1. +** All lengths in bytes. +** This is just an auxiliary function +*/ +#if 0 +static void _append(char **s1, int l1, const char *s2, int l2){ + *s1 = realloc(*s1, (l1+l2+1)*sizeof(char)); + strncpy((*s1)+l1, s2, l2); + *(*(s1)+l1+l2) = '\0'; +} +#endif + +#ifndef HAVE_TRIM + +/* +** given strings s, s1 and s2 replaces occurrences of s1 in s by s2 +*/ +static void replaceFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *z1; /* string s (first parameter) */ + const char *z2; /* string s1 (second parameter) string to look for */ + const char *z3; /* string s2 (third parameter) string to replace occurrences of s1 with */ + int lz1; + int lz2; + int lz3; + int lzo=0; + char *zo=0; + int ret=0; + const char *zt1; + const char *zt2; + + assert( 3==argc ); + + if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){ + sqlite3_result_null(context); + return; + } + + z1 = sqlite3_value_text(argv[0]); + z2 = sqlite3_value_text(argv[1]); + z3 = sqlite3_value_text(argv[2]); + /* handle possible null values */ + if( 0==z2 ){ + z2=""; + } + if( 0==z3 ){ + z3=""; + } + + lz1 = strlen(z1); + lz2 = strlen(z2); + lz3 = strlen(z3); + +#if 0 + /* special case when z2 is empty (or null) nothing will be changed */ + if( 0==lz2 ){ + sqlite3_result_text(context, z1, -1, SQLITE_TRANSIENT); + return; + } +#endif + + zt1=z1; + zt2=z1; + + while(1){ + ret=_substr(z2,zt1 , 0, &zt2); + + if( ret<0 ) + break; + + _append(&zo, lzo, zt1, zt2-zt1); + lzo+=zt2-zt1; + _append(&zo, lzo, z3, lz3); + lzo+=lz3; + + zt1=zt2+lz2; + } + _append(&zo, lzo, zt1, lz1-(zt1-z1)); + sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT); + sqlite3_free(zo); +} +#endif + +/* +** given a string returns the same string but with the characters in reverse order +*/ +static void reverseFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + const char *z; + const char *zt; + char *rz; + char *rzt; + int l = 0; + int i = 0; + + assert( 1==argc ); + + if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){ + sqlite3_result_null(context); + return; + } + z = (char *)sqlite3_value_text(argv[0]); + l = (int) strlen(z); + rz = sqlite3_malloc(l+1); + if (!rz){ + sqlite3_result_error_nomem(context); + return; + } + rzt = rz+l; + *(rzt--) = '\0'; + + zt=z; + while( sqliteCharVal((unsigned char *)zt)!=0 ){ + z=zt; + sqliteNextChar(zt); + for(i=1; zt-i>=z; ++i){ + *(rzt--)=*(zt-i); + } + } + + sqlite3_result_text(context, rz, -1, SQLITE_TRANSIENT); + sqlite3_free(rz); +} + +/* +** An instance of the following structure holds the context of a +** stdev() or variance() aggregate computation. +** implementaion of http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Algorithm_II +** less prone to rounding errors +*/ +typedef struct StdevCtx StdevCtx; +struct StdevCtx { + double rM; + double rS; + i64 cnt; /* number of elements */ +}; + +/* +** An instance of the following structure holds the context of a +** mode() or median() aggregate computation. +** Depends on structures defined in map.c (see map & map) +** These aggregate functions only work for integers and floats although +** they could be made to work for strings. This is usually considered meaningless. +** Only usuall order (for median), no use of collation functions (would this even make sense?) +*/ +typedef struct ModeCtx ModeCtx; +struct ModeCtx { + i64 riM; /* integer value found so far */ + double rdM; /* double value found so far */ + i64 cnt; /* number of elements so far */ + double pcnt; /* number of elements smaller than a percentile */ + i64 mcnt; /* maximum number of occurrences (for mode) */ + i64 mn; /* number of occurrences (for mode and percentiles) */ + i64 is_double; /* whether the computation is being done for doubles (>0) or integers (=0) */ + map* m; /* map structure used for the computation */ + int done; /* whether the answer has been found */ +}; + +/* +** called for each value received during a calculation of stdev or variance +*/ +static void varianceStep(sqlite3_context *context, int argc, sqlite3_value **argv){ + StdevCtx *p; + + double delta; + double x; + + assert( argc==1 ); + p = sqlite3_aggregate_context(context, sizeof(*p)); + /* only consider non-null values */ + if( SQLITE_NULL != sqlite3_value_numeric_type(argv[0]) ){ + p->cnt++; + x = sqlite3_value_double(argv[0]); + delta = (x-p->rM); + p->rM += delta/p->cnt; + p->rS += delta*(x-p->rM); + } +} + +/* +** called for each value received during a calculation of mode of median +*/ +static void modeStep(sqlite3_context *context, int argc, sqlite3_value **argv){ + ModeCtx *p; + i64 xi=0; + double xd=0.0; + i64 *iptr; + double *dptr; + int type; + + assert( argc==1 ); + type = sqlite3_value_numeric_type(argv[0]); + + if( type == SQLITE_NULL) + return; + + p = sqlite3_aggregate_context(context, sizeof(*p)); + + if( 0==(p->m) ){ + p->m = calloc(1, sizeof(map)); + if( type==SQLITE_INTEGER ){ + /* map will be used for integers */ + *(p->m) = map_make(int_cmp); + p->is_double = 0; + }else{ + p->is_double = 1; + /* map will be used for doubles */ + *(p->m) = map_make(double_cmp); + } + } + + ++(p->cnt); + + if( 0==p->is_double ){ + xi = sqlite3_value_int64(argv[0]); + iptr = (i64*)calloc(1,sizeof(i64)); + *iptr = xi; + map_insert(p->m, iptr); + }else{ + xd = sqlite3_value_double(argv[0]); + dptr = (double*)calloc(1,sizeof(double)); + *dptr = xd; + map_insert(p->m, dptr); + } +} + +/* +** Auxiliary function that iterates all elements in a map and finds the mode +** (most frequent value) +*/ +static void modeIterate(void* e, i64 c, void* pp){ + i64 ei; + double ed; + ModeCtx *p = (ModeCtx*)pp; + + if( 0==p->is_double ){ + ei = *(int*)(e); + + if( p->mcnt==c ){ + ++p->mn; + }else if( p->mcntriM = ei; + p->mcnt = c; + p->mn=1; + } + }else{ + ed = *(double*)(e); + + if( p->mcnt==c ){ + ++p->mn; + }else if(p->mcntrdM = ed; + p->mcnt = c; + p->mn=1; + } + } +} + +/* +** Auxiliary function that iterates all elements in a map and finds the median +** (the value such that the number of elements smaller is equal the the number of +** elements larger) +*/ +static void medianIterate(void* e, i64 c, void* pp){ + i64 ei; + double ed; + double iL; + double iR; + int il; + int ir; + ModeCtx *p = (ModeCtx*)pp; + + if(p->done>0) + return; + + iL = p->pcnt; + iR = p->cnt - p->pcnt; + il = p->mcnt + c; + ir = p->cnt - p->mcnt; + + if( il >= iL ){ + if( ir >= iR ){ + ++p->mn; + if( 0==p->is_double ){ + ei = *(int*)(e); + p->riM += ei; + }else{ + ed = *(double*)(e); + p->rdM += ed; + } + }else{ + p->done=1; + } + } + p->mcnt+=c; +} + +/* +** Returns the mode value +*/ +static void modeFinalize(sqlite3_context *context){ + ModeCtx *p; + p = sqlite3_aggregate_context(context, 0); + if( p && p->m ){ + map_iterate(p->m, modeIterate, p); + map_destroy(p->m); + free(p->m); + + if( 1==p->mn ){ + if( 0==p->is_double ) + sqlite3_result_int64(context, p->riM); + else + sqlite3_result_double(context, p->rdM); + } + } +} + +/* +** auxiliary function for percentiles +*/ +static void _medianFinalize(sqlite3_context *context){ + ModeCtx *p; + p = (ModeCtx*) sqlite3_aggregate_context(context, 0); + if( p && p->m ){ + p->done=0; + map_iterate(p->m, medianIterate, p); + map_destroy(p->m); + free(p->m); + + if( 0==p->is_double ) + if( 1==p->mn ) + sqlite3_result_int64(context, p->riM); + else + sqlite3_result_double(context, p->riM*1.0/p->mn); + else + sqlite3_result_double(context, p->rdM/p->mn); + } +} + +/* +** Returns the median value +*/ +static void medianFinalize(sqlite3_context *context){ + ModeCtx *p; + p = (ModeCtx*) sqlite3_aggregate_context(context, 0); + if( p!=0 ){ + p->pcnt = (p->cnt)/2.0; + _medianFinalize(context); + } +} + +/* +** Returns the lower_quartile value +*/ +static void lower_quartileFinalize(sqlite3_context *context){ + ModeCtx *p; + p = (ModeCtx*) sqlite3_aggregate_context(context, 0); + if( p!=0 ){ + p->pcnt = (p->cnt)/4.0; + _medianFinalize(context); + } +} + +/* +** Returns the upper_quartile value +*/ +static void upper_quartileFinalize(sqlite3_context *context){ + ModeCtx *p; + p = (ModeCtx*) sqlite3_aggregate_context(context, 0); + if( p!=0 ){ + p->pcnt = (p->cnt)*3/4.0; + _medianFinalize(context); + } +} + +/* +** Returns the stdev value +*/ +static void stdevFinalize(sqlite3_context *context){ + StdevCtx *p; + p = sqlite3_aggregate_context(context, 0); + if( p && p->cnt>1 ){ + sqlite3_result_double(context, sqrt(p->rS/(p->cnt-1))); + }else{ + sqlite3_result_double(context, 0.0); + } +} + +/* +** Returns the variance value +*/ +static void varianceFinalize(sqlite3_context *context){ + StdevCtx *p; + p = sqlite3_aggregate_context(context, 0); + if( p && p->cnt>1 ){ + sqlite3_result_double(context, p->rS/(p->cnt-1)); + }else{ + sqlite3_result_double(context, 0.0); + } +} + +#ifdef SQLITE_SOUNDEX + +/* relicoder factored code */ +/* +** Calculates the soundex value of a string +*/ + +static void soundex(const u8 *zIn, char *zResult){ + int i, j; + static const unsigned char iCode[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, + }; + + for(i=0; zIn[i] && !isalpha(zIn[i]); i++){} + if( zIn[i] ){ + zResult[0] = toupper(zIn[i]); + for(j=1; j<4 && zIn[i]; i++){ + int code = iCode[zIn[i]&0x7f]; + if( code>0 ){ + zResult[j++] = code + '0'; + } + } + while( j<4 ){ + zResult[j++] = '0'; + } + zResult[j] = 0; + }else{ + strcpy(zResult, "?000"); + } +} + +/* +** computes the number of different characters between the soundex value fo 2 strings +*/ +static void differenceFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + char zResult1[8]; + char zResult2[8]; + char *zR1 = zResult1; + char *zR2 = zResult2; + int rVal = 0; + int i = 0; + const u8 *zIn1; + const u8 *zIn2; + + assert( argc==2 ); + + if( sqlite3_value_type(argv[0])==SQLITE_NULL || sqlite3_value_type(argv[1])==SQLITE_NULL ){ + sqlite3_result_null(context); + return; + } + + zIn1 = (u8*)sqlite3_value_text(argv[0]); + zIn2 = (u8*)sqlite3_value_text(argv[1]); + + soundex(zIn1, zR1); + soundex(zIn2, zR2); + + for(i=0; i<4; ++i){ + if( sqliteCharVal((unsigned char *)zR1)==sqliteCharVal((unsigned char *)zR2) ) + ++rVal; + sqliteNextChar(zR1); + sqliteNextChar(zR2); + } + sqlite3_result_int(context, rVal); +} +#endif + +static void lastRowsFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ + sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3_result_int64(context, sqlite3_changes(db)); +} + +/* +** This function registered all of the above C functions as SQL +** functions. This should be the only routine in this file with +** external linkage. +*/ +int RegisterExtensionFunctions(sqlite3 *db){ + static const struct FuncDef { + char *zName; + signed char nArg; + u8 argType; /* 0: none. 1: db 2: (-1) */ + u8 eTextRep; /* 1: UTF-16. 0: UTF-8 */ + u8 needCollSeq; + void (*xFunc)(sqlite3_context*,int,sqlite3_value **); + } aFuncs[] = { + /* math.h */ +#ifndef SQLITE_ENABLE_MATH_FUNCTIONS + { "acos", 1, 0, SQLITE_UTF8, 0, acosFunc }, + { "asin", 1, 0, SQLITE_UTF8, 0, asinFunc }, + { "atan", 1, 0, SQLITE_UTF8, 0, atanFunc }, +#endif + { "atn2", 2, 0, SQLITE_UTF8, 0, atn2Func }, + /* XXX alias */ +#ifndef SQLITE_ENABLE_MATH_FUNCTIONS + { "atan2", 2, 0, SQLITE_UTF8, 0, atn2Func }, + { "acosh", 1, 0, SQLITE_UTF8, 0, acoshFunc }, + { "asinh", 1, 0, SQLITE_UTF8, 0, asinhFunc }, + { "atanh", 1, 0, SQLITE_UTF8, 0, atanhFunc }, + + { "difference", 2, 0, SQLITE_UTF8, 0, differenceFunc}, + { "degrees", 1, 0, SQLITE_UTF8, 0, rad2degFunc }, + { "radians", 1, 0, SQLITE_UTF8, 0, deg2radFunc }, + + { "cos", 1, 0, SQLITE_UTF8, 0, cosFunc }, + { "sin", 1, 0, SQLITE_UTF8, 0, sinFunc }, + { "tan", 1, 0, SQLITE_UTF8, 0, tanFunc }, +#endif + { "cot", 1, 0, SQLITE_UTF8, 0, cotFunc }, +#ifndef SQLITE_ENABLE_MATH_FUNCTIONS + { "cosh", 1, 0, SQLITE_UTF8, 0, coshFunc }, + { "sinh", 1, 0, SQLITE_UTF8, 0, sinhFunc }, + { "tanh", 1, 0, SQLITE_UTF8, 0, tanhFunc }, +#endif + { "coth", 1, 0, SQLITE_UTF8, 0, cothFunc }, + +#ifndef SQLITE_ENABLE_MATH_FUNCTIONS + { "exp", 1, 0, SQLITE_UTF8, 0, expFunc }, + { "log", 1, 0, SQLITE_UTF8, 0, logFunc }, + { "ln", 1, 0, SQLITE_UTF8, 0, logFunc }, + { "log10", 1, 0, SQLITE_UTF8, 0, log10Func }, + { "power", 2, 0, SQLITE_UTF8, 0, powerFunc }, + { "sign", 1, 0, SQLITE_UTF8, 0, signFunc }, + { "sqrt", 1, 0, SQLITE_UTF8, 0, sqrtFunc }, +#endif + { "square", 1, 0, SQLITE_UTF8, 0, squareFunc }, + +#ifndef SQLITE_ENABLE_MATH_FUNCTIONS + { "ceil", 1, 0, SQLITE_UTF8, 0, ceilFunc }, + { "ceiling", 1, 0, SQLITE_UTF8, 0, ceilFunc }, + { "floor", 1, 0, SQLITE_UTF8, 0, floorFunc }, + + { "pi", 0, 0, SQLITE_UTF8, 1, piFunc }, +#endif + + { "last_rows_affected", 0, 0, SQLITE_UTF8, 0, lastRowsFunc }, + + /* string */ + { "replicate", 2, 0, SQLITE_UTF8, 0, replicateFunc }, + { "charindex", 2, 0, SQLITE_UTF8, 0, charindexFunc }, + { "charindex", 3, 0, SQLITE_UTF8, 0, charindexFunc }, + { "leftstr", 2, 0, SQLITE_UTF8, 0, leftFunc }, + { "rightstr", 2, 0, SQLITE_UTF8, 0, rightFunc }, +#ifndef HAVE_TRIM + { "ltrim", 1, 0, SQLITE_UTF8, 0, ltrimFunc }, + { "rtrim", 1, 0, SQLITE_UTF8, 0, rtrimFunc }, + { "trim", 1, 0, SQLITE_UTF8, 0, trimFunc }, + { "replace", 3, 0, SQLITE_UTF8, 0, replaceFunc }, +#endif + { "reverse", 1, 0, SQLITE_UTF8, 0, reverseFunc }, + { "proper", 1, 0, SQLITE_UTF8, 0, properFunc }, + { "padl", 2, 0, SQLITE_UTF8, 0, padlFunc }, + { "padr", 2, 0, SQLITE_UTF8, 0, padrFunc }, + { "padc", 2, 0, SQLITE_UTF8, 0, padcFunc }, + { "strfilter", 2, 0, SQLITE_UTF8, 0, strfilterFunc }, + + }; + /* Aggregate functions */ + static const struct FuncDefAgg { + char *zName; + signed char nArg; + u8 argType; + u8 needCollSeq; + void (*xStep)(sqlite3_context*,int,sqlite3_value**); + void (*xFinalize)(sqlite3_context*); + } aAggs[] = { + { "stdev", 1, 0, 0, varianceStep, stdevFinalize }, + { "variance", 1, 0, 0, varianceStep, varianceFinalize }, + { "mode", 1, 0, 0, modeStep, modeFinalize }, + { "median", 1, 0, 0, modeStep, medianFinalize }, + { "lower_quartile", 1, 0, 0, modeStep, lower_quartileFinalize }, + { "upper_quartile", 1, 0, 0, modeStep, upper_quartileFinalize }, + }; + int i; + + for(i=0; ineedCollSeq = 1; + } + } +#endif + } + + for(i=0; ineedCollSeq = 1; + } + } +#endif + } + return 0; +} + +#ifdef COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE +int sqlite3_extension_init( + sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi){ + SQLITE_EXTENSION_INIT2(pApi); + RegisterExtensionFunctions(db); + return 0; +} +#endif /* COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE */ + +map map_make(cmp_func cmp){ + map r; + r.cmp=cmp; + r.base = 0; + + return r; +} + +static +void* xcalloc(size_t nmemb, size_t size, char* s){ + void* ret = calloc(nmemb, size); + return ret; +} + +static +void xfree(void* p){ + free(p); +} + +static +void node_insert(node** n, cmp_func cmp, void *e){ + int c; + node* nn; + if(*n==0){ + nn = (node*)xcalloc(1,sizeof(node), "for node"); + nn->data = e; + nn->count = 1; + *n=nn; + }else{ + c=cmp((*n)->data,e); + if(0==c){ + ++((*n)->count); + xfree(e); + }else if(c>0){ + /* put it right here */ + node_insert(&((*n)->l), cmp, e); + }else{ + node_insert(&((*n)->r), cmp, e); + } + } +} + +void map_insert(map *m, void *e){ + node_insert(&(m->base), m->cmp, e); +} + +static +void node_iterate(node *n, map_iterator iter, void* p){ + if(n){ + if(n->l) + node_iterate(n->l, iter, p); + iter(n->data, n->count, p); + if(n->r) + node_iterate(n->r, iter, p); + } +} + +void map_iterate(map *m, map_iterator iter, void* p){ + node_iterate(m->base, iter, p); +} + +static +void node_destroy(node *n){ + if(0!=n){ + xfree(n->data); + if(n->l) + node_destroy(n->l); + if(n->r) + node_destroy(n->r); + + xfree(n); + } +} + +void map_destroy(map *m){ + node_destroy(m->base); +} + +int int_cmp(const void *a, const void *b){ + i64 aa = *(i64 *)(a); + i64 bb = *(i64 *)(b); + /* printf("cmp %d <=> %d\n",aa,bb); */ + if(aa==bb) + return 0; + else if(aa %d\n",aa,bb); */ + if(aa==bb) + return 0; + else if(aa %lld\n", ee,c); +} +#endif +/*** End of #include "extensionfunctions.c" ***/ + +#endif + +/* +** CSV import +*/ +#ifdef SQLITE_ENABLE_CSV +/* Prototype for initialization function of CSV extension */ +SQLITE_API +int sqlite3_csv_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); +/* #include "csv.c" */ +/*** Begin of #include "csv.c" ***/ +/* +** 2016-05-28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains the implementation of an SQLite virtual table for +** reading CSV files. +** +** Usage: +** +** .load ./csv +** CREATE VIRTUAL TABLE temp.csv USING csv(filename=FILENAME); +** SELECT * FROM csv; +** +** The columns are named "c1", "c2", "c3", ... by default. Or the +** application can define its own CREATE TABLE statement using the +** schema= parameter, like this: +** +** CREATE VIRTUAL TABLE temp.csv2 USING csv( +** filename = "../http.log", +** schema = "CREATE TABLE x(date,ipaddr,url,referrer,userAgent)" +** ); +** +** Instead of specifying a file, the text of the CSV can be loaded using +** the data= parameter. +** +** If the columns=N parameter is supplied, then the CSV file is assumed to have +** N columns. If both the columns= and schema= parameters are omitted, then +** the number and names of the columns is determined by the first line of +** the CSV input. +** +** Some extra debugging features (used for testing virtual tables) are available +** if this module is compiled with -DSQLITE_TEST. +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +#include +#include +#include +#include +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** A macro to hint to the compiler that a function should not be +** inlined. +*/ +#if defined(__GNUC__) +# define CSV_NOINLINE __attribute__((noinline)) +#elif defined(_MSC_VER) && _MSC_VER>=1310 +# define CSV_NOINLINE __declspec(noinline) +#else +# define CSV_NOINLINE +#endif + + +/* Max size of the error message in a CsvReader */ +#define CSV_MXERR 200 + +/* Size of the CsvReader input buffer */ +#define CSV_INBUFSZ 1024 + +/* A context object used when read a CSV file. */ +typedef struct CsvReader CsvReader; +struct CsvReader { + FILE *in; /* Read the CSV text from this input stream */ + char *z; /* Accumulated text for a field */ + int n; /* Number of bytes in z */ + int nAlloc; /* Space allocated for z[] */ + int nLine; /* Current line number */ + int bNotFirst; /* True if prior text has been seen */ + int cTerm; /* Character that terminated the most recent field */ + size_t iIn; /* Next unread character in the input buffer */ + size_t nIn; /* Number of characters in the input buffer */ + char *zIn; /* The input buffer */ + char zErr[CSV_MXERR]; /* Error message */ +}; + +/* Initialize a CsvReader object */ +static void csv_reader_init(CsvReader *p){ + p->in = 0; + p->z = 0; + p->n = 0; + p->nAlloc = 0; + p->nLine = 0; + p->bNotFirst = 0; + p->nIn = 0; + p->zIn = 0; + p->zErr[0] = 0; +} + +/* Close and reset a CsvReader object */ +static void csv_reader_reset(CsvReader *p){ + if( p->in ){ + fclose(p->in); + sqlite3_free(p->zIn); + } + sqlite3_free(p->z); + csv_reader_init(p); +} + +/* Report an error on a CsvReader */ +static void csv_errmsg(CsvReader *p, const char *zFormat, ...){ + va_list ap; + va_start(ap, zFormat); + sqlite3_vsnprintf(CSV_MXERR, p->zErr, zFormat, ap); + va_end(ap); +} + +/* Open the file associated with a CsvReader +** Return the number of errors. +*/ +static int csv_reader_open( + CsvReader *p, /* The reader to open */ + const char *zFilename, /* Read from this filename */ + const char *zData /* ... or use this data */ +){ + if( zFilename ){ + p->zIn = sqlite3_malloc( CSV_INBUFSZ ); + if( p->zIn==0 ){ + csv_errmsg(p, "out of memory"); + return 1; + } + p->in = fopen(zFilename, "rb"); + if( p->in==0 ){ + sqlite3_free(p->zIn); + csv_reader_reset(p); + csv_errmsg(p, "cannot open '%s' for reading", zFilename); + return 1; + } + }else{ + assert( p->in==0 ); + p->zIn = (char*)zData; + p->nIn = strlen(zData); + } + return 0; +} + +/* The input buffer has overflowed. Refill the input buffer, then +** return the next character +*/ +static CSV_NOINLINE int csv_getc_refill(CsvReader *p){ + size_t got; + + assert( p->iIn>=p->nIn ); /* Only called on an empty input buffer */ + assert( p->in!=0 ); /* Only called if reading froma file */ + + got = fread(p->zIn, 1, CSV_INBUFSZ, p->in); + if( got==0 ) return EOF; + p->nIn = got; + p->iIn = 1; + return p->zIn[0]; +} + +/* Return the next character of input. Return EOF at end of input. */ +static int csv_getc(CsvReader *p){ + if( p->iIn >= p->nIn ){ + if( p->in!=0 ) return csv_getc_refill(p); + return EOF; + } + return ((unsigned char*)p->zIn)[p->iIn++]; +} + +/* Increase the size of p->z and append character c to the end. +** Return 0 on success and non-zero if there is an OOM error */ +static CSV_NOINLINE int csv_resize_and_append(CsvReader *p, char c){ + char *zNew; + int nNew = p->nAlloc*2 + 100; + zNew = sqlite3_realloc64(p->z, nNew); + if( zNew ){ + p->z = zNew; + p->nAlloc = nNew; + p->z[p->n++] = c; + return 0; + }else{ + csv_errmsg(p, "out of memory"); + return 1; + } +} + +/* Append a single character to the CsvReader.z[] array. +** Return 0 on success and non-zero if there is an OOM error */ +static int csv_append(CsvReader *p, char c){ + if( p->n>=p->nAlloc-1 ) return csv_resize_and_append(p, c); + p->z[p->n++] = c; + return 0; +} + +/* Read a single field of CSV text. Compatible with rfc4180 and extended +** with the option of having a separator other than ",". +** +** + Input comes from p->in. +** + Store results in p->z of length p->n. Space to hold p->z comes +** from sqlite3_malloc64(). +** + Keep track of the line number in p->nLine. +** + Store the character that terminates the field in p->cTerm. Store +** EOF on end-of-file. +** +** Return 0 at EOF or on OOM. On EOF, the p->cTerm character will have +** been set to EOF. +*/ +static char *csv_read_one_field(CsvReader *p){ + int c; + p->n = 0; + c = csv_getc(p); + if( c==EOF ){ + p->cTerm = EOF; + return 0; + } + if( c=='"' ){ + int pc, ppc; + int startLine = p->nLine; + pc = ppc = 0; + while( 1 ){ + c = csv_getc(p); + if( c<='"' || pc=='"' ){ + if( c=='\n' ) p->nLine++; + if( c=='"' ){ + if( pc=='"' ){ + pc = 0; + continue; + } + } + if( (c==',' && pc=='"') + || (c=='\n' && pc=='"') + || (c=='\n' && pc=='\r' && ppc=='"') + || (c==EOF && pc=='"') + ){ + do{ p->n--; }while( p->z[p->n]!='"' ); + p->cTerm = (char)c; + break; + } + if( pc=='"' && c!='\r' ){ + csv_errmsg(p, "line %d: unescaped %c character", p->nLine, '"'); + break; + } + if( c==EOF ){ + csv_errmsg(p, "line %d: unterminated %c-quoted field\n", + startLine, '"'); + p->cTerm = (char)c; + break; + } + } + if( csv_append(p, (char)c) ) return 0; + ppc = pc; + pc = c; + } + }else{ + /* If this is the first field being parsed and it begins with the + ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ + if( (c&0xff)==0xef && p->bNotFirst==0 ){ + csv_append(p, (char)c); + c = csv_getc(p); + if( (c&0xff)==0xbb ){ + csv_append(p, (char)c); + c = csv_getc(p); + if( (c&0xff)==0xbf ){ + p->bNotFirst = 1; + p->n = 0; + return csv_read_one_field(p); + } + } + } + while( c>',' || (c!=EOF && c!=',' && c!='\n') ){ + if( csv_append(p, (char)c) ) return 0; + c = csv_getc(p); + } + if( c=='\n' ){ + p->nLine++; + if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; + } + p->cTerm = (char)c; + } + assert( p->z==0 || p->nnAlloc ); + if( p->z ) p->z[p->n] = 0; + p->bNotFirst = 1; + return p->z; +} + + +/* Forward references to the various virtual table methods implemented +** in this file. */ +static int csvtabCreate(sqlite3*, void*, int, const char*const*, + sqlite3_vtab**,char**); +static int csvtabConnect(sqlite3*, void*, int, const char*const*, + sqlite3_vtab**,char**); +static int csvtabBestIndex(sqlite3_vtab*,sqlite3_index_info*); +static int csvtabDisconnect(sqlite3_vtab*); +static int csvtabOpen(sqlite3_vtab*, sqlite3_vtab_cursor**); +static int csvtabClose(sqlite3_vtab_cursor*); +static int csvtabFilter(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); +static int csvtabNext(sqlite3_vtab_cursor*); +static int csvtabEof(sqlite3_vtab_cursor*); +static int csvtabColumn(sqlite3_vtab_cursor*,sqlite3_context*,int); +static int csvtabRowid(sqlite3_vtab_cursor*,sqlite3_int64*); + +/* An instance of the CSV virtual table */ +typedef struct CsvTable { + sqlite3_vtab base; /* Base class. Must be first */ + char *zFilename; /* Name of the CSV file */ + char *zData; /* Raw CSV data in lieu of zFilename */ + long iStart; /* Offset to start of data in zFilename */ + int nCol; /* Number of columns in the CSV file */ + unsigned int tstFlags; /* Bit values used for testing */ +} CsvTable; + +/* Allowed values for tstFlags */ +#define CSVTEST_FIDX 0x0001 /* Pretend that constrained search cost less*/ + +/* A cursor for the CSV virtual table */ +typedef struct CsvCursor { + sqlite3_vtab_cursor base; /* Base class. Must be first */ + CsvReader rdr; /* The CsvReader object */ + char **azVal; /* Value of the current row */ + int *aLen; /* Length of each entry */ + sqlite3_int64 iRowid; /* The current rowid. Negative for EOF */ +} CsvCursor; + +/* Transfer error message text from a reader into a CsvTable */ +static void csv_xfer_error(CsvTable *pTab, CsvReader *pRdr){ + sqlite3_free(pTab->base.zErrMsg); + pTab->base.zErrMsg = sqlite3_mprintf("%s", pRdr->zErr); +} + +/* +** This method is the destructor fo a CsvTable object. +*/ +static int csvtabDisconnect(sqlite3_vtab *pVtab){ + CsvTable *p = (CsvTable*)pVtab; + sqlite3_free(p->zFilename); + sqlite3_free(p->zData); + sqlite3_free(p); + return SQLITE_OK; +} + +/* Skip leading whitespace. Return a pointer to the first non-whitespace +** character, or to the zero terminator if the string has only whitespace */ +static const char *csv_skip_whitespace(const char *z){ + while( isspace((unsigned char)z[0]) ) z++; + return z; +} + +/* Remove trailing whitespace from the end of string z[] */ +static void csv_trim_whitespace(char *z){ + size_t n = strlen(z); + while( n>0 && isspace((unsigned char)z[n]) ) n--; + z[n] = 0; +} + +/* Dequote the string */ +static void csv_dequote(char *z){ + int j; + char cQuote = z[0]; + size_t i, n; + + if( cQuote!='\'' && cQuote!='"' ) return; + n = strlen(z); + if( n<2 || z[n-1]!=z[0] ) return; + for(i=1, j=0; izErr. If there are no errors, p->zErr[0]==0. +*/ +static int csv_string_parameter( + CsvReader *p, /* Leave the error message here, if there is one */ + const char *zParam, /* Parameter we are checking for */ + const char *zArg, /* Raw text of the virtual table argment */ + char **pzVal /* Write the dequoted string value here */ +){ + const char *zValue; + zValue = csv_parameter(zParam,(int)strlen(zParam),zArg); + if( zValue==0 ) return 0; + p->zErr[0] = 0; + if( *pzVal ){ + csv_errmsg(p, "more than one '%s' parameter", zParam); + return 1; + } + *pzVal = sqlite3_mprintf("%s", zValue); + if( *pzVal==0 ){ + csv_errmsg(p, "out of memory"); + return 1; + } + csv_trim_whitespace(*pzVal); + csv_dequote(*pzVal); + return 1; +} + + +/* Return 0 if the argument is false and 1 if it is true. Return -1 if +** we cannot really tell. +*/ +static int csv_boolean(const char *z){ + if( sqlite3_stricmp("yes",z)==0 + || sqlite3_stricmp("on",z)==0 + || sqlite3_stricmp("true",z)==0 + || (z[0]=='1' && z[1]==0) + ){ + return 1; + } + if( sqlite3_stricmp("no",z)==0 + || sqlite3_stricmp("off",z)==0 + || sqlite3_stricmp("false",z)==0 + || (z[0]=='0' && z[1]==0) + ){ + return 0; + } + return -1; +} + +/* Check to see if the string is of the form: "TAG = BOOLEAN" or just "TAG". +** If it is, set *pValue to be the value of the boolean ("true" if there is +** not "= BOOLEAN" component) and return non-zero. If the input string +** does not begin with TAG, return zero. +*/ +static int csv_boolean_parameter( + const char *zTag, /* Tag we are looking for */ + int nTag, /* Size of the tag in bytes */ + const char *z, /* Input parameter */ + int *pValue /* Write boolean value here */ +){ + int b; + z = csv_skip_whitespace(z); + if( strncmp(zTag, z, nTag)!=0 ) return 0; + z = csv_skip_whitespace(z + nTag); + if( z[0]==0 ){ + *pValue = 1; + return 1; + } + if( z[0]!='=' ) return 0; + z = csv_skip_whitespace(z+1); + b = csv_boolean(z); + if( b>=0 ){ + *pValue = b; + return 1; + } + return 0; +} + +/* +** Parameters: +** filename=FILENAME Name of file containing CSV content +** data=TEXT Direct CSV content. +** schema=SCHEMA Alternative CSV schema. +** header=YES|NO First row of CSV defines the names of +** columns if "yes". Default "no". +** columns=N Assume the CSV file contains N columns. +** +** Only available if compiled with SQLITE_TEST: +** +** testflags=N Bitmask of test flags. Optional +** +** If schema= is omitted, then the columns are named "c0", "c1", "c2", +** and so forth. If columns=N is omitted, then the file is opened and +** the number of columns in the first row is counted to determine the +** column count. If header=YES, then the first row is skipped. +*/ +static int csvtabConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + CsvTable *pNew = 0; /* The CsvTable object to construct */ + int bHeader = -1; /* header= flags. -1 means not seen yet */ + int rc = SQLITE_OK; /* Result code from this routine */ + int i, j; /* Loop counters */ +#ifdef SQLITE_TEST + int tstFlags = 0; /* Value for testflags=N parameter */ +#endif + int b; /* Value of a boolean parameter */ + int nCol = -99; /* Value of the columns= parameter */ + CsvReader sRdr; /* A CSV file reader used to store an error + ** message and/or to count the number of columns */ + static const char *azParam[] = { + "filename", "data", "schema", + }; + char *azPValue[3]; /* Parameter values */ +# define CSV_FILENAME (azPValue[0]) +# define CSV_DATA (azPValue[1]) +# define CSV_SCHEMA (azPValue[2]) + + + assert( sizeof(azPValue)==sizeof(azParam) ); + memset(&sRdr, 0, sizeof(sRdr)); + memset(azPValue, 0, sizeof(azPValue)); + for(i=3; i=0 ){ + csv_errmsg(&sRdr, "more than one 'header' parameter"); + goto csvtab_connect_error; + } + bHeader = b; + }else +#ifdef SQLITE_TEST + if( (zValue = csv_parameter("testflags",9,z))!=0 ){ + tstFlags = (unsigned int)atoi(zValue); + }else +#endif + if( (zValue = csv_parameter("columns",7,z))!=0 ){ + if( nCol>0 ){ + csv_errmsg(&sRdr, "more than one 'columns' parameter"); + goto csvtab_connect_error; + } + nCol = atoi(zValue); + if( nCol<=0 ){ + csv_errmsg(&sRdr, "column= value must be positive"); + goto csvtab_connect_error; + } + }else + { + csv_errmsg(&sRdr, "bad parameter: '%s'", z); + goto csvtab_connect_error; + } + } + if( (CSV_FILENAME==0)==(CSV_DATA==0) ){ + csv_errmsg(&sRdr, "must specify either filename= or data= but not both"); + goto csvtab_connect_error; + } + + if( (nCol<=0 || bHeader==1) + && csv_reader_open(&sRdr, CSV_FILENAME, CSV_DATA) + ){ + goto csvtab_connect_error; + } + pNew = sqlite3_malloc( sizeof(*pNew) ); + *ppVtab = (sqlite3_vtab*)pNew; + if( pNew==0 ) goto csvtab_connect_oom; + memset(pNew, 0, sizeof(*pNew)); + if( CSV_SCHEMA==0 ){ + sqlite3_str *pStr = sqlite3_str_new(0); + char *zSep = ""; + int iCol = 0; + sqlite3_str_appendf(pStr, "CREATE TABLE x("); + if( nCol<0 && bHeader<1 ){ + nCol = 0; + do{ + csv_read_one_field(&sRdr); + nCol++; + }while( sRdr.cTerm==',' ); + } + if( nCol>0 && bHeader<1 ){ + for(iCol=0; iCol0 && iColnCol = nCol; + sqlite3_str_appendf(pStr, ")"); + CSV_SCHEMA = sqlite3_str_finish(pStr); + if( CSV_SCHEMA==0 ) goto csvtab_connect_oom; + }else if( nCol<0 ){ + do{ + csv_read_one_field(&sRdr); + pNew->nCol++; + }while( sRdr.cTerm==',' ); + }else{ + pNew->nCol = nCol; + } + pNew->zFilename = CSV_FILENAME; CSV_FILENAME = 0; + pNew->zData = CSV_DATA; CSV_DATA = 0; +#ifdef SQLITE_TEST + pNew->tstFlags = tstFlags; +#endif + if( bHeader!=1 ){ + pNew->iStart = 0; + }else if( pNew->zData ){ + pNew->iStart = (int)sRdr.iIn; + }else{ + pNew->iStart = (int)(ftell(sRdr.in) - sRdr.nIn + sRdr.iIn); + } + csv_reader_reset(&sRdr); + rc = sqlite3_declare_vtab(db, CSV_SCHEMA); + if( rc ){ + csv_errmsg(&sRdr, "bad schema: '%s' - %s", CSV_SCHEMA, sqlite3_errmsg(db)); + goto csvtab_connect_error; + } + for(i=0; ibase); + for(i=0; ibase.pVtab; + int i; + for(i=0; inCol; i++){ + sqlite3_free(pCur->azVal[i]); + pCur->azVal[i] = 0; + pCur->aLen[i] = 0; + } +} + +/* +** The xConnect and xCreate methods do the same thing, but they must be +** different so that the virtual table is not an eponymous virtual table. +*/ +static int csvtabCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + return csvtabConnect(db, pAux, argc, argv, ppVtab, pzErr); +} + +/* +** Destructor for a CsvCursor. +*/ +static int csvtabClose(sqlite3_vtab_cursor *cur){ + CsvCursor *pCur = (CsvCursor*)cur; + csvtabCursorRowReset(pCur); + csv_reader_reset(&pCur->rdr); + sqlite3_free(cur); + return SQLITE_OK; +} + +/* +** Constructor for a new CsvTable cursor object. +*/ +static int csvtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ + CsvTable *pTab = (CsvTable*)p; + CsvCursor *pCur; + size_t nByte; + nByte = sizeof(*pCur) + (sizeof(char*)+sizeof(int))*pTab->nCol; + pCur = sqlite3_malloc64( nByte ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, nByte); + pCur->azVal = (char**)&pCur[1]; + pCur->aLen = (int*)&pCur->azVal[pTab->nCol]; + *ppCursor = &pCur->base; + if( csv_reader_open(&pCur->rdr, pTab->zFilename, pTab->zData) ){ + csv_xfer_error(pTab, &pCur->rdr); + return SQLITE_ERROR; + } + return SQLITE_OK; +} + + +/* +** Advance a CsvCursor to its next row of input. +** Set the EOF marker if we reach the end of input. +*/ +static int csvtabNext(sqlite3_vtab_cursor *cur){ + CsvCursor *pCur = (CsvCursor*)cur; + CsvTable *pTab = (CsvTable*)cur->pVtab; + int i = 0; + char *z; + do{ + z = csv_read_one_field(&pCur->rdr); + if( z==0 ){ + break; + } + if( inCol ){ + if( pCur->aLen[i] < pCur->rdr.n+1 ){ + char *zNew = sqlite3_realloc64(pCur->azVal[i], pCur->rdr.n+1); + if( zNew==0 ){ + csv_errmsg(&pCur->rdr, "out of memory"); + csv_xfer_error(pTab, &pCur->rdr); + break; + } + pCur->azVal[i] = zNew; + pCur->aLen[i] = pCur->rdr.n+1; + } + memcpy(pCur->azVal[i], z, pCur->rdr.n+1); + i++; + } + }while( pCur->rdr.cTerm==',' ); + if( z==0 && i==0 ){ + pCur->iRowid = -1; + }else{ + pCur->iRowid++; + while( inCol ){ + sqlite3_free(pCur->azVal[i]); + pCur->azVal[i] = 0; + pCur->aLen[i] = 0; + i++; + } + } + return SQLITE_OK; +} + +/* +** Return values of columns for the row at which the CsvCursor +** is currently pointing. +*/ +static int csvtabColumn( + sqlite3_vtab_cursor *cur, /* The cursor */ + sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ + int i /* Which column to return */ +){ + CsvCursor *pCur = (CsvCursor*)cur; + CsvTable *pTab = (CsvTable*)cur->pVtab; + if( i>=0 && inCol && pCur->azVal[i]!=0 ){ + sqlite3_result_text(ctx, pCur->azVal[i], -1, SQLITE_TRANSIENT); + } + return SQLITE_OK; +} + +/* +** Return the rowid for the current row. +*/ +static int csvtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + CsvCursor *pCur = (CsvCursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** Return TRUE if the cursor has been moved off of the last +** row of output. +*/ +static int csvtabEof(sqlite3_vtab_cursor *cur){ + CsvCursor *pCur = (CsvCursor*)cur; + return pCur->iRowid<0; +} + +/* +** Only a full table scan is supported. So xFilter simply rewinds to +** the beginning. +*/ +static int csvtabFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + CsvCursor *pCur = (CsvCursor*)pVtabCursor; + CsvTable *pTab = (CsvTable*)pVtabCursor->pVtab; + pCur->iRowid = 0; + + /* Ensure the field buffer is always allocated. Otherwise, if the + ** first field is zero bytes in size, this may be mistaken for an OOM + ** error in csvtabNext(). */ + if( csv_append(&pCur->rdr, 0) ) return SQLITE_NOMEM; + + if( pCur->rdr.in==0 ){ + assert( pCur->rdr.zIn==pTab->zData ); + assert( pTab->iStart>=0 ); + assert( (size_t)pTab->iStart<=pCur->rdr.nIn ); + pCur->rdr.iIn = pTab->iStart; + }else{ + fseek(pCur->rdr.in, pTab->iStart, SEEK_SET); + pCur->rdr.iIn = 0; + pCur->rdr.nIn = 0; + } + return csvtabNext(pVtabCursor); +} + +/* +** Only a forward full table scan is supported. xBestIndex is mostly +** a no-op. If CSVTEST_FIDX is set, then the presence of equality +** constraints lowers the estimated cost, which is fiction, but is useful +** for testing certain kinds of virtual table behavior. +*/ +static int csvtabBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo +){ + pIdxInfo->estimatedCost = 1000000; +#ifdef SQLITE_TEST + if( (((CsvTable*)tab)->tstFlags & CSVTEST_FIDX)!=0 ){ + /* The usual (and sensible) case is to always do a full table scan. + ** The code in this branch only runs when testflags=1. This code + ** generates an artifical and unrealistic plan which is useful + ** for testing virtual table logic but is not helpful to real applications. + ** + ** Any ==, LIKE, or GLOB constraint is marked as usable by the virtual + ** table (even though it is not) and the cost of running the virtual table + ** is reduced from 1 million to just 10. The constraints are *not* marked + ** as omittable, however, so the query planner should still generate a + ** plan that gives a correct answer, even if they plan is not optimal. + */ + int i; + int nConst = 0; + for(i=0; inConstraint; i++){ + unsigned char op; + if( pIdxInfo->aConstraint[i].usable==0 ) continue; + op = pIdxInfo->aConstraint[i].op; + if( op==SQLITE_INDEX_CONSTRAINT_EQ + || op==SQLITE_INDEX_CONSTRAINT_LIKE + || op==SQLITE_INDEX_CONSTRAINT_GLOB + ){ + pIdxInfo->estimatedCost = 10; + pIdxInfo->aConstraintUsage[nConst].argvIndex = nConst+1; + nConst++; + } + } + } +#endif + return SQLITE_OK; +} + + +static sqlite3_module CsvModule = { + 0, /* iVersion */ + csvtabCreate, /* xCreate */ + csvtabConnect, /* xConnect */ + csvtabBestIndex, /* xBestIndex */ + csvtabDisconnect, /* xDisconnect */ + csvtabDisconnect, /* xDestroy */ + csvtabOpen, /* xOpen - open a cursor */ + csvtabClose, /* xClose - close a cursor */ + csvtabFilter, /* xFilter - configure scan constraints */ + csvtabNext, /* xNext - advance a cursor */ + csvtabEof, /* xEof - check for end of scan */ + csvtabColumn, /* xColumn - read data */ + csvtabRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadowName */ + 0 /* xIntegrity */ +}; + +#ifdef SQLITE_TEST +/* +** For virtual table testing, make a version of the CSV virtual table +** available that has an xUpdate function. But the xUpdate always returns +** SQLITE_READONLY since the CSV file is not really writable. +*/ +static int csvtabUpdate(sqlite3_vtab *p,int n,sqlite3_value**v,sqlite3_int64*x){ + return SQLITE_READONLY; +} +static sqlite3_module CsvModuleFauxWrite = { + 0, /* iVersion */ + csvtabCreate, /* xCreate */ + csvtabConnect, /* xConnect */ + csvtabBestIndex, /* xBestIndex */ + csvtabDisconnect, /* xDisconnect */ + csvtabDisconnect, /* xDestroy */ + csvtabOpen, /* xOpen - open a cursor */ + csvtabClose, /* xClose - close a cursor */ + csvtabFilter, /* xFilter - configure scan constraints */ + csvtabNext, /* xNext - advance a cursor */ + csvtabEof, /* xEof - check for end of scan */ + csvtabColumn, /* xColumn - read data */ + csvtabRowid, /* xRowid - read data */ + csvtabUpdate, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadowName */ + 0 /* xIntegrity */ +}; +#endif /* SQLITE_TEST */ + +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +#ifndef SQLITE_API +#define SQLITE_API +#endif +/* +** This routine is called when the extension is loaded. The new +** CSV virtual table module is registered with the calling database +** connection. +*/ +SQLITE_API +int sqlite3_csv_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + int rc; + SQLITE_EXTENSION_INIT2(pApi); + rc = sqlite3_create_module(db, "csv", &CsvModule, 0); +#ifdef SQLITE_TEST + if( rc==SQLITE_OK ){ + rc = sqlite3_create_module(db, "csv_wr", &CsvModuleFauxWrite, 0); + } +#endif + return rc; +#else + return SQLITE_OK; +#endif +} +/*** End of #include "csv.c" ***/ + +#endif + +/* +** VSV import +*/ +#ifdef SQLITE_ENABLE_VSV +/* Prototype for initialization function of VSV extension */ +SQLITE_API +int sqlite3_vsv_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); +/* #include "vsv.c" */ +/*** Begin of #include "vsv.c" ***/ +/* +** 2020-02-08 modified by Keith Medcalf who also disclaims all copyright +** on the modifications and hereby places this code in the public domain +** +** This file contains the implementation of an SQLite virtual table for +** reading VSV (Variably Separated Values), which are like CSV files, +** but subtly different. VSV supports a number of extensions to the +** CSV format as well as more processing options. +** +** http:\\www.dessus.com\files\vsv.c +** +** Usage: +** +** create virtual table temp.vsv using vsv(...); +** select * from vsv; +** +** The parameters to the vsv module (the vsv(...) part) are as follows: +** +** filename=STRING the filename, passed to the Operating System +** data=STRING alternative data +** schema=STRING Alternate Schema to use +** columns=N columns parsed from the VSV file +** header=BOOL whether or not a header row is present +** skip=N number of leading data rows to skip +** rsep=STRING record separator +** fsep=STRING field separator +** validatetext=BOOL validate UTF-8 encoding of text fields +** affinity=AFFINITY affinity to apply to each returned value +** nulls=BOOL empty fields are returned as NULL +** +** +** Defaults: +** +** filename / data nothing. You must provide one or the other +** it is an error to provide both or neither +** schema nothing. If not provided then one will be +** generated for you from the header, or if no +** header is available then autogenerated using +** field names manufactured as cX where X is the +** column number +** columns nothing. If not specified then the number of +** columns is determined by counting the fields +** in the first record of the VSV file (which +** will be the header row if header is specified), +** the number of columns is not parsed from the +** schema even if one is provided +** header=no no header row in the VSV file +** skip=0 do not skip any data rows in the VSV file +** fsep=',' default field separator is a comma +** rsep='\n' default record separator is a newline +** validatetext=no do not validate text field encoding +** affinity=none do not apply affinity to each returned value +** nulls=off empty fields returned as zero-length +** +** +** Parameter types: +** +** STRING means a quoted string +** N means a whole number not containing a sign +** BOOL means something that evaluates as true or false +** it is case insensitive +** yes, no, true, false, 1, 0 +** AFFINITY means an SQLite3 type specification +** it is case insensitive +** none, blob, text, integer, real, numeric +** +** STRING means a quoted string. The quote character may be either +** a single quote or a double quote. Two quote characters in a row +** will be replaced with one quote character. STRINGS do not +** need to be quoted if it is obvious where they begin and end +** (that is, they do not contain a comma or other character that the +** parser treats especially, such as : or \). Leading and trailing +** spaces will be trimmed from unquoted strings. +** +** filename =./this/filename.here, ... +** filename =./this/filename.here , ... +** filename = ./this/filename.here, ... +** filename = ./this/filename.here , ... +** filename = './this/filename.here', ... +** filename = "./this/filename.here", ... +** +** are all equivalent. +** +** BOOL defaults to true so the following specifications are all the +** same: +** +** header = true +** header = yes +** header = 1 +** header +** +** +** Specific Parameters: +** +** The platform/compiler/OS fopen call is responsible for interpreting +** the filename. It may contain anything recognized by the OS. +** +** The separator string containing exactly one character, or a valid +** escape sequence. Recognized escape sequences are: +** +** \t horizontal tab, ascii character 9 (0x09) +** \n linefeed, ascii character 10 (0x0a) +** \v vertical tab, ascii character 11 (0x0b) +** \f form feed, ascii character 12 (0x0c) +** \xhh specific byte where hh is hexadecimal +** +** The validatetext setting will cause the validity of the field +** encoding (not its contents) to be verified. It effects how +** fields that are supposed to contain text will be returned to +** the SQLite3 library in order to prevent invalid utf8 data from +** being stored or processed as if it were valid utf8 text. +** +** The nulls option will cause fields that do not contain anything +** to return NULL rather than an empty result. Two separators +** side-by-each with no intervening characters at all will be +** returned as NULL if nulls is true; if nulls is false or +** the contents are explicity empty ("") then a 0 length blob +** (if affinity=blob) or 0 length text string. +** +** For the affinity setting, the following processing is applied to +** each value returned by the VSV virtual table: +** +** none no affinity is applied, all fields will be +** returned as text just like in the original +** csv module, embedded nulls will terminate +** the text. if validatetext is in effect then +** an error will be thrown if the field does +** not contain validly encoded text or contains +** embedded nulls +** +** blob all fields will be returned as blobs +** validatetext has no effect +** +** text all fields will be returned as text just +** like in the original csv module, embedded +** nulls will terminate the text. +** if validatetext is in effect then a blob +** will be returned if the field does not +** contain validly encoded text or the field +** contains embedded nulls +** +** integer if the field data looks like an integer, +** (regex "^ *(\+|-)?\d+ *$"), +** then an integer will be returned as +** provided by the compiler and platform +** runtime strtoll function +** otherwise the field will be processed as +** text as defined above +** +** real if the field data looks like a number, +** (regex "^ *(\+|-)?(\d+\.?\d*|\d*\.?\d+)([eE](\+|-)?\d+)? *$") +** then a double will be returned as +** provided by the compiler and platform +** runtime strtold function otherwise the +** field will be processed as text as +** defined above +** +** numeric if the field looks like an integer +** (see integer above) that integer will be +** returned +** if the field looks like a number +** (see real above) then the number will +** returned as an integer if it has no +** fractional part and +** (a) your platform/compiler supports +** long double and the number will fit in +** a 64-bit integer; or, +** (b) your platform/compiler does not +** support long double (treats it as a double) +** then a 64-bit integer will only be returned +** for integers that can be represented in the +** 53 bit significand of a double +** +** The nulls option will cause fields that do not contain anything +** to return NULL rather than an empty result. Two separators +** side-by-each with no intervening characters at all will be +** returned as NULL if nulls is true; if nulls is false or +** the contents are explicity empty ("") then a 0 length blob +** (if affinity=blob) or 0 length text string will be returned. +** +*/ +/* +** 2016-05-28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains the implementation of an SQLite virtual table for +** reading CSV files. +** +** Usage: +** +** .load ./csv +** CREATE VIRTUAL TABLE temp.csv USING csv(filename=FILENAME); +** SELECT * FROM csv; +** +** The columns are named "c1", "c2", "c3", ... by default. Or the +** application can define its own CREATE TABLE statement using the +** schema= parameter, like this: +** +** CREATE VIRTUAL TABLE temp.csv2 USING csv( +** filename = "../http.log", +** schema = "CREATE TABLE x(date,ipaddr,url,referrer,userAgent)" +** ); +** +** Instead of specifying a file, the text of the CSV can be loaded using +** the data= parameter. +** +** If the columns=N parameter is supplied, then the CSV file is assumed to have +** N columns. If both the columns= and schema= parameters are omitted, then +** the number and names of the columns is determined by the first line of +** the CSV input. +** +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef SQLITE_HAVE_ZLIB +#include +#define fopen gzopen +#define fclose gzclose +#define fread gzfread +#define fseek gzseek +#define ftell gztell +#endif + +#undef LONGDOUBLE_CONSTANT +#undef LONGDOUBLE_TYPE +#if defined(SQLITE_USE_QUADMATH) && defined(__GNUC__) && defined(_WIN64) +#include +#define LONGDOUBLE_TYPE __float128 +#define LONGDOUBLE_CONSTANT(x) x##Q +#define modfl modfq +#define strtold strtoflt128 +#else +#define LONGDOUBLE_TYPE long double +#define LONGDOUBLE_CONSTANT(x) x##L +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** A macro to hint to the compiler that a function should not be +** inlined. +*/ +#if defined(__GNUC__) +#define VSV_NOINLINE __attribute__((noinline)) +#elif defined(_MSC_VER) && _MSC_VER>=1310 +#define VSV_NOINLINE __declspec(noinline) +#else +#define VSV_NOINLINE +#endif + + +/* +** Max size of the error message in a VsvReader +*/ +#define VSV_MXERR 200 + +/* +** Size of the VsvReader input buffer +*/ +#define VSV_INBUFSZ 1024 + +/* +** A context object used when read a VSV file. +*/ +typedef struct VsvReader VsvReader; +struct VsvReader +{ +#ifdef SQLITE_HAVE_ZLIB + gzFile in; /* Read the VSV text from this compressed input stream */ +#else + FILE *in; /* Read the VSV text from this input stream */ +#endif + char *z; /* Accumulated text for a field */ + int n; /* Number of bytes in z */ + int nAlloc; /* Space allocated for z[] */ + int nLine; /* Current line number */ + int bNotFirst; /* True if prior text has been seen */ + int cTerm; /* Character that terminated the most recent field */ + int fsep; /* Field Seperator Character */ + int rsep; /* Record Seperator Character */ + int affinity; /* Perform Affinity Conversions */ + int notNull; /* Have we seen data for field */ + size_t iIn; /* Next unread character in the input buffer */ + size_t nIn; /* Number of characters in the input buffer */ + char *zIn; /* The input buffer */ + char zErr[VSV_MXERR]; /* Error message */ +}; + +/* +** Initialize a VsvReader object +*/ +static void vsv_reader_init(VsvReader *p) +{ + p->in = 0; + p->z = 0; + p->n = 0; + p->nAlloc = 0; + p->nLine = 0; + p->bNotFirst = 0; + p->nIn = 0; + p->zIn = 0; + p->notNull = 0; + p->zErr[0] = 0; +} + +/* +** Close and reset a VsvReader object +*/ +static void vsv_reader_reset(VsvReader *p) +{ + if (p->in) + { + fclose(p->in); + sqlite3_free(p->zIn); + } + sqlite3_free(p->z); + vsv_reader_init(p); +} + +/* +** Report an error on a VsvReader +*/ +static void vsv_errmsg(VsvReader *p, const char *zFormat, ...) +{ + va_list ap; + va_start(ap, zFormat); + sqlite3_vsnprintf(VSV_MXERR, p->zErr, zFormat, ap); + va_end(ap); +} + +/* +** Open the file associated with a VsvReader +** Return the number of errors. +*/ +static int vsv_reader_open( + VsvReader *p, /* The reader to open */ + const char *zFilename, /* Read from this filename */ + const char *zData /* ... or use this data */ + ) +{ + if (zFilename) + { + p->zIn = sqlite3_malloc(VSV_INBUFSZ); + if (p->zIn==0) + { + vsv_errmsg(p, "out of memory"); + return 1; + } + p->in = fopen(zFilename, "rb"); + if (p->in==0) + { + sqlite3_free(p->zIn); + vsv_reader_reset(p); + vsv_errmsg(p, "cannot open '%s' for reading", zFilename); + return 1; + } + } + else + { + assert( p->in==0 ); + p->zIn = (char*)zData; + p->nIn = strlen(zData); + } + return 0; +} + +/* +** The input buffer has overflowed. Refill the input buffer, then +** return the next character +*/ +static VSV_NOINLINE int vsv_getc_refill(VsvReader *p) +{ + size_t got; + + assert( p->iIn>=p->nIn ); /* Only called on an empty input buffer */ + assert( p->in!=0 ); /* Only called if reading from a file */ + + got = fread(p->zIn, 1, VSV_INBUFSZ, p->in); + if (got==0) + { + return EOF; + } + p->nIn = got; + p->iIn = 1; + return p->zIn[0]; +} + +/* +** Return the next character of input. Return EOF at end of input. +*/ +static int vsv_getc(VsvReader *p) +{ + if (p->iIn >= p->nIn) + { + if (p->in!=0) + { + return vsv_getc_refill(p); + } + return EOF; + } + return((unsigned char*)p->zIn)[p->iIn++]; +} + +/* +** Increase the size of p->z and append character c to the end. +** Return 0 on success and non-zero if there is an OOM error +*/ +static VSV_NOINLINE int vsv_resize_and_append(VsvReader *p, char c) +{ + char *zNew; + int nNew = p->nAlloc*2 + 100; + zNew = sqlite3_realloc64(p->z, nNew); + if (zNew) + { + p->z = zNew; + p->nAlloc = nNew; + p->z[p->n++] = c; + return 0; + } + else + { + vsv_errmsg(p, "out of memory"); + return 1; + } +} + +/* +** Append a single character to the VsvReader.z[] array. +** Return 0 on success and non-zero if there is an OOM error +*/ +static int vsv_append(VsvReader *p, char c) +{ + if (p->n>=p->nAlloc-1) + { + return vsv_resize_and_append(p, c); + } + p->z[p->n++] = c; + return 0; +} + +/* +** Read a single field of VSV text. Compatible with rfc4180 and extended +** with the option of having a separator other than ",". +** +** + Input comes from p->in. +** + Store results in p->z of length p->n. Space to hold p->z comes +** from sqlite3_malloc64(). +** + Keep track of the line number in p->nLine. +** + Store the character that terminates the field in p->cTerm. Store +** EOF on end-of-file. +** +** Return 0 at EOF or on OOM. On EOF, the p->cTerm character will have +** been set to EOF. +*/ +static char *vsv_read_one_field(VsvReader *p) +{ + int c; + p->notNull = 0; + p->n = 0; + c = vsv_getc(p); + if (c==EOF) + { + p->cTerm = EOF; + return 0; + } + if (c=='"') + { + int pc, ppc; + int startLine = p->nLine; + p->notNull = 1; + pc = ppc = 0; + while (1) + { + c = vsv_getc(p); + if (c=='\n') + { + p->nLine++; + } + if (c=='"' && pc=='"') + { + pc = ppc; + ppc = 0; + continue; + } + if ( (c==p->fsep && pc=='"') + || (c==p->rsep && pc=='"') + || (p->rsep=='\n' && c=='\n' && pc=='\r' && ppc=='"') + || (c==EOF && pc=='"') + ) + { + do + { + p->n--; + } + while (p->z[p->n]!='"'); + p->cTerm = (char)c; + break; + } + if (pc=='"' && p->rsep=='\n' && c!='\r') + { + vsv_errmsg(p, "line %d: unescaped %c character", p->nLine, '"'); + break; + } + if (c==EOF) + { + vsv_errmsg(p, "line %d: unterminated %c-quoted field\n", startLine, '"'); + p->cTerm = (char)c; + break; + } + if (vsv_append(p, (char)c)) + { + return 0; + } + ppc = pc; + pc = c; + } + } + else + { + /* + ** If this is the first field being parsed and it begins with the + ** UTF-8 BOM (0xEF BB BF) then skip the BOM + */ + if ((c&0xff)==0xef && p->bNotFirst==0) + { + vsv_append(p, (char)c); + c = vsv_getc(p); + if ((c&0xff)==0xbb) + { + vsv_append(p, (char)c); + c = vsv_getc(p); + if ((c&0xff)==0xbf) + { + p->bNotFirst = 1; + p->n = 0; + return vsv_read_one_field(p); + } + } + } + while (c!=EOF && c!=p->rsep && c!=p->fsep) + { + if (c=='\n') + p->nLine++; + if (!p->notNull) + p->notNull = 1; + if (vsv_append(p, (char)c)) + return 0; + c = vsv_getc(p); + } + if (c=='\n') + { + p->nLine++; + } + if (p->n>0 && (p->rsep=='\n' || p->fsep=='\n') && p->z[p->n-1]=='\r') + { + p->n--; + if (p->n==0) + { + p->notNull = 0; + } + } + p->cTerm = (char)c; + } + assert( p->z==0 || p->nnAlloc ); + if (p->z) + { + p->z[p->n] = 0; + } + p->bNotFirst = 1; + return p->z; +} + + +/* +** Forward references to the various virtual table methods implemented +** in this file. +*/ +static int vsvtabCreate(sqlite3*, void*, int, const char*const*, sqlite3_vtab**,char**); +static int vsvtabConnect(sqlite3*, void*, int, const char*const*, sqlite3_vtab**,char**); +static int vsvtabBestIndex(sqlite3_vtab*,sqlite3_index_info*); +static int vsvtabDisconnect(sqlite3_vtab*); +static int vsvtabOpen(sqlite3_vtab*, sqlite3_vtab_cursor**); +static int vsvtabClose(sqlite3_vtab_cursor*); +static int vsvtabFilter(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, int argc, sqlite3_value **argv); +static int vsvtabNext(sqlite3_vtab_cursor*); +static int vsvtabEof(sqlite3_vtab_cursor*); +static int vsvtabColumn(sqlite3_vtab_cursor*,sqlite3_context*,int); +static int vsvtabRowid(sqlite3_vtab_cursor*,sqlite3_int64*); + +/* +** An instance of the VSV virtual table +*/ +typedef struct VsvTable +{ + sqlite3_vtab base; /* Base class. Must be first */ + char *zFilename; /* Name of the VSV file */ + char *zData; /* Raw VSV data in lieu of zFilename */ + long iStart; /* Offset to start of data in zFilename */ + int nCol; /* Number of columns in the VSV file */ + int fsep; /* The field seperator for this VSV file */ + int rsep; /* The record seperator for this VSV file */ + int affinity; /* Perform affinity conversions */ + int nulls; /* Process NULLs */ + int validateUTF8; /* Validate UTF8 */ + unsigned int tstFlags; /* Bit values used for testing */ +} VsvTable; + +/* +** Allowed values for tstFlags +*/ +#define VSVTEST_FIDX 0x0001 /* Pretend that constrained searchs cost less*/ + +/* +** A cursor for the VSV virtual table +*/ +typedef struct VsvCursor +{ + sqlite3_vtab_cursor base; /* Base class. Must be first */ + VsvReader rdr; /* The VsvReader object */ + char **azVal; /* Value of the current row */ + int *aLen; /* Allocation Length of each entry */ + int *dLen; /* Data Length of each entry */ + sqlite3_int64 iRowid; /* The current rowid. Negative for EOF */ +} VsvCursor; + +/* +** Transfer error message text from a reader into a VsvTable +*/ +static void vsv_xfer_error(VsvTable *pTab, VsvReader *pRdr) +{ + sqlite3_free(pTab->base.zErrMsg); + pTab->base.zErrMsg = sqlite3_mprintf("%s", pRdr->zErr); +} + +/* +** This method is the destructor for a VsvTable object. +*/ +static int vsvtabDisconnect(sqlite3_vtab *pVtab) +{ + VsvTable *p = (VsvTable*)pVtab; + sqlite3_free(p->zFilename); + sqlite3_free(p->zData); + sqlite3_free(p); + return SQLITE_OK; +} + +/* +** Skip leading whitespace. Return a pointer to the first non-whitespace +** character, or to the zero terminator if the string has only whitespace +*/ +static const char *vsv_skip_whitespace(const char *z) +{ + while (isspace((unsigned char)z[0])) + { + z++; + } + return z; +} + +/* +** Remove trailing whitespace from the end of string z[] +*/ +static void vsv_trim_whitespace(char *z) +{ + size_t n = strlen(z); + while (n>0 && isspace((unsigned char)z[n])) + { + n--; + } + z[n] = 0; +} + +/* +** Dequote the string +*/ +static void vsv_dequote(char *z) +{ + int j; + char cQuote = z[0]; + size_t i, n; + + if (cQuote!='\'' && cQuote!='"') + { + return; + } + n = strlen(z); + if (n<2 || z[n-1]!=z[0]) + { + return; + } + for (i=1, j=0; izErr. If there are no errors, p->zErr[0]==0. +*/ +static int vsv_string_parameter( + VsvReader *p, /* Leave the error message here, if there is one */ + const char *zParam, /* Parameter we are checking for */ + const char *zArg, /* Raw text of the virtual table argment */ + char **pzVal /* Write the dequoted string value here */ + ) +{ + const char *zValue; + zValue = vsv_parameter(zParam,(int)strlen(zParam),zArg); + if (zValue==0) + { + return 0; + } + p->zErr[0] = 0; + if (*pzVal) + { + vsv_errmsg(p, "more than one '%s' parameter", zParam); + return 1; + } + *pzVal = sqlite3_mprintf("%s", zValue); + if (*pzVal==0) + { + vsv_errmsg(p, "out of memory"); + return 1; + } + vsv_trim_whitespace(*pzVal); + vsv_dequote(*pzVal); + return 1; +} + + +/* +** Return 0 if the argument is false and 1 if it is true. Return -1 if +** we cannot really tell. +*/ +static int vsv_boolean(const char *z) +{ + if (sqlite3_stricmp("yes",z)==0 + || sqlite3_stricmp("on",z)==0 + || sqlite3_stricmp("true",z)==0 + || (z[0]=='1' && z[1]==0) + ) + { + return 1; + } + if (sqlite3_stricmp("no",z)==0 + || sqlite3_stricmp("off",z)==0 + || sqlite3_stricmp("false",z)==0 + || (z[0]=='0' && z[1]==0) + ) + { + return 0; + } + return -1; +} + +/* +** Check to see if the string is of the form: "TAG = BOOLEAN" or just "TAG". +** If it is, set *pValue to be the value of the boolean ("true" if there is +** not "= BOOLEAN" component) and return non-zero. If the input string +** does not begin with TAG, return zero. +*/ +static int vsv_boolean_parameter( + const char *zTag, /* Tag we are looking for */ + int nTag, /* Size of the tag in bytes */ + const char *z, /* Input parameter */ + int *pValue /* Write boolean value here */ + ) +{ + int b; + z = vsv_skip_whitespace(z); + if (strncmp(zTag, z, nTag)!=0) + { + return 0; + } + z = vsv_skip_whitespace(z + nTag); + if (z[0]==0) + { + *pValue = 1; + return 1; + } + if (z[0]!='=') + { + return 0; + } + z = vsv_skip_whitespace(z+1); + b = vsv_boolean(z); + if (b>=0) + { + *pValue = b; + return 1; + } + return 0; +} + +/* +** Convert the seperator character specification into the character code +** Return 1 signifies error, 0 for no error +** +** Recognized inputs: +** any single character +** escaped characters \f \n \t \v +** escaped hex byte \x1e \x1f etc (RS and US respectively) +** +*/ +static int vsv_parse_sep_char(char *in, int dflt, int *out) +{ + if (!in) + { + *out = dflt; + return 0; + } + switch (strlen(in)) + { + case 0: + { + *out = dflt; + return 0; + } + case 1: + { + *out = in[0]; + return 0; + } + case 2: + { + if (in[0] != '\\') + { + return 1; + } + switch (in[1]) + { + case 'f': + { + *out = 12; + return 0; + } + case 'n': + { + *out = 10; + return 0; + } + case 't': + { + *out = 9; + return 0; + } + case 'v': + { + *out = 11; + return 0; + } + } + return 1; + } + case 4: + { + if (sqlite3_strnicmp(in, "\\x", 2) != 0) + { + return 1; + } + if (!isxdigit(in[2]) || !isxdigit(in[3])) + { + return 1; + } + *out = ((in[2] > '9' ? (in[2] & 0x0f) + 9 : in[2] & 0x0f) << 4) + + (in[3] > '9' ? (in[3] & 0x0f) + 9 : in[3] & 0x0f); + return 0; + } + } + return 0; +} + +/* +** Parameters: +** filename=FILENAME Name of file containing VSV content +** data=TEXT Direct VSV content. +** schema=SCHEMA Alternative VSV schema. +** header=YES|NO First row of VSV defines the names of +** columns if "yes". Default "no". +** columns=N Assume the VSV file contains N columns. +** fsep=FSET Field Seperator +** rsep=RSEP Record Seperator +** skip=N skip N records of file (default 0) +** affinity=AFF affinity to apply to ALL columns +** default: none +** none text integer real numeric +** +** Only available if compiled with SQLITE_TEST: +** +** testflags=N Bitmask of test flags. Optional +** +** If schema= is omitted, then the columns are named "c0", "c1", "c2", +** and so forth. If columns=N is omitted, then the file is opened and +** the number of columns in the first row is counted to determine the +** column count. If header=YES, then the first row is skipped. +*/ +static int vsvtabConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr + ) +{ + VsvTable *pNew = 0; /* The VsvTable object to construct */ + int affinity = -1; /* Affinity coercion */ + int bHeader = -1; /* header= flags. -1 means not seen yet */ + int validateUTF8 = -1; /* validateUTF8 flag */ + int rc = SQLITE_OK; /* Result code from this routine */ + int i, j; /* Loop counters */ +#ifdef SQLITE_TEST + int tstFlags = 0; /* Value for testflags=N parameter */ +#endif + int b; /* Value of a boolean parameter */ + int nCol = -99; /* Value of the columns= parameter */ + int nSkip = -1; /* Value of the skip= parameter */ + int bNulls = -1; /* Process Nulls flag */ + VsvReader sRdr; /* A VSV file reader used to store an error + ** message and/or to count the number of columns */ + static const char *azParam[] = { + "filename", "data", "schema", "fsep", "rsep" + }; + char *azPValue[5]; /* Parameter values */ +#define VSV_FILENAME (azPValue[0]) +#define VSV_DATA (azPValue[1]) +#define VSV_SCHEMA (azPValue[2]) +#define VSV_FSEP (azPValue[3]) +#define VSV_RSEP (azPValue[4]) + + + assert( sizeof(azPValue)==sizeof(azParam) ); + memset(&sRdr, 0, sizeof(sRdr)); + memset(azPValue, 0, sizeof(azPValue)); + for (i=3; i=0) + { + vsv_errmsg(&sRdr, "more than one 'header' parameter"); + goto vsvtab_connect_error; + } + bHeader = b; + } + else if (vsv_boolean_parameter("validatetext",12,z,&b)) + { + if (validateUTF8>=0) + { + vsv_errmsg(&sRdr, "more than one 'validatetext' parameter"); + goto vsvtab_connect_error; + } + validateUTF8 = b; + } + else if (vsv_boolean_parameter("nulls",5,z,&b)) + { + if (bNulls>=0) + { + vsv_errmsg(&sRdr, "more than one 'nulls' parameter"); + goto vsvtab_connect_error; + } + bNulls = b; + } + else +#ifdef SQLITE_TEST + if ((zValue = vsv_parameter("testflags",9,z))!=0) + { + tstFlags = (unsigned int)atoi(zValue); + } + else +#endif + if ((zValue = vsv_parameter("columns",7,z))!=0) + { + if (nCol>0) + { + vsv_errmsg(&sRdr, "more than one 'columns' parameter"); + goto vsvtab_connect_error; + } + nCol = atoi(zValue); + if (nCol<=0) + { + vsv_errmsg(&sRdr, "column= value must be positive"); + goto vsvtab_connect_error; + } + } + else if ((zValue = vsv_parameter("skip",4,z))!=0) + { + if (nSkip>0) + { + vsv_errmsg(&sRdr, "more than one 'skip' parameter"); + goto vsvtab_connect_error; + } + nSkip = atoi(zValue); + if (nSkip<=0) + { + vsv_errmsg(&sRdr, "skip= value must be positive"); + goto vsvtab_connect_error; + } + } + else if ((zValue = vsv_parameter("affinity",8,z))!=0) + { + if (affinity>-1) + { + vsv_errmsg(&sRdr, "more than one 'affinity' parameter"); + goto vsvtab_connect_error; + } + if (sqlite3_strnicmp(zValue,"none",4)==0) affinity=0; + else if (sqlite3_strnicmp(zValue,"blob",4)==0) affinity=1; + else if (sqlite3_strnicmp(zValue,"text",4)==0) affinity=2; + else if (sqlite3_strnicmp(zValue,"integer",7)==0) affinity=3; + else if (sqlite3_strnicmp(zValue,"real",4)==0) affinity=4; + else if (sqlite3_strnicmp(zValue,"numeric",7)==0) affinity=5; + else + { + vsv_errmsg(&sRdr, "unknown affinity: '%s'", zValue); + goto vsvtab_connect_error; + } + } + else + { + vsv_errmsg(&sRdr, "bad parameter: '%s'", z); + goto vsvtab_connect_error; + } + } + if (affinity==-1) + { + affinity = 0; + } + if (bNulls==-1) + { + bNulls = 0; + } + if (validateUTF8==-1) + { + validateUTF8 = 0; + } + if ((VSV_FILENAME==0)==(VSV_DATA==0)) + { + vsv_errmsg(&sRdr, "must specify either filename= or data= but not both"); + goto vsvtab_connect_error; + } + if (vsv_parse_sep_char(VSV_FSEP, ',', &(sRdr.fsep))) + { + vsv_errmsg(&sRdr, "cannot parse fsep: '%s'", VSV_FSEP); + goto vsvtab_connect_error; + } + if (vsv_parse_sep_char(VSV_RSEP, '\n', &(sRdr.rsep))) + { + vsv_errmsg(&sRdr, "cannot parse rsep: '%s'", VSV_RSEP); + goto vsvtab_connect_error; + } + + + if ((nCol <= 0 || bHeader == 1) && vsv_reader_open(&sRdr, VSV_FILENAME, VSV_DATA)) + { + goto vsvtab_connect_error; + } + pNew = sqlite3_malloc( sizeof(*pNew) ); + *ppVtab = (sqlite3_vtab*)pNew; + if (pNew==0) + { + goto vsvtab_connect_oom; + } + memset(pNew, 0, sizeof(*pNew)); + pNew->fsep = sRdr.fsep; + pNew->rsep = sRdr.rsep; + pNew->affinity = affinity; + pNew->validateUTF8 = validateUTF8; + pNew->nulls = bNulls; + if (VSV_SCHEMA==0) + { + sqlite3_str *pStr = sqlite3_str_new(0); + char *zSep = ""; + int iCol = 0; + sqlite3_str_appendf(pStr, "CREATE TABLE x("); + if (nCol<0 && bHeader<1) + { + nCol = 0; + do + { + vsv_read_one_field(&sRdr); + nCol++; + } + while (sRdr.cTerm==sRdr.fsep); + } + if (nCol>0 && bHeader<1) + { + for (iCol=0; iCol0 && iColnCol = nCol; + if (nSkip>0) + { + int tskip = nSkip + (bHeader==1); + vsv_reader_reset(&sRdr); + if (vsv_reader_open(&sRdr, VSV_FILENAME, VSV_DATA)) + { + goto vsvtab_connect_error; + } + do + { + do + { + if (!vsv_read_one_field(&sRdr)) + goto vsvtab_connect_error; + } + while (sRdr.cTerm==sRdr.fsep); + tskip--; + } + while (tskip>0 && sRdr.cTerm==sRdr.rsep); + if (tskip>0) + { + vsv_errmsg(&sRdr, "premature end of file during skip"); + goto vsvtab_connect_error; + } + } + pNew->zFilename = VSV_FILENAME; VSV_FILENAME = 0; + pNew->zData = VSV_DATA; VSV_DATA = 0; +#ifdef SQLITE_TEST + pNew->tstFlags = tstFlags; +#endif + if (bHeader!=1 && nSkip<1) + { + pNew->iStart = 0; + } + else if (pNew->zData) + { + pNew->iStart = (int)sRdr.iIn; + } + else + { + pNew->iStart = (int)(ftell(sRdr.in) - sRdr.nIn + sRdr.iIn); + } + vsv_reader_reset(&sRdr); + rc = sqlite3_declare_vtab(db, VSV_SCHEMA); + if (rc) + { + vsv_errmsg(&sRdr, "bad schema: '%s' - %s", VSV_SCHEMA, sqlite3_errmsg(db)); + goto vsvtab_connect_error; + } + for (i=0; ibase); + } + for (i=0; ibase.pVtab; + int i; + for (i=0; inCol; i++) + { + sqlite3_free(pCur->azVal[i]); + pCur->azVal[i] = 0; + pCur->aLen[i] = 0; + pCur->dLen[i] = -1; + } +} + +/* +** The xConnect and xCreate methods do the same thing, but they must be +** different so that the virtual table is not an eponymous virtual table. +*/ +static int vsvtabCreate( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr + ) +{ + return vsvtabConnect(db, pAux, argc, argv, ppVtab, pzErr); +} + +/* +** Destructor for a VsvCursor. +*/ +static int vsvtabClose(sqlite3_vtab_cursor *cur) +{ + VsvCursor *pCur = (VsvCursor*)cur; + vsvtabCursorRowReset(pCur); + vsv_reader_reset(&pCur->rdr); + sqlite3_free(cur); + return SQLITE_OK; +} + +/* +** Constructor for a new VsvTable cursor object. +*/ +static int vsvtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor) +{ + VsvTable *pTab = (VsvTable*)p; + VsvCursor *pCur; + size_t nByte; + nByte = sizeof(*pCur) + (sizeof(char*)+(2*sizeof(int)))*pTab->nCol; + pCur = sqlite3_malloc64( nByte ); + if (pCur==0) + return SQLITE_NOMEM; + memset(pCur, 0, nByte); + pCur->azVal = (char**)&pCur[1]; + pCur->aLen = (int*)&pCur->azVal[pTab->nCol]; + pCur->dLen = (int*)&pCur->aLen[pTab->nCol]; + pCur->rdr.fsep = pTab->fsep; + pCur->rdr.rsep = pTab->rsep; + pCur->rdr.affinity = pTab->affinity; + *ppCursor = &pCur->base; + if (vsv_reader_open(&pCur->rdr, pTab->zFilename, pTab->zData)) + { + vsv_xfer_error(pTab, &pCur->rdr); + return SQLITE_ERROR; + } + return SQLITE_OK; +} + + +/* +** Advance a VsvCursor to its next row of input. +** Set the EOF marker if we reach the end of input. +*/ +static int vsvtabNext(sqlite3_vtab_cursor *cur) +{ + VsvCursor *pCur = (VsvCursor*)cur; + VsvTable *pTab = (VsvTable*)cur->pVtab; + int i = 0; + char *z; + do + { + z = vsv_read_one_field(&pCur->rdr); + if (z==0) + { + if (inCol) + pCur->dLen[i] = -1; + } + else if (inCol) + { + if (pCur->aLen[i] < pCur->rdr.n+1) + { + char *zNew = sqlite3_realloc64(pCur->azVal[i], pCur->rdr.n+1); + if (zNew==0) + { + z = 0; + vsv_errmsg(&pCur->rdr, "out of memory"); + vsv_xfer_error(pTab, &pCur->rdr); + break; + } + pCur->azVal[i] = zNew; + pCur->aLen[i] = pCur->rdr.n+1; + } + if (!pCur->rdr.notNull && pTab->nulls) + { + pCur->dLen[i] = -1; + } + else + { + pCur->dLen[i] = pCur->rdr.n; + memcpy(pCur->azVal[i], z, pCur->rdr.n+1); + } + i++; + } + } + while (pCur->rdr.cTerm==pCur->rdr.fsep); + if ((pCur->rdr.cTerm==EOF && i==0)) + { + pCur->iRowid = -1; + } + else + { + pCur->iRowid++; + while (inCol) + { + pCur->dLen[i] = -1; + i++; + } + } + return SQLITE_OK; +} + +/* +** +** Determine affinity of field +** +** ignore leading space +** then may have + or - +** then may have digits or . (if . found then type=real) +** then may have digits (if another . then not number) +** then may have e (if found then type=real) +** then may have + or - +** then may have digits +** then may have trailing space +*/ +static int vsv_isValidNumber(char *arg) +{ + char *start; + char *stop; + int isValid = 0; + int hasDigit = 0; + + start = arg; + stop = arg + strlen(arg) - 1; + while (start <= stop && *start==' ') // strip spaces from begining + { + start++; + } + while (start <= stop && *stop==' ') // strip spaces from end + { + stop--; + } + if (start > stop) + { + goto vsv_end_isValidNumber; + } + if (start <= stop && (*start=='+' || *start=='-')) // may have + or - + { + start++; + } + if (start <= stop && isdigit(*start)) // must have a digit to be valid + { + hasDigit = 1; + isValid = 1; + } + while (start <= stop && isdigit(*start)) // bunch of digits + { + start++; + } + if (start <= stop && *start=='.') // may have . + { + isValid = 2; + start++; + } + if (start <= stop && isdigit(*start)) + { + hasDigit = 1; + } + while (start <= stop && isdigit(*start)) // bunch of digits + { + start++; + } + if (!hasDigit) // no digits then invalid + { + isValid = 0; + goto vsv_end_isValidNumber; + } + if (start <= stop && (*start=='e' || *start=='E')) // may have 'e' or 'E' + { + isValid = 3; + start++; + } + if (start <= stop && isValid == 3 && (*start == '+' || *start == '-')) + { + start++; + } + if (start <= stop && isValid == 3 && isdigit(*start)) + { + isValid = 2; + } + while (start <= stop && isdigit(*start)) // bunch of digits + { + start++; + } + if (isValid == 3) + { + isValid = 0; + } +vsv_end_isValidNumber: + if (start <= stop) + { + isValid = 0; + } + return isValid; +} + + +/* +** Validate UTF-8 +** Return -1 if invalid else length +*/ +static long long vsv_utf8IsValid(char *string) +{ + long long length = 0; + unsigned char *start; + int trailing = 0; + unsigned char c; + + start = (unsigned char *)string; + while ((c = *start)) + { + if (trailing) + { + if ((c & 0xC0) == 0x80) + { + trailing--; + start++; + length++; + continue; + } + else + { + length = -1; + break; + } + } + if ((c & 0x80) == 0) + { + start++; + length++; + continue; + } + if ((c & 0xE0) == 0xC0) + { + trailing = 1; + start++; + length++; + continue; + } + if ((c & 0xF0) == 0xE0) + { + trailing = 2; + start++; + length++; + continue; + } + if ((c & 0xF8) == 0xF0) + { + trailing = 3; + start++; + length++; + continue; + } +#if 0 // UTF-8 does not encode sequences longer than 4 bytes (yet) + if ((c & 0xFC) == 0xF8) + { + trailing = 4; + start++; + length++; + continue; + } + if ((c & 0xFE) == 0xFC) + { + trailing = 5; + start++; + length++; + continue; + } + if ((c & 0xFF) == 0xFE) + { + trailing = 6; + start++; + length++; + continue; + } + if ((c & 0xFF) == 0xFF) + { + trailing = 7; + start++; + length++; + continue; + } +#endif + length = -1; + break; + } + return length; +} + +/* +** Return values of columns for the row at which the VsvCursor +** is currently pointing. +*/ +static int vsvtabColumn( + sqlite3_vtab_cursor *cur, /* The cursor */ + sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ + int i /* Which column to return */ + ) +{ + VsvCursor *pCur = (VsvCursor*)cur; + VsvTable *pTab = (VsvTable*)cur->pVtab; + long long dLen = pCur->dLen[i]; + long long length = 0; + static int hasExtended = 0; + + if (i>=0 && inCol && pCur->azVal[i]!=0 && dLen>-1) + { + switch (pTab->affinity) + { + case 0: + { + if (pTab->validateUTF8) + { + length = vsv_utf8IsValid(pCur->azVal[i]); + if (length == dLen) + { + sqlite3_result_text(ctx, pCur->azVal[i], dLen, SQLITE_TRANSIENT); + } + else + { + sqlite3_result_error(ctx, "Invalid UTF8 Data", -1); + } + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], -1, SQLITE_TRANSIENT); + } + break; + } + case 1: + { + sqlite3_result_blob(ctx, pCur->azVal[i], dLen, SQLITE_TRANSIENT); + break; + } + case 2: + { + if (pTab->validateUTF8) + { + length = vsv_utf8IsValid(pCur->azVal[i]); + if (length < dLen) + { + sqlite3_result_blob(ctx, pCur->azVal[i], dLen, SQLITE_TRANSIENT); + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], length, SQLITE_TRANSIENT); + } + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], -1, SQLITE_TRANSIENT); + } + break; + } + case 3: + { + switch (vsv_isValidNumber(pCur->azVal[i])) + { + case 1: + { + sqlite3_result_int64(ctx, strtoll(pCur->azVal[i], 0, 10)); + break; + } + default: + { + if (pTab->validateUTF8) + { + length = vsv_utf8IsValid(pCur->azVal[i]); + if (length < dLen) + { + sqlite3_result_blob(ctx, pCur->azVal[i], dLen, SQLITE_TRANSIENT); + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], length, SQLITE_TRANSIENT); + } + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], -1, SQLITE_TRANSIENT); + } + break; + } + } + break; + } + case 4: + { + switch (vsv_isValidNumber(pCur->azVal[i])) + { + case 1: + case 2: + { + sqlite3_result_double(ctx, strtod(pCur->azVal[i], 0)); + break; + } + default: + { + if (pTab->validateUTF8) + { + length = vsv_utf8IsValid(pCur->azVal[i]); + if (length < dLen) + { + sqlite3_result_blob(ctx, pCur->azVal[i], dLen, SQLITE_TRANSIENT); + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], length, SQLITE_TRANSIENT); + } + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], -1, SQLITE_TRANSIENT); + } + break; + } + } + break; + } + case 5: + { + switch (vsv_isValidNumber(pCur->azVal[i])) + { + case 1: + { + sqlite_int64 ival; + + ival = strtoll(pCur->azVal[i], 0, 10); + if (ival > LLONG_MIN && ival < LLONG_MAX) { + sqlite3_result_int64(ctx, ival); + break; + } + + } + case 2: + { + LONGDOUBLE_TYPE dv, fp, ip; + +#if defined(SQLITE_USE_QUADMATH) && defined(__GNUC__) && defined(_WIN64) + if (!hasExtended) hasExtended = 1; +#else + if (!hasExtended) { + if (sizeof(long double) > sizeof(double)) { + volatile unsigned long long i = ULLONG_MAX; + volatile long double l; + volatile double d; + l = i; + d = i; + hasExtended = (d == l) ? -1 : 1; + } else { + hasExtended = -1; + } + } +#endif + + dv = strtold(pCur->azVal[i], 0); + fp = modfl(dv, &ip); + if (hasExtended<0) + { + if (fp==0.0L && ip >= -9007199254740991LL && dv <= 9007199254740991LL) + { + sqlite3_result_int64(ctx, (long long)ip); + } + else + { + sqlite3_result_double(ctx, dv); + } + } + else + { + if (fp==0.0L && ip >= LLONG_MIN && ip <= LLONG_MAX) + { + sqlite3_result_int64(ctx, (long long)ip); + } + else + { + sqlite3_result_double(ctx, dv); + } + } + break; + } + default: + { + if (pTab->validateUTF8) + { + length = vsv_utf8IsValid(pCur->azVal[i]); + if (length < dLen) + { + sqlite3_result_blob(ctx, pCur->azVal[i], dLen, SQLITE_TRANSIENT); + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], length, SQLITE_TRANSIENT); + } + } + else + { + sqlite3_result_text(ctx, pCur->azVal[i], -1, SQLITE_TRANSIENT); + } + break; + } + } + } + } + } + return SQLITE_OK; +} + +/* +** Return the rowid for the current row. +*/ +static int vsvtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid) +{ + VsvCursor *pCur = (VsvCursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** Return TRUE if the cursor has been moved off of the last +** row of output. +*/ +static int vsvtabEof(sqlite3_vtab_cursor *cur) +{ + VsvCursor *pCur = (VsvCursor*)cur; + return pCur->iRowid<0; +} + +/* +** Only a full table scan is supported. So xFilter simply rewinds to +** the beginning. +*/ +static int vsvtabFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv + ) +{ + VsvCursor *pCur = (VsvCursor*)pVtabCursor; + VsvTable *pTab = (VsvTable*)pVtabCursor->pVtab; + pCur->iRowid = 0; + + /* Ensure the field buffer is always allocated. Otherwise, if the + ** first field is zero bytes in size, this may be mistaken for an OOM + ** error in csvtabNext(). */ + if( vsv_append(&pCur->rdr, 0) ) return SQLITE_NOMEM; + + if (pCur->rdr.in==0) + { + assert( pCur->rdr.zIn==pTab->zData ); + assert( pTab->iStart>=0 ); + assert( (size_t)pTab->iStart<=pCur->rdr.nIn ); + pCur->rdr.iIn = pTab->iStart; + } + else + { + fseek(pCur->rdr.in, pTab->iStart, SEEK_SET); + pCur->rdr.iIn = 0; + pCur->rdr.nIn = 0; + } + return vsvtabNext(pVtabCursor); +} + +/* +** Only a forward full table scan is supported. xBestIndex is mostly +** a no-op. If VSVTEST_FIDX is set, then the presence of equality +** constraints lowers the estimated cost, which is fiction, but is useful +** for testing certain kinds of virtual table behavior. +*/ +static int vsvtabBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo + ) +{ + pIdxInfo->estimatedCost = 1000000; +#ifdef SQLITE_TEST + if ((((VsvTable*)tab)->tstFlags & VSVTEST_FIDX)!=0) + { + /* The usual (and sensible) case is to always do a full table scan. + ** The code in this branch only runs when testflags=1. This code + ** generates an artifical and unrealistic plan which is useful + ** for testing virtual table logic but is not helpful to real applications. + ** + ** Any ==, LIKE, or GLOB constraint is marked as usable by the virtual + ** table (even though it is not) and the cost of running the virtual table + ** is reduced from 1 million to just 10. The constraints are *not* marked + ** as omittable, however, so the query planner should still generate a + ** plan that gives a correct answer, even if they plan is not optimal. + */ + int i; + int nConst = 0; + for (i=0; inConstraint; i++) + { + unsigned char op; + if (pIdxInfo->aConstraint[i].usable==0) continue; + op = pIdxInfo->aConstraint[i].op; + if (op==SQLITE_INDEX_CONSTRAINT_EQ + || op==SQLITE_INDEX_CONSTRAINT_LIKE + || op==SQLITE_INDEX_CONSTRAINT_GLOB + ) + { + pIdxInfo->estimatedCost = 10; + pIdxInfo->aConstraintUsage[nConst].argvIndex = nConst+1; + nConst++; + } + } + } +#endif + return SQLITE_OK; +} + + +static sqlite3_module VsvModule = { + 0, /* iVersion */ + vsvtabCreate, /* xCreate */ + vsvtabConnect, /* xConnect */ + vsvtabBestIndex, /* xBestIndex */ + vsvtabDisconnect, /* xDisconnect */ + vsvtabDisconnect, /* xDestroy */ + vsvtabOpen, /* xOpen - open a cursor */ + vsvtabClose, /* xClose - close a cursor */ + vsvtabFilter, /* xFilter - configure scan constraints */ + vsvtabNext, /* xNext - advance a cursor */ + vsvtabEof, /* xEof - check for end of scan */ + vsvtabColumn, /* xColumn - read data */ + vsvtabRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; + +#ifdef SQLITE_TEST +/* +** For virtual table testing, make a version of the VSV virtual table +** available that has an xUpdate function. But the xUpdate always returns +** SQLITE_READONLY since the VSV file is not really writable. +*/ +static int vsvtabUpdate(sqlite3_vtab *p,int n,sqlite3_value**v,sqlite3_int64*x) +{ + return SQLITE_READONLY; +} +static sqlite3_module VsvModuleFauxWrite = { + 0, /* iVersion */ + vsvtabCreate, /* xCreate */ + vsvtabConnect, /* xConnect */ + vsvtabBestIndex, /* xBestIndex */ + vsvtabDisconnect, /* xDisconnect */ + vsvtabDisconnect, /* xDestroy */ + vsvtabOpen, /* xOpen - open a cursor */ + vsvtabClose, /* xClose - close a cursor */ + vsvtabFilter, /* xFilter - configure scan constraints */ + vsvtabNext, /* xNext - advance a cursor */ + vsvtabEof, /* xEof - check for end of scan */ + vsvtabColumn, /* xColumn - read data */ + vsvtabRowid, /* xRowid - read data */ + vsvtabUpdate, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ +}; +#endif /* SQLITE_TEST */ + +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ + +/* +** This routine is called when the extension is loaded. The new +** VSV virtual table module is registered with the calling database +** connection. +*/ +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_vsv_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi + ) +{ +#ifndef SQLITE_OMIT_VIRTUALTABLE + int rc; + SQLITE_EXTENSION_INIT2(pApi); + rc = sqlite3_create_module(db, "vsv", &VsvModule, 0); +#ifdef SQLITE_TEST + if (rc==SQLITE_OK) + { + rc = sqlite3_create_module(db, "vsv_wr", &VsvModuleFauxWrite, 0); + } +#endif + return rc; +#else + return SQLITE_OK; +#endif +} + +#undef modfl +#undef strtold + +/*** End of #include "vsv.c" ***/ + +#endif + +/* +** SHA3 +*/ +#ifdef SQLITE_ENABLE_SHA3 +/* Prototype for initialization function of SHA3 extension */ +SQLITE_API +int sqlite3_shathree_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); +/* #include "shathree.c" */ +/*** Begin of #include "shathree.c" ***/ +/* +** 2017-03-08 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This SQLite extension implements functions that compute SHA3 hashes +** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard. +** Three SQL functions are implemented: +** +** sha3(X,SIZE) +** sha3_agg(Y,SIZE) +** sha3_query(Z,SIZE) +** +** The sha3(X) function computes the SHA3 hash of the input X, or NULL if +** X is NULL. If inputs X is text, the UTF-8 rendering of that text is +** used to compute the hash. If X is a BLOB, then the binary data of the +** blob is used to compute the hash. If X is an integer or real number, +** then that number if converted into UTF-8 text and the hash is computed +** over the text. +** +** The sha3_agg(Y) function computes the SHA3 hash of all Y inputs. Since +** order is important for the hash, it is recommended that the Y expression +** by followed by an ORDER BY clause to guarantee that the inputs occur +** in the desired order. +** +** The sha3_query(Y) function evaluates all queries in the SQL statements of Y +** and returns a hash of their results. +** +** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm +** is used. If SIZE is included it must be one of the integers 224, 256, +** 384, or 512, to determine SHA3 hash variant that is computed. +** +** Because the sha3_agg() and sha3_query() functions compute a hash over +** multiple values, the values are encode to use include type information. +** +** In sha3_agg(), the sequence of bytes that gets hashed for each input +** Y depends on the datatype of Y: +** +** typeof(Y)='null' A single "N" is hashed. (One byte) +** +** typeof(Y)='integer' The data hash is the character "I" followed +** by an 8-byte big-endian binary of the +** 64-bit signed integer. (Nine bytes total.) +** +** typeof(Y)='real' The character "F" followed by an 8-byte +** big-ending binary of the double. (Nine +** bytes total.) +** +** typeof(Y)='text' The hash is over prefix "Tnnn:" followed +** by the UTF8 encoding of the text. The "nnn" +** in the prefix is the minimum-length decimal +** representation of the octet_length of the text. +** Notice the ":" at the end of the prefix, which +** is needed to separate the prefix from the +** content in cases where the content starts +** with a digit. +** +** typeof(Y)='blob' The hash is taken over prefix "Bnnn:" followed +** by the binary content of the blob. The "nnn" +** in the prefix is the minimum-length decimal +** representation of the byte-length of the blob. +** +** According to the rules above, all of the following SELECT statements +** should return TRUE: +** +** SELECT sha3(1) = sha3('1'); +** +** SELECT sha3('hello') = sha3(x'68656c6c6f'); +** +** WITH a(x) AS (VALUES('xyzzy')) +** SELECT sha3_agg(x) = sha3('T5:xyzzy') FROM a; +** +** WITH a(x) AS (VALUES(x'010203')) +** SELECT sha3_agg(x) = sha3(x'42333a010203') FROM a; +** +** WITH a(x) AS (VALUES(0x123456)) +** SELECT sha3_agg(x) = sha3(x'490000000000123456') FROM a; +** +** WITH a(x) AS (VALUES(100.015625)) +** SELECT sha3_agg(x) = sha3(x'464059010000000000') FROM a; +** +** WITH a(x) AS (VALUES(NULL)) +** SELECT sha3_agg(x) = sha3('N') FROM a; +** +** +** In sha3_query(), individual column values are encoded as with +** sha3_agg(), but with the addition that a single "R" character is +** inserted at the start of each row. +** +** Note that sha3_agg() hashes rows for which Y is NULL. Add a FILTER +** clause if NULL rows should be excluded: +** +** SELECT sha3_agg(x ORDER BY rowid) FILTER(WHERE x NOT NULL) FROM t1; +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +#include +#include +#include + +#ifndef SQLITE_AMALGAMATION +typedef sqlite3_uint64 u64; +#endif /* SQLITE_AMALGAMATION */ + +/****************************************************************************** +** The Hash Engine +*/ +/* +** Macros to determine whether the machine is big or little endian, +** and whether or not that determination is run-time or compile-time. +** +** For best performance, an attempt is made to guess at the byte-order +** using C-preprocessor macros. If that is unsuccessful, or if +** -DSHA3_BYTEORDER=0 is set, then byte-order is determined +** at run-time. +*/ +#ifndef SHA3_BYTEORDER +# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ + defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ + defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ + defined(__arm__) +# define SHA3_BYTEORDER 1234 +# elif defined(sparc) || defined(__ppc__) +# define SHA3_BYTEORDER 4321 +# else +# define SHA3_BYTEORDER 0 +# endif +#endif + + +/* +** State structure for a SHA3 hash in progress +*/ +typedef struct SHA3Context SHA3Context; +struct SHA3Context { + union { + u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */ + unsigned char x[1600]; /* ... or 1600 bytes */ + } u; + unsigned nRate; /* Bytes of input accepted per Keccak iteration */ + unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */ + unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */ + unsigned iSize; /* 224, 256, 358, or 512 */ +}; + +/* +** A single step of the Keccak mixing function for a 1600-bit state +*/ +static void KeccakF1600Step(SHA3Context *p){ + int i; + u64 b0, b1, b2, b3, b4; + u64 c0, c1, c2, c3, c4; + u64 d0, d1, d2, d3, d4; + static const u64 RC[] = { + 0x0000000000000001ULL, 0x0000000000008082ULL, + 0x800000000000808aULL, 0x8000000080008000ULL, + 0x000000000000808bULL, 0x0000000080000001ULL, + 0x8000000080008081ULL, 0x8000000000008009ULL, + 0x000000000000008aULL, 0x0000000000000088ULL, + 0x0000000080008009ULL, 0x000000008000000aULL, + 0x000000008000808bULL, 0x800000000000008bULL, + 0x8000000000008089ULL, 0x8000000000008003ULL, + 0x8000000000008002ULL, 0x8000000000000080ULL, + 0x000000000000800aULL, 0x800000008000000aULL, + 0x8000000080008081ULL, 0x8000000000008080ULL, + 0x0000000080000001ULL, 0x8000000080008008ULL + }; +# define a00 (p->u.s[0]) +# define a01 (p->u.s[1]) +# define a02 (p->u.s[2]) +# define a03 (p->u.s[3]) +# define a04 (p->u.s[4]) +# define a10 (p->u.s[5]) +# define a11 (p->u.s[6]) +# define a12 (p->u.s[7]) +# define a13 (p->u.s[8]) +# define a14 (p->u.s[9]) +# define a20 (p->u.s[10]) +# define a21 (p->u.s[11]) +# define a22 (p->u.s[12]) +# define a23 (p->u.s[13]) +# define a24 (p->u.s[14]) +# define a30 (p->u.s[15]) +# define a31 (p->u.s[16]) +# define a32 (p->u.s[17]) +# define a33 (p->u.s[18]) +# define a34 (p->u.s[19]) +# define a40 (p->u.s[20]) +# define a41 (p->u.s[21]) +# define a42 (p->u.s[22]) +# define a43 (p->u.s[23]) +# define a44 (p->u.s[24]) +# define ROL64(a,x) ((a<>(64-x))) + + for(i=0; i<24; i+=4){ + c0 = a00^a10^a20^a30^a40; + c1 = a01^a11^a21^a31^a41; + c2 = a02^a12^a22^a32^a42; + c3 = a03^a13^a23^a33^a43; + c4 = a04^a14^a24^a34^a44; + d0 = c4^ROL64(c1, 1); + d1 = c0^ROL64(c2, 1); + d2 = c1^ROL64(c3, 1); + d3 = c2^ROL64(c4, 1); + d4 = c3^ROL64(c0, 1); + + b0 = (a00^d0); + b1 = ROL64((a11^d1), 44); + b2 = ROL64((a22^d2), 43); + b3 = ROL64((a33^d3), 21); + b4 = ROL64((a44^d4), 14); + a00 = b0 ^((~b1)& b2 ); + a00 ^= RC[i]; + a11 = b1 ^((~b2)& b3 ); + a22 = b2 ^((~b3)& b4 ); + a33 = b3 ^((~b4)& b0 ); + a44 = b4 ^((~b0)& b1 ); + + b2 = ROL64((a20^d0), 3); + b3 = ROL64((a31^d1), 45); + b4 = ROL64((a42^d2), 61); + b0 = ROL64((a03^d3), 28); + b1 = ROL64((a14^d4), 20); + a20 = b0 ^((~b1)& b2 ); + a31 = b1 ^((~b2)& b3 ); + a42 = b2 ^((~b3)& b4 ); + a03 = b3 ^((~b4)& b0 ); + a14 = b4 ^((~b0)& b1 ); + + b4 = ROL64((a40^d0), 18); + b0 = ROL64((a01^d1), 1); + b1 = ROL64((a12^d2), 6); + b2 = ROL64((a23^d3), 25); + b3 = ROL64((a34^d4), 8); + a40 = b0 ^((~b1)& b2 ); + a01 = b1 ^((~b2)& b3 ); + a12 = b2 ^((~b3)& b4 ); + a23 = b3 ^((~b4)& b0 ); + a34 = b4 ^((~b0)& b1 ); + + b1 = ROL64((a10^d0), 36); + b2 = ROL64((a21^d1), 10); + b3 = ROL64((a32^d2), 15); + b4 = ROL64((a43^d3), 56); + b0 = ROL64((a04^d4), 27); + a10 = b0 ^((~b1)& b2 ); + a21 = b1 ^((~b2)& b3 ); + a32 = b2 ^((~b3)& b4 ); + a43 = b3 ^((~b4)& b0 ); + a04 = b4 ^((~b0)& b1 ); + + b3 = ROL64((a30^d0), 41); + b4 = ROL64((a41^d1), 2); + b0 = ROL64((a02^d2), 62); + b1 = ROL64((a13^d3), 55); + b2 = ROL64((a24^d4), 39); + a30 = b0 ^((~b1)& b2 ); + a41 = b1 ^((~b2)& b3 ); + a02 = b2 ^((~b3)& b4 ); + a13 = b3 ^((~b4)& b0 ); + a24 = b4 ^((~b0)& b1 ); + + c0 = a00^a20^a40^a10^a30; + c1 = a11^a31^a01^a21^a41; + c2 = a22^a42^a12^a32^a02; + c3 = a33^a03^a23^a43^a13; + c4 = a44^a14^a34^a04^a24; + d0 = c4^ROL64(c1, 1); + d1 = c0^ROL64(c2, 1); + d2 = c1^ROL64(c3, 1); + d3 = c2^ROL64(c4, 1); + d4 = c3^ROL64(c0, 1); + + b0 = (a00^d0); + b1 = ROL64((a31^d1), 44); + b2 = ROL64((a12^d2), 43); + b3 = ROL64((a43^d3), 21); + b4 = ROL64((a24^d4), 14); + a00 = b0 ^((~b1)& b2 ); + a00 ^= RC[i+1]; + a31 = b1 ^((~b2)& b3 ); + a12 = b2 ^((~b3)& b4 ); + a43 = b3 ^((~b4)& b0 ); + a24 = b4 ^((~b0)& b1 ); + + b2 = ROL64((a40^d0), 3); + b3 = ROL64((a21^d1), 45); + b4 = ROL64((a02^d2), 61); + b0 = ROL64((a33^d3), 28); + b1 = ROL64((a14^d4), 20); + a40 = b0 ^((~b1)& b2 ); + a21 = b1 ^((~b2)& b3 ); + a02 = b2 ^((~b3)& b4 ); + a33 = b3 ^((~b4)& b0 ); + a14 = b4 ^((~b0)& b1 ); + + b4 = ROL64((a30^d0), 18); + b0 = ROL64((a11^d1), 1); + b1 = ROL64((a42^d2), 6); + b2 = ROL64((a23^d3), 25); + b3 = ROL64((a04^d4), 8); + a30 = b0 ^((~b1)& b2 ); + a11 = b1 ^((~b2)& b3 ); + a42 = b2 ^((~b3)& b4 ); + a23 = b3 ^((~b4)& b0 ); + a04 = b4 ^((~b0)& b1 ); + + b1 = ROL64((a20^d0), 36); + b2 = ROL64((a01^d1), 10); + b3 = ROL64((a32^d2), 15); + b4 = ROL64((a13^d3), 56); + b0 = ROL64((a44^d4), 27); + a20 = b0 ^((~b1)& b2 ); + a01 = b1 ^((~b2)& b3 ); + a32 = b2 ^((~b3)& b4 ); + a13 = b3 ^((~b4)& b0 ); + a44 = b4 ^((~b0)& b1 ); + + b3 = ROL64((a10^d0), 41); + b4 = ROL64((a41^d1), 2); + b0 = ROL64((a22^d2), 62); + b1 = ROL64((a03^d3), 55); + b2 = ROL64((a34^d4), 39); + a10 = b0 ^((~b1)& b2 ); + a41 = b1 ^((~b2)& b3 ); + a22 = b2 ^((~b3)& b4 ); + a03 = b3 ^((~b4)& b0 ); + a34 = b4 ^((~b0)& b1 ); + + c0 = a00^a40^a30^a20^a10; + c1 = a31^a21^a11^a01^a41; + c2 = a12^a02^a42^a32^a22; + c3 = a43^a33^a23^a13^a03; + c4 = a24^a14^a04^a44^a34; + d0 = c4^ROL64(c1, 1); + d1 = c0^ROL64(c2, 1); + d2 = c1^ROL64(c3, 1); + d3 = c2^ROL64(c4, 1); + d4 = c3^ROL64(c0, 1); + + b0 = (a00^d0); + b1 = ROL64((a21^d1), 44); + b2 = ROL64((a42^d2), 43); + b3 = ROL64((a13^d3), 21); + b4 = ROL64((a34^d4), 14); + a00 = b0 ^((~b1)& b2 ); + a00 ^= RC[i+2]; + a21 = b1 ^((~b2)& b3 ); + a42 = b2 ^((~b3)& b4 ); + a13 = b3 ^((~b4)& b0 ); + a34 = b4 ^((~b0)& b1 ); + + b2 = ROL64((a30^d0), 3); + b3 = ROL64((a01^d1), 45); + b4 = ROL64((a22^d2), 61); + b0 = ROL64((a43^d3), 28); + b1 = ROL64((a14^d4), 20); + a30 = b0 ^((~b1)& b2 ); + a01 = b1 ^((~b2)& b3 ); + a22 = b2 ^((~b3)& b4 ); + a43 = b3 ^((~b4)& b0 ); + a14 = b4 ^((~b0)& b1 ); + + b4 = ROL64((a10^d0), 18); + b0 = ROL64((a31^d1), 1); + b1 = ROL64((a02^d2), 6); + b2 = ROL64((a23^d3), 25); + b3 = ROL64((a44^d4), 8); + a10 = b0 ^((~b1)& b2 ); + a31 = b1 ^((~b2)& b3 ); + a02 = b2 ^((~b3)& b4 ); + a23 = b3 ^((~b4)& b0 ); + a44 = b4 ^((~b0)& b1 ); + + b1 = ROL64((a40^d0), 36); + b2 = ROL64((a11^d1), 10); + b3 = ROL64((a32^d2), 15); + b4 = ROL64((a03^d3), 56); + b0 = ROL64((a24^d4), 27); + a40 = b0 ^((~b1)& b2 ); + a11 = b1 ^((~b2)& b3 ); + a32 = b2 ^((~b3)& b4 ); + a03 = b3 ^((~b4)& b0 ); + a24 = b4 ^((~b0)& b1 ); + + b3 = ROL64((a20^d0), 41); + b4 = ROL64((a41^d1), 2); + b0 = ROL64((a12^d2), 62); + b1 = ROL64((a33^d3), 55); + b2 = ROL64((a04^d4), 39); + a20 = b0 ^((~b1)& b2 ); + a41 = b1 ^((~b2)& b3 ); + a12 = b2 ^((~b3)& b4 ); + a33 = b3 ^((~b4)& b0 ); + a04 = b4 ^((~b0)& b1 ); + + c0 = a00^a30^a10^a40^a20; + c1 = a21^a01^a31^a11^a41; + c2 = a42^a22^a02^a32^a12; + c3 = a13^a43^a23^a03^a33; + c4 = a34^a14^a44^a24^a04; + d0 = c4^ROL64(c1, 1); + d1 = c0^ROL64(c2, 1); + d2 = c1^ROL64(c3, 1); + d3 = c2^ROL64(c4, 1); + d4 = c3^ROL64(c0, 1); + + b0 = (a00^d0); + b1 = ROL64((a01^d1), 44); + b2 = ROL64((a02^d2), 43); + b3 = ROL64((a03^d3), 21); + b4 = ROL64((a04^d4), 14); + a00 = b0 ^((~b1)& b2 ); + a00 ^= RC[i+3]; + a01 = b1 ^((~b2)& b3 ); + a02 = b2 ^((~b3)& b4 ); + a03 = b3 ^((~b4)& b0 ); + a04 = b4 ^((~b0)& b1 ); + + b2 = ROL64((a10^d0), 3); + b3 = ROL64((a11^d1), 45); + b4 = ROL64((a12^d2), 61); + b0 = ROL64((a13^d3), 28); + b1 = ROL64((a14^d4), 20); + a10 = b0 ^((~b1)& b2 ); + a11 = b1 ^((~b2)& b3 ); + a12 = b2 ^((~b3)& b4 ); + a13 = b3 ^((~b4)& b0 ); + a14 = b4 ^((~b0)& b1 ); + + b4 = ROL64((a20^d0), 18); + b0 = ROL64((a21^d1), 1); + b1 = ROL64((a22^d2), 6); + b2 = ROL64((a23^d3), 25); + b3 = ROL64((a24^d4), 8); + a20 = b0 ^((~b1)& b2 ); + a21 = b1 ^((~b2)& b3 ); + a22 = b2 ^((~b3)& b4 ); + a23 = b3 ^((~b4)& b0 ); + a24 = b4 ^((~b0)& b1 ); + + b1 = ROL64((a30^d0), 36); + b2 = ROL64((a31^d1), 10); + b3 = ROL64((a32^d2), 15); + b4 = ROL64((a33^d3), 56); + b0 = ROL64((a34^d4), 27); + a30 = b0 ^((~b1)& b2 ); + a31 = b1 ^((~b2)& b3 ); + a32 = b2 ^((~b3)& b4 ); + a33 = b3 ^((~b4)& b0 ); + a34 = b4 ^((~b0)& b1 ); + + b3 = ROL64((a40^d0), 41); + b4 = ROL64((a41^d1), 2); + b0 = ROL64((a42^d2), 62); + b1 = ROL64((a43^d3), 55); + b2 = ROL64((a44^d4), 39); + a40 = b0 ^((~b1)& b2 ); + a41 = b1 ^((~b2)& b3 ); + a42 = b2 ^((~b3)& b4 ); + a43 = b3 ^((~b4)& b0 ); + a44 = b4 ^((~b0)& b1 ); + } +} + +/* +** Initialize a new hash. iSize determines the size of the hash +** in bits and should be one of 224, 256, 384, or 512. Or iSize +** can be zero to use the default hash size of 256 bits. +*/ +static void SHA3Init(SHA3Context *p, int iSize){ + memset(p, 0, sizeof(*p)); + p->iSize = iSize; + if( iSize>=128 && iSize<=512 ){ + p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; + }else{ + p->nRate = (1600 - 2*256)/8; + } +#if SHA3_BYTEORDER==1234 + /* Known to be little-endian at compile-time. No-op */ +#elif SHA3_BYTEORDER==4321 + p->ixMask = 7; /* Big-endian */ +#else + { + static unsigned int one = 1; + if( 1==*(unsigned char*)&one ){ + /* Little endian. No byte swapping. */ + p->ixMask = 0; + }else{ + /* Big endian. Byte swap. */ + p->ixMask = 7; + } + } +#endif +} + +/* +** Make consecutive calls to the SHA3Update function to add new content +** to the hash +*/ +static void SHA3Update( + SHA3Context *p, + const unsigned char *aData, + unsigned int nData +){ + unsigned int i = 0; + if( aData==0 ) return; +#if SHA3_BYTEORDER==1234 + if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ + for(; i+7u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; + p->nLoaded += 8; + if( p->nLoaded>=p->nRate ){ + KeccakF1600Step(p); + p->nLoaded = 0; + } + } + } +#endif + for(; iu.x[p->nLoaded] ^= aData[i]; +#elif SHA3_BYTEORDER==4321 + p->u.x[p->nLoaded^0x07] ^= aData[i]; +#else + p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; +#endif + p->nLoaded++; + if( p->nLoaded==p->nRate ){ + KeccakF1600Step(p); + p->nLoaded = 0; + } + } +} + +/* +** After all content has been added, invoke SHA3Final() to compute +** the final hash. The function returns a pointer to the binary +** hash value. +*/ +static unsigned char *SHA3Final(SHA3Context *p){ + unsigned int i; + if( p->nLoaded==p->nRate-1 ){ + const unsigned char c1 = 0x86; + SHA3Update(p, &c1, 1); + }else{ + const unsigned char c2 = 0x06; + const unsigned char c3 = 0x80; + SHA3Update(p, &c2, 1); + p->nLoaded = p->nRate - 1; + SHA3Update(p, &c3, 1); + } + for(i=0; inRate; i++){ + p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; + } + return &p->u.x[p->nRate]; +} +/* End of the hashing logic +*****************************************************************************/ + +/* +** Implementation of the sha3(X,SIZE) function. +** +** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default +** size is 256. If X is a BLOB, it is hashed as is. +** For all other non-NULL types of input, X is converted into a UTF-8 string +** and the string is hashed without the trailing 0x00 terminator. The hash +** of a NULL value is NULL. +*/ +static void sha3Func( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + SHA3Context cx; + int eType = sqlite3_value_type(argv[0]); + int nByte = sqlite3_value_bytes(argv[0]); + int iSize; + if( argc==1 ){ + iSize = 256; + }else{ + iSize = sqlite3_value_int(argv[1]); + if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ + sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " + "384 512", -1); + return; + } + } + if( eType==SQLITE_NULL ) return; + SHA3Init(&cx, iSize); + if( eType==SQLITE_BLOB ){ + SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte); + }else{ + SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte); + } + sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); +} + +/* Compute a string using sqlite3_vsnprintf() with a maximum length +** of 50 bytes and add it to the hash. +*/ +static void sha3_step_vformat( + SHA3Context *p, /* Add content to this context */ + const char *zFormat, + ... +){ + va_list ap; + int n; + char zBuf[50]; + va_start(ap, zFormat); + sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap); + va_end(ap); + n = (int)strlen(zBuf); + SHA3Update(p, (unsigned char*)zBuf, n); +} + +/* +** Update a SHA3Context using a single sqlite3_value. +*/ +static void sha3UpdateFromValue(SHA3Context *p, sqlite3_value *pVal){ + switch( sqlite3_value_type(pVal) ){ + case SQLITE_NULL: { + SHA3Update(p, (const unsigned char*)"N",1); + break; + } + case SQLITE_INTEGER: { + sqlite3_uint64 u; + int j; + unsigned char x[9]; + sqlite3_int64 v = sqlite3_value_int64(pVal); + memcpy(&u, &v, 8); + for(j=8; j>=1; j--){ + x[j] = u & 0xff; + u >>= 8; + } + x[0] = 'I'; + SHA3Update(p, x, 9); + break; + } + case SQLITE_FLOAT: { + sqlite3_uint64 u; + int j; + unsigned char x[9]; + double r = sqlite3_value_double(pVal); + memcpy(&u, &r, 8); + for(j=8; j>=1; j--){ + x[j] = u & 0xff; + u >>= 8; + } + x[0] = 'F'; + SHA3Update(p,x,9); + break; + } + case SQLITE_TEXT: { + int n2 = sqlite3_value_bytes(pVal); + const unsigned char *z2 = sqlite3_value_text(pVal); + sha3_step_vformat(p,"T%d:",n2); + SHA3Update(p, z2, n2); + break; + } + case SQLITE_BLOB: { + int n2 = sqlite3_value_bytes(pVal); + const unsigned char *z2 = sqlite3_value_blob(pVal); + sha3_step_vformat(p,"B%d:",n2); + SHA3Update(p, z2, n2); + break; + } + } +} + +/* +** Implementation of the sha3_query(SQL,SIZE) function. +** +** This function compiles and runs the SQL statement(s) given in the +** argument. The results are hashed using a SIZE-bit SHA3. The default +** size is 256. +** +** The format of the byte stream that is hashed is summarized as follows: +** +** S: +** R +** N +** I +** F +** B: +** T: +** +** is the original SQL text for each statement run and is +** the size of that text. The SQL text is UTF-8. A single R character +** occurs before the start of each row. N means a NULL value. +** I mean an 8-byte little-endian integer . F is a floating point +** number with an 8-byte little-endian IEEE floating point value . +** B means blobs of bytes. T means text rendered as +** bytes of UTF-8. The and values are expressed as an ASCII +** text integers. +** +** For each SQL statement in the X input, there is one S segment. Each +** S segment is followed by zero or more R segments, one for each row in the +** result set. After each R, there are one or more N, I, F, B, or T segments, +** one for each column in the result set. Segments are concatentated directly +** with no delimiters of any kind. +*/ +static void sha3QueryFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + const char *zSql = (const char*)sqlite3_value_text(argv[0]); + sqlite3_stmt *pStmt = 0; + int nCol; /* Number of columns in the result set */ + int i; /* Loop counter */ + int rc; + int n; + const char *z; + SHA3Context cx; + int iSize; + + if( argc==1 ){ + iSize = 256; + }else{ + iSize = sqlite3_value_int(argv[1]); + if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ + sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " + "384 512", -1); + return; + } + } + if( zSql==0 ) return; + SHA3Init(&cx, iSize); + while( zSql[0] ){ + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); + if( rc ){ + char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s", + zSql, sqlite3_errmsg(db)); + sqlite3_finalize(pStmt); + sqlite3_result_error(context, zMsg, -1); + sqlite3_free(zMsg); + return; + } + if( !sqlite3_stmt_readonly(pStmt) ){ + char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); + sqlite3_finalize(pStmt); + sqlite3_result_error(context, zMsg, -1); + sqlite3_free(zMsg); + return; + } + nCol = sqlite3_column_count(pStmt); + z = sqlite3_sql(pStmt); + if( z ){ + n = (int)strlen(z); + sha3_step_vformat(&cx,"S%d:",n); + SHA3Update(&cx,(unsigned char*)z,n); + } + + /* Compute a hash over the result of the query */ + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + SHA3Update(&cx,(const unsigned char*)"R",1); + for(i=0; inRate==0 ){ + int sz = 256; + if( argc==2 ){ + sz = sqlite3_value_int(argv[1]); + if( sz!=224 && sz!=384 && sz!=512 ){ + sz = 256; + } + } + SHA3Init(p, sz); + } + sha3UpdateFromValue(p, argv[0]); +} + + +/* +** xFinal function for sha3_agg(). +*/ +static void sha3AggFinal(sqlite3_context *context){ + SHA3Context *p; + p = (SHA3Context*)sqlite3_aggregate_context(context, sizeof(*p)); + if( p==0 ) return; + if( p->iSize ){ + sqlite3_result_blob(context, SHA3Final(p), p->iSize/8, SQLITE_TRANSIENT); + } +} + +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_shathree_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused parameter */ + rc = sqlite3_create_function(db, "sha3", 1, + SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, + 0, sha3Func, 0, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "sha3", 2, + SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, + 0, sha3Func, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "sha3_agg", 1, + SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, + 0, 0, sha3AggStep, sha3AggFinal); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "sha3_agg", 2, + SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, + 0, 0, sha3AggStep, sha3AggFinal); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "sha3_query", 1, + SQLITE_UTF8 | SQLITE_DIRECTONLY, + 0, sha3QueryFunc, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "sha3_query", 2, + SQLITE_UTF8 | SQLITE_DIRECTONLY, + 0, sha3QueryFunc, 0, 0); + } + return rc; +} +/*** End of #include "shathree.c" ***/ + +#endif + +/* +** CARRAY +*/ +#ifdef SQLITE_ENABLE_CARRAY +/* Prototype for initialization function of CARRAY extension */ +SQLITE_API +int sqlite3_carray_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); +/* #include "carray.c" */ +/*** Begin of #include "carray.c" ***/ +/* +** 2016-06-29 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file demonstrates how to create a table-valued-function that +** returns the values in a C-language array. +** Examples: +** +** SELECT * FROM carray($ptr,5) +** +** The query above returns 5 integers contained in a C-language array +** at the address $ptr. $ptr is a pointer to the array of integers. +** The pointer value must be assigned to $ptr using the +** sqlite3_bind_pointer() interface with a pointer type of "carray". +** For example: +** +** static int aX[] = { 53, 9, 17, 2231, 4, 99 }; +** int i = sqlite3_bind_parameter_index(pStmt, "$ptr"); +** sqlite3_bind_pointer(pStmt, i, aX, "carray", 0); +** +** There is an optional third parameter to determine the datatype of +** the C-language array. Allowed values of the third parameter are +** 'int32', 'int64', 'double', 'char*', 'struct iovec'. Example: +** +** SELECT * FROM carray($ptr,10,'char*'); +** +** The default value of the third parameter is 'int32'. +** +** HOW IT WORKS +** +** The carray "function" is really a virtual table with the +** following schema: +** +** CREATE TABLE carray( +** value, +** pointer HIDDEN, +** count HIDDEN, +** ctype TEXT HIDDEN +** ); +** +** If the hidden columns "pointer" and "count" are unconstrained, then +** the virtual table has no rows. Otherwise, the virtual table interprets +** the integer value of "pointer" as a pointer to the array and "count" +** as the number of elements in the array. The virtual table steps through +** the array, element by element. +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +#include +#include +#ifdef _WIN32 + struct iovec { + void *iov_base; + size_t iov_len; + }; +#else +# include +#endif + +/* Allowed values for the mFlags parameter to sqlite3_carray_bind(). +** Must exactly match the definitions in carray.h. +*/ +#ifndef CARRAY_INT32 +# define CARRAY_INT32 0 /* Data is 32-bit signed integers */ +# define CARRAY_INT64 1 /* Data is 64-bit signed integers */ +# define CARRAY_DOUBLE 2 /* Data is doubles */ +# define CARRAY_TEXT 3 /* Data is char* */ +# define CARRAY_BLOB 4 /* Data is struct iovec* */ +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Names of allowed datatypes +*/ +static const char *azType[] = { "int32", "int64", "double", "char*", + "struct iovec" }; + +/* +** Structure used to hold the sqlite3_carray_bind() information +*/ +typedef struct carray_bind carray_bind; +struct carray_bind { + void *aData; /* The data */ + int nData; /* Number of elements */ + int mFlags; /* Control flags */ + void (*xDel)(void*); /* Destructor for aData */ +}; + + +/* carray_cursor is a subclass of sqlite3_vtab_cursor which will +** serve as the underlying representation of a cursor that scans +** over rows of the result +*/ +typedef struct carray_cursor carray_cursor; +struct carray_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + sqlite3_int64 iRowid; /* The rowid */ + void *pPtr; /* Pointer to the array of values */ + sqlite3_int64 iCnt; /* Number of integers in the array */ + unsigned char eType; /* One of the CARRAY_type values */ +}; + +/* +** The carrayConnect() method is invoked to create a new +** carray_vtab that describes the carray virtual table. +** +** Think of this routine as the constructor for carray_vtab objects. +** +** All this routine needs to do is: +** +** (1) Allocate the carray_vtab object and initialize all fields. +** +** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the +** result set of queries against carray will look like. +*/ +static int carrayConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + sqlite3_vtab *pNew; + int rc; + +/* Column numbers */ +#define CARRAY_COLUMN_VALUE 0 +#define CARRAY_COLUMN_POINTER 1 +#define CARRAY_COLUMN_COUNT 2 +#define CARRAY_COLUMN_CTYPE 3 + + rc = sqlite3_declare_vtab(db, + "CREATE TABLE x(value,pointer hidden,count hidden,ctype hidden)"); + if( rc==SQLITE_OK ){ + pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + } + return rc; +} + +/* +** This method is the destructor for carray_cursor objects. +*/ +static int carrayDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** Constructor for a new carray_cursor object. +*/ +static int carrayOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ + carray_cursor *pCur; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Destructor for a carray_cursor. +*/ +static int carrayClose(sqlite3_vtab_cursor *cur){ + sqlite3_free(cur); + return SQLITE_OK; +} + + +/* +** Advance a carray_cursor to its next row of output. +*/ +static int carrayNext(sqlite3_vtab_cursor *cur){ + carray_cursor *pCur = (carray_cursor*)cur; + pCur->iRowid++; + return SQLITE_OK; +} + +/* +** Return values of columns for the row at which the carray_cursor +** is currently pointing. +*/ +static int carrayColumn( + sqlite3_vtab_cursor *cur, /* The cursor */ + sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ + int i /* Which column to return */ +){ + carray_cursor *pCur = (carray_cursor*)cur; + sqlite3_int64 x = 0; + switch( i ){ + case CARRAY_COLUMN_POINTER: return SQLITE_OK; + case CARRAY_COLUMN_COUNT: x = pCur->iCnt; break; + case CARRAY_COLUMN_CTYPE: { + sqlite3_result_text(ctx, azType[pCur->eType], -1, SQLITE_STATIC); + return SQLITE_OK; + } + default: { + switch( pCur->eType ){ + case CARRAY_INT32: { + int *p = (int*)pCur->pPtr; + sqlite3_result_int(ctx, p[pCur->iRowid-1]); + return SQLITE_OK; + } + case CARRAY_INT64: { + sqlite3_int64 *p = (sqlite3_int64*)pCur->pPtr; + sqlite3_result_int64(ctx, p[pCur->iRowid-1]); + return SQLITE_OK; + } + case CARRAY_DOUBLE: { + double *p = (double*)pCur->pPtr; + sqlite3_result_double(ctx, p[pCur->iRowid-1]); + return SQLITE_OK; + } + case CARRAY_TEXT: { + const char **p = (const char**)pCur->pPtr; + sqlite3_result_text(ctx, p[pCur->iRowid-1], -1, SQLITE_TRANSIENT); + return SQLITE_OK; + } + case CARRAY_BLOB: { + const struct iovec *p = (struct iovec*)pCur->pPtr; + sqlite3_result_blob(ctx, p[pCur->iRowid-1].iov_base, + (int)p[pCur->iRowid-1].iov_len, SQLITE_TRANSIENT); + return SQLITE_OK; + } + } + } + } + sqlite3_result_int64(ctx, x); + return SQLITE_OK; +} + +/* +** Return the rowid for the current row. In this implementation, the +** rowid is the same as the output value. +*/ +static int carrayRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + carray_cursor *pCur = (carray_cursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** Return TRUE if the cursor has been moved off of the last +** row of output. +*/ +static int carrayEof(sqlite3_vtab_cursor *cur){ + carray_cursor *pCur = (carray_cursor*)cur; + return pCur->iRowid>pCur->iCnt; +} + +/* +** This method is called to "rewind" the carray_cursor object back +** to the first row of output. +*/ +static int carrayFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + carray_cursor *pCur = (carray_cursor *)pVtabCursor; + pCur->pPtr = 0; + pCur->iCnt = 0; + switch( idxNum ){ + case 1: { + carray_bind *pBind = sqlite3_value_pointer(argv[0], "carray-bind"); + if( pBind==0 ) break; + pCur->pPtr = pBind->aData; + pCur->iCnt = pBind->nData; + pCur->eType = pBind->mFlags & 0x07; + break; + } + case 2: + case 3: { + pCur->pPtr = sqlite3_value_pointer(argv[0], "carray"); + pCur->iCnt = pCur->pPtr ? sqlite3_value_int64(argv[1]) : 0; + if( idxNum<3 ){ + pCur->eType = CARRAY_INT32; + }else{ + unsigned char i; + const char *zType = (const char*)sqlite3_value_text(argv[2]); + for(i=0; i=sizeof(azType)/sizeof(azType[0]) ){ + pVtabCursor->pVtab->zErrMsg = sqlite3_mprintf( + "unknown datatype: %Q", zType); + return SQLITE_ERROR; + }else{ + pCur->eType = i; + } + } + break; + } + } + pCur->iRowid = 1; + return SQLITE_OK; +} + +/* +** SQLite will invoke this method one or more times while planning a query +** that uses the carray virtual table. This routine needs to create +** a query plan for each invocation and compute an estimated cost for that +** plan. +** +** In this implementation idxNum is used to represent the +** query plan. idxStr is unused. +** +** idxNum is: +** +** 1 If only the pointer= constraint exists. In this case, the +** parameter must be bound using sqlite3_carray_bind(). +** +** 2 if the pointer= and count= constraints exist. +** +** 3 if the ctype= constraint also exists. +** +** idxNum is 0 otherwise and carray becomes an empty table. +*/ +static int carrayBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo +){ + int i; /* Loop over constraints */ + int ptrIdx = -1; /* Index of the pointer= constraint, or -1 if none */ + int cntIdx = -1; /* Index of the count= constraint, or -1 if none */ + int ctypeIdx = -1; /* Index of the ctype= constraint, or -1 if none */ + + const struct sqlite3_index_constraint *pConstraint; + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + if( pConstraint->usable==0 ) continue; + if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; + switch( pConstraint->iColumn ){ + case CARRAY_COLUMN_POINTER: + ptrIdx = i; + break; + case CARRAY_COLUMN_COUNT: + cntIdx = i; + break; + case CARRAY_COLUMN_CTYPE: + ctypeIdx = i; + break; + } + } + if( ptrIdx>=0 ){ + pIdxInfo->aConstraintUsage[ptrIdx].argvIndex = 1; + pIdxInfo->aConstraintUsage[ptrIdx].omit = 1; + pIdxInfo->estimatedCost = (double)1; + pIdxInfo->estimatedRows = 100; + pIdxInfo->idxNum = 1; + if( cntIdx>=0 ){ + pIdxInfo->aConstraintUsage[cntIdx].argvIndex = 2; + pIdxInfo->aConstraintUsage[cntIdx].omit = 1; + pIdxInfo->idxNum = 2; + if( ctypeIdx>=0 ){ + pIdxInfo->aConstraintUsage[ctypeIdx].argvIndex = 3; + pIdxInfo->aConstraintUsage[ctypeIdx].omit = 1; + pIdxInfo->idxNum = 3; + } + } + }else{ + pIdxInfo->estimatedCost = (double)2147483647; + pIdxInfo->estimatedRows = 2147483647; + pIdxInfo->idxNum = 0; + } + return SQLITE_OK; +} + +/* +** This following structure defines all the methods for the +** carray virtual table. +*/ +static sqlite3_module carrayModule = { + 0, /* iVersion */ + 0, /* xCreate */ + carrayConnect, /* xConnect */ + carrayBestIndex, /* xBestIndex */ + carrayDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + carrayOpen, /* xOpen - open a cursor */ + carrayClose, /* xClose - close a cursor */ + carrayFilter, /* xFilter - configure scan constraints */ + carrayNext, /* xNext - advance a cursor */ + carrayEof, /* xEof - check for end of scan */ + carrayColumn, /* xColumn - read data */ + carrayRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadow */ + 0 /* xIntegrity */ +}; + +/* +** Destructor for the carray_bind object +*/ +static void carrayBindDel(void *pPtr){ + carray_bind *p = (carray_bind*)pPtr; + if( p->xDel!=SQLITE_STATIC ){ + p->xDel(p->aData); + } + sqlite3_free(p); +} + +/* +** Invoke this interface in order to bind to the single-argument +** version of CARRAY(). +*/ +SQLITE_API int sqlite3_carray_bind( + sqlite3_stmt *pStmt, + int idx, + void *aData, + int nData, + int mFlags, + void (*xDestroy)(void*) +){ + carray_bind *pNew; + int i; + pNew = sqlite3_malloc64(sizeof(*pNew)); + if( pNew==0 ){ + if( xDestroy!=SQLITE_STATIC && xDestroy!=SQLITE_TRANSIENT ){ + xDestroy(aData); + } + return SQLITE_NOMEM; + } + pNew->nData = nData; + pNew->mFlags = mFlags; + if( xDestroy==SQLITE_TRANSIENT ){ + sqlite3_int64 sz = nData; + switch( mFlags & 0x07 ){ + case CARRAY_INT32: sz *= 4; break; + case CARRAY_INT64: sz *= 8; break; + case CARRAY_DOUBLE: sz *= 8; break; + case CARRAY_TEXT: sz *= sizeof(char*); break; + case CARRAY_BLOB: sz *= sizeof(struct iovec); break; + } + if( (mFlags & 0x07)==CARRAY_TEXT ){ + for(i=0; iaData = sqlite3_malloc64( sz ); + if( pNew->aData==0 ){ + sqlite3_free(pNew); + return SQLITE_NOMEM; + } + if( (mFlags & 0x07)==CARRAY_TEXT ){ + char **az = (char**)pNew->aData; + char *z = (char*)&az[nData]; + for(i=0; iaData; + unsigned char *z = (unsigned char*)&p[nData]; + for(i=0; iaData, aData, sz); + } + pNew->xDel = sqlite3_free; + }else{ + pNew->aData = aData; + pNew->xDel = xDestroy; + } + return sqlite3_bind_pointer(pStmt, idx, pNew, "carray-bind", carrayBindDel); +} + + +/* +** For testing purpose in the TCL test harness, we need a method for +** setting the pointer value. The inttoptr(X) SQL function accomplishes +** this. Tcl script will bind an integer to X and the inttoptr() SQL +** function will use sqlite3_result_pointer() to convert that integer into +** a pointer. +** +** This is for testing on TCL only. +*/ +#ifdef SQLITE_TEST +static void inttoptrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + void *p; + sqlite3_int64 i64; + i64 = sqlite3_value_int64(argv[0]); + if( sizeof(i64)==sizeof(p) ){ + memcpy(&p, &i64, sizeof(p)); + }else{ + int i32 = i64 & 0xffffffff; + memcpy(&p, &i32, sizeof(p)); + } + sqlite3_result_pointer(context, p, "carray", 0); +} +#endif /* SQLITE_TEST */ + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_carray_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = sqlite3_create_module(db, "carray", &carrayModule, 0); +#ifdef SQLITE_TEST + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "inttoptr", 1, SQLITE_UTF8, 0, + inttoptrFunc, 0, 0); + } +#endif /* SQLITE_TEST */ +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + return rc; +} +/*** End of #include "carray.c" ***/ + +#endif + +/* +** FILEIO +*/ +#ifdef SQLITE_ENABLE_FILEIO +/* Prototype for initialization function of FILEIO extension */ +SQLITE_API +int sqlite3_fileio_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); + +/* MinGW specifics */ +#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) +# include +# include +# if defined(__MINGW32__) +# define DIRENT dirent +# ifndef S_ISLNK +# define S_ISLNK(mode) (0) +# endif +# endif +#endif + +/* #include "test_windirent.c" */ +/*** Begin of #include "test_windirent.c" ***/ +/* +** 2015 November 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code to implement most of the opendir() family of +** POSIX functions on Win32 using the MSVCRT. +*/ + +#if defined(_WIN32) && defined(_MSC_VER) +/* #include "test_windirent.h" */ +/*** Begin of #include "test_windirent.h" ***/ +/* +** 2015 November 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains declarations for most of the opendir() family of +** POSIX functions on Win32 using the MSVCRT. +*/ + +#if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H) +#define SQLITE_WINDIRENT_H + +/* +** We need several data types from the Windows SDK header. +*/ + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif + +#include "windows.h" + +/* +** We need several support functions from the SQLite core. +*/ + +/* #include "sqlite3.h" */ + + +/* +** We need several things from the ANSI and MSVCRT headers. +*/ + +#include +#include +#include +#include +#include +#include +#include + +/* +** We may need several defines that should have been in "sys/stat.h". +*/ + +#ifndef S_ISREG +#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) +#endif + +#ifndef S_ISDIR +#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) +#endif + +#ifndef S_ISLNK +#define S_ISLNK(mode) (0) +#endif + +/* +** We may need to provide the "mode_t" type. +*/ + +#ifndef MODE_T_DEFINED + #define MODE_T_DEFINED + typedef unsigned short mode_t; +#endif + +/* +** We may need to provide the "ino_t" type. +*/ + +#ifndef INO_T_DEFINED + #define INO_T_DEFINED + typedef unsigned short ino_t; +#endif + +/* +** We need to define "NAME_MAX" if it was not present in "limits.h". +*/ + +#ifndef NAME_MAX +# ifdef FILENAME_MAX +# define NAME_MAX (FILENAME_MAX) +# else +# define NAME_MAX (260) +# endif +# define DIRENT_NAME_MAX (NAME_MAX) +#endif + +/* +** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T". +*/ + +#ifndef NULL_INTPTR_T +# define NULL_INTPTR_T ((intptr_t)(0)) +#endif + +#ifndef BAD_INTPTR_T +# define BAD_INTPTR_T ((intptr_t)(-1)) +#endif + +/* +** We need to provide the necessary structures and related types. +*/ + +#ifndef DIRENT_DEFINED +#define DIRENT_DEFINED +typedef struct DIRENT DIRENT; +typedef DIRENT *LPDIRENT; +struct DIRENT { + ino_t d_ino; /* Sequence number, do not use. */ + unsigned d_attributes; /* Win32 file attributes. */ + char d_name[NAME_MAX + 1]; /* Name within the directory. */ +}; +#endif + +#ifndef DIR_DEFINED +#define DIR_DEFINED +typedef struct DIR DIR; +typedef DIR *LPDIR; +struct DIR { + intptr_t d_handle; /* Value returned by "_findfirst". */ + DIRENT d_first; /* DIRENT constructed based on "_findfirst". */ + DIRENT d_next; /* DIRENT constructed based on "_findnext". */ +}; +#endif + +/* +** Provide a macro, for use by the implementation, to determine if a +** particular directory entry should be skipped over when searching for +** the next directory entry that should be returned by the readdir(). +*/ + +#ifndef is_filtered +# define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM)) +#endif + +/* +** Provide the function prototype for the POSIX compatible getenv() +** function. This function is not thread-safe. +*/ + +extern const char *windirent_getenv(const char *name); + +/* +** Finally, we can provide the function prototypes for the opendir(), +** readdir(), and closedir() POSIX functions. +*/ + +extern LPDIR opendir(const char *dirname); +extern LPDIRENT readdir(LPDIR dirp); +extern INT closedir(LPDIR dirp); + +#endif /* defined(WIN32) && defined(_MSC_VER) */ +/*** End of #include "test_windirent.h" ***/ + + +/* +** Implementation of the POSIX getenv() function using the Win32 API. +** This function is not thread-safe. +*/ +const char *windirent_getenv( + const char *name +){ + static char value[32768]; /* Maximum length, per MSDN */ + DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */ + DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */ + + memset(value, 0, sizeof(value)); + dwRet = GetEnvironmentVariableA(name, value, dwSize); + if( dwRet==0 || dwRet>dwSize ){ + /* + ** The function call to GetEnvironmentVariableA() failed -OR- + ** the buffer is not large enough. Either way, return NULL. + */ + return 0; + }else{ + /* + ** The function call to GetEnvironmentVariableA() succeeded + ** -AND- the buffer contains the entire value. + */ + return value; + } +} + +/* +** Implementation of the POSIX opendir() function using the MSVCRT. +*/ +LPDIR opendir( + const char *dirname /* Directory name, UTF8 encoding */ +){ + struct _wfinddata_t data; + LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR)); + SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]); + wchar_t *b1; + sqlite3_int64 sz; + + if( dirp==NULL ) return NULL; + memset(dirp, 0, sizeof(DIR)); + + /* TODO: Remove this if Unix-style root paths are not used. */ + if( sqlite3_stricmp(dirname, "/")==0 ){ + dirname = windirent_getenv("SystemDrive"); + } + + memset(&data, 0, sizeof(data)); + sz = strlen(dirname); + b1 = sqlite3_malloc64( (sz+3)*sizeof(b1[0]) ); + if( b1==0 ){ + closedir(dirp); + return NULL; + } + sz = MultiByteToWideChar(CP_UTF8, 0, dirname, sz, b1, sz); + b1[sz++] = '\\'; + b1[sz++] = '*'; + b1[sz] = 0; + if( sz+1>(sqlite3_int64)namesize ){ + closedir(dirp); + sqlite3_free(b1); + return NULL; + } + memcpy(data.name, b1, (sz+1)*sizeof(b1[0])); + sqlite3_free(b1); + dirp->d_handle = _wfindfirst(data.name, &data); + + if( dirp->d_handle==BAD_INTPTR_T ){ + closedir(dirp); + return NULL; + } + + /* TODO: Remove this block to allow hidden and/or system files. */ + if( is_filtered(data) ){ +next: + + memset(&data, 0, sizeof(data)); + if( _wfindnext(dirp->d_handle, &data)==-1 ){ + closedir(dirp); + return NULL; + } + + /* TODO: Remove this block to allow hidden and/or system files. */ + if( is_filtered(data) ) goto next; + } + + dirp->d_first.d_attributes = data.attrib; + WideCharToMultiByte(CP_UTF8, 0, data.name, -1, + dirp->d_first.d_name, DIRENT_NAME_MAX, 0, 0); + return dirp; +} + +/* +** Implementation of the POSIX readdir() function using the MSVCRT. +*/ +LPDIRENT readdir( + LPDIR dirp +){ + struct _wfinddata_t data; + + if( dirp==NULL ) return NULL; + + if( dirp->d_first.d_ino==0 ){ + dirp->d_first.d_ino++; + dirp->d_next.d_ino++; + + return &dirp->d_first; + } + +next: + + memset(&data, 0, sizeof(data)); + if( _wfindnext(dirp->d_handle, &data)==-1 ) return NULL; + + /* TODO: Remove this block to allow hidden and/or system files. */ + if( is_filtered(data) ) goto next; + + dirp->d_next.d_ino++; + dirp->d_next.d_attributes = data.attrib; + WideCharToMultiByte(CP_UTF8, 0, data.name, -1, + dirp->d_next.d_name, DIRENT_NAME_MAX, 0, 0); + return &dirp->d_next; +} + +/* +** Implementation of the POSIX closedir() function using the MSVCRT. +*/ +INT closedir( + LPDIR dirp +){ + INT result = 0; + + if( dirp==NULL ) return EINVAL; + + if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){ + result = _findclose(dirp->d_handle); + } + + sqlite3_free(dirp); + return result; +} + +#endif /* defined(WIN32) && defined(_MSC_VER) */ +/*** End of #include "test_windirent.c" ***/ + +/* #include "fileio.c" */ +/*** Begin of #include "fileio.c" ***/ +/* +** 2014-06-13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This SQLite extension implements SQL functions readfile() and +** writefile(), and eponymous virtual type "fsdir". +** +** WRITEFILE(FILE, DATA [, MODE [, MTIME]]): +** +** If neither of the optional arguments is present, then this UDF +** function writes blob DATA to file FILE. If successful, the number +** of bytes written is returned. If an error occurs, NULL is returned. +** +** If the first option argument - MODE - is present, then it must +** be passed an integer value that corresponds to a POSIX mode +** value (file type + permissions, as returned in the stat.st_mode +** field by the stat() system call). Three types of files may +** be written/created: +** +** regular files: (mode & 0170000)==0100000 +** symbolic links: (mode & 0170000)==0120000 +** directories: (mode & 0170000)==0040000 +** +** For a directory, the DATA is ignored. For a symbolic link, it is +** interpreted as text and used as the target of the link. For a +** regular file, it is interpreted as a blob and written into the +** named file. Regardless of the type of file, its permissions are +** set to (mode & 0777) before returning. +** +** If the optional MTIME argument is present, then it is interpreted +** as an integer - the number of seconds since the unix epoch. The +** modification-time of the target file is set to this value before +** returning. +** +** If five or more arguments are passed to this function and an +** error is encountered, an exception is raised. +** +** READFILE(FILE): +** +** Read and return the contents of file FILE (type blob) from disk. +** +** FSDIR: +** +** Used as follows: +** +** SELECT * FROM fsdir($path [, $dir]); +** +** Parameter $path is an absolute or relative pathname. If the file that it +** refers to does not exist, it is an error. If the path refers to a regular +** file or symbolic link, it returns a single row. Or, if the path refers +** to a directory, it returns one row for the directory, and one row for each +** file within the hierarchy rooted at $path. +** +** Each row has the following columns: +** +** name: Path to file or directory (text value). +** mode: Value of stat.st_mode for directory entry (an integer). +** mtime: Value of stat.st_mtime for directory entry (an integer). +** data: For a regular file, a blob containing the file data. For a +** symlink, a text value containing the text of the link. For a +** directory, NULL. +** +** If a non-NULL value is specified for the optional $dir parameter and +** $path is a relative path, then $path is interpreted relative to $dir. +** And the paths returned in the "name" column of the table are also +** relative to directory $dir. +** +** Notes on building this extension for Windows: +** Unless linked statically with the SQLite library, a preprocessor +** symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone +** DLL form of this extension for WIN32. See its use below for details. +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +#include +#include +#include + +#include +#include +#include +#if !defined(_WIN32) && !defined(WIN32) +# include +# include +# include +# include +#else +# include "windows.h" +# include +# include +/* # include "test_windirent.h" */ + +# define dirent DIRENT +# define stat _stat +# define chmod(path,mode) fileio_chmod(path,mode) +# define mkdir(path,mode) fileio_mkdir(path) +#endif +#include +#include + +/* When used as part of the CLI, the sqlite3_stdio.h module will have +** been included before this one. In that case use the sqlite3_stdio.h +** #defines. If not, create our own for fopen(). +*/ +#ifndef _SQLITE3_STDIO_H_ +# define sqlite3_fopen fopen +#endif + +/* +** Structure of the fsdir() table-valued function +*/ + /* 0 1 2 3 4 5 */ +#define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)" +#define FSDIR_COLUMN_NAME 0 /* Name of the file */ +#define FSDIR_COLUMN_MODE 1 /* Access mode */ +#define FSDIR_COLUMN_MTIME 2 /* Last modification time */ +#define FSDIR_COLUMN_DATA 3 /* File content */ +#define FSDIR_COLUMN_PATH 4 /* Path to top of search */ +#define FSDIR_COLUMN_DIR 5 /* Path is relative to this directory */ + +/* +** UTF8 chmod() function for Windows +*/ +#if defined(_WIN32) || defined(WIN32) +static int fileio_chmod(const char *zPath, int pmode){ + sqlite3_int64 sz = strlen(zPath); + wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(b1[0]) ); + int rc; + if( b1==0 ) return -1; + sz = MultiByteToWideChar(CP_UTF8, 0, zPath, sz, b1, sz); + b1[sz] = 0; + rc = _wchmod(b1, pmode); + sqlite3_free(b1); + return rc; +} +#endif + +/* +** UTF8 mkdir() function for Windows +*/ +#if defined(_WIN32) || defined(WIN32) +static int fileio_mkdir(const char *zPath){ + sqlite3_int64 sz = strlen(zPath); + wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(b1[0]) ); + int rc; + if( b1==0 ) return -1; + sz = MultiByteToWideChar(CP_UTF8, 0, zPath, sz, b1, sz); + b1[sz] = 0; + rc = _wmkdir(b1); + sqlite3_free(b1); + return rc; +} +#endif + + +/* +** Set the result stored by context ctx to a blob containing the +** contents of file zName. Or, leave the result unchanged (NULL) +** if the file does not exist or is unreadable. +** +** If the file exceeds the SQLite blob size limit, through an +** SQLITE_TOOBIG error. +** +** Throw an SQLITE_IOERR if there are difficulties pulling the file +** off of disk. +*/ +static void readFileContents(sqlite3_context *ctx, const char *zName){ + FILE *in; + sqlite3_int64 nIn; + void *pBuf; + sqlite3 *db; + int mxBlob; + + in = sqlite3_fopen(zName, "rb"); + if( in==0 ){ + /* File does not exist or is unreadable. Leave the result set to NULL. */ + return; + } + fseek(in, 0, SEEK_END); + nIn = ftell(in); + rewind(in); + db = sqlite3_context_db_handle(ctx); + mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1); + if( nIn>mxBlob ){ + sqlite3_result_error_code(ctx, SQLITE_TOOBIG); + fclose(in); + return; + } + pBuf = sqlite3_malloc64( nIn ? nIn : 1 ); + if( pBuf==0 ){ + sqlite3_result_error_nomem(ctx); + fclose(in); + return; + } + if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){ + sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free); + }else{ + sqlite3_result_error_code(ctx, SQLITE_IOERR); + sqlite3_free(pBuf); + } + fclose(in); +} + +/* +** Implementation of the "readfile(X)" SQL function. The entire content +** of the file named X is read and returned as a BLOB. NULL is returned +** if the file does not exist or is unreadable. +*/ +static void readfileFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zName; + (void)(argc); /* Unused parameter */ + zName = (const char*)sqlite3_value_text(argv[0]); + if( zName==0 ) return; + readFileContents(context, zName); +} + +/* +** Set the error message contained in context ctx to the results of +** vprintf(zFmt, ...). +*/ +static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ + char *zMsg = 0; + va_list ap; + va_start(ap, zFmt); + zMsg = sqlite3_vmprintf(zFmt, ap); + sqlite3_result_error(ctx, zMsg, -1); + sqlite3_free(zMsg); + va_end(ap); +} + +#if defined(_WIN32) +/* +** This function is designed to convert a Win32 FILETIME structure into the +** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC). +*/ +static sqlite3_uint64 fileTimeToUnixTime( + LPFILETIME pFileTime +){ + SYSTEMTIME epochSystemTime; + ULARGE_INTEGER epochIntervals; + FILETIME epochFileTime; + ULARGE_INTEGER fileIntervals; + + memset(&epochSystemTime, 0, sizeof(SYSTEMTIME)); + epochSystemTime.wYear = 1970; + epochSystemTime.wMonth = 1; + epochSystemTime.wDay = 1; + SystemTimeToFileTime(&epochSystemTime, &epochFileTime); + epochIntervals.LowPart = epochFileTime.dwLowDateTime; + epochIntervals.HighPart = epochFileTime.dwHighDateTime; + + fileIntervals.LowPart = pFileTime->dwLowDateTime; + fileIntervals.HighPart = pFileTime->dwHighDateTime; + + return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000; +} + + +#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32)) +# /* To allow a standalone DLL, use this next replacement function: */ +# undef sqlite3_win32_utf8_to_unicode +# define sqlite3_win32_utf8_to_unicode utf8_to_utf16 +# +LPWSTR utf8_to_utf16(const char *z){ + int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0); + LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR)); + if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) ) + return rv; + sqlite3_free(rv); + return 0; +} +#endif + +/* +** This function attempts to normalize the time values found in the stat() +** buffer to UTC. This is necessary on Win32, where the runtime library +** appears to return these values as local times. +*/ +static void statTimesToUtc( + const char *zPath, + struct stat *pStatBuf +){ + HANDLE hFindFile; + WIN32_FIND_DATAW fd; + LPWSTR zUnicodeName; + extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); + zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath); + if( zUnicodeName ){ + memset(&fd, 0, sizeof(WIN32_FIND_DATAW)); + hFindFile = FindFirstFileW(zUnicodeName, &fd); + if( hFindFile!=NULL ){ + pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime); + pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime); + pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime); + FindClose(hFindFile); + } + sqlite3_free(zUnicodeName); + } +} +#endif + +/* +** This function is used in place of stat(). On Windows, special handling +** is required in order for the included time to be returned as UTC. On all +** other systems, this function simply calls stat(). +*/ +static int fileStat( + const char *zPath, + struct stat *pStatBuf +){ +#if defined(_WIN32) + sqlite3_int64 sz = strlen(zPath); + wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(b1[0]) ); + int rc; + if( b1==0 ) return 1; + sz = MultiByteToWideChar(CP_UTF8, 0, zPath, sz, b1, sz); + b1[sz] = 0; + rc = _wstat(b1, pStatBuf); + if( rc==0 ) statTimesToUtc(zPath, pStatBuf); + return rc; +#else + return stat(zPath, pStatBuf); +#endif +} + +/* +** This function is used in place of lstat(). On Windows, special handling +** is required in order for the included time to be returned as UTC. On all +** other systems, this function simply calls lstat(). +*/ +static int fileLinkStat( + const char *zPath, + struct stat *pStatBuf +){ +#if defined(_WIN32) + return fileStat(zPath, pStatBuf); +#else + return lstat(zPath, pStatBuf); +#endif +} + +/* +** Argument zFile is the name of a file that will be created and/or written +** by SQL function writefile(). This function ensures that the directory +** zFile will be written to exists, creating it if required. The permissions +** for any path components created by this function are set in accordance +** with the current umask. +** +** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise, +** SQLITE_OK is returned if the directory is successfully created, or +** SQLITE_ERROR otherwise. +*/ +static int makeDirectory( + const char *zFile +){ + char *zCopy = sqlite3_mprintf("%s", zFile); + int rc = SQLITE_OK; + + if( zCopy==0 ){ + rc = SQLITE_NOMEM; + }else{ + int nCopy = (int)strlen(zCopy); + int i = 1; + + while( rc==SQLITE_OK ){ + struct stat sStat; + int rc2; + + for(; zCopy[i]!='/' && i=0 ){ +#if defined(_WIN32) +#if !SQLITE_OS_WINRT + /* Windows */ + FILETIME lastAccess; + FILETIME lastWrite; + SYSTEMTIME currentTime; + LONGLONG intervals; + HANDLE hFile; + LPWSTR zUnicodeName; + extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); + + GetSystemTime(¤tTime); + SystemTimeToFileTime(¤tTime, &lastAccess); + intervals = (mtime*10000000) + 116444736000000000; + lastWrite.dwLowDateTime = (DWORD)intervals; + lastWrite.dwHighDateTime = intervals >> 32; + zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile); + if( zUnicodeName==0 ){ + return 1; + } + hFile = CreateFileW( + zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL + ); + sqlite3_free(zUnicodeName); + if( hFile!=INVALID_HANDLE_VALUE ){ + BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite); + CloseHandle(hFile); + return !bResult; + }else{ + return 1; + } +#endif +#elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */ + /* Recent unix */ + struct timespec times[2]; + times[0].tv_nsec = times[1].tv_nsec = 0; + times[0].tv_sec = time(0); + times[1].tv_sec = mtime; + if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){ + return 1; + } +#else + /* Legacy unix. + ** + ** Do not use utimes() on a symbolic link - it sees through the link and + ** modifies the timestamps on the target. Or fails if the target does + ** not exist. */ + if( 0==S_ISLNK(mode) ){ + struct timeval times[2]; + times[0].tv_usec = times[1].tv_usec = 0; + times[0].tv_sec = time(0); + times[1].tv_sec = mtime; + if( utimes(zFile, times) ){ + return 1; + } + } +#endif + } + + return 0; +} + +/* +** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function. +** Refer to header comments at the top of this file for details. +*/ +static void writefileFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zFile; + mode_t mode = 0; + int res; + sqlite3_int64 mtime = -1; + + if( argc<2 || argc>4 ){ + sqlite3_result_error(context, + "wrong number of arguments to function writefile()", -1 + ); + return; + } + + zFile = (const char*)sqlite3_value_text(argv[0]); + if( zFile==0 ) return; + if( argc>=3 ){ + mode = (mode_t)sqlite3_value_int(argv[2]); + } + if( argc==4 ){ + mtime = sqlite3_value_int64(argv[3]); + } + + res = writeFile(context, zFile, argv[1], mode, mtime); + if( res==1 && errno==ENOENT ){ + if( makeDirectory(zFile)==SQLITE_OK ){ + res = writeFile(context, zFile, argv[1], mode, mtime); + } + } + + if( argc>2 && res!=0 ){ + if( S_ISLNK(mode) ){ + ctxErrorMsg(context, "failed to create symlink: %s", zFile); + }else if( S_ISDIR(mode) ){ + ctxErrorMsg(context, "failed to create directory: %s", zFile); + }else{ + ctxErrorMsg(context, "failed to write file: %s", zFile); + } + } +} + +/* +** SQL function: lsmode(MODE) +** +** Given a numberic st_mode from stat(), convert it into a human-readable +** text string in the style of "ls -l". +*/ +static void lsModeFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + int i; + int iMode = sqlite3_value_int(argv[0]); + char z[16]; + (void)argc; + if( S_ISLNK(iMode) ){ + z[0] = 'l'; + }else if( S_ISREG(iMode) ){ + z[0] = '-'; + }else if( S_ISDIR(iMode) ){ + z[0] = 'd'; + }else{ + z[0] = '?'; + } + for(i=0; i<3; i++){ + int m = (iMode >> ((2-i)*3)); + char *a = &z[1 + i*3]; + a[0] = (m & 0x4) ? 'r' : '-'; + a[1] = (m & 0x2) ? 'w' : '-'; + a[2] = (m & 0x1) ? 'x' : '-'; + } + z[10] = '\0'; + sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Cursor type for recursively iterating through a directory structure. +*/ +typedef struct fsdir_cursor fsdir_cursor; +typedef struct FsdirLevel FsdirLevel; + +struct FsdirLevel { + DIR *pDir; /* From opendir() */ + char *zDir; /* Name of directory (nul-terminated) */ +}; + +struct fsdir_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + + int nLvl; /* Number of entries in aLvl[] array */ + int iLvl; /* Index of current entry */ + FsdirLevel *aLvl; /* Hierarchy of directories being traversed */ + + const char *zBase; + int nBase; + + struct stat sStat; /* Current lstat() results */ + char *zPath; /* Path to current entry */ + sqlite3_int64 iRowid; /* Current rowid */ +}; + +typedef struct fsdir_tab fsdir_tab; +struct fsdir_tab { + sqlite3_vtab base; /* Base class - must be first */ +}; + +/* +** Construct a new fsdir virtual table object. +*/ +static int fsdirConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + fsdir_tab *pNew = 0; + int rc; + (void)pAux; + (void)argc; + (void)argv; + (void)pzErr; + rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA); + if( rc==SQLITE_OK ){ + pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); + } + *ppVtab = (sqlite3_vtab*)pNew; + return rc; +} + +/* +** This method is the destructor for fsdir vtab objects. +*/ +static int fsdirDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** Constructor for a new fsdir_cursor object. +*/ +static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ + fsdir_cursor *pCur; + (void)p; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + pCur->iLvl = -1; + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Reset a cursor back to the state it was in when first returned +** by fsdirOpen(). +*/ +static void fsdirResetCursor(fsdir_cursor *pCur){ + int i; + for(i=0; i<=pCur->iLvl; i++){ + FsdirLevel *pLvl = &pCur->aLvl[i]; + if( pLvl->pDir ) closedir(pLvl->pDir); + sqlite3_free(pLvl->zDir); + } + sqlite3_free(pCur->zPath); + sqlite3_free(pCur->aLvl); + pCur->aLvl = 0; + pCur->zPath = 0; + pCur->zBase = 0; + pCur->nBase = 0; + pCur->nLvl = 0; + pCur->iLvl = -1; + pCur->iRowid = 1; +} + +/* +** Destructor for an fsdir_cursor. +*/ +static int fsdirClose(sqlite3_vtab_cursor *cur){ + fsdir_cursor *pCur = (fsdir_cursor*)cur; + + fsdirResetCursor(pCur); + sqlite3_free(pCur); + return SQLITE_OK; +} + +/* +** Set the error message for the virtual table associated with cursor +** pCur to the results of vprintf(zFmt, ...). +*/ +static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){ + va_list ap; + va_start(ap, zFmt); + pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); + va_end(ap); +} + + +/* +** Advance an fsdir_cursor to its next row of output. +*/ +static int fsdirNext(sqlite3_vtab_cursor *cur){ + fsdir_cursor *pCur = (fsdir_cursor*)cur; + mode_t m = pCur->sStat.st_mode; + + pCur->iRowid++; + if( S_ISDIR(m) ){ + /* Descend into this directory */ + int iNew = pCur->iLvl + 1; + FsdirLevel *pLvl; + if( iNew>=pCur->nLvl ){ + int nNew = iNew+1; + sqlite3_int64 nByte = nNew*sizeof(FsdirLevel); + FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte); + if( aNew==0 ) return SQLITE_NOMEM; + memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl)); + pCur->aLvl = aNew; + pCur->nLvl = nNew; + } + pCur->iLvl = iNew; + pLvl = &pCur->aLvl[iNew]; + + pLvl->zDir = pCur->zPath; + pCur->zPath = 0; + pLvl->pDir = opendir(pLvl->zDir); + if( pLvl->pDir==0 ){ + fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath); + return SQLITE_ERROR; + } + } + + while( pCur->iLvl>=0 ){ + FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl]; + struct dirent *pEntry = readdir(pLvl->pDir); + if( pEntry ){ + if( pEntry->d_name[0]=='.' ){ + if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue; + if( pEntry->d_name[1]=='\0' ) continue; + } + sqlite3_free(pCur->zPath); + pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name); + if( pCur->zPath==0 ) return SQLITE_NOMEM; + if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ + fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); + return SQLITE_ERROR; + } + return SQLITE_OK; + } + closedir(pLvl->pDir); + sqlite3_free(pLvl->zDir); + pLvl->pDir = 0; + pLvl->zDir = 0; + pCur->iLvl--; + } + + /* EOF */ + sqlite3_free(pCur->zPath); + pCur->zPath = 0; + return SQLITE_OK; +} + +/* +** Return values of columns for the row at which the series_cursor +** is currently pointing. +*/ +static int fsdirColumn( + sqlite3_vtab_cursor *cur, /* The cursor */ + sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ + int i /* Which column to return */ +){ + fsdir_cursor *pCur = (fsdir_cursor*)cur; + switch( i ){ + case FSDIR_COLUMN_NAME: { + sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT); + break; + } + + case FSDIR_COLUMN_MODE: + sqlite3_result_int64(ctx, pCur->sStat.st_mode); + break; + + case FSDIR_COLUMN_MTIME: + sqlite3_result_int64(ctx, pCur->sStat.st_mtime); + break; + + case FSDIR_COLUMN_DATA: { + mode_t m = pCur->sStat.st_mode; + if( S_ISDIR(m) ){ + sqlite3_result_null(ctx); +#if !defined(_WIN32) && !defined(WIN32) + }else if( S_ISLNK(m) ){ + char aStatic[64]; + char *aBuf = aStatic; + sqlite3_int64 nBuf = 64; + int n; + + while( 1 ){ + n = readlink(pCur->zPath, aBuf, nBuf); + if( nzPath); + } + } + case FSDIR_COLUMN_PATH: + default: { + /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters. + ** always return their values as NULL */ + break; + } + } + return SQLITE_OK; +} + +/* +** Return the rowid for the current row. In this implementation, the +** first row returned is assigned rowid value 1, and each subsequent +** row a value 1 more than that of the previous. +*/ +static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + fsdir_cursor *pCur = (fsdir_cursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** Return TRUE if the cursor has been moved off of the last +** row of output. +*/ +static int fsdirEof(sqlite3_vtab_cursor *cur){ + fsdir_cursor *pCur = (fsdir_cursor*)cur; + return (pCur->zPath==0); +} + +/* +** xFilter callback. +** +** idxNum==1 PATH parameter only +** idxNum==2 Both PATH and DIR supplied +*/ +static int fsdirFilter( + sqlite3_vtab_cursor *cur, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + const char *zDir = 0; + fsdir_cursor *pCur = (fsdir_cursor*)cur; + (void)idxStr; + fsdirResetCursor(pCur); + + if( idxNum==0 ){ + fsdirSetErrmsg(pCur, "table function fsdir requires an argument"); + return SQLITE_ERROR; + } + + assert( argc==idxNum && (argc==1 || argc==2) ); + zDir = (const char*)sqlite3_value_text(argv[0]); + if( zDir==0 ){ + fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument"); + return SQLITE_ERROR; + } + if( argc==2 ){ + pCur->zBase = (const char*)sqlite3_value_text(argv[1]); + } + if( pCur->zBase ){ + pCur->nBase = (int)strlen(pCur->zBase)+1; + pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir); + }else{ + pCur->zPath = sqlite3_mprintf("%s", zDir); + } + + if( pCur->zPath==0 ){ + return SQLITE_NOMEM; + } + if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ + fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); + return SQLITE_ERROR; + } + + return SQLITE_OK; +} + +/* +** SQLite will invoke this method one or more times while planning a query +** that uses the generate_series virtual table. This routine needs to create +** a query plan for each invocation and compute an estimated cost for that +** plan. +** +** In this implementation idxNum is used to represent the +** query plan. idxStr is unused. +** +** The query plan is represented by values of idxNum: +** +** (1) The path value is supplied by argv[0] +** (2) Path is in argv[0] and dir is in argv[1] +*/ +static int fsdirBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo +){ + int i; /* Loop over constraints */ + int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */ + int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */ + int seenPath = 0; /* True if an unusable PATH= constraint is seen */ + int seenDir = 0; /* True if an unusable DIR= constraint is seen */ + const struct sqlite3_index_constraint *pConstraint; + + (void)tab; + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; + switch( pConstraint->iColumn ){ + case FSDIR_COLUMN_PATH: { + if( pConstraint->usable ){ + idxPath = i; + seenPath = 0; + }else if( idxPath<0 ){ + seenPath = 1; + } + break; + } + case FSDIR_COLUMN_DIR: { + if( pConstraint->usable ){ + idxDir = i; + seenDir = 0; + }else if( idxDir<0 ){ + seenDir = 1; + } + break; + } + } + } + if( seenPath || seenDir ){ + /* If input parameters are unusable, disallow this plan */ + return SQLITE_CONSTRAINT; + } + + if( idxPath<0 ){ + pIdxInfo->idxNum = 0; + /* The pIdxInfo->estimatedCost should have been initialized to a huge + ** number. Leave it unchanged. */ + pIdxInfo->estimatedRows = 0x7fffffff; + }else{ + pIdxInfo->aConstraintUsage[idxPath].omit = 1; + pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1; + if( idxDir>=0 ){ + pIdxInfo->aConstraintUsage[idxDir].omit = 1; + pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2; + pIdxInfo->idxNum = 2; + pIdxInfo->estimatedCost = 10.0; + }else{ + pIdxInfo->idxNum = 1; + pIdxInfo->estimatedCost = 100.0; + } + } + + return SQLITE_OK; +} + +/* +** Register the "fsdir" virtual table. +*/ +static int fsdirRegister(sqlite3 *db){ + static sqlite3_module fsdirModule = { + 0, /* iVersion */ + 0, /* xCreate */ + fsdirConnect, /* xConnect */ + fsdirBestIndex, /* xBestIndex */ + fsdirDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + fsdirOpen, /* xOpen - open a cursor */ + fsdirClose, /* xClose - close a cursor */ + fsdirFilter, /* xFilter - configure scan constraints */ + fsdirNext, /* xNext - advance a cursor */ + fsdirEof, /* xEof - check for end of scan */ + fsdirColumn, /* xColumn - read data */ + fsdirRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadowName */ + 0 /* xIntegrity */ + }; + + int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0); + return rc; +} +#else /* SQLITE_OMIT_VIRTUALTABLE */ +# define fsdirRegister(x) SQLITE_OK +#endif + +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_fileio_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused parameter */ + rc = sqlite3_create_function(db, "readfile", 1, + SQLITE_UTF8|SQLITE_DIRECTONLY, 0, + readfileFunc, 0, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "writefile", -1, + SQLITE_UTF8|SQLITE_DIRECTONLY, 0, + writefileFunc, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0, + lsModeFunc, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = fsdirRegister(db); + } + return rc; +} + +#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32)) +/* To allow a standalone DLL, make test_windirent.c use the same + * redefined SQLite API calls as the above extension code does. + * Just pull in this .c to accomplish this. As a beneficial side + * effect, this extension becomes a single translation unit. */ +/* # include "test_windirent.c" */ + +#endif +/*** End of #include "fileio.c" ***/ + +#endif + +/* +** SERIES +*/ +#ifdef SQLITE_ENABLE_SERIES +/* Prototype for initialization function of SERIES extension */ +SQLITE_API +int sqlite3_series_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); +/* #include "series.c" */ +/*** Begin of #include "series.c" ***/ +/* +** 2015-08-18, 2023-04-28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file demonstrates how to create a table-valued-function using +** a virtual table. This demo implements the generate_series() function +** which gives the same results as the eponymous function in PostgreSQL, +** within the limitation that its arguments are signed 64-bit integers. +** +** Considering its equivalents to generate_series(start,stop,step): A +** value V[n] sequence is produced for integer n ascending from 0 where +** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 ) +** for each produced value (independent of production time ordering.) +** +** All parameters must be either integer or convertable to integer. +** The start parameter is required. +** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff) +** The step parameter defaults to 1 and 0 is treated as 1. +** +** Examples: +** +** SELECT * FROM generate_series(0,100,5); +** +** The query above returns integers from 0 through 100 counting by steps +** of 5. +** +** SELECT * FROM generate_series(0,100); +** +** Integers from 0 through 100 with a step size of 1. +** +** SELECT * FROM generate_series(20) LIMIT 10; +** +** Integers 20 through 29. +** +** SELECT * FROM generate_series(0,-100,-5); +** +** Integers 0 -5 -10 ... -100. +** +** SELECT * FROM generate_series(0,-1); +** +** Empty sequence. +** +** HOW IT WORKS +** +** The generate_series "function" is really a virtual table with the +** following schema: +** +** CREATE TABLE generate_series( +** value, +** start HIDDEN, +** stop HIDDEN, +** step HIDDEN +** ); +** +** The virtual table also has a rowid which is an alias for the value. +** +** Function arguments in queries against this virtual table are translated +** into equality constraints against successive hidden columns. In other +** words, the following pairs of queries are equivalent to each other: +** +** SELECT * FROM generate_series(0,100,5); +** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5; +** +** SELECT * FROM generate_series(0,100); +** SELECT * FROM generate_series WHERE start=0 AND stop=100; +** +** SELECT * FROM generate_series(20) LIMIT 10; +** SELECT * FROM generate_series WHERE start=20 LIMIT 10; +** +** The generate_series virtual table implementation leaves the xCreate method +** set to NULL. This means that it is not possible to do a CREATE VIRTUAL +** TABLE command with "generate_series" as the USING argument. Instead, there +** is a single generate_series virtual table that is always available without +** having to be created first. +** +** The xBestIndex method looks for equality constraints against the hidden +** start, stop, and step columns, and if present, it uses those constraints +** to bound the sequence of generated values. If the equality constraints +** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step. +** xBestIndex returns a small cost when both start and stop are available, +** and a very large cost if either start or stop are unavailable. This +** encourages the query planner to order joins such that the bounds of the +** series are well-defined. +** +** Update on 2024-08-22: +** xBestIndex now also looks for equality and inequality constraints against +** the value column and uses those constraints as additional bounds against +** the sequence range. Thus, a query like this: +** +** SELECT value FROM generate_series($SA,$EA) +** WHERE value BETWEEN $SB AND $EB; +** +** Is logically the same as: +** +** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB)); +** +** Constraints on the value column can server as substitutes for constraints +** on the hidden start and stop columns. So, the following two queries +** are equivalent: +** +** SELECT value FROM generate_series($S,$E); +** SELECT value FROM generate_series WHERE value BETWEEN $S and $E; +** +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +#include +#include +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Return that member of a generate_series(...) sequence whose 0-based +** index is ix. The 0th member is given by smBase. The sequence members +** progress per ix increment by smStep. +*/ +static sqlite3_int64 genSeqMember( + sqlite3_int64 smBase, + sqlite3_int64 smStep, + sqlite3_uint64 ix +){ + static const sqlite3_uint64 mxI64 = + ((sqlite3_uint64)0x7fffffff)<<32 | 0xffffffff; + if( ix>=mxI64 ){ + /* Get ix into signed i64 range. */ + ix -= mxI64; + /* With 2's complement ALU, this next can be 1 step, but is split into + * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */ + smBase += (mxI64/2) * smStep; + smBase += (mxI64 - mxI64/2) * smStep; + } + /* Under UBSAN (or on 1's complement machines), must do this last term + * in steps to avoid the dreaded (and harmless) signed multiply overflow. */ + if( ix>=2 ){ + sqlite3_int64 ix2 = (sqlite3_int64)ix/2; + smBase += ix2*smStep; + ix -= ix2; + } + return smBase + ((sqlite3_int64)ix)*smStep; +} + +typedef unsigned char u8; + +typedef struct SequenceSpec { + sqlite3_int64 iOBase; /* Original starting value ("start") */ + sqlite3_int64 iOTerm; /* Original terminal value ("stop") */ + sqlite3_int64 iBase; /* Starting value to actually use */ + sqlite3_int64 iTerm; /* Terminal value to actually use */ + sqlite3_int64 iStep; /* Increment ("step") */ + sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */ + sqlite3_uint64 uSeqIndexNow; /* Current index during generation */ + sqlite3_int64 iValueNow; /* Current value during generation */ + u8 isNotEOF; /* Sequence generation not exhausted */ + u8 isReversing; /* Sequence is being reverse generated */ +} SequenceSpec; + +/* +** Prepare a SequenceSpec for use in generating an integer series +** given initialized iBase, iTerm and iStep values. Sequence is +** initialized per given isReversing. Other members are computed. +*/ +static void setupSequence( SequenceSpec *pss ){ + int bSameSigns; + pss->uSeqIndexMax = 0; + pss->isNotEOF = 0; + bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0); + if( pss->iTerm < pss->iBase ){ + sqlite3_uint64 nuspan = 0; + if( bSameSigns ){ + nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm); + }else{ + /* Under UBSAN (or on 1's complement machines), must do this in steps. + * In this clause, iBase>=0 and iTerm<0 . */ + nuspan = 1; + nuspan += pss->iBase; + nuspan += -(pss->iTerm+1); + } + if( pss->iStep<0 ){ + pss->isNotEOF = 1; + if( nuspan==ULONG_MAX ){ + pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1; + }else if( pss->iStep>LLONG_MIN ){ + pss->uSeqIndexMax = nuspan/-pss->iStep; + } + } + }else if( pss->iTerm > pss->iBase ){ + sqlite3_uint64 puspan = 0; + if( bSameSigns ){ + puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase); + }else{ + /* Under UBSAN (or on 1's complement machines), must do this in steps. + * In this clause, iTerm>=0 and iBase<0 . */ + puspan = 1; + puspan += pss->iTerm; + puspan += -(pss->iBase+1); + } + if( pss->iStep>0 ){ + pss->isNotEOF = 1; + pss->uSeqIndexMax = puspan/pss->iStep; + } + }else if( pss->iTerm == pss->iBase ){ + pss->isNotEOF = 1; + pss->uSeqIndexMax = 0; + } + pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0; + pss->iValueNow = (pss->isReversing) + ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax) + : pss->iBase; +} + +/* +** Progress sequence generator to yield next value, if any. +** Leave its state to either yield next value or be at EOF. +** Return whether there is a next value, or 0 at EOF. +*/ +static int progressSequence( SequenceSpec *pss ){ + if( !pss->isNotEOF ) return 0; + if( pss->isReversing ){ + if( pss->uSeqIndexNow > 0 ){ + pss->uSeqIndexNow--; + pss->iValueNow -= pss->iStep; + }else{ + pss->isNotEOF = 0; + } + }else{ + if( pss->uSeqIndexNow < pss->uSeqIndexMax ){ + pss->uSeqIndexNow++; + pss->iValueNow += pss->iStep; + }else{ + pss->isNotEOF = 0; + } + } + return pss->isNotEOF; +} + +/* series_cursor is a subclass of sqlite3_vtab_cursor which will +** serve as the underlying representation of a cursor that scans +** over rows of the result +*/ +typedef struct series_cursor series_cursor; +struct series_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + SequenceSpec ss; /* (this) Derived class data */ +}; + +/* +** The seriesConnect() method is invoked to create a new +** series_vtab that describes the generate_series virtual table. +** +** Think of this routine as the constructor for series_vtab objects. +** +** All this routine needs to do is: +** +** (1) Allocate the series_vtab object and initialize all fields. +** +** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the +** result set of queries against generate_series will look like. +*/ +static int seriesConnect( + sqlite3 *db, + void *pUnused, + int argcUnused, const char *const*argvUnused, + sqlite3_vtab **ppVtab, + char **pzErrUnused +){ + sqlite3_vtab *pNew; + int rc; + +/* Column numbers */ +#define SERIES_COLUMN_ROWID (-1) +#define SERIES_COLUMN_VALUE 0 +#define SERIES_COLUMN_START 1 +#define SERIES_COLUMN_STOP 2 +#define SERIES_COLUMN_STEP 3 + + (void)pUnused; + (void)argcUnused; + (void)argvUnused; + (void)pzErrUnused; + rc = sqlite3_declare_vtab(db, + "CREATE TABLE x(value,start hidden,stop hidden,step hidden)"); + if( rc==SQLITE_OK ){ + pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); + } + return rc; +} + +/* +** This method is the destructor for series_cursor objects. +*/ +static int seriesDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** Constructor for a new series_cursor object. +*/ +static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){ + series_cursor *pCur; + (void)pUnused; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Destructor for a series_cursor. +*/ +static int seriesClose(sqlite3_vtab_cursor *cur){ + sqlite3_free(cur); + return SQLITE_OK; +} + + +/* +** Advance a series_cursor to its next row of output. +*/ +static int seriesNext(sqlite3_vtab_cursor *cur){ + series_cursor *pCur = (series_cursor*)cur; + progressSequence( & pCur->ss ); + return SQLITE_OK; +} + +/* +** Return values of columns for the row at which the series_cursor +** is currently pointing. +*/ +static int seriesColumn( + sqlite3_vtab_cursor *cur, /* The cursor */ + sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ + int i /* Which column to return */ +){ + series_cursor *pCur = (series_cursor*)cur; + sqlite3_int64 x = 0; + switch( i ){ + case SERIES_COLUMN_START: x = pCur->ss.iOBase; break; + case SERIES_COLUMN_STOP: x = pCur->ss.iOTerm; break; + case SERIES_COLUMN_STEP: x = pCur->ss.iStep; break; + default: x = pCur->ss.iValueNow; break; + } + sqlite3_result_int64(ctx, x); + return SQLITE_OK; +} + +#ifndef LARGEST_UINT64 +#define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) +#define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32)) +#define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) +#endif + +/* +** The rowid is the same as the value. +*/ +static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + series_cursor *pCur = (series_cursor*)cur; + *pRowid = pCur->ss.iValueNow; + return SQLITE_OK; +} + +/* +** Return TRUE if the cursor has been moved off of the last +** row of output. +*/ +static int seriesEof(sqlite3_vtab_cursor *cur){ + series_cursor *pCur = (series_cursor*)cur; + return !pCur->ss.isNotEOF; +} + +/* True to cause run-time checking of the start=, stop=, and/or step= +** parameters. The only reason to do this is for testing the +** constraint checking logic for virtual tables in the SQLite core. +*/ +#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY +# define SQLITE_SERIES_CONSTRAINT_VERIFY 0 +#endif + +/* +** This method is called to "rewind" the series_cursor object back +** to the first row of output. This method is always called at least +** once prior to any call to seriesColumn() or seriesRowid() or +** seriesEof(). +** +** The query plan selected by seriesBestIndex is passed in the idxNum +** parameter. (idxStr is not used in this implementation.) idxNum +** is a bitmask showing which constraints are available: +** +** 0x0001: start=VALUE +** 0x0002: stop=VALUE +** 0x0004: step=VALUE +** 0x0008: descending order +** 0x0010: ascending order +** 0x0020: LIMIT VALUE +** 0x0040: OFFSET VALUE +** 0x0080: value=VALUE +** 0x0100: value>=VALUE +** 0x0200: value>VALUE +** 0x1000: value<=VALUE +** 0x2000: valuess.iBase = sqlite3_value_int64(argv[i++]); + }else{ + pCur->ss.iBase = 0; + } + if( idxNum & 0x02 ){ + pCur->ss.iTerm = sqlite3_value_int64(argv[i++]); + }else{ + pCur->ss.iTerm = 0xffffffff; + } + if( idxNum & 0x04 ){ + pCur->ss.iStep = sqlite3_value_int64(argv[i++]); + if( pCur->ss.iStep==0 ){ + pCur->ss.iStep = 1; + }else if( pCur->ss.iStep<0 ){ + if( (idxNum & 0x10)==0 ) idxNum |= 0x08; + } + }else{ + pCur->ss.iStep = 1; + } + + /* If there are constraints on the value column but there are + ** no constraints on the start, stop, and step columns, then + ** initialize the default range to be the entire range of 64-bit signed + ** integers. This range will contracted by the value column constraints + ** further below. + */ + if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){ + pCur->ss.iBase = SMALLEST_INT64; + } + if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){ + pCur->ss.iTerm = LARGEST_INT64; + } + pCur->ss.iOBase = pCur->ss.iBase; + pCur->ss.iOTerm = pCur->ss.iTerm; + + /* Extract the LIMIT and OFFSET values, but do not apply them yet. + ** The range must first be constrained by the limits on value. + */ + if( idxNum & 0x20 ){ + iLimit = sqlite3_value_int64(argv[i++]); + if( idxNum & 0x40 ){ + iOffset = sqlite3_value_int64(argv[i++]); + } + } + + if( idxNum & 0x3380 ){ + /* Extract the maximum range of output values determined by + ** constraints on the "value" column. + */ + if( idxNum & 0x0080 ){ + if( sqlite3_value_numeric_type(argv[i])==SQLITE_FLOAT ){ + double r = sqlite3_value_double(argv[i++]); + if( r==ceil(r) ){ + iMin = iMax = (sqlite3_int64)r; + }else{ + returnNoRows = 1; + } + }else{ + iMin = iMax = sqlite3_value_int64(argv[i++]); + } + }else{ + if( idxNum & 0x0300 ){ + if( sqlite3_value_numeric_type(argv[i])==SQLITE_FLOAT ){ + double r = sqlite3_value_double(argv[i++]); + if( idxNum & 0x0200 && r==ceil(r) ){ + iMin = (sqlite3_int64)ceil(r+1.0); + }else{ + iMin = (sqlite3_int64)ceil(r); + } + }else{ + iMin = sqlite3_value_int64(argv[i++]); + if( idxNum & 0x0200 ){ + if( iMin==LARGEST_INT64 ){ + returnNoRows = 1; + }else{ + iMin++; + } + } + } + } + if( idxNum & 0x3000 ){ + if( sqlite3_value_numeric_type(argv[i])==SQLITE_FLOAT ){ + double r = sqlite3_value_double(argv[i++]); + if( (idxNum & 0x2000)!=0 && r==floor(r) ){ + iMax = (sqlite3_int64)(r-1.0); + }else{ + iMax = (sqlite3_int64)floor(r); + } + }else{ + iMax = sqlite3_value_int64(argv[i++]); + if( idxNum & 0x2000 ){ + if( iMax==SMALLEST_INT64 ){ + returnNoRows = 1; + }else{ + iMax--; + } + } + } + } + if( iMin>iMax ){ + returnNoRows = 1; + } + } + + /* Try to reduce the range of values to be generated based on + ** constraints on the "value" column. + */ + if( pCur->ss.iStep>0 ){ + sqlite3_int64 szStep = pCur->ss.iStep; + if( pCur->ss.iBasess.iBase; + pCur->ss.iBase += ((d+szStep-1)/szStep)*szStep; + } + if( pCur->ss.iTerm>iMax ){ + pCur->ss.iTerm = iMax; + } + }else{ + sqlite3_int64 szStep = -pCur->ss.iStep; + assert( szStep>0 ); + if( pCur->ss.iBase>iMax ){ + sqlite3_uint64 d = pCur->ss.iBase - iMax; + pCur->ss.iBase -= ((d+szStep-1)/szStep)*szStep; + } + if( pCur->ss.iTermss.iTerm = iMin; + } + } + } + + /* Apply LIMIT and OFFSET constraints, if any */ + if( idxNum & 0x20 ){ + if( iOffset>0 ){ + pCur->ss.iBase += pCur->ss.iStep*iOffset; + } + if( iLimit>=0 ){ + sqlite3_int64 iTerm; + iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep; + if( pCur->ss.iStep<0 ){ + if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm; + }else{ + if( iTermss.iTerm ) pCur->ss.iTerm = iTerm; + } + } + } + + + for(i=0; iss.iBase = 1; + pCur->ss.iTerm = 0; + pCur->ss.iStep = 1; + } + if( idxNum & 0x08 ){ + pCur->ss.isReversing = pCur->ss.iStep > 0; + }else{ + pCur->ss.isReversing = pCur->ss.iStep < 0; + } + setupSequence( &pCur->ss ); + return SQLITE_OK; +} + +/* +** SQLite will invoke this method one or more times while planning a query +** that uses the generate_series virtual table. This routine needs to create +** a query plan for each invocation and compute an estimated cost for that +** plan. +** +** In this implementation idxNum is used to represent the +** query plan. idxStr is unused. +** +** The query plan is represented by bits in idxNum: +** +** 0x0001 start = $num +** 0x0002 stop = $num +** 0x0004 step = $num +** 0x0008 output is in descending order +** 0x0010 output is in ascending order +** 0x0020 LIMIT $num +** 0x0040 OFFSET $num +** 0x0080 value = $num +** 0x0100 value >= $num +** 0x0200 value > $num +** 0x1000 value <= $num +** 0x2000 value < $num +** +** Only one of 0x0100 or 0x0200 will be returned. Similarly, only +** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then +** none of the 0xff00 bits will be set. +** +** The order of parameters passed to xFilter is as follows: +** +** * The argument to start= if bit 0x0001 is in the idxNum mask +** * The argument to stop= if bit 0x0002 is in the idxNum mask +** * The argument to step= if bit 0x0004 is in the idxNum mask +** * The argument to LIMIT if bit 0x0020 is in the idxNum mask +** * The argument to OFFSET if bit 0x0040 is in the idxNum mask +** * The argument to value=, or value>= or value> if any of +** bits 0x0380 are in the idxNum mask +** * The argument to value<= or value< if either of bits 0x3000 +** are in the mask +** +*/ +static int seriesBestIndex( + sqlite3_vtab *pVTab, + sqlite3_index_info *pIdxInfo +){ + int i, j; /* Loop over constraints */ + int idxNum = 0; /* The query plan bitmask */ +#ifndef ZERO_ARGUMENT_GENERATE_SERIES + int bStartSeen = 0; /* EQ constraint seen on the START column */ +#endif + int unusableMask = 0; /* Mask of unusable constraints */ + int nArg = 0; /* Number of arguments that seriesFilter() expects */ + int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET, + ** and value. aIdx[5] covers value=, value>=, and + ** value>, aIdx[6] covers value<= and value< */ + const struct sqlite3_index_constraint *pConstraint; + + /* This implementation assumes that the start, stop, and step columns + ** are the last three columns in the virtual table. */ + assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 ); + assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 ); + + aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1; + pConstraint = pIdxInfo->aConstraint; + for(i=0; inConstraint; i++, pConstraint++){ + int iCol; /* 0 for start, 1 for stop, 2 for step */ + int iMask; /* bitmask for those column */ + int op = pConstraint->op; + if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT + && op<=SQLITE_INDEX_CONSTRAINT_OFFSET + ){ + if( pConstraint->usable==0 ){ + /* do nothing */ + }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){ + aIdx[3] = i; + idxNum |= 0x20; + }else{ + assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET ); + aIdx[4] = i; + idxNum |= 0x40; + } + continue; + } + if( pConstraint->iColumniColumn==SERIES_COLUMN_VALUE || + pConstraint->iColumn==SERIES_COLUMN_ROWID) + && pConstraint->usable + ){ + switch( op ){ + case SQLITE_INDEX_CONSTRAINT_EQ: + case SQLITE_INDEX_CONSTRAINT_IS: { + idxNum |= 0x0080; + idxNum &= ~0x3300; + aIdx[5] = i; + aIdx[6] = -1; +#ifndef ZERO_ARGUMENT_GENERATE_SERIES + bStartSeen = 1; +#endif + break; + } + case SQLITE_INDEX_CONSTRAINT_GE: { + if( idxNum & 0x0080 ) break; + idxNum |= 0x0100; + idxNum &= ~0x0200; + aIdx[5] = i; +#ifndef ZERO_ARGUMENT_GENERATE_SERIES + bStartSeen = 1; +#endif + break; + } + case SQLITE_INDEX_CONSTRAINT_GT: { + if( idxNum & 0x0080 ) break; + idxNum |= 0x0200; + idxNum &= ~0x0100; + aIdx[5] = i; +#ifndef ZERO_ARGUMENT_GENERATE_SERIES + bStartSeen = 1; +#endif + break; + } + case SQLITE_INDEX_CONSTRAINT_LE: { + if( idxNum & 0x0080 ) break; + idxNum |= 0x1000; + idxNum &= ~0x2000; + aIdx[6] = i; + break; + } + case SQLITE_INDEX_CONSTRAINT_LT: { + if( idxNum & 0x0080 ) break; + idxNum |= 0x2000; + idxNum &= ~0x1000; + aIdx[6] = i; + break; + } + } + } + continue; + } + iCol = pConstraint->iColumn - SERIES_COLUMN_START; + assert( iCol>=0 && iCol<=2 ); + iMask = 1 << iCol; +#ifndef ZERO_ARGUMENT_GENERATE_SERIES + if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){ + bStartSeen = 1; + } +#endif + if( pConstraint->usable==0 ){ + unusableMask |= iMask; + continue; + }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){ + idxNum |= iMask; + aIdx[iCol] = i; + } + } + if( aIdx[3]==0 ){ + /* Ignore OFFSET if LIMIT is omitted */ + idxNum &= ~0x60; + aIdx[4] = 0; + } + for(i=0; i<7; i++){ + if( (j = aIdx[i])>=0 ){ + pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg; + pIdxInfo->aConstraintUsage[j].omit = + !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3; + } + } + /* The current generate_column() implementation requires at least one + ** argument (the START value). Legacy versions assumed START=0 if the + ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES + ** to obtain the legacy behavior */ +#ifndef ZERO_ARGUMENT_GENERATE_SERIES + if( !bStartSeen ){ + sqlite3_free(pVTab->zErrMsg); + pVTab->zErrMsg = sqlite3_mprintf( + "first argument to \"generate_series()\" missing or unusable"); + return SQLITE_ERROR; + } +#endif + if( (unusableMask & ~idxNum)!=0 ){ + /* The start, stop, and step columns are inputs. Therefore if there + ** are unusable constraints on any of start, stop, or step then + ** this plan is unusable */ + return SQLITE_CONSTRAINT; + } + if( (idxNum & 0x03)==0x03 ){ + /* Both start= and stop= boundaries are available. This is the + ** the preferred case */ + pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0)); + pIdxInfo->estimatedRows = 1000; + if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){ + if( pIdxInfo->aOrderBy[0].desc ){ + idxNum |= 0x08; + }else{ + idxNum |= 0x10; + } + pIdxInfo->orderByConsumed = 1; + } + }else if( (idxNum & 0x21)==0x21 ){ + /* We have start= and LIMIT */ + pIdxInfo->estimatedRows = 2500; + }else{ + /* If either boundary is missing, we have to generate a huge span + ** of numbers. Make this case very expensive so that the query + ** planner will work hard to avoid it. */ + pIdxInfo->estimatedRows = 2147483647; + } + pIdxInfo->idxNum = idxNum; +#ifdef SQLITE_INDEX_SCAN_HEX + pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX; +#endif + return SQLITE_OK; +} + +/* +** This following structure defines all the methods for the +** generate_series virtual table. +*/ +static sqlite3_module seriesModule = { + 0, /* iVersion */ + 0, /* xCreate */ + seriesConnect, /* xConnect */ + seriesBestIndex, /* xBestIndex */ + seriesDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + seriesOpen, /* xOpen - open a cursor */ + seriesClose, /* xClose - close a cursor */ + seriesFilter, /* xFilter - configure scan constraints */ + seriesNext, /* xNext - advance a cursor */ + seriesEof, /* xEof - check for end of scan */ + seriesColumn, /* xColumn - read data */ + seriesRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadowName */ + 0 /* xIntegrity */ +}; + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_series_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){ + *pzErrMsg = sqlite3_mprintf( + "generate_series() requires SQLite 3.8.12 or later"); + return SQLITE_ERROR; + } + rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0); +#endif + return rc; +} +/*** End of #include "series.c" ***/ + +#endif + +/* +** UUID +*/ +#ifdef SQLITE_ENABLE_UUID +/* Prototype for initialization function of UUID extension */ +SQLITE_API +int sqlite3_uuid_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); +/* #include "uuid.c" */ +/*** Begin of #include "uuid.c" ***/ +/* +** 2019-10-23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This SQLite extension implements functions that handling RFC-4122 UUIDs +** Three SQL functions are implemented: +** +** uuid() - generate a version 4 UUID as a string +** uuid_str(X) - convert a UUID X into a well-formed UUID string +** uuid_blob(X) - convert a UUID X into a 16-byte blob +** +** The output from uuid() and uuid_str(X) are always well-formed RFC-4122 +** UUID strings in this format: +** +** xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx +** +** All of the 'x', 'M', and 'N' values are lower-case hexadecimal digits. +** The M digit indicates the "version". For uuid()-generated UUIDs, the +** version is always "4" (a random UUID). The upper three bits of N digit +** are the "variant". This library only supports variant 1 (indicated +** by values of N between '8' and 'b') as those are overwhelming the most +** common. Other variants are for legacy compatibility only. +** +** The output of uuid_blob(X) is always a 16-byte blob. The UUID input +** string is converted in network byte order (big-endian) in accordance +** with RFC-4122 specifications for variant-1 UUIDs. Note that network +** byte order is *always* used, even if the input self-identifies as a +** variant-2 UUID. +** +** The input X to the uuid_str() and uuid_blob() functions can be either +** a string or a BLOB. If it is a BLOB it must be exactly 16 bytes in +** length or else a NULL is returned. If the input is a string it must +** consist of 32 hexadecimal digits, upper or lower case, optionally +** surrounded by {...} and with optional "-" characters interposed in the +** middle. The flexibility of input is inspired by the PostgreSQL +** implementation of UUID functions that accept in all of the following +** formats: +** +** A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11 +** {a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11} +** a0eebc999c0b4ef8bb6d6bb9bd380a11 +** a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11 +** {a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11} +** +** If any of the above inputs are passed into uuid_str(), the output will +** always be in the canonical RFC-4122 format: +** +** a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 +** +** If the X input string has too few or too many digits or contains +** stray characters other than {, }, or -, then NULL is returned. +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +#include +#include +#include + +#if !defined(SQLITE_ASCII) && !defined(SQLITE_EBCDIC) +# define SQLITE_ASCII 1 +#endif + +/* +** Translate a single byte of Hex into an integer. +** This routine only works if h really is a valid hexadecimal +** character: 0..9a..fA..F +*/ +static unsigned char sqlite3UuidHexToInt(int h){ + assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); +#ifdef SQLITE_ASCII + h += 9*(1&(h>>6)); +#endif +#ifdef SQLITE_EBCDIC + h += 9*(1&~(h>>4)); +#endif + return (unsigned char)(h & 0xf); +} + +/* +** Convert a 16-byte BLOB into a well-formed RFC-4122 UUID. The output +** buffer zStr should be at least 37 bytes in length. The output will +** be zero-terminated. +*/ +static void sqlite3UuidBlobToStr( + const unsigned char *aBlob, /* Input blob */ + unsigned char *zStr /* Write the answer here */ +){ + static const char zDigits[] = "0123456789abcdef"; + int i, k; + unsigned char x; + k = 0; + for(i=0, k=0x550; i<16; i++, k=k>>1){ + if( k&1 ){ + zStr[0] = '-'; + zStr++; + } + x = aBlob[i]; + zStr[0] = zDigits[x>>4]; + zStr[1] = zDigits[x&0xf]; + zStr += 2; + } + *zStr = 0; +} + +/* +** Attempt to parse a zero-terminated input string zStr into a binary +** UUID. Return 0 on success, or non-zero if the input string is not +** parsable. +*/ +static int sqlite3UuidStrToBlob( + const unsigned char *zStr, /* Input string */ + unsigned char *aBlob /* Write results here */ +){ + int i; + if( zStr[0]=='{' ) zStr++; + for(i=0; i<16; i++){ + if( zStr[0]=='-' ) zStr++; + if( isxdigit(zStr[0]) && isxdigit(zStr[1]) ){ + aBlob[i] = (sqlite3UuidHexToInt(zStr[0])<<4) + + sqlite3UuidHexToInt(zStr[1]); + zStr += 2; + }else{ + return 1; + } + } + if( zStr[0]=='}' ) zStr++; + return zStr[0]!=0; +} + +/* +** Render sqlite3_value pIn as a 16-byte UUID blob. Return a pointer +** to the blob, or NULL if the input is not well-formed. +*/ +static const unsigned char *sqlite3UuidInputToBlob( + sqlite3_value *pIn, /* Input text */ + unsigned char *pBuf /* output buffer */ +){ + switch( sqlite3_value_type(pIn) ){ + case SQLITE_TEXT: { + const unsigned char *z = sqlite3_value_text(pIn); + if( sqlite3UuidStrToBlob(z, pBuf) ) return 0; + return pBuf; + } + case SQLITE_BLOB: { + int n = sqlite3_value_bytes(pIn); + return n==16 ? sqlite3_value_blob(pIn) : 0; + } + default: { + return 0; + } + } +} + +/* Implementation of uuid() */ +static void sqlite3UuidFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + unsigned char aBlob[16]; + unsigned char zStr[37]; + (void)argc; + (void)argv; + sqlite3_randomness(16, aBlob); + aBlob[6] = (aBlob[6]&0x0f) + 0x40; + aBlob[8] = (aBlob[8]&0x3f) + 0x80; + sqlite3UuidBlobToStr(aBlob, zStr); + sqlite3_result_text(context, (char*)zStr, 36, SQLITE_TRANSIENT); +} + +/* Implementation of uuid_str() */ +static void sqlite3UuidStrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + unsigned char aBlob[16]; + unsigned char zStr[37]; + const unsigned char *pBlob; + (void)argc; + pBlob = sqlite3UuidInputToBlob(argv[0], aBlob); + if( pBlob==0 ) return; + sqlite3UuidBlobToStr(pBlob, zStr); + sqlite3_result_text(context, (char*)zStr, 36, SQLITE_TRANSIENT); +} + +/* Implementation of uuid_blob() */ +static void sqlite3UuidBlobFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + unsigned char aBlob[16]; + const unsigned char *pBlob; + (void)argc; + pBlob = sqlite3UuidInputToBlob(argv[0], aBlob); + if( pBlob==0 ) return; + sqlite3_result_blob(context, pBlob, 16, SQLITE_TRANSIENT); +} + +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_uuid_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused parameter */ + rc = sqlite3_create_function(db, "uuid", 0, SQLITE_UTF8|SQLITE_INNOCUOUS, 0, + sqlite3UuidFunc, 0, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "uuid_str", 1, + SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, + 0, sqlite3UuidStrFunc, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "uuid_blob", 1, + SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, + 0, sqlite3UuidBlobFunc, 0, 0); + } + return rc; +} +/*** End of #include "uuid.c" ***/ + +#endif + +/* +** REGEXP +*/ +#ifdef SQLITE_ENABLE_REGEXP +/* Prototype for initialization function of REGEXP extension */ +SQLITE_API +int sqlite3_regexp_init(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi); +/* #include "regexp.c" */ +/*** Begin of #include "regexp.c" ***/ +/* +** 2012-11-13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** The code in this file implements a compact but reasonably +** efficient regular-expression matcher for posix extended regular +** expressions against UTF8 text. +** +** This file is an SQLite extension. It registers a single function +** named "regexp(A,B)" where A is the regular expression and B is the +** string to be matched. By registering this function, SQLite will also +** then implement the "B regexp A" operator. Note that with the function +** the regular expression comes first, but with the operator it comes +** second. +** +** The following regular expression syntax is supported: +** +** X* zero or more occurrences of X +** X+ one or more occurrences of X +** X? zero or one occurrences of X +** X{p,q} between p and q occurrences of X +** (X) match X +** X|Y X or Y +** ^X X occurring at the beginning of the string +** X$ X occurring at the end of the string +** . Match any single character +** \c Character c where c is one of \{}()[]|*+?. +** \c C-language escapes for c in afnrtv. ex: \t or \n +** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX +** \xXX Where XX is exactly 2 hex digits, unicode value XX +** [abc] Any single character from the set abc +** [^abc] Any single character not in the set abc +** [a-z] Any single character in the range a-z +** [^a-z] Any single character not in the range a-z +** \b Word boundary +** \w Word character. [A-Za-z0-9_] +** \W Non-word character +** \d Digit +** \D Non-digit +** \s Whitespace character +** \S Non-whitespace character +** +** A nondeterministic finite automaton (NFA) is used for matching, so the +** performance is bounded by O(N*M) where N is the size of the regular +** expression and M is the size of the input string. The matcher never +** exhibits exponential behavior. Note that the X{p,q} operator expands +** to p copies of X following by q-p copies of X? and that the size of the +** regular expression in the O(N*M) performance bound is computed after +** this expansion. +*/ +#include +#include +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 + +/* +** The following #defines change the names of some functions implemented in +** this file to prevent name collisions with C-library functions of the +** same name. +*/ +#define re_match sqlite3re_match +#define re_compile sqlite3re_compile +#define re_free sqlite3re_free + +/* The end-of-input character */ +#define RE_EOF 0 /* End of input */ +#define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */ + +/* The NFA is implemented as sequence of opcodes taken from the following +** set. Each opcode has a single integer argument. +*/ +#define RE_OP_MATCH 1 /* Match the one character in the argument */ +#define RE_OP_ANY 2 /* Match any one character. (Implements ".") */ +#define RE_OP_ANYSTAR 3 /* Special optimized version of .* */ +#define RE_OP_FORK 4 /* Continue to both next and opcode at iArg */ +#define RE_OP_GOTO 5 /* Jump to opcode at iArg */ +#define RE_OP_ACCEPT 6 /* Halt and indicate a successful match */ +#define RE_OP_CC_INC 7 /* Beginning of a [...] character class */ +#define RE_OP_CC_EXC 8 /* Beginning of a [^...] character class */ +#define RE_OP_CC_VALUE 9 /* Single value in a character class */ +#define RE_OP_CC_RANGE 10 /* Range of values in a character class */ +#define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */ +#define RE_OP_NOTWORD 12 /* Not a perl word character */ +#define RE_OP_DIGIT 13 /* digit: [0-9] */ +#define RE_OP_NOTDIGIT 14 /* Not a digit */ +#define RE_OP_SPACE 15 /* space: [ \t\n\r\v\f] */ +#define RE_OP_NOTSPACE 16 /* Not a digit */ +#define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */ +#define RE_OP_ATSTART 18 /* Currently at the start of the string */ + +#if defined(SQLITE_DEBUG) +/* Opcode names used for symbolic debugging */ +static const char *ReOpName[] = { + "EOF", + "MATCH", + "ANY", + "ANYSTAR", + "FORK", + "GOTO", + "ACCEPT", + "CC_INC", + "CC_EXC", + "CC_VALUE", + "CC_RANGE", + "WORD", + "NOTWORD", + "DIGIT", + "NOTDIGIT", + "SPACE", + "NOTSPACE", + "BOUNDARY", + "ATSTART", +}; +#endif /* SQLITE_DEBUG */ + + +/* Each opcode is a "state" in the NFA */ +typedef unsigned short ReStateNumber; + +/* Because this is an NFA and not a DFA, multiple states can be active at +** once. An instance of the following object records all active states in +** the NFA. The implementation is optimized for the common case where the +** number of actives states is small. +*/ +typedef struct ReStateSet { + unsigned nState; /* Number of current states */ + ReStateNumber *aState; /* Current states */ +} ReStateSet; + +/* An input string read one character at a time. +*/ +typedef struct ReInput ReInput; +struct ReInput { + const unsigned char *z; /* All text */ + int i; /* Next byte to read */ + int mx; /* EOF when i>=mx */ +}; + +/* A compiled NFA (or an NFA that is in the process of being compiled) is +** an instance of the following object. +*/ +typedef struct ReCompiled ReCompiled; +struct ReCompiled { + ReInput sIn; /* Regular expression text */ + const char *zErr; /* Error message to return */ + char *aOp; /* Operators for the virtual machine */ + int *aArg; /* Arguments to each operator */ + unsigned (*xNextChar)(ReInput*); /* Next character function */ + unsigned char zInit[12]; /* Initial text to match */ + int nInit; /* Number of bytes in zInit */ + unsigned nState; /* Number of entries in aOp[] and aArg[] */ + unsigned nAlloc; /* Slots allocated for aOp[] and aArg[] */ +}; + +/* Add a state to the given state set if it is not already there */ +static void re_add_state(ReStateSet *pSet, int newState){ + unsigned i; + for(i=0; inState; i++) if( pSet->aState[i]==newState ) return; + pSet->aState[pSet->nState++] = (ReStateNumber)newState; +} + +/* Extract the next unicode character from *pzIn and return it. Advance +** *pzIn to the first byte past the end of the character returned. To +** be clear: this routine converts utf8 to unicode. This routine is +** optimized for the common case where the next character is a single byte. +*/ +static unsigned re_next_char(ReInput *p){ + unsigned c; + if( p->i>=p->mx ) return 0; + c = p->z[p->i++]; + if( c>=0x80 ){ + if( (c&0xe0)==0xc0 && p->imx && (p->z[p->i]&0xc0)==0x80 ){ + c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f); + if( c<0x80 ) c = 0xfffd; + }else if( (c&0xf0)==0xe0 && p->i+1mx && (p->z[p->i]&0xc0)==0x80 + && (p->z[p->i+1]&0xc0)==0x80 ){ + c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f); + p->i += 2; + if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd; + }else if( (c&0xf8)==0xf0 && p->i+2mx && (p->z[p->i]&0xc0)==0x80 + && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){ + c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6) + | (p->z[p->i+2]&0x3f); + p->i += 3; + if( c<=0xffff || c>0x10ffff ) c = 0xfffd; + }else{ + c = 0xfffd; + } + } + return c; +} +static unsigned re_next_char_nocase(ReInput *p){ + unsigned c = re_next_char(p); + if( c>='A' && c<='Z' ) c += 'a' - 'A'; + return c; +} + +/* Return true if c is a perl "word" character: [A-Za-z0-9_] */ +static int re_word_char(int c){ + return (c>='0' && c<='9') || (c>='a' && c<='z') + || (c>='A' && c<='Z') || c=='_'; +} + +/* Return true if c is a "digit" character: [0-9] */ +static int re_digit_char(int c){ + return (c>='0' && c<='9'); +} + +/* Return true if c is a perl "space" character: [ \t\r\n\v\f] */ +static int re_space_char(int c){ + return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; +} + +/* Run a compiled regular expression on the zero-terminated input +** string zIn[]. Return true on a match and false if there is no match. +*/ +static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){ + ReStateSet aStateSet[2], *pThis, *pNext; + ReStateNumber aSpace[100]; + ReStateNumber *pToFree; + unsigned int i = 0; + unsigned int iSwap = 0; + int c = RE_START; + int cPrev = 0; + int rc = 0; + ReInput in; + + in.z = zIn; + in.i = 0; + in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn); + + /* Look for the initial prefix match, if there is one. */ + if( pRe->nInit ){ + unsigned char x = pRe->zInit[0]; + while( in.i+pRe->nInit<=in.mx + && (zIn[in.i]!=x || + strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0) + ){ + in.i++; + } + if( in.i+pRe->nInit>in.mx ) return 0; + c = RE_START-1; + } + + if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){ + pToFree = 0; + aStateSet[0].aState = aSpace; + }else{ + pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState ); + if( pToFree==0 ) return -1; + aStateSet[0].aState = pToFree; + } + aStateSet[1].aState = &aStateSet[0].aState[pRe->nState]; + pNext = &aStateSet[1]; + pNext->nState = 0; + re_add_state(pNext, 0); + while( c!=RE_EOF && pNext->nState>0 ){ + cPrev = c; + c = pRe->xNextChar(&in); + pThis = pNext; + pNext = &aStateSet[iSwap]; + iSwap = 1 - iSwap; + pNext->nState = 0; + for(i=0; inState; i++){ + int x = pThis->aState[i]; + switch( pRe->aOp[x] ){ + case RE_OP_MATCH: { + if( pRe->aArg[x]==c ) re_add_state(pNext, x+1); + break; + } + case RE_OP_ATSTART: { + if( cPrev==RE_START ) re_add_state(pThis, x+1); + break; + } + case RE_OP_ANY: { + if( c!=0 ) re_add_state(pNext, x+1); + break; + } + case RE_OP_WORD: { + if( re_word_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_NOTWORD: { + if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1); + break; + } + case RE_OP_DIGIT: { + if( re_digit_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_NOTDIGIT: { + if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1); + break; + } + case RE_OP_SPACE: { + if( re_space_char(c) ) re_add_state(pNext, x+1); + break; + } + case RE_OP_NOTSPACE: { + if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1); + break; + } + case RE_OP_BOUNDARY: { + if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1); + break; + } + case RE_OP_ANYSTAR: { + re_add_state(pNext, x); + re_add_state(pThis, x+1); + break; + } + case RE_OP_FORK: { + re_add_state(pThis, x+pRe->aArg[x]); + re_add_state(pThis, x+1); + break; + } + case RE_OP_GOTO: { + re_add_state(pThis, x+pRe->aArg[x]); + break; + } + case RE_OP_ACCEPT: { + rc = 1; + goto re_match_end; + } + case RE_OP_CC_EXC: { + if( c==0 ) break; + /* fall-through */ goto re_op_cc_inc; + } + case RE_OP_CC_INC: re_op_cc_inc: { + int j = 1; + int n = pRe->aArg[x]; + int hit = 0; + for(j=1; j>0 && jaOp[x+j]==RE_OP_CC_VALUE ){ + if( pRe->aArg[x+j]==c ){ + hit = 1; + j = -1; + } + }else{ + if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){ + hit = 1; + j = -1; + }else{ + j++; + } + } + } + if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit; + if( hit ) re_add_state(pNext, x+n); + break; + } + } + } + } + for(i=0; inState; i++){ + int x = pNext->aState[i]; + while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x]; + if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; } + } +re_match_end: + sqlite3_free(pToFree); + return rc; +} + +/* Resize the opcode and argument arrays for an RE under construction. +*/ +static int re_resize(ReCompiled *p, int N){ + char *aOp; + int *aArg; + aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0])); + if( aOp==0 ) return 1; + p->aOp = aOp; + aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0])); + if( aArg==0 ) return 1; + p->aArg = aArg; + p->nAlloc = N; + return 0; +} + +/* Insert a new opcode and argument into an RE under construction. The +** insertion point is just prior to existing opcode iBefore. +*/ +static int re_insert(ReCompiled *p, int iBefore, int op, int arg){ + int i; + if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0; + for(i=p->nState; i>iBefore; i--){ + p->aOp[i] = p->aOp[i-1]; + p->aArg[i] = p->aArg[i-1]; + } + p->nState++; + p->aOp[iBefore] = (char)op; + p->aArg[iBefore] = arg; + return iBefore; +} + +/* Append a new opcode and argument to the end of the RE under construction. +*/ +static int re_append(ReCompiled *p, int op, int arg){ + return re_insert(p, p->nState, op, arg); +} + +/* Make a copy of N opcodes starting at iStart onto the end of the RE +** under construction. +*/ +static void re_copy(ReCompiled *p, int iStart, int N){ + if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return; + memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0])); + memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0])); + p->nState += N; +} + +/* Return true if c is a hexadecimal digit character: [0-9a-fA-F] +** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c). If +** c is not a hex digit *pV is unchanged. +*/ +static int re_hex(int c, int *pV){ + if( c>='0' && c<='9' ){ + c -= '0'; + }else if( c>='a' && c<='f' ){ + c -= 'a' - 10; + }else if( c>='A' && c<='F' ){ + c -= 'A' - 10; + }else{ + return 0; + } + *pV = (*pV)*16 + (c & 0xff); + return 1; +} + +/* A backslash character has been seen, read the next character and +** return its interpretation. +*/ +static unsigned re_esc_char(ReCompiled *p){ + static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]"; + static const char zTrans[] = "\a\f\n\r\t\v"; + int i, v = 0; + char c; + if( p->sIn.i>=p->sIn.mx ) return 0; + c = p->sIn.z[p->sIn.i]; + if( c=='u' && p->sIn.i+4sIn.mx ){ + const unsigned char *zIn = p->sIn.z + p->sIn.i; + if( re_hex(zIn[1],&v) + && re_hex(zIn[2],&v) + && re_hex(zIn[3],&v) + && re_hex(zIn[4],&v) + ){ + p->sIn.i += 5; + return v; + } + } + if( c=='x' && p->sIn.i+2sIn.mx ){ + const unsigned char *zIn = p->sIn.z + p->sIn.i; + if( re_hex(zIn[1],&v) + && re_hex(zIn[2],&v) + ){ + p->sIn.i += 3; + return v; + } + } + for(i=0; zEsc[i] && zEsc[i]!=c; i++){} + if( zEsc[i] ){ + if( i<6 ) c = zTrans[i]; + p->sIn.i++; + }else{ + p->zErr = "unknown \\ escape"; + } + return c; +} + +/* Forward declaration */ +static const char *re_subcompile_string(ReCompiled*); + +/* Peek at the next byte of input */ +static unsigned char rePeek(ReCompiled *p){ + return p->sIn.isIn.mx ? p->sIn.z[p->sIn.i] : 0; +} + +/* Compile RE text into a sequence of opcodes. Continue up to the +** first unmatched ")" character, then return. If an error is found, +** return a pointer to the error message string. +*/ +static const char *re_subcompile_re(ReCompiled *p){ + const char *zErr; + int iStart, iEnd, iGoto; + iStart = p->nState; + zErr = re_subcompile_string(p); + if( zErr ) return zErr; + while( rePeek(p)=='|' ){ + iEnd = p->nState; + re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart); + iGoto = re_append(p, RE_OP_GOTO, 0); + p->sIn.i++; + zErr = re_subcompile_string(p); + if( zErr ) return zErr; + p->aArg[iGoto] = p->nState - iGoto; + } + return 0; +} + +/* Compile an element of regular expression text (anything that can be +** an operand to the "|" operator). Return NULL on success or a pointer +** to the error message if there is a problem. +*/ +static const char *re_subcompile_string(ReCompiled *p){ + int iPrev = -1; + int iStart; + unsigned c; + const char *zErr; + while( (c = p->xNextChar(&p->sIn))!=0 ){ + iStart = p->nState; + switch( c ){ + case '|': + case ')': { + p->sIn.i--; + return 0; + } + case '(': { + zErr = re_subcompile_re(p); + if( zErr ) return zErr; + if( rePeek(p)!=')' ) return "unmatched '('"; + p->sIn.i++; + break; + } + case '.': { + if( rePeek(p)=='*' ){ + re_append(p, RE_OP_ANYSTAR, 0); + p->sIn.i++; + }else{ + re_append(p, RE_OP_ANY, 0); + } + break; + } + case '*': { + if( iPrev<0 ) return "'*' without operand"; + re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1); + re_append(p, RE_OP_FORK, iPrev - p->nState + 1); + break; + } + case '+': { + if( iPrev<0 ) return "'+' without operand"; + re_append(p, RE_OP_FORK, iPrev - p->nState); + break; + } + case '?': { + if( iPrev<0 ) return "'?' without operand"; + re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1); + break; + } + case '$': { + re_append(p, RE_OP_MATCH, RE_EOF); + break; + } + case '^': { + re_append(p, RE_OP_ATSTART, 0); + break; + } + case '{': { + int m = 0, n = 0; + int sz, j; + if( iPrev<0 ) return "'{m,n}' without operand"; + while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; } + n = m; + if( c==',' ){ + p->sIn.i++; + n = 0; + while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; } + } + if( c!='}' ) return "unmatched '{'"; + if( n>0 && nsIn.i++; + sz = p->nState - iPrev; + if( m==0 ){ + if( n==0 ) return "both m and n are zero in '{m,n}'"; + re_insert(p, iPrev, RE_OP_FORK, sz+1); + iPrev++; + n--; + }else{ + for(j=1; j0 ){ + re_append(p, RE_OP_FORK, -sz); + } + break; + } + case '[': { + unsigned int iFirst = p->nState; + if( rePeek(p)=='^' ){ + re_append(p, RE_OP_CC_EXC, 0); + p->sIn.i++; + }else{ + re_append(p, RE_OP_CC_INC, 0); + } + while( (c = p->xNextChar(&p->sIn))!=0 ){ + if( c=='[' && rePeek(p)==':' ){ + return "POSIX character classes not supported"; + } + if( c=='\\' ) c = re_esc_char(p); + if( rePeek(p)=='-' ){ + re_append(p, RE_OP_CC_RANGE, c); + p->sIn.i++; + c = p->xNextChar(&p->sIn); + if( c=='\\' ) c = re_esc_char(p); + re_append(p, RE_OP_CC_RANGE, c); + }else{ + re_append(p, RE_OP_CC_VALUE, c); + } + if( rePeek(p)==']' ){ p->sIn.i++; break; } + } + if( c==0 ) return "unclosed '['"; + if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst; + break; + } + case '\\': { + int specialOp = 0; + switch( rePeek(p) ){ + case 'b': specialOp = RE_OP_BOUNDARY; break; + case 'd': specialOp = RE_OP_DIGIT; break; + case 'D': specialOp = RE_OP_NOTDIGIT; break; + case 's': specialOp = RE_OP_SPACE; break; + case 'S': specialOp = RE_OP_NOTSPACE; break; + case 'w': specialOp = RE_OP_WORD; break; + case 'W': specialOp = RE_OP_NOTWORD; break; + } + if( specialOp ){ + p->sIn.i++; + re_append(p, specialOp, 0); + }else{ + c = re_esc_char(p); + re_append(p, RE_OP_MATCH, c); + } + break; + } + default: { + re_append(p, RE_OP_MATCH, c); + break; + } + } + iPrev = iStart; + } + return 0; +} + +/* Free and reclaim all the memory used by a previously compiled +** regular expression. Applications should invoke this routine once +** for every call to re_compile() to avoid memory leaks. +*/ +static void re_free(void *p){ + ReCompiled *pRe = (ReCompiled*)p; + if( pRe ){ + sqlite3_free(pRe->aOp); + sqlite3_free(pRe->aArg); + sqlite3_free(pRe); + } +} + +/* +** Compile a textual regular expression in zIn[] into a compiled regular +** expression suitable for us by re_match() and return a pointer to the +** compiled regular expression in *ppRe. Return NULL on success or an +** error message if something goes wrong. +*/ +static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){ + ReCompiled *pRe; + const char *zErr; + int i, j; + + *ppRe = 0; + pRe = sqlite3_malloc( sizeof(*pRe) ); + if( pRe==0 ){ + return "out of memory"; + } + memset(pRe, 0, sizeof(*pRe)); + pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char; + if( re_resize(pRe, 30) ){ + re_free(pRe); + return "out of memory"; + } + if( zIn[0]=='^' ){ + zIn++; + }else{ + re_append(pRe, RE_OP_ANYSTAR, 0); + } + pRe->sIn.z = (unsigned char*)zIn; + pRe->sIn.i = 0; + pRe->sIn.mx = (int)strlen(zIn); + zErr = re_subcompile_re(pRe); + if( zErr ){ + re_free(pRe); + return zErr; + } + if( pRe->sIn.i>=pRe->sIn.mx ){ + re_append(pRe, RE_OP_ACCEPT, 0); + *ppRe = pRe; + }else{ + re_free(pRe); + return "unrecognized character"; + } + + /* The following is a performance optimization. If the regex begins with + ** ".*" (if the input regex lacks an initial "^") and afterwards there are + ** one or more matching characters, enter those matching characters into + ** zInit[]. The re_match() routine can then search ahead in the input + ** string looking for the initial match without having to run the whole + ** regex engine over the string. Do not worry about trying to match + ** unicode characters beyond plane 0 - those are very rare and this is + ** just an optimization. */ + if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){ + for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){ + unsigned x = pRe->aArg[i]; + if( x<=0x7f ){ + pRe->zInit[j++] = (unsigned char)x; + }else if( x<=0x7ff ){ + pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6)); + pRe->zInit[j++] = 0x80 | (x&0x3f); + }else if( x<=0xffff ){ + pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12)); + pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f); + pRe->zInit[j++] = 0x80 | (x&0x3f); + }else{ + break; + } + } + if( j>0 && pRe->zInit[j-1]==0 ) j--; + pRe->nInit = j; + } + return pRe->zErr; +} + +/* +** Implementation of the regexp() SQL function. This function implements +** the build-in REGEXP operator. The first argument to the function is the +** pattern and the second argument is the string. So, the SQL statements: +** +** A REGEXP B +** +** is implemented as regexp(B,A). +*/ +static void re_sql_func( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + ReCompiled *pRe; /* Compiled regular expression */ + const char *zPattern; /* The regular expression */ + const unsigned char *zStr;/* String being searched */ + const char *zErr; /* Compile error message */ + int setAux = 0; /* True to invoke sqlite3_set_auxdata() */ + + (void)argc; /* Unused */ + pRe = sqlite3_get_auxdata(context, 0); + if( pRe==0 ){ + zPattern = (const char*)sqlite3_value_text(argv[0]); + if( zPattern==0 ) return; + zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0); + if( zErr ){ + re_free(pRe); + sqlite3_result_error(context, zErr, -1); + return; + } + if( pRe==0 ){ + sqlite3_result_error_nomem(context); + return; + } + setAux = 1; + } + zStr = (const unsigned char*)sqlite3_value_text(argv[1]); + if( zStr!=0 ){ + sqlite3_result_int(context, re_match(pRe, zStr, -1)); + } + if( setAux ){ + sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free); + } +} + +#if defined(SQLITE_DEBUG) +/* +** This function is used for testing and debugging only. It is only available +** if the SQLITE_DEBUG compile-time option is used. +** +** Compile a regular expression and then convert the compiled expression into +** text and return that text. +*/ +static void re_bytecode_func( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zPattern; + const char *zErr; + ReCompiled *pRe; + sqlite3_str *pStr; + int i; + int n; + char *z; + (void)argc; + + zPattern = (const char*)sqlite3_value_text(argv[0]); + if( zPattern==0 ) return; + zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0); + if( zErr ){ + re_free(pRe); + sqlite3_result_error(context, zErr, -1); + return; + } + if( pRe==0 ){ + sqlite3_result_error_nomem(context); + return; + } + pStr = sqlite3_str_new(0); + if( pStr==0 ) goto re_bytecode_func_err; + if( pRe->nInit>0 ){ + sqlite3_str_appendf(pStr, "INIT "); + for(i=0; inInit; i++){ + sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]); + } + sqlite3_str_appendf(pStr, "\n"); + } + for(i=0; (unsigned)inState; i++){ + sqlite3_str_appendf(pStr, "%-8s %4d\n", + ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]); + } + n = sqlite3_str_length(pStr); + z = sqlite3_str_finish(pStr); + if( n==0 ){ + sqlite3_free(z); + }else{ + sqlite3_result_text(context, z, n-1, sqlite3_free); + } + +re_bytecode_func_err: + re_free(pRe); +} + +#endif /* SQLITE_DEBUG */ + +/* +** Invoke this routine to register the regexp() function with the +** SQLite database connection. +*/ +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_regexp_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused */ + rc = sqlite3_create_function(db, "regexp", 2, + SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, + 0, re_sql_func, 0, 0); + if( rc==SQLITE_OK ){ + /* The regexpi(PATTERN,STRING) function is a case-insensitive version + ** of regexp(PATTERN,STRING). */ + rc = sqlite3_create_function(db, "regexpi", 2, + SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, + (void*)db, re_sql_func, 0, 0); +#if defined(SQLITE_DEBUG) + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "regexp_bytecode", 1, + SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, + 0, re_bytecode_func, 0, 0); + } +#endif /* SQLITE_DEBUG */ + } + return rc; +} +/*** End of #include "regexp.c" ***/ + +#endif + +#if defined(SQLITE_ENABLE_COMPRESS) || defined(SQLITE_ENABLE_SQLAR) || defined(SQLITE_ENABLE_ZIPFILE) +#if SQLITE3MC_USE_MINIZ != 0 +/* #include "miniz.c" */ +/*** Begin of #include "miniz.c" ***/ +/* #include "miniz.h" */ +/*** Begin of #include "miniz.h" ***/ +#define MINIZ_EXPORT +/* miniz.c 2.2.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateReset/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ + + + + +/* Defines to completely disable specific portions of miniz.c: + If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ + +/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ +/*#define MINIZ_NO_STDIO */ + +/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ +/* get/set file times, and the C run-time funcs that get/set times won't be called. */ +/* The current downside is the times written to your archives will be from 1979. */ +/*#define MINIZ_NO_TIME */ + +/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ +/*#define MINIZ_NO_ZLIB_APIS */ + +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ +/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. + Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc + callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user + functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ +/*#define MINIZ_NO_MALLOC */ + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ +#define MINIZ_NO_TIME +#endif + +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ +#define MINIZ_X86_OR_X64_CPU 1 +#else +#define MINIZ_X86_OR_X64_CPU 0 +#endif + +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ +#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) +#if MINIZ_X86_OR_X64_CPU +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#define MINIZ_UNALIGNED_USE_MEMCPY +#else +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ +#define MINIZ_HAS_64BIT_REGISTERS 1 +#else +#define MINIZ_HAS_64BIT_REGISTERS 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API Definitions. */ + +/* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ +typedef unsigned long mz_ulong; + +/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ +MINIZ_EXPORT void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +/* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ +MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +/* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ +MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +/* Compression strategies. */ +enum +{ + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 +}; + +/* Method */ +#define MZ_DEFLATED 8 + +/* Heap allocation callbacks. +Note that mz_alloc_func parameter types purposely differ from zlib's: items/size is size_t, not unsigned long. */ +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ +enum +{ + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 +}; + +#define MZ_VERSION "10.2.0" +#define MZ_VERNUM 0xA100 +#define MZ_VER_MAJOR 10 +#define MZ_VER_MINOR 2 +#define MZ_VER_REVISION 0 +#define MZ_VER_SUBREVISION 0 + +#ifndef MINIZ_NO_ZLIB_APIS + +/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ +enum +{ + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 +}; + +/* Return status codes. MZ_PARAM_ERROR is non-standard. */ +enum +{ + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 +}; + +/* Window bits */ +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +/* Compression/decompression stream struct. */ +typedef struct mz_stream_s +{ + const unsigned char *next_in; /* pointer to next byte to read */ + unsigned int avail_in; /* number of bytes available at next_in */ + mz_ulong total_in; /* total number of bytes consumed so far */ + + unsigned char *next_out; /* pointer to next byte to write */ + unsigned int avail_out; /* number of bytes that can be written to next_out */ + mz_ulong total_out; /* total number of bytes produced so far */ + + char *msg; /* error msg (unused) */ + struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ + + mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ + mz_free_func zfree; /* optional heap free function (defaults to free) */ + void *opaque; /* heap alloc function user pointer */ + + int data_type; /* data_type (unused) */ + mz_ulong adler; /* adler32 of the source or uncompressed data */ + mz_ulong reserved; /* not used */ +} mz_stream; + +typedef mz_stream *mz_streamp; + +/* Returns the version string of miniz.c. */ +MINIZ_EXPORT const char *mz_version(void); + +/* mz_deflateInit() initializes a compressor with default options: */ +/* Parameters: */ +/* pStream must point to an initialized mz_stream struct. */ +/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ +/* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ +/* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if the input parameters are bogus. */ +/* MZ_MEM_ERROR on out of memory. */ +MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level); + +/* mz_deflateInit2() is like mz_deflate(), except with more control: */ +/* Additional parameters: */ +/* method must be MZ_DEFLATED */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ +/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ +MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ +MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream); + +/* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ +/* Return values: */ +/* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ +/* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ +MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush); + +/* mz_deflateEnd() deinitializes a compressor: */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream); + +/* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ +MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +/* Single-call compression functions mz_compress() and mz_compress2(): */ +/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ +MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +/* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ +MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len); + +/* Initializes a decompressor. */ +MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream); + +/* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ +MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ +MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream); + +/* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ +/* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ +/* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ +/* Return values: */ +/* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ +/* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_DATA_ERROR if the deflate stream is invalid. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ +/* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ +MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush); + +/* Deinitializes a decompressor. */ +MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream); + +/* Single-call decompression. */ +/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ +MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +MINIZ_EXPORT int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len); + +/* Returns a string description of the specified error code, or NULL if the error code is invalid. */ +MINIZ_EXPORT const char *mz_error(int err); + +/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflateReset mz_inflateReset +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define uncompress2 mz_uncompress2 +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +#endif /* MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + + + + + + +#include +#include +#include +#include + + + +/* ------------------- Types and macros */ +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#define MZ_FILE FILE +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifdef MINIZ_NO_TIME +typedef struct mz_dummy_time_t_tag +{ + int m_dummy; +} mz_dummy_time_t; +#define MZ_TIME_T mz_dummy_time_t +#else +#define MZ_TIME_T time_t +#endif + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void)x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) + +#ifdef _MSC_VER +#define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) +#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) +#else +#define MZ_FORCEINLINE inline +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +extern MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); +extern MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address); +extern MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); + +#define MZ_UINT16_MAX (0xFFFFU) +#define MZ_UINT32_MAX (0xFFFFFFFFU) + +#ifdef __cplusplus +} +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif +/* ------------------- Low-level Compression API Definitions */ + +/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ +#define TDEFL_LESS_MEMORY 0 + +/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ +/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ +enum +{ + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ +/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ +/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ +/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ +/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ +/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ +/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ +/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ +/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +/* High level compression functions: */ +/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ +/* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must free() the returned block when it's no longer needed. */ +MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ +/* Returns 0 on failure. */ +MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* Compresses an image to a compressed PNG file in memory. */ +/* On entry: */ +/* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ +/* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ +/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ +/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pLen_out will be set to the size of the PNG image file. */ +/* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ +MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + +/* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ +MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum +{ + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 +}; + +/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ +#if TDEFL_LESS_MEMORY +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#else +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#endif + +/* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ +typedef enum { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1 +} tdefl_status; + +/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ +typedef enum { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +/* tdefl's compression state structure. */ +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +/* Initializes the compressor. */ +/* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ +/* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ +/* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ +/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ +MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +/* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ +MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ +/* tdefl_compress_buffer() always consumes the entire input buffer. */ +MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +/* Create tdefl_compress() flags given zlib-style compression parameters. */ +/* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ +/* window_bits may be -15 (raw deflate) or 15 (zlib) */ +/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ +MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor structure in C so that */ +/* non-C language bindings to tdefl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void); +MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp); +#endif + +#ifdef __cplusplus +} +#endif + + +/* ------------------- Low-level Decompression API Definitions */ + +#ifdef __cplusplus +extern "C" { +#endif +/* Decompression flags used by tinfl_decompress(). */ +/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ +/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ +/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ +/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +/* High level decompression functions: */ +/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ +/* On return: */ +/* Function returns a pointer to the decompressed data, or NULL on failure. */ +/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must call mz_free() on the returned block when it's no longer needed. */ +MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ +/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ +/* Returns 1 on success or 0 on failure. */ +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; +typedef struct tinfl_decompressor_tag tinfl_decompressor; + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tinfl_decompressor structure in C so that */ +/* non-C language bindings to tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); +MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); +#endif + +/* Max size of LZ dictionary. */ +#define TINFL_LZ_DICT_SIZE 32768 + +/* Return status. */ +typedef enum { + /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ + /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ + /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, + + /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ + TINFL_STATUS_BAD_PARAM = -3, + + /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ + TINFL_STATUS_ADLER32_MISMATCH = -2, + + /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ + TINFL_STATUS_FAILED = -1, + + /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ + + /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ + /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ + TINFL_STATUS_DONE = 0, + + /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ + /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ + /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + + /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ + /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ + /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ + /* so I may need to add some code to address this. */ + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +/* Initializes the decompressor to its initial state. */ +#define tinfl_init(r) \ + do \ + { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ +/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ +MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +/* Internal/private bits follow. */ +enum +{ + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#else +#define TINFL_USE_64BIT_BITBUF 0 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +#ifdef __cplusplus +} +#endif + + + + +/* ------------------- ZIP archive reading/writing */ + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +enum +{ + /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 +}; + +typedef struct +{ + /* Central directory file index. */ + mz_uint32 m_file_index; + + /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ + mz_uint64 m_central_dir_ofs; + + /* These fields are copied directly from the zip's central dir. */ + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; + +#ifndef MINIZ_NO_TIME + MZ_TIME_T m_time; +#endif + + /* CRC-32 of uncompressed data. */ + mz_uint32 m_crc32; + + /* File's compressed size. */ + mz_uint64 m_comp_size; + + /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ + mz_uint64 m_uncomp_size; + + /* Zip internal and external file attributes. */ + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + + /* Entry's local header file offset in bytes. */ + mz_uint64 m_local_header_ofs; + + /* Size of comment in bytes. */ + mz_uint32 m_comment_size; + + /* MZ_TRUE if the entry appears to be a directory. */ + mz_bool m_is_directory; + + /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ + mz_bool m_is_encrypted; + + /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ + mz_bool m_is_supported; + + /* Filename. If string ends in '/' it's a subdirectory entry. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + + /* Comment field. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); +typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, + MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ + MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ + MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ + MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, + MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, + /*After adding a compressed file, seek back + to local file header and set the correct sizes*/ + MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000 +} mz_zip_flags; + +typedef enum { + MZ_ZIP_TYPE_INVALID = 0, + MZ_ZIP_TYPE_USER, + MZ_ZIP_TYPE_MEMORY, + MZ_ZIP_TYPE_HEAP, + MZ_ZIP_TYPE_FILE, + MZ_ZIP_TYPE_CFILE, + MZ_ZIP_TOTAL_TYPES +} mz_zip_type; + +/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ +typedef enum { + MZ_ZIP_NO_ERROR = 0, + MZ_ZIP_UNDEFINED_ERROR, + MZ_ZIP_TOO_MANY_FILES, + MZ_ZIP_FILE_TOO_LARGE, + MZ_ZIP_UNSUPPORTED_METHOD, + MZ_ZIP_UNSUPPORTED_ENCRYPTION, + MZ_ZIP_UNSUPPORTED_FEATURE, + MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, + MZ_ZIP_NOT_AN_ARCHIVE, + MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, + MZ_ZIP_UNSUPPORTED_MULTIDISK, + MZ_ZIP_DECOMPRESSION_FAILED, + MZ_ZIP_COMPRESSION_FAILED, + MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, + MZ_ZIP_CRC_CHECK_FAILED, + MZ_ZIP_UNSUPPORTED_CDIR_SIZE, + MZ_ZIP_ALLOC_FAILED, + MZ_ZIP_FILE_OPEN_FAILED, + MZ_ZIP_FILE_CREATE_FAILED, + MZ_ZIP_FILE_WRITE_FAILED, + MZ_ZIP_FILE_READ_FAILED, + MZ_ZIP_FILE_CLOSE_FAILED, + MZ_ZIP_FILE_SEEK_FAILED, + MZ_ZIP_FILE_STAT_FAILED, + MZ_ZIP_INVALID_PARAMETER, + MZ_ZIP_INVALID_FILENAME, + MZ_ZIP_BUF_TOO_SMALL, + MZ_ZIP_INTERNAL_ERROR, + MZ_ZIP_FILE_NOT_FOUND, + MZ_ZIP_ARCHIVE_TOO_LARGE, + MZ_ZIP_VALIDATION_FAILED, + MZ_ZIP_WRITE_CALLBACK_FAILED, + MZ_ZIP_TOTAL_ERRORS +} mz_zip_error; + +typedef struct +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + + /* We only support up to UINT32_MAX files in zip64 mode. */ + mz_uint32 m_total_files; + mz_zip_mode m_zip_mode; + mz_zip_type m_zip_type; + mz_zip_error m_last_error; + + mz_uint64 m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + mz_file_needs_keepalive m_pNeeds_keepalive; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef struct +{ + mz_zip_archive *pZip; + mz_uint flags; + + int status; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32; +#endif + mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + void *pWrite_buf; + + size_t out_blk_remain; + + tinfl_decompressor inflator; + +} mz_zip_reader_extract_iter_state; + +/* -------- ZIP reading */ + +/* Inits a ZIP archive reader. */ +/* These functions read and validate the archive's central directory. */ +MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); + +MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +/* Read a archive from a disk file. */ +/* file_start_ofs is the file offset where the archive actually begins, or 0. */ +/* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ +MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); + +/* Read an archive from an already opened FILE, beginning at the current file position. */ +/* The archive is assumed to be archive_size bytes long. If archive_size is 0, then the entire rest of the file is assumed to contain the archive. */ +/* The FILE will NOT be closed when mz_zip_reader_end() is called. */ +MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); +#endif + +/* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ +MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +/* -------- ZIP reading or writing */ + +/* Clears a mz_zip_archive struct to all zeros. */ +/* Important: This must be done before passing the struct to any mz_zip functions. */ +MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip); + +MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); +MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); + +/* Returns the total number of files in the archive. */ +MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); +MINIZ_EXPORT mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); +MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); + +/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ +MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); + +/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ +/* Note that the m_last_error functionality is not thread safe. */ +MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); +MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); +MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); +MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); +MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); + +/* MZ_TRUE if the archive file entry is a directory entry. */ +MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the file is encrypted/strong encrypted. */ +MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ +MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); + +/* Retrieves the filename of an archive file entry. */ +/* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ +MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); + +/* Returns detailed information about an archive file entry. */ +MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +/* MZ_TRUE if the file is in zip64 format. */ +/* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ +MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); + +/* Returns the total central directory size in bytes. */ +/* The current max supported size is <= MZ_UINT32_MAX. */ +MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); + +/* Extracts a archive file to a memory buffer using no memory allocation. */ +/* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +/* Extracts a archive file to a memory buffer. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +/* Extracts a archive file to a dynamically allocated heap buffer. */ +/* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ +/* Returns NULL and sets the last error on failure. */ +MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +/* Extracts a archive file using a callback function to output the file's data. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +/* Extract a file iteratively */ +MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); +MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); +MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); + +#ifndef MINIZ_NO_STDIO +/* Extracts a archive file to a disk file and sets its last accessed and modified times. */ +/* This function only extracts files, not archive directory records. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); + +/* Extracts a archive file starting at the current position in the destination FILE stream. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); +#endif + +#if 0 +/* TODO */ + typedef void *mz_zip_streaming_extract_state_ptr; + mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); + size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); + mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); +#endif + +/* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ +/* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ +MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + +/* Validates an entire archive by calling mz_zip_validate_file() on each file. */ +MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); + +/* Misc utils/helpers, valid for ZIP reading or writing */ +MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); +MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); + +/* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ +MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip); + +/* -------- ZIP writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +/* Inits a ZIP archive writer. */ +/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ +/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ +MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); + +MINIZ_EXPORT mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); +MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +MINIZ_EXPORT mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); +#endif + +/* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ +/* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ +/* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ +/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ +/* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ +/* the archive is finalized the file's central directory will be hosed. */ +MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); +MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); + +/* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ +/* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ +/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + +/* Adds the contents of a file to an archive. This function also records the disk file's modified time into the archive. */ +/* File data is supplied via a read callback function. User mz_zip_writer_add_(c)file to add a file directly.*/ +MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + + +#ifndef MINIZ_NO_STDIO +/* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); +#endif + +/* Adds a file to an archive by fully cloning the data from another archive. */ +/* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); + +/* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ +/* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ +/* An archive must be manually finalized by calling this function for it to be valid. */ +MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); + +/* Finalizes a heap archive, returning a poiner to the heap block and its size. */ +/* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ +MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); + +/* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ +/* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ +MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +/* -------- Misc. high-level helper functions: */ + +/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ +/* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +/* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ +MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); + +/* Reads a single file from an archive into a heap block. */ +/* If pComment is not NULL, only the file with the specified comment will be extracted. */ +/* Returns NULL on failure. */ +MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); +MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifdef __cplusplus +} +#endif + +#endif /* MINIZ_NO_ARCHIVE_APIS */ +/*** End of #include "miniz.h" ***/ + +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * 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. + * + **************************************************************************/ + + + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API's */ + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; +} + +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ +#if 0 + mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) + { + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } + return ~crcu32; + } +#elif defined(USE_EXTERNAL_MZCRC) +/* If USE_EXTERNAL_CRC is defined, an external module will export the + * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version. + * Depending on the impl, it may be necessary to ~ the input/output crc values. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len); +#else +/* Faster, but larger CPU cache footprint. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, + 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, + 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, + 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, + 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, + 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, + 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, + 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, + 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, + 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, + 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, + 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, + 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, + 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, + 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, + 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, + 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, + 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, + 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, + 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, + 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, + 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, + 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, + 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, + 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, + 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, + 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; + const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; + + while (buf_len >= 4) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; + pByte_buf += 4; + buf_len -= 4; + } + + while (buf_len) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + ++pByte_buf; + --buf_len; + } + + return ~crc32; +} +#endif + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) +{ + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); +} +MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address) +{ + (void)opaque, (void)address; + MZ_FREE(address); +} +MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) +{ + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); +} + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +#ifndef MINIZ_NO_ZLIB_APIS + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; /* Can't make forward progress without some input. + */ + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflateReset(mz_streamp pStream) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + + pDecomp = (inflate_state *)pStream->state; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + /* pDecomp->m_window_bits = window_bits */; + + return MZ_OK; +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state *pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state *)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + /* flush != MZ_FINISH then we must assume there's more input. */ + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for (;;) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ + else if (flush == MZ_FINISH) + { + /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} +int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((*pSource_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)*pSource_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + *pSource_len = *pSource_len - stream.avail_in; + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_uncompress2(pDest, pDest_len, pSource, &source_len); +} + +const char *mz_error(int err) +{ + static struct + { + int m_err; + const char *m_pDesc; + } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif /*MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + 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 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. + + For more information, please refer to +*/ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * 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. + * + **************************************************************************/ + + + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Compression (independent from all decompression API's) */ + +/* Purposely making these tables static for faster init and thread safety. */ +static const mz_uint16 s_tdefl_len_sym[256] = + { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, + 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, + 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 + }; + +static const mz_uint8 s_tdefl_len_extra[256] = + { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 + }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = + { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 + }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = + { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7 + }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = + { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 + }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = + { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 + }; + +/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ +typedef struct +{ + mz_uint16 m_key, m_sym_index; +} tdefl_sym_freq; +static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) + { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32 *pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) + { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; +} + +/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) + { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) + { + if (leaf >= n || A[root].m_key < A[leaf].m_key) + { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) + { + while (root >= 0 && (int)A[root].m_key == dpth) + { + used++; + root--; + } + while (avbl > used) + { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } +} + +/* Limits canonical Huffman code table's max code size. */ +enum +{ + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 +}; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) + { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) + { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) \ + do \ + { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) \ + { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) \ + { \ + if (rle_repeat_count < 3) \ + { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } \ + else \ + { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } + +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) \ + { \ + if (rle_z_count < 3) \ + { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } \ + else if (rle_z_count <= 10) \ + { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } \ + else \ + { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64 *)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); + TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ + if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) + { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) + { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else + { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) + { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) +#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) +#endif +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16 *)(d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) + continue; + p = s; + probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + if (!probe_len) + { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); + break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8* p) +{ + mz_uint32 ret; + memcpy(&ret, p, sizeof(mz_uint32)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p) +#endif +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((TDEFL_READ_UNALIGNED_WORD32(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist)); +#else + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; +#endif + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + /* Simple lazy/greedy parsing state machine. */ + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) + { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + /* Move the lookahead forward by len_to_move bytes. */ + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); + /* Check if it's time to flush the current LZ codes to the internal output buffer. */ + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) + { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) + { + MZ_CLEAR_OBJ(d->m_hash); + MZ_CLEAR_OBJ(d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + *d->m_pLZ_flags = 0; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_dict); + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do + { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; +} + +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +/* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ +#endif + +/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) +{ + /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) + { + MZ_FREE(pComp); + return NULL; + } + /* write dummy header */ + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); + /* compress image data */ + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) + { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) + { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + /* write real header */ + *pLen_out = out_buf.m_size - 41; + { + static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; + mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, + 0x0a, 0x1a, 0x0a, 0x00, 0x00, + 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x49, 0x44, 0x41, + 0x54 }; + pnghdr[18] = (mz_uint8)(w >> 8); + pnghdr[19] = (mz_uint8)w; + pnghdr[22] = (mz_uint8)(h >> 8); + pnghdr[23] = (mz_uint8)h; + pnghdr[25] = chans[num_chans]; + pnghdr[33] = (mz_uint8)(*pLen_out >> 24); + pnghdr[34] = (mz_uint8)(*pLen_out >> 16); + pnghdr[35] = (mz_uint8)(*pLen_out >> 8); + pnghdr[36] = (mz_uint8)*pLen_out; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + /* write footer (IDAT CRC-32, followed by IEND chunk) */ + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); + /* compute final size of file, grab compressed data buffer and return */ + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; +} +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +} + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ +/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc() +{ + return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); +} + +void tdefl_compressor_free(tdefl_compressor *pComp) +{ + MZ_FREE(pComp); +} +#endif + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#ifdef __cplusplus +} +#endif + /************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * 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. + * + **************************************************************************/ + + + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Decompression (completely independent from all compression API's) */ + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN \ + switch (r->m_state) \ + { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do \ + { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index:; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do \ + { \ + for (;;) \ + { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END +#define TINFL_CR_FINISH } + +#define TINFL_GET_BYTE(state_index, c) \ + do \ + { \ + while (pIn_buf_cur >= pIn_buf_end) \ + { \ + TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ + } \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) \ + do \ + { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END + +/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ +/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ +/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ +/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do \ + { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) \ + { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } \ + else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < 15); + +/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ +/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ +/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ +/* The slow path is only executed at the very end of the input buffer. */ +/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ +/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ + do \ + { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) \ + { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) \ + { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } \ + else \ + { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; + static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; + static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; + static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) + { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) + { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) + { + TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) + { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) + { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; + } + r->m_table_sizes[2] = 19; + } + for (; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; + tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; + pTable = &r->m_tables[r->m_type]; + MZ_CLEAR_OBJ(total_syms); + MZ_CLEAR_OBJ(pTable->m_look_up); + MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) + { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) + { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) + { + pTable->m_look_up[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + { + pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) + { + pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) + { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); + if (dist < 16) + { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for (;;) + { + mz_uint8 *pSrc; + for (;;) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist == 0 || dist > dist_from_out_buf_start || dist_from_out_buf_start == 0) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32)*2); +#else + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; +#endif + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + while(counter>2) + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + counter -= 3; + } + if (counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + + /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ + TINFL_SKIP_BITS(32, num_bits & 7); + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ + + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + for (counter = 0; counter < 4; ++counter) + { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + + TINFL_CR_FINISH + +common_exit: + /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ + /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ + if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) + { + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + } + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +/* Higher level helper functions. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for (;;) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for (;;) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +#ifndef MINIZ_NO_MALLOC +tinfl_decompressor *tinfl_decompressor_alloc() +{ + tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); + if (pDecomp) + tinfl_init(pDecomp); + return pDecomp; +} + +void tinfl_decompressor_free(tinfl_decompressor *pDecomp) +{ + MZ_FREE(pDecomp); +} +#endif + +#ifdef __cplusplus +} +#endif + /************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * 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. + * + **************************************************************************/ + + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- .ZIP archive reading */ + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include + +#if defined(_MSC_VER) || defined(__MINGW64__) +static FILE *mz_fopen(const char *pFilename, const char *pMode) +{ + FILE *pFile = NULL; + fopen_s(&pFile, pFilename, pMode); + return pFile; +} +static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) +{ + FILE *pFile = NULL; + if (freopen_s(&pFile, pPath, pMode, pStream)) + return NULL; + return pFile; +} +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN mz_fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT _stat64 +#define MZ_FILE_STAT _stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN mz_freopen +#define MZ_DELETE_FILE remove +#elif defined(__MINGW32__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__USE_LARGEFILE64) /* gcc, clang */ +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__APPLE__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen(p, m, s) +#define MZ_DELETE_FILE remove + +#else +#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#ifdef __STRICT_ANSI__ +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#else +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#endif +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#endif /* #ifdef _MSC_VER */ +#endif /* #ifdef MINIZ_NO_STDIO */ + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +/* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ +enum +{ + /* ZIP archive identifiers and record sizes */ + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + + /* ZIP64 archive identifier and record sizes */ + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, + MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, + MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, + MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, + MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, + + /* Central directory header record offsets */ + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + + /* Local directory header offsets */ + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, + + /* End of central directory offsets */ + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + + /* ZIP64 End of central directory locator offsets */ + MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ + + /* ZIP64 End of central directory header offsets */ + MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ + MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, + MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + + /* The flags passed in when the archive is initially opened. */ + uint32_t m_init_flags; + + /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ + mz_bool m_zip64; + + /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ + mz_bool m_zip64_has_extended_info_fields; + + /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ + MZ_FILE *m_pFile; + mz_uint64 m_file_archive_start_ofs; + + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size + +#if defined(DEBUG) || defined(_DEBUG) +static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) +{ + MZ_ASSERT(index < pArray->m_size); + return index; +} +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] +#else +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] +#endif + +static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) +{ + memset(pArray, 0, sizeof(mz_zip_array)); + pArray->m_element_size = element_size; +} + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) + { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + if (n > 0) + memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; + *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif /* #ifdef _MSC_VER */ + + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifndef MINIZ_NO_STDIO +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) +{ + struct MZ_FILE_STAT_STRUCT file_stat; + + /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + + *pTime = file_stat.st_mtime; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ + +static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) +{ + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; + + return !utime(pFilename, &t); +} +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ + +static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + if (pZip) + pZip->m_last_error = err_num; + return MZ_FALSE; +} + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + pZip->m_last_error = MZ_ZIP_NO_ERROR; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + pZip->m_pState->m_init_flags = flags; + pZip->m_pState->m_zip64 = MZ_FALSE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) \ + do \ + { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END + +/* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices; + mz_uint32 start, end; + const mz_uint32 size = pZip->m_total_files; + + if (size <= 1U) + return; + + pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + + start = (size - 2U) >> 1U; + for (;;) + { + mz_uint64 child, root = start; + for (;;) + { + if ((child = (root << 1U) + 1U) >= size) + break; + child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + if (!start) + break; + start--; + } + + end = size - 1; + while (end > 0) + { + mz_uint64 child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for (;;) + { + if ((child = (root << 1U) + 1U) >= end) + break; + child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) +{ + mz_int64 cur_file_ofs; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + + /* Basic sanity checks - reject files which are too small */ + if (pZip->m_archive_size < record_size) + return MZ_FALSE; + + /* Find the record by scanning the file from the end towards the beginning. */ + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + + for (i = n - 4; i >= 0; --i) + { + mz_uint s = MZ_READ_LE32(pBuf + i); + if (s == record_sig) + { + if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + break; + } + } + + if (i >= 0) + { + cur_file_ofs += i; + break; + } + + /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) + return MZ_FALSE; + + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + + *pOfs = cur_file_ofs; + return MZ_TRUE; +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) +{ + mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; + mz_uint64 cdir_ofs = 0; + mz_int64 cur_file_ofs = 0; + const mz_uint8 *p; + + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; + + mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; + + mz_uint64 zip64_end_of_central_dir_ofs = 0; + + /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); + + /* Read and verify the end of central directory record. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + { + if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) + { + zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); + if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) + { + pZip->m_pState->m_zip64 = MZ_TRUE; + } + } + } + } + } + + pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); + cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + + if (pZip->m_pState->m_zip64) + { + mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); + mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); + mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); + mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); + + if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (zip64_total_num_of_disks != 1U) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + /* Check for miniz's practical limits */ + if (zip64_cdir_total_entries > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; + + if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; + + /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ + if (zip64_size_of_central_directory > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + cdir_size = (mz_uint32)zip64_size_of_central_directory; + + num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); + + cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); + + cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); + } + + if (pZip->m_total_files != cdir_entries_on_this_disk) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + /* Now create an index into the central directory file records, do some basic sanity checking on each record */ + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; + mz_uint64 comp_size, decomp_size, local_header_ofs; + + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + (ext_data_size) && + (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = ext_data_size; + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data; + void* buf = NULL; + + if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > n) + { + buf = MZ_MALLOC(ext_data_size); + if(buf==NULL) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size, buf, ext_data_size) != ext_data_size) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (mz_uint8*)buf; + } + else + { + pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; + } + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ + pZip->m_pState->m_zip64 = MZ_TRUE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + + MZ_FREE(buf); + } + } + + /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ + if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) + { + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (comp_size != MZ_UINT32_MAX) + { + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + n -= total_header_size; + p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +void mz_zip_zero_struct(mz_zip_archive *pZip) +{ + if (pZip) + MZ_CLEAR_OBJ(*pZip); +} + +static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_bool status = MZ_TRUE; + + if (!pZip) + return MZ_FALSE; + + if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; + + return MZ_FALSE; + } + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; + status = MZ_FALSE; + } + } + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return status; +} + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + return mz_zip_reader_end_internal(pZip, MZ_TRUE); +} +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_archive_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) +{ + if (!pMem) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pNeeds_keepalive = NULL; + +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + + pZip->m_pState->m_mem_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); +} + +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) +{ + mz_uint64 file_size; + MZ_FILE *pFile; + + if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) +{ + mz_uint64 cur_file_ofs; + + if ((!pZip) || (!pFile)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + cur_file_ofs = MZ_FTELL64(pFile); + + if (!archive_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + + archive_size = MZ_FTELL64(pFile) - cur_file_ofs; + + if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = archive_size; + pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; +} + +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint bit_flag; + mz_uint method; + + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); + bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + + if ((method != 0) && (method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + return MZ_FALSE; + } + + if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + return MZ_FALSE; + } + + if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, attribute_mapping_id, external_attr; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ + /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ + /* FIXME: Remove this check? Is it necessary - we already check the filename. */ + attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; + (void)attribute_mapping_id; + + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) + { + return MZ_TRUE; + } + + return MZ_FALSE; +} + +static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) +{ + mz_uint n; + const mz_uint8 *p = pCentral_dir_header; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_FALSE; + + if ((!p) || (!pStat)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Extract fields from the central directory record. */ + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + /* Copy as much of the filename and comment as possible. */ + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); + pStat->m_comment[n] = '\0'; + + /* Set some flags for convienance */ + pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); + pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); + pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); + + /* See if we need to read any zip64 extended information fields. */ + /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ + if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; + mz_uint32 field_data_remaining = field_data_size; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_TRUE; + + if (pStat->m_uncomp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_uncomp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_comp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_comp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_local_header_ofs == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const uint32_t size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + + if (pIndex) + *pIndex = 0; + + if (size) + { + /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ + /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ + mz_int64 l = 0, h = (mz_int64)size - 1; + + while (l <= h) + { + mz_int64 m = l + ((h - l) >> 1); + uint32_t file_index = pIndices[(uint32_t)m]; + + int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint32 index; + if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + return -1; + else + return (int)index; +} + +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) +{ + mz_uint file_index; + size_t name_len, comment_len; + + if (pIndex) + *pIndex = 0; + + if ((!pZip) || (!pZip->m_pState) || (!pName)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* See if we can use a binary search */ + if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && + ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + { + return mz_zip_locate_file_binary_search(pZip, pName, pIndex); + } + + /* Locate the entry by scanning the entire central directory */ + name_len = strlen(pName); + if (name_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Ensure supplied output buffer is large enough. */ + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); + + /* Read and parse the local directory entry. */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) + { + if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + } +#endif + + return MZ_TRUE; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + /* Read directly from the archive in memory. */ + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + /* Use a user provided read buffer. */ + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + /* Temporarily allocate a read buffer. */ + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return NULL; + } + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + return NULL; + } + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + { + if (pSize) + *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32 = MZ_CRC32_INIT; +#endif + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pState->m_pMem) + { + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + } + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); +#endif + } + + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + } +#endif + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + status = TINFL_STATUS_FAILED; + } + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); +#endif + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (file_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_reader_extract_iter_state *pState; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + /* Argument sanity check */ + if ((!pZip) || (!pZip->m_pState)) + return NULL; + + /* Allocate an iterator status structure */ + pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); + if (!pState) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + /* Fetch file details */ + if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Encryption and patch files are not supported. */ + if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Init state - save args */ + pState->pZip = pZip; + pState->flags = flags; + + /* Init state - reset variables to defaults */ + pState->status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + pState->file_crc32 = MZ_CRC32_INIT; +#endif + pState->read_buf_ofs = 0; + pState->out_buf_ofs = 0; + pState->pRead_buf = NULL; + pState->pWrite_buf = NULL; + pState->out_blk_remain = 0; + + /* Read and parse the local directory entry. */ + pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + pState->cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; + pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + else + { + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, therefore intermediate read buffer required */ + pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + else + { + /* Decompression not required - we will be reading directly into user buffer, no temp buf required */ + pState->read_buf_size = 0; + } + pState->read_buf_avail = 0; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, init decompressor */ + tinfl_init( &pState->inflator ); + + /* Allocate write buffer */ + if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + if (pState->pRead_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + + return pState; +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_uint32 file_index; + + /* Locate file index by name */ + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return NULL; + + /* Construct iterator */ + return mz_zip_reader_extract_iter_new(pZip, file_index, flags); +} + +size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size) +{ + size_t copied_to_caller = 0; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) + return 0; + + if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data, calc amount to return. */ + copied_to_caller = (size_t)MZ_MIN( buf_size, pState->comp_remaining ); + + /* Zip is in memory....or requires reading from a file? */ + if (pState->pZip->m_pState->m_pMem) + { + /* Copy data to caller's buffer */ + memcpy( pvBuf, pState->pRead_buf, copied_to_caller ); + pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller; + } + else + { + /* Read directly into caller's buffer */ + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller) + { + /* Failed to read all that was asked for, flag failure and alert user */ + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + copied_to_caller = 0; + } + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Compute CRC if not returning compressed data only */ + if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); +#endif + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += copied_to_caller; + pState->out_buf_ofs += copied_to_caller; + pState->comp_remaining -= copied_to_caller; + } + else + { + do + { + /* Calc ptr to write buffer - given current output pos and block size */ + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + /* Calc max output size - given current output pos and block size */ + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + if (!pState->out_blk_remain) + { + /* Read more data from file if none available (and reading from file) */ + if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) + { + /* Calc read size */ + pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining); + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += pState->read_buf_avail; + pState->comp_remaining -= pState->read_buf_avail; + pState->read_buf_ofs = 0; + } + + /* Perform decompression */ + in_buf_size = (size_t)pState->read_buf_avail; + pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + pState->read_buf_avail -= in_buf_size; + pState->read_buf_ofs += in_buf_size; + + /* Update current output block size remaining */ + pState->out_blk_remain = out_buf_size; + } + + if (pState->out_blk_remain) + { + /* Calc amount to return. */ + size_t to_copy = MZ_MIN( (buf_size - copied_to_caller), pState->out_blk_remain ); + + /* Copy data to caller's buffer */ + memcpy( (uint8_t*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy ); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Perform CRC */ + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); +#endif + + /* Decrement data consumed from block */ + pState->out_blk_remain -= to_copy; + + /* Inc output offset, while performing sanity check */ + if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Increment counter of data copied to caller */ + copied_to_caller += to_copy; + } + } while ( (copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)) ); + } + + /* Return how many bytes were copied into user buffer */ + return copied_to_caller; +} + +mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState) +{ + int status; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) + return MZ_FALSE; + + /* Was decompression completed and requested? */ + if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + pState->status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (pState->file_crc32 != pState->file_stat.m_crc32) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + } +#endif + } + + /* Free buffers */ + if (!pState->pZip->m_pState->m_pMem) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); + if (pState->pWrite_buf) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); + + /* Save status */ + status = pState->status; + + /* Free context */ + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); + + return status == TINFL_STATUS_DONE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; + + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + + if (MZ_FCLOSE(pFile) == EOF) + { + if (status) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + + status = MZ_FALSE; + } + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + + return status; +} + +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} + +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); +} + +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_uint32 *p = (mz_uint32 *)pOpaque; + (void)file_ofs; + *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); + return n; +} + +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + mz_zip_internal_state *pState; + const mz_uint8 *pCentral_dir_header; + mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint64 local_header_ofs = 0; + mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; + mz_bool has_data_descriptor; + mz_uint32 local_header_bit_flags; + + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (file_index > pZip->m_total_files) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); + + if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_is_encrypted) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports stored and deflate. */ + if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + if (!file_stat.m_is_supported) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + /* Read and parse the local directory entry. */ + local_header_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); + local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + has_data_descriptor = (local_header_bit_flags & 8) != 0; + + if (local_header_filename_len != strlen(file_stat.m_filename)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + goto handle_failure; + } + + if (local_header_filename_len) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ + if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ + /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ + if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) + { + mz_uint8 descriptor_buf[32]; + mz_bool has_id; + const mz_uint8 *pSrc; + mz_uint32 file_crc32; + mz_uint64 comp_size = 0, uncomp_size = 0; + + mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; + + file_crc32 = MZ_READ_LE32(pSrc); + + if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); + } + else + { + comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); + } + + if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + else + { + if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + mz_zip_array_clear(pZip, &file_data_array); + + if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) + { + if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + return MZ_FALSE; + + /* 1 more check to be sure, although the extract checks too. */ + if (uncomp_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + return MZ_FALSE; + } + } + + return MZ_TRUE; + +handle_failure: + mz_zip_array_clear(pZip, &file_data_array); + return MZ_FALSE; +} + +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) +{ + mz_zip_internal_state *pState; + uint32_t i; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Basic sanity checks */ + if (!pState->m_zip64) + { + if (pZip->m_total_files > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pZip->m_archive_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + else + { + if (pZip->m_total_files >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + for (i = 0; i < pZip->m_total_files; i++) + { + if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) + { + mz_uint32 found_index; + mz_zip_archive_file_stat stat; + + if (!mz_zip_reader_file_stat(pZip, i, &stat)) + return MZ_FALSE; + + if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) + return MZ_FALSE; + + /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ + if (found_index != i) + return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + } + + if (!mz_zip_validate_file(pZip, i, flags)) + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if ((!pMem) || (!size)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if (!pFilename) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +/* ------------------- .ZIP archive writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); +} +static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); +} +static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) +{ + mz_write_le32(p, (mz_uint32)v); + mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); +} + +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) +#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); + + if (!n) + return 0; + + /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ + if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + return 0; + } + + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + + while (new_capacity < new_size) + new_capacity *= 2; + + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return 0; + } + + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + status = MZ_FALSE; + } + } + + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) +{ + mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; + + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + { + if (!pZip->m_pRead) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (pZip->m_file_offset_alignment) + { + /* Ensure user specified file offset alignment is a power of 2. */ + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + + pZip->m_pState->m_zip64 = zip64; + pZip->m_pState->m_zip64_has_extended_info_fields = zip64; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + return mz_zip_writer_init_v2(pZip, existing_size, 0); +} + +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_mem_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; + + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + return 0; + } + + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); +} + +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) +{ + MZ_FILE *pFile; + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + + pZip->m_pState->m_pFile = pFile; + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; + char buf[4096]; + + MZ_CLEAR_OBJ(buf); + + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, 0, flags)) + return MZ_FALSE; + + pZip->m_pState->m_pFile = pFile; + pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_zip_internal_state *pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) + { + /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max size */ + if (pZip->m_pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + } + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) + { + /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + } + /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory location. */ + /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ + /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); +} + +/* TODO: pArchive_name is a terrible name here! */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) +#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) +static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) +{ + mz_uint8 *pDst = pBuf; + mz_uint32 field_size = 0; + + MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + MZ_WRITE_LE16(pDst + 2, 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + MZ_WRITE_LE64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pComp_size) + { + MZ_WRITE_LE64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + MZ_WRITE_LE64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + MZ_WRITE_LE16(pBuf + 2, field_size); + + return (mz_uint32)(pDst - pBuf); +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, + mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, + const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes, + const char *user_extra_data, mz_uint user_extra_data_len) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + if (!pZip->m_pState->m_zip64) + { + if (local_header_ofs > 0xFFFFFFFF) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, (mz_uint16)(extra_size + user_extra_data_len), comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + /* Try to resize the central directory array back into its original state. */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ + if (*pArchive_name == '/') + return MZ_FALSE; + + /* Making sure the name does not contain drive letters or DOS style backward slashes is the responsibility of the program using miniz*/ + + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); +} + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint16 bit_flags = 0; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + +#ifndef MINIZ_NO_TIME + if (last_modified != NULL) + { + mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); + } + else + { + MZ_TIME_T cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif /* #ifndef MINIZ_NO_TIME */ + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + /* Set DOS Subdirectory attribute bit. */ + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + + /* Subdirectories cannot contain data. */ + if ((buf_size) || (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += num_alignment_padding_bytes; + + MZ_CLEAR_OBJ(local_dir_header); + + if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + method = MZ_DEFLATED; + } + + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + + if (pExtra_data != NULL) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + if (uncomp_size) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 gen_flags = (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) ? 0 : MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_zip_internal_state *pState; + mz_uint64 file_ofs = 0, cur_archive_header_file_ofs; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if ((!pState->m_zip64) && (max_size > MZ_UINT32_MAX)) + { + /* Source file is too large for non-zip64 */ + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + pState->m_zip64 = MZ_TRUE; + } + + /* We could support this, but why? */ + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + +#ifndef MINIZ_NO_TIME + if (pFile_time) + { + mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); + } +#endif + + if (max_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_archive_file_ofs; + + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + if (max_size && level) + { + method = MZ_DEFLATED; + } + + MZ_CLEAR_OBJ(local_dir_header); + if (pState->m_zip64) + { + if (max_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + else + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, NULL, + NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (max_size) + { + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!level) + { + while (1) + { + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, MZ_ZIP_MAX_IO_BUF_SIZE); + if (n == 0) + break; + + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + file_ofs += n; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + cur_archive_file_ofs += n; + } + uncomp_size = file_ofs; + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + } + + for (;;) + { + tdefl_status status; + tdefl_flush flush = TDEFL_NO_FLUSH; + + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, MZ_ZIP_MAX_IO_BUF_SIZE); + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + break; + } + + file_ofs += n; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + + if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) + flush = TDEFL_FULL_FLUSH; + + if (n == 0) + flush = TDEFL_FINISH; + + status = tdefl_compress_buffer(pComp, pRead_buf, n, flush); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + { + mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + break; + } + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return MZ_FALSE; + } + + uncomp_size = file_ofs; + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + if (!(level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + { + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, + (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : uncomp_size, + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : comp_size, + uncomp_crc32, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + cur_archive_header_file_ofs = local_dir_header_ofs; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + if (pExtra_data != NULL) + { + cur_archive_header_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_header_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_header_file_ofs += extra_size; + } + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO + +static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pSrc_file); + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pSrc_file); +} + +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + return mz_zip_writer_add_read_buf_callback(pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, max_size, pFile_time, pComment, comment_size, level_and_flags, + user_extra_data, user_extra_data_len, user_extra_data_central, user_extra_data_central_len); +} + +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + MZ_FILE *pSrc_file = NULL; + mz_uint64 uncomp_size = 0; + MZ_TIME_T file_modified_time; + MZ_TIME_T *pFile_time = NULL; + mz_bool status; + + memset(&file_modified_time, 0, sizeof(file_modified_time)); + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + pFile_time = &file_modified_time; + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); +#endif + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); + + MZ_FCLOSE(pSrc_file); + + return status; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) +{ + /* + 64 should be enough for any new zip64 data */ + if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); + + if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) + { + mz_uint8 new_ext_block[64]; + mz_uint8 *pDst = new_ext_block; + mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + mz_write_le16(pDst + sizeof(mz_uint16), 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + mz_write_le64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + } + + if (pComp_size) + { + mz_write_le64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + mz_write_le64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + } + + if (pDisk_start) + { + mz_write_le32(pDst, *pDisk_start); + pDst += sizeof(mz_uint32); + } + + mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); + + if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if ((pExt) && (ext_len)) + { + mz_uint32 extra_size_remaining = ext_len; + const mz_uint8 *pExtra_data = pExt; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + return MZ_TRUE; +} + +/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; + mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; + const mz_uint8 *pSrc_central_header; + mz_zip_archive_file_stat src_file_stat; + mz_uint32 src_filename_len, src_comment_len, src_ext_len; + mz_uint32 local_header_filename_size, local_header_extra_len; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ + if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Get pointer to the source central dir header and crack it */ + if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); + src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); + src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; + + /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ + if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + if (!pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) + return MZ_FALSE; + + cur_src_file_ofs = src_file_stat.m_local_header_ofs; + cur_dst_file_ofs = pZip->m_archive_size; + + /* Read the source archive's local dir header */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Compute the total size we need to copy (filename+extra data+compressed data) */ + local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; + + /* Try to find a zip64 extended information field */ + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_zip_array file_data_array; + const mz_uint8 *pExtra_data; + mz_uint32 extra_size_remaining = local_header_extra_len; + + mz_zip_array_init(&file_data_array, 1); + if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + + mz_zip_array_clear(pZip, &file_data_array); + } + + if (!pState->m_zip64) + { + /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ + /* We also check when the archive is finalized so this doesn't need to be perfect. */ + mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; + + if (approx_new_archive_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + /* Write dest archive padding */ + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + + cur_dst_file_ofs += num_alignment_padding_bytes; + + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + while (src_archive_bytes_remaining) + { + n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_dst_file_ofs += n; + + src_archive_bytes_remaining -= n; + } + + /* Now deal with the optional data descriptor */ + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + /* Copy data descriptor */ + if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + /* src is zip64, dest must be zip64 */ + + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ + /* uncomp_size 2 */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); + } + else + { + /* src is NOT zip64 */ + mz_bool has_id; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + + if (pZip->m_pState->m_zip64) + { + /* dest is zip64, so upgrade the data descriptor */ + const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0)); + const mz_uint32 src_crc32 = pSrc_descriptor[0]; + const mz_uint64 src_comp_size = pSrc_descriptor[1]; + const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; + + mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); + mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); + + n = sizeof(mz_uint32) * 6; + } + else + { + /* dest is NOT zip64, just copy it as-is */ + n = sizeof(mz_uint32) * (has_id ? 4 : 3); + } + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + /* Finally, add the new central dir header */ + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + + if (pState->m_zip64) + { + /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ + const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; + mz_zip_array new_ext_block; + + mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); + + if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return MZ_FALSE; + } + + MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + mz_zip_array_clear(pZip, &new_ext_block); + } + else + { + /* sanity checks */ + if (cur_dst_file_ofs > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (local_dir_header_ofs >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + } + + /* This shouldn't trigger unless we screwed up during the initial sanity checks */ + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + { + /* TODO: Support central dirs >= 32-bits in size */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + } + + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[256]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + /* Write central directory */ + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += central_dir_size; + } + + if (pState->m_zip64) + { + /* Write zip64 end of central directory header */ + mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; + + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + /* Write zip64 end of central directory locator */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Write end of central directory record */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) +{ + if ((!ppBuf) || (!pSize)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + *ppBuf = NULL; + *pSize = 0; + + if ((!pZip) || (!pZip->m_pState)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_pWrite != mz_zip_heap_write_func) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *ppBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + return mz_zip_writer_end_internal(pZip, MZ_TRUE); +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); +} + +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + mz_zip_zero_struct(&zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_FILENAME; + return MZ_FALSE; + } + + /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ + /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + /* Create a new archive. */ + if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + created_new_archive = MZ_TRUE; + } + else + { + /* Append to an existing archive. */ + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); + + return MZ_FALSE; + } + } + + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + actual_err = zip_archive.m_last_error; + + /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ + if (!mz_zip_writer_finalize_archive(&zip_archive)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if (!mz_zip_writer_end_internal(&zip_archive, status)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if ((!status) && (created_new_archive)) + { + /* It's a new archive and something went wrong, so just delete it. */ + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + + if (pErr) + *pErr = actual_err; + + return status; +} + +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) +{ + mz_uint32 file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + + return NULL; + } + + mz_zip_zero_struct(&zip_archive); + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + return NULL; + } + + if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) + { + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + } + + mz_zip_reader_end_internal(&zip_archive, p != NULL); + + if (pErr) + *pErr = zip_archive.m_last_error; + + return p; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* ------------------- Misc utils */ + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; +} + +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; +} + +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = err_num; + return prev_err; +} + +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + return pZip->m_last_error; +} + +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) +{ + return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); +} + +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = MZ_ZIP_NO_ERROR; + return prev_err; +} + +const char *mz_zip_get_error_string(mz_zip_error mz_err) +{ + switch (mz_err) + { + case MZ_ZIP_NO_ERROR: + return "no error"; + case MZ_ZIP_UNDEFINED_ERROR: + return "undefined error"; + case MZ_ZIP_TOO_MANY_FILES: + return "too many files"; + case MZ_ZIP_FILE_TOO_LARGE: + return "file too large"; + case MZ_ZIP_UNSUPPORTED_METHOD: + return "unsupported method"; + case MZ_ZIP_UNSUPPORTED_ENCRYPTION: + return "unsupported encryption"; + case MZ_ZIP_UNSUPPORTED_FEATURE: + return "unsupported feature"; + case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: + return "failed finding central directory"; + case MZ_ZIP_NOT_AN_ARCHIVE: + return "not a ZIP archive"; + case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: + return "invalid header or archive is corrupted"; + case MZ_ZIP_UNSUPPORTED_MULTIDISK: + return "unsupported multidisk archive"; + case MZ_ZIP_DECOMPRESSION_FAILED: + return "decompression failed or archive is corrupted"; + case MZ_ZIP_COMPRESSION_FAILED: + return "compression failed"; + case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: + return "unexpected decompressed size"; + case MZ_ZIP_CRC_CHECK_FAILED: + return "CRC-32 check failed"; + case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: + return "unsupported central directory size"; + case MZ_ZIP_ALLOC_FAILED: + return "allocation failed"; + case MZ_ZIP_FILE_OPEN_FAILED: + return "file open failed"; + case MZ_ZIP_FILE_CREATE_FAILED: + return "file create failed"; + case MZ_ZIP_FILE_WRITE_FAILED: + return "file write failed"; + case MZ_ZIP_FILE_READ_FAILED: + return "file read failed"; + case MZ_ZIP_FILE_CLOSE_FAILED: + return "file close failed"; + case MZ_ZIP_FILE_SEEK_FAILED: + return "file seek failed"; + case MZ_ZIP_FILE_STAT_FAILED: + return "file stat failed"; + case MZ_ZIP_INVALID_PARAMETER: + return "invalid parameter"; + case MZ_ZIP_INVALID_FILENAME: + return "invalid filename"; + case MZ_ZIP_BUF_TOO_SMALL: + return "buffer too small"; + case MZ_ZIP_INTERNAL_ERROR: + return "internal error"; + case MZ_ZIP_FILE_NOT_FOUND: + return "file not found"; + case MZ_ZIP_ARCHIVE_TOO_LARGE: + return "archive is too large"; + case MZ_ZIP_VALIDATION_FAILED: + return "validation failed"; + case MZ_ZIP_WRITE_CALLBACK_FAILED: + return "write calledback failed"; + default: + break; + } + + return "unknown error"; +} + +/* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return MZ_FALSE; + + return pZip->m_pState->m_zip64; +} + +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + + return pZip->m_pState->m_central_dir.m_size; +} + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) +{ + if (!pZip) + return 0; + return pZip->m_archive_size; +} + +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_file_archive_start_ofs; +} + +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_pFile; +} + +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + if (filename_buf_size) + pFilename[0] = '\0'; + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return 0; + } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); +} + +mz_bool mz_zip_end(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_FALSE; + + if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + return mz_zip_reader_end(pZip); +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + return mz_zip_writer_end(pZip); +#endif + + return MZ_FALSE; +} + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ +/*** End of #include "miniz.c" ***/ + +#endif +#endif + +/* +** COMPRESS +*/ +#ifdef SQLITE_ENABLE_COMPRESS +SQLITE_API +int sqlite3_compress_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi); +/* #include "compress.c" */ +/*** Begin of #include "compress.c" ***/ +/* +** 2014-06-13 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This SQLite extension implements SQL compression functions +** compress() and uncompress() using ZLIB. +*/ +/* #include "sqlite3ext.h" */ + +SQLITE_EXTENSION_INIT1 +/* #include "zlibwrap.h" */ +/*** Begin of #include "zlibwrap.h" ***/ +/* +** Name: zlibwrap.h +** Purpose: Include wrapper for miniz.h +** Author: Ulrich Telle +** Created: 2022-05-09 +** Copyright: (c) 2022 Ulrich Telle +** License: MIT +*/ + +/// \file zlibwrap.h Include wrapper for using miniz.h instead of the original zlib.h + +#ifndef SQLITE3MC_ZLIBWRAP_H_ +#define SQLITE3MC_ZLIBWRAP_H_ + +#if SQLITE3MC_USE_MINIZ != 0 +/* #include "miniz.h" */ + +#else +#include +#endif + + +#endif /* SQLITE3MC_ZLIBWRAP_H_ */ +/*** End of #include "zlibwrap.h" ***/ + + +/* +** Implementation of the "compress(X)" SQL function. The input X is +** compressed using zLib and the output is returned. +** +** The output is a BLOB that begins with a variable-length integer that +** is the input size in bytes (the size of X before compression). The +** variable-length integer is implemented as 1 to 5 bytes. There are +** seven bits per integer stored in the lower seven bits of each byte. +** More significant bits occur first. The most significant bit (0x80) +** is a flag to indicate the end of the integer. +** +** This function, SQLAR, and ZIP all use the same "deflate" compression +** algorithm, but each is subtly different: +** +** * ZIP uses raw deflate. +** +** * SQLAR uses the "zlib format" which is raw deflate with a two-byte +** algorithm-identification header and a four-byte checksum at the end. +** +** * This utility uses the "zlib format" like SQLAR, but adds the variable- +** length integer uncompressed size value at the beginning. +** +** This function might be extended in the future to support compression +** formats other than deflate, by providing a different algorithm-id +** mark following the variable-length integer size parameter. +*/ +static void compressFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *pIn; + unsigned char *pOut; + unsigned int nIn; + unsigned long int nOut; + unsigned char x[8]; + int rc; + int i, j; + + pIn = sqlite3_value_blob(argv[0]); + nIn = sqlite3_value_bytes(argv[0]); + nOut = 13 + nIn + (nIn+999)/1000; + pOut = sqlite3_malloc( nOut+5 ); + for(i=4; i>=0; i--){ + x[i] = (nIn >> (7*(4-i)))&0x7f; + } + for(i=0; i<4 && x[i]==0; i++){} + for(j=0; i<=4; i++, j++) pOut[j] = x[i]; + pOut[j-1] |= 0x80; + rc = compress(&pOut[j], &nOut, pIn, nIn); + if( rc==Z_OK ){ + sqlite3_result_blob(context, pOut, nOut+j, sqlite3_free); + }else{ + sqlite3_free(pOut); + } +} + +/* +** Implementation of the "uncompress(X)" SQL function. The argument X +** is a blob which was obtained from compress(Y). The output will be +** the value Y. +*/ +static void uncompressFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *pIn; + unsigned char *pOut; + unsigned int nIn; + unsigned long int nOut; + int rc; + unsigned int i; + + pIn = sqlite3_value_blob(argv[0]); + nIn = sqlite3_value_bytes(argv[0]); + nOut = 0; + for(i=0; i + +/* +** Implementation of the "sqlar_compress(X)" SQL function. +** +** If the type of X is SQLITE_BLOB, and compressing that blob using +** zlib utility function compress() yields a smaller blob, return the +** compressed blob. Otherwise, return a copy of X. +** +** SQLar uses the "zlib format" for compressed content. The zlib format +** contains a two-byte identification header and a four-byte checksum at +** the end. This is different from ZIP which uses the raw deflate format. +** +** Future enhancements to SQLar might add support for new compression formats. +** If so, those new formats will be identified by alternative headers in the +** compressed data. +*/ +static void sqlarCompressFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + assert( argc==1 ); + if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ + const Bytef *pData = sqlite3_value_blob(argv[0]); + uLong nData = sqlite3_value_bytes(argv[0]); + uLongf nOut = compressBound(nData); + Bytef *pOut; + + pOut = (Bytef*)sqlite3_malloc(nOut); + if( pOut==0 ){ + sqlite3_result_error_nomem(context); + return; + }else{ + if( Z_OK!=compress(pOut, &nOut, pData, nData) ){ + sqlite3_result_error(context, "error in compress()", -1); + }else if( nOut +#include +#include +#ifndef SQLITE_NO_STDINT +# include +#endif + +/* #include "zlibwrap.h" */ + + +/* When used as part of the CLI, the sqlite3_stdio.h module will have +** been included before this one. In that case use the sqlite3_stdio.h +** #defines. If not, create our own for fopen(). +*/ +#ifndef _SQLITE3_STDIO_H_ +# define sqlite3_fopen fopen +#endif + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +#ifndef SQLITE_AMALGAMATION + +#ifndef UINT32_TYPE +# ifdef HAVE_UINT32_T +# define UINT32_TYPE uint32_t +# else +# define UINT32_TYPE unsigned int +# endif +#endif +#ifndef UINT16_TYPE +# ifdef HAVE_UINT16_T +# define UINT16_TYPE uint16_t +# else +# define UINT16_TYPE unsigned short int +# endif +#endif +typedef sqlite3_int64 i64; +typedef unsigned char u8; +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ +#define MIN(a,b) ((a)<(b) ? (a) : (b)) + +#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) +# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1 +#endif +#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS) +# define ALWAYS(X) (1) +# define NEVER(X) (0) +#elif !defined(NDEBUG) +# define ALWAYS(X) ((X)?1:(assert(0),0)) +# define NEVER(X) ((X)?(assert(0),1):0) +#else +# define ALWAYS(X) (X) +# define NEVER(X) (X) +#endif + +#endif /* SQLITE_AMALGAMATION */ + +/* +** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. +** +** In some ways it would be better to obtain these values from system +** header files. But, the dependency is undesirable and (a) these +** have been stable for decades, (b) the values are part of POSIX and +** are also made explicit in [man stat], and (c) are part of the +** file format for zip archives. +*/ +#ifndef S_IFDIR +# define S_IFDIR 0040000 +#endif +#ifndef S_IFREG +# define S_IFREG 0100000 +#endif +#ifndef S_IFLNK +# define S_IFLNK 0120000 +#endif + +static const char ZIPFILE_SCHEMA[] = + "CREATE TABLE y(" + "name PRIMARY KEY," /* 0: Name of file in zip archive */ + "mode," /* 1: POSIX mode for file */ + "mtime," /* 2: Last modification time (secs since 1970)*/ + "sz," /* 3: Size of object */ + "rawdata," /* 4: Raw data */ + "data," /* 5: Uncompressed data */ + "method," /* 6: Compression method (integer) */ + "z HIDDEN" /* 7: Name of zip file */ + ") WITHOUT ROWID;"; + +#define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ +#define ZIPFILE_BUFFER_SIZE (64*1024) + + +/* +** Magic numbers used to read and write zip files. +** +** ZIPFILE_NEWENTRY_MADEBY: +** Use this value for the "version-made-by" field in new zip file +** entries. The upper byte indicates "unix", and the lower byte +** indicates that the zip file matches pkzip specification 3.0. +** This is what info-zip seems to do. +** +** ZIPFILE_NEWENTRY_REQUIRED: +** Value for "version-required-to-extract" field of new entries. +** Version 2.0 is required to support folders and deflate compression. +** +** ZIPFILE_NEWENTRY_FLAGS: +** Value for "general-purpose-bit-flags" field of new entries. Bit +** 11 means "utf-8 filename and comment". +** +** ZIPFILE_SIGNATURE_CDS: +** First 4 bytes of a valid CDS record. +** +** ZIPFILE_SIGNATURE_LFH: +** First 4 bytes of a valid LFH record. +** +** ZIPFILE_SIGNATURE_EOCD +** First 4 bytes of a valid EOCD record. +*/ +#define ZIPFILE_EXTRA_TIMESTAMP 0x5455 +#define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) +#define ZIPFILE_NEWENTRY_REQUIRED 20 +#define ZIPFILE_NEWENTRY_FLAGS 0x800 +#define ZIPFILE_SIGNATURE_CDS 0x02014b50 +#define ZIPFILE_SIGNATURE_LFH 0x04034b50 +#define ZIPFILE_SIGNATURE_EOCD 0x06054b50 + +/* +** The sizes of the fixed-size part of each of the three main data +** structures in a zip archive. +*/ +#define ZIPFILE_LFH_FIXED_SZ 30 +#define ZIPFILE_EOCD_FIXED_SZ 22 +#define ZIPFILE_CDS_FIXED_SZ 46 + +/* +*** 4.3.16 End of central directory record: +*** +*** end of central dir signature 4 bytes (0x06054b50) +*** number of this disk 2 bytes +*** number of the disk with the +*** start of the central directory 2 bytes +*** total number of entries in the +*** central directory on this disk 2 bytes +*** total number of entries in +*** the central directory 2 bytes +*** size of the central directory 4 bytes +*** offset of start of central +*** directory with respect to +*** the starting disk number 4 bytes +*** .ZIP file comment length 2 bytes +*** .ZIP file comment (variable size) +*/ +typedef struct ZipfileEOCD ZipfileEOCD; +struct ZipfileEOCD { + u16 iDisk; + u16 iFirstDisk; + u16 nEntry; + u16 nEntryTotal; + u32 nSize; + u32 iOffset; +}; + +/* +*** 4.3.12 Central directory structure: +*** +*** ... +*** +*** central file header signature 4 bytes (0x02014b50) +*** version made by 2 bytes +*** version needed to extract 2 bytes +*** general purpose bit flag 2 bytes +*** compression method 2 bytes +*** last mod file time 2 bytes +*** last mod file date 2 bytes +*** crc-32 4 bytes +*** compressed size 4 bytes +*** uncompressed size 4 bytes +*** file name length 2 bytes +*** extra field length 2 bytes +*** file comment length 2 bytes +*** disk number start 2 bytes +*** internal file attributes 2 bytes +*** external file attributes 4 bytes +*** relative offset of local header 4 bytes +*/ +typedef struct ZipfileCDS ZipfileCDS; +struct ZipfileCDS { + u16 iVersionMadeBy; + u16 iVersionExtract; + u16 flags; + u16 iCompression; + u16 mTime; + u16 mDate; + u32 crc32; + u32 szCompressed; + u32 szUncompressed; + u16 nFile; + u16 nExtra; + u16 nComment; + u16 iDiskStart; + u16 iInternalAttr; + u32 iExternalAttr; + u32 iOffset; + char *zFile; /* Filename (sqlite3_malloc()) */ +}; + +/* +*** 4.3.7 Local file header: +*** +*** local file header signature 4 bytes (0x04034b50) +*** version needed to extract 2 bytes +*** general purpose bit flag 2 bytes +*** compression method 2 bytes +*** last mod file time 2 bytes +*** last mod file date 2 bytes +*** crc-32 4 bytes +*** compressed size 4 bytes +*** uncompressed size 4 bytes +*** file name length 2 bytes +*** extra field length 2 bytes +*** +*/ +typedef struct ZipfileLFH ZipfileLFH; +struct ZipfileLFH { + u16 iVersionExtract; + u16 flags; + u16 iCompression; + u16 mTime; + u16 mDate; + u32 crc32; + u32 szCompressed; + u32 szUncompressed; + u16 nFile; + u16 nExtra; +}; + +typedef struct ZipfileEntry ZipfileEntry; +struct ZipfileEntry { + ZipfileCDS cds; /* Parsed CDS record */ + u32 mUnixTime; /* Modification time, in UNIX format */ + u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ + i64 iDataOff; /* Offset to data in file (if aData==0) */ + u8 *aData; /* cds.szCompressed bytes of compressed data */ + ZipfileEntry *pNext; /* Next element in in-memory CDS */ +}; + +/* +** Cursor type for zipfile tables. +*/ +typedef struct ZipfileCsr ZipfileCsr; +struct ZipfileCsr { + sqlite3_vtab_cursor base; /* Base class - must be first */ + i64 iId; /* Cursor ID */ + u8 bEof; /* True when at EOF */ + u8 bNoop; /* If next xNext() call is no-op */ + + /* Used outside of write transactions */ + FILE *pFile; /* Zip file */ + i64 iNextOff; /* Offset of next record in central directory */ + ZipfileEOCD eocd; /* Parse of central directory record */ + + ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ + ZipfileEntry *pCurrent; /* Current entry */ + ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ +}; + +typedef struct ZipfileTab ZipfileTab; +struct ZipfileTab { + sqlite3_vtab base; /* Base class - must be first */ + char *zFile; /* Zip file this table accesses (may be NULL) */ + sqlite3 *db; /* Host database connection */ + u8 *aBuffer; /* Temporary buffer used for various tasks */ + + ZipfileCsr *pCsrList; /* List of cursors */ + i64 iNextCsrid; + + /* The following are used by write transactions only */ + ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ + ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ + FILE *pWriteFd; /* File handle open on zip archive */ + i64 szCurrent; /* Current size of zip archive */ + i64 szOrig; /* Size of archive at start of transaction */ +}; + +/* +** Set the error message contained in context ctx to the results of +** vprintf(zFmt, ...). +*/ +static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ + char *zMsg = 0; + va_list ap; + va_start(ap, zFmt); + zMsg = sqlite3_vmprintf(zFmt, ap); + sqlite3_result_error(ctx, zMsg, -1); + sqlite3_free(zMsg); + va_end(ap); +} + +/* +** If string zIn is quoted, dequote it in place. Otherwise, if the string +** is not quoted, do nothing. +*/ +static void zipfileDequote(char *zIn){ + char q = zIn[0]; + if( q=='"' || q=='\'' || q=='`' || q=='[' ){ + int iIn = 1; + int iOut = 0; + if( q=='[' ) q = ']'; + while( ALWAYS(zIn[iIn]) ){ + char c = zIn[iIn++]; + if( c==q && zIn[iIn++]!=q ) break; + zIn[iOut++] = c; + } + zIn[iOut] = '\0'; + } +} + +/* +** Construct a new ZipfileTab virtual table object. +** +** argv[0] -> module name ("zipfile") +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> "column name" and other module argument fields. +*/ +static int zipfileConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; + int nFile = 0; + const char *zFile = 0; + ZipfileTab *pNew = 0; + int rc; + (void)pAux; + + /* If the table name is not "zipfile", require that the argument be + ** specified. This stops zipfile tables from being created as: + ** + ** CREATE VIRTUAL TABLE zzz USING zipfile(); + ** + ** It does not prevent: + ** + ** CREATE VIRTUAL TABLE zipfile USING zipfile(); + */ + assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); + if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ + *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); + return SQLITE_ERROR; + } + + if( argc>3 ){ + zFile = argv[3]; + nFile = (int)strlen(zFile)+1; + } + + rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); + if( rc==SQLITE_OK ){ + pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, nByte+nFile); + pNew->db = db; + pNew->aBuffer = (u8*)&pNew[1]; + if( zFile ){ + pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; + memcpy(pNew->zFile, zFile, nFile); + zipfileDequote(pNew->zFile); + } + } + sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); + *ppVtab = (sqlite3_vtab*)pNew; + return rc; +} + +/* +** Free the ZipfileEntry structure indicated by the only argument. +*/ +static void zipfileEntryFree(ZipfileEntry *p){ + if( p ){ + sqlite3_free(p->cds.zFile); + sqlite3_free(p); + } +} + +/* +** Release resources that should be freed at the end of a write +** transaction. +*/ +static void zipfileCleanupTransaction(ZipfileTab *pTab){ + ZipfileEntry *pEntry; + ZipfileEntry *pNext; + + if( pTab->pWriteFd ){ + fclose(pTab->pWriteFd); + pTab->pWriteFd = 0; + } + for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ + pNext = pEntry->pNext; + zipfileEntryFree(pEntry); + } + pTab->pFirstEntry = 0; + pTab->pLastEntry = 0; + pTab->szCurrent = 0; + pTab->szOrig = 0; +} + +/* +** This method is the destructor for zipfile vtab objects. +*/ +static int zipfileDisconnect(sqlite3_vtab *pVtab){ + zipfileCleanupTransaction((ZipfileTab*)pVtab); + sqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** Constructor for a new ZipfileCsr object. +*/ +static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ + ZipfileTab *pTab = (ZipfileTab*)p; + ZipfileCsr *pCsr; + pCsr = sqlite3_malloc(sizeof(*pCsr)); + *ppCsr = (sqlite3_vtab_cursor*)pCsr; + if( pCsr==0 ){ + return SQLITE_NOMEM; + } + memset(pCsr, 0, sizeof(*pCsr)); + pCsr->iId = ++pTab->iNextCsrid; + pCsr->pCsrNext = pTab->pCsrList; + pTab->pCsrList = pCsr; + return SQLITE_OK; +} + +/* +** Reset a cursor back to the state it was in when first returned +** by zipfileOpen(). +*/ +static void zipfileResetCursor(ZipfileCsr *pCsr){ + ZipfileEntry *p; + ZipfileEntry *pNext; + + pCsr->bEof = 0; + if( pCsr->pFile ){ + fclose(pCsr->pFile); + pCsr->pFile = 0; + zipfileEntryFree(pCsr->pCurrent); + pCsr->pCurrent = 0; + } + + for(p=pCsr->pFreeEntry; p; p=pNext){ + pNext = p->pNext; + zipfileEntryFree(p); + } +} + +/* +** Destructor for an ZipfileCsr. +*/ +static int zipfileClose(sqlite3_vtab_cursor *cur){ + ZipfileCsr *pCsr = (ZipfileCsr*)cur; + ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); + ZipfileCsr **pp; + zipfileResetCursor(pCsr); + + /* Remove this cursor from the ZipfileTab.pCsrList list. */ + for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); + *pp = pCsr->pCsrNext; + + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Set the error message for the virtual table associated with cursor +** pCsr to the results of vprintf(zFmt, ...). +*/ +static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ + va_list ap; + va_start(ap, zFmt); + sqlite3_free(pTab->base.zErrMsg); + pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); + va_end(ap); +} +static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ + va_list ap; + va_start(ap, zFmt); + sqlite3_free(pCsr->base.pVtab->zErrMsg); + pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); + va_end(ap); +} + +/* +** Read nRead bytes of data from offset iOff of file pFile into buffer +** aRead[]. Return SQLITE_OK if successful, or an SQLite error code +** otherwise. +** +** If an error does occur, output variable (*pzErrmsg) may be set to point +** to an English language error message. It is the responsibility of the +** caller to eventually free this buffer using +** sqlite3_free(). +*/ +static int zipfileReadData( + FILE *pFile, /* Read from this file */ + u8 *aRead, /* Read into this buffer */ + int nRead, /* Number of bytes to read */ + i64 iOff, /* Offset to read from */ + char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ +){ + size_t n; + fseek(pFile, (long)iOff, SEEK_SET); + n = fread(aRead, 1, nRead, pFile); + if( (int)n!=nRead ){ + *pzErrmsg = sqlite3_mprintf("error in fread()"); + return SQLITE_ERROR; + } + return SQLITE_OK; +} + +static int zipfileAppendData( + ZipfileTab *pTab, + const u8 *aWrite, + int nWrite +){ + if( nWrite>0 ){ + size_t n = nWrite; + fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); + n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); + if( (int)n!=nWrite ){ + pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); + return SQLITE_ERROR; + } + pTab->szCurrent += nWrite; + } + return SQLITE_OK; +} + +/* +** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. +*/ +static u16 zipfileGetU16(const u8 *aBuf){ + return (aBuf[1] << 8) + aBuf[0]; +} + +/* +** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. +*/ +static u32 zipfileGetU32(const u8 *aBuf){ + if( aBuf==0 ) return 0; + return ((u32)(aBuf[3]) << 24) + + ((u32)(aBuf[2]) << 16) + + ((u32)(aBuf[1]) << 8) + + ((u32)(aBuf[0]) << 0); +} + +/* +** Write a 16-bit little endiate integer into buffer aBuf. +*/ +static void zipfilePutU16(u8 *aBuf, u16 val){ + aBuf[0] = val & 0xFF; + aBuf[1] = (val>>8) & 0xFF; +} + +/* +** Write a 32-bit little endiate integer into buffer aBuf. +*/ +static void zipfilePutU32(u8 *aBuf, u32 val){ + aBuf[0] = val & 0xFF; + aBuf[1] = (val>>8) & 0xFF; + aBuf[2] = (val>>16) & 0xFF; + aBuf[3] = (val>>24) & 0xFF; +} + +#define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) +#define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) + +#define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } +#define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } + +/* +** Magic numbers used to read CDS records. +*/ +#define ZIPFILE_CDS_NFILE_OFF 28 +#define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 + +/* +** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR +** if the record is not well-formed, or SQLITE_OK otherwise. +*/ +static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ + u8 *aRead = aBuf; + u32 sig = zipfileRead32(aRead); + int rc = SQLITE_OK; + if( sig!=ZIPFILE_SIGNATURE_CDS ){ + rc = SQLITE_ERROR; + }else{ + pCDS->iVersionMadeBy = zipfileRead16(aRead); + pCDS->iVersionExtract = zipfileRead16(aRead); + pCDS->flags = zipfileRead16(aRead); + pCDS->iCompression = zipfileRead16(aRead); + pCDS->mTime = zipfileRead16(aRead); + pCDS->mDate = zipfileRead16(aRead); + pCDS->crc32 = zipfileRead32(aRead); + pCDS->szCompressed = zipfileRead32(aRead); + pCDS->szUncompressed = zipfileRead32(aRead); + assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); + pCDS->nFile = zipfileRead16(aRead); + pCDS->nExtra = zipfileRead16(aRead); + pCDS->nComment = zipfileRead16(aRead); + pCDS->iDiskStart = zipfileRead16(aRead); + pCDS->iInternalAttr = zipfileRead16(aRead); + pCDS->iExternalAttr = zipfileRead32(aRead); + pCDS->iOffset = zipfileRead32(aRead); + assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); + } + + return rc; +} + +/* +** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR +** if the record is not well-formed, or SQLITE_OK otherwise. +*/ +static int zipfileReadLFH( + u8 *aBuffer, + ZipfileLFH *pLFH +){ + u8 *aRead = aBuffer; + int rc = SQLITE_OK; + + u32 sig = zipfileRead32(aRead); + if( sig!=ZIPFILE_SIGNATURE_LFH ){ + rc = SQLITE_ERROR; + }else{ + pLFH->iVersionExtract = zipfileRead16(aRead); + pLFH->flags = zipfileRead16(aRead); + pLFH->iCompression = zipfileRead16(aRead); + pLFH->mTime = zipfileRead16(aRead); + pLFH->mDate = zipfileRead16(aRead); + pLFH->crc32 = zipfileRead32(aRead); + pLFH->szCompressed = zipfileRead32(aRead); + pLFH->szUncompressed = zipfileRead32(aRead); + pLFH->nFile = zipfileRead16(aRead); + pLFH->nExtra = zipfileRead16(aRead); + } + return rc; +} + + +/* +** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. +** Scan through this buffer to find an "extra-timestamp" field. If one +** exists, extract the 32-bit modification-timestamp from it and store +** the value in output parameter *pmTime. +** +** Zero is returned if no extra-timestamp record could be found (and so +** *pmTime is left unchanged), or non-zero otherwise. +** +** The general format of an extra field is: +** +** Header ID 2 bytes +** Data Size 2 bytes +** Data N bytes +*/ +static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ + int ret = 0; + u8 *p = aExtra; + u8 *pEnd = &aExtra[nExtra]; + + while( p modtime is present */ + *pmTime = zipfileGetU32(&p[1]); + ret = 1; + } + break; + } + } + + p += nByte; + } + return ret; +} + +/* +** Convert the standard MS-DOS timestamp stored in the mTime and mDate +** fields of the CDS structure passed as the only argument to a 32-bit +** UNIX seconds-since-the-epoch timestamp. Return the result. +** +** "Standard" MS-DOS time format: +** +** File modification time: +** Bits 00-04: seconds divided by 2 +** Bits 05-10: minute +** Bits 11-15: hour +** File modification date: +** Bits 00-04: day +** Bits 05-08: month (1-12) +** Bits 09-15: years from 1980 +** +** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx +*/ +static u32 zipfileMtime(ZipfileCDS *pCDS){ + int Y,M,D,X1,X2,A,B,sec,min,hr; + i64 JDsec; + Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); + M = ((pCDS->mDate >> 5) & 0x0F); + D = (pCDS->mDate & 0x1F); + sec = (pCDS->mTime & 0x1F)*2; + min = (pCDS->mTime >> 5) & 0x3F; + hr = (pCDS->mTime >> 11) & 0x1F; + if( M<=2 ){ + Y--; + M += 12; + } + X1 = 36525*(Y+4716)/100; + X2 = 306001*(M+1)/10000; + A = Y/100; + B = 2 - A + (A/4); + JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec; + return (u32)(JDsec - (i64)24405875*(i64)8640); +} + +/* +** The opposite of zipfileMtime(). This function populates the mTime and +** mDate fields of the CDS structure passed as the first argument according +** to the UNIX timestamp value passed as the second. +*/ +static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ + /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */ + i64 JD = (i64)2440588 + mUnixTime / (24*60*60); + + int A, B, C, D, E; + int yr, mon, day; + int hr, min, sec; + + A = (int)((JD - 1867216.25)/36524.25); + A = (int)(JD + 1 + A - (A/4)); + B = A + 1524; + C = (int)((B - 122.1)/365.25); + D = (36525*(C&32767))/100; + E = (int)((B-D)/30.6001); + + day = B - D - (int)(30.6001*E); + mon = (E<14 ? E-1 : E-13); + yr = mon>2 ? C-4716 : C-4715; + + hr = (mUnixTime % (24*60*60)) / (60*60); + min = (mUnixTime % (60*60)) / 60; + sec = (mUnixTime % 60); + + if( yr>=1980 ){ + pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); + pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); + }else{ + pCds->mDate = pCds->mTime = 0; + } + + assert( mUnixTime<315507600 + || mUnixTime==zipfileMtime(pCds) + || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) + /* || (mUnixTime % 2) */ + ); +} + +/* +** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in +** size) containing an entire zip archive image. Or, if aBlob is NULL, +** then pFile is a file-handle open on a zip file. In either case, this +** function creates a ZipfileEntry object based on the zip archive entry +** for which the CDS record is at offset iOff. +** +** If successful, SQLITE_OK is returned and (*ppEntry) set to point to +** the new object. Otherwise, an SQLite error code is returned and the +** final value of (*ppEntry) undefined. +*/ +static int zipfileGetEntry( + ZipfileTab *pTab, /* Store any error message here */ + const u8 *aBlob, /* Pointer to in-memory file image */ + int nBlob, /* Size of aBlob[] in bytes */ + FILE *pFile, /* If aBlob==0, read from this file */ + i64 iOff, /* Offset of CDS record */ + ZipfileEntry **ppEntry /* OUT: Pointer to new object */ +){ + u8 *aRead; + char **pzErr = &pTab->base.zErrMsg; + int rc = SQLITE_OK; + (void)nBlob; + + if( aBlob==0 ){ + aRead = pTab->aBuffer; + rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); + }else{ + aRead = (u8*)&aBlob[iOff]; + } + + if( rc==SQLITE_OK ){ + sqlite3_int64 nAlloc; + ZipfileEntry *pNew; + + int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); + int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); + nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); + + nAlloc = sizeof(ZipfileEntry) + nExtra; + if( aBlob ){ + nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); + } + + pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pNew, 0, sizeof(ZipfileEntry)); + rc = zipfileReadCDS(aRead, &pNew->cds); + if( rc!=SQLITE_OK ){ + *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff); + }else if( aBlob==0 ){ + rc = zipfileReadData( + pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr + ); + }else{ + aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; + } + } + + if( rc==SQLITE_OK ){ + u32 *pt = &pNew->mUnixTime; + pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); + pNew->aExtra = (u8*)&pNew[1]; + memcpy(pNew->aExtra, &aRead[nFile], nExtra); + if( pNew->cds.zFile==0 ){ + rc = SQLITE_NOMEM; + }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ + pNew->mUnixTime = zipfileMtime(&pNew->cds); + } + } + + if( rc==SQLITE_OK ){ + static const int szFix = ZIPFILE_LFH_FIXED_SZ; + ZipfileLFH lfh; + if( pFile ){ + rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); + }else{ + aRead = (u8*)&aBlob[pNew->cds.iOffset]; + } + + if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh); + if( rc==SQLITE_OK ){ + pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; + pNew->iDataOff += lfh.nFile + lfh.nExtra; + if( aBlob && pNew->cds.szCompressed ){ + pNew->aData = &pNew->aExtra[nExtra]; + memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); + } + }else{ + *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", + (int)pNew->cds.iOffset + ); + } + } + + if( rc!=SQLITE_OK ){ + zipfileEntryFree(pNew); + }else{ + *ppEntry = pNew; + } + } + + return rc; +} + +/* +** Advance an ZipfileCsr to its next row of output. +*/ +static int zipfileNext(sqlite3_vtab_cursor *cur){ + ZipfileCsr *pCsr = (ZipfileCsr*)cur; + int rc = SQLITE_OK; + + if( pCsr->pFile ){ + i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; + zipfileEntryFree(pCsr->pCurrent); + pCsr->pCurrent = 0; + if( pCsr->iNextOff>=iEof ){ + pCsr->bEof = 1; + }else{ + ZipfileEntry *p = 0; + ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); + rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); + if( rc==SQLITE_OK ){ + pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; + pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; + } + pCsr->pCurrent = p; + } + }else{ + if( !pCsr->bNoop ){ + pCsr->pCurrent = pCsr->pCurrent->pNext; + } + if( pCsr->pCurrent==0 ){ + pCsr->bEof = 1; + } + } + + pCsr->bNoop = 0; + return rc; +} + +static void zipfileFree(void *p) { + sqlite3_free(p); +} + +/* +** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the +** size is nOut bytes. This function uncompresses the data and sets the +** return value in context pCtx to the result (a blob). +** +** If an error occurs, an error code is left in pCtx instead. +*/ +static void zipfileInflate( + sqlite3_context *pCtx, /* Store result here */ + const u8 *aIn, /* Compressed data */ + int nIn, /* Size of buffer aIn[] in bytes */ + int nOut /* Expected output size */ +){ + u8 *aRes = sqlite3_malloc(nOut); + if( aRes==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + int err; + z_stream str; + memset(&str, 0, sizeof(str)); + + str.next_in = (Byte*)aIn; + str.avail_in = nIn; + str.next_out = (Byte*)aRes; + str.avail_out = nOut; + + err = inflateInit2(&str, -15); + if( err!=Z_OK ){ + zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); + }else{ + err = inflate(&str, Z_NO_FLUSH); + if( err!=Z_STREAM_END ){ + zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); + }else{ + sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree); + aRes = 0; + } + } + sqlite3_free(aRes); + inflateEnd(&str); + } +} + +/* +** Buffer aIn (size nIn bytes) contains uncompressed data. This function +** compresses it and sets (*ppOut) to point to a buffer containing the +** compressed data. The caller is responsible for eventually calling +** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) +** is set to the size of buffer (*ppOut) in bytes. +** +** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error +** code is returned and an error message left in virtual-table handle +** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this +** case. +*/ +static int zipfileDeflate( + const u8 *aIn, int nIn, /* Input */ + u8 **ppOut, int *pnOut, /* Output */ + char **pzErr /* OUT: Error message */ +){ + int rc = SQLITE_OK; + sqlite3_int64 nAlloc; + z_stream str; + u8 *aOut; + + memset(&str, 0, sizeof(str)); + str.next_in = (Bytef*)aIn; + str.avail_in = nIn; + deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); + + nAlloc = deflateBound(&str, nIn); + aOut = (u8*)sqlite3_malloc64(nAlloc); + if( aOut==0 ){ + rc = SQLITE_NOMEM; + }else{ + int res; + str.next_out = aOut; + str.avail_out = nAlloc; + res = deflate(&str, Z_FINISH); + if( res==Z_STREAM_END ){ + *ppOut = aOut; + *pnOut = (int)str.total_out; + }else{ + sqlite3_free(aOut); + *pzErr = sqlite3_mprintf("zipfile: deflate() error"); + rc = SQLITE_ERROR; + } + deflateEnd(&str); + } + + return rc; +} + + +/* +** Return values of columns for the row at which the series_cursor +** is currently pointing. +*/ +static int zipfileColumn( + sqlite3_vtab_cursor *cur, /* The cursor */ + sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ + int i /* Which column to return */ +){ + ZipfileCsr *pCsr = (ZipfileCsr*)cur; + ZipfileCDS *pCDS = &pCsr->pCurrent->cds; + int rc = SQLITE_OK; + switch( i ){ + case 0: /* name */ + sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); + break; + case 1: /* mode */ + /* TODO: Whether or not the following is correct surely depends on + ** the platform on which the archive was created. */ + sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); + break; + case 2: { /* mtime */ + sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); + break; + } + case 3: { /* sz */ + if( sqlite3_vtab_nochange(ctx)==0 ){ + sqlite3_result_int64(ctx, pCDS->szUncompressed); + } + break; + } + case 4: /* rawdata */ + if( sqlite3_vtab_nochange(ctx) ) break; + case 5: { /* data */ + if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ + int sz = pCDS->szCompressed; + int szFinal = pCDS->szUncompressed; + if( szFinal>0 ){ + u8 *aBuf; + u8 *aFree = 0; + if( pCsr->pCurrent->aData ){ + aBuf = pCsr->pCurrent->aData; + }else{ + aBuf = aFree = sqlite3_malloc64(sz); + if( aBuf==0 ){ + rc = SQLITE_NOMEM; + }else{ + FILE *pFile = pCsr->pFile; + if( pFile==0 ){ + pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; + } + rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, + &pCsr->base.pVtab->zErrMsg + ); + } + } + if( rc==SQLITE_OK ){ + if( i==5 && pCDS->iCompression ){ + zipfileInflate(ctx, aBuf, sz, szFinal); + }else{ + sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); + } + } + sqlite3_free(aFree); + }else{ + /* Figure out if this is a directory or a zero-sized file. Consider + ** it to be a directory either if the mode suggests so, or if + ** the final character in the name is '/'. */ + u32 mode = pCDS->iExternalAttr >> 16; + if( !(mode & S_IFDIR) + && pCDS->nFile>=1 + && pCDS->zFile[pCDS->nFile-1]!='/' + ){ + sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); + } + } + } + break; + } + case 6: /* method */ + sqlite3_result_int(ctx, pCDS->iCompression); + break; + default: /* z */ + assert( i==7 ); + sqlite3_result_int64(ctx, pCsr->iId); + break; + } + + return rc; +} + +/* +** Return TRUE if the cursor is at EOF. +*/ +static int zipfileEof(sqlite3_vtab_cursor *cur){ + ZipfileCsr *pCsr = (ZipfileCsr*)cur; + return pCsr->bEof; +} + +/* +** If aBlob is not NULL, then it points to a buffer nBlob bytes in size +** containing an entire zip archive image. Or, if aBlob is NULL, then pFile +** is guaranteed to be a file-handle open on a zip file. +** +** This function attempts to locate the EOCD record within the zip archive +** and populate *pEOCD with the results of decoding it. SQLITE_OK is +** returned if successful. Otherwise, an SQLite error code is returned and +** an English language error message may be left in virtual-table pTab. +*/ +static int zipfileReadEOCD( + ZipfileTab *pTab, /* Return errors here */ + const u8 *aBlob, /* Pointer to in-memory file image */ + int nBlob, /* Size of aBlob[] in bytes */ + FILE *pFile, /* Read from this file if aBlob==0 */ + ZipfileEOCD *pEOCD /* Object to populate */ +){ + u8 *aRead = pTab->aBuffer; /* Temporary buffer */ + int nRead; /* Bytes to read from file */ + int rc = SQLITE_OK; + + memset(pEOCD, 0, sizeof(ZipfileEOCD)); + if( aBlob==0 ){ + i64 iOff; /* Offset to read from */ + i64 szFile; /* Total size of file in bytes */ + fseek(pFile, 0, SEEK_END); + szFile = (i64)ftell(pFile); + if( szFile==0 ){ + return SQLITE_OK; + } + nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); + iOff = szFile - nRead; + rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); + }else{ + nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); + aRead = (u8*)&aBlob[nBlob-nRead]; + } + + if( rc==SQLITE_OK ){ + int i; + + /* Scan backwards looking for the signature bytes */ + for(i=nRead-20; i>=0; i--){ + if( aRead[i]==0x50 && aRead[i+1]==0x4b + && aRead[i+2]==0x05 && aRead[i+3]==0x06 + ){ + break; + } + } + if( i<0 ){ + pTab->base.zErrMsg = sqlite3_mprintf( + "cannot find end of central directory record" + ); + return SQLITE_ERROR; + } + + aRead += i+4; + pEOCD->iDisk = zipfileRead16(aRead); + pEOCD->iFirstDisk = zipfileRead16(aRead); + pEOCD->nEntry = zipfileRead16(aRead); + pEOCD->nEntryTotal = zipfileRead16(aRead); + pEOCD->nSize = zipfileRead32(aRead); + pEOCD->iOffset = zipfileRead32(aRead); + } + + return rc; +} + +/* +** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry +** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added +** to the end of the list. Otherwise, it is added to the list immediately +** before pBefore (which is guaranteed to be a part of said list). +*/ +static void zipfileAddEntry( + ZipfileTab *pTab, + ZipfileEntry *pBefore, + ZipfileEntry *pNew +){ + assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); + assert( pNew->pNext==0 ); + if( pBefore==0 ){ + if( pTab->pFirstEntry==0 ){ + pTab->pFirstEntry = pTab->pLastEntry = pNew; + }else{ + assert( pTab->pLastEntry->pNext==0 ); + pTab->pLastEntry->pNext = pNew; + pTab->pLastEntry = pNew; + } + }else{ + ZipfileEntry **pp; + for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); + pNew->pNext = pBefore; + *pp = pNew; + } +} + +static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){ + ZipfileEOCD eocd; + int rc; + int i; + i64 iOff; + + rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); + iOff = eocd.iOffset; + for(i=0; rc==SQLITE_OK && ipWriteFd, iOff, &pNew); + + if( rc==SQLITE_OK ){ + zipfileAddEntry(pTab, 0, pNew); + iOff += ZIPFILE_CDS_FIXED_SZ; + iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; + } + } + return rc; +} + +/* +** xFilter callback. +*/ +static int zipfileFilter( + sqlite3_vtab_cursor *cur, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; + ZipfileCsr *pCsr = (ZipfileCsr*)cur; + const char *zFile = 0; /* Zip file to scan */ + int rc = SQLITE_OK; /* Return Code */ + int bInMemory = 0; /* True for an in-memory zipfile */ + + (void)idxStr; + (void)argc; + + zipfileResetCursor(pCsr); + + if( pTab->zFile ){ + zFile = pTab->zFile; + }else if( idxNum==0 ){ + zipfileCursorErr(pCsr, "zipfile() function requires an argument"); + return SQLITE_ERROR; + }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ + static const u8 aEmptyBlob = 0; + const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); + int nBlob = sqlite3_value_bytes(argv[0]); + assert( pTab->pFirstEntry==0 ); + if( aBlob==0 ){ + aBlob = &aEmptyBlob; + nBlob = 0; + } + rc = zipfileLoadDirectory(pTab, aBlob, nBlob); + pCsr->pFreeEntry = pTab->pFirstEntry; + pTab->pFirstEntry = pTab->pLastEntry = 0; + if( rc!=SQLITE_OK ) return rc; + bInMemory = 1; + }else{ + zFile = (const char*)sqlite3_value_text(argv[0]); + } + + if( 0==pTab->pWriteFd && 0==bInMemory ){ + pCsr->pFile = zFile ? sqlite3_fopen(zFile, "rb") : 0; + if( pCsr->pFile==0 ){ + zipfileCursorErr(pCsr, "cannot open file: %s", zFile); + rc = SQLITE_ERROR; + }else{ + rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); + if( rc==SQLITE_OK ){ + if( pCsr->eocd.nEntry==0 ){ + pCsr->bEof = 1; + }else{ + pCsr->iNextOff = pCsr->eocd.iOffset; + rc = zipfileNext(cur); + } + } + } + }else{ + pCsr->bNoop = 1; + pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; + rc = zipfileNext(cur); + } + + return rc; +} + +/* +** xBestIndex callback. +*/ +static int zipfileBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo +){ + int i; + int idx = -1; + int unusable = 0; + (void)tab; + + for(i=0; inConstraint; i++){ + const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; + if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; + if( pCons->usable==0 ){ + unusable = 1; + }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + idx = i; + } + } + pIdxInfo->estimatedCost = 1000.0; + if( idx>=0 ){ + pIdxInfo->aConstraintUsage[idx].argvIndex = 1; + pIdxInfo->aConstraintUsage[idx].omit = 1; + pIdxInfo->idxNum = 1; + }else if( unusable ){ + return SQLITE_CONSTRAINT; + } + return SQLITE_OK; +} + +static ZipfileEntry *zipfileNewEntry(const char *zPath){ + ZipfileEntry *pNew; + pNew = sqlite3_malloc(sizeof(ZipfileEntry)); + if( pNew ){ + memset(pNew, 0, sizeof(ZipfileEntry)); + pNew->cds.zFile = sqlite3_mprintf("%s", zPath); + if( pNew->cds.zFile==0 ){ + sqlite3_free(pNew); + pNew = 0; + } + } + return pNew; +} + +static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ + ZipfileCDS *pCds = &pEntry->cds; + u8 *a = aBuf; + + pCds->nExtra = 9; + + /* Write the LFH itself */ + zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); + zipfileWrite16(a, pCds->iVersionExtract); + zipfileWrite16(a, pCds->flags); + zipfileWrite16(a, pCds->iCompression); + zipfileWrite16(a, pCds->mTime); + zipfileWrite16(a, pCds->mDate); + zipfileWrite32(a, pCds->crc32); + zipfileWrite32(a, pCds->szCompressed); + zipfileWrite32(a, pCds->szUncompressed); + zipfileWrite16(a, (u16)pCds->nFile); + zipfileWrite16(a, pCds->nExtra); + assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); + + /* Add the file name */ + memcpy(a, pCds->zFile, (int)pCds->nFile); + a += (int)pCds->nFile; + + /* The "extra" data */ + zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); + zipfileWrite16(a, 5); + *a++ = 0x01; + zipfileWrite32(a, pEntry->mUnixTime); + + return a-aBuf; +} + +static int zipfileAppendEntry( + ZipfileTab *pTab, + ZipfileEntry *pEntry, + const u8 *pData, + int nData +){ + u8 *aBuf = pTab->aBuffer; + int nBuf; + int rc; + + nBuf = zipfileSerializeLFH(pEntry, aBuf); + rc = zipfileAppendData(pTab, aBuf, nBuf); + if( rc==SQLITE_OK ){ + pEntry->iDataOff = pTab->szCurrent; + rc = zipfileAppendData(pTab, pData, nData); + } + + return rc; +} + +static int zipfileGetMode( + sqlite3_value *pVal, + int bIsDir, /* If true, default to directory */ + u32 *pMode, /* OUT: Mode value */ + char **pzErr /* OUT: Error message */ +){ + const char *z = (const char*)sqlite3_value_text(pVal); + u32 mode = 0; + if( z==0 ){ + mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); + }else if( z[0]>='0' && z[0]<='9' ){ + mode = (unsigned int)sqlite3_value_int(pVal); + }else{ + const char zTemplate[11] = "-rwxrwxrwx"; + int i; + if( strlen(z)!=10 ) goto parse_error; + switch( z[0] ){ + case '-': mode |= S_IFREG; break; + case 'd': mode |= S_IFDIR; break; + case 'l': mode |= S_IFLNK; break; + default: goto parse_error; + } + for(i=1; i<10; i++){ + if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); + else if( z[i]!='-' ) goto parse_error; + } + } + if( ((mode & S_IFDIR)==0)==bIsDir ){ + /* The "mode" attribute is a directory, but data has been specified. + ** Or vice-versa - no data but "mode" is a file or symlink. */ + *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); + return SQLITE_CONSTRAINT; + } + *pMode = mode; + return SQLITE_OK; + + parse_error: + *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); + return SQLITE_ERROR; +} + +/* +** Both (const char*) arguments point to nul-terminated strings. Argument +** nB is the value of strlen(zB). This function returns 0 if the strings are +** identical, ignoring any trailing '/' character in either path. */ +static int zipfileComparePath(const char *zA, const char *zB, int nB){ + int nA = (int)strlen(zA); + if( nA>0 && zA[nA-1]=='/' ) nA--; + if( nB>0 && zB[nB-1]=='/' ) nB--; + if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; + return 1; +} + +static int zipfileBegin(sqlite3_vtab *pVtab){ + ZipfileTab *pTab = (ZipfileTab*)pVtab; + int rc = SQLITE_OK; + + assert( pTab->pWriteFd==0 ); + if( pTab->zFile==0 || pTab->zFile[0]==0 ){ + pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename"); + return SQLITE_ERROR; + } + + /* Open a write fd on the file. Also load the entire central directory + ** structure into memory. During the transaction any new file data is + ** appended to the archive file, but the central directory is accumulated + ** in main-memory until the transaction is committed. */ + pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+"); + if( pTab->pWriteFd==0 ){ + pTab->base.zErrMsg = sqlite3_mprintf( + "zipfile: failed to open file %s for writing", pTab->zFile + ); + rc = SQLITE_ERROR; + }else{ + fseek(pTab->pWriteFd, 0, SEEK_END); + pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); + rc = zipfileLoadDirectory(pTab, 0, 0); + } + + if( rc!=SQLITE_OK ){ + zipfileCleanupTransaction(pTab); + } + + return rc; +} + +/* +** Return the current time as a 32-bit timestamp in UNIX epoch format (like +** time(2)). +*/ +static u32 zipfileTime(void){ + sqlite3_vfs *pVfs = sqlite3_vfs_find(0); + u32 ret; + if( pVfs==0 ) return 0; + if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ + i64 ms; + pVfs->xCurrentTimeInt64(pVfs, &ms); + ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); + }else{ + double day; + pVfs->xCurrentTime(pVfs, &day); + ret = (u32)((day - 2440587.5) * 86400); + } + return ret; +} + +/* +** Return a 32-bit timestamp in UNIX epoch format. +** +** If the value passed as the only argument is either NULL or an SQL NULL, +** return the current time. Otherwise, return the value stored in (*pVal) +** cast to a 32-bit unsigned integer. +*/ +static u32 zipfileGetTime(sqlite3_value *pVal){ + if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ + return zipfileTime(); + } + return (u32)sqlite3_value_int64(pVal); +} + +/* +** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry +** linked list. Remove it from the list and free the object. +*/ +static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ + if( pOld ){ + if( pTab->pFirstEntry==pOld ){ + pTab->pFirstEntry = pOld->pNext; + if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0; + }else{ + ZipfileEntry *p; + for(p=pTab->pFirstEntry; p; p=p->pNext){ + if( p->pNext==pOld ){ + p->pNext = pOld->pNext; + if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p; + break; + } + } + } + zipfileEntryFree(pOld); + } +} + +/* +** xUpdate method. +*/ +static int zipfileUpdate( + sqlite3_vtab *pVtab, + int nVal, + sqlite3_value **apVal, + sqlite_int64 *pRowid +){ + ZipfileTab *pTab = (ZipfileTab*)pVtab; + int rc = SQLITE_OK; /* Return Code */ + ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ + + u32 mode = 0; /* Mode for new entry */ + u32 mTime = 0; /* Modification time for new entry */ + i64 sz = 0; /* Uncompressed size */ + const char *zPath = 0; /* Path for new entry */ + int nPath = 0; /* strlen(zPath) */ + const u8 *pData = 0; /* Pointer to buffer containing content */ + int nData = 0; /* Size of pData buffer in bytes */ + int iMethod = 0; /* Compression method for new entry */ + u8 *pFree = 0; /* Free this */ + char *zFree = 0; /* Also free this */ + ZipfileEntry *pOld = 0; + ZipfileEntry *pOld2 = 0; + int bUpdate = 0; /* True for an update that modifies "name" */ + int bIsDir = 0; + u32 iCrc32 = 0; + + (void)pRowid; + + if( pTab->pWriteFd==0 ){ + rc = zipfileBegin(pVtab); + if( rc!=SQLITE_OK ) return rc; + } + + /* If this is a DELETE or UPDATE, find the archive entry to delete. */ + if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ + const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); + int nDelete = (int)strlen(zDelete); + if( nVal>1 ){ + const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); + if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ + bUpdate = 1; + } + } + for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ + if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ + break; + } + assert( pOld->pNext ); + } + } + + if( nVal>1 ){ + /* Check that "sz" and "rawdata" are both NULL: */ + if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ + zipfileTableErr(pTab, "sz must be NULL"); + rc = SQLITE_CONSTRAINT; + } + if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ + zipfileTableErr(pTab, "rawdata must be NULL"); + rc = SQLITE_CONSTRAINT; + } + + if( rc==SQLITE_OK ){ + if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ + /* data=NULL. A directory */ + bIsDir = 1; + }else{ + /* Value specified for "data", and possibly "method". This must be + ** a regular file or a symlink. */ + const u8 *aIn = sqlite3_value_blob(apVal[7]); + int nIn = sqlite3_value_bytes(apVal[7]); + int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; + + iMethod = sqlite3_value_int(apVal[8]); + sz = nIn; + pData = aIn; + nData = nIn; + if( iMethod!=0 && iMethod!=8 ){ + zipfileTableErr(pTab, "unknown compression method: %d", iMethod); + rc = SQLITE_CONSTRAINT; + }else{ + if( bAuto || iMethod ){ + int nCmp; + rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); + if( rc==SQLITE_OK ){ + if( iMethod || nCmpbase.zErrMsg); + } + + if( rc==SQLITE_OK ){ + zPath = (const char*)sqlite3_value_text(apVal[2]); + if( zPath==0 ) zPath = ""; + nPath = (int)strlen(zPath); + mTime = zipfileGetTime(apVal[4]); + } + + if( rc==SQLITE_OK && bIsDir ){ + /* For a directory, check that the last character in the path is a + ** '/'. This appears to be required for compatibility with info-zip + ** (the unzip command on unix). It does not create directories + ** otherwise. */ + if( nPath<=0 || zPath[nPath-1]!='/' ){ + zFree = sqlite3_mprintf("%s/", zPath); + zPath = (const char*)zFree; + if( zFree==0 ){ + rc = SQLITE_NOMEM; + nPath = 0; + }else{ + nPath = (int)strlen(zPath); + } + } + } + + /* Check that we're not inserting a duplicate entry -OR- updating an + ** entry with a path, thereby making it into a duplicate. */ + if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ + ZipfileEntry *p; + for(p=pTab->pFirstEntry; p; p=p->pNext){ + if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ + switch( sqlite3_vtab_on_conflict(pTab->db) ){ + case SQLITE_IGNORE: { + goto zipfile_update_done; + } + case SQLITE_REPLACE: { + pOld2 = p; + break; + } + default: { + zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); + rc = SQLITE_CONSTRAINT; + break; + } + } + break; + } + } + } + + if( rc==SQLITE_OK ){ + /* Create the new CDS record. */ + pNew = zipfileNewEntry(zPath); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; + pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; + pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; + pNew->cds.iCompression = (u16)iMethod; + zipfileMtimeToDos(&pNew->cds, mTime); + pNew->cds.crc32 = iCrc32; + pNew->cds.szCompressed = nData; + pNew->cds.szUncompressed = (u32)sz; + pNew->cds.iExternalAttr = (mode<<16); + pNew->cds.iOffset = (u32)pTab->szCurrent; + pNew->cds.nFile = (u16)nPath; + pNew->mUnixTime = (u32)mTime; + rc = zipfileAppendEntry(pTab, pNew, pData, nData); + zipfileAddEntry(pTab, pOld, pNew); + } + } + } + + if( rc==SQLITE_OK && (pOld || pOld2) ){ + ZipfileCsr *pCsr; + for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ + if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ + pCsr->pCurrent = pCsr->pCurrent->pNext; + pCsr->bNoop = 1; + } + } + + zipfileRemoveEntryFromList(pTab, pOld); + zipfileRemoveEntryFromList(pTab, pOld2); + } + +zipfile_update_done: + sqlite3_free(pFree); + sqlite3_free(zFree); + return rc; +} + +static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ + u8 *a = aBuf; + zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); + zipfileWrite16(a, p->iDisk); + zipfileWrite16(a, p->iFirstDisk); + zipfileWrite16(a, p->nEntry); + zipfileWrite16(a, p->nEntryTotal); + zipfileWrite32(a, p->nSize); + zipfileWrite32(a, p->iOffset); + zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ + + return a-aBuf; +} + +static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ + int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); + assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); + return zipfileAppendData(pTab, pTab->aBuffer, nBuf); +} + +/* +** Serialize the CDS structure into buffer aBuf[]. Return the number +** of bytes written. +*/ +static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ + u8 *a = aBuf; + ZipfileCDS *pCDS = &pEntry->cds; + + if( pEntry->aExtra==0 ){ + pCDS->nExtra = 9; + } + + zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); + zipfileWrite16(a, pCDS->iVersionMadeBy); + zipfileWrite16(a, pCDS->iVersionExtract); + zipfileWrite16(a, pCDS->flags); + zipfileWrite16(a, pCDS->iCompression); + zipfileWrite16(a, pCDS->mTime); + zipfileWrite16(a, pCDS->mDate); + zipfileWrite32(a, pCDS->crc32); + zipfileWrite32(a, pCDS->szCompressed); + zipfileWrite32(a, pCDS->szUncompressed); + assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); + zipfileWrite16(a, pCDS->nFile); + zipfileWrite16(a, pCDS->nExtra); + zipfileWrite16(a, pCDS->nComment); + zipfileWrite16(a, pCDS->iDiskStart); + zipfileWrite16(a, pCDS->iInternalAttr); + zipfileWrite32(a, pCDS->iExternalAttr); + zipfileWrite32(a, pCDS->iOffset); + + memcpy(a, pCDS->zFile, pCDS->nFile); + a += pCDS->nFile; + + if( pEntry->aExtra ){ + int n = (int)pCDS->nExtra + (int)pCDS->nComment; + memcpy(a, pEntry->aExtra, n); + a += n; + }else{ + assert( pCDS->nExtra==9 ); + zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); + zipfileWrite16(a, 5); + *a++ = 0x01; + zipfileWrite32(a, pEntry->mUnixTime); + } + + return a-aBuf; +} + +static int zipfileCommit(sqlite3_vtab *pVtab){ + ZipfileTab *pTab = (ZipfileTab*)pVtab; + int rc = SQLITE_OK; + if( pTab->pWriteFd ){ + i64 iOffset = pTab->szCurrent; + ZipfileEntry *p; + ZipfileEOCD eocd; + int nEntry = 0; + + /* Write out all entries */ + for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ + int n = zipfileSerializeCDS(p, pTab->aBuffer); + rc = zipfileAppendData(pTab, pTab->aBuffer, n); + nEntry++; + } + + /* Write out the EOCD record */ + eocd.iDisk = 0; + eocd.iFirstDisk = 0; + eocd.nEntry = (u16)nEntry; + eocd.nEntryTotal = (u16)nEntry; + eocd.nSize = (u32)(pTab->szCurrent - iOffset); + eocd.iOffset = (u32)iOffset; + rc = zipfileAppendEOCD(pTab, &eocd); + + zipfileCleanupTransaction(pTab); + } + return rc; +} + +static int zipfileRollback(sqlite3_vtab *pVtab){ + return zipfileCommit(pVtab); +} + +static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ + ZipfileCsr *pCsr; + for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ + if( iId==pCsr->iId ) break; + } + return pCsr; +} + +static void zipfileFunctionCds( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + ZipfileCsr *pCsr; + ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); + assert( argc>0 ); + + pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); + if( pCsr ){ + ZipfileCDS *p = &pCsr->pCurrent->cds; + char *zRes = sqlite3_mprintf("{" + "\"version-made-by\" : %u, " + "\"version-to-extract\" : %u, " + "\"flags\" : %u, " + "\"compression\" : %u, " + "\"time\" : %u, " + "\"date\" : %u, " + "\"crc32\" : %u, " + "\"compressed-size\" : %u, " + "\"uncompressed-size\" : %u, " + "\"file-name-length\" : %u, " + "\"extra-field-length\" : %u, " + "\"file-comment-length\" : %u, " + "\"disk-number-start\" : %u, " + "\"internal-attr\" : %u, " + "\"external-attr\" : %u, " + "\"offset\" : %u }", + (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, + (u32)p->flags, (u32)p->iCompression, + (u32)p->mTime, (u32)p->mDate, + (u32)p->crc32, (u32)p->szCompressed, + (u32)p->szUncompressed, (u32)p->nFile, + (u32)p->nExtra, (u32)p->nComment, + (u32)p->iDiskStart, (u32)p->iInternalAttr, + (u32)p->iExternalAttr, (u32)p->iOffset + ); + + if( zRes==0 ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); + sqlite3_free(zRes); + } + } +} + +/* +** xFindFunction method. +*/ +static int zipfileFindFunction( + sqlite3_vtab *pVtab, /* Virtual table handle */ + int nArg, /* Number of SQL function arguments */ + const char *zName, /* Name of SQL function */ + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ + void **ppArg /* OUT: User data for *pxFunc */ +){ + (void)nArg; + if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ + *pxFunc = zipfileFunctionCds; + *ppArg = (void*)pVtab; + return 1; + } + return 0; +} + +typedef struct ZipfileBuffer ZipfileBuffer; +struct ZipfileBuffer { + u8 *a; /* Pointer to buffer */ + int n; /* Size of buffer in bytes */ + int nAlloc; /* Byte allocated at a[] */ +}; + +typedef struct ZipfileCtx ZipfileCtx; +struct ZipfileCtx { + int nEntry; + ZipfileBuffer body; + ZipfileBuffer cds; +}; + +static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){ + if( pBuf->n+nByte>pBuf->nAlloc ){ + u8 *aNew; + sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; + int nReq = pBuf->n + nByte; + + while( nNewa, nNew); + if( aNew==0 ) return SQLITE_NOMEM; + pBuf->a = aNew; + pBuf->nAlloc = (int)nNew; + } + return SQLITE_OK; +} + +/* +** xStep() callback for the zipfile() aggregate. This can be called in +** any of the following ways: +** +** SELECT zipfile(name,data) ... +** SELECT zipfile(name,mode,mtime,data) ... +** SELECT zipfile(name,mode,mtime,data,method) ... +*/ +static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ + ZipfileCtx *p; /* Aggregate function context */ + ZipfileEntry e; /* New entry to add to zip archive */ + + sqlite3_value *pName = 0; + sqlite3_value *pMode = 0; + sqlite3_value *pMtime = 0; + sqlite3_value *pData = 0; + sqlite3_value *pMethod = 0; + + int bIsDir = 0; + u32 mode; + int rc = SQLITE_OK; + char *zErr = 0; + + int iMethod = -1; /* Compression method to use (0 or 8) */ + + const u8 *aData = 0; /* Possibly compressed data for new entry */ + int nData = 0; /* Size of aData[] in bytes */ + int szUncompressed = 0; /* Size of data before compression */ + u8 *aFree = 0; /* Free this before returning */ + u32 iCrc32 = 0; /* crc32 of uncompressed data */ + + char *zName = 0; /* Path (name) of new entry */ + int nName = 0; /* Size of zName in bytes */ + char *zFree = 0; /* Free this before returning */ + int nByte; + + memset(&e, 0, sizeof(e)); + p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); + if( p==0 ) return; + + /* Martial the arguments into stack variables */ + if( nVal!=2 && nVal!=4 && nVal!=5 ){ + zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); + rc = SQLITE_ERROR; + goto zipfile_step_out; + } + pName = apVal[0]; + if( nVal==2 ){ + pData = apVal[1]; + }else{ + pMode = apVal[1]; + pMtime = apVal[2]; + pData = apVal[3]; + if( nVal==5 ){ + pMethod = apVal[4]; + } + } + + /* Check that the 'name' parameter looks ok. */ + zName = (char*)sqlite3_value_text(pName); + nName = sqlite3_value_bytes(pName); + if( zName==0 ){ + zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); + rc = SQLITE_ERROR; + goto zipfile_step_out; + } + + /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use + ** deflate compression) or NULL (choose automatically). */ + if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ + iMethod = (int)sqlite3_value_int64(pMethod); + if( iMethod!=0 && iMethod!=8 ){ + zErr = sqlite3_mprintf("illegal method value: %d", iMethod); + rc = SQLITE_ERROR; + goto zipfile_step_out; + } + } + + /* Now inspect the data. If this is NULL, then the new entry must be a + ** directory. Otherwise, figure out whether or not the data should + ** be deflated or simply stored in the zip archive. */ + if( sqlite3_value_type(pData)==SQLITE_NULL ){ + bIsDir = 1; + iMethod = 0; + }else{ + aData = sqlite3_value_blob(pData); + szUncompressed = nData = sqlite3_value_bytes(pData); + iCrc32 = crc32(0, aData, nData); + if( iMethod<0 || iMethod==8 ){ + int nOut = 0; + rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); + if( rc!=SQLITE_OK ){ + goto zipfile_step_out; + } + if( iMethod==8 || nOut0 && zName[nName-1]=='/' ){ + zErr = sqlite3_mprintf("non-directory name must not end with /"); + rc = SQLITE_ERROR; + goto zipfile_step_out; + } + }else{ + if( nName==0 || zName[nName-1]!='/' ){ + zName = zFree = sqlite3_mprintf("%s/", zName); + if( zName==0 ){ + rc = SQLITE_NOMEM; + goto zipfile_step_out; + } + nName = (int)strlen(zName); + }else{ + while( nName>1 && zName[nName-2]=='/' ) nName--; + } + } + + /* Assemble the ZipfileEntry object for the new zip archive entry */ + e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; + e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; + e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; + e.cds.iCompression = (u16)iMethod; + zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); + e.cds.crc32 = iCrc32; + e.cds.szCompressed = nData; + e.cds.szUncompressed = szUncompressed; + e.cds.iExternalAttr = (mode<<16); + e.cds.iOffset = p->body.n; + e.cds.nFile = (u16)nName; + e.cds.zFile = zName; + + /* Append the LFH to the body of the new archive */ + nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; + if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; + p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); + + /* Append the data to the body of the new archive */ + if( nData>0 ){ + if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; + memcpy(&p->body.a[p->body.n], aData, nData); + p->body.n += nData; + } + + /* Append the CDS record to the directory of the new archive */ + nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; + if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; + p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); + + /* Increment the count of entries in the archive */ + p->nEntry++; + + zipfile_step_out: + sqlite3_free(aFree); + sqlite3_free(zFree); + if( rc ){ + if( zErr ){ + sqlite3_result_error(pCtx, zErr, -1); + }else{ + sqlite3_result_error_code(pCtx, rc); + } + } + sqlite3_free(zErr); +} + +/* +** xFinalize() callback for zipfile aggregate function. +*/ +static void zipfileFinal(sqlite3_context *pCtx){ + ZipfileCtx *p; + ZipfileEOCD eocd; + sqlite3_int64 nZip; + u8 *aZip; + + p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); + if( p==0 ) return; + if( p->nEntry>0 ){ + memset(&eocd, 0, sizeof(eocd)); + eocd.nEntry = (u16)p->nEntry; + eocd.nEntryTotal = (u16)p->nEntry; + eocd.nSize = p->cds.n; + eocd.iOffset = p->body.n; + + nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; + aZip = (u8*)sqlite3_malloc64(nZip); + if( aZip==0 ){ + sqlite3_result_error_nomem(pCtx); + }else{ + memcpy(aZip, p->body.a, p->body.n); + memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); + zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); + sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree); + } + } + + sqlite3_free(p->body.a); + sqlite3_free(p->cds.a); +} + + +/* +** Register the "zipfile" virtual table. +*/ +static int zipfileRegister(sqlite3 *db){ + static sqlite3_module zipfileModule = { + 1, /* iVersion */ + zipfileConnect, /* xCreate */ + zipfileConnect, /* xConnect */ + zipfileBestIndex, /* xBestIndex */ + zipfileDisconnect, /* xDisconnect */ + zipfileDisconnect, /* xDestroy */ + zipfileOpen, /* xOpen - open a cursor */ + zipfileClose, /* xClose - close a cursor */ + zipfileFilter, /* xFilter - configure scan constraints */ + zipfileNext, /* xNext - advance a cursor */ + zipfileEof, /* xEof - check for end of scan */ + zipfileColumn, /* xColumn - read data */ + 0, /* xRowid - read data */ + zipfileUpdate, /* xUpdate */ + zipfileBegin, /* xBegin */ + 0, /* xSync */ + zipfileCommit, /* xCommit */ + zipfileRollback, /* xRollback */ + zipfileFindFunction, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollback */ + 0, /* xShadowName */ + 0 /* xIntegrity */ + }; + + int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); + if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, + zipfileStep, zipfileFinal + ); + } + assert( sizeof(i64)==8 ); + assert( sizeof(u32)==4 ); + assert( sizeof(u16)==2 ); + assert( sizeof(u8)==1 ); + return rc; +} +#else /* SQLITE_OMIT_VIRTUALTABLE */ +# define zipfileRegister(x) SQLITE_OK +#endif + +#ifndef SQLITE_API +#define SQLITE_API +#endif +SQLITE_API +int sqlite3_zipfile_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused parameter */ + return zipfileRegister(db); +} +/*** End of #include "zipfile.c" ***/ + +#endif + +/* +** Multi cipher VFS +*/ +/* #include "sqlite3mc_vfs.c" */ +/*** Begin of #include "sqlite3mc_vfs.c" ***/ +/* +** Name: sqlite3mc_vfs.c +** Purpose: Implementation of SQLite VFS for Multiple Ciphers +** Author: Ulrich Telle +** Created: 2020-02-28 +** Copyright: (c) 2020-2023 Ulrich Telle +** License: MIT +*/ + +/* #include "sqlite3mc_vfs.h" */ + +/* #include "sqlite3.h" */ + +#include +#include +#include +/* #include "mystdint.h" */ + + +/* +** Type definitions +*/ + +typedef struct sqlite3mc_file sqlite3mc_file; +typedef struct sqlite3mc_vfs sqlite3mc_vfs; + +/* +** SQLite3 Multiple Ciphers file structure +*/ + +struct sqlite3mc_file +{ + sqlite3_file base; /* sqlite3_file I/O methods */ + sqlite3_file* pFile; /* Real underlying OS file */ + sqlite3mc_vfs* pVfsMC; /* Pointer to the sqlite3mc_vfs object */ + const char* zFileName; /* File name */ + int openFlags; /* Open flags */ + sqlite3mc_file* pMainNext; /* Next main db file */ + sqlite3mc_file* pMainDb; /* Main database to which this one is attached */ + Codec* codec; /* Codec if encrypted */ + int pageNo; /* Page number (in case of journal files) */ +}; + +/* +** SQLite3 Multiple Ciphers VFS structure +*/ + +struct sqlite3mc_vfs +{ + sqlite3_vfs base; /* Multiple Ciphers VFS shim methods */ + sqlite3_mutex* mutex; /* Mutex to protect pMain */ + sqlite3mc_file* pMain; /* List of main database files */ +}; + +#define REALVFS(p) ((sqlite3_vfs*)(((sqlite3mc_vfs*)(p))->base.pAppData)) +#define REALFILE(p) (((sqlite3mc_file*)(p))->pFile) + +/* +** Prototypes for VFS methods +*/ + +static int mcVfsOpen(sqlite3_vfs* pVfs, const char* zName, sqlite3_file* pFile, int flags, int* pOutFlags); +static int mcVfsDelete(sqlite3_vfs* pVfs, const char* zName, int syncDir); +static int mcVfsAccess(sqlite3_vfs* pVfs, const char* zName, int flags, int* pResOut); +static int mcVfsFullPathname(sqlite3_vfs* pVfs, const char* zName, int nOut, char* zOut); +static void* mcVfsDlOpen(sqlite3_vfs* pVfs, const char* zFilename); +static void mcVfsDlError(sqlite3_vfs* pVfs, int nByte, char* zErrMsg); +static void (*mcVfsDlSym(sqlite3_vfs* pVfs, void* p, const char* zSymbol))(void); +static void mcVfsDlClose(sqlite3_vfs* pVfs, void* p); +static int mcVfsRandomness(sqlite3_vfs* pVfs, int nByte, char* zOut); +static int mcVfsSleep(sqlite3_vfs* pVfs, int microseconds); +static int mcVfsCurrentTime(sqlite3_vfs* pVfs, double* pOut); +static int mcVfsGetLastError(sqlite3_vfs* pVfs, int nErr, char* zOut); +static int mcVfsCurrentTimeInt64(sqlite3_vfs* pVfs, sqlite3_int64* pOut); +static int mcVfsSetSystemCall(sqlite3_vfs* pVfs, const char* zName, sqlite3_syscall_ptr pNewFunc); +static sqlite3_syscall_ptr mcVfsGetSystemCall(sqlite3_vfs* pVfs, const char* zName); +static const char* mcVfsNextSystemCall(sqlite3_vfs* pVfs, const char* zName); + +/* +** Prototypes for IO methods +*/ + +static int mcIoClose(sqlite3_file* pFile); +static int mcIoRead(sqlite3_file* pFile, void*, int iAmt, sqlite3_int64 iOfst); +static int mcIoWrite(sqlite3_file* pFile,const void*,int iAmt, sqlite3_int64 iOfst); +static int mcIoTruncate(sqlite3_file* pFile, sqlite3_int64 size); +static int mcIoSync(sqlite3_file* pFile, int flags); +static int mcIoFileSize(sqlite3_file* pFile, sqlite3_int64* pSize); +static int mcIoLock(sqlite3_file* pFile, int lock); +static int mcIoUnlock(sqlite3_file* pFile, int lock); +static int mcIoCheckReservedLock(sqlite3_file* pFile, int *pResOut); +static int mcIoFileControl(sqlite3_file* pFile, int op, void *pArg); +static int mcIoSectorSize(sqlite3_file* pFile); +static int mcIoDeviceCharacteristics(sqlite3_file* pFile); +static int mcIoShmMap(sqlite3_file* pFile, int iPg, int pgsz, int map, void volatile** p); +static int mcIoShmLock(sqlite3_file* pFile, int offset, int n, int flags); +static void mcIoShmBarrier(sqlite3_file* pFile); +static int mcIoShmUnmap(sqlite3_file* pFile, int deleteFlag); +static int mcIoFetch(sqlite3_file* pFile, sqlite3_int64 iOfst, int iAmt, void** pp); +static int mcIoUnfetch(sqlite3_file* pFile, sqlite3_int64 iOfst, void* p); + +#define SQLITE3MC_VFS_NAME ("multipleciphers") + +#define SQLITE3MC_FCNTL_PVFS 0x3f98c078 + +/* +** Header sizes of WAL journal files +*/ +static const int walFrameHeaderSize = 24; +static const int walFileHeaderSize = 32; + +/* +** Global I/O method structure of SQLite3 Multiple Ciphers VFS +*/ + +#define IOMETHODS_VERSION_MIN 1 +#define IOMETHODS_VERSION_MAX 3 + +static sqlite3_io_methods mcIoMethodsGlobal1 = +{ + 1, /* iVersion */ + mcIoClose, /* xClose */ + mcIoRead, /* xRead */ + mcIoWrite, /* xWrite */ + mcIoTruncate, /* xTruncate */ + mcIoSync, /* xSync */ + mcIoFileSize, /* xFileSize */ + mcIoLock, /* xLock */ + mcIoUnlock, /* xUnlock */ + mcIoCheckReservedLock, /* xCheckReservedLock */ + mcIoFileControl, /* xFileControl */ + mcIoSectorSize, /* xSectorSize */ + mcIoDeviceCharacteristics, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0, /* xShmUnmap */ + 0, /* xFetch */ + 0, /* xUnfetch */ +}; + +static sqlite3_io_methods mcIoMethodsGlobal2 = +{ + 2, /* iVersion */ + mcIoClose, /* xClose */ + mcIoRead, /* xRead */ + mcIoWrite, /* xWrite */ + mcIoTruncate, /* xTruncate */ + mcIoSync, /* xSync */ + mcIoFileSize, /* xFileSize */ + mcIoLock, /* xLock */ + mcIoUnlock, /* xUnlock */ + mcIoCheckReservedLock, /* xCheckReservedLock */ + mcIoFileControl, /* xFileControl */ + mcIoSectorSize, /* xSectorSize */ + mcIoDeviceCharacteristics, /* xDeviceCharacteristics */ + mcIoShmMap, /* xShmMap */ + mcIoShmLock, /* xShmLock */ + mcIoShmBarrier, /* xShmBarrier */ + mcIoShmUnmap, /* xShmUnmap */ + 0, /* xFetch */ + 0, /* xUnfetch */ +}; + +static sqlite3_io_methods mcIoMethodsGlobal3 = +{ + 3, /* iVersion */ + mcIoClose, /* xClose */ + mcIoRead, /* xRead */ + mcIoWrite, /* xWrite */ + mcIoTruncate, /* xTruncate */ + mcIoSync, /* xSync */ + mcIoFileSize, /* xFileSize */ + mcIoLock, /* xLock */ + mcIoUnlock, /* xUnlock */ + mcIoCheckReservedLock, /* xCheckReservedLock */ + mcIoFileControl, /* xFileControl */ + mcIoSectorSize, /* xSectorSize */ + mcIoDeviceCharacteristics, /* xDeviceCharacteristics */ + mcIoShmMap, /* xShmMap */ + mcIoShmLock, /* xShmLock */ + mcIoShmBarrier, /* xShmBarrier */ + mcIoShmUnmap, /* xShmUnmap */ + mcIoFetch, /* xFetch */ + mcIoUnfetch, /* xUnfetch */ +}; + +static sqlite3_io_methods* mcIoMethodsGlobal[] = + { 0, &mcIoMethodsGlobal1 , &mcIoMethodsGlobal2 , &mcIoMethodsGlobal3 }; + +/* +** Internal functions +*/ + +/* +** Add an item to the list of main database files, if it is not already present. +*/ +static void mcMainListAdd(sqlite3mc_file* pFile) +{ + assert( (pFile->openFlags & SQLITE_OPEN_MAIN_DB) ); + sqlite3_mutex_enter(pFile->pVfsMC->mutex); + pFile->pMainNext = pFile->pVfsMC->pMain; + pFile->pVfsMC->pMain = pFile; + sqlite3_mutex_leave(pFile->pVfsMC->mutex); +} + +/* +** Remove an item from the list of main database files. +*/ +static void mcMainListRemove(sqlite3mc_file* pFile) +{ + sqlite3mc_file** pMainPrev; + sqlite3_mutex_enter(pFile->pVfsMC->mutex); + for (pMainPrev = &pFile->pVfsMC->pMain; *pMainPrev && *pMainPrev != pFile; pMainPrev = &((*pMainPrev)->pMainNext)){} + if (*pMainPrev) *pMainPrev = pFile->pMainNext; + pFile->pMainNext = 0; + sqlite3_mutex_leave(pFile->pVfsMC->mutex); +} + +/* +** Given that zFileName points to a buffer containing a database file name passed to +** either the xOpen() or xAccess() VFS method, search the list of main database files +** for a file handle opened by the same database connection on the corresponding +** database file. +*/ +static sqlite3mc_file* mcFindDbMainFileName(sqlite3mc_vfs* mcVfs, const char* zFileName) +{ + sqlite3mc_file* pDb; + sqlite3_mutex_enter(mcVfs->mutex); + for (pDb = mcVfs->pMain; pDb && pDb->zFileName != zFileName; pDb = pDb->pMainNext){} + sqlite3_mutex_leave(mcVfs->mutex); + return pDb; +} + +/* +** Find a pointer to the Multiple Ciphers VFS in use for a database connection. +*/ +static sqlite3mc_vfs* mcFindVfs(sqlite3* db, const char* zDbName) +{ + sqlite3mc_vfs* pVfsMC = NULL; + if (db->pVfs && db->pVfs->xOpen == mcVfsOpen) + { + /* The top level VFS is a Multiple Ciphers VFS */ + pVfsMC = (sqlite3mc_vfs*)(db->pVfs); + } + else + { + /* + ** The top level VFS is not a Multiple Ciphers VFS. + ** Retrieve the Multiple Ciphers VFS via file control function, + ** if it is included in the VFS stack. + */ + sqlite3mc_vfs* pVfs = NULL; + if ((sqlite3_file_control(db, zDbName, SQLITE3MC_FCNTL_PVFS, &pVfs) == SQLITE_OK) && + (pVfs && pVfs->base.xOpen == mcVfsOpen)) + { + pVfsMC = pVfs; + } + } + return pVfsMC; +} + +/* +** Check whether the VFS of the database file corresponding +** to the database schema name supports encryption. +*/ +SQLITE_PRIVATE int sqlite3mcIsEncryptionSupported(sqlite3* db, const char* zDbName) +{ + sqlite3mc_vfs* pVfsMC = mcFindVfs(db, zDbName); + return (pVfsMC != NULL); +} + +/* +** Find the codec of the database file +** corresponding to the database schema name. +*/ +SQLITE_PRIVATE Codec* sqlite3mcGetCodec(sqlite3* db, const char* zDbName) +{ + Codec* codec = NULL; + sqlite3mc_vfs* pVfsMC = mcFindVfs(db, zDbName); + + if (pVfsMC) + { + const char* dbFileName = sqlite3_db_filename(db, zDbName); + sqlite3mc_file* pDbMain = mcFindDbMainFileName(pVfsMC, dbFileName); + if (pDbMain) + { + codec = pDbMain->codec; + } + } + return codec; +} + +/* +** Find the codec of the main database file. +*/ +SQLITE_PRIVATE Codec* sqlite3mcGetMainCodec(sqlite3* db) +{ + return sqlite3mcGetCodec(db, "main"); +} + +SQLITE_PRIVATE int sqlite3mcIsBackupSupported(sqlite3* pSrc, const char* zSrc, sqlite3* pDest, const char* zDest) +{ + int ok = 1; + if (pSrc != pDest) + { + Codec* codecSrc = sqlite3mcGetCodec(pSrc, zSrc); + Codec* codecDest = sqlite3mcGetCodec(pDest, zDest); + if (codecSrc && codecDest) + { + /* Both databases have a codec, are encrypted, and have the same page size */ + ok = sqlite3mcIsEncrypted(codecSrc) && sqlite3mcIsEncrypted(codecDest) && + (sqlite3mcGetPageSizeReadCipher(codecSrc) == sqlite3mcGetPageSizeWriteCipher(codecDest)) && + (sqlite3mcGetReadReserved(codecSrc) == sqlite3mcGetWriteReserved(codecDest)); + } + else + { + /* At least one database has no codec */ + /* Backup supported if both databases are plain databases */ + ok = !codecSrc && !codecDest; + } + } + return ok; +} + +/* +** Set the codec of the database file with the given database file name. +** +** The parameter db, the handle of the database connection, is currently +** not used to determine the database file handle, for which the codec +** should be set. The reason is that for shared cache mode the database +** connection handle is not unique, and it is not even clear which +** connection handle is actually valid, because the association between +** connection handles and database file handles is not maintained properly. +*/ +SQLITE_PRIVATE void sqlite3mcSetCodec(sqlite3* db, const char* zDbName, const char* zFileName, Codec* codec) +{ + sqlite3mc_file* pDbMain = NULL; + sqlite3mc_vfs* pVfsMC = mcFindVfs(db, zDbName); + if (pVfsMC) + { + pDbMain = mcFindDbMainFileName(pVfsMC, zFileName); + } + if (pDbMain) + { + Codec* prevCodec = pDbMain->codec; + Codec* msgCodec = (codec) ? codec : prevCodec; + pDbMain->codec = codec; + if (msgCodec) + { + /* Reset error state of pager */ + mcReportCodecError(sqlite3mcGetBtShared(msgCodec), SQLITE_OK); + } + if (prevCodec) + { + /* + ** Free a codec that was already associated with this main database file handle + */ + sqlite3mcCodecFree(prevCodec); + } + } + else + { + /* + ** No main database file handle found, free codec + */ + sqlite3mcCodecFree(codec); + } +} + +/* +** This function is called by the wal module when writing page content +** into the log file. +** +** This function returns a pointer to a buffer containing the encrypted +** page content. If a malloc fails, this function may return NULL. +*/ +SQLITE_PRIVATE void* sqlite3mcPagerCodec(PgHdrMC* pPg) +{ + sqlite3_file* pFile = sqlite3PagerFile(pPg->pPager); + void* aData = 0; + if (pFile->pMethods == &mcIoMethodsGlobal1 || + pFile->pMethods == &mcIoMethodsGlobal2 || + pFile->pMethods == &mcIoMethodsGlobal3) + { + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + Codec* codec = mcFile->codec; + if (codec != 0 && codec->m_walLegacy == 0 && sqlite3mcIsEncrypted(codec)) + { + aData = sqlite3mcCodec(codec, pPg->pData, pPg->pgno, 6); + } + else + { + aData = (char*) pPg->pData; + } + } + else + { + aData = (char*) pPg->pData; + } + return aData; +} + +/* +** Implementation of VFS methods +*/ + +static int mcVfsOpen(sqlite3_vfs* pVfs, const char* zName, sqlite3_file* pFile, int flags, int* pOutFlags) +{ + int rc; + sqlite3mc_vfs* mcVfs = (sqlite3mc_vfs*) pVfs; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + mcFile->pFile = (sqlite3_file*) &mcFile[1]; + mcFile->pVfsMC = mcVfs; + mcFile->openFlags = flags; + mcFile->zFileName = zName; + mcFile->codec = 0; + mcFile->pMainDb = 0; + mcFile->pMainNext = 0; + mcFile->pageNo = 0; + + if (zName) + { + if (flags & SQLITE_OPEN_MAIN_DB) + { + mcFile->zFileName = zName; + SQLITE3MC_DEBUG_LOG("mcVfsOpen MAIN: mcFile=%p fileName=%s\n", mcFile, mcFile->zFileName); + } + else if (flags & SQLITE_OPEN_TEMP_DB) + { + mcFile->zFileName = zName; + SQLITE3MC_DEBUG_LOG("mcVfsOpen TEMP: mcFile=%p fileName=%s\n", mcFile, mcFile->zFileName); + } +#if 0 + else if (flags & SQLITE_OPEN_TRANSIENT_DB) + { + /* + ** TODO: When does SQLite open a transient DB? Could/Should it be encrypted? + */ + } +#endif + else if (flags & SQLITE_OPEN_MAIN_JOURNAL) + { + const char* dbFileName = sqlite3_filename_database(zName); + mcFile->pMainDb = mcFindDbMainFileName(mcFile->pVfsMC, dbFileName); + mcFile->zFileName = zName; + SQLITE3MC_DEBUG_LOG("mcVfsOpen MAIN Journal: mcFile=%p fileName=%s dbFileName=%s\n", mcFile, mcFile->zFileName, dbFileName); + } +#if 0 + else if (flags & SQLITE_OPEN_TEMP_JOURNAL) + { + /* + ** TODO: When does SQLite open a temporary journal? Could/Should it be encrypted? + */ + } +#endif + else if (flags & SQLITE_OPEN_SUBJOURNAL) + { + const char* dbFileName = sqlite3_filename_database(zName); + mcFile->pMainDb = mcFindDbMainFileName(mcFile->pVfsMC, dbFileName); + mcFile->zFileName = zName; + SQLITE3MC_DEBUG_LOG("mcVfsOpen SUB Journal: mcFile=%p fileName=%s dbFileName=%s\n", mcFile, mcFile->zFileName, dbFileName); + } +#if 0 + else if (flags & SQLITE_OPEN_MASTER_JOURNAL) + { + /* + ** Master journal contains only administrative information + ** No encryption necessary + */ + } +#endif + else if (flags & SQLITE_OPEN_WAL) + { + const char* dbFileName = sqlite3_filename_database(zName); + mcFile->pMainDb = mcFindDbMainFileName(mcFile->pVfsMC, dbFileName); + mcFile->zFileName = zName; + SQLITE3MC_DEBUG_LOG("mcVfsOpen WAL Journal: mcFile=%p fileName=%s dbFileName=%s\n", mcFile, mcFile->zFileName, dbFileName); + } + } + + rc = REALVFS(pVfs)->xOpen(REALVFS(pVfs), zName, mcFile->pFile, flags, pOutFlags); + if (rc == SQLITE_OK) + { + /* + ** Real open succeeded + ** Initialize methods (use same version number as underlying implementation + ** Register main database files + */ + int ioMethodsVersion = mcFile->pFile->pMethods->iVersion; + if (ioMethodsVersion < IOMETHODS_VERSION_MIN || + ioMethodsVersion > IOMETHODS_VERSION_MAX) + { + /* If version out of range, use highest known version */ + ioMethodsVersion = IOMETHODS_VERSION_MAX; + } + pFile->pMethods = mcIoMethodsGlobal[ioMethodsVersion]; + if (flags & SQLITE_OPEN_MAIN_DB) + { + mcMainListAdd(mcFile); + } + } + return rc; +} + +static int mcVfsDelete(sqlite3_vfs* pVfs, const char* zName, int syncDir) +{ + return REALVFS(pVfs)->xDelete(REALVFS(pVfs), zName, syncDir); +} + +static int mcVfsAccess(sqlite3_vfs* pVfs, const char* zName, int flags, int* pResOut) +{ + return REALVFS(pVfs)->xAccess(REALVFS(pVfs), zName, flags, pResOut); +} + +static int mcVfsFullPathname(sqlite3_vfs* pVfs, const char* zName, int nOut, char* zOut) +{ + return REALVFS(pVfs)->xFullPathname(REALVFS(pVfs), zName, nOut, zOut); +} + +static void* mcVfsDlOpen(sqlite3_vfs* pVfs, const char* zFilename) +{ + return REALVFS(pVfs)->xDlOpen(REALVFS(pVfs), zFilename); +} + +static void mcVfsDlError(sqlite3_vfs* pVfs, int nByte, char* zErrMsg) +{ + REALVFS(pVfs)->xDlError(REALVFS(pVfs), nByte, zErrMsg); +} + +static void (*mcVfsDlSym(sqlite3_vfs* pVfs, void* p, const char* zSymbol))(void) +{ + return REALVFS(pVfs)->xDlSym(REALVFS(pVfs), p, zSymbol); +} + +static void mcVfsDlClose(sqlite3_vfs* pVfs, void* p) +{ + REALVFS(pVfs)->xDlClose(REALVFS(pVfs), p); +} + +static int mcVfsRandomness(sqlite3_vfs* pVfs, int nByte, char* zOut) +{ + return REALVFS(pVfs)->xRandomness(REALVFS(pVfs), nByte, zOut); +} + +static int mcVfsSleep(sqlite3_vfs* pVfs, int microseconds) +{ + return REALVFS(pVfs)->xSleep(REALVFS(pVfs), microseconds); +} + +static int mcVfsCurrentTime(sqlite3_vfs* pVfs, double* pOut) +{ + return REALVFS(pVfs)->xCurrentTime(REALVFS(pVfs), pOut); +} + +static int mcVfsGetLastError(sqlite3_vfs* pVfs, int code, char* pOut) +{ + return REALVFS(pVfs)->xGetLastError(REALVFS(pVfs), code, pOut); +} + +static int mcVfsCurrentTimeInt64(sqlite3_vfs* pVfs, sqlite3_int64* pOut) +{ + return REALVFS(pVfs)->xCurrentTimeInt64(REALVFS(pVfs), pOut); +} + +static int mcVfsSetSystemCall(sqlite3_vfs* pVfs, const char* zName, sqlite3_syscall_ptr pNewFunc) +{ + return REALVFS(pVfs)->xSetSystemCall(REALVFS(pVfs), zName, pNewFunc); +} + +static sqlite3_syscall_ptr mcVfsGetSystemCall(sqlite3_vfs* pVfs, const char* zName) +{ + return REALVFS(pVfs)->xGetSystemCall(REALVFS(pVfs), zName); +} + +static const char* mcVfsNextSystemCall(sqlite3_vfs* pVfs, const char* zName) +{ + return REALVFS(pVfs)->xNextSystemCall(REALVFS(pVfs), zName); +} + +/* +** IO methods +*/ + +static int mcIoClose(sqlite3_file* pFile) +{ + int rc; + sqlite3mc_file* p = (sqlite3mc_file*) pFile; + + /* + ** Unregister main database files + */ + if (p->openFlags & SQLITE_OPEN_MAIN_DB) + { + mcMainListRemove(p); + } + + /* + ** Release codec memory + */ + if (p->codec) + { + sqlite3mcCodecFree(p->codec); + p->codec = 0; + } + + assert(p->pMainNext == 0 && p->pVfsMC->pMain != p); + rc = REALFILE(pFile)->pMethods->xClose(REALFILE(pFile)); + return rc; +} + +/* +** Read operation on main database file +*/ +static int mcReadMainDb(sqlite3_file* pFile, void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + + /* + ** Special case: read 16 bytes salt from beginning of database file without decrypting + */ + if (offset == 0 && count == 16) + { + return rc; + } + + if (mcFile->codec != 0 && sqlite3mcIsEncrypted(mcFile->codec)) + { + const int pageSize = sqlite3mcGetPageSize(mcFile->codec); + const int deltaOffset = offset % pageSize; + const int deltaCount = count % pageSize; + if (deltaOffset || deltaCount) + { + /* + ** Read partial page + */ + int pageNo = 0; + void* bufferDecrypted = 0; + const sqlite3_int64 prevOffset = offset - deltaOffset; + unsigned char* pageBuffer = sqlite3mcGetPageBuffer(mcFile->codec); + + /* + ** Read complete page from file + */ + rc = REALFILE(pFile)->pMethods->xRead(REALFILE(pFile), pageBuffer, pageSize, prevOffset); + if (rc == SQLITE_IOERR_SHORT_READ) + { + return rc; + } + + /* + ** Determine page number and decrypt page buffer + */ + pageNo = prevOffset / pageSize + 1; + bufferDecrypted = sqlite3mcCodec(mcFile->codec, pageBuffer, pageNo, 3); + rc = sqlite3mcGetCodecLastError(mcFile->codec); + + /* + ** Return the requested content + */ + if (deltaOffset) + { + memcpy(buffer, pageBuffer + deltaOffset, count); + } + else + { + memcpy(buffer, pageBuffer, count); + } + } + else + { + /* + ** Read full page(s) + ** + ** In fact, SQLite reads only one database page at a time. + ** This would allow to remove the page loop below. + */ + unsigned char* data = (unsigned char*) buffer; + int pageNo = offset / pageSize + 1; + int nPages = count / pageSize; + int iPage; + for (iPage = 0; iPage < nPages; ++iPage) + { + void* bufferDecrypted = sqlite3mcCodec(mcFile->codec, data, pageNo, 3); + rc = sqlite3mcGetCodecLastError(mcFile->codec); + data += pageSize; + offset += pageSize; + ++pageNo; + } + } + } + return rc; +} + +/* +** Read operation on main journal file +*/ +static int mcReadMainJournal(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + Codec* codec = (mcFile->pMainDb) ? mcFile->pMainDb->codec : 0; + + if (codec != 0 && sqlite3mcIsEncrypted(codec)) + { + const int pageSize = sqlite3mcGetPageSize(codec); + + if (count == pageSize && mcFile->pageNo != 0) + { + /* + ** Decrypt the page buffer, but only if the page number is valid + */ + void* bufferDecrypted = sqlite3mcCodec(codec, (char*) buffer, mcFile->pageNo, 3); + rc = sqlite3mcGetCodecLastError(codec); + mcFile->pageNo = 0; + } + else if (count == 4) + { + /* + ** SQLite always reads the page number from the journal file + ** immediately before the corresponding page content is read. + */ + mcFile->pageNo = sqlite3Get4byte(buffer); + } + } + return rc; +} + +/* +** Read operation on subjournal file +*/ +static int mcReadSubJournal(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + Codec* codec = (mcFile->pMainDb) ? mcFile->pMainDb->codec : 0; + + if (codec != 0 && sqlite3mcIsEncrypted(codec)) + { + const int pageSize = sqlite3mcGetPageSize(codec); + + if (count == pageSize && mcFile->pageNo != 0) + { + /* + ** Decrypt the page buffer, but only if the page number is valid + */ + void* bufferDecrypted = sqlite3mcCodec(codec, (char*) buffer, mcFile->pageNo, 3); + rc = sqlite3mcGetCodecLastError(codec); + } + else if (count == 4) + { + /* + ** SQLite always reads the page number from the journal file + ** immediately before the corresponding page content is read. + */ + mcFile->pageNo = sqlite3Get4byte(buffer); + } + } + return rc; +} + +/* +** Read operation on WAL journal file +*/ +static int mcReadWal(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + Codec* codec = (mcFile->pMainDb) ? mcFile->pMainDb->codec : 0; + + if (codec != 0 && sqlite3mcIsEncrypted(codec)) + { + const int pageSize = sqlite3mcGetPageSize(codec); + + if (count == pageSize) + { + int pageNo = 0; + unsigned char ac[4]; + + /* + ** Determine page number + ** + ** It is necessary to explicitly read the page number from the frame header. + */ + rc = REALFILE(pFile)->pMethods->xRead(REALFILE(pFile), ac, 4, offset - walFrameHeaderSize); + if (rc == SQLITE_OK) + { + pageNo = sqlite3Get4byte(ac); + } + + /* + ** Decrypt page content if page number is valid + */ + if (pageNo != 0) + { + void* bufferDecrypted = sqlite3mcCodec(codec, (char*)buffer, pageNo, 3); + rc = sqlite3mcGetCodecLastError(codec); + } + } + else if (codec->m_walLegacy != 0 && count == pageSize + walFrameHeaderSize) + { + int pageNo = sqlite3Get4byte(buffer); + + /* + ** Decrypt page content if page number is valid + */ + if (pageNo != 0) + { + void* bufferDecrypted = sqlite3mcCodec(codec, (char*)buffer+walFrameHeaderSize, pageNo, 3); + rc = sqlite3mcGetCodecLastError(codec); + } + } + } + return rc; +} + +static int mcIoRead(sqlite3_file* pFile, void* buffer, int count, sqlite3_int64 offset) +{ + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + int rc = REALFILE(pFile)->pMethods->xRead(REALFILE(pFile), buffer, count, offset); + if (rc == SQLITE_IOERR_SHORT_READ) + { + return rc; + } + + if (mcFile->openFlags & SQLITE_OPEN_MAIN_DB) + { + rc = mcReadMainDb(pFile, buffer, count, offset); + } +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_TEMP_DB) + { + /* + ** TODO: Could/Should a temporary database file be encrypted? + */ + } +#endif +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_TRANSIENT_DB) + { + /* + ** TODO: Could/Should a transient database file be encrypted? + */ + } +#endif + else if (mcFile->openFlags & SQLITE_OPEN_MAIN_JOURNAL) + { + rc = mcReadMainJournal(pFile, buffer, count, offset); + } +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_TEMP_JOURNAL) + { + /* + ** TODO: Could/Should a temporary journal file be encrypted? + */ + } +#endif + else if (mcFile->openFlags & SQLITE_OPEN_SUBJOURNAL) + { + rc = mcReadSubJournal(pFile, buffer, count, offset); + } +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_MASTER_JOURNAL) + { + /* + ** Master journal contains only administrative information + ** No encryption necessary + */ + } +#endif + else if (mcFile->openFlags & SQLITE_OPEN_WAL) + { + rc = mcReadWal(pFile, buffer, count, offset); + } + return rc; +} + +/* +** Write operation on main database file +*/ +static int mcWriteMainDb(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + + if (mcFile->codec != 0 && sqlite3mcIsEncrypted(mcFile->codec)) + { + const int pageSize = sqlite3mcGetPageSize(mcFile->codec); + const int deltaOffset = offset % pageSize; + const int deltaCount = count % pageSize; + + if (deltaOffset || deltaCount) + { + /* + ** Write partial page + ** + ** SQLite does never write partial database pages. + ** Therefore no encryption is required in this case. + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + else + { + /* + ** Write full page(s) + ** + ** In fact, SQLite writes only one database page at a time. + ** This would allow to remove the page loop below. + */ + char* data = (char*) buffer; + int pageNo = offset / pageSize + 1; + int nPages = count / pageSize; + int iPage; + for (iPage = 0; iPage < nPages; ++iPage) + { + void* bufferEncrypted = sqlite3mcCodec(mcFile->codec, data, pageNo, 6); + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), bufferEncrypted, pageSize, offset); + data += pageSize; + offset += pageSize; + ++pageNo; + } + } + } + else + { + /* + ** Write buffer without encryption + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + return rc; +} + +/* +** Write operation on main journal file +*/ +static int mcWriteMainJournal(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + Codec* codec = (mcFile->pMainDb) ? mcFile->pMainDb->codec : 0; + + if (codec != 0 && sqlite3mcIsEncrypted(codec)) + { + const int pageSize = sqlite3mcGetPageSize(codec); + const int frameSize = pageSize + 4 + 4; + + if (count == pageSize && mcFile->pageNo != 0) + { + /* + ** Encrypt the page buffer, but only if the page number is valid + */ + void* bufferEncrypted = sqlite3mcCodec(codec, (char*) buffer, mcFile->pageNo, 7); + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), bufferEncrypted, pageSize, offset); + } + else + { + /* + ** Write buffer without encryption + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + if (count == 4) + { + /* + ** SQLite always writes the page number to the journal file + ** immediately before the corresponding page content is written. + */ + mcFile->pageNo = (rc == SQLITE_OK) ? sqlite3Get4byte(buffer) : 0; + } + } + } + else + { + /* + ** Write buffer without encryption + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + return rc; +} + +/* +** Write operation on subjournal file +*/ +static int mcWriteSubJournal(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + Codec* codec = (mcFile->pMainDb) ? mcFile->pMainDb->codec : 0; + + if (codec != 0 && sqlite3mcIsEncrypted(codec)) + { + const int pageSize = sqlite3mcGetPageSize(codec); + const int frameSize = pageSize + 4; + + if (count == pageSize && mcFile->pageNo != 0) + { + /* + ** Encrypt the page buffer, but only if the page number is valid + */ + void* bufferEncrypted = sqlite3mcCodec(codec, (char*) buffer, mcFile->pageNo, 7); + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), bufferEncrypted, pageSize, offset); + } + else + { + /* + ** Write buffer without encryption + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + if (count == 4) + { + /* + ** SQLite always writes the page number to the journal file + ** immediately before the corresponding page content is written. + */ + mcFile->pageNo = (rc == SQLITE_OK) ? sqlite3Get4byte(buffer) : 0; + } + } + } + else + { + /* + ** Write buffer without encryption + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + return rc; +} + +/* +** Write operation on WAL journal file +*/ +static int mcWriteWal(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + Codec* codec = (mcFile->pMainDb) ? mcFile->pMainDb->codec : 0; + + if (codec != 0 && codec->m_walLegacy != 0 && sqlite3mcIsEncrypted(codec)) + { + const int pageSize = sqlite3mcGetPageSize(codec); + + if (count == pageSize) + { + int pageNo = 0; + unsigned char ac[4]; + + /* + ** Read the corresponding page number from the file + ** + ** In WAL mode SQLite does not write the page number of a page to file + ** immediately before writing the corresponding page content. + ** Page numbers and checksums are written to file independently. + ** Therefore it is necessary to explicitly read the page number + ** on writing to file the content of a page. + */ + rc = REALFILE(pFile)->pMethods->xRead(REALFILE(pFile), ac, 4, offset - walFrameHeaderSize); + if (rc == SQLITE_OK) + { + pageNo = sqlite3Get4byte(ac); + } + + if (pageNo != 0) + { + /* + ** Encrypt the page buffer, but only if the page number is valid + */ + void* bufferEncrypted = sqlite3mcCodec(codec, (char*) buffer, pageNo, 7); + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), bufferEncrypted, pageSize, offset); + } + else + { + /* + ** Write buffer without encryption if the page number could not be determined + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + } + else if (count == pageSize + walFrameHeaderSize) + { + int pageNo = sqlite3Get4byte(buffer); + if (pageNo != 0) + { + /* + ** Encrypt the page buffer, but only if the page number is valid + */ + void* bufferEncrypted = sqlite3mcCodec(codec, (char*)buffer+walFrameHeaderSize, pageNo, 7); + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, walFrameHeaderSize, offset); + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), bufferEncrypted, pageSize, offset+walFrameHeaderSize); + } + else + { + /* + ** Write buffer without encryption if the page number could not be determined + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + } + else + { + /* + ** Write buffer without encryption if it is not a database page + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + } + else + { + /* + ** Write buffer without encryption + */ + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + return rc; +} + +static int mcIoWrite(sqlite3_file* pFile, const void* buffer, int count, sqlite3_int64 offset) +{ + int rc = SQLITE_OK; + int doDefault = 1; + sqlite3mc_file* mcFile = (sqlite3mc_file*) pFile; + + if (mcFile->openFlags & SQLITE_OPEN_MAIN_DB) + { + rc = mcWriteMainDb(pFile, buffer, count, offset); + } +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_TEMP_DB) + { + /* + ** TODO: Could/Should a temporary database file be encrypted? + */ + } +#endif +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_TRANSIENT_DB) + { + /* + ** TODO: Could/Should a transient database file be encrypted? + */ + } +#endif + else if (mcFile->openFlags & SQLITE_OPEN_MAIN_JOURNAL) + { + rc = mcWriteMainJournal(pFile, buffer, count, offset); + } +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_TEMP_JOURNAL) + { + /* + ** TODO: Could/Should a temporary journal file be encrypted? + */ + } +#endif + else if (mcFile->openFlags & SQLITE_OPEN_SUBJOURNAL) + { + rc = mcWriteSubJournal(pFile, buffer, count, offset); +} +#if 0 + else if (mcFile->openFlags & SQLITE_OPEN_MASTER_JOURNAL) + { + /* + ** Master journal contains only administrative information + ** No encryption necessary + */ + } +#endif + /* + ** The page content is encrypted in memory in the WAL journal handler. + ** This provides for compatibility with legacy applications using the + ** previous SQLITE_HAS_CODEC encryption API. + */ + else if (mcFile->openFlags & SQLITE_OPEN_WAL) + { + rc = mcWriteWal(pFile, buffer, count, offset); + } + else + { + rc = REALFILE(pFile)->pMethods->xWrite(REALFILE(pFile), buffer, count, offset); + } + return rc; +} + +static int mcIoTruncate(sqlite3_file* pFile, sqlite3_int64 size) +{ + return REALFILE(pFile)->pMethods->xTruncate(REALFILE(pFile), size); +} + +static int mcIoSync(sqlite3_file* pFile, int flags) +{ + return REALFILE(pFile)->pMethods->xSync(REALFILE(pFile), flags); +} + +static int mcIoFileSize(sqlite3_file* pFile, sqlite3_int64* pSize) +{ + return REALFILE(pFile)->pMethods->xFileSize(REALFILE(pFile), pSize); +} + +static int mcIoLock(sqlite3_file* pFile, int lock) +{ + return REALFILE(pFile)->pMethods->xLock(REALFILE(pFile), lock); +} + +static int mcIoUnlock(sqlite3_file* pFile, int lock) +{ + return REALFILE(pFile)->pMethods->xUnlock(REALFILE(pFile), lock); +} + +static int mcIoCheckReservedLock(sqlite3_file* pFile, int* pResOut) +{ + return REALFILE(pFile)->pMethods->xCheckReservedLock(REALFILE(pFile), pResOut); +} + +static int mcIoFileControl(sqlite3_file* pFile, int op, void* pArg) +{ + int rc = SQLITE_OK; + int doReal = 1; + sqlite3mc_file* p = (sqlite3mc_file*) pFile; + + switch (op) + { + case SQLITE3MC_FCNTL_PVFS: + { + *(sqlite3mc_vfs**) pArg = p->pVfsMC; + doReal = 0; + } + break; + case SQLITE_FCNTL_PDB: + { +#if 0 + /* + ** pArg points to the sqlite3* handle for which the database file was opened. + ** In shared cache mode this function is invoked for every use of the database + ** file in a connection. Unfortunately there is no notification, when a database + ** file is no longer used by a connection (close in normal mode). + ** + ** For now, the database handle will not be stored in the file object. + ** In the future, this behaviour may be changed, especially, if shared cache mode + ** is disabled. Shared cache mode is enabled for backward compatibility only, its + ** use is not recommended. A future version of SQLite might disable it by default. + */ + sqlite3* db = *((sqlite3**) pArg); +#endif + } + break; + case SQLITE_FCNTL_PRAGMA: + { + /* + ** Handle pragmas specific to this database file + */ +#if 0 + /* + ** SQLite invokes this function for all pragmas, which are related to the schema + ** associated with this database file. In case of an unknown pragma, this function + ** should return SQLITE_NOTFOUND. However, since this VFS is just a shim, handling + ** of the pragma is forwarded to the underlying real VFS in such a case. + ** + ** For now, all pragmas are handled at the connection level. + ** For this purpose the SQLite's pragma handling is intercepted. + ** The latter requires a patch of SQLite's amalgamation code. + ** Maybe a future version will be able to abandon the patch. + */ + char* pragmaName = ((char**) pArg)[1]; + char* pragmaValue = ((char**) pArg)[2]; + if (sqlite3StrICmp(pragmaName, "...") == 0) + { + /* Action */ + /* ((char**) pArg)[0] = sqlite3_mprintf("error msg.");*/ + doReal = 0; + } +#endif + } + break; + default: + break; + } + if (doReal) + { + rc = REALFILE(pFile)->pMethods->xFileControl(REALFILE(pFile), op, pArg); + if (rc == SQLITE_OK && op == SQLITE_FCNTL_VFSNAME) + { + sqlite3mc_vfs* pVfsMC = p->pVfsMC; + char* zIn = *(char**)pArg; + char* zOut = sqlite3_mprintf("%s/%z", pVfsMC->base.zName, zIn); + *(char**)pArg = zOut; + if (zOut == 0) rc = SQLITE_NOMEM; + } + } + return rc; +} + +static int mcIoSectorSize(sqlite3_file* pFile) +{ + if (REALFILE(pFile)->pMethods->xSectorSize) + return REALFILE(pFile)->pMethods->xSectorSize(REALFILE(pFile)); + else + return SQLITE_DEFAULT_SECTOR_SIZE; +} + +static int mcIoDeviceCharacteristics(sqlite3_file* pFile) +{ + return REALFILE(pFile)->pMethods->xDeviceCharacteristics(REALFILE(pFile)); +} + +static int mcIoShmMap(sqlite3_file* pFile, int iPg, int pgsz, int map, void volatile** p) +{ + return REALFILE(pFile)->pMethods->xShmMap(REALFILE(pFile), iPg, pgsz, map, p); +} + +static int mcIoShmLock(sqlite3_file* pFile, int offset, int n, int flags) +{ + return REALFILE(pFile)->pMethods->xShmLock(REALFILE(pFile), offset, n, flags); +} + +static void mcIoShmBarrier(sqlite3_file* pFile) +{ + REALFILE(pFile)->pMethods->xShmBarrier(REALFILE(pFile)); +} + +static int mcIoShmUnmap(sqlite3_file* pFile, int deleteFlag) +{ + return REALFILE(pFile)->pMethods->xShmUnmap(REALFILE(pFile), deleteFlag); +} + +static int mcIoFetch(sqlite3_file* pFile, sqlite3_int64 iOfst, int iAmt, void** pp) +{ + return REALFILE(pFile)->pMethods->xFetch(REALFILE(pFile), iOfst, iAmt, pp); +} + +static int mcIoUnfetch( sqlite3_file* pFile, sqlite3_int64 iOfst, void* p) +{ + return REALFILE(pFile)->pMethods->xUnfetch(REALFILE(pFile), iOfst, p); +} + +/* +** SQLite3 Multiple Ciphers internal API functions +*/ + +/* +** Check the requested VFS +*/ +SQLITE_PRIVATE int +sqlite3mcCheckVfs(const char* zVfs) +{ + int rc = SQLITE_OK; + sqlite3_vfs* pVfs = sqlite3_vfs_find(zVfs); + if (pVfs == NULL) + { + /* VFS not found */ + int prefixLen = (int) strlen(SQLITE3MC_VFS_NAME); + if (strncmp(zVfs, SQLITE3MC_VFS_NAME, prefixLen) == 0) + { + /* VFS name starts with prefix. */ + const char* zVfsNameEnd = zVfs + strlen(SQLITE3MC_VFS_NAME); + if (*zVfsNameEnd == '-') + { + /* Prefix separator found, determine the name of the real VFS. */ + const char* zVfsReal = zVfsNameEnd + 1; + pVfs = sqlite3_vfs_find(zVfsReal); + if (pVfs != NULL) + { + /* Real VFS exists */ + /* Create VFS with encryption support based on real VFS */ + rc = sqlite3mc_vfs_create(zVfsReal, 0); + } + } + } + } + return rc; +} + +SQLITE_PRIVATE int +sqlite3mcPagerHasCodec(PagerMC* pPager) +{ + int hasCodec = 0; + sqlite3mc_vfs* pVfsMC = NULL; + sqlite3_vfs* pVfs = pPager->pVfs; + + /* Check whether the VFS stack of the pager contains a Multiple Ciphers VFS */ + for (; pVfs; pVfs = pVfs->pNext) + { + if (pVfs && pVfs->xOpen == mcVfsOpen) + { + /* Multiple Ciphers VFS found */ + pVfsMC = (sqlite3mc_vfs*)(pVfs); + break; + } + } + + /* Check whether codec is enabled for associated database file */ + if (pVfsMC) + { + sqlite3mc_file* mcFile = mcFindDbMainFileName(pVfsMC, pPager->zFilename); + if (mcFile) + { + Codec* codec = mcFile->codec; + hasCodec = (codec != 0 && sqlite3mcIsEncrypted(codec)); + } + } + return hasCodec; +} + +/* +** SQLite3 Multiple Ciphers external API functions +*/ + +static void mcVfsDestroy(sqlite3_vfs* pVfs) +{ + if (pVfs && pVfs->xOpen == mcVfsOpen) + { + /* Destroy the VFS instance only if no file is referring to it any longer */ + if (((sqlite3mc_vfs*) pVfs)->pMain == 0) + { + sqlite3_mutex_free(((sqlite3mc_vfs*)pVfs)->mutex); + sqlite3_vfs_unregister(pVfs); + sqlite3_free(pVfs); + } + } +} + +/* +** Unregister and destroy a Multiple Ciphers VFS +** created by an earlier call to sqlite3mc_vfs_create(). +*/ +SQLITE_API void sqlite3mc_vfs_destroy(const char* zName) +{ + mcVfsDestroy(sqlite3_vfs_find(zName)); +} + +/* +** Create a Multiple Ciphers VFS based on the underlying VFS with name given by zVfsReal. +** If makeDefault is true, the VFS is set as the default VFS. +*/ +SQLITE_API int sqlite3mc_vfs_create(const char* zVfsReal, int makeDefault) +{ + static sqlite3_vfs mcVfsTemplate = + { + 3, /* iVersion */ + 0, /* szOsFile */ + 1024, /* mxPathname */ + 0, /* pNext */ + 0, /* zName */ + 0, /* pAppData */ + mcVfsOpen, /* xOpen */ + mcVfsDelete, /* xDelete */ + mcVfsAccess, /* xAccess */ + mcVfsFullPathname, /* xFullPathname */ +#ifndef SQLITE_OMIT_LOAD_EXTENSION + mcVfsDlOpen, /* xDlOpen */ + mcVfsDlError, /* xDlError */ + mcVfsDlSym, /* xDlSym */ + mcVfsDlClose, /* xDlClose */ +#else + 0, 0, 0, 0, +#endif + mcVfsRandomness, /* xRandomness */ + mcVfsSleep, /* xSleep */ + mcVfsCurrentTime, /* xCurrentTime */ + mcVfsGetLastError, /* xGetLastError */ + mcVfsCurrentTimeInt64, /* xCurrentTimeInt64 */ + mcVfsSetSystemCall, /* xSetSystemCall */ + mcVfsGetSystemCall, /* xGetSystemCall */ + mcVfsNextSystemCall /* xNextSystemCall */ + }; + sqlite3mc_vfs* pVfsNew = 0; /* Newly allocated VFS */ + sqlite3_vfs* pVfsReal = sqlite3_vfs_find(zVfsReal); /* Real VFS */ + int rc; + + if (pVfsReal) + { + size_t nPrefix = strlen(SQLITE3MC_VFS_NAME); + size_t nRealName = strlen(pVfsReal->zName); + size_t nName = nPrefix + nRealName + 1; + size_t nByte = sizeof(sqlite3mc_vfs) + nName + 1; + pVfsNew = (sqlite3mc_vfs*) sqlite3_malloc64(nByte); + if (pVfsNew) + { + char* zSpace = (char*) &pVfsNew[1]; + memset(pVfsNew, 0, nByte); + memcpy(&pVfsNew->base, &mcVfsTemplate, sizeof(sqlite3_vfs)); + pVfsNew->base.iVersion = pVfsReal->iVersion; + pVfsNew->base.pAppData = pVfsReal; + pVfsNew->base.mxPathname = pVfsReal->mxPathname; + pVfsNew->base.szOsFile = sizeof(sqlite3mc_file) + pVfsReal->szOsFile; + + /* Set name of new VFS as combination of the multiple ciphers prefix and the name of the underlying VFS */ + pVfsNew->base.zName = (const char*) zSpace; + memcpy(zSpace, SQLITE3MC_VFS_NAME, nPrefix); + memcpy(zSpace + nPrefix, "-", 1); + memcpy(zSpace + nPrefix + 1, pVfsReal->zName, nRealName); + + /* Allocate the mutex and register the new VFS */ + pVfsNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); + if (pVfsNew->mutex) + { + rc = sqlite3_vfs_register(&pVfsNew->base, makeDefault); + if (rc != SQLITE_OK) + { + sqlite3_mutex_free(pVfsNew->mutex); + } + } + else + { + /* Mutex could not be allocated */ + rc = SQLITE_NOMEM; + } + if (rc != SQLITE_OK) + { + /* Mutex could not be allocated or new VFS could not be registered */ + sqlite3_free(pVfsNew); + } + } + else + { + /* New VFS could not be allocated */ + rc = SQLITE_NOMEM; + } + } + else + { + /* Underlying VFS not found */ + rc = SQLITE_NOTFOUND; + } + return rc; +} + +/* +** Shutdown all registered SQLite3 Multiple Ciphers VFSs +*/ +SQLITE_API void sqlite3mc_vfs_shutdown() +{ + sqlite3_vfs* pVfs; + sqlite3_vfs* pVfsNext; + for (pVfs = sqlite3_vfs_find(0); pVfs; pVfs = pVfsNext) + { + pVfsNext = pVfs->pNext; + mcVfsDestroy(pVfs); + } +} +/*** End of #include "sqlite3mc_vfs.c" ***/ + + +static int +mcRegisterCodecExtensions(sqlite3* db, char** pzErrMsg, const sqlite3_api_routines* pApi) +{ + int rc = SQLITE_OK; + CodecParameter* codecParameterTable = NULL; + + void* codecParamTable = sqlite3_get_clientdata(db, globalConfigTableName); + if (codecParamTable) + { + /* Return if codec extension functions are already defined */ + return rc; + } + + /* Generate copy of global codec parameter table */ + codecParameterTable = sqlite3mcCloneCodecParameterTable(); + rc = (codecParameterTable != NULL) ? SQLITE_OK : SQLITE_NOMEM; + if (rc == SQLITE_OK) + { + sqlite3_set_clientdata(db, globalConfigTableName, codecParameterTable, sqlite3mcFreeCodecParameterTable); + } + + rc = (codecParameterTable != NULL) ? SQLITE_OK : SQLITE_NOMEM; + if (rc == SQLITE_OK) + { + rc = sqlite3_create_function(db, "sqlite3mc_config", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, + codecParameterTable, sqlite3mcConfigParams, 0, 0); + } + if (rc == SQLITE_OK) + { + rc = sqlite3_create_function(db, "sqlite3mc_config", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, + codecParameterTable, sqlite3mcConfigParams, 0, 0); + } + if (rc == SQLITE_OK) + { + rc = sqlite3_create_function(db, "sqlite3mc_config", 3, SQLITE_UTF8 | SQLITE_DETERMINISTIC, + codecParameterTable, sqlite3mcConfigParams, 0, 0); + } + if (rc == SQLITE_OK) + { + rc = sqlite3_create_function(db, "sqlite3mc_codec_data", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, + NULL, sqlite3mcCodecDataSql, 0, 0); + } + if (rc == SQLITE_OK) + { + rc = sqlite3_create_function(db, "sqlite3mc_codec_data", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, + NULL, sqlite3mcCodecDataSql, 0, 0); + } + if (rc == SQLITE_OK) + { + rc = sqlite3_create_function(db, "sqlite3mc_version", 0, SQLITE_UTF8 | SQLITE_DETERMINISTIC, + NULL, sqlite3mcVersion, 0, 0); + } + return rc; +} + +#ifdef SQLITE_ENABLE_EXTFUNC +static int +sqlite3_extfunc_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi) +{ + return RegisterExtensionFunctions(db); +} +#endif + +static int +mcCheckValidName(const char* name) +{ + size_t nl; + if (!name) + return SQLITE_ERROR; + + /* Check for valid cipher name length */ + nl = strlen(name); + if (nl < 1 || nl >= CIPHER_NAME_MAXLEN) + return SQLITE_ERROR; + + /* Check for already registered names */ + CipherName* cipherNameTable = &globalCipherNameTable[0]; + for (; cipherNameTable->m_name[0] != 0; ++cipherNameTable) + { + if (sqlite3_stricmp(name, cipherNameTable->m_name) == 0) break; + } + if (cipherNameTable->m_name[0] != 0) + return SQLITE_ERROR; + + /* Check for valid character set (1st char = alpha, rest = alpha-numeric or underscore) */ + if (sqlite3Isalpha(name[0])) + { + size_t j; + for (j = 1; j < nl && (name[j] == '_' || sqlite3Isalnum(name[j])); ++j) {} + if (j == nl) + return SQLITE_OK; + } + return SQLITE_ERROR; +} + +SQLITE_PRIVATE int +sqlite3mcGetGlobalCipherCount() +{ + int cipherCount = 0; + sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN)); + cipherCount = globalCipherCount; + sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN)); + return cipherCount; +} + +static int +sqlite3mcRegisterCipher(const CipherDescriptor* desc, const CipherParams* params, int makeDefault) +{ + int rc; + int np; + CipherParams* cipherParams; + + /* Sanity checks */ + + /* Cipher description AND parameter are required */ + if (!desc || !params) + return SQLITE_ERROR; + + /* ALL methods of the cipher descriptor need to be defined */ + if (!desc->m_name || + !desc->m_allocateCipher || + !desc->m_freeCipher || + !desc->m_cloneCipher || + !desc->m_getLegacy || + !desc->m_getPageSize || + !desc->m_getReserved || + !desc->m_getSalt || + !desc->m_generateKey || + !desc->m_encryptPage || + !desc->m_decryptPage) + return SQLITE_ERROR; + + /* Check for valid cipher name */ + if (mcCheckValidName(desc->m_name) != SQLITE_OK) + return SQLITE_ERROR; + + /* Check cipher parameters */ + for (np = 0; np < CIPHER_PARAMS_COUNT_MAX; ++np) + { + CipherParams entry = params[np]; + /* Check for sentinel parameter */ + if (entry.m_name == 0 || entry.m_name[0] == 0) + break; + /* Check for valid parameter name */ + if (mcCheckValidName(entry.m_name) != SQLITE_OK) + return SQLITE_ERROR; + /* Check for valid parameter specification */ + if (!(entry.m_minValue >= 0 && entry.m_maxValue >= 0 && entry.m_minValue <= entry.m_maxValue && + entry.m_value >= entry.m_minValue && entry.m_value <= entry.m_maxValue && + entry.m_default >= entry.m_minValue && entry.m_default <= entry.m_maxValue)) + return SQLITE_ERROR; + } + + /* Check for parameter count in valid range and valid sentinel parameter */ + if (np >= CIPHER_PARAMS_COUNT_MAX || params[np].m_name == 0) + return SQLITE_ERROR; + + /* Sanity checks were successful, now register cipher */ + + cipherParams = (CipherParams*) sqlite3_malloc((np+1) * sizeof(CipherParams)); + if (!cipherParams) + return SQLITE_NOMEM; + + /* Check for */ + if (globalCipherCount < CODEC_COUNT_MAX) + { + int n; + char* cipherName; + ++globalCipherCount; + cipherName = globalCipherNameTable[globalCipherCount].m_name; + strcpy(cipherName, desc->m_name); + + globalCodecDescriptorTable[globalCipherCount - 1] = *desc; + globalCodecDescriptorTable[globalCipherCount - 1].m_name = cipherName; + + globalCodecParameterTable[globalCipherCount].m_name = cipherName; + globalCodecParameterTable[globalCipherCount].m_id = globalCipherCount; + globalCodecParameterTable[globalCipherCount].m_params = cipherParams; + + /* Copy parameters */ + for (n = 0; n < np; ++n) + { + char* paramName = (char*) sqlite3_malloc((int)strlen(params[n].m_name) + 1); + strcpy(paramName, params[n].m_name); + cipherParams[n] = params[n]; + cipherParams[n].m_name = paramName; + } + /* Add sentinel */ + cipherParams[n] = params[n]; + cipherParams[n].m_name = globalSentinelName; + + /* Make cipher default, if requested */ + if (makeDefault) + { + CipherParams* param = globalCodecParameterTable[0].m_params; + for (; param->m_name[0] != 0; ++param) + { + if (sqlite3_stricmp("cipher", param->m_name) == 0) break; + } + if (param->m_name[0] != 0) + { + param->m_value = param->m_default = globalCipherCount; + } + } + + rc = SQLITE_OK; + } + else + { + rc = SQLITE_NOMEM; + } + + return rc; +} + +SQLITE_API int +sqlite3mc_register_cipher(const CipherDescriptor* desc, const CipherParams* params, int makeDefault) +{ + int rc; +#ifndef SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if (rc) return rc; +#endif + sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN)); + rc = sqlite3mcRegisterCipher(desc, params, makeDefault); + sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MAIN)); + return rc; +} + +SQLITE_PRIVATE int +sqlite3mcInitCipherTables() +{ + size_t n; + + /* Initialize global configuration table name */ + sqlite3_randomness(CIPHER_NAME_MAXLEN, globalConfigTableName); + for (n = 0; n < CIPHER_NAME_MAXLEN-1; ++n) + { + if (globalConfigTableName[n] == 0) + globalConfigTableName[n] = '@'; + } + globalConfigTableName[CIPHER_NAME_MAXLEN-1] = 0; + + /* Initialize cipher name table */ + strcpy(globalCipherNameTable[0].m_name, "global"); + for (n = 1; n < CODEC_COUNT_MAX + 2; ++n) + { + strcpy(globalCipherNameTable[n].m_name, ""); + } + + /* Initialize cipher descriptor table */ + for (n = 0; n < CODEC_COUNT_MAX + 1; ++n) + { + globalCodecDescriptorTable[n] = mcSentinelDescriptor; + } + + /* Initialize cipher parameter table */ + globalCodecParameterTable[0] = globalCommonParams; + for (n = 1; n < CODEC_COUNT_MAX + 2; ++n) + { + globalCodecParameterTable[n] = globalSentinelParams; + } + + return SQLITE_OK; +} + +SQLITE_PRIVATE void +sqlite3mcTermCipherTables() +{ + size_t n; + for (n = CODEC_COUNT_MAX+1; n > 0; --n) + { + if (globalCodecParameterTable[n].m_name[0] != 0) + { + int k; + CipherParams* params = globalCodecParameterTable[n].m_params; + for (k = 0; params[k].m_name[0] != 0; ++k) + { + sqlite3_free((char*) params[k].m_name); + } + sqlite3_free(globalCodecParameterTable[n].m_params); + } + } + globalCipherCount = 0; +} + +SQLITE_PRIVATE int +sqlite3mc_initialize(const char* arg) +{ + int rc = sqlite3mcInitCipherTables(); +#if HAVE_CIPHER_AES_128_CBC + if (rc == SQLITE_OK) + { + rc = sqlite3mcRegisterCipher(&mcAES128Descriptor, mcAES128Params, (CODEC_TYPE_AES128 == CODEC_TYPE)); + } +#endif +#if HAVE_CIPHER_AES_256_CBC + if (rc == SQLITE_OK) + { + rc = sqlite3mcRegisterCipher(&mcAES256Descriptor, mcAES256Params, (CODEC_TYPE_AES256 == CODEC_TYPE)); + } +#endif +#if HAVE_CIPHER_CHACHA20 + if (rc == SQLITE_OK) + { + rc = sqlite3mcRegisterCipher(&mcChaCha20Descriptor, mcChaCha20Params, (CODEC_TYPE_CHACHA20 == CODEC_TYPE)); + } +#endif +#if HAVE_CIPHER_SQLCIPHER + if (rc == SQLITE_OK) + { + rc = sqlite3mcRegisterCipher(&mcSQLCipherDescriptor, mcSQLCipherParams, (CODEC_TYPE_SQLCIPHER == CODEC_TYPE)); + } +#endif +#if HAVE_CIPHER_RC4 + if (rc == SQLITE_OK) + { + rc = sqlite3mcRegisterCipher(&mcRC4Descriptor, mcRC4Params, (CODEC_TYPE_RC4 == CODEC_TYPE)); + } +#endif +#if HAVE_CIPHER_ASCON128 + if (rc == SQLITE_OK) + { + rc = sqlite3mcRegisterCipher(&mcAscon128Descriptor, mcAscon128Params, (CODEC_TYPE_ASCON128 == CODEC_TYPE)); + } +#endif +#if HAVE_CIPHER_AEGIS + if (rc == SQLITE_OK) + { + aegis_init(); + rc = sqlite3mcRegisterCipher(&mcAegisDescriptor, mcAegisParams, (CODEC_TYPE_AEGIS == CODEC_TYPE)); + } +#endif + + /* + ** Initialize and register MultiCipher VFS as default VFS + ** if it isn't already registered + */ + if (rc == SQLITE_OK) + { + rc = sqlite3mc_vfs_create(NULL, 1); + } + return rc; +} + +SQLITE_PRIVATE int +sqlite3mc_builtin_extensions(sqlite3* db) +{ + char* errmsg = NULL; + int rc = SQLITE_OK; + + /* + ** Register Multi Cipher extension + */ + if (rc == SQLITE_OK) + { + rc = mcRegisterCodecExtensions(db, &errmsg, NULL); + } +#ifdef SQLITE_ENABLE_EXTFUNC + if (rc == SQLITE_OK) + { + rc = sqlite3_extfunc_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_CSV + if (rc == SQLITE_OK) + { + rc = sqlite3_csv_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_VSV + if (rc == SQLITE_OK) + { + rc = sqlite3_vsv_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_SHA3 + if (rc == SQLITE_OK) + { + rc = sqlite3_shathree_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_CARRAY + if (rc == SQLITE_OK) + { + rc = sqlite3_carray_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_FILEIO + if (rc == SQLITE_OK) + { + rc = sqlite3_fileio_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_SERIES + if (rc == SQLITE_OK) + { + rc = sqlite3_series_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_UUID + if (rc == SQLITE_OK) + { + rc = sqlite3_uuid_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_REGEXP + if (rc == SQLITE_OK) + { + rc = sqlite3_regexp_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_COMPRESS + if (rc == SQLITE_OK) + { + rc = sqlite3_compress_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_SQLAR + if (rc == SQLITE_OK) + { + rc = sqlite3_sqlar_init(db, &errmsg, NULL); + } +#endif +#ifdef SQLITE_ENABLE_ZIPFILE + if (rc == SQLITE_OK) + { + rc = sqlite3_zipfile_init(db, &errmsg, NULL); + } +#endif + return rc; +} + +SQLITE_PRIVATE void +sqlite3mc_shutdown(void) +{ + sqlite3mc_vfs_shutdown(); + sqlite3mcTermCipherTables(); +} + +/* +** TCL/TK Extension and/or Shell +*/ +#ifdef SQLITE_ENABLE_TCL +/* #include "tclsqlite.c" */ +/*** Begin of #include "tclsqlite.c" ***/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** A TCL Interface to SQLite. Append this file to sqlite3.c and +** compile the whole thing to build a TCL-enabled version of SQLite. +** +** Compile-time options: +** +** -DTCLSH Add a "main()" routine that works as a tclsh. +** +** -DTCLSH_INIT_PROC=name +** +** Invoke name(interp) to initialize the Tcl interpreter. +** If name(interp) returns a non-NULL string, then run +** that string as a Tcl script to launch the application. +** If name(interp) returns NULL, then run the regular +** tclsh-emulator code. +*/ +#ifdef TCLSH_INIT_PROC +# define TCLSH 1 +#endif + +/* +** If requested, include the SQLite compiler options file for MSVC. +*/ +#if defined(INCLUDE_MSVC_H) +# include "msvc.h" +#endif + +/****** Copy of tclsqlite.h ******/ +#if defined(INCLUDE_SQLITE_TCL_H) +# include "sqlite_tcl.h" /* Special case for Windows using STDCALL */ +#else +# include /* All normal cases */ +# ifndef SQLITE_TCLAPI +# define SQLITE_TCLAPI +# endif +#endif +/* Compatability between Tcl8.6 and Tcl9.0 */ +#if TCL_MAJOR_VERSION==9 +# define CONST const +#elif !defined(Tcl_Size) + typedef int Tcl_Size; +#endif +/**** End copy of tclsqlite.h ****/ + +#include + +/* +** Some additional include files are needed if this file is not +** appended to the amalgamation. +*/ +#ifndef SQLITE_AMALGAMATION +/* # include "sqlite3.h" */ + +# include +# include +# include + typedef unsigned char u8; +# ifndef SQLITE_PTRSIZE +# if defined(__SIZEOF_POINTER__) +# define SQLITE_PTRSIZE __SIZEOF_POINTER__ +# elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \ + defined(_M_ARM) || defined(__arm__) || defined(__x86) || \ + (defined(__APPLE__) && defined(__POWERPC__)) || \ + (defined(__TOS_AIX__) && !defined(__64BIT__)) +# define SQLITE_PTRSIZE 4 +# else +# define SQLITE_PTRSIZE 8 +# endif +# endif /* SQLITE_PTRSIZE */ +# if defined(HAVE_STDINT_H) || (defined(__STDC_VERSION__) && \ + (__STDC_VERSION__ >= 199901L)) +# include + typedef uintptr_t uptr; +# elif SQLITE_PTRSIZE==4 + typedef unsigned int uptr; +# else + typedef sqlite3_uint64 uptr; +# endif +#endif +#include + +/* Used to get the current process ID */ +#if !defined(_WIN32) +# include +# include +# define GETPID getpid +#elif !defined(_WIN32_WCE) +# ifndef SQLITE_AMALGAMATION +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# endif +# include +# define isatty(h) _isatty(h) +# define GETPID (int)GetCurrentProcessId +#endif + +/* + * Windows needs to know which symbols to export. Unix does not. + * BUILD_sqlite should be undefined for Unix. + */ +#ifdef BUILD_sqlite +#undef TCL_STORAGE_CLASS +#define TCL_STORAGE_CLASS DLLEXPORT +#endif /* BUILD_sqlite */ + +#define NUM_PREPARED_STMTS 10 +#define MAX_PREPARED_STMTS 100 + +/* Forward declaration */ +typedef struct SqliteDb SqliteDb; + +/* +** New SQL functions can be created as TCL scripts. Each such function +** is described by an instance of the following structure. +** +** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, +** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation +** attempts to determine the type of the result based on the Tcl object. +** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text()) +** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER +** or SQLITE_FLOAT, then an attempt is made to return an integer or float +** value, falling back to float and then text if this is not possible. +*/ +typedef struct SqlFunc SqlFunc; +struct SqlFunc { + Tcl_Interp *interp; /* The TCL interpret to execute the function */ + Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */ + SqliteDb *pDb; /* Database connection that owns this function */ + int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */ + int eType; /* Type of value to return */ + char *zName; /* Name of this function */ + SqlFunc *pNext; /* Next function on the list of them all */ +}; + +/* +** New collation sequences function can be created as TCL scripts. Each such +** function is described by an instance of the following structure. +*/ +typedef struct SqlCollate SqlCollate; +struct SqlCollate { + Tcl_Interp *interp; /* The TCL interpret to execute the function */ + char *zScript; /* The script to be run */ + SqlCollate *pNext; /* Next function on the list of them all */ +}; + +/* +** Prepared statements are cached for faster execution. Each prepared +** statement is described by an instance of the following structure. +*/ +typedef struct SqlPreparedStmt SqlPreparedStmt; +struct SqlPreparedStmt { + SqlPreparedStmt *pNext; /* Next in linked list */ + SqlPreparedStmt *pPrev; /* Previous on the list */ + sqlite3_stmt *pStmt; /* The prepared statement */ + int nSql; /* chars in zSql[] */ + const char *zSql; /* Text of the SQL statement */ + int nParm; /* Size of apParm array */ + Tcl_Obj **apParm; /* Array of referenced object pointers */ +}; + +typedef struct IncrblobChannel IncrblobChannel; + +/* +** There is one instance of this structure for each SQLite database +** that has been opened by the SQLite TCL interface. +** +** If this module is built with SQLITE_TEST defined (to create the SQLite +** testfixture executable), then it may be configured to use either +** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements. +** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used. +*/ +struct SqliteDb { + sqlite3 *db; /* The "real" database structure. MUST BE FIRST */ + Tcl_Interp *interp; /* The interpreter used for this database */ + char *zBusy; /* The busy callback routine */ + char *zCommit; /* The commit hook callback routine */ + char *zTrace; /* The trace callback routine */ + char *zTraceV2; /* The trace_v2 callback routine */ + char *zProfile; /* The profile callback routine */ + char *zProgress; /* The progress callback routine */ + char *zBindFallback; /* Callback to invoke on a binding miss */ + char *zAuth; /* The authorization callback routine */ + int disableAuth; /* Disable the authorizer if it exists */ + char *zNull; /* Text to substitute for an SQL NULL value */ + SqlFunc *pFunc; /* List of SQL functions */ + Tcl_Obj *pUpdateHook; /* Update hook script (if any) */ + Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */ + Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */ + Tcl_Obj *pWalHook; /* WAL hook script (if any) */ + Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */ + SqlCollate *pCollate; /* List of SQL collation functions */ + int rc; /* Return code of most recent sqlite3_exec() */ + Tcl_Obj *pCollateNeeded; /* Collation needed script */ + SqlPreparedStmt *stmtList; /* List of prepared statements*/ + SqlPreparedStmt *stmtLast; /* Last statement in the list */ + int maxStmt; /* The next maximum number of stmtList */ + int nStmt; /* Number of statements in stmtList */ + IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */ + int nStep, nSort, nIndex; /* Statistics for most recent operation */ + int nVMStep; /* Another statistic for most recent operation */ + int nTransaction; /* Number of nested [transaction] methods */ + int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */ + int nRef; /* Delete object when this reaches 0 */ +#ifdef SQLITE_TEST + int bLegacyPrepare; /* True to use sqlite3_prepare() */ +#endif +}; + +struct IncrblobChannel { + sqlite3_blob *pBlob; /* sqlite3 blob handle */ + SqliteDb *pDb; /* Associated database connection */ + sqlite3_int64 iSeek; /* Current seek offset */ + unsigned int isClosed; /* TCL_CLOSE_READ or TCL_CLOSE_WRITE */ + Tcl_Channel channel; /* Channel identifier */ + IncrblobChannel *pNext; /* Linked list of all open incrblob channels */ + IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */ +}; + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +*/ +static int strlen30(const char *z){ + const char *z2 = z; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + + +#ifndef SQLITE_OMIT_INCRBLOB +/* +** Close all incrblob channels opened using database connection pDb. +** This is called when shutting down the database connection. +*/ +static void closeIncrblobChannels(SqliteDb *pDb){ + IncrblobChannel *p; + IncrblobChannel *pNext; + + for(p=pDb->pIncrblob; p; p=pNext){ + pNext = p->pNext; + + /* Note: Calling unregister here call Tcl_Close on the incrblob channel, + ** which deletes the IncrblobChannel structure at *p. So do not + ** call Tcl_Free() here. + */ + Tcl_UnregisterChannel(pDb->interp, p->channel); + } +} + +/* +** Close an incremental blob channel. +*/ +static int SQLITE_TCLAPI incrblobClose2( + ClientData instanceData, + Tcl_Interp *interp, + int flags +){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + int rc; + sqlite3 *db = p->pDb->db; + + if( flags ){ + p->isClosed |= flags; + return TCL_OK; + } + + /* If we reach this point, then we really do need to close the channel */ + rc = sqlite3_blob_close(p->pBlob); + + /* Remove the channel from the SqliteDb.pIncrblob list. */ + if( p->pNext ){ + p->pNext->pPrev = p->pPrev; + } + if( p->pPrev ){ + p->pPrev->pNext = p->pNext; + } + if( p->pDb->pIncrblob==p ){ + p->pDb->pIncrblob = p->pNext; + } + + /* Free the IncrblobChannel structure */ + Tcl_Free((char *)p); + + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE); + return TCL_ERROR; + } + return TCL_OK; +} +static int SQLITE_TCLAPI incrblobClose( + ClientData instanceData, + Tcl_Interp *interp +){ + return incrblobClose2(instanceData, interp, 0); +} + + +/* +** Read data from an incremental blob channel. +*/ +static int SQLITE_TCLAPI incrblobInput( + ClientData instanceData, + char *buf, + int bufSize, + int *errorCodePtr +){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + sqlite3_int64 nRead = bufSize; /* Number of bytes to read */ + sqlite3_int64 nBlob; /* Total size of the blob */ + int rc; /* sqlite error code */ + + nBlob = sqlite3_blob_bytes(p->pBlob); + if( (p->iSeek+nRead)>nBlob ){ + nRead = nBlob-p->iSeek; + } + if( nRead<=0 ){ + return 0; + } + + rc = sqlite3_blob_read(p->pBlob, (void *)buf, (int)nRead, (int)p->iSeek); + if( rc!=SQLITE_OK ){ + *errorCodePtr = rc; + return -1; + } + + p->iSeek += nRead; + return nRead; +} + +/* +** Write data to an incremental blob channel. +*/ +static int SQLITE_TCLAPI incrblobOutput( + ClientData instanceData, + const char *buf, + int toWrite, + int *errorCodePtr +){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + sqlite3_int64 nWrite = toWrite; /* Number of bytes to write */ + sqlite3_int64 nBlob; /* Total size of the blob */ + int rc; /* sqlite error code */ + + nBlob = sqlite3_blob_bytes(p->pBlob); + if( (p->iSeek+nWrite)>nBlob ){ + *errorCodePtr = EINVAL; + return -1; + } + if( nWrite<=0 ){ + return 0; + } + + rc = sqlite3_blob_write(p->pBlob, (void*)buf,(int)nWrite, (int)p->iSeek); + if( rc!=SQLITE_OK ){ + *errorCodePtr = EIO; + return -1; + } + + p->iSeek += nWrite; + return nWrite; +} + +/* The datatype of Tcl_DriverWideSeekProc changes between tcl8.6 and tcl9.0 */ +#if TCL_MAJOR_VERSION==9 +# define WideSeekProcType long long +#else +# define WideSeekProcType Tcl_WideInt +#endif + +/* +** Seek an incremental blob channel. +*/ +static WideSeekProcType SQLITE_TCLAPI incrblobWideSeek( + ClientData instanceData, + WideSeekProcType offset, + int seekMode, + int *errorCodePtr +){ + IncrblobChannel *p = (IncrblobChannel *)instanceData; + + switch( seekMode ){ + case SEEK_SET: + p->iSeek = offset; + break; + case SEEK_CUR: + p->iSeek += offset; + break; + case SEEK_END: + p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset; + break; + + default: assert(!"Bad seekMode"); + } + + return p->iSeek; +} +static int SQLITE_TCLAPI incrblobSeek( + ClientData instanceData, + long offset, + int seekMode, + int *errorCodePtr +){ + return incrblobWideSeek(instanceData,offset,seekMode,errorCodePtr); +} + + +static void SQLITE_TCLAPI incrblobWatch( + ClientData instanceData, + int mode +){ + /* NO-OP */ +} +static int SQLITE_TCLAPI incrblobHandle( + ClientData instanceData, + int dir, + ClientData *hPtr +){ + return TCL_ERROR; +} + +static Tcl_ChannelType IncrblobChannelType = { + "incrblob", /* typeName */ + TCL_CHANNEL_VERSION_5, /* version */ + incrblobClose, /* closeProc */ + incrblobInput, /* inputProc */ + incrblobOutput, /* outputProc */ + incrblobSeek, /* seekProc */ + 0, /* setOptionProc */ + 0, /* getOptionProc */ + incrblobWatch, /* watchProc (this is a no-op) */ + incrblobHandle, /* getHandleProc (always returns error) */ + incrblobClose2, /* close2Proc */ + 0, /* blockModeProc */ + 0, /* flushProc */ + 0, /* handlerProc */ + incrblobWideSeek, /* wideSeekProc */ +}; + +/* +** Create a new incrblob channel. +*/ +static int createIncrblobChannel( + Tcl_Interp *interp, + SqliteDb *pDb, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite_int64 iRow, + int isReadonly +){ + IncrblobChannel *p; + sqlite3 *db = pDb->db; + sqlite3_blob *pBlob; + int rc; + int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE); + + /* This variable is used to name the channels: "incrblob_[incr count]" */ + static int count = 0; + char zChannel[64]; + + rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob); + if( rc!=SQLITE_OK ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); + return TCL_ERROR; + } + + p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel)); + memset(p, 0, sizeof(*p)); + p->pBlob = pBlob; + if( (flags & TCL_WRITABLE)==0 ) p->isClosed |= TCL_CLOSE_WRITE; + + sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count); + p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags); + Tcl_RegisterChannel(interp, p->channel); + + /* Link the new channel into the SqliteDb.pIncrblob list. */ + p->pNext = pDb->pIncrblob; + p->pPrev = 0; + if( p->pNext ){ + p->pNext->pPrev = p; + } + pDb->pIncrblob = p; + p->pDb = pDb; + + Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE); + return TCL_OK; +} +#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */ + #define closeIncrblobChannels(pDb) +#endif + +/* +** Look at the script prefix in pCmd. We will be executing this script +** after first appending one or more arguments. This routine analyzes +** the script to see if it is safe to use Tcl_EvalObjv() on the script +** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much +** faster. +** +** Scripts that are safe to use with Tcl_EvalObjv() consists of a +** command name followed by zero or more arguments with no [...] or $ +** or {...} or ; to be seen anywhere. Most callback scripts consist +** of just a single procedure name and they meet this requirement. +*/ +static int safeToUseEvalObjv(Tcl_Obj *pCmd){ + /* We could try to do something with Tcl_Parse(). But we will instead + ** just do a search for forbidden characters. If any of the forbidden + ** characters appear in pCmd, we will report the string as unsafe. + */ + const char *z; + Tcl_Size n; + z = Tcl_GetStringFromObj(pCmd, &n); + while( n-- > 0 ){ + int c = *(z++); + if( c=='$' || c=='[' || c==';' ) return 0; + } + return 1; +} + +/* +** Find an SqlFunc structure with the given name. Or create a new +** one if an existing one cannot be found. Return a pointer to the +** structure. +*/ +static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){ + SqlFunc *p, *pNew; + int nName = strlen30(zName); + pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 ); + pNew->zName = (char*)&pNew[1]; + memcpy(pNew->zName, zName, nName+1); + for(p=pDb->pFunc; p; p=p->pNext){ + if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){ + Tcl_Free((char*)pNew); + return p; + } + } + pNew->interp = pDb->interp; + pNew->pDb = pDb; + pNew->pScript = 0; + pNew->pNext = pDb->pFunc; + pDb->pFunc = pNew; + return pNew; +} + +/* +** Free a single SqlPreparedStmt object. +*/ +static void dbFreeStmt(SqlPreparedStmt *pStmt){ +#ifdef SQLITE_TEST + if( sqlite3_sql(pStmt->pStmt)==0 ){ + Tcl_Free((char *)pStmt->zSql); + } +#endif + sqlite3_finalize(pStmt->pStmt); + Tcl_Free((char *)pStmt); +} + +/* +** Finalize and free a list of prepared statements +*/ +static void flushStmtCache(SqliteDb *pDb){ + SqlPreparedStmt *pPreStmt; + SqlPreparedStmt *pNext; + + for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){ + pNext = pPreStmt->pNext; + dbFreeStmt(pPreStmt); + } + pDb->nStmt = 0; + pDb->stmtLast = 0; + pDb->stmtList = 0; +} + +/* +** Increment the reference counter on the SqliteDb object. The reference +** should be released by calling delDatabaseRef(). +*/ +static void addDatabaseRef(SqliteDb *pDb){ + pDb->nRef++; +} + +/* +** Decrement the reference counter associated with the SqliteDb object. +** If it reaches zero, delete the object. +*/ +static void delDatabaseRef(SqliteDb *pDb){ + assert( pDb->nRef>0 ); + pDb->nRef--; + if( pDb->nRef==0 ){ + flushStmtCache(pDb); + closeIncrblobChannels(pDb); + sqlite3_close(pDb->db); + while( pDb->pFunc ){ + SqlFunc *pFunc = pDb->pFunc; + pDb->pFunc = pFunc->pNext; + assert( pFunc->pDb==pDb ); + Tcl_DecrRefCount(pFunc->pScript); + Tcl_Free((char*)pFunc); + } + while( pDb->pCollate ){ + SqlCollate *pCollate = pDb->pCollate; + pDb->pCollate = pCollate->pNext; + Tcl_Free((char*)pCollate); + } + if( pDb->zBusy ){ + Tcl_Free(pDb->zBusy); + } + if( pDb->zTrace ){ + Tcl_Free(pDb->zTrace); + } + if( pDb->zTraceV2 ){ + Tcl_Free(pDb->zTraceV2); + } + if( pDb->zProfile ){ + Tcl_Free(pDb->zProfile); + } + if( pDb->zBindFallback ){ + Tcl_Free(pDb->zBindFallback); + } + if( pDb->zAuth ){ + Tcl_Free(pDb->zAuth); + } + if( pDb->zNull ){ + Tcl_Free(pDb->zNull); + } + if( pDb->pUpdateHook ){ + Tcl_DecrRefCount(pDb->pUpdateHook); + } + if( pDb->pPreUpdateHook ){ + Tcl_DecrRefCount(pDb->pPreUpdateHook); + } + if( pDb->pRollbackHook ){ + Tcl_DecrRefCount(pDb->pRollbackHook); + } + if( pDb->pWalHook ){ + Tcl_DecrRefCount(pDb->pWalHook); + } + if( pDb->pCollateNeeded ){ + Tcl_DecrRefCount(pDb->pCollateNeeded); + } + Tcl_Free((char*)pDb); + } +} + +/* +** TCL calls this procedure when an sqlite3 database command is +** deleted. +*/ +static void SQLITE_TCLAPI DbDeleteCmd(void *db){ + SqliteDb *pDb = (SqliteDb*)db; + delDatabaseRef(pDb); +} + +/* +** This routine is called when a database file is locked while trying +** to execute SQL. +*/ +static int DbBusyHandler(void *cd, int nTries){ + SqliteDb *pDb = (SqliteDb*)cd; + int rc; + char zVal[30]; + + sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries); + rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0); + if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ + return 0; + } + return 1; +} + +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK +/* +** This routine is invoked as the 'progress callback' for the database. +*/ +static int DbProgressHandler(void *cd){ + SqliteDb *pDb = (SqliteDb*)cd; + int rc; + + assert( pDb->zProgress ); + rc = Tcl_Eval(pDb->interp, pDb->zProgress); + if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ + return 1; + } + return 0; +} +#endif + +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ + !defined(SQLITE_OMIT_DEPRECATED) +/* +** This routine is called by the SQLite trace handler whenever a new +** block of SQL is executed. The TCL script in pDb->zTrace is executed. +*/ +static void DbTraceHandler(void *cd, const char *zSql){ + SqliteDb *pDb = (SqliteDb*)cd; + Tcl_DString str; + + Tcl_DStringInit(&str); + Tcl_DStringAppend(&str, pDb->zTrace, -1); + Tcl_DStringAppendElement(&str, zSql); + Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); + Tcl_DStringFree(&str); + Tcl_ResetResult(pDb->interp); +} +#endif + +#ifndef SQLITE_OMIT_TRACE +/* +** This routine is called by the SQLite trace_v2 handler whenever a new +** supported event is generated. Unsupported event types are ignored. +** The TCL script in pDb->zTraceV2 is executed, with the arguments for +** the event appended to it (as list elements). +*/ +static int DbTraceV2Handler( + unsigned type, /* One of the SQLITE_TRACE_* event types. */ + void *cd, /* The original context data pointer. */ + void *pd, /* Primary event data, depends on event type. */ + void *xd /* Extra event data, depends on event type. */ +){ + SqliteDb *pDb = (SqliteDb*)cd; + Tcl_Obj *pCmd; + + switch( type ){ + case SQLITE_TRACE_STMT: { + sqlite3_stmt *pStmt = (sqlite3_stmt *)pd; + char *zSql = (char *)xd; + + pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(pDb->interp, pCmd, + Tcl_NewWideIntObj((Tcl_WideInt)(uptr)pStmt)); + Tcl_ListObjAppendElement(pDb->interp, pCmd, + Tcl_NewStringObj(zSql, -1)); + Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + Tcl_ResetResult(pDb->interp); + break; + } + case SQLITE_TRACE_PROFILE: { + sqlite3_stmt *pStmt = (sqlite3_stmt *)pd; + sqlite3_int64 ns = *(sqlite3_int64*)xd; + + pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(pDb->interp, pCmd, + Tcl_NewWideIntObj((Tcl_WideInt)(uptr)pStmt)); + Tcl_ListObjAppendElement(pDb->interp, pCmd, + Tcl_NewWideIntObj((Tcl_WideInt)ns)); + Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + Tcl_ResetResult(pDb->interp); + break; + } + case SQLITE_TRACE_ROW: { + sqlite3_stmt *pStmt = (sqlite3_stmt *)pd; + + pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(pDb->interp, pCmd, + Tcl_NewWideIntObj((Tcl_WideInt)(uptr)pStmt)); + Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + Tcl_ResetResult(pDb->interp); + break; + } + case SQLITE_TRACE_CLOSE: { + sqlite3 *db = (sqlite3 *)pd; + + pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(pDb->interp, pCmd, + Tcl_NewWideIntObj((Tcl_WideInt)(uptr)db)); + Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + Tcl_ResetResult(pDb->interp); + break; + } + } + return SQLITE_OK; +} +#endif + +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ + !defined(SQLITE_OMIT_DEPRECATED) +/* +** This routine is called by the SQLite profile handler after a statement +** SQL has executed. The TCL script in pDb->zProfile is evaluated. +*/ +static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){ + SqliteDb *pDb = (SqliteDb*)cd; + Tcl_DString str; + char zTm[100]; + + sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm); + Tcl_DStringInit(&str); + Tcl_DStringAppend(&str, pDb->zProfile, -1); + Tcl_DStringAppendElement(&str, zSql); + Tcl_DStringAppendElement(&str, zTm); + Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); + Tcl_DStringFree(&str); + Tcl_ResetResult(pDb->interp); +} +#endif + +/* +** This routine is called when a transaction is committed. The +** TCL script in pDb->zCommit is executed. If it returns non-zero or +** if it throws an exception, the transaction is rolled back instead +** of being committed. +*/ +static int DbCommitHandler(void *cd){ + SqliteDb *pDb = (SqliteDb*)cd; + int rc; + + rc = Tcl_Eval(pDb->interp, pDb->zCommit); + if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ + return 1; + } + return 0; +} + +static void DbRollbackHandler(void *clientData){ + SqliteDb *pDb = (SqliteDb*)clientData; + assert(pDb->pRollbackHook); + if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){ + Tcl_BackgroundError(pDb->interp); + } +} + +/* +** This procedure handles wal_hook callbacks. +*/ +static int DbWalHandler( + void *clientData, + sqlite3 *db, + const char *zDb, + int nEntry +){ + int ret = SQLITE_OK; + Tcl_Obj *p; + SqliteDb *pDb = (SqliteDb*)clientData; + Tcl_Interp *interp = pDb->interp; + assert(pDb->pWalHook); + + assert( db==pDb->db ); + p = Tcl_DuplicateObj(pDb->pWalHook); + Tcl_IncrRefCount(p); + Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1)); + Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry)); + if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0) + || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret) + ){ + Tcl_BackgroundError(interp); + } + Tcl_DecrRefCount(p); + + return ret; +} + +#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) +static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){ + char zBuf[64]; + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg); + Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY); + sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg); + Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY); +} +#else +# define setTestUnlockNotifyVars(x,y,z) +#endif + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY +static void DbUnlockNotify(void **apArg, int nArg){ + int i; + for(i=0; iinterp, i, nArg); + assert( pDb->pUnlockNotify); + Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags); + Tcl_DecrRefCount(pDb->pUnlockNotify); + pDb->pUnlockNotify = 0; + } +} +#endif + +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK +/* +** Pre-update hook callback. +*/ +static void DbPreUpdateHandler( + void *p, + sqlite3 *db, + int op, + const char *zDb, + const char *zTbl, + sqlite_int64 iKey1, + sqlite_int64 iKey2 +){ + SqliteDb *pDb = (SqliteDb *)p; + Tcl_Obj *pCmd; + static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"}; + + assert( (SQLITE_DELETE-1)/9 == 0 ); + assert( (SQLITE_INSERT-1)/9 == 1 ); + assert( (SQLITE_UPDATE-1)/9 == 2 ); + assert( pDb->pPreUpdateHook ); + assert( db==pDb->db ); + assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); + + pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2)); + Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); +} +#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ + +static void DbUpdateHandler( + void *p, + int op, + const char *zDb, + const char *zTbl, + sqlite_int64 rowid +){ + SqliteDb *pDb = (SqliteDb *)p; + Tcl_Obj *pCmd; + static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"}; + + assert( (SQLITE_DELETE-1)/9 == 0 ); + assert( (SQLITE_INSERT-1)/9 == 1 ); + assert( (SQLITE_UPDATE-1)/9 == 2 ); + + assert( pDb->pUpdateHook ); + assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); + + pCmd = Tcl_DuplicateObj(pDb->pUpdateHook); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1)); + Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid)); + Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); +} + +static void tclCollateNeeded( + void *pCtx, + sqlite3 *db, + int enc, + const char *zName +){ + SqliteDb *pDb = (SqliteDb *)pCtx; + Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded); + Tcl_IncrRefCount(pScript); + Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1)); + Tcl_EvalObjEx(pDb->interp, pScript, 0); + Tcl_DecrRefCount(pScript); +} + +/* +** This routine is called to evaluate an SQL collation function implemented +** using TCL script. +*/ +static int tclSqlCollate( + void *pCtx, + int nA, + const void *zA, + int nB, + const void *zB +){ + SqlCollate *p = (SqlCollate *)pCtx; + Tcl_Obj *pCmd; + + pCmd = Tcl_NewStringObj(p->zScript, -1); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA)); + Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB)); + Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + return (atoi(Tcl_GetStringResult(p->interp))); +} + +/* +** This routine is called to evaluate an SQL function implemented +** using TCL script. +*/ +static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){ + SqlFunc *p = sqlite3_user_data(context); + Tcl_Obj *pCmd; + int i; + int rc; + + if( argc==0 ){ + /* If there are no arguments to the function, call Tcl_EvalObjEx on the + ** script object directly. This allows the TCL compiler to generate + ** bytecode for the command on the first invocation and thus make + ** subsequent invocations much faster. */ + pCmd = p->pScript; + Tcl_IncrRefCount(pCmd); + rc = Tcl_EvalObjEx(p->interp, pCmd, 0); + Tcl_DecrRefCount(pCmd); + }else{ + /* If there are arguments to the function, make a shallow copy of the + ** script object, lappend the arguments, then evaluate the copy. + ** + ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated. + ** The new Tcl_Obj contains pointers to the original list elements. + ** That way, when Tcl_EvalObjv() is run and shimmers the first element + ** of the list to tclCmdNameType, that alternate representation will + ** be preserved and reused on the next invocation. + */ + Tcl_Obj **aArg; + Tcl_Size nArg; + if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){ + sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); + return; + } + pCmd = Tcl_NewListObj(nArg, aArg); + Tcl_IncrRefCount(pCmd); + for(i=0; i=-2147483647 && v<=2147483647 ){ + pVal = Tcl_NewIntObj((int)v); + }else{ + pVal = Tcl_NewWideIntObj(v); + } + break; + } + case SQLITE_FLOAT: { + double r = sqlite3_value_double(pIn); + pVal = Tcl_NewDoubleObj(r); + break; + } + case SQLITE_NULL: { + pVal = Tcl_NewStringObj(p->pDb->zNull, -1); + break; + } + default: { + int bytes = sqlite3_value_bytes(pIn); + pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes); + break; + } + } + rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal); + if( rc ){ + Tcl_DecrRefCount(pCmd); + sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); + return; + } + } + if( !p->useEvalObjv ){ + /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd + ** is a list without a string representation. To prevent this from + ** happening, make sure pCmd has a valid string representation */ + Tcl_GetString(pCmd); + } + rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + } + + if( rc && rc!=TCL_RETURN ){ + sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); + }else{ + Tcl_Obj *pVar = Tcl_GetObjResult(p->interp); + Tcl_Size n; + u8 *data; + const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); + char c = zType[0]; + int eType = p->eType; + + if( eType==SQLITE_NULL ){ + if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){ + /* Only return a BLOB type if the Tcl variable is a bytearray and + ** has no string representation. */ + eType = SQLITE_BLOB; + }else if( (c=='b' && pVar->bytes==0 && strcmp(zType,"boolean")==0 ) + || (c=='b' && pVar->bytes==0 && strcmp(zType,"booleanString")==0 ) + || (c=='w' && strcmp(zType,"wideInt")==0) + || (c=='i' && strcmp(zType,"int")==0) + ){ + eType = SQLITE_INTEGER; + }else if( c=='d' && strcmp(zType,"double")==0 ){ + eType = SQLITE_FLOAT; + }else{ + eType = SQLITE_TEXT; + } + } + + switch( eType ){ + case SQLITE_BLOB: { + data = Tcl_GetByteArrayFromObj(pVar, &n); + sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT); + break; + } + case SQLITE_INTEGER: { + Tcl_WideInt v; + if( TCL_OK==Tcl_GetWideIntFromObj(0, pVar, &v) ){ + sqlite3_result_int64(context, v); + break; + } + /* fall-through */ + } + case SQLITE_FLOAT: { + double r; + if( TCL_OK==Tcl_GetDoubleFromObj(0, pVar, &r) ){ + sqlite3_result_double(context, r); + break; + } + /* fall-through */ + } + default: { + data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); + sqlite3_result_text64(context, (char *)data, n, SQLITE_TRANSIENT, + SQLITE_UTF8); + break; + } + } + + } +} + +#ifndef SQLITE_OMIT_AUTHORIZATION +/* +** This is the authentication function. It appends the authentication +** type code and the two arguments to zCmd[] then invokes the result +** on the interpreter. The reply is examined to determine if the +** authentication fails or succeeds. +*/ +static int auth_callback( + void *pArg, + int code, + const char *zArg1, + const char *zArg2, + const char *zArg3, + const char *zArg4 +){ + const char *zCode; + Tcl_DString str; + int rc; + const char *zReply; + /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer + ** callback is a copy of the third parameter to the + ** sqlite3_set_authorizer() interface. + */ + SqliteDb *pDb = (SqliteDb*)pArg; + if( pDb->disableAuth ) return SQLITE_OK; + + /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an + ** integer action code that specifies the particular action to be + ** authorized. */ + switch( code ){ + case SQLITE_COPY : zCode="SQLITE_COPY"; break; + case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break; + case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break; + case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break; + case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break; + case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break; + case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break; + case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break; + case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break; + case SQLITE_DELETE : zCode="SQLITE_DELETE"; break; + case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break; + case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break; + case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break; + case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break; + case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break; + case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break; + case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break; + case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break; + case SQLITE_INSERT : zCode="SQLITE_INSERT"; break; + case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break; + case SQLITE_READ : zCode="SQLITE_READ"; break; + case SQLITE_SELECT : zCode="SQLITE_SELECT"; break; + case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break; + case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break; + case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break; + case SQLITE_DETACH : zCode="SQLITE_DETACH"; break; + case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break; + case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break; + case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break; + case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break; + case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break; + case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break; + case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break; + case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break; + default : zCode="????"; break; + } + Tcl_DStringInit(&str); + Tcl_DStringAppend(&str, pDb->zAuth, -1); + Tcl_DStringAppendElement(&str, zCode); + Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : ""); + Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : ""); + Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : ""); + Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : ""); + rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str)); + Tcl_DStringFree(&str); + zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY"; + if( strcmp(zReply,"SQLITE_OK")==0 ){ + rc = SQLITE_OK; + }else if( strcmp(zReply,"SQLITE_DENY")==0 ){ + rc = SQLITE_DENY; + }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){ + rc = SQLITE_IGNORE; + }else{ + rc = 999; + } + return rc; +} +#endif /* SQLITE_OMIT_AUTHORIZATION */ + +#if 0 +/* +** This routine reads a line of text from FILE in, stores +** the text in memory obtained from malloc() and returns a pointer +** to the text. NULL is returned at end of file, or if malloc() +** fails. +** +** The interface is like "readline" but no command-line editing +** is done. +** +** copied from shell.c from '.import' command +*/ +static char *local_getline(char *zPrompt, FILE *in){ + char *zLine; + int nLine; + int n; + + nLine = 100; + zLine = malloc( nLine ); + if( zLine==0 ) return 0; + n = 0; + while( 1 ){ + if( n+100>nLine ){ + nLine = nLine*2 + 100; + zLine = realloc(zLine, nLine); + if( zLine==0 ) return 0; + } + if( fgets(&zLine[n], nLine - n, in)==0 ){ + if( n==0 ){ + free(zLine); + return 0; + } + zLine[n] = 0; + break; + } + while( zLine[n] ){ n++; } + if( n>0 && zLine[n-1]=='\n' ){ + n--; + zLine[n] = 0; + break; + } + } + zLine = realloc( zLine, n+1 ); + return zLine; +} +#endif + + +/* +** This function is part of the implementation of the command: +** +** $db transaction [-deferred|-immediate|-exclusive] SCRIPT +** +** It is invoked after evaluating the script SCRIPT to commit or rollback +** the transaction or savepoint opened by the [transaction] command. +*/ +static int SQLITE_TCLAPI DbTransPostCmd( + ClientData data[], /* data[0] is the Sqlite3Db* for $db */ + Tcl_Interp *interp, /* Tcl interpreter */ + int result /* Result of evaluating SCRIPT */ +){ + static const char *const azEnd[] = { + "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */ + "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */ + "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction", + "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */ + }; + SqliteDb *pDb = (SqliteDb*)data[0]; + int rc = result; + const char *zEnd; + + pDb->nTransaction--; + zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)]; + + pDb->disableAuth++; + if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){ + /* This is a tricky scenario to handle. The most likely cause of an + ** error is that the exec() above was an attempt to commit the + ** top-level transaction that returned SQLITE_BUSY. Or, less likely, + ** that an IO-error has occurred. In either case, throw a Tcl exception + ** and try to rollback the transaction. + ** + ** But it could also be that the user executed one or more BEGIN, + ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing + ** this method's logic. Not clear how this would be best handled. + */ + if( rc!=TCL_ERROR ){ + Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); + rc = TCL_ERROR; + } + sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0); + } + pDb->disableAuth--; + + delDatabaseRef(pDb); + return rc; +} + +/* +** Unless SQLITE_TEST is defined, this function is a simple wrapper around +** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either +** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending +** on whether or not the [db_use_legacy_prepare] command has been used to +** configure the connection. +*/ +static int dbPrepare( + SqliteDb *pDb, /* Database object */ + const char *zSql, /* SQL to compile */ + sqlite3_stmt **ppStmt, /* OUT: Prepared statement */ + const char **pzOut /* OUT: Pointer to next SQL statement */ +){ + unsigned int prepFlags = 0; +#ifdef SQLITE_TEST + if( pDb->bLegacyPrepare ){ + return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut); + } +#endif + /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT + ** flags, which uses less lookaside memory. But if the cache is small, + ** omit that flag to make full use of lookaside */ + if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT; + + return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut); +} + +/* +** Search the cache for a prepared-statement object that implements the +** first SQL statement in the buffer pointed to by parameter zIn. If +** no such prepared-statement can be found, allocate and prepare a new +** one. In either case, bind the current values of the relevant Tcl +** variables to any $var, :var or @var variables in the statement. Before +** returning, set *ppPreStmt to point to the prepared-statement object. +** +** Output parameter *pzOut is set to point to the next SQL statement in +** buffer zIn, or to the '\0' byte at the end of zIn if there is no +** next statement. +** +** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned +** and an error message loaded into interpreter pDb->interp. +*/ +static int dbPrepareAndBind( + SqliteDb *pDb, /* Database object */ + char const *zIn, /* SQL to compile */ + char const **pzOut, /* OUT: Pointer to next SQL statement */ + SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */ +){ + const char *zSql = zIn; /* Pointer to first SQL statement in zIn */ + sqlite3_stmt *pStmt = 0; /* Prepared statement object */ + SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */ + int nSql; /* Length of zSql in bytes */ + int nVar = 0; /* Number of variables in statement */ + int iParm = 0; /* Next free entry in apParm */ + char c; + int i; + int needResultReset = 0; /* Need to invoke Tcl_ResetResult() */ + int rc = SQLITE_OK; /* Value to return */ + Tcl_Interp *interp = pDb->interp; + + *ppPreStmt = 0; + + /* Trim spaces from the start of zSql and calculate the remaining length. */ + while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; } + nSql = strlen30(zSql); + + for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){ + int n = pPreStmt->nSql; + if( nSql>=n + && memcmp(pPreStmt->zSql, zSql, n)==0 + && (zSql[n]==0 || zSql[n-1]==';') + ){ + pStmt = pPreStmt->pStmt; + *pzOut = &zSql[pPreStmt->nSql]; + + /* When a prepared statement is found, unlink it from the + ** cache list. It will later be added back to the beginning + ** of the cache list in order to implement LRU replacement. + */ + if( pPreStmt->pPrev ){ + pPreStmt->pPrev->pNext = pPreStmt->pNext; + }else{ + pDb->stmtList = pPreStmt->pNext; + } + if( pPreStmt->pNext ){ + pPreStmt->pNext->pPrev = pPreStmt->pPrev; + }else{ + pDb->stmtLast = pPreStmt->pPrev; + } + pDb->nStmt--; + nVar = sqlite3_bind_parameter_count(pStmt); + break; + } + } + + /* If no prepared statement was found. Compile the SQL text. Also allocate + ** a new SqlPreparedStmt structure. */ + if( pPreStmt==0 ){ + int nByte; + + if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); + return TCL_ERROR; + } + if( pStmt==0 ){ + if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){ + /* A compile-time error in the statement. */ + Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); + return TCL_ERROR; + }else{ + /* The statement was a no-op. Continue to the next statement + ** in the SQL string. + */ + return TCL_OK; + } + } + + assert( pPreStmt==0 ); + nVar = sqlite3_bind_parameter_count(pStmt); + nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *); + pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte); + memset(pPreStmt, 0, nByte); + + pPreStmt->pStmt = pStmt; + pPreStmt->nSql = (int)(*pzOut - zSql); + pPreStmt->zSql = sqlite3_sql(pStmt); + pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1]; +#ifdef SQLITE_TEST + if( pPreStmt->zSql==0 ){ + char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1); + memcpy(zCopy, zSql, pPreStmt->nSql); + zCopy[pPreStmt->nSql] = '\0'; + pPreStmt->zSql = zCopy; + } +#endif + } + assert( pPreStmt ); + assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql ); + assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) ); + + /* Bind values to parameters that begin with $ or : */ + for(i=1; i<=nVar; i++){ + const char *zVar = sqlite3_bind_parameter_name(pStmt, i); + if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){ + Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0); + if( pVar==0 && pDb->zBindFallback!=0 ){ + Tcl_Obj *pCmd; + int rx; + pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1); + Tcl_IncrRefCount(pCmd); + Tcl_ListObjAppendElement(interp, pCmd, Tcl_NewStringObj(zVar,-1)); + if( needResultReset ) Tcl_ResetResult(interp); + needResultReset = 1; + rx = Tcl_EvalObjEx(interp, pCmd, TCL_EVAL_DIRECT); + Tcl_DecrRefCount(pCmd); + if( rx==TCL_OK ){ + pVar = Tcl_GetObjResult(interp); + }else if( rx==TCL_ERROR ){ + rc = TCL_ERROR; + break; + }else{ + pVar = 0; + } + } + if( pVar ){ + Tcl_Size n; + u8 *data; + const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); + c = zType[0]; + if( zVar[0]=='@' || + (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){ + /* Load a BLOB type if the Tcl variable is a bytearray and + ** it has no string representation or the host + ** parameter name begins with "@". */ + data = Tcl_GetByteArrayFromObj(pVar, &n); + sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC); + Tcl_IncrRefCount(pVar); + pPreStmt->apParm[iParm++] = pVar; + }else if( c=='b' && pVar->bytes==0 + && (strcmp(zType,"booleanString")==0 + || strcmp(zType,"boolean")==0) + ){ + int nn; + Tcl_GetBooleanFromObj(interp, pVar, &nn); + sqlite3_bind_int(pStmt, i, nn); + }else if( c=='d' && strcmp(zType,"double")==0 ){ + double r; + Tcl_GetDoubleFromObj(interp, pVar, &r); + sqlite3_bind_double(pStmt, i, r); + }else if( (c=='w' && strcmp(zType,"wideInt")==0) || + (c=='i' && strcmp(zType,"int")==0) ){ + Tcl_WideInt v; + Tcl_GetWideIntFromObj(interp, pVar, &v); + sqlite3_bind_int64(pStmt, i, v); + }else{ + data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); + sqlite3_bind_text64(pStmt, i, (char *)data, n, SQLITE_STATIC, + SQLITE_UTF8); + Tcl_IncrRefCount(pVar); + pPreStmt->apParm[iParm++] = pVar; + } + }else{ + sqlite3_bind_null(pStmt, i); + } + if( needResultReset ) Tcl_ResetResult(pDb->interp); + } + } + pPreStmt->nParm = iParm; + *ppPreStmt = pPreStmt; + if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp); + + return rc; +} + +/* +** Release a statement reference obtained by calling dbPrepareAndBind(). +** There should be exactly one call to this function for each call to +** dbPrepareAndBind(). +** +** If the discard parameter is non-zero, then the statement is deleted +** immediately. Otherwise it is added to the LRU list and may be returned +** by a subsequent call to dbPrepareAndBind(). +*/ +static void dbReleaseStmt( + SqliteDb *pDb, /* Database handle */ + SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */ + int discard /* True to delete (not cache) the pPreStmt */ +){ + int i; + + /* Free the bound string and blob parameters */ + for(i=0; inParm; i++){ + Tcl_DecrRefCount(pPreStmt->apParm[i]); + } + pPreStmt->nParm = 0; + + if( pDb->maxStmt<=0 || discard ){ + /* If the cache is turned off, deallocated the statement */ + dbFreeStmt(pPreStmt); + }else{ + /* Add the prepared statement to the beginning of the cache list. */ + pPreStmt->pNext = pDb->stmtList; + pPreStmt->pPrev = 0; + if( pDb->stmtList ){ + pDb->stmtList->pPrev = pPreStmt; + } + pDb->stmtList = pPreStmt; + if( pDb->stmtLast==0 ){ + assert( pDb->nStmt==0 ); + pDb->stmtLast = pPreStmt; + }else{ + assert( pDb->nStmt>0 ); + } + pDb->nStmt++; + + /* If we have too many statement in cache, remove the surplus from + ** the end of the cache list. */ + while( pDb->nStmt>pDb->maxStmt ){ + SqlPreparedStmt *pLast = pDb->stmtLast; + pDb->stmtLast = pLast->pPrev; + pDb->stmtLast->pNext = 0; + pDb->nStmt--; + dbFreeStmt(pLast); + } + } +} + +/* +** Structure used with dbEvalXXX() functions: +** +** dbEvalInit() +** dbEvalStep() +** dbEvalFinalize() +** dbEvalRowInfo() +** dbEvalColumnValue() +*/ +typedef struct DbEvalContext DbEvalContext; +struct DbEvalContext { + SqliteDb *pDb; /* Database handle */ + Tcl_Obj *pSql; /* Object holding string zSql */ + const char *zSql; /* Remaining SQL to execute */ + SqlPreparedStmt *pPreStmt; /* Current statement */ + int nCol; /* Number of columns returned by pStmt */ + int evalFlags; /* Flags used */ + Tcl_Obj *pArray; /* Name of array variable */ + Tcl_Obj **apColName; /* Array of column names */ +}; + +#define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */ + +/* +** Release any cache of column names currently held as part of +** the DbEvalContext structure passed as the first argument. +*/ +static void dbReleaseColumnNames(DbEvalContext *p){ + if( p->apColName ){ + int i; + for(i=0; inCol; i++){ + Tcl_DecrRefCount(p->apColName[i]); + } + Tcl_Free((char *)p->apColName); + p->apColName = 0; + } + p->nCol = 0; +} + +/* +** Initialize a DbEvalContext structure. +** +** If pArray is not NULL, then it contains the name of a Tcl array +** variable. The "*" member of this array is set to a list containing +** the names of the columns returned by the statement as part of each +** call to dbEvalStep(), in order from left to right. e.g. if the names +** of the returned columns are a, b and c, it does the equivalent of the +** tcl command: +** +** set ${pArray}(*) {a b c} +*/ +static void dbEvalInit( + DbEvalContext *p, /* Pointer to structure to initialize */ + SqliteDb *pDb, /* Database handle */ + Tcl_Obj *pSql, /* Object containing SQL script */ + Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */ + int evalFlags /* Flags controlling evaluation */ +){ + memset(p, 0, sizeof(DbEvalContext)); + p->pDb = pDb; + p->zSql = Tcl_GetString(pSql); + p->pSql = pSql; + Tcl_IncrRefCount(pSql); + if( pArray ){ + p->pArray = pArray; + Tcl_IncrRefCount(pArray); + } + p->evalFlags = evalFlags; + addDatabaseRef(p->pDb); +} + +/* +** Obtain information about the row that the DbEvalContext passed as the +** first argument currently points to. +*/ +static void dbEvalRowInfo( + DbEvalContext *p, /* Evaluation context */ + int *pnCol, /* OUT: Number of column names */ + Tcl_Obj ***papColName /* OUT: Array of column names */ +){ + /* Compute column names */ + if( 0==p->apColName ){ + sqlite3_stmt *pStmt = p->pPreStmt->pStmt; + int i; /* Iterator variable */ + int nCol; /* Number of columns returned by pStmt */ + Tcl_Obj **apColName = 0; /* Array of column names */ + + p->nCol = nCol = sqlite3_column_count(pStmt); + if( nCol>0 && (papColName || p->pArray) ){ + apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol ); + for(i=0; iapColName = apColName; + } + + /* If results are being stored in an array variable, then create + ** the array(*) entry for that array + */ + if( p->pArray ){ + Tcl_Interp *interp = p->pDb->interp; + Tcl_Obj *pColList = Tcl_NewObj(); + Tcl_Obj *pStar = Tcl_NewStringObj("*", -1); + + for(i=0; ipArray, pStar, pColList, 0); + Tcl_DecrRefCount(pStar); + } + } + + if( papColName ){ + *papColName = p->apColName; + } + if( pnCol ){ + *pnCol = p->nCol; + } +} + +/* +** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is +** returned, then an error message is stored in the interpreter before +** returning. +** +** A return value of TCL_OK means there is a row of data available. The +** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This +** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK +** is returned, then the SQL script has finished executing and there are +** no further rows available. This is similar to SQLITE_DONE. +*/ +static int dbEvalStep(DbEvalContext *p){ + const char *zPrevSql = 0; /* Previous value of p->zSql */ + + while( p->zSql[0] || p->pPreStmt ){ + int rc; + if( p->pPreStmt==0 ){ + zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql); + rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt); + if( rc!=TCL_OK ) return rc; + }else{ + int rcs; + SqliteDb *pDb = p->pDb; + SqlPreparedStmt *pPreStmt = p->pPreStmt; + sqlite3_stmt *pStmt = pPreStmt->pStmt; + + rcs = sqlite3_step(pStmt); + if( rcs==SQLITE_ROW ){ + return TCL_OK; + } + if( p->pArray ){ + dbEvalRowInfo(p, 0, 0); + } + rcs = sqlite3_reset(pStmt); + + pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1); + pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1); + pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1); + pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1); + dbReleaseColumnNames(p); + p->pPreStmt = 0; + + if( rcs!=SQLITE_OK ){ + /* If a run-time error occurs, report the error and stop reading + ** the SQL. */ + dbReleaseStmt(pDb, pPreStmt, 1); +#if SQLITE_TEST + if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){ + /* If the runtime error was an SQLITE_SCHEMA, and the database + ** handle is configured to use the legacy sqlite3_prepare() + ** interface, retry prepare()/step() on the same SQL statement. + ** This only happens once. If there is a second SQLITE_SCHEMA + ** error, the error will be returned to the caller. */ + p->zSql = zPrevSql; + continue; + } +#endif + Tcl_SetObjResult(pDb->interp, + Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); + return TCL_ERROR; + }else{ + dbReleaseStmt(pDb, pPreStmt, 0); + } + } + } + + /* Finished */ + return TCL_BREAK; +} + +/* +** Free all resources currently held by the DbEvalContext structure passed +** as the first argument. There should be exactly one call to this function +** for each call to dbEvalInit(). +*/ +static void dbEvalFinalize(DbEvalContext *p){ + if( p->pPreStmt ){ + sqlite3_reset(p->pPreStmt->pStmt); + dbReleaseStmt(p->pDb, p->pPreStmt, 0); + p->pPreStmt = 0; + } + if( p->pArray ){ + Tcl_DecrRefCount(p->pArray); + p->pArray = 0; + } + Tcl_DecrRefCount(p->pSql); + dbReleaseColumnNames(p); + delDatabaseRef(p->pDb); +} + +/* +** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains +** the value for the iCol'th column of the row currently pointed to by +** the DbEvalContext structure passed as the first argument. +*/ +static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){ + sqlite3_stmt *pStmt = p->pPreStmt->pStmt; + switch( sqlite3_column_type(pStmt, iCol) ){ + case SQLITE_BLOB: { + int bytes = sqlite3_column_bytes(pStmt, iCol); + const char *zBlob = sqlite3_column_blob(pStmt, iCol); + if( !zBlob ) bytes = 0; + return Tcl_NewByteArrayObj((u8*)zBlob, bytes); + } + case SQLITE_INTEGER: { + sqlite_int64 v = sqlite3_column_int64(pStmt, iCol); + if( v>=-2147483647 && v<=2147483647 ){ + return Tcl_NewIntObj((int)v); + }else{ + return Tcl_NewWideIntObj(v); + } + } + case SQLITE_FLOAT: { + return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol)); + } + case SQLITE_NULL: { + return Tcl_NewStringObj(p->pDb->zNull, -1); + } + } + + return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1); +} + +/* +** If using Tcl version 8.6 or greater, use the NR functions to avoid +** recursive evaluation of scripts by the [db eval] and [db trans] +** commands. Even if the headers used while compiling the extension +** are 8.6 or newer, the code still tests the Tcl version at runtime. +** This allows stubs-enabled builds to be used with older Tcl libraries. +*/ +#if TCL_MAJOR_VERSION>8 || !defined(TCL_MINOR_VERSION) \ + || TCL_MINOR_VERSION>=6 +# define SQLITE_TCL_NRE 1 +static int DbUseNre(void){ + int major, minor; + Tcl_GetVersion(&major, &minor, 0, 0); + return( (major==8 && minor>=6) || major>8 ); +} +#else +/* +** Compiling using headers earlier than 8.6. In this case NR cannot be +** used, so DbUseNre() to always return zero. Add #defines for the other +** Tcl_NRxxx() functions to prevent them from causing compilation errors, +** even though the only invocations of them are within conditional blocks +** of the form: +** +** if( DbUseNre() ) { ... } +*/ +# define SQLITE_TCL_NRE 0 +# define DbUseNre() 0 +# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0 +# define Tcl_NREvalObj(a,b,c) 0 +# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0 +#endif + +/* +** This function is part of the implementation of the command: +** +** $db eval SQL ?ARRAYNAME? SCRIPT +*/ +static int SQLITE_TCLAPI DbEvalNextCmd( + ClientData data[], /* data[0] is the (DbEvalContext*) */ + Tcl_Interp *interp, /* Tcl interpreter */ + int result /* Result so far */ +){ + int rc = result; /* Return code */ + + /* The first element of the data[] array is a pointer to a DbEvalContext + ** structure allocated using Tcl_Alloc(). The second element of data[] + ** is a pointer to a Tcl_Obj containing the script to run for each row + ** returned by the queries encapsulated in data[0]. */ + DbEvalContext *p = (DbEvalContext *)data[0]; + Tcl_Obj *pScript = (Tcl_Obj *)data[1]; + Tcl_Obj *pArray = p->pArray; + + while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){ + int i; + int nCol; + Tcl_Obj **apColName; + dbEvalRowInfo(p, &nCol, &apColName); + for(i=0; ievalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0 + && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL + ){ + Tcl_UnsetVar2(interp, Tcl_GetString(pArray), + Tcl_GetString(apColName[i]), 0); + }else{ + Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0); + } + } + + /* The required interpreter variables are now populated with the data + ** from the current row. If using NRE, schedule callbacks to evaluate + ** script pScript, then to invoke this function again to fetch the next + ** row (or clean up if there is no next row or the script throws an + ** exception). After scheduling the callbacks, return control to the + ** caller. + ** + ** If not using NRE, evaluate pScript directly and continue with the + ** next iteration of this while(...) loop. */ + if( DbUseNre() ){ + Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0); + return Tcl_NREvalObj(interp, pScript, 0); + }else{ + rc = Tcl_EvalObjEx(interp, pScript, 0); + } + } + + Tcl_DecrRefCount(pScript); + dbEvalFinalize(p); + Tcl_Free((char *)p); + + if( rc==TCL_OK || rc==TCL_BREAK ){ + Tcl_ResetResult(interp); + rc = TCL_OK; + } + return rc; +} + +/* +** This function is used by the implementations of the following database +** handle sub-commands: +** +** $db update_hook ?SCRIPT? +** $db wal_hook ?SCRIPT? +** $db commit_hook ?SCRIPT? +** $db preupdate hook ?SCRIPT? +*/ +static void DbHookCmd( + Tcl_Interp *interp, /* Tcl interpreter */ + SqliteDb *pDb, /* Database handle */ + Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */ + Tcl_Obj **ppHook /* Pointer to member of SqliteDb */ +){ + sqlite3 *db = pDb->db; + + if( *ppHook ){ + Tcl_SetObjResult(interp, *ppHook); + if( pArg ){ + Tcl_DecrRefCount(*ppHook); + *ppHook = 0; + } + } + if( pArg ){ + assert( !(*ppHook) ); + if( Tcl_GetString(pArg)[0] ){ + *ppHook = pArg; + Tcl_IncrRefCount(*ppHook); + } + } + +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK + sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb); +#endif + sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb); + sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb); + sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb); +} + +/* +** The "sqlite" command below creates a new Tcl command for each +** connection it opens to an SQLite database. This routine is invoked +** whenever one of those connection-specific commands is executed +** in Tcl. For example, if you run Tcl code like this: +** +** sqlite3 db1 "my_database" +** db1 close +** +** The first command opens a connection to the "my_database" database +** and calls that connection "db1". The second command causes this +** subroutine to be invoked. +*/ +static int SQLITE_TCLAPI DbObjCmd( + void *cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + SqliteDb *pDb = (SqliteDb*)cd; + int choice; + int rc = TCL_OK; + static const char *DB_strs[] = { + "authorizer", "backup", "bind_fallback", + "busy", "cache", "changes", + "close", "collate", "collation_needed", + "commit_hook", "complete", "config", + "copy", "deserialize", "enable_load_extension", + "errorcode", "erroroffset", "eval", + "exists", "function", "incrblob", + "interrupt", "last_insert_rowid", "nullvalue", + "onecolumn", "preupdate", "profile", + "progress", "rekey", "restore", + "rollback_hook", "serialize", "status", + "timeout", "total_changes", "trace", + "trace_v2", "transaction", "unlock_notify", + "update_hook", "version", "wal_hook", + 0 + }; + enum DB_enum { + DB_AUTHORIZER, DB_BACKUP, DB_BIND_FALLBACK, + DB_BUSY, DB_CACHE, DB_CHANGES, + DB_CLOSE, DB_COLLATE, DB_COLLATION_NEEDED, + DB_COMMIT_HOOK, DB_COMPLETE, DB_CONFIG, + DB_COPY, DB_DESERIALIZE, DB_ENABLE_LOAD_EXTENSION, + DB_ERRORCODE, DB_ERROROFFSET, DB_EVAL, + DB_EXISTS, DB_FUNCTION, DB_INCRBLOB, + DB_INTERRUPT, DB_LAST_INSERT_ROWID, DB_NULLVALUE, + DB_ONECOLUMN, DB_PREUPDATE, DB_PROFILE, + DB_PROGRESS, DB_REKEY, DB_RESTORE, + DB_ROLLBACK_HOOK, DB_SERIALIZE, DB_STATUS, + DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE, + DB_TRACE_V2, DB_TRANSACTION, DB_UNLOCK_NOTIFY, + DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK, + }; + /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */ + + if( objc<2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ..."); + return TCL_ERROR; + } + if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){ + return TCL_ERROR; + } + + switch( (enum DB_enum)choice ){ + + /* $db authorizer ?CALLBACK? + ** + ** Invoke the given callback to authorize each SQL operation as it is + ** compiled. 5 arguments are appended to the callback before it is + ** invoked: + ** + ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...) + ** (2) First descriptive name (depends on authorization type) + ** (3) Second descriptive name + ** (4) Name of the database (ex: "main", "temp") + ** (5) Name of trigger that is doing the access + ** + ** The callback should return one of the following strings: SQLITE_OK, + ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error. + ** + ** If this method is invoked with no arguments, the current authorization + ** callback string is returned. + */ + case DB_AUTHORIZER: { +#ifdef SQLITE_OMIT_AUTHORIZATION + Tcl_AppendResult(interp, "authorization not available in this build", + (char*)0); + return TCL_ERROR; +#else + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zAuth ){ + Tcl_AppendResult(interp, pDb->zAuth, (char*)0); + } + }else{ + char *zAuth; + Tcl_Size len; + if( pDb->zAuth ){ + Tcl_Free(pDb->zAuth); + } + zAuth = Tcl_GetStringFromObj(objv[2], &len); + if( zAuth && len>0 ){ + pDb->zAuth = Tcl_Alloc( len + 1 ); + memcpy(pDb->zAuth, zAuth, len+1); + }else{ + pDb->zAuth = 0; + } + if( pDb->zAuth ){ + typedef int (*sqlite3_auth_cb)( + void*,int,const char*,const char*, + const char*,const char*); + pDb->interp = interp; + sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb); + }else{ + sqlite3_set_authorizer(pDb->db, 0, 0); + } + } +#endif + break; + } + + /* $db backup ?DATABASE? FILENAME + ** + ** Open or create a database file named FILENAME. Transfer the + ** content of local database DATABASE (default: "main") into the + ** FILENAME database. + */ + case DB_BACKUP: { + const char *zDestFile; + const char *zSrcDb; + sqlite3 *pDest; + sqlite3_backup *pBackup; + + if( objc==3 ){ + zSrcDb = "main"; + zDestFile = Tcl_GetString(objv[2]); + }else if( objc==4 ){ + zSrcDb = Tcl_GetString(objv[2]); + zDestFile = Tcl_GetString(objv[3]); + }else{ + Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); + return TCL_ERROR; + } + rc = sqlite3_open_v2(zDestFile, &pDest, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "cannot open target database: ", + sqlite3_errmsg(pDest), (char*)0); + sqlite3_close(pDest); + return TCL_ERROR; + } + pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb); + if( pBackup==0 ){ + Tcl_AppendResult(interp, "backup failed: ", + sqlite3_errmsg(pDest), (char*)0); + sqlite3_close(pDest); + return TCL_ERROR; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = TCL_OK; + }else{ + Tcl_AppendResult(interp, "backup failed: ", + sqlite3_errmsg(pDest), (char*)0); + rc = TCL_ERROR; + } + sqlite3_close(pDest); + break; + } + + /* $db bind_fallback ?CALLBACK? + ** + ** When resolving bind parameters in an SQL statement, if the parameter + ** cannot be associated with a TCL variable then invoke CALLBACK with a + ** single argument that is the name of the parameter and use the return + ** value of the CALLBACK as the binding. If CALLBACK returns something + ** other than TCL_OK or TCL_ERROR then bind a NULL. + ** + ** If CALLBACK is an empty string, then revert to the default behavior + ** which is to set the binding to NULL. + ** + ** If CALLBACK returns an error, that causes the statement execution to + ** abort. Hence, to configure a connection so that it throws an error + ** on an attempt to bind an unknown variable, do something like this: + ** + ** proc bind_error {name} {error "no such variable: $name"} + ** db bind_fallback bind_error + */ + case DB_BIND_FALLBACK: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zBindFallback ){ + Tcl_AppendResult(interp, pDb->zBindFallback, (char*)0); + } + }else{ + char *zCallback; + Tcl_Size len; + if( pDb->zBindFallback ){ + Tcl_Free(pDb->zBindFallback); + } + zCallback = Tcl_GetStringFromObj(objv[2], &len); + if( zCallback && len>0 ){ + pDb->zBindFallback = Tcl_Alloc( len + 1 ); + memcpy(pDb->zBindFallback, zCallback, len+1); + }else{ + pDb->zBindFallback = 0; + } + } + break; + } + + /* $db busy ?CALLBACK? + ** + ** Invoke the given callback if an SQL statement attempts to open + ** a locked database file. + */ + case DB_BUSY: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zBusy ){ + Tcl_AppendResult(interp, pDb->zBusy, (char*)0); + } + }else{ + char *zBusy; + Tcl_Size len; + if( pDb->zBusy ){ + Tcl_Free(pDb->zBusy); + } + zBusy = Tcl_GetStringFromObj(objv[2], &len); + if( zBusy && len>0 ){ + pDb->zBusy = Tcl_Alloc( len + 1 ); + memcpy(pDb->zBusy, zBusy, len+1); + }else{ + pDb->zBusy = 0; + } + if( pDb->zBusy ){ + pDb->interp = interp; + sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb); + }else{ + sqlite3_busy_handler(pDb->db, 0, 0); + } + } + break; + } + + /* $db cache flush + ** $db cache size n + ** + ** Flush the prepared statement cache, or set the maximum number of + ** cached statements. + */ + case DB_CACHE: { + char *subCmd; + int n; + + if( objc<=2 ){ + Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?"); + return TCL_ERROR; + } + subCmd = Tcl_GetStringFromObj( objv[2], 0 ); + if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){ + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "flush"); + return TCL_ERROR; + }else{ + flushStmtCache( pDb ); + } + }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){ + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "size n"); + return TCL_ERROR; + }else{ + if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){ + Tcl_AppendResult( interp, "cannot convert \"", + Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0); + return TCL_ERROR; + }else{ + if( n<0 ){ + flushStmtCache( pDb ); + n = 0; + }else if( n>MAX_PREPARED_STMTS ){ + n = MAX_PREPARED_STMTS; + } + pDb->maxStmt = n; + } + } + }else{ + Tcl_AppendResult( interp, "bad option \"", + Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", + (char*)0); + return TCL_ERROR; + } + break; + } + + /* $db changes + ** + ** Return the number of rows that were modified, inserted, or deleted by + ** the most recent INSERT, UPDATE or DELETE statement, not including + ** any changes made by trigger programs. + */ + case DB_CHANGES: { + Tcl_Obj *pResult; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + pResult = Tcl_GetObjResult(interp); + Tcl_SetWideIntObj(pResult, sqlite3_changes64(pDb->db)); + break; + } + + /* $db close + ** + ** Shutdown the database + */ + case DB_CLOSE: { + Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0)); + break; + } + + /* + ** $db collate NAME SCRIPT + ** + ** Create a new SQL collation function called NAME. Whenever + ** that function is called, invoke SCRIPT to evaluate the function. + */ + case DB_COLLATE: { + SqlCollate *pCollate; + char *zName; + char *zScript; + Tcl_Size nScript; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT"); + return TCL_ERROR; + } + zName = Tcl_GetStringFromObj(objv[2], 0); + zScript = Tcl_GetStringFromObj(objv[3], &nScript); + pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 ); + if( pCollate==0 ) return TCL_ERROR; + pCollate->interp = interp; + pCollate->pNext = pDb->pCollate; + pCollate->zScript = (char*)&pCollate[1]; + pDb->pCollate = pCollate; + memcpy(pCollate->zScript, zScript, nScript+1); + if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8, + pCollate, tclSqlCollate) ){ + Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); + return TCL_ERROR; + } + break; + } + + /* + ** $db collation_needed SCRIPT + ** + ** Create a new SQL collation function called NAME. Whenever + ** that function is called, invoke SCRIPT to evaluate the function. + */ + case DB_COLLATION_NEEDED: { + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT"); + return TCL_ERROR; + } + if( pDb->pCollateNeeded ){ + Tcl_DecrRefCount(pDb->pCollateNeeded); + } + pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]); + Tcl_IncrRefCount(pDb->pCollateNeeded); + sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded); + break; + } + + /* $db commit_hook ?CALLBACK? + ** + ** Invoke the given callback just before committing every SQL transaction. + ** If the callback throws an exception or returns non-zero, then the + ** transaction is aborted. If CALLBACK is an empty string, the callback + ** is disabled. + */ + case DB_COMMIT_HOOK: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zCommit ){ + Tcl_AppendResult(interp, pDb->zCommit, (char*)0); + } + }else{ + const char *zCommit; + Tcl_Size len; + if( pDb->zCommit ){ + Tcl_Free(pDb->zCommit); + } + zCommit = Tcl_GetStringFromObj(objv[2], &len); + if( zCommit && len>0 ){ + pDb->zCommit = Tcl_Alloc( len + 1 ); + memcpy(pDb->zCommit, zCommit, len+1); + }else{ + pDb->zCommit = 0; + } + if( pDb->zCommit ){ + pDb->interp = interp; + sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb); + }else{ + sqlite3_commit_hook(pDb->db, 0, 0); + } + } + break; + } + + /* $db complete SQL + ** + ** Return TRUE if SQL is a complete SQL statement. Return FALSE if + ** additional lines of input are needed. This is similar to the + ** built-in "info complete" command of Tcl. + */ + case DB_COMPLETE: { +#ifndef SQLITE_OMIT_COMPLETE + Tcl_Obj *pResult; + int isComplete; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SQL"); + return TCL_ERROR; + } + isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) ); + pResult = Tcl_GetObjResult(interp); + Tcl_SetBooleanObj(pResult, isComplete); +#endif + break; + } + + /* $db config ?OPTION? ?BOOLEAN? + ** + ** Configure the database connection using the sqlite3_db_config() + ** interface. + */ + case DB_CONFIG: { + static const struct DbConfigChoices { + const char *zName; + int op; + } aDbConfig[] = { + { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, + { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, + { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, + { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, + { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, + { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, + { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, + { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, + { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, + { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, + { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, + { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, + { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, + { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, + { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, + { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, + }; + Tcl_Obj *pResult; + int ii; + if( objc>4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?OPTION? ?BOOLEAN?"); + return TCL_ERROR; + } + if( objc==2 ){ + /* With no arguments, list all configuration options and with the + ** current value */ + pResult = Tcl_NewListObj(0,0); + for(ii=0; iidb, aDbConfig[ii].op, -1, &v); + Tcl_ListObjAppendElement(interp, pResult, + Tcl_NewStringObj(aDbConfig[ii].zName,-1)); + Tcl_ListObjAppendElement(interp, pResult, + Tcl_NewIntObj(v)); + } + }else{ + const char *zOpt = Tcl_GetString(objv[2]); + int onoff = -1; + int v = 0; + if( zOpt[0]=='-' ) zOpt++; + for(ii=0; ii=sizeof(aDbConfig)/sizeof(aDbConfig[0]) ){ + Tcl_AppendResult(interp, "unknown config option: \"", zOpt, + "\"", (void*)0); + return TCL_ERROR; + } + if( objc==4 ){ + if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ){ + return TCL_ERROR; + } + } + sqlite3_db_config(pDb->db, aDbConfig[ii].op, onoff, &v); + pResult = Tcl_NewIntObj(v); + } + Tcl_SetObjResult(interp, pResult); + break; + } + + /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR? + ** + ** Copy data into table from filename, optionally using SEPARATOR + ** as column separators. If a column contains a null string, or the + ** value of NULLINDICATOR, a NULL is inserted for the column. + ** conflict-algorithm is one of the sqlite conflict algorithms: + ** rollback, abort, fail, ignore, replace + ** On success, return the number of lines processed, not necessarily same + ** as 'db changes' due to conflict-algorithm selected. + ** + ** This code is basically an implementation/enhancement of + ** the sqlite3 shell.c ".import" command. + ** + ** This command usage is equivalent to the sqlite2.x COPY statement, + ** which imports file data into a table using the PostgreSQL COPY file format: + ** $db copy $conflict_algorithm $table_name $filename \t \\N + */ + case DB_COPY: { + char *zTable; /* Insert data into this table */ + char *zFile; /* The file from which to extract data */ + char *zConflict; /* The conflict algorithm to use */ + sqlite3_stmt *pStmt; /* A statement */ + int nCol; /* Number of columns in the table */ + int nByte; /* Number of bytes in an SQL string */ + int i, j; /* Loop counters */ + int nSep; /* Number of bytes in zSep[] */ + int nNull; /* Number of bytes in zNull[] */ + char *zSql; /* An SQL statement */ + char *zLine; /* A single line of input from the file */ + char **azCol; /* zLine[] broken up into columns */ + const char *zCommit; /* How to commit changes */ + Tcl_Channel in; /* The input file */ + int lineno = 0; /* Line number of input file */ + char zLineNum[80]; /* Line number print buffer */ + Tcl_Obj *str; + Tcl_Obj *pResult; /* interp result */ + + const char *zSep; + const char *zNull; + if( objc<5 || objc>7 ){ + Tcl_WrongNumArgs(interp, 2, objv, + "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?"); + return TCL_ERROR; + } + if( objc>=6 ){ + zSep = Tcl_GetStringFromObj(objv[5], 0); + }else{ + zSep = "\t"; + } + if( objc>=7 ){ + zNull = Tcl_GetStringFromObj(objv[6], 0); + }else{ + zNull = ""; + } + zConflict = Tcl_GetStringFromObj(objv[2], 0); + zTable = Tcl_GetStringFromObj(objv[3], 0); + zFile = Tcl_GetStringFromObj(objv[4], 0); + nSep = strlen30(zSep); + nNull = strlen30(zNull); + if( nSep==0 ){ + Tcl_AppendResult(interp,"Error: non-null separator required for copy", + (char*)0); + return TCL_ERROR; + } + if(strcmp(zConflict, "rollback") != 0 && + strcmp(zConflict, "abort" ) != 0 && + strcmp(zConflict, "fail" ) != 0 && + strcmp(zConflict, "ignore" ) != 0 && + strcmp(zConflict, "replace" ) != 0 ) { + Tcl_AppendResult(interp, "Error: \"", zConflict, + "\", conflict-algorithm must be one of: rollback, " + "abort, fail, ignore, or replace", (char*)0); + return TCL_ERROR; + } + zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable); + if( zSql==0 ){ + Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0); + return TCL_ERROR; + } + nByte = strlen30(zSql); + rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc ){ + Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0); + nCol = 0; + }else{ + nCol = sqlite3_column_count(pStmt); + } + sqlite3_finalize(pStmt); + if( nCol==0 ) { + return TCL_ERROR; + } + zSql = malloc( nByte + 50 + nCol*2 ); + if( zSql==0 ) { + Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0); + return TCL_ERROR; + } + sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?", + zConflict, zTable); + j = strlen30(zSql); + for(i=1; idb, zSql, -1, &pStmt, 0); + free(zSql); + if( rc ){ + Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0); + sqlite3_finalize(pStmt); + return TCL_ERROR; + } + in = Tcl_OpenFileChannel(interp, zFile, "rb", 0666); + if( in==0 ){ + sqlite3_finalize(pStmt); + return TCL_ERROR; + } + Tcl_SetChannelOption(NULL, in, "-translation", "auto"); + azCol = malloc( sizeof(azCol[0])*(nCol+1) ); + if( azCol==0 ) { + Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0); + Tcl_Close(interp, in); + return TCL_ERROR; + } + str = Tcl_NewObj(); + Tcl_IncrRefCount(str); + (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0); + zCommit = "COMMIT"; + while( Tcl_GetsObj(in, str)>=0 ) { + char *z; + Tcl_Size byteLen; + lineno++; + zLine = (char *)Tcl_GetByteArrayFromObj(str, &byteLen); + azCol[0] = zLine; + for(i=0, z=zLine; *z; z++){ + if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){ + *z = 0; + i++; + if( i0 && strcmp(azCol[i], zNull)==0) + || strlen30(azCol[i])==0 + ){ + sqlite3_bind_null(pStmt, i+1); + }else{ + sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC); + } + } + sqlite3_step(pStmt); + rc = sqlite3_reset(pStmt); + Tcl_SetObjLength(str, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0); + zCommit = "ROLLBACK"; + break; + } + } + Tcl_DecrRefCount(str); + free(azCol); + Tcl_Close(interp, in); + sqlite3_finalize(pStmt); + (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0); + + if( zCommit[0] == 'C' ){ + /* success, set result as number of lines processed */ + pResult = Tcl_GetObjResult(interp); + Tcl_SetIntObj(pResult, lineno); + rc = TCL_OK; + }else{ + /* failure, append lineno where failed */ + sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno); + Tcl_AppendResult(interp,", failed while processing line: ",zLineNum, + (char*)0); + rc = TCL_ERROR; + } + break; + } + + /* + ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE + ** + ** Reopen DATABASE (default "main") using the content in $VALUE + */ + case DB_DESERIALIZE: { +#ifdef SQLITE_OMIT_DESERIALIZE + Tcl_AppendResult(interp, "MEMDB not available in this build", + (char*)0); + rc = TCL_ERROR; +#else + const char *zSchema = 0; + Tcl_Obj *pValue = 0; + unsigned char *pBA; + unsigned char *pData; + Tcl_Size len; + int xrc; + sqlite3_int64 mxSize = 0; + int i; + int isReadonly = 0; + + + if( objc<3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE"); + rc = TCL_ERROR; + break; + } + for(i=2; i0 ){ + Tcl_AppendResult(interp, "out of memory", (char*)0); + rc = TCL_ERROR; + }else{ + int flags; + if( len>0 ) memcpy(pData, pBA, len); + if( isReadonly ){ + flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY; + }else{ + flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE; + } + xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags); + if( xrc ){ + Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0); + rc = TCL_ERROR; + } + if( mxSize>0 ){ + sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize); + } + } +deserialize_error: +#endif + break; + } + + /* + ** $db enable_load_extension BOOLEAN + ** + ** Turn the extension loading feature on or off. It if off by + ** default. + */ + case DB_ENABLE_LOAD_EXTENSION: { +#ifndef SQLITE_OMIT_LOAD_EXTENSION + int onoff; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN"); + return TCL_ERROR; + } + if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){ + return TCL_ERROR; + } + sqlite3_enable_load_extension(pDb->db, onoff); + break; +#else + Tcl_AppendResult(interp, "extension loading is turned off at compile-time", + (char*)0); + return TCL_ERROR; +#endif + } + + /* + ** $db errorcode + ** + ** Return the numeric error code that was returned by the most recent + ** call to sqlite3_exec(). + */ + case DB_ERRORCODE: { + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db))); + break; + } + + /* + ** $db erroroffset + ** + ** Return the numeric error code that was returned by the most recent + ** call to sqlite3_exec(). + */ + case DB_ERROROFFSET: { + Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_error_offset(pDb->db))); + break; + } + + /* + ** $db exists $sql + ** $db onecolumn $sql + ** + ** The onecolumn method is the equivalent of: + ** lindex [$db eval $sql] 0 + */ + case DB_EXISTS: + case DB_ONECOLUMN: { + Tcl_Obj *pResult = 0; + DbEvalContext sEval; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SQL"); + return TCL_ERROR; + } + + dbEvalInit(&sEval, pDb, objv[2], 0, 0); + rc = dbEvalStep(&sEval); + if( choice==DB_ONECOLUMN ){ + if( rc==TCL_OK ){ + pResult = dbEvalColumnValue(&sEval, 0); + }else if( rc==TCL_BREAK ){ + Tcl_ResetResult(interp); + } + }else if( rc==TCL_BREAK || rc==TCL_OK ){ + pResult = Tcl_NewBooleanObj(rc==TCL_OK); + } + dbEvalFinalize(&sEval); + if( pResult ) Tcl_SetObjResult(interp, pResult); + + if( rc==TCL_BREAK ){ + rc = TCL_OK; + } + break; + } + + /* + ** $db eval ?options? $sql ?array? ?{ ...code... }? + ** + ** The SQL statement in $sql is evaluated. For each row, the values are + ** placed in elements of the array named "array" and ...code... is executed. + ** If "array" and "code" are omitted, then no callback is every invoked. + ** If "array" is an empty string, then the values are placed in variables + ** that have the same name as the fields extracted by the query. + */ + case DB_EVAL: { + int evalFlags = 0; + const char *zOpt; + while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){ + if( strcmp(zOpt, "-withoutnulls")==0 ){ + evalFlags |= SQLITE_EVAL_WITHOUTNULLS; + } + else{ + Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0); + return TCL_ERROR; + } + objc--; + objv++; + } + if( objc<3 || objc>5 ){ + Tcl_WrongNumArgs(interp, 2, objv, + "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?"); + return TCL_ERROR; + } + + if( objc==3 ){ + DbEvalContext sEval; + Tcl_Obj *pRet = Tcl_NewObj(); + Tcl_IncrRefCount(pRet); + dbEvalInit(&sEval, pDb, objv[2], 0, 0); + while( TCL_OK==(rc = dbEvalStep(&sEval)) ){ + int i; + int nCol; + dbEvalRowInfo(&sEval, &nCol, 0); + for(i=0; i=5 && *(char *)Tcl_GetString(objv[3]) ){ + pArray = objv[3]; + } + pScript = objv[objc-1]; + Tcl_IncrRefCount(pScript); + + p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext)); + dbEvalInit(p, pDb, objv[2], pArray, evalFlags); + + cd2[0] = (void *)p; + cd2[1] = (void *)pScript; + rc = DbEvalNextCmd(cd2, interp, TCL_OK); + } + break; + } + + /* + ** $db function NAME [OPTIONS] SCRIPT + ** + ** Create a new SQL function called NAME. Whenever that function is + ** called, invoke SCRIPT to evaluate the function. + ** + ** Options: + ** --argcount N Function has exactly N arguments + ** --deterministic The function is pure + ** --directonly Prohibit use inside triggers and views + ** --innocuous Has no side effects or information leaks + ** --returntype TYPE Specify the return type of the function + */ + case DB_FUNCTION: { + int flags = SQLITE_UTF8; + SqlFunc *pFunc; + Tcl_Obj *pScript; + char *zName; + int nArg = -1; + int i; + int eType = SQLITE_NULL; + if( objc<4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT"); + return TCL_ERROR; + } + for(i=3; i<(objc-1); i++){ + const char *z = Tcl_GetString(objv[i]); + int n = strlen30(z); + if( n>1 && strncmp(z, "-argcount",n)==0 ){ + if( i==(objc-2) ){ + Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR; + if( nArg<0 ){ + Tcl_AppendResult(interp, "number of arguments must be non-negative", + (char*)0); + return TCL_ERROR; + } + i++; + }else + if( n>1 && strncmp(z, "-deterministic",n)==0 ){ + flags |= SQLITE_DETERMINISTIC; + }else + if( n>1 && strncmp(z, "-directonly",n)==0 ){ + flags |= SQLITE_DIRECTONLY; + }else + if( n>1 && strncmp(z, "-innocuous",n)==0 ){ + flags |= SQLITE_INNOCUOUS; + }else + if( n>1 && strncmp(z, "-returntype", n)==0 ){ + const char *azType[] = {"integer", "real", "text", "blob", "any", 0}; + assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 ); + assert( SQLITE_BLOB==4 && SQLITE_NULL==5 ); + if( i==(objc-2) ){ + Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0); + return TCL_ERROR; + } + i++; + if( Tcl_GetIndexFromObj(interp, objv[i], azType, "type", 0, &eType) ){ + return TCL_ERROR; + } + eType++; + }else{ + Tcl_AppendResult(interp, "bad option \"", z, + "\": must be -argcount, -deterministic, -directonly," + " -innocuous, or -returntype", (char*)0 + ); + return TCL_ERROR; + } + } + + pScript = objv[objc-1]; + zName = Tcl_GetStringFromObj(objv[2], 0); + pFunc = findSqlFunc(pDb, zName); + if( pFunc==0 ) return TCL_ERROR; + if( pFunc->pScript ){ + Tcl_DecrRefCount(pFunc->pScript); + } + pFunc->pScript = pScript; + Tcl_IncrRefCount(pScript); + pFunc->useEvalObjv = safeToUseEvalObjv(pScript); + pFunc->eType = eType; + rc = sqlite3_create_function(pDb->db, zName, nArg, flags, + pFunc, tclSqlFunc, 0, 0); + if( rc!=SQLITE_OK ){ + rc = TCL_ERROR; + Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); + } + break; + } + + /* + ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID + */ + case DB_INCRBLOB: { +#ifdef SQLITE_OMIT_INCRBLOB + Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0); + return TCL_ERROR; +#else + int isReadonly = 0; + const char *zDb = "main"; + const char *zTable; + const char *zColumn; + Tcl_WideInt iRow; + + /* Check for the -readonly option */ + if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){ + isReadonly = 1; + } + + if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){ + Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID"); + return TCL_ERROR; + } + + if( objc==(6+isReadonly) ){ + zDb = Tcl_GetString(objv[2+isReadonly]); + } + zTable = Tcl_GetString(objv[objc-3]); + zColumn = Tcl_GetString(objv[objc-2]); + rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow); + + if( rc==TCL_OK ){ + rc = createIncrblobChannel( + interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly + ); + } +#endif + break; + } + + /* + ** $db interrupt + ** + ** Interrupt the execution of the inner-most SQL interpreter. This + ** causes the SQL statement to return an error of SQLITE_INTERRUPT. + */ + case DB_INTERRUPT: { + sqlite3_interrupt(pDb->db); + break; + } + + /* + ** $db nullvalue ?STRING? + ** + ** Change text used when a NULL comes back from the database. If ?STRING? + ** is not present, then the current string used for NULL is returned. + ** If STRING is present, then STRING is returned. + ** + */ + case DB_NULLVALUE: { + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE"); + return TCL_ERROR; + } + if( objc==3 ){ + Tcl_Size len; + char *zNull = Tcl_GetStringFromObj(objv[2], &len); + if( pDb->zNull ){ + Tcl_Free(pDb->zNull); + } + if( zNull && len>0 ){ + pDb->zNull = Tcl_Alloc( len + 1 ); + memcpy(pDb->zNull, zNull, len); + pDb->zNull[len] = '\0'; + }else{ + pDb->zNull = 0; + } + } + Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1)); + break; + } + + /* + ** $db last_insert_rowid + ** + ** Return an integer which is the ROWID for the most recent insert. + */ + case DB_LAST_INSERT_ROWID: { + Tcl_Obj *pResult; + Tcl_WideInt rowid; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + rowid = sqlite3_last_insert_rowid(pDb->db); + pResult = Tcl_GetObjResult(interp); + Tcl_SetWideIntObj(pResult, rowid); + break; + } + + /* + ** The DB_ONECOLUMN method is implemented together with DB_EXISTS. + */ + + /* $db progress ?N CALLBACK? + ** + ** Invoke the given callback every N virtual machine opcodes while executing + ** queries. + */ + case DB_PROGRESS: { + if( objc==2 ){ + if( pDb->zProgress ){ + Tcl_AppendResult(interp, pDb->zProgress, (char*)0); + } +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + sqlite3_progress_handler(pDb->db, 0, 0, 0); +#endif + }else if( objc==4 ){ + char *zProgress; + Tcl_Size len; + int N; + if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){ + return TCL_ERROR; + }; + if( pDb->zProgress ){ + Tcl_Free(pDb->zProgress); + } + zProgress = Tcl_GetStringFromObj(objv[3], &len); + if( zProgress && len>0 ){ + pDb->zProgress = Tcl_Alloc( len + 1 ); + memcpy(pDb->zProgress, zProgress, len+1); + }else{ + pDb->zProgress = 0; + } +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + if( pDb->zProgress ){ + pDb->interp = interp; + sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb); + }else{ + sqlite3_progress_handler(pDb->db, 0, 0, 0); + } +#endif + }else{ + Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK"); + return TCL_ERROR; + } + break; + } + + /* $db profile ?CALLBACK? + ** + ** Make arrangements to invoke the CALLBACK routine after each SQL statement + ** that has run. The text of the SQL and the amount of elapse time are + ** appended to CALLBACK before the script is run. + */ + case DB_PROFILE: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zProfile ){ + Tcl_AppendResult(interp, pDb->zProfile, (char*)0); + } + }else{ + char *zProfile; + Tcl_Size len; + if( pDb->zProfile ){ + Tcl_Free(pDb->zProfile); + } + zProfile = Tcl_GetStringFromObj(objv[2], &len); + if( zProfile && len>0 ){ + pDb->zProfile = Tcl_Alloc( len + 1 ); + memcpy(pDb->zProfile, zProfile, len+1); + }else{ + pDb->zProfile = 0; + } +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ + !defined(SQLITE_OMIT_DEPRECATED) + if( pDb->zProfile ){ + pDb->interp = interp; + sqlite3_profile(pDb->db, DbProfileHandler, pDb); + }else{ + sqlite3_profile(pDb->db, 0, 0); + } +#endif + } + break; + } + + /* + ** $db rekey KEY + ** + ** Change the encryption key on the currently open database. + */ + case DB_REKEY: { + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "KEY"); + return TCL_ERROR; + } + break; + } + + /* $db restore ?DATABASE? FILENAME + ** + ** Open a database file named FILENAME. Transfer the content + ** of FILENAME into the local database DATABASE (default: "main"). + */ + case DB_RESTORE: { + const char *zSrcFile; + const char *zDestDb; + sqlite3 *pSrc; + sqlite3_backup *pBackup; + int nTimeout = 0; + + if( objc==3 ){ + zDestDb = "main"; + zSrcFile = Tcl_GetString(objv[2]); + }else if( objc==4 ){ + zDestDb = Tcl_GetString(objv[2]); + zSrcFile = Tcl_GetString(objv[3]); + }else{ + Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); + return TCL_ERROR; + } + rc = sqlite3_open_v2(zSrcFile, &pSrc, + SQLITE_OPEN_READONLY | pDb->openFlags, 0); + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, "cannot open source database: ", + sqlite3_errmsg(pSrc), (char*)0); + sqlite3_close(pSrc); + return TCL_ERROR; + } + pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main"); + if( pBackup==0 ){ + Tcl_AppendResult(interp, "restore failed: ", + sqlite3_errmsg(pDb->db), (char*)0); + sqlite3_close(pSrc); + return TCL_ERROR; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK + || rc==SQLITE_BUSY ){ + if( rc==SQLITE_BUSY ){ + if( nTimeout++ >= 3 ) break; + sqlite3_sleep(100); + } + } + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = TCL_OK; + }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ + Tcl_AppendResult(interp, "restore failed: source database busy", + (char*)0); + rc = TCL_ERROR; + }else{ + Tcl_AppendResult(interp, "restore failed: ", + sqlite3_errmsg(pDb->db), (char*)0); + rc = TCL_ERROR; + } + sqlite3_close(pSrc); + break; + } + + /* + ** $db serialize ?DATABASE? + ** + ** Return a serialization of a database. + */ + case DB_SERIALIZE: { +#ifdef SQLITE_OMIT_DESERIALIZE + Tcl_AppendResult(interp, "MEMDB not available in this build", + (char*)0); + rc = TCL_ERROR; +#else + const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main"; + sqlite3_int64 sz = 0; + unsigned char *pData; + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?"); + rc = TCL_ERROR; + }else{ + int needFree; + pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY); + if( pData ){ + needFree = 0; + }else{ + pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0); + needFree = 1; + } + Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz)); + if( needFree ) sqlite3_free(pData); + } +#endif + break; + } + + /* + ** $db status (step|sort|autoindex|vmstep) + ** + ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or + ** SQLITE_STMTSTATUS_SORT for the most recent eval. + */ + case DB_STATUS: { + int v; + const char *zOp; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)"); + return TCL_ERROR; + } + zOp = Tcl_GetString(objv[2]); + if( strcmp(zOp, "step")==0 ){ + v = pDb->nStep; + }else if( strcmp(zOp, "sort")==0 ){ + v = pDb->nSort; + }else if( strcmp(zOp, "autoindex")==0 ){ + v = pDb->nIndex; + }else if( strcmp(zOp, "vmstep")==0 ){ + v = pDb->nVMStep; + }else{ + Tcl_AppendResult(interp, + "bad argument: should be autoindex, step, sort or vmstep", + (char*)0); + return TCL_ERROR; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(v)); + break; + } + + /* + ** $db timeout MILLESECONDS + ** + ** Delay for the number of milliseconds specified when a file is locked. + */ + case DB_TIMEOUT: { + int ms; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR; + sqlite3_busy_timeout(pDb->db, ms); + break; + } + + /* + ** $db total_changes + ** + ** Return the number of rows that were modified, inserted, or deleted + ** since the database handle was created. + */ + case DB_TOTAL_CHANGES: { + Tcl_Obj *pResult; + if( objc!=2 ){ + Tcl_WrongNumArgs(interp, 2, objv, ""); + return TCL_ERROR; + } + pResult = Tcl_GetObjResult(interp); + Tcl_SetWideIntObj(pResult, sqlite3_total_changes64(pDb->db)); + break; + } + + /* $db trace ?CALLBACK? + ** + ** Make arrangements to invoke the CALLBACK routine for each SQL statement + ** that is executed. The text of the SQL is appended to CALLBACK before + ** it is executed. + */ + case DB_TRACE: { + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zTrace ){ + Tcl_AppendResult(interp, pDb->zTrace, (char*)0); + } + }else{ + char *zTrace; + Tcl_Size len; + if( pDb->zTrace ){ + Tcl_Free(pDb->zTrace); + } + zTrace = Tcl_GetStringFromObj(objv[2], &len); + if( zTrace && len>0 ){ + pDb->zTrace = Tcl_Alloc( len + 1 ); + memcpy(pDb->zTrace, zTrace, len+1); + }else{ + pDb->zTrace = 0; + } +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ + !defined(SQLITE_OMIT_DEPRECATED) + if( pDb->zTrace ){ + pDb->interp = interp; + sqlite3_trace(pDb->db, DbTraceHandler, pDb); + }else{ + sqlite3_trace(pDb->db, 0, 0); + } +#endif + } + break; + } + + /* $db trace_v2 ?CALLBACK? ?MASK? + ** + ** Make arrangements to invoke the CALLBACK routine for each trace event + ** matching the mask that is generated. The parameters are appended to + ** CALLBACK before it is executed. + */ + case DB_TRACE_V2: { + if( objc>4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?"); + return TCL_ERROR; + }else if( objc==2 ){ + if( pDb->zTraceV2 ){ + Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0); + } + }else{ + char *zTraceV2; + Tcl_Size len; + Tcl_WideInt wMask = 0; + if( objc==4 ){ + static const char *TTYPE_strs[] = { + "statement", "profile", "row", "close", 0 + }; + enum TTYPE_enum { + TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE + }; + Tcl_Size i; + if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){ + return TCL_ERROR; + } + for(i=0; izTraceV2 ){ + Tcl_Free(pDb->zTraceV2); + } + zTraceV2 = Tcl_GetStringFromObj(objv[2], &len); + if( zTraceV2 && len>0 ){ + pDb->zTraceV2 = Tcl_Alloc( len + 1 ); + memcpy(pDb->zTraceV2, zTraceV2, len+1); + }else{ + pDb->zTraceV2 = 0; + } +#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) + if( pDb->zTraceV2 ){ + pDb->interp = interp; + sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb); + }else{ + sqlite3_trace_v2(pDb->db, 0, 0, 0); + } +#endif + } + break; + } + + /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT + ** + ** Start a new transaction (if we are not already in the midst of a + ** transaction) and execute the TCL script SCRIPT. After SCRIPT + ** completes, either commit the transaction or roll it back if SCRIPT + ** throws an exception. Or if no new transaction was started, do nothing. + ** pass the exception on up the stack. + ** + ** This command was inspired by Dave Thomas's talk on Ruby at the + ** 2005 O'Reilly Open Source Convention (OSCON). + */ + case DB_TRANSACTION: { + Tcl_Obj *pScript; + const char *zBegin = "SAVEPOINT _tcl_transaction"; + if( objc!=3 && objc!=4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT"); + return TCL_ERROR; + } + + if( pDb->nTransaction==0 && objc==4 ){ + static const char *TTYPE_strs[] = { + "deferred", "exclusive", "immediate", 0 + }; + enum TTYPE_enum { + TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE + }; + int ttype; + if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type", + 0, &ttype) ){ + return TCL_ERROR; + } + switch( (enum TTYPE_enum)ttype ){ + case TTYPE_DEFERRED: /* no-op */; break; + case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break; + case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break; + } + } + pScript = objv[objc-1]; + + /* Run the SQLite BEGIN command to open a transaction or savepoint. */ + pDb->disableAuth++; + rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0); + pDb->disableAuth--; + if( rc!=SQLITE_OK ){ + Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); + return TCL_ERROR; + } + pDb->nTransaction++; + + /* If using NRE, schedule a callback to invoke the script pScript, then + ** a second callback to commit (or rollback) the transaction or savepoint + ** opened above. If not using NRE, evaluate the script directly, then + ** call function DbTransPostCmd() to commit (or rollback) the transaction + ** or savepoint. */ + addDatabaseRef(pDb); /* DbTransPostCmd() calls delDatabaseRef() */ + if( DbUseNre() ){ + Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0); + (void)Tcl_NREvalObj(interp, pScript, 0); + }else{ + rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0)); + } + break; + } + + /* + ** $db unlock_notify ?script? + */ + case DB_UNLOCK_NOTIFY: { +#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY + Tcl_AppendResult(interp, "unlock_notify not available in this build", + (char*)0); + rc = TCL_ERROR; +#else + if( objc!=2 && objc!=3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); + rc = TCL_ERROR; + }else{ + void (*xNotify)(void **, int) = 0; + void *pNotifyArg = 0; + + if( pDb->pUnlockNotify ){ + Tcl_DecrRefCount(pDb->pUnlockNotify); + pDb->pUnlockNotify = 0; + } + + if( objc==3 ){ + xNotify = DbUnlockNotify; + pNotifyArg = (void *)pDb; + pDb->pUnlockNotify = objv[2]; + Tcl_IncrRefCount(pDb->pUnlockNotify); + } + + if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){ + Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); + rc = TCL_ERROR; + } + } +#endif + break; + } + + /* + ** $db preupdate_hook count + ** $db preupdate_hook hook ?SCRIPT? + ** $db preupdate_hook new INDEX + ** $db preupdate_hook old INDEX + */ + case DB_PREUPDATE: { +#ifndef SQLITE_ENABLE_PREUPDATE_HOOK + Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time", + (char*)0); + rc = TCL_ERROR; +#else + static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0}; + enum DbPreupdateSubCmd { + PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD + }; + int iSub; + + if( objc<3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?"); + } + if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){ + return TCL_ERROR; + } + + switch( (enum DbPreupdateSubCmd)iSub ){ + case PRE_COUNT: { + int nCol = sqlite3_preupdate_count(pDb->db); + Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol)); + break; + } + + case PRE_HOOK: { + if( objc>4 ){ + Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?"); + return TCL_ERROR; + } + DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook); + break; + } + + case PRE_DEPTH: { + Tcl_Obj *pRet; + if( objc!=3 ){ + Tcl_WrongNumArgs(interp, 3, objv, ""); + return TCL_ERROR; + } + pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db)); + Tcl_SetObjResult(interp, pRet); + break; + } + + case PRE_NEW: + case PRE_OLD: { + int iIdx; + sqlite3_value *pValue; + if( objc!=4 ){ + Tcl_WrongNumArgs(interp, 3, objv, "INDEX"); + return TCL_ERROR; + } + if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){ + return TCL_ERROR; + } + + if( iSub==PRE_OLD ){ + rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue); + }else{ + assert( iSub==PRE_NEW ); + rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue); + } + + if( rc==SQLITE_OK ){ + Tcl_Obj *pObj; + pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1); + Tcl_SetObjResult(interp, pObj); + }else{ + Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); + return TCL_ERROR; + } + } + } +#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ + break; + } + + /* + ** $db wal_hook ?script? + ** $db update_hook ?script? + ** $db rollback_hook ?script? + */ + case DB_WAL_HOOK: + case DB_UPDATE_HOOK: + case DB_ROLLBACK_HOOK: { + /* set ppHook to point at pUpdateHook or pRollbackHook, depending on + ** whether [$db update_hook] or [$db rollback_hook] was invoked. + */ + Tcl_Obj **ppHook = 0; + if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook; + if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook; + if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook; + if( objc>3 ){ + Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); + return TCL_ERROR; + } + + DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook); + break; + } + + /* $db version + ** + ** Return the version string for this database. + */ + case DB_VERSION: { + int i; + for(i=2; ibLegacyPrepare) ){ + return TCL_ERROR; + } + }else + + /* $db version -last-stmt-ptr + ** + ** Return a string which is a hex encoding of the pointer to the + ** most recent sqlite3_stmt in the statement cache. + */ + if( strcmp(zArg, "-last-stmt-ptr")==0 ){ + char zBuf[100]; + sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", + pDb->stmtList ? pDb->stmtList->pStmt: 0); + Tcl_SetResult(interp, zBuf, TCL_VOLATILE); + }else +#endif /* SQLITE_TEST */ + { + Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0); + return TCL_ERROR; + } + } + if( i==2 ){ + Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC); + } + break; + } + + + } /* End of the SWITCH statement */ + return rc; +} + +#if SQLITE_TCL_NRE +/* +** Adaptor that provides an objCmd interface to the NRE-enabled +** interface implementation. +*/ +static int SQLITE_TCLAPI DbObjCmdAdaptor( + void *cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv); +} +#endif /* SQLITE_TCL_NRE */ + +/* +** Issue the usage message when the "sqlite3" command arguments are +** incorrect. +*/ +static int sqliteCmdUsage( + Tcl_Interp *interp, + Tcl_Obj *const*objv +){ + Tcl_WrongNumArgs(interp, 1, objv, + "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?" + " ?-nofollow BOOLEAN?" + " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?" + ); + return TCL_ERROR; +} + +/* +** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN? +** ?-create BOOLEAN? ?-nomutex BOOLEAN? +** ?-nofollow BOOLEAN? +** +** This is the main Tcl command. When the "sqlite" Tcl command is +** invoked, this routine runs to process that command. +** +** The first argument, DBNAME, is an arbitrary name for a new +** database connection. This command creates a new command named +** DBNAME that is used to control that connection. The database +** connection is deleted when the DBNAME command is deleted. +** +** The second argument is the name of the database file. +** +*/ +static int SQLITE_TCLAPI DbMain( + void *cd, + Tcl_Interp *interp, + int objc, + Tcl_Obj *const*objv +){ + SqliteDb *p; + const char *zArg; + char *zErrMsg; + int i; + const char *zFile = 0; + const char *zVfs = 0; + int flags; + int bTranslateFileName = 1; + Tcl_DString translatedFilename; + int rc; + + /* In normal use, each TCL interpreter runs in a single thread. So + ** by default, we can turn off mutexing on SQLite database connections. + ** However, for testing purposes it is useful to have mutexes turned + ** on. So, by default, mutexes default off. But if compiled with + ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on. + */ +#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX + flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; +#else + flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX; +#endif + + if( objc==1 ) return sqliteCmdUsage(interp, objv); + if( objc==2 ){ + zArg = Tcl_GetStringFromObj(objv[1], 0); + if( strcmp(zArg,"-version")==0 ){ + Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0); + return TCL_OK; + } + if( strcmp(zArg,"-sourceid")==0 ){ + Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0); + return TCL_OK; + } + if( strcmp(zArg,"-has-codec")==0 ){ + Tcl_AppendResult(interp,"0",(char*)0); + return TCL_OK; + } + if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv); + } + for(i=2; idb, flags, zVfs); + if( bTranslateFileName ){ + Tcl_DStringFree(&translatedFilename); + } + if( p->db ){ + if( SQLITE_OK!=sqlite3_errcode(p->db) ){ + zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); + sqlite3_close(p->db); + p->db = 0; + } + }else{ + zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc)); + } + if( p->db==0 ){ + Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE); + Tcl_Free((char*)p); + sqlite3_free(zErrMsg); + return TCL_ERROR; + } + p->maxStmt = NUM_PREPARED_STMTS; + p->openFlags = flags & SQLITE_OPEN_URI; + p->interp = interp; + zArg = Tcl_GetStringFromObj(objv[1], 0); + if( DbUseNre() ){ + Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd, + (char*)p, DbDeleteCmd); + }else{ + Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd); + } + p->nRef = 1; + return TCL_OK; +} + +/* +** Provide a dummy Tcl_InitStubs if we are using this as a static +** library. +*/ +#ifndef USE_TCL_STUBS +# undef Tcl_InitStubs +# define Tcl_InitStubs(a,b,c) TCL_VERSION +#endif + +/* +** Make sure we have a PACKAGE_VERSION macro defined. This will be +** defined automatically by the TEA makefile. But other makefiles +** do not define it. +*/ +#ifndef PACKAGE_VERSION +# define PACKAGE_VERSION SQLITE_VERSION +#endif + +/* +** Initialize this module. +** +** This Tcl module contains only a single new Tcl command named "sqlite". +** (Hence there is no namespace. There is no point in using a namespace +** if the extension only supplies one new name!) The "sqlite" command is +** used to open a new SQLite database. See the DbMain() routine above +** for additional information. +** +** The EXTERN macros are required by TCL in order to work on windows. +*/ +EXTERN int Sqlite3_Init(Tcl_Interp *interp){ + int rc = Tcl_InitStubs(interp, "8.5-", 0) ? TCL_OK : TCL_ERROR; + if( rc==TCL_OK ){ + Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0); +#ifndef SQLITE_3_SUFFIX_ONLY + /* The "sqlite" alias is undocumented. It is here only to support + ** legacy scripts. All new scripts should use only the "sqlite3" + ** command. */ + Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0); +#endif + rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION); + } + return rc; +} +EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } +EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } +EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } + +/* Because it accesses the file-system and uses persistent state, SQLite +** is not considered appropriate for safe interpreters. Hence, we cause +** the _SafeInit() interfaces return TCL_ERROR. +*/ +EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; } +EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;} + +/* +** Versions of all of the above entry points that omit the "3" at the end +** of the name. Years ago (circa 2004) the "3" was necessary to distinguish +** SQLite version 3 from Sqlite version 2. But two decades have elapsed. +** SQLite2 is not longer a conflict. So it is ok to omit the "3". +** +** Omitting the "3" helps TCL find the entry point. +*/ +EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp);} +EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } +EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } +EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } +EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; } +EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;} + +/* Also variants with a lowercase "s". I'm told that these are +** deprecated in Tcl9, but they continue to be included for backwards +** compatibility. */ +EXTERN int sqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp);} +EXTERN int sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp);} + + +/* +** If the TCLSH macro is defined, add code to make a stand-alone program. +*/ +#if defined(TCLSH) + +/* This is the main routine for an ordinary TCL shell. If there are +** arguments, run the first argument as a script. Otherwise, read TCL +** commands from standard input +*/ +static const char *tclsh_main_loop(void){ + static const char zMainloop[] = + "if {[llength $argv]>=1} {\n" +#ifdef WIN32 + "set new [list]\n" + "foreach arg $argv {\n" + "if {[string match -* $arg] || [file exists $arg]} {\n" + "lappend new $arg\n" + "} else {\n" + "set once 0\n" + "foreach match [lsort [glob -nocomplain $arg]] {\n" + "lappend new $match\n" + "set once 1\n" + "}\n" + "if {!$once} {lappend new $arg}\n" + "}\n" + "}\n" + "set argv $new\n" + "unset new\n" +#endif + "set argv0 [lindex $argv 0]\n" + "set argv [lrange $argv 1 end]\n" + "source $argv0\n" + "} else {\n" + "set line {}\n" + "while {![eof stdin]} {\n" + "if {$line!=\"\"} {\n" + "puts -nonewline \"> \"\n" + "} else {\n" + "puts -nonewline \"% \"\n" + "}\n" + "flush stdout\n" + "append line [gets stdin]\n" + "if {[info complete $line]} {\n" + "if {[catch {uplevel #0 $line} result]} {\n" + "puts stderr \"Error: $result\"\n" + "} elseif {$result!=\"\"} {\n" + "puts $result\n" + "}\n" + "set line {}\n" + "} else {\n" + "append line \\n\n" + "}\n" + "}\n" + "}\n" + ; + return zMainloop; +} + +#ifndef TCLSH_MAIN +# define TCLSH_MAIN main +#endif +int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){ + Tcl_Interp *interp; + int i; + const char *zScript = 0; + char zArgc[32]; +#if defined(TCLSH_INIT_PROC) + extern const char *TCLSH_INIT_PROC(Tcl_Interp*); +#endif + +#if !defined(_WIN32_WCE) + if( getenv("SQLITE_DEBUG_BREAK") ){ + if( isatty(0) && isatty(2) ){ + fprintf(stderr, + "attach debugger to process %d and press any key to continue.\n", + GETPID()); + fgetc(stdin); + }else{ +#if defined(_WIN32) || defined(WIN32) + DebugBreak(); +#elif defined(SIGTRAP) + raise(SIGTRAP); +#endif + } + } +#endif + + /* Call sqlite3_shutdown() once before doing anything else. This is to + ** test that sqlite3_shutdown() can be safely called by a process before + ** sqlite3_initialize() is. */ + sqlite3_shutdown(); + + Tcl_FindExecutable(argv[0]); + Tcl_SetSystemEncoding(NULL, "utf-8"); + interp = Tcl_CreateInterp(); + Sqlite3_Init(interp); + + sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1); + Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY); + Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY); + for(i=1; i` or `ReadOnlySpan`) into an open database (reference: [SQLite Deserialization](https://www.sqlite.org/c3ref/deserialize.html)). -- [SQLite 3.50.1](https://sqlite.org/releaselog/3_50_1.html) +- [SQLite3 Multiple Ciphers 2.1.3](https://github.com/utelle/SQLite3MultipleCiphers/releases/tag/v2.1.3) (based on [SQLite 3.50.1](https://sqlite.org/releaselog/3_50_1.html)) + Enabled modules: [R\*Tree](https://sqlite.org/rtree.html), [Geopoly](https://sqlite.org/geopoly.html), [FTS5](https://sqlite.org/fts5.html), [Built-In Math Functions](https://www.sqlite.org/lang_mathfunc.html) + Supports Windows, Linux, macOS, WebGL, Android, iOS, tvOS and visionOS platforms + Supports persisting data in WebGL builds by using a [custom VFS backed by Indexed DB](https://github.com/gilzoide/idbvfs). @@ -101,7 +101,7 @@ SQLite-net for Unity first-party code is licensed under the [MIT license](LICENS Third-party code: - SQLite-net: [MIT license](Runtime/sqlite-net/LICENSE.txt) -- SQLite: [public domain](https://sqlite.org/copyright.html) +- SQLite3 Multiple Ciphers: [MIT license](https://github.com/utelle/SQLite3MultipleCiphers/blob/main/LICENSE) ## Modifications made to SQLite-net source code From 59c59255054094c2606b18f2a6e1607c58e441ea Mon Sep 17 00:00:00 2001 From: gilzoide Date: Sat, 28 Jun 2025 11:56:29 -0300 Subject: [PATCH 2/2] Bump NDK version to r27c --- Plugins/tools~/Dockerfile.build.android | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugins/tools~/Dockerfile.build.android b/Plugins/tools~/Dockerfile.build.android index 4ecff8b..a683d60 100644 --- a/Plugins/tools~/Dockerfile.build.android +++ b/Plugins/tools~/Dockerfile.build.android @@ -1,7 +1,7 @@ # syntax=docker/dockerfile:1 FROM debian:12-slim -ARG NDK_VERSION=r26c +ARG NDK_VERSION=r27c RUN apt-get -qq update \ && apt-get -qq install -y --no-install-recommends \