diff --git a/.gitignore b/.gitignore index 63f5d90..aa12e67 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ build-* *~ *.user +*.o client/bin/ client/obj/ diff --git a/LICENSE b/LICENSE index a388783..aa54ffd 100644 --- a/LICENSE +++ b/LICENSE @@ -22,6 +22,11 @@ Licenses Used By: Client ====== +blowfish-api +------------ +https://github.com/tombonner/blowfish-api +Attribution + DOS Serial Library ------------------ https://github.com/kstenerud/DOS-Serial-Library @@ -32,6 +37,11 @@ ENet https://github.com/zpl-c/enet MIT +ini +--- +https://github.com/rxi/ini +MIT + MemWatch -------- http://www.linkdata.se/sourcecode/memwatch/ @@ -80,6 +90,11 @@ ENet https://github.com/zpl-c/enet MIT +ini +--- +https://github.com/rxi/ini +MIT + MemWatch -------- http://www.linkdata.se/sourcecode/memwatch/ diff --git a/client/Makefile.djgpp b/client/Makefile.djgpp index 489f53b..ddd89ea 100644 --- a/client/Makefile.djgpp +++ b/client/Makefile.djgpp @@ -33,7 +33,9 @@ BINDIR = bin ## CHANGE THIS ## # CFLAGS, LDFLAGS, CPPFLAGS, PREFIX can be overriden on CLI -CFLAGS := $(DEBUG) -I$(SRCDIR) -I$(SRCDIR)/system -I$(SRCDIR)/dos -I$(SRCDIR)/gui -I$(SRCDIR)/thirdparty -I$(SRCDIR)/thirdparty/serial -I$(SHARED) -I$(SHARED)/thirdparty +CFLAGS := $(DEBUG) +CFLAGS += -I$(SRCDIR) -I$(SRCDIR)/system -I$(SRCDIR)/dos -I$(SRCDIR)/gui -I$(SRCDIR)/thirdparty +CFLAGS += -I$(SHARED) -I$(SHARED)/thirdparty CPPFLAGS := LDFLAGS := PREFIX := /usr/local diff --git a/client/client.pro b/client/client.pro index 99aabe0..b427574 100644 --- a/client/client.pro +++ b/client/client.pro @@ -16,6 +16,8 @@ # along with this program. If not, see . # +#CONFIG *= testing + # NOTE: You'll occasionally find a file with a capital "C" extension. # These are C files that we want ignored by the DOS compiler. @@ -25,8 +27,7 @@ CONFIG -= qt DESTDIR = $$OUT_PWD/bin SHARED = $$PWD/../shared -DOS_HEADERS = \ - src/thirdparty/serial/serial.h +DOS_HEADERS = DOS_SOURCES = \ src/thirdparty/serial/serial.c \ @@ -59,14 +60,17 @@ HEADERS = \ $$SHARED/thirdparty/stb_ds.h \ $$SHARED/thirdparty/stb_image.h \ $$SHARED/thirdparty/memwatch/memwatch.h \ - src/system/comport.h \ + $$SHARED/thirdparty/blowfish-api/blowfish.h \ + $$SHARED/thirdparty/ini/src/ini.h \ + src/config.h \ + src/system/util.h \ src/thirdparty/minicoro/minicoro.h \ + src/system/comport.h \ src/settings.h \ src/system/color.h \ src/system/memory.h \ src/system/surface.h \ src/system/taglist.h \ - src/test.h \ src/system/keyboard.h \ src/system/task.h \ src/system/timer.h \ @@ -97,10 +101,14 @@ HEADERS = \ SOURCES = \ $$LINUX_SOURCES \ $$SHARED/thirdparty/memwatch/memwatch.c \ + $$SHARED/thirdparty/blowfish-api/blowfish.c \ + $$SHARED/thirdparty/ini/src/ini.c \ + src/config.c \ src/system/memory.c \ src/settings.c \ src/system/surface.c \ src/system/taglist.c \ + src/system/util.c \ src/test.c \ src/system/array.c \ src/system/log.c \ @@ -135,3 +143,9 @@ OTHER_FILES = \ build.sh \ test.sh \ test.conf + +testing { + DEFINES *= TESTING + HEADERS += src/test.h + SOURCES += src/test.c +} diff --git a/client/src/config.c b/client/src/config.c new file mode 100644 index 0000000..cdc4272 --- /dev/null +++ b/client/src/config.c @@ -0,0 +1,97 @@ +/* + * Kangaroo Punch MultiPlayer Game Server Mark II + * Copyright (C) 2020-2021 Scott Duensing + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + + +#include "thirdparty/ini/src/ini.h" + +#include "config.h" +#include "util.h" + + +ConfigT _configData; + +static char *_configName = NULL; + + +void configShutdown(void) { + FILE *out = NULL; + + out = fopen(_configName, "w"); + if (out) { + fprintf(out, + "[VIDEO]\n" + "WIDTH=%d\n" + "HEIGHT=%d\n" + "DEPTH=%d\n\n" + "[SERIAL]\n" + "COM=%d\n\n" + "[SERVER]\n" + "HOST=%s\n" + "PORT=%d\n\n" + "[USER]\n" + "NAME=%s\n", + _configData.videoWidth, _configData.videoHeight, _configData.videoDepth, + _configData.serialCom, + _configData.serverHost, _configData.serverPort, + _configData.userName + ); + fclose(out); + } + + free(_configData.serverHost); + _configData.serverHost = NULL; + + free(_configData.userName); + _configData.userName = NULL; + + free(_configName); + _configName = NULL; +} + + +void configStartup(char *file) { + ini_t *ini = NULL; + + // We need this later. + _configName = utilAppNameWithNewExtensionGet(file, "ini"); + + // Numeric Defaults. + _configData.videoWidth = 800; + _configData.videoHeight = 600; + _configData.videoDepth = 16; + _configData.serialCom = 0; + _configData.serverPort = 16550; + + // Load from disk if available. + ini = ini_load(_configName); + if (ini) { + ini_sget(ini, "VIDEO", "WIDTH", "%d", &_configData.videoWidth); + ini_sget(ini, "VIDEO", "HEIGHT", "%d", &_configData.videoHeight); + ini_sget(ini, "VIDEO", "DEPTH", "%d", &_configData.videoDepth); + ini_sget(ini, "SERIAL", "COM", "%d", &_configData.serialCom); + _configData.serverHost = strdup(ini_get(ini, "SERVER", "HOST")); + ini_sget(ini, "SERVER", "PORT", "%d", &_configData.serverPort); + _configData.userName = strdup(ini_get(ini, "USER", "NAME")); + ini_free(ini); + } + + // String defaults. + if (!_configData.serverHost) _configData.serverHost = strdup("\"kanga.world\""); + if (!_configData.userName) _configData.userName = strdup("\"New User\""); +} diff --git a/client/src/config.h b/client/src/config.h new file mode 100644 index 0000000..bd801e5 --- /dev/null +++ b/client/src/config.h @@ -0,0 +1,46 @@ +/* + * Kangaroo Punch MultiPlayer Game Server Mark II + * Copyright (C) 2020-2021 Scott Duensing + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + + +#ifndef CONFIG_H +#define CONFIG_H + + +#include "os.h" + + +typedef struct ConfigS { + uint16_t videoWidth; + uint16_t videoHeight; + uint8_t videoDepth; + uint8_t serialCom; + char *serverHost; + uint16_t serverPort; + char *userName; +} ConfigT; + + +extern ConfigT _configData; + + +void configShutdown(void); +void configStartup(char *file); + + +#endif // CONFIG_H diff --git a/client/src/dos/vesa.c b/client/src/dos/vesa.c index be4d60c..a748b1c 100644 --- a/client/src/dos/vesa.c +++ b/client/src/dos/vesa.c @@ -22,6 +22,7 @@ #include "vesa.h" #include "surface.h" +#include "../system/log.h" // http://www.delorie.com/djgpp/doc/brennan/brennan_att_inline_djgpp.html @@ -135,13 +136,9 @@ typedef struct VBESurfaceS { static void vbeCreatePalette(void); static VBEInfoT *vbeGetInfo(void); static VBEModeInfoT *vbeGetModeInfo(uint16_t vbeModeNumber); -//static VBEModeInfoT *vbeGetModeInfoPtr(void); static void *vbeGetPmodeInterface(void); -//static VBESurfaceT *vbeGetVBESurfacePtr(void); static uint8_t vbeIsDesiredMode(void); -//static VBESurfaceT *vbeModeInit(uint16_t xRes, uint16_t yRes, uint8_t bpp); static uint16_t vbeSelectModeNumber(uint16_t xRes, uint16_t yRes, uint8_t bpp); -//static void vbeSetDisplayStart(uint32_t pixel, uint32_t scanline); static VBESurfaceT *vbeSetMode(uint16_t vbeModeNumber); static uint16_t vbeSetScanlineLength(uint16_t pixelLength); @@ -305,13 +302,6 @@ static VBEModeInfoT *vbeGetModeInfo(uint16_t vbeModeNumber) { } -/* -static VBEModeInfoT *vbeGetModeInfoPtr(void) { - return(&_vbeModeInfo); -} -*/ - - static void *vbeGetPmodeInterface(void) { __dpmi_regs r; __dpmi_meminfo m; @@ -332,7 +322,6 @@ static void *vbeGetPmodeInterface(void) { // need memory-mapped IO? if (_pmodeInterfacePtr->ioInfo) { - printf("\nGot IOInfo\n"); ptr = (uint16_t *)((char *)_pmodeInterfacePtr + _pmodeInterfacePtr->ioInfo); // skip the port table... while (*ptr != 0xFFFF) @@ -362,13 +351,6 @@ static void *vbeGetPmodeInterface(void) { } -/* -static VBESurfaceT *vbeGetVBESurfacePtr(void) { - return(&_vbeSurface); -} -*/ - - static uint8_t vbeIsDesiredMode(void) { // This is a custom filter to remove modes not supported by the calling application. @@ -400,32 +382,6 @@ ColorT vbeColorMake(uint8_t red, uint8_t green, uint8_t blue) { } -/* -static VBESurfaceT *vbeModeInit(uint16_t xRes, uint16_t yRes, uint8_t bpp) { - uint16_t vbeModeNumber; - __dpmi_meminfo m; - - if (_vbeSurface.vbeBoolean == 0) return NULL; - if (_vbeSurface.vbeInitBoolean == 0) return NULL; - - m.size = (_vbeInfo.totalMemory * 64 * 1024); - m.address = _vbeSurface.lfbLinearAddress; - __dpmi_unlock_linear_region(&m); - __dpmi_free_physical_address_mapping(&m); - __dpmi_free_ldt_descriptor(_vbeSurface.lfbSelector); - - _vbeSurface.vbeInitBoolean = 0; - - if ((vbeModeNumber = vbeSelectModeNumber(xRes, yRes, bpp)) == 0) return NULL; - - vbeModeNumber |= 0x8000; - if (vbeSetMode(vbeModeNumber) == NULL) return NULL; - - return(&_vbeSurface); -} -*/ - - void vbePresent(void) { SurfaceT *o = surfaceOffScreenGet(); _movedatal(_my_ds(), (int32_t)o->buffer.bits32, _vbeSurface.lfbSelector, 0x0, _vbeSurface.screenDWords); @@ -450,43 +406,6 @@ static uint16_t vbeSelectModeNumber(uint16_t xRes, uint16_t yRes, uint8_t bpp) { } -/* -static void vbeSetDisplayStart(uint32_t pixel, uint32_t scanline) { - __dpmi_regs r; - int32_t address; - int32_t selector; - - if (pmVBESetDisplayStart) { - address = (_yTable[scanline] + (pixel * _vbeSurface.bytesPerPixel)) >> 2; - selector = (_vbeSurface.ioSegment) ? _vbeSurface.ioSegment : _my_ds(); - asm( - " pushw %%es ; " - " movw %w1, %%es ; " // set the IO segment - " call *%0 ; " // call the VESA function - " popw %%es " - : // no outputs - - : "S"(pmVBESetDisplayStart), // function pointer in esi - "a"(selector), // IO segment in eax - "b"(0x0080), // mode in ebx - "c"(address & 0xFFFF), // low word of address in ecx - "d"((address >> 16)) // high word of address in edx - - : "memory", "%edi", "%cc" // touches edi and flags - ); - - return; - } - - r.x.ax = 0x4F07; - r.x.bx = 0x0080; - r.x.cx = pixel; - r.x.dx = scanline; - __dpmi_int(0x10, &r); -} -*/ - - static VBESurfaceT *vbeSetMode(uint16_t vbeModeNumber) { __dpmi_regs r; __dpmi_meminfo m; @@ -597,10 +516,11 @@ int16_t vbeInfoShow(void) { //printf("Based on: VBE 2.0 driver v1.0 (c) 1999, Tobias Koch \n\n"); if (vbeGetInfo() == NULL) { - printf("No VESA BIOS Extensions found.\n"); + logWrite("No VESA BIOS Extensions found.\n"); + vbeShutdown(); return(1); } - printf( + logWrite( "Video Memory - %d KB\n" "VBE Version - %d.%d detected\n" "OEM Specification - %s\n", @@ -609,7 +529,7 @@ int16_t vbeInfoShow(void) { _vbeInfo.oemStringPtr); if (_vbeInfo.vbeVersion >= 0x0200) { - printf( + logWrite( "OEM Software Revision - %d.%d\n" "OEM Vendor Name - %s\n" "OEM Product Name - %s\n" @@ -621,7 +541,8 @@ int16_t vbeInfoShow(void) { _vbeInfo.oemProductRevPtr, vbeGetPmodeInterface() ? "Found" : "Missing"); } else { - printf("VESA BIOS Extension 2.0 or better required!\n"); + logWrite("VESA BIOS Extension 2.0 or better required!\n"); + vbeShutdown(); return(1); } @@ -629,7 +550,7 @@ int16_t vbeInfoShow(void) { if (_vbeInfo.videoModePtr[counter] == 0xFFFF) break; vbeGetModeInfo(_vbeInfo.videoModePtr[counter]); if (vbeIsDesiredMode()) { - printf("Mode %Xh - %4d x %4d x %2d - RGB %d:%d:%d - %s\n", + logWrite("Mode %Xh - %4d x %4d x %2d - RGB %d:%d:%d - %s\n", _vbeInfo.videoModePtr[counter], _vbeModeInfo.xResolution, _vbeModeInfo.yResolution, @@ -641,6 +562,7 @@ int16_t vbeInfoShow(void) { } } + vbeShutdown(); return(0); } @@ -652,7 +574,7 @@ int16_t vbeShutdown(void) { if (_vbeSurface.vbeInitBoolean == 0) { r.x.ax = 0x03; // make sure we're in 3h __dpmi_int(0x10, &r); // for buggy vesa implementations - return(1); + //return(1); } if (_yTable) free(_yTable); @@ -690,23 +612,27 @@ uint8_t vbeStartup(uint16_t xRes, uint16_t yRes, uint8_t bpp) { uint16_t vbeModeNumber; if (vbeGetInfo() == NULL) { - printf("No VESA BIOS Extensions found.\n"); + logWrite("No VESA BIOS Extensions found.\n"); + vbeShutdown(); return 1; } if (_vbeInfo.vbeVersion < 0x0200) { - printf("VBE Version 2.0 or better required.\n"); + logWrite("VBE Version 2.0 or better required.\n"); + vbeShutdown(); return 2; } vbeGetPmodeInterface(); if ((vbeModeNumber = vbeSelectModeNumber(xRes, yRes, bpp)) == 0) { - printf("No appropriate video mode available.\n"); + logWrite("No appropriate video mode available.\n"); + vbeShutdown(); return 3; } if (vbeSetMode(vbeModeNumber) == NULL) { + vbeShutdown(); return 4; } diff --git a/client/src/main.c b/client/src/main.c index 048d60f..9b0f158 100644 --- a/client/src/main.c +++ b/client/src/main.c @@ -18,22 +18,19 @@ */ -//#define TESTING - - /* * To Do: * * - Replace any direct data manipulation from outside a class with methods to handle it - * - More widget states: Ghosted, hidden + * - More widget states: Ghosted (underway), hidden * - Methods that can change the width of a widget (such as setTitle) need to repaint the parent window as well * - Metrics, colors, etc. should be defined in each widget and not in GUI * - Widgets should support a "changed" callback that can cancel the change * - Use LabelT in all widgets that have a label * - Find a light grey to replace white widget data areas * - No thumb in listbox scrollbar - * - * - Random crash on exit - looks memwatch / task related - hasn't happened on DOS yet + * - Layout container widgets! + * - DOS makefile is placing thirdparty object files in the wrong place */ @@ -48,6 +45,7 @@ #include "font.h" #include "timer.h" #include "gui.h" +#include "config.h" #include "welcome.h" @@ -113,33 +111,29 @@ static void taskGuiEventLoop(void *data) { int main(int argc, char *argv[]) { - uint16_t xResolution = 0; - uint16_t yResolution = 0; - uint16_t colorDepth = 0; - memoryStartup(argv[0]); logOpenByHandle(memoryLogHandleGet()); + configStartup(argv[0]); // 0 1 2 3 4 5 6 7 8 // 12345678901234567890123456789012345678901234567890123456789012345678901234567890 - printf("Kangaroo Punch MultiPlayer DOS Game Client Mark II\n"); - printf("Copyright (C) 2020-2021 Scott Duensing scott@kangaroopunch.com\n\n"); - fflush(stdout); + logWrite("%s", "Kangaroo Punch MultiPlayer DOS Game Client Mark II\n"); + logWrite("%s", "Copyright (C) 2020-2021 Scott Duensing scott@kangaroopunch.com\n\n"); - // Command line needs to have the desired resolution and color depth on it. - if (argc != 4) { - vbeInfoShow(); - fflush(stdout); - memoryShutdown(); - return 0; + if (argc > 1) { + if (strcmp(argv[1], "/?") == 0) { + vbeInfoShow(); + configShutdown(); + logClose(); + memoryShutdown(); + return 0; + } } - xResolution = atoi(argv[1]); - yResolution = atoi(argv[2]); - colorDepth = atoi(argv[3]); // Do we have the video mode they asked for? - if (vbeStartup(xResolution, yResolution, colorDepth)) { - fflush(stdout); + if (vbeStartup(_configData.videoWidth, _configData.videoHeight, _configData.videoDepth)) { + configShutdown(); + logClose(); memoryShutdown(); return 1; } @@ -165,7 +159,7 @@ int main(int argc, char *argv[]) { mouseShutdown(); surfaceShutdown(); vbeShutdown(); - + configShutdown(); logClose(); memoryShutdown(); diff --git a/client/src/settings.c b/client/src/settings.c index 59f62ea..ff76dbc 100644 --- a/client/src/settings.c +++ b/client/src/settings.c @@ -25,6 +25,7 @@ #include "task.h" #include "comport.h" #include "timer.h" +#include "config.h" #include "window.h" #include "button.h" @@ -37,9 +38,10 @@ #define GROUP_COM 1 -#define PORT_NONE 0 -#define PORT_BAD 1 -#define PORT_GOOD 2 +#define PORT_NONE 0 +#define PORT_NO_MODEM 1 +#define PORT_BAD_MODEM 2 +#define PORT_GOOD_MODEM 3 #define TITLE_LEN 80 @@ -49,6 +51,7 @@ typedef struct PortS { char title[TITLE_LEN]; uint8_t selected; uint8_t enabled; + RadioT *rdoCOM; } PortT; @@ -59,16 +62,35 @@ static WindowT *winSettings; static FrameT *frmComPorts; static FrameT *frmServer; static ButtonT *btnOkay; -static RadioT *rdoCOM[4]; static TextboxT *txtServer; static UpdownT *updPort; +static PortT port[4]; + static void btnOkayClick(WidgetT *widget); static void btnOkayClick(WidgetT *widget) { + uint8_t x; + RadioT *selected = radioSelectedGet(port[0].rdoCOM); + (void)widget; + + // Save selected COM port. + for (x=0; x<4; x++) { + if (selected == port[x].rdoCOM) { + _configData.serialCom = x + 1; + break; + } + } + + // Save server info. + free(_configData.serverHost); + _configData.serverHost = strdup(textboxValueGet(txtServer)); + _configData.serverPort = updownValueGet(updPort); + + // Return to welcome dialog. taskCreate(taskWelcome, NULL); guiDelete(D(winSettings)); } @@ -80,7 +102,6 @@ void taskSettings(void *data) { uint32_t len; char buffer[1024]; uint8_t quarterSeconds = 0; - PortT port[4]; uint8_t selected = 1; (void)data; @@ -101,6 +122,7 @@ void taskSettings(void *data) { tagListRun(uiDetecting); taskYield(); // Cause dialog to paint. + // Scan the COM ports for a compatable modem. for (int x=0; x<4; x++) { rc = comOpen(x, 57600L, 8, 'n', 1, SER_HANDSHAKING_RTSCTS); if (rc == SER_SUCCESS) { @@ -116,15 +138,22 @@ void taskSettings(void *data) { buffer[len] = 0; if (strstr(buffer, "OK")) { snprintf(port[x].title, TITLE_LEN - 1, "COM%d - SoftModem Found!", x + 1); - port[x].status = PORT_GOOD; + port[x].status = PORT_GOOD_MODEM; port[x].selected = selected; port[x].enabled = 1; selected = 0; } else { - snprintf(port[x].title, TITLE_LEN - 1, "COM%d - Incompatable Modem", x + 1); - port[x].status = PORT_BAD; - port[x].selected = 0; - port[x].enabled = 0; + if (strstr(buffer, "ERROR")) { + snprintf(port[x].title, TITLE_LEN - 1, "COM%d - Incompatable Modem", x + 1); + port[x].status = PORT_BAD_MODEM; + port[x].selected = 0; + port[x].enabled = 0; + } else { + snprintf(port[x].title, TITLE_LEN - 1, "COM%d - No Modem", x + 1); + port[x].status = PORT_NO_MODEM; + port[x].selected = 0; + port[x].enabled = 0; + } } comClose(x); } else { @@ -154,12 +183,12 @@ void taskSettings(void *data) { T_TEXTBOX, O(txtServer), T_X, 5, T_WIDTH, 250, T_TITLE, P("Address:"), - T_VALUE, P("kangaworld.kangaroopunch.com"), + T_VALUE, P(_configData.serverHost), T_TEXTBOX, T_DONE, T_UPDOWN, O(updPort), T_X, 5, T_Y, 30, T_WIDTH, 250, T_TITLE, P(" Port:"), - T_VALUE, 16550, + T_VALUE, _configData.serverPort, T_MINIMUM, 1, T_MAXIMUM, 65535, T_UPDOWN, T_DONE, @@ -177,12 +206,23 @@ void taskSettings(void *data) { tagListRun(uiSettings); + // If we found more than one, use the last selected. + if (_configData.serialCom > 0 && _configData.serialCom < 4) { + if (port[_configData.serialCom - 1].enabled) { + for (len=0; len<4; len++) { + port[len].selected = 0; + } + port[_configData.serialCom - 1].selected = 1; + } + } + + // Add COM discovery to GUI. rc = 0; for (len=0; len<4; len++) { - rdoCOM[len] = radioNew(5, rc, port[len].title, GROUP_COM); - if (port[len].selected) radioSelectedSet(rdoCOM[len]); - widgetEnableSet(W(rdoCOM[len]), port[len].enabled); - guiAttach(W(frmComPorts), W(rdoCOM[len])); + port[len].rdoCOM = radioNew(5, rc, port[len].title, GROUP_COM); + if (port[len].selected) radioSelectedSet(port[len].rdoCOM); + widgetEnableSet(W(port[len].rdoCOM), port[len].enabled); + guiAttach(W(frmComPorts), W(port[len].rdoCOM)); rc += 20; } } diff --git a/client/src/system/memory.c b/client/src/system/memory.c index 3191e0f..64c48ff 100644 --- a/client/src/system/memory.c +++ b/client/src/system/memory.c @@ -19,6 +19,7 @@ #include "memory.h" +#include "util.h" FILE *_memoryLog = NULL; @@ -47,28 +48,14 @@ void memoryOutput(int c) { void memoryShutdown(void) { #ifdef MEMORY_CHECK_ENABLED + unlink("memwatch.log"); // It just insists on creating this! mwTerm(); #endif } void memoryStartup(char *appName) { - char logName[32] = { "log.log" }; - char *c = NULL; - int16_t x = strlen(appName); - - // Find last portion of filename. - while (x > 0) { - if (appName[x] == '/' || appName[x] == '\\') break; - x--; - } - if (strlen(appName) - x < 32) { - // Replace any extension with ".log" - strncpy(logName, &appName[x + 1], 31); - c = strstr(logName, "."); - if (c) *c = 0; - strncat(logName, ".log", 31); - } + char *logName = utilAppNameWithNewExtensionGet(appName, "log"); _memoryLog = fopen(logName, "w"); @@ -77,4 +64,6 @@ void memoryStartup(char *appName) { mwSetOutFunc(memoryOutput); mwInit(); #endif + + free(logName); } diff --git a/client/src/system/os.h b/client/src/system/os.h index 5770731..c1ea19c 100644 --- a/client/src/system/os.h +++ b/client/src/system/os.h @@ -30,6 +30,7 @@ #include #include #include +#include #ifdef __linux__ diff --git a/client/src/system/util.c b/client/src/system/util.c new file mode 100644 index 0000000..3d1a002 --- /dev/null +++ b/client/src/system/util.c @@ -0,0 +1,51 @@ +/* + * Kangaroo Punch MultiPlayer Game Server Mark II + * Copyright (C) 2020-2021 Scott Duensing + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + + +#include "util.h" + + +char *utilAppNameWithNewExtensionGet(char *appName, char *extension) { + char *c = NULL; + char *newName = NULL; + int16_t x = strlen(appName); + uint16_t len = 2 + strlen(extension); // 2 = dot in extension and 0 terminator. + + // Find last portion of filename. + while (x > 0) { + if (appName[x] == '/' || appName[x] == '\\') break; + x--; + len++; + } + + // We use this + length of new extension for new string length. + newName = (char *)malloc(len); + if (newName) { + if (strlen(appName) - x < len) { + // Replace extension + strncpy(newName, &appName[x + 1], len - 1); + c = strstr(newName, "."); + if (c) *c = 0; + strncat(newName, ".", len - 1); + strncat(newName, extension, len - 1); + } + } + + return newName; +} diff --git a/client/src/system/util.h b/client/src/system/util.h new file mode 100644 index 0000000..78ad2e6 --- /dev/null +++ b/client/src/system/util.h @@ -0,0 +1,31 @@ +/* + * Kangaroo Punch MultiPlayer Game Server Mark II + * Copyright (C) 2020-2021 Scott Duensing + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + + +#ifndef UTIL_H +#define UTIL_H + + +#include "os.h" + + +char *utilAppNameWithNewExtensionGet(char *appName, char *extension); + + +#endif // UTIL_H diff --git a/shared/thirdparty/blowfish-api/Makefile b/shared/thirdparty/blowfish-api/Makefile new file mode 100644 index 0000000..7472574 --- /dev/null +++ b/shared/thirdparty/blowfish-api/Makefile @@ -0,0 +1,25 @@ +TARGET = blowfish_test +LIBS = -lgomp +CC = gcc +CFLAGS = -std=c99 -Wall -Wextra -Werror -pedantic -O3 -I ./ -fopenmp +LDFLAGS = + +.PHONY: default all clean + +default: $(TARGET) +all: default + +OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c)) +HEADERS = $(wildcard *.h) + +%.o: %.c $(HEADERS) + $(CC) $(CFLAGS) -c $< -o $@ + +.PRECIOUS: $(TARGET) $(OBJECTS) + +$(TARGET): $(OBJECTS) + $(CC) $(OBJECTS) $(LIBS) -o $@ + +clean: + -rm -f *.o + -rm -f $(TARGET) diff --git a/shared/thirdparty/blowfish-api/README.md b/shared/thirdparty/blowfish-api/README.md new file mode 100644 index 0000000..025f65f --- /dev/null +++ b/shared/thirdparty/blowfish-api/README.md @@ -0,0 +1,4 @@ +blowfish-api +============ + +Portable, optimised implementation of Bruce Schneier's 64-bit symmetric block cipher, Blowfish. Includes support for multiple block cipher modes, including electronic codebook (ECB), cipher block chaining (CBC), cipher feedback (CFB), output feedback (OFB) and counter (CTR), as well as support for weak key detection and parallelisation using OpenMP. diff --git a/shared/thirdparty/blowfish-api/blowfish.c b/shared/thirdparty/blowfish-api/blowfish.c new file mode 100644 index 0000000..df7ebe7 --- /dev/null +++ b/shared/thirdparty/blowfish-api/blowfish.c @@ -0,0 +1,1596 @@ +/** + + @file blowfish.c + + @brief Portable, optimised implementation of Bruce Schneier's 64-bit + symmetric block cipher, Blowfish. Includes support for multiple + block cipher modes, including electronic codebook (ECB), cipher + block chaining (CBC), cipher feedback (CFB), output feedback + (OFB) and counter (CTR), as well as support for weak key + detection and parallelisation using OpenMP. + + For more information on the Blowfish block cipher algorithm see + http://www.schneier.com/blowfish.html + + @author Tom Bonner (tom.bonner@gmail.com) + + @date 15-June-2008 + + Copyright (c) 2008, Tom Bonner. + + 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. + + Except as contained in this notice, the name(s) of the above copyright + holders shall not be used in advertising or otherwise to promote the sale, + use or other dealings in this Software without prior written authorisation. + + 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. + + */ + +#include "blowfish.h" + +/** + + @ingroup blowfish + @defgroup blowfish_api Blowfish API + @{ + + @details See description for @ref blowfish.c + + @todo Include support for little-endian systems. + + @todo Remove restrictions on buffer lengths being a multiple of 8 by either padding input buffers, or truncating enciphered data, depending on the selected block cipher mode. + + */ + +/** + + @internal + + @page glossary Glossary of symbols + + @param Iv 8-byte initialisation vector. + + @param xL High 4-bytes of block to encipher/decipher. + + @param xR Low 4-bytes of block to encipher/decipher. + + @param C 8-byte block of ciphertext. + + @param P PArray or 8-byte block of plaintext. + + @param S Sbox. + + @param k Key. + + @param E Blowfish encipher. + + @param D Blowfish decipher. + + @param n Round number. + + */ + +/* Internal function prototypes (Encipher/Decipher stream callbacks) */ + +static void _BLOWFISH_EncipherStream_ECB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG PlainTextStream, BLOWFISH_PULONG CipherTextStream, BLOWFISH_SIZE_T StreamLength ); +static void _BLOWFISH_DecipherStream_ECB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG CipherTextStream, BLOWFISH_PULONG PlainTextStream, BLOWFISH_SIZE_T StreamLength ); +static void _BLOWFISH_EncipherStream_CBC ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG PlainTextStream, BLOWFISH_PULONG CipherTextStream, BLOWFISH_SIZE_T StreamLength ); +static void _BLOWFISH_DecipherStream_CBC ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG CipherTextStream, BLOWFISH_PULONG PlainTextStream, BLOWFISH_SIZE_T StreamLength ); +static void _BLOWFISH_EncipherStream_CFB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG PlainTextStream, BLOWFISH_PULONG CipherTextStream, BLOWFISH_SIZE_T StreamLength ); +static void _BLOWFISH_DecipherStream_CFB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG CipherTextStream, BLOWFISH_PULONG PlainTextStream, BLOWFISH_SIZE_T StreamLength ); +static void _BLOWFISH_EncipherDecipherStream_OFB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG InStream, BLOWFISH_PULONG OutStream, BLOWFISH_SIZE_T StreamLength ); +static void _BLOWFISH_EncipherDecipherStream_CTR ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG InStream, BLOWFISH_PULONG OutStream, BLOWFISH_SIZE_T StreamLength ); + +/** @internal Original S-Boxes (hexdigits of pi). */ + +static const BLOWFISH_ULONG _BLOWFISH_SBox [ BLOWFISH_SBOXES ] [ BLOWFISH_SBOX_ENTRIES ] = +{ + { + 0xd1310ba6l, 0x98dfb5acl, 0x2ffd72dbl, 0xd01adfb7l, + 0xb8e1afedl, 0x6a267e96l, 0xba7c9045l, 0xf12c7f99l, + 0x24a19947l, 0xb3916cf7l, 0x0801f2e2l, 0x858efc16l, + 0x636920d8l, 0x71574e69l, 0xa458fea3l, 0xf4933d7el, + 0x0d95748fl, 0x728eb658l, 0x718bcd58l, 0x82154aeel, + 0x7b54a41dl, 0xc25a59b5l, 0x9c30d539l, 0x2af26013l, + 0xc5d1b023l, 0x286085f0l, 0xca417918l, 0xb8db38efl, + 0x8e79dcb0l, 0x603a180el, 0x6c9e0e8bl, 0xb01e8a3el, + 0xd71577c1l, 0xbd314b27l, 0x78af2fdal, 0x55605c60l, + 0xe65525f3l, 0xaa55ab94l, 0x57489862l, 0x63e81440l, + 0x55ca396al, 0x2aab10b6l, 0xb4cc5c34l, 0x1141e8cel, + 0xa15486afl, 0x7c72e993l, 0xb3ee1411l, 0x636fbc2al, + 0x2ba9c55dl, 0x741831f6l, 0xce5c3e16l, 0x9b87931el, + 0xafd6ba33l, 0x6c24cf5cl, 0x7a325381l, 0x28958677l, + 0x3b8f4898l, 0x6b4bb9afl, 0xc4bfe81bl, 0x66282193l, + 0x61d809ccl, 0xfb21a991l, 0x487cac60l, 0x5dec8032l, + 0xef845d5dl, 0xe98575b1l, 0xdc262302l, 0xeb651b88l, + 0x23893e81l, 0xd396acc5l, 0x0f6d6ff3l, 0x83f44239l, + 0x2e0b4482l, 0xa4842004l, 0x69c8f04al, 0x9e1f9b5el, + 0x21c66842l, 0xf6e96c9al, 0x670c9c61l, 0xabd388f0l, + 0x6a51a0d2l, 0xd8542f68l, 0x960fa728l, 0xab5133a3l, + 0x6eef0b6cl, 0x137a3be4l, 0xba3bf050l, 0x7efb2a98l, + 0xa1f1651dl, 0x39af0176l, 0x66ca593el, 0x82430e88l, + 0x8cee8619l, 0x456f9fb4l, 0x7d84a5c3l, 0x3b8b5ebel, + 0xe06f75d8l, 0x85c12073l, 0x401a449fl, 0x56c16aa6l, + 0x4ed3aa62l, 0x363f7706l, 0x1bfedf72l, 0x429b023dl, + 0x37d0d724l, 0xd00a1248l, 0xdb0fead3l, 0x49f1c09bl, + 0x075372c9l, 0x80991b7bl, 0x25d479d8l, 0xf6e8def7l, + 0xe3fe501al, 0xb6794c3bl, 0x976ce0bdl, 0x04c006bal, + 0xc1a94fb6l, 0x409f60c4l, 0x5e5c9ec2l, 0x196a2463l, + 0x68fb6fafl, 0x3e6c53b5l, 0x1339b2ebl, 0x3b52ec6fl, + 0x6dfc511fl, 0x9b30952cl, 0xcc814544l, 0xaf5ebd09l, + 0xbee3d004l, 0xde334afdl, 0x660f2807l, 0x192e4bb3l, + 0xc0cba857l, 0x45c8740fl, 0xd20b5f39l, 0xb9d3fbdbl, + 0x5579c0bdl, 0x1a60320al, 0xd6a100c6l, 0x402c7279l, + 0x679f25fel, 0xfb1fa3ccl, 0x8ea5e9f8l, 0xdb3222f8l, + 0x3c7516dfl, 0xfd616b15l, 0x2f501ec8l, 0xad0552abl, + 0x323db5fal, 0xfd238760l, 0x53317b48l, 0x3e00df82l, + 0x9e5c57bbl, 0xca6f8ca0l, 0x1a87562el, 0xdf1769dbl, + 0xd542a8f6l, 0x287effc3l, 0xac6732c6l, 0x8c4f5573l, + 0x695b27b0l, 0xbbca58c8l, 0xe1ffa35dl, 0xb8f011a0l, + 0x10fa3d98l, 0xfd2183b8l, 0x4afcb56cl, 0x2dd1d35bl, + 0x9a53e479l, 0xb6f84565l, 0xd28e49bcl, 0x4bfb9790l, + 0xe1ddf2dal, 0xa4cb7e33l, 0x62fb1341l, 0xcee4c6e8l, + 0xef20cadal, 0x36774c01l, 0xd07e9efel, 0x2bf11fb4l, + 0x95dbda4dl, 0xae909198l, 0xeaad8e71l, 0x6b93d5a0l, + 0xd08ed1d0l, 0xafc725e0l, 0x8e3c5b2fl, 0x8e7594b7l, + 0x8ff6e2fbl, 0xf2122b64l, 0x8888b812l, 0x900df01cl, + 0x4fad5ea0l, 0x688fc31cl, 0xd1cff191l, 0xb3a8c1adl, + 0x2f2f2218l, 0xbe0e1777l, 0xea752dfel, 0x8b021fa1l, + 0xe5a0cc0fl, 0xb56f74e8l, 0x18acf3d6l, 0xce89e299l, + 0xb4a84fe0l, 0xfd13e0b7l, 0x7cc43b81l, 0xd2ada8d9l, + 0x165fa266l, 0x80957705l, 0x93cc7314l, 0x211a1477l, + 0xe6ad2065l, 0x77b5fa86l, 0xc75442f5l, 0xfb9d35cfl, + 0xebcdaf0cl, 0x7b3e89a0l, 0xd6411bd3l, 0xae1e7e49l, + 0x00250e2dl, 0x2071b35el, 0x226800bbl, 0x57b8e0afl, + 0x2464369bl, 0xf009b91el, 0x5563911dl, 0x59dfa6aal, + 0x78c14389l, 0xd95a537fl, 0x207d5ba2l, 0x02e5b9c5l, + 0x83260376l, 0x6295cfa9l, 0x11c81968l, 0x4e734a41l, + 0xb3472dcal, 0x7b14a94al, 0x1b510052l, 0x9a532915l, + 0xd60f573fl, 0xbc9bc6e4l, 0x2b60a476l, 0x81e67400l, + 0x08ba6fb5l, 0x571be91fl, 0xf296ec6bl, 0x2a0dd915l, + 0xb6636521l, 0xe7b9f9b6l, 0xff34052el, 0xc5855664l, + 0x53b02d5dl, 0xa99f8fa1l, 0x08ba4799l, 0x6e85076al + }, + { + 0x4b7a70e9l, 0xb5b32944l, 0xdb75092el, 0xc4192623l, + 0xad6ea6b0l, 0x49a7df7dl, 0x9cee60b8l, 0x8fedb266l, + 0xecaa8c71l, 0x699a17ffl, 0x5664526cl, 0xc2b19ee1l, + 0x193602a5l, 0x75094c29l, 0xa0591340l, 0xe4183a3el, + 0x3f54989al, 0x5b429d65l, 0x6b8fe4d6l, 0x99f73fd6l, + 0xa1d29c07l, 0xefe830f5l, 0x4d2d38e6l, 0xf0255dc1l, + 0x4cdd2086l, 0x8470eb26l, 0x6382e9c6l, 0x021ecc5el, + 0x09686b3fl, 0x3ebaefc9l, 0x3c971814l, 0x6b6a70a1l, + 0x687f3584l, 0x52a0e286l, 0xb79c5305l, 0xaa500737l, + 0x3e07841cl, 0x7fdeae5cl, 0x8e7d44ecl, 0x5716f2b8l, + 0xb03ada37l, 0xf0500c0dl, 0xf01c1f04l, 0x0200b3ffl, + 0xae0cf51al, 0x3cb574b2l, 0x25837a58l, 0xdc0921bdl, + 0xd19113f9l, 0x7ca92ff6l, 0x94324773l, 0x22f54701l, + 0x3ae5e581l, 0x37c2dadcl, 0xc8b57634l, 0x9af3dda7l, + 0xa9446146l, 0x0fd0030el, 0xecc8c73el, 0xa4751e41l, + 0xe238cd99l, 0x3bea0e2fl, 0x3280bba1l, 0x183eb331l, + 0x4e548b38l, 0x4f6db908l, 0x6f420d03l, 0xf60a04bfl, + 0x2cb81290l, 0x24977c79l, 0x5679b072l, 0xbcaf89afl, + 0xde9a771fl, 0xd9930810l, 0xb38bae12l, 0xdccf3f2el, + 0x5512721fl, 0x2e6b7124l, 0x501adde6l, 0x9f84cd87l, + 0x7a584718l, 0x7408da17l, 0xbc9f9abcl, 0xe94b7d8cl, + 0xec7aec3al, 0xdb851dfal, 0x63094366l, 0xc464c3d2l, + 0xef1c1847l, 0x3215d908l, 0xdd433b37l, 0x24c2ba16l, + 0x12a14d43l, 0x2a65c451l, 0x50940002l, 0x133ae4ddl, + 0x71dff89el, 0x10314e55l, 0x81ac77d6l, 0x5f11199bl, + 0x043556f1l, 0xd7a3c76bl, 0x3c11183bl, 0x5924a509l, + 0xf28fe6edl, 0x97f1fbfal, 0x9ebabf2cl, 0x1e153c6el, + 0x86e34570l, 0xeae96fb1l, 0x860e5e0al, 0x5a3e2ab3l, + 0x771fe71cl, 0x4e3d06fal, 0x2965dcb9l, 0x99e71d0fl, + 0x803e89d6l, 0x5266c825l, 0x2e4cc978l, 0x9c10b36al, + 0xc6150ebal, 0x94e2ea78l, 0xa5fc3c53l, 0x1e0a2df4l, + 0xf2f74ea7l, 0x361d2b3dl, 0x1939260fl, 0x19c27960l, + 0x5223a708l, 0xf71312b6l, 0xebadfe6el, 0xeac31f66l, + 0xe3bc4595l, 0xa67bc883l, 0xb17f37d1l, 0x018cff28l, + 0xc332ddefl, 0xbe6c5aa5l, 0x65582185l, 0x68ab9802l, + 0xeecea50fl, 0xdb2f953bl, 0x2aef7dadl, 0x5b6e2f84l, + 0x1521b628l, 0x29076170l, 0xecdd4775l, 0x619f1510l, + 0x13cca830l, 0xeb61bd96l, 0x0334fe1el, 0xaa0363cfl, + 0xb5735c90l, 0x4c70a239l, 0xd59e9e0bl, 0xcbaade14l, + 0xeecc86bcl, 0x60622ca7l, 0x9cab5cabl, 0xb2f3846el, + 0x648b1eafl, 0x19bdf0cal, 0xa02369b9l, 0x655abb50l, + 0x40685a32l, 0x3c2ab4b3l, 0x319ee9d5l, 0xc021b8f7l, + 0x9b540b19l, 0x875fa099l, 0x95f7997el, 0x623d7da8l, + 0xf837889al, 0x97e32d77l, 0x11ed935fl, 0x16681281l, + 0x0e358829l, 0xc7e61fd6l, 0x96dedfa1l, 0x7858ba99l, + 0x57f584a5l, 0x1b227263l, 0x9b83c3ffl, 0x1ac24696l, + 0xcdb30aebl, 0x532e3054l, 0x8fd948e4l, 0x6dbc3128l, + 0x58ebf2efl, 0x34c6ffeal, 0xfe28ed61l, 0xee7c3c73l, + 0x5d4a14d9l, 0xe864b7e3l, 0x42105d14l, 0x203e13e0l, + 0x45eee2b6l, 0xa3aaabeal, 0xdb6c4f15l, 0xfacb4fd0l, + 0xc742f442l, 0xef6abbb5l, 0x654f3b1dl, 0x41cd2105l, + 0xd81e799el, 0x86854dc7l, 0xe44b476al, 0x3d816250l, + 0xcf62a1f2l, 0x5b8d2646l, 0xfc8883a0l, 0xc1c7b6a3l, + 0x7f1524c3l, 0x69cb7492l, 0x47848a0bl, 0x5692b285l, + 0x095bbf00l, 0xad19489dl, 0x1462b174l, 0x23820e00l, + 0x58428d2al, 0x0c55f5eal, 0x1dadf43el, 0x233f7061l, + 0x3372f092l, 0x8d937e41l, 0xd65fecf1l, 0x6c223bdbl, + 0x7cde3759l, 0xcbee7460l, 0x4085f2a7l, 0xce77326el, + 0xa6078084l, 0x19f8509el, 0xe8efd855l, 0x61d99735l, + 0xa969a7aal, 0xc50c06c2l, 0x5a04abfcl, 0x800bcadcl, + 0x9e447a2el, 0xc3453484l, 0xfdd56705l, 0x0e1e9ec9l, + 0xdb73dbd3l, 0x105588cdl, 0x675fda79l, 0xe3674340l, + 0xc5c43465l, 0x713e38d8l, 0x3d28f89el, 0xf16dff20l, + 0x153e21e7l, 0x8fb03d4al, 0xe6e39f2bl, 0xdb83adf7l + }, + { + 0xe93d5a68l, 0x948140f7l, 0xf64c261cl, 0x94692934l, + 0x411520f7l, 0x7602d4f7l, 0xbcf46b2el, 0xd4a20068l, + 0xd4082471l, 0x3320f46al, 0x43b7d4b7l, 0x500061afl, + 0x1e39f62el, 0x97244546l, 0x14214f74l, 0xbf8b8840l, + 0x4d95fc1dl, 0x96b591afl, 0x70f4ddd3l, 0x66a02f45l, + 0xbfbc09ecl, 0x03bd9785l, 0x7fac6dd0l, 0x31cb8504l, + 0x96eb27b3l, 0x55fd3941l, 0xda2547e6l, 0xabca0a9al, + 0x28507825l, 0x530429f4l, 0x0a2c86dal, 0xe9b66dfbl, + 0x68dc1462l, 0xd7486900l, 0x680ec0a4l, 0x27a18deel, + 0x4f3ffea2l, 0xe887ad8cl, 0xb58ce006l, 0x7af4d6b6l, + 0xaace1e7cl, 0xd3375fecl, 0xce78a399l, 0x406b2a42l, + 0x20fe9e35l, 0xd9f385b9l, 0xee39d7abl, 0x3b124e8bl, + 0x1dc9faf7l, 0x4b6d1856l, 0x26a36631l, 0xeae397b2l, + 0x3a6efa74l, 0xdd5b4332l, 0x6841e7f7l, 0xca7820fbl, + 0xfb0af54el, 0xd8feb397l, 0x454056acl, 0xba489527l, + 0x55533a3al, 0x20838d87l, 0xfe6ba9b7l, 0xd096954bl, + 0x55a867bcl, 0xa1159a58l, 0xcca92963l, 0x99e1db33l, + 0xa62a4a56l, 0x3f3125f9l, 0x5ef47e1cl, 0x9029317cl, + 0xfdf8e802l, 0x04272f70l, 0x80bb155cl, 0x05282ce3l, + 0x95c11548l, 0xe4c66d22l, 0x48c1133fl, 0xc70f86dcl, + 0x07f9c9eel, 0x41041f0fl, 0x404779a4l, 0x5d886e17l, + 0x325f51ebl, 0xd59bc0d1l, 0xf2bcc18fl, 0x41113564l, + 0x257b7834l, 0x602a9c60l, 0xdff8e8a3l, 0x1f636c1bl, + 0x0e12b4c2l, 0x02e1329el, 0xaf664fd1l, 0xcad18115l, + 0x6b2395e0l, 0x333e92e1l, 0x3b240b62l, 0xeebeb922l, + 0x85b2a20el, 0xe6ba0d99l, 0xde720c8cl, 0x2da2f728l, + 0xd0127845l, 0x95b794fdl, 0x647d0862l, 0xe7ccf5f0l, + 0x5449a36fl, 0x877d48fal, 0xc39dfd27l, 0xf33e8d1el, + 0x0a476341l, 0x992eff74l, 0x3a6f6eabl, 0xf4f8fd37l, + 0xa812dc60l, 0xa1ebddf8l, 0x991be14cl, 0xdb6e6b0dl, + 0xc67b5510l, 0x6d672c37l, 0x2765d43bl, 0xdcd0e804l, + 0xf1290dc7l, 0xcc00ffa3l, 0xb5390f92l, 0x690fed0bl, + 0x667b9ffbl, 0xcedb7d9cl, 0xa091cf0bl, 0xd9155ea3l, + 0xbb132f88l, 0x515bad24l, 0x7b9479bfl, 0x763bd6ebl, + 0x37392eb3l, 0xcc115979l, 0x8026e297l, 0xf42e312dl, + 0x6842ada7l, 0xc66a2b3bl, 0x12754cccl, 0x782ef11cl, + 0x6a124237l, 0xb79251e7l, 0x06a1bbe6l, 0x4bfb6350l, + 0x1a6b1018l, 0x11caedfal, 0x3d25bdd8l, 0xe2e1c3c9l, + 0x44421659l, 0x0a121386l, 0xd90cec6el, 0xd5abea2al, + 0x64af674el, 0xda86a85fl, 0xbebfe988l, 0x64e4c3fel, + 0x9dbc8057l, 0xf0f7c086l, 0x60787bf8l, 0x6003604dl, + 0xd1fd8346l, 0xf6381fb0l, 0x7745ae04l, 0xd736fcccl, + 0x83426b33l, 0xf01eab71l, 0xb0804187l, 0x3c005e5fl, + 0x77a057bel, 0xbde8ae24l, 0x55464299l, 0xbf582e61l, + 0x4e58f48fl, 0xf2ddfda2l, 0xf474ef38l, 0x8789bdc2l, + 0x5366f9c3l, 0xc8b38e74l, 0xb475f255l, 0x46fcd9b9l, + 0x7aeb2661l, 0x8b1ddf84l, 0x846a0e79l, 0x915f95e2l, + 0x466e598el, 0x20b45770l, 0x8cd55591l, 0xc902de4cl, + 0xb90bace1l, 0xbb8205d0l, 0x11a86248l, 0x7574a99el, + 0xb77f19b6l, 0xe0a9dc09l, 0x662d09a1l, 0xc4324633l, + 0xe85a1f02l, 0x09f0be8cl, 0x4a99a025l, 0x1d6efe10l, + 0x1ab93d1dl, 0x0ba5a4dfl, 0xa186f20fl, 0x2868f169l, + 0xdcb7da83l, 0x573906fel, 0xa1e2ce9bl, 0x4fcd7f52l, + 0x50115e01l, 0xa70683fal, 0xa002b5c4l, 0x0de6d027l, + 0x9af88c27l, 0x773f8641l, 0xc3604c06l, 0x61a806b5l, + 0xf0177a28l, 0xc0f586e0l, 0x006058aal, 0x30dc7d62l, + 0x11e69ed7l, 0x2338ea63l, 0x53c2dd94l, 0xc2c21634l, + 0xbbcbee56l, 0x90bcb6del, 0xebfc7da1l, 0xce591d76l, + 0x6f05e409l, 0x4b7c0188l, 0x39720a3dl, 0x7c927c24l, + 0x86e3725fl, 0x724d9db9l, 0x1ac15bb4l, 0xd39eb8fcl, + 0xed545578l, 0x08fca5b5l, 0xd83d7cd3l, 0x4dad0fc4l, + 0x1e50ef5el, 0xb161e6f8l, 0xa28514d9l, 0x6c51133cl, + 0x6fd5c7e7l, 0x56e14ec4l, 0x362abfcel, 0xddc6c837l, + 0xd79a3234l, 0x92638212l, 0x670efa8el, 0x406000e0l + }, + { + 0x3a39ce37l, 0xd3faf5cfl, 0xabc27737l, 0x5ac52d1bl, + 0x5cb0679el, 0x4fa33742l, 0xd3822740l, 0x99bc9bbel, + 0xd5118e9dl, 0xbf0f7315l, 0xd62d1c7el, 0xc700c47bl, + 0xb78c1b6bl, 0x21a19045l, 0xb26eb1bel, 0x6a366eb4l, + 0x5748ab2fl, 0xbc946e79l, 0xc6a376d2l, 0x6549c2c8l, + 0x530ff8eel, 0x468dde7dl, 0xd5730a1dl, 0x4cd04dc6l, + 0x2939bbdbl, 0xa9ba4650l, 0xac9526e8l, 0xbe5ee304l, + 0xa1fad5f0l, 0x6a2d519al, 0x63ef8ce2l, 0x9a86ee22l, + 0xc089c2b8l, 0x43242ef6l, 0xa51e03aal, 0x9cf2d0a4l, + 0x83c061bal, 0x9be96a4dl, 0x8fe51550l, 0xba645bd6l, + 0x2826a2f9l, 0xa73a3ae1l, 0x4ba99586l, 0xef5562e9l, + 0xc72fefd3l, 0xf752f7dal, 0x3f046f69l, 0x77fa0a59l, + 0x80e4a915l, 0x87b08601l, 0x9b09e6adl, 0x3b3ee593l, + 0xe990fd5al, 0x9e34d797l, 0x2cf0b7d9l, 0x022b8b51l, + 0x96d5ac3al, 0x017da67dl, 0xd1cf3ed6l, 0x7c7d2d28l, + 0x1f9f25cfl, 0xadf2b89bl, 0x5ad6b472l, 0x5a88f54cl, + 0xe029ac71l, 0xe019a5e6l, 0x47b0acfdl, 0xed93fa9bl, + 0xe8d3c48dl, 0x283b57ccl, 0xf8d56629l, 0x79132e28l, + 0x785f0191l, 0xed756055l, 0xf7960e44l, 0xe3d35e8cl, + 0x15056dd4l, 0x88f46dbal, 0x03a16125l, 0x0564f0bdl, + 0xc3eb9e15l, 0x3c9057a2l, 0x97271aecl, 0xa93a072al, + 0x1b3f6d9bl, 0x1e6321f5l, 0xf59c66fbl, 0x26dcf319l, + 0x7533d928l, 0xb155fdf5l, 0x03563482l, 0x8aba3cbbl, + 0x28517711l, 0xc20ad9f8l, 0xabcc5167l, 0xccad925fl, + 0x4de81751l, 0x3830dc8el, 0x379d5862l, 0x9320f991l, + 0xea7a90c2l, 0xfb3e7bcel, 0x5121ce64l, 0x774fbe32l, + 0xa8b6e37el, 0xc3293d46l, 0x48de5369l, 0x6413e680l, + 0xa2ae0810l, 0xdd6db224l, 0x69852dfdl, 0x09072166l, + 0xb39a460al, 0x6445c0ddl, 0x586cdecfl, 0x1c20c8ael, + 0x5bbef7ddl, 0x1b588d40l, 0xccd2017fl, 0x6bb4e3bbl, + 0xdda26a7el, 0x3a59ff45l, 0x3e350a44l, 0xbcb4cdd5l, + 0x72eacea8l, 0xfa6484bbl, 0x8d6612ael, 0xbf3c6f47l, + 0xd29be463l, 0x542f5d9el, 0xaec2771bl, 0xf64e6370l, + 0x740e0d8dl, 0xe75b1357l, 0xf8721671l, 0xaf537d5dl, + 0x4040cb08l, 0x4eb4e2ccl, 0x34d2466al, 0x0115af84l, + 0xe1b00428l, 0x95983a1dl, 0x06b89fb4l, 0xce6ea048l, + 0x6f3f3b82l, 0x3520ab82l, 0x011a1d4bl, 0x277227f8l, + 0x611560b1l, 0xe7933fdcl, 0xbb3a792bl, 0x344525bdl, + 0xa08839e1l, 0x51ce794bl, 0x2f32c9b7l, 0xa01fbac9l, + 0xe01cc87el, 0xbcc7d1f6l, 0xcf0111c3l, 0xa1e8aac7l, + 0x1a908749l, 0xd44fbd9al, 0xd0dadecbl, 0xd50ada38l, + 0x0339c32al, 0xc6913667l, 0x8df9317cl, 0xe0b12b4fl, + 0xf79e59b7l, 0x43f5bb3al, 0xf2d519ffl, 0x27d9459cl, + 0xbf97222cl, 0x15e6fc2al, 0x0f91fc71l, 0x9b941525l, + 0xfae59361l, 0xceb69cebl, 0xc2a86459l, 0x12baa8d1l, + 0xb6c1075el, 0xe3056a0cl, 0x10d25065l, 0xcb03a442l, + 0xe0ec6e0el, 0x1698db3bl, 0x4c98a0bel, 0x3278e964l, + 0x9f1f9532l, 0xe0d392dfl, 0xd3a0342bl, 0x8971f21el, + 0x1b0a7441l, 0x4ba3348cl, 0xc5be7120l, 0xc37632d8l, + 0xdf359f8dl, 0x9b992f2el, 0xe60b6f47l, 0x0fe3f11dl, + 0xe54cda54l, 0x1edad891l, 0xce6279cfl, 0xcd3e7e6fl, + 0x1618b166l, 0xfd2c1d05l, 0x848fd2c5l, 0xf6fb2299l, + 0xf523f357l, 0xa6327623l, 0x93a83531l, 0x56cccd02l, + 0xacf08162l, 0x5a75ebb5l, 0x6e163697l, 0x88d273ccl, + 0xde966292l, 0x81b949d0l, 0x4c50901bl, 0x71c65614l, + 0xe6c6c7bdl, 0x327a140al, 0x45e1d006l, 0xc3f27b9al, + 0xc9aa53fdl, 0x62a80f00l, 0xbb25bfe2l, 0x35bdd2f6l, + 0x71126905l, 0xb2040222l, 0xb6cbcf7cl, 0xcd769c2bl, + 0x53113ec0l, 0x1640e3d3l, 0x38abbd60l, 0x2547adf0l, + 0xba38209cl, 0xf746ce76l, 0x77afa1c5l, 0x20756060l, + 0x85cbfe4el, 0x8ae88dd8l, 0x7aaaf9b0l, 0x4cf9aa7el, + 0x1948c25cl, 0x02fb8a8cl, 0x01c36ae4l, 0xd6ebe1f9l, + 0x90d4f869l, 0xa65cdea0l, 0x3f09252dl, 0xc208e69fl, + 0xb74e6132l, 0xce77e25bl, 0x578fdfe3l, 0x3ac372e6l + } +}; + +/** @internal Original P-Array (hexdigits of pi) */ + +static const BLOWFISH_ULONG _BLOWFISH_PArray [ BLOWFISH_SUBKEYS ] = +{ + 0x243f6a88l, 0x85a308d3l, 0x13198a2el, + 0x03707344l, 0xa4093822l, 0x299f31d0l, + 0x082efa98l, 0xec4e6c89l, 0x452821e6l, + 0x38d01377l, 0xbe5466cfl, 0x34e90c6cl, + 0xc0ac29b7l, 0xc97c50ddl, 0x3f84d5b5l, + 0xb5470917l, 0x9216d5d9l, 0x8979fb1bl +}; + +/** + + @internal + + Set the mode and original initialisation vector in a context record. + + @param Context Pointer to a context record to set the mode and initialisation vector. + + @param Mode Mode to use when enciphering/decipering blocks. For supported modes see #BLOWFISH_MODE. + + @param IvHigh32 High 32-bits of the initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB. + + @param IvLow32 Low 32-bits of the initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB. + + @remarks It is an unchecked runtime error to supply a null pointer to this function. + + @return #BLOWFISH_RC_SUCCESS The mode and original initialisation vector were set successfully. + + @return #BLOWFISH_RC_INVALID_MODE The mode supplied was invalid. + + */ + +static BLOWFISH_RC _BLOWFISH_SetMode ( BLOWFISH_PCONTEXT Context, BLOWFISH_MODE Mode, BLOWFISH_ULONG IvHigh32, BLOWFISH_ULONG IvLow32 ) +{ + /* Validate the block cipher mode, and set pointers to the encipher/decipher stream callbacks */ + + switch ( Mode ) + { + case BLOWFISH_MODE_ECB: + { + Context->EncipherStream = &_BLOWFISH_EncipherStream_ECB; + Context->DecipherStream = &_BLOWFISH_DecipherStream_ECB; + + break; + } + case BLOWFISH_MODE_CBC: + { + Context->EncipherStream = &_BLOWFISH_EncipherStream_CBC; + Context->DecipherStream = &_BLOWFISH_DecipherStream_CBC; + + break; + } + case BLOWFISH_MODE_CFB: + { + Context->EncipherStream = &_BLOWFISH_EncipherStream_CFB; + Context->DecipherStream = &_BLOWFISH_DecipherStream_CFB; + + break; + } + case BLOWFISH_MODE_OFB: + { + Context->EncipherStream = &_BLOWFISH_EncipherDecipherStream_OFB; + Context->DecipherStream = &_BLOWFISH_EncipherDecipherStream_OFB; + + break; + } + case BLOWFISH_MODE_CTR: + { + Context->EncipherStream = &_BLOWFISH_EncipherDecipherStream_CTR; + Context->DecipherStream = &_BLOWFISH_EncipherDecipherStream_CTR; + + break; + } + default: + { + return BLOWFISH_RC_INVALID_MODE; + } + } + + /* Save the initialisation vector */ + + Context->OriginalIvHigh32 = IvHigh32; + Context->OriginalIvLow32 = IvLow32; + + return BLOWFISH_RC_SUCCESS; +} + +/** + + @internal + + Initialise the P-Array and S-Boxes in a context record based on the key. + + @param Context Pointer to a context record to initialise. + + @param Key Pointer to the key. + + @param KeyLength Length of the Key buffer. + + @remarks It is an unchecked runtime error to supply a null pointer to this function. + + @return #BLOWFISH_RC_SUCCESS Successfully initialised the context record. + + @return #BLOWFISH_RC_INVALID_KEY The length of the key is invalid. + + @return #BLOWFISH_RC_WEAK_KEY The key has been deemed to be weak. + + */ + +static BLOWFISH_RC _BLOWFISH_SetKey ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR Key, BLOWFISH_SIZE_T KeyLength ) +{ + BLOWFISH_SIZE_T i; + BLOWFISH_SIZE_T j; + BLOWFISH_SIZE_T k; + BLOWFISH_ULONG Data = 0; + BLOWFISH_ULONG XLeft = 0; + BLOWFISH_ULONG XRight = 0; + + /* Ensure the key length is valid, ( between 4 and 56 bytes ) */ + + if ( KeyLength < BLOWFISH_MIN_KEY_LENGTH || KeyLength > BLOWFISH_MAX_KEY_LENGTH ) + { + return BLOWFISH_RC_INVALID_KEY; + } + + /* Copy the original S-Boxes to the context */ + + for ( i = 0; i < BLOWFISH_SBOXES; i++ ) + { + for ( j = 0; j < BLOWFISH_SBOX_ENTRIES; j++ ) + { + Context->SBox [ i ] [ j ] = _BLOWFISH_SBox [ i ] [ j ]; + } + } + + /* XOR the original P-Array and key into the context P-Array */ + + for ( i = 0, j = 0; i < BLOWFISH_SUBKEYS; i++ ) + { + for ( k = 0; k < 4; k++ ) + { + Data = ( Data << 8 ) | Key [ j ]; + + /* Have we reached the end of the key? */ + + j++; + + if ( j >= KeyLength ) + { + /* Resume from the begining of the key */ + + j = 0; + } + } + + Context->PArray [ i ] = _BLOWFISH_PArray [ i ] ^ Data; + } + + /* Update all entries in the context P-Array with output from the continuously changing blowfish algorithm */ + + for ( i = 0; i < BLOWFISH_SUBKEYS; i += 2 ) + { + BLOWFISH_Encipher ( Context, &XLeft, &XRight ); + + Context->PArray [ i ] = XLeft; + Context->PArray [ i + 1 ] = XRight; + } + + /* Update all entries in the context S-Boxes with output from the continuously changing blowfish algorithm */ + + for ( i = 0; i < BLOWFISH_SBOXES; i++ ) + { + for ( j = 0; j < BLOWFISH_SBOX_ENTRIES; j += 2 ) + { + BLOWFISH_Encipher ( Context, &XLeft, &XRight ); + + /* Test the strength of the key */ + + if ( XLeft == XRight ) + { + return BLOWFISH_RC_WEAK_KEY; + } + + Context->SBox [ i ] [ j ] = XLeft; + Context->SBox [ i ] [ j + 1 ] = XRight; + } + } + + return BLOWFISH_RC_SUCCESS; +} + +BLOWFISH_RC BLOWFISH_Init ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR Key, BLOWFISH_SIZE_T KeyLength, BLOWFISH_MODE Mode, BLOWFISH_ULONG IvHigh32, BLOWFISH_ULONG IvLow32 ) +{ + BLOWFISH_RC ReturnCode; + + /* Ensure pointers are valid */ + + if ( Context == 0 || Key == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Set the mode and initialisation vector */ + + ReturnCode = _BLOWFISH_SetMode ( Context, Mode, IvHigh32, IvLow32 ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Initialise the P-Array and S-Boxes based on the key */ + + ReturnCode = _BLOWFISH_SetKey ( Context, Key, KeyLength ); + } + + return ReturnCode; +} + +BLOWFISH_RC BLOWFISH_Reset ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR Key, BLOWFISH_SIZE_T KeyLength, BLOWFISH_MODE Mode, BLOWFISH_ULONG IvHigh32, BLOWFISH_ULONG IvLow32 ) +{ + BLOWFISH_RC ReturnCode = BLOWFISH_RC_SUCCESS; + + /* Ensure the context pointer is valid */ + + if ( Context == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Has a new mode been specified */ + + if ( Mode != BLOWFISH_MODE_CURRENT ) + { + /* Reinitialise the mode and initialisation vector */ + + ReturnCode = _BLOWFISH_SetMode ( Context, Mode, IvHigh32, IvLow32 ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + return ReturnCode; + } + } + + /* Has a new key been specified? */ + + if ( Key != 0 ) + { + /* Reinitialise the P-Array and S-Boxes based on the new key */ + + ReturnCode = _BLOWFISH_SetKey ( Context, Key, KeyLength ); + } + + return ReturnCode; +} + +BLOWFISH_RC BLOWFISH_CloneContext ( BLOWFISH_PCONTEXT InContext, BLOWFISH_PCONTEXT OutContext ) +{ + if ( InContext == 0 || OutContext == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Copy the context record */ + + *OutContext = *InContext; + + return BLOWFISH_RC_SUCCESS; +} + +BLOWFISH_RC BLOWFISH_Exit ( BLOWFISH_PCONTEXT Context ) +{ + BLOWFISH_PUCHAR MemoryToWipe = (BLOWFISH_PUCHAR)Context; + BLOWFISH_SIZE_T i; + + /* Ensure the context pointer is valid */ + + if ( Context == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Overwrite the context record with null bytes (do not use memset!) */ + + for ( i = 0; i < (BLOWFISH_SIZE_T)sizeof ( *Context ); i++ ) + { + MemoryToWipe [ i ] = 0x00; + } + + return BLOWFISH_RC_SUCCESS; +} + +/** + + @internal + + Restore the original initialisation vector in a context record. + + @param Context Pointer to an initialised context record. + +*/ + +#define _BLOWFISH_BEGINSTREAM( Context ) \ +{ \ + Context->IvHigh32 = Context->OriginalIvHigh32; \ + Context->IvLow32 = Context->OriginalIvLow32; \ +} + +BLOWFISH_RC BLOWFISH_BeginStream ( BLOWFISH_PCONTEXT Context ) +{ + /* Ensure the context pointer is valid */ + + if ( Context == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + _BLOWFISH_BEGINSTREAM ( Context ); + + return BLOWFISH_RC_SUCCESS; +} + +/** + + @internal + + Overwrite the final initialisation vector in a context record. + + @param Context Pointer to an initialised context record. + +*/ + +#define _BLOWFISH_ENDSTREAM( Context ) \ +{ \ + Context->IvHigh32 = 0; \ + Context->IvLow32 = 0; \ +} + +BLOWFISH_RC BLOWFISH_EndStream ( BLOWFISH_PCONTEXT Context ) +{ + /* Ensure the context pointer is valid */ + + if ( Context == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + _BLOWFISH_ENDSTREAM ( Context ); + + return BLOWFISH_RC_SUCCESS; +} + +/** + + @internal + + Perform a single round of the cipher. + + xL = xL XOR Pn + + xR = F(xL) XOR xR + + Divide xL into four eight-bit quarters: a, b, c, and d. + + Then, F(xL) = ((S0,a + S1,b mod 232) XOR S2,c) + S3,d mod 232. + + See @link glossary @endlink for more information. + + @remarks After each round the caller must swap xL and xR. + + @param XLeft High 32-bits of the message to encipher. + + @param XRight Low 32-bits of the message to encipher. + + @param P Pointer to the P-Array. + + @param S0, S1, S2, S3 Pointers to each element of the S-Box array. + + @param Round Current round to perform (0-15 to encipher, 17-2 to decipher). + + */ + +#define _BLOWFISH_CIPHER( XLeft, XRight, P, S0, S1, S2, S3, Round ) \ +{ \ + XLeft ^= P [ Round ]; \ + XRight ^= ( ( ( S0 [ XLeft >> 24 ] + \ + S1 [ ( XLeft >> 16 ) & 0xff ] ) ^ \ + S2 [ ( XLeft >> 8 ) & 0xff ] ) + \ + S3 [ XLeft & 0xff ] ); \ +} + +/** + + @internal + + Perform 16-round encipher, finalise round and unswap xL and xR: + + xR = xR XOR P18 + + xL = xL XOR P17 + + See @link glossary @endlink for more information. + + @param BufferHigh Pointer to the high 32-bits of the output buffer. + + @param BufferLow Pointer to the low 32-bits of the output buffer. + + @param XLeft High 32-bits of the message to encipher. + + @param XRight Low 32-bits of the message to encipher. + + @param P Pointer to the P-Array. + + @param S0, S1, S2, S3 Pointers to each element of the S-Box array. + + @remarks If BufferHigh and BufferLow are the same variables as XLeft and XRight then the result will not be swapped! + + */ + +#define _BLOWFISH_ENCIPHER( BufferHigh, BufferLow, XLeft, XRight, P, S0, S1, S2, S3 ) \ +{ \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 0 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 1 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 2 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 3 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 4 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 5 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 6 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 7 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 8 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 9 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 10 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 11 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 12 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 13 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 14 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 15 ); \ + BufferLow = XLeft ^ P [ 16 ]; \ + BufferHigh = XRight ^ P [ 17 ]; \ +} + +void BLOWFISH_Encipher ( BLOWFISH_PCONTEXT Context, BLOWFISH_PULONG High32, BLOWFISH_PULONG Low32 ) +{ + BLOWFISH_ULONG XLeft = *High32; + BLOWFISH_ULONG XRight = *Low32; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + + /* Encipher 8-byte plaintext block */ + + _BLOWFISH_ENCIPHER ( *High32, *Low32, XLeft, XRight, P, S0, S1, S2, S3 ); + + return; +} + +/** + + @internal + + Encipher a stream of data in electronic codebook mode. + + Cn = Ek ( Pn ) + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param PlainTextStream Buffer of plaintext to encipher. + + @param CipherTextStream Buffer to receive the ciphertext. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + @remarks This function can be parallelised using OpenMP. + + */ + +static void _BLOWFISH_EncipherStream_ECB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG PlainTextStream, BLOWFISH_PULONG CipherTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft; + BLOWFISH_ULONG XRight; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + + /* Encipher plaintext in 8-byte blocks */ + +#ifdef _OPENMP + + #pragma omp parallel for default ( none ) private ( i, XLeft, XRight ) shared ( PlainTextStream, CipherTextStream, P, S0, S1, S2, S3, StreamLength ) schedule ( static ) + +#endif + + for ( i = 0; i < StreamLength; i += 2 ) + { + XLeft = PlainTextStream [ i ]; + XRight = PlainTextStream [ i + 1 ]; + + _BLOWFISH_ENCIPHER ( CipherTextStream [ i ], CipherTextStream [ i + 1 ], XLeft, XRight, P, S0, S1, S2, S3 ); + } + + return; +} + +/** + + @internal + + Encipher a stream of data in cipher block chaining mode. + + Round 1: + + C0 = Ek ( P0 XOR Iv ) + + Round n: + + Cn = Ek ( Pn XOR ( Cn - 1 ) ) + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param PlainTextStream Buffer of plaintext to encipher. + + @param CipherTextStream Buffer to receive the ciphertext. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + */ + +static void _BLOWFISH_EncipherStream_CBC ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG PlainTextStream, BLOWFISH_PULONG CipherTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft; + BLOWFISH_ULONG XRight; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + + /* XOR the first block of plaintext with the initialisation vector */ + + XLeft = PlainTextStream [ 0 ] ^ Context->IvHigh32; + XRight = PlainTextStream [ 1 ] ^ Context->IvLow32; + + /* Encipher the first block of plaintext */ + + _BLOWFISH_ENCIPHER ( CipherTextStream [ 0 ], CipherTextStream [ 1 ], XLeft, XRight, P, S0, S1, S2, S3 ); + + /* Encrypt any remaining blocks */ + + for ( i = 2; i < StreamLength; i += 2 ) + { + /* XOR the block of plaintext with the previous block of ciphertext */ + + XLeft = PlainTextStream [ i ] ^ CipherTextStream [ i - 2 ]; + XRight = PlainTextStream [ i + 1 ] ^ CipherTextStream [ i - 1 ]; + + /* Encipher the block of plaintext */ + + _BLOWFISH_ENCIPHER ( CipherTextStream [ i ], CipherTextStream [ i + 1 ], XLeft, XRight, P, S0, S1, S2, S3 ); + } + + /* Preserve the previous block of ciphertext as the new initialisation vector for stream based operations */ + + Context->IvHigh32 = CipherTextStream [ i - 2 ]; + Context->IvLow32 = CipherTextStream [ i - 1 ]; + + return; +} + +/** + + @internal + + Encipher a stream of data in cipher feedback mode. + + Round 1: + + C0 = P0 XOR Ek ( Iv ) + + Round n: + + Cn = Pn XOR Ek ( ( Cn - 1 ) ) + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param PlainTextStream Buffer of plaintext to encipher. + + @param CipherTextStream Buffer to receive the ciphertext. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + */ + +static void _BLOWFISH_EncipherStream_CFB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG PlainTextStream, BLOWFISH_PULONG CipherTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft = Context->IvHigh32; + BLOWFISH_ULONG XRight = Context->IvLow32; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + + /* Encipher the initialisation vector */ + + _BLOWFISH_ENCIPHER ( XRight, XLeft, XLeft, XRight, P, S0, S1, S2, S3 ); + + /* XOR the enciphered initialisation vector with the plaintext to yeild the ciphertext */ + + XRight ^= PlainTextStream [ 0 ]; + XLeft ^= PlainTextStream [ 1 ]; + + CipherTextStream [ 0 ] = XRight; + CipherTextStream [ 1 ] = XLeft; + + for ( i = 2; i < StreamLength; i += 2 ) + { + /* Encipher the previous block of ciphertext */ + + XLeft = CipherTextStream [ i - 2 ]; + XRight = CipherTextStream [ i - 1 ]; + + _BLOWFISH_ENCIPHER ( XRight, XLeft, XLeft, XRight, P, S0, S1, S2, S3 ); + + /* XOR the enciphered previous block of ciphertext with the plaintext to yeild the current block of ciphertext */ + + XRight ^= PlainTextStream [ i ]; + XLeft ^= PlainTextStream [ i + 1 ]; + + CipherTextStream [ i ] = XRight; + CipherTextStream [ i + 1 ] = XLeft; + } + + /* Preserve the previous block of ciphertext as the new initialisation vector for stream based operations */ + + Context->IvHigh32 = XRight; + Context->IvLow32 = XLeft; + + return; +} + +/** + + @internal + + Encipher/Decipher a stream of data in output feedback mode. + + Iv = Ek ( Iv ) + + Cn = Pn XOR Iv + + To decipher simply swap C and P. + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param InStream Pointer to either a buffer of plaintext to encipher, or a buffer of ciphertext to decipher. + + @param OutStream Pointer to a buffer to receive either the ciphertext or plaintext output. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + */ + +static void _BLOWFISH_EncipherDecipherStream_OFB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG InStream, BLOWFISH_PULONG OutStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft = Context->IvHigh32; + BLOWFISH_ULONG XRight = Context->IvLow32; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + + for ( i = 0; i < StreamLength; i += 2 ) + { + /* Encipher the initialisation vector */ + + _BLOWFISH_ENCIPHER ( XRight, XLeft, XLeft, XRight, P, S0, S1, S2, S3 ); + + /* Store and swap the enciphered initialisation vector */ + + OutStream [ i ] = XRight; + OutStream [ i + 1 ] = XLeft; + + XLeft = OutStream [ i ]; + XRight = OutStream [ i + 1 ]; + + /* XOR the enciphered initialisation vector with the ciphertext or plaintext */ + + OutStream [ i ] ^= InStream [ i ]; + OutStream [ i + 1 ] ^= InStream [ i + 1 ]; + } + + /* Preserve the enciphered initialisation vector as the new initialisation vector for stream based operations */ + + Context->IvHigh32 = XLeft; + Context->IvLow32 = XRight; + + return; +} + +/** + + @internal + + Encipher/Decipher a stream of data in counter (segmented integer counter) mode. + + O = Ek ( Iv ADD ( n ) ) + + Cn = Pn XOR O + + To decipher simply swap C and P. + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param InStream Pointer to either a buffer of plaintext to encipher, or a buffer of ciphertext to decipher. + + @param OutStream Pointer to a buffer to receive either the ciphertext or plaintext output. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + @remarks This function can be parallelised using OpenMP. + + */ + +static void _BLOWFISH_EncipherDecipherStream_CTR ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG InStream, BLOWFISH_PULONG OutStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft; + BLOWFISH_ULONG XRight; + BLOWFISH_ULONG IvHigh32 = Context->IvHigh32; + BLOWFISH_ULONG IvLow32 = Context->IvLow32; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + +#ifdef _OPENMP + + #pragma omp parallel for default ( none ) private ( i, XLeft, XRight ) shared ( InStream, OutStream, IvHigh32, IvLow32, P, S0, S1, S2, S3, StreamLength ) schedule ( static ) + +#endif + + for ( i = 0; i < StreamLength; i += 2 ) + { + /* Encipher the initialisation vector added with the counter */ + + XLeft = IvHigh32 + (BLOWFISH_ULONG)i; + XRight = IvLow32 + (BLOWFISH_ULONG)( i + 1 ); + + _BLOWFISH_ENCIPHER ( XRight, XLeft, XLeft, XRight, P, S0, S1, S2, S3 ); + + /* XOR the enciphered initialisation vector with the plaintext or ciphertext */ + + OutStream [ i ] = InStream [ i ] ^ XRight; + OutStream [ i + 1 ] = InStream [ i + 1 ] ^ XLeft; + } + + /* Preserve the initialisation vector added with the counter as the new initialisation vector for stream based operations */ + + Context->IvHigh32 += (BLOWFISH_ULONG)StreamLength; + Context->IvLow32 += (BLOWFISH_ULONG)( StreamLength + 1 ); + + return; +} + +BLOWFISH_RC BLOWFISH_EncipherStream ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR PlainTextStream, BLOWFISH_PUCHAR CipherTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + /* Ensure the context and stream buffer pointers are non null */ + + if ( Context == 0 || PlainTextStream == 0 || CipherTextStream == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Ensure the stream length is a multiple of 8 */ + + if ( ( StreamLength & ~0x07 ) == 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#ifdef _OPENMP + + /* Ensure the stream length is not negative */ + + if ( StreamLength < 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#endif + + /* Encipher stream based on block cipher mode */ + + Context->EncipherStream ( Context, (BLOWFISH_PCULONG)PlainTextStream, (BLOWFISH_PULONG)CipherTextStream, StreamLength >> 2 ); + + return BLOWFISH_RC_SUCCESS; +} + +BLOWFISH_RC BLOWFISH_EncipherBuffer ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR PlainTextBuffer, BLOWFISH_PUCHAR CipherTextBuffer, BLOWFISH_SIZE_T BufferLength ) +{ + /* Ensure the context and buffer pointers are non null */ + + if ( Context == 0 || CipherTextBuffer == 0 || PlainTextBuffer == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Ensure the buffer length is a multiple of 8 */ + + if ( ( BufferLength & ~0x07 ) == 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#ifdef _OPENMP + + /* Ensure the buffer length is not negative */ + + if ( BufferLength < 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#endif + + /* Encipher buffer as a stream based on the block cipher mode */ + + _BLOWFISH_BEGINSTREAM ( Context ); + + Context->EncipherStream ( Context, (BLOWFISH_PCULONG)PlainTextBuffer, (BLOWFISH_PULONG)CipherTextBuffer, BufferLength >> 2 ); + + _BLOWFISH_ENDSTREAM ( Context ); + + return BLOWFISH_RC_SUCCESS; +} + +/** + + @internal + + Perform 16-round decipher, finalise round and unswap xL and xR: + + xR = xR XOR P0 + + xL = xL XOR P1 + + See @link glossary @endlink for more information. + + @param BufferHigh Pointer to the high 32-bits of the output buffer. + + @param BufferLow Pointer to the low 32-bits of the output buffer. + + @param XLeft High 32-bits of the message to decipher. + + @param XRight Low 32-bits of the message to decipher. + + @param P Pointer to the P-Array. + + @param S0, S1, S2, S3 Pointers to each element of the S-Box array. + + @remarks If BufferHigh and BufferLow are the same variables as XLeft and XRight then the result will not be swapped! + + */ + +#define _BLOWFISH_DECIPHER( BufferHigh, BufferLow, XLeft, XRight, P, S0, S1, S2, S3 ) \ +{ \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 17 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 16 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 15 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 14 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 13 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 12 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 11 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 10 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 9 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 8 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 7 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 6 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 5 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 4 ); \ + _BLOWFISH_CIPHER ( XLeft, XRight, P, S0, S1, S2, S3, 3 ); \ + _BLOWFISH_CIPHER ( XRight, XLeft, P, S0, S1, S2, S3, 2 ); \ + BufferHigh = XRight ^ P [ 0 ]; \ + BufferLow = XLeft ^ P [ 1 ]; \ +} + +void BLOWFISH_Decipher ( BLOWFISH_PCONTEXT Context, BLOWFISH_PULONG High32, BLOWFISH_PULONG Low32 ) +{ + BLOWFISH_ULONG XLeft = *High32; + BLOWFISH_ULONG XRight = *Low32; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + + /* Decipher 8-byte plaintext block */ + + _BLOWFISH_DECIPHER ( *High32, *Low32, XLeft, XRight, P, S0, S1, S2, S3 ); + + return; +} + +/** + + @internal + + Decipher a stream of data in electronic codebook mode. + + Pn = Ek ( Cn ) + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param CipherTextStream Buffer of ciphertext to decipher. + + @param CipherTextStream Buffer to receive the plaintext. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + @remarks This function can be parallelised using OpenMP. + + */ + +static void _BLOWFISH_DecipherStream_ECB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG CipherTextStream, BLOWFISH_PULONG PlainTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft; + BLOWFISH_ULONG XRight; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + + /* Decipher ciphertext in 8-byte blocks */ + +#ifdef _OPENMP + + #pragma omp parallel for default ( none ) private ( i, XLeft, XRight ) shared ( PlainTextStream, CipherTextStream, P, S0, S1, S2, S3, StreamLength ) schedule ( static ) + +#endif + + for ( i = 0; i < StreamLength; i += 2 ) + { + XLeft = CipherTextStream [ i ]; + XRight = CipherTextStream [ i + 1 ]; + + _BLOWFISH_DECIPHER ( PlainTextStream [ i ], PlainTextStream [ i + 1 ], XLeft, XRight, P, S0, S1, S2, S3 ); + } + + return; +} + +/** + + @internal + + Decipher a stream of data in cipher block chaining mode. + + Round 1: + + P0 = Dk ( C0 ) XOR ( Iv ) + + Round n: + + Pn = Dk ( Cn ) XOR ( Cn - 1 ) + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param CipherTextStream Buffer of ciphertext to decipher. + + @param CipherTextStream Buffer to receive the plaintext. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + @remarks This function can be parallelised using OpenMP. + + */ + +static void _BLOWFISH_DecipherStream_CBC ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG CipherTextStream, BLOWFISH_PULONG PlainTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft; + BLOWFISH_ULONG XRight; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + + /* Decipher the first block of ciphertext */ + + XLeft = CipherTextStream [ 0 ]; + XRight = CipherTextStream [ 1 ]; + + _BLOWFISH_DECIPHER ( PlainTextStream [ 0 ], PlainTextStream [ 1 ], XLeft, XRight, P, S0, S1, S2, S3 ); + + /* XOR the deciphered first block with the initialisation vector to yeild the plaintext */ + + PlainTextStream [ 0 ] ^= Context->IvHigh32; + PlainTextStream [ 1 ] ^= Context->IvLow32; + + /* Decrypt any remaining blocks */ + +#ifdef _OPENMP + + #pragma omp parallel for default ( none ) private ( i, XLeft, XRight ) shared ( PlainTextStream, CipherTextStream, P, S0, S1, S2, S3, StreamLength ) schedule ( static ) + +#endif + + for ( i = 2; i < StreamLength; i += 2 ) + { + /* Decipher block of ciphertext */ + + XLeft = CipherTextStream [ i ]; + XRight = CipherTextStream [ i + 1 ]; + + _BLOWFISH_DECIPHER ( PlainTextStream [ i ], PlainTextStream [ i + 1 ], XLeft, XRight, P, S0, S1, S2, S3 ); + + /* XOR the deciphered block with the previous block of ciphertext to yeild the plaintext */ + + PlainTextStream [ i ] ^= CipherTextStream [ i - 2 ]; + PlainTextStream [ i + 1 ] ^= CipherTextStream [ i - 1 ]; + } + + /* Preserve the previous block of ciphertext as the new initialisation vector for stream based operations */ + + Context->IvHigh32 = CipherTextStream [ StreamLength - 2 ]; + Context->IvLow32 = CipherTextStream [ StreamLength - 1 ]; + + return; +} + +/** + + @internal + + Decipher a stream of data in cipher feedback mode. + + Round 1: + + P0 = C0 XOR Ek ( Iv ) + + Round n: + + Pn = Cn XOR Ek ( ( Cn - 1 ) ) + + See @link glossary @endlink for more information. + + @param Context Pointer to an initialised context record. + + @param CipherTextStream Buffer of ciphertext to decipher. + + @param CipherTextStream Buffer to receive the plaintext. + + @param StreamLength Length of the plaintext and ciphertext stream buffers in 4-byte blocks. + + @remarks It is an unchecked runtime error to supply either a null pointer, or a stream buffer length that is not a multiple of 4 to this function. + + @remarks This function can be parallelised using OpenMP. + + */ + +static void _BLOWFISH_DecipherStream_CFB ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCULONG CipherTextStream, BLOWFISH_PULONG PlainTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + BLOWFISH_ULONG XLeft; + BLOWFISH_ULONG XRight; + BLOWFISH_PULONG P = Context->PArray; + BLOWFISH_PULONG S0 = Context->SBox [ 0 ]; + BLOWFISH_PULONG S1 = Context->SBox [ 1 ]; + BLOWFISH_PULONG S2 = Context->SBox [ 2 ]; + BLOWFISH_PULONG S3 = Context->SBox [ 3 ]; + BLOWFISH_SIZE_T i; + + /* Encipher the initialisation vector */ + + XLeft = Context->IvHigh32; + XRight = Context->IvLow32; + + _BLOWFISH_ENCIPHER ( XRight, XLeft, XLeft, XRight, P, S0, S1, S2, S3 ); + + /* XOR enciphered initialisation vector with the ciphertext to yeild the plaintext */ + + PlainTextStream [ 0 ] = XRight ^ CipherTextStream [ 0 ]; + PlainTextStream [ 1 ] = XLeft ^ CipherTextStream [ 1 ]; + + /* Decrypt any remaining blocks */ + +#ifdef _OPENMP + + #pragma omp parallel for default ( none ) private ( i, XLeft, XRight ) shared ( PlainTextStream, CipherTextStream, P, S0, S1, S2, S3, StreamLength ) schedule ( static ) + +#endif + + for ( i = 2; i < StreamLength; i += 2 ) + { + /* Encipher the previous block of ciphertext */ + + XLeft = CipherTextStream [ i - 2 ]; + XRight = CipherTextStream [ i - 1 ]; + + _BLOWFISH_ENCIPHER ( XRight, XLeft, XLeft, XRight, P, S0, S1, S2, S3 ); + + /* XOR the enciphered previous block of ciphertext with the current block ciphertext to yeild the plaintext */ + + PlainTextStream [ i ] = XRight ^ CipherTextStream [ i ]; + PlainTextStream [ i + 1 ] = XLeft ^ CipherTextStream [ i + 1 ]; + } + + /* Preserve the previous block of ciphertext as the new initialisation vector for stream based operations */ + + Context->IvHigh32 = CipherTextStream [ StreamLength - 2 ]; + Context->IvLow32 = CipherTextStream [ StreamLength - 1 ]; + + return; +} + +BLOWFISH_RC BLOWFISH_DecipherStream ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR CipherTextStream, BLOWFISH_PUCHAR PlainTextStream, BLOWFISH_SIZE_T StreamLength ) +{ + /* Ensure the context and stream buffer pointers are non null */ + + if ( Context == 0 || CipherTextStream == 0 || PlainTextStream == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Ensure the stream length is a multiple of 8 */ + + if ( ( StreamLength & ~0x07 ) == 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#ifdef _OPENMP + + /* Ensure the stream length is not negative */ + + if ( StreamLength < 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#endif + + /* Decipher stream buffer based on block cipher mode */ + + Context->DecipherStream ( Context, (BLOWFISH_PCULONG)CipherTextStream, (BLOWFISH_PULONG)PlainTextStream, StreamLength >> 2 ); + + return BLOWFISH_RC_SUCCESS; +} + +BLOWFISH_RC BLOWFISH_DecipherBuffer ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR CipherTextBuffer, BLOWFISH_PUCHAR PlainTextBuffer, BLOWFISH_SIZE_T BufferLength ) +{ + /* Ensure the context and buffer pointers are non null */ + + if ( Context == 0 || CipherTextBuffer == 0 || PlainTextBuffer == 0 ) + { + return BLOWFISH_RC_INVALID_PARAMETER; + } + + /* Ensure the buffer length is a multiple of 8 */ + + if ( ( BufferLength & ~0x07 ) == 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#ifdef _OPENMP + + /* Ensure the buffer length is not negative */ + + if ( BufferLength < 0 ) + { + return BLOWFISH_RC_BAD_BUFFER_LENGTH; + } + +#endif + + /* Decipher buffer as a stream based on the block cipher mode */ + + _BLOWFISH_BEGINSTREAM ( Context ); + + Context->DecipherStream ( Context, (BLOWFISH_PCULONG)CipherTextBuffer, (BLOWFISH_PULONG)PlainTextBuffer, BufferLength >> 2 ); + + _BLOWFISH_ENDSTREAM ( Context ); + + return BLOWFISH_RC_SUCCESS; +} + +/** @} */ diff --git a/shared/thirdparty/blowfish-api/blowfish.h b/shared/thirdparty/blowfish-api/blowfish.h new file mode 100644 index 0000000..5c63ce4 --- /dev/null +++ b/shared/thirdparty/blowfish-api/blowfish.h @@ -0,0 +1,408 @@ +/** + + @file blowfish.h + + @brief Public interface for Bruce Schneier's 64-bit symmetric block + cipher, Blowfish. + + @author Tom Bonner (tom.bonner@gmail.com) + + @date 15-June-2008 + + Copyright (c) 2008, Tom Bonner. + + 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. + + Except as contained in this notice, the name(s) of the above copyright + holders shall not be used in advertising or otherwise to promote the sale, + use or other dealings in this Software without prior written authorisation. + + 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 __BLOWFISH_H__ +#define __BLOWFISH_H__ + +/** + + @ingroup blowfish + @defgroup blowfish_api Blowfish API + @{ + +*/ + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Definitions for fixed sized types required by Blowfish, to be redefined where necessary. */ + +typedef unsigned char BLOWFISH_UCHAR; /*!< Must be an 8-bit unsigned type. */ +typedef BLOWFISH_UCHAR * BLOWFISH_PUCHAR; /*!< Must be a pointer to an 8-bit unsigned type. */ +typedef const BLOWFISH_UCHAR * BLOWFISH_PCUCHAR; /*!< Must be a pointer to a constant 8-bit unsigned type */ + +typedef unsigned int BLOWFISH_ULONG; /*!< Must be a 32-bit unsigned type. */ +typedef BLOWFISH_ULONG * BLOWFISH_PULONG; /*!< Must be a pointer to a 32-bit unsigned type. */ +typedef const BLOWFISH_ULONG * BLOWFISH_PCULONG; /*!< Must be a pointer to a constant 32-bit unsigned type. */ + +/* Note! Altering the size and/or signedness of BLOWFISH_SIZE_T will affect the amount of data that can be enciphed/deciphered! */ + +#ifdef _OPENMP + +typedef signed long BLOWFISH_SIZE_T; /*!< Must be a signed 32 or 64-bit type for use with OpenMP. */ + +#else + +typedef unsigned long BLOWFISH_SIZE_T; /*!< Must be an unsigned 32 or 64-bit type. */ + +#endif + +/** Blowfish block cipher modes. */ + +typedef enum _BLOWFISH_MODE +{ + BLOWFISH_MODE_CURRENT = 0, /*!< For use only with #BLOWFISH_Reset to re-use the mode that the context record was initialised with. */ + BLOWFISH_MODE_ECB, /*!< Electronic codebook mode. Encipher/Decipher data in 8-byte blocks. This mode is weak at masking repeating patterns, and therefore insecure, but can be parallelised. */ + BLOWFISH_MODE_CBC, /*!< Cipher block chaining mode (recommended). XOR plaintext block with previous cipher text block before encrypting. This mode cannot be parallelised for encryption. */ + BLOWFISH_MODE_CFB, /*!< Cipher feedback mode. Plaintext is XOR encrypted with previous block of ciphertext. This mode cannot be parallelised for encryption. */ + BLOWFISH_MODE_OFB, /*!< Ouput feedback mode. Plaintext is XOR encrypted with enciphered initialisation vector. This mode cannot be parallelised. */ + BLOWFISH_MODE_CTR /*!< Counter mode. Plaintext is XOR encrypted with enciphered initialisation vector added with a counter. This mode can be parallelised for encryption/decryption. */ + +} BLOWFISH_MODE; + +/** Blowfish return codes. */ + +typedef enum _BLOWFISH_RC +{ + BLOWFISH_RC_SUCCESS = 0, /*!< Function completed successfully. */ + BLOWFISH_RC_INVALID_PARAMETER, /*!< One of the parameters suppied to the function is invalid (null pointer). */ + BLOWFISH_RC_INVALID_KEY, /*!< The length of the key supplied to the #BLOWFISH_Init/#BLOWFISH_Reset function is either greater than #BLOWFISH_MAX_KEY_LENGTH or less than #BLOWFISH_MIN_KEY_LENGTH. */ + BLOWFISH_RC_WEAK_KEY, /*!< The key supplied to the #BLOWFISH_Init/#BLOWFISH_Reset function has been deemed to be weak, and should not be used. */ + BLOWFISH_RC_BAD_BUFFER_LENGTH, /*!< The size of the buffer supplied to one of the encipher/decipher buffer/stream functions is not a multiple of 8. */ + BLOWFISH_RC_INVALID_MODE, /*!< The mode specified to the #BLOWFISH_Init/#BLOWFISH_Reset function is not supported. */ + BLOWFISH_RC_TEST_FAILED, /*!< Self test failed. For more information see stdout (only used by test applications). */ + BLOWFISH_RC_ERROR, /*!< Generic error (only used by test applications). */ + +} BLOWFISH_RC; + +/* Various static array/buffer lengths (do not modify!). */ + +#define BLOWFISH_SUBKEYS 18 /*!< Number of subkeys in the P-Array. */ +#define BLOWFISH_SBOXES 4 /*!< Number of S-Boxes. */ +#define BLOWFISH_SBOX_ENTRIES 256 /*!< Number of entries in each S-Box. */ + +#define BLOWFISH_MIN_KEY_LENGTH 4 /*!< Maximum length of a key (4-bytes, or 32-bits). */ +#define BLOWFISH_MAX_KEY_LENGTH 56 /*!< Maximum length of a key (56-bytes, or 448-bits). */ + +/** Blowfish context record. */ + +typedef struct _BLOWFISH_CONTEXT +{ + BLOWFISH_ULONG PArray [ BLOWFISH_SUBKEYS ]; /*!< Original P-Array which has been XOR'd with the key, and overwritten with output from #BLOWFISH_Encipher. */ + BLOWFISH_ULONG SBox [ BLOWFISH_SBOXES ] [ BLOWFISH_SBOX_ENTRIES ]; /*!< Original S-Boxes which have been overwritten with output from #BLOWFISH_Encipher. */ + BLOWFISH_ULONG OriginalIvHigh32; /*!< Original high 32-bytes of the initialisation vector. */ + BLOWFISH_ULONG OriginalIvLow32; /*!< Original low 32-bytes of the initialisation vector. */ + BLOWFISH_ULONG IvHigh32; /*!< Current high 32-bytes of the initialisation vector (used for stream operations). */ + BLOWFISH_ULONG IvLow32; /*!< Current low 32-bytes of the initialisation vector (used for stream operations). */ + void ( *EncipherStream ) ( ); /*!< Pointer to a callback function to perform the encipher based on the block cipher mode */ + void ( *DecipherStream ) ( ); /*!< Pointer to a callback function to perform the decipher based on the block cipher mode */ + +} BLOWFISH_CONTEXT, *BLOWFISH_PCONTEXT; + +/* Function prototypes. */ + +/** + + Initialise a Blowfish context record. + + @param Context Pointer to a Blowfish context record to initialise. + + @param Key Pointer to a key to use for enciphering/deciphering data. + + @param KeyLength Length of the key, which cannot exceed #BLOWFISH_MAX_KEY_LENGTH bytes (sizeof(#BLOWFISH_CONTEXT::PArray)), or be less than #BLOWFISH_MIN_KEY_LENGTH bytes. + + @param Mode Mode to use when enciphering/decipering blocks. For supported modes see #BLOWFISH_MODE + + @param IvHigh32 High 32-bits of the initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB. + + @param IvLow32 Low 32-bits of the initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB. + + @remarks For stream based enciphering/deciphering, call #BLOWFISH_BeginStream/#BLOWFISH_EndStream before/afer processing the stream. + + @remarks Operations performed on a blowfish context record are not thread safe. Use #BLOWFISH_CloneContext to create a copy of a context record that can be safely used by another thread. + + @return #BLOWFISH_RC_SUCCESS Initialised context record successfully. + + @return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or key pointer is null. + + @return #BLOWFISH_RC_INVALID_KEY The key is either too short or too long. + + @return #BLOWFISH_RC_WEAK_KEY The key has been deemed to be weak. + + @return #BLOWFISH_RC_INVALID_MODE The specified mode is not supported. + + */ + +BLOWFISH_RC BLOWFISH_Init ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR Key, BLOWFISH_SIZE_T KeyLength, BLOWFISH_MODE Mode, BLOWFISH_ULONG IvHigh32, BLOWFISH_ULONG IvLow32 ); + +/** + + Reinitialise either the key and/or mode and initialisation vector in a Blowfish context record. + + @param Context Pointer to an initialised Blowfish context record to reinitialise. + + @param Key Pointer to a new key to use for enciphering/deciphering data. (May be null to re-use the current key). + + @param KeyLength Length of the new key, which cannot exceed #BLOWFISH_MAX_KEY_LENGTH bytes (sizeof(#BLOWFISH_CONTEXT::PArray)), or be less than #BLOWFISH_MIN_KEY_LENGTH bytes. (May be 0 if Key is null). + + @param Mode New mode to use when enciphering/decipering blocks. Use #BLOWFISH_MODE_CURRENT to re-use the current mode and initialisation vector. For supported modes see #BLOWFISH_MODE. + + @param IvHigh32 High 32-bits of the new initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CURRENT. + + @param IvLow32 Low 32-bits of the new initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CURRENT. + + @remarks See #BLOWFISH_Init remarks. + + @return #BLOWFISH_RC_SUCCESS Reinitialised the context record successfully. + + @return #BLOWFISH_RC_INVALID_PARAMETER The context record pointer is null. + + @return #BLOWFISH_RC_INVALID_KEY The key is either too short or too long. + + @return #BLOWFISH_RC_WEAK_KEY The key has been deemed to be weak. + + @return #BLOWFISH_RC_INVALID_MODE The specified mode is not supported. + + */ + +BLOWFISH_RC BLOWFISH_Reset ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR Key, BLOWFISH_SIZE_T KeyLength, BLOWFISH_MODE Mode, BLOWFISH_ULONG IvHigh32, BLOWFISH_ULONG IvLow32 ); + +/** + + Copy an initialised context record into an uninitialised context record for use in another thread. + + @param InContext Pointer to an initialised context record. + + @param OutContext Pointer to an uninitialised context record. + + @remarks Destroy the cloned context record using #BLOWFISH_Exit. + + @return BLOWFISH_RC_SUCCESS The context record was cloned successfully. + + @return BLOWFISH_RC_INVALID_PARAMETER One of the context record pointers is null. + + */ + +BLOWFISH_RC BLOWFISH_CloneContext ( BLOWFISH_PCONTEXT InContext, BLOWFISH_PCONTEXT OutContext ); + +/** + + Clear a blowfish context record. + + @param Context Pointer to an initialised context record to overwrite. + + @remarks Call this function regardless of whether #BLOWFISH_Init succeeds. + + @remarks It is a security risk to not call this function once you have finished enciphering/deciphering data! + + @remarks The context record may not be used again after this call without first calling #BLOWFISH_Init. + + @return #BLOWFISH_RC_SUCCESS The context record was overwritten successfully. + + @return #BLOWFISH_RC_INVALID_PARAMETER The supplied context record pointer is null. + + */ + +BLOWFISH_RC BLOWFISH_Exit ( BLOWFISH_PCONTEXT Context ); + +/** + + Initialise a context record for stream based enciphering/deciphering. + + @param Context Pointer to an initialised context record. + + @remarks Before re-using the context record to process another stream, be sure to end and begin a new stream using #BLOWFISH_EndStream and BLOWFISH_BeginStream. + + @remarks After calling BLOWFISH_BeginStream, the context will become corrupt if it is passed to any function other than #BLOWFISH_EncipherStream/#BLOWFISH_DecipherStream before calling #BLOWFISH_EndStream. + + @return #BLOWFISH_RC_SUCCESS The context record was initialised for stream ciphering successfully. + + @return #BLOWFISH_RC_INVALID_PARAMETER The supplied context record pointer is null. + + */ + +BLOWFISH_RC BLOWFISH_BeginStream ( BLOWFISH_PCONTEXT Context ); + +/** + + Clear sensitive data from a context record after performing stream based enciphering/deciphering. + + @param Context Pointer to an initialised context record. + + @remarks The context record may be re-used after this call without needing to call #BLOWFISH_Init again. + + @remarks After calling BLOWFISH_EndStream, the context record may be used in non-stream based functions without risking corruption. (See #BLOWFISH_BeginStream remarks) + + @return #BLOWFISH_RC_SUCCESS Sensitive data was cleared from the context record successfully. + + @return #BLOWFISH_RC_INVALID_PARAMETER The supplied context record pointer is null. + + */ + +BLOWFISH_RC BLOWFISH_EndStream ( BLOWFISH_PCONTEXT Context ); + +/** + + Encipher an 8-byte block of data. + + @param Context Pointer to an initialised context record. + + @param High32 Pointer to the high 32 bits of data to encipher. + + @param Low32 Pointer to the low 32 bits of data to encipher. + + @remarks It is an unchecked runtime error to supply a null parameter to this function. + + */ + +void BLOWFISH_Encipher ( BLOWFISH_PCONTEXT Context, BLOWFISH_PULONG High32, BLOWFISH_PULONG Low32 ); + +/** + + Encipher a buffer of data as part of a stream. + + @param Context Pointer to an initialised context record. + + @param PlainTextStream Pointer to a buffer of data to encipher within the stream. + + @param CipherTextStream Pointer to a buffer within the stream to receive the enciphered data. + + @param StreamLength Length of the plaintext and ciphertext stream buffers. Must be a multiple of 8. + + @remarks The PlainTextStream and CipherTextStream pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR. + + @remarks The PlainTextStream and CipherTextStream pointers must point to an offset within the stream that is a multiple of 8. + + @return #BLOWFISH_RC_SUCCESS Successfully enciphered data. + + @return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the stream buffer pointer is null. + + @return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the stream buffer is not a multiple of 8. + + */ + +BLOWFISH_RC BLOWFISH_EncipherStream ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR PlainTextStream, BLOWFISH_PUCHAR CipherTextStream, BLOWFISH_SIZE_T StreamLength ); + +/** + + Encipher a buffer of data. + + @param Context Pointer to an initialised context record. + + @param PlainTextBuffer Pointer to a buffer of data to encipher. + + @param CipherTextBuffer Pointer to a buffer to receive the enciphered data. + + @param BufferLength Length of the plaintext and ciphertext buffers. Must be a multiple of 8. + + @remarks The PlainTextBuffer and CipherTextBuffer pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR. + + @return #BLOWFISH_RC_SUCCESS Successfully enciphered data. + + @return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the buffer pointer is null. + + @return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the buffer is not a multiple of 8. + + */ + +BLOWFISH_RC BLOWFISH_EncipherBuffer ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR PlainTextBuffer, BLOWFISH_PUCHAR CipherTextBuffer, BLOWFISH_SIZE_T BufferLength ); + +/** + + Decipher an 8-byte block of data. + + @param Context Pointer to an initialised context record. + + @param High32 Pointer to the high 32 bits of data to decipher. + + @param Low32 Pointer to the low 32 bits of data to decipher. + + @remarks It is an unchecked runtime error to supply a null parameter to this function. + + */ + +void BLOWFISH_Decipher ( BLOWFISH_PCONTEXT Context, BLOWFISH_PULONG High32, BLOWFISH_PULONG Low32 ); + +/** + + Decipher a buffer of data as part of a stream. + + @param Context Pointer to an initialised context record. + + @param CipherTextStream Pointer to a buffer of data to decipher within the stream. + + @param PlainTextStream Pointer to a buffer within the stream to receive the deciphered data. + + @param StreamLength Length of the plaintext and ciphertext stream buffers. Must be a multiple of 8. + + @remarks The PlainTextStream and CipherTextStream pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR. + + @remarks The PlainTextStream and CipherTextStream pointers must point to an offset within the stream that is a multiple of 8. + + @return #BLOWFISH_RC_SUCCESS Successfully enciphered data. + + @return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the stream buffer pointer is null. + + @return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the stream buffer is not a multiple of 8. + + */ + +BLOWFISH_RC BLOWFISH_DecipherStream ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR CipherTextStream, BLOWFISH_PUCHAR PlainTextStream, BLOWFISH_SIZE_T StreamLength ); + +/** + + Decipher a buffer of data. + + @param Context Pointer to an initialised context record. + + @param CipherTextBuffer Pointer to a buffer of data to decipher. + + @param PlainTextBuffer Pointer to a buffer to receive the deciphered data. + + @param BufferLength Length of the ciphertext and plaintext buffers. Must be a multiple of 8. + + @remarks The PlainTextBuffer and CipherTextBuffer pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR. + + @return #BLOWFISH_RC_SUCCESS Successfully enciphered data. + + @return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the buffer pointer is null. + + @return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the buffer is not a multiple of 8. + + */ + +BLOWFISH_RC BLOWFISH_DecipherBuffer ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR CipherTextBuffer, BLOWFISH_PUCHAR PlainTextBuffer, BLOWFISH_SIZE_T BufferLength ); + +#ifdef __cplusplus +} +#endif + +/** @} */ + +#endif /* __BLOWFISH_H__ */ diff --git a/shared/thirdparty/blowfish-api/blowfish_test.C b/shared/thirdparty/blowfish-api/blowfish_test.C new file mode 100644 index 0000000..f6be3a3 --- /dev/null +++ b/shared/thirdparty/blowfish-api/blowfish_test.C @@ -0,0 +1,891 @@ +/** + + @file blowfish_test.c + + @brief Blowfish self-test application. Includes standard ECB mode + tests and throughput tests (parallel and serial) for all + supported modes (ECB, CBC, CFB, OFB and CTR). + + @author Tom Bonner (tom.bonner@gmail.com) + + @date 22-June-2008 + + Copyright (c) 2008, Tom Bonner. + + 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. + + Except as contained in this notice, the name(s) of the above copyright + holders shall not be used in advertising or otherwise to promote the sale, + use or other dealings in this Software without prior written authorisation. + + 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. + + */ + +#include +#include +#include +#include + +#ifdef _OPENMP + +#include + +#endif + +#include + +/** + + @ingroup blowfish + @defgroup blowfish_selftest Blowfish Self-Test + @{ + + */ + +/** @internal Test vector. */ + +typedef struct __BLOWFISH_TEST_VECTOR +{ + BLOWFISH_UCHAR Key [ 8 ]; /*!< 8-Byte key to use in the test. */ + BLOWFISH_ULONG PlainText [ 2 ]; /*!< 8-Byte block of plaintext to encipher. */ + BLOWFISH_ULONG CipherText [ 2 ]; /*!< 8-Byte block of expected ciphertext. */ + +} _BLOWFISH_TEST_VECTOR; + +/** @internal ECB Test vector data from http://www.mirrors.wiretapped.net/security/cryptography/algorithms/blowfish/blowfish-TESTVECTORS.txt */ + +static const _BLOWFISH_TEST_VECTOR _BLOWFISH_EcbTv1 [ ] = +{ + { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00000000, 0x00000000 }, { 0x4ef99745, 0x6198dd78 } }, + { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, { 0xffffffff, 0xffffffff }, { 0x51866fd5, 0xb85ecb8a } }, + { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, { 0x00000000, 0x00000000 }, { 0xf21e9a77, 0xb71c49bc } }, + { { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }, { 0x01234567, 0x89abcdef }, { 0x7d0cc630, 0xafda1ec7 } }, + { { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }, { 0x11111111, 0x11111111 }, { 0x2466dd87, 0x8b963c9d } }, + { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0xffffffff, 0xffffffff }, { 0x014933e0, 0xcdaff6e4 } }, + { { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }, { 0x01234567, 0x89abcdef }, { 0xfa34ec48, 0x47b268b2 } }, + { { 0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e }, { 0x01234567, 0x89abcdef }, { 0xa7907951, 0x08ea3cae } }, + { { 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x10000000, 0x00000001 }, { 0x7d856f9a, 0x613063f2 } }, + { { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, { 0x11111111, 0x11111111 }, { 0x61f9c380, 0x2281b096 } }, + { { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }, { 0x01234567, 0x89abcdef }, { 0x0aceab0f, 0xc6a0a28d } }, + { { 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57 }, { 0x01a1d6d0, 0x39776742 }, { 0x59c68245, 0xeb05282b } }, + { { 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e }, { 0x5cd54ca8, 0x3def57da }, { 0xb1b8cc0b, 0x250f09a0 } }, + { { 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86 }, { 0x0248d438, 0x06f67172 }, { 0x1730e577, 0x8bea1da4 } }, + { { 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e }, { 0x51454b58, 0x2ddf440a }, { 0xa25e7856, 0xcf2651eb } }, + { { 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6 }, { 0x42fd4430, 0x59577fa2 }, { 0x353882b1, 0x09ce8f1a } }, + { { 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce }, { 0x059b5e08, 0x51cf143a }, { 0x48f4d088, 0x4c379918 } }, + { { 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6 }, { 0x0756d8e0, 0x774761d2 }, { 0x432193b7, 0x8951fc98 } }, + { { 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe }, { 0x762514b8, 0x29bf486a }, { 0x13f04154, 0xd69d1ae5 } }, + { { 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16 }, { 0x3bdd1190, 0x49372802 }, { 0x2eedda93, 0xffd39c79 } }, + { { 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f }, { 0x26955f68, 0x35af609a }, { 0xd887e039, 0x3c2da6e3 } }, + { { 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46 }, { 0x164d5e40, 0x4f275232 }, { 0x5f99d04f, 0x5b163969 } }, + { { 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e }, { 0x6b056e18, 0x759f5cca }, { 0x4a057a3b, 0x24d3977b } }, + { { 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76 }, { 0x004bd6ef, 0x09176062 }, { 0x452031c1, 0xe4fada8e } }, + { { 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07 }, { 0x480d3900, 0x6ee762f2 }, { 0x7555ae39, 0xf59b87bd } }, + { { 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f }, { 0x437540c8, 0x698f3cfa }, { 0x53c55f9c, 0xb49fc019 } }, + { { 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7 }, { 0x072d43a0, 0x77075292 }, { 0x7a8e7bfa, 0x937e89a3 } }, + { { 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf }, { 0x02fe5577, 0x8117f12a }, { 0xcf9c5d7a, 0x4986adb5 } }, + { { 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6 }, { 0x1d9d5c50, 0x18f728c2 }, { 0xd1abb290, 0x658bc778 } }, + { { 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef }, { 0x30553228, 0x6d6f295a }, { 0x55cb3774, 0xd13ef201 } }, + { { 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe }, { 0x01234567, 0x89abcdef }, { 0xc39e072d, 0x9fac631d } }, + { { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, { 0x00000000, 0x00000000 }, { 0x24594688, 0x5754369a } }, + { { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }, { 0xffffffff, 0xffffffff }, { 0x6b5c5a9c, 0x5d9e0a5a } } +}; + +/** @internal Part of ECB Test vector. See #_BLOWFISH_EcbTv1. */ + +static const BLOWFISH_UCHAR _BLOWFISH_EcbTv2Key [ ] = { 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 }; + +/** @internal Part of ECB Test vector. See #_BLOWFISH_EcbTv1. */ + + static const BLOWFISH_ULONG _BLOWFISH_EcbTv2PlainText [ 2 ] = { 0xfedcba98, 0x76543210 }; + +/** @internal Part of ECB Test vector. See #_BLOWFISH_EcbTv1. */ + +static const BLOWFISH_ULONG _BLOWFISH_EcbTv2CipherText [ ] [ 2 ] = +{ + { 0xbe1e6394, 0x08640f05 }, { 0xb39e4448, 0x1bdb1e6e }, { 0x9457aa83, 0xb1928c0d }, + { 0x8bb77032, 0xf960629d }, { 0xe87a244e, 0x2cc85e82 }, { 0x15750e7a, 0x4f4ec577 }, + { 0x122ba70b, 0x3ab64ae0 }, { 0x3a833c9a, 0xffc537f6 }, { 0x9409da87, 0xa90f6bf2 }, + { 0x884f8062, 0x5060b8b4 }, { 0x1f85031c, 0x19e11968 }, { 0x79d9373a, 0x714ca34f }, + { 0x93142887, 0xee3be15c }, { 0x03429e83, 0x8ce2d14b }, { 0xa4299e27, 0x469ff67b }, + { 0xafd5aed1, 0xc1bc96a8 }, { 0x10851c0e, 0x3858da9f }, { 0xe6f51ed7, 0x9b9db21f }, + { 0x64a6e14a, 0xfd36b46f }, { 0x80c7d7d4, 0x5a5479ad }, { 0x05044b62, 0xfa52d080 } +}; + +/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */ + +static const BLOWFISH_UCHAR _BLOWFISH_Tv3Key [ ] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87 }; + +/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */ + +static const BLOWFISH_ULONG _BLOWFISH_Tv3Iv [ 2 ] = { 0xfedcba98, 0x76543210 }; + +/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */ + +static const BLOWFISH_ULONG _BLOWFISH_Tv3PlainText [ 6 ] = { 0x37363534, 0x33323120, 0x4e6f7720, 0x69732074, 0x68652074, 0x696d6520 }; + +/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */ + +static const BLOWFISH_ULONG _BLOWFISH_Tv3CipherText [ ] [ 6 ] = +{ + { 0x6b77b4d6, 0x3006dee6, 0x05b156e2, 0x74039793, 0x58deb9e7, 0x154616d9 }, /*!< CBC mode ciphertext. */ + { 0xe73214a2, 0x822139ca, 0xf26ecf6d, 0x2eb9e76e, 0x3da3de04, 0xd1517200 }, /*!< CFB mode ciphertext. */ + { 0xe73214a2, 0x822139ca, 0x62b343cc, 0x5b655873, 0x10dd908d, 0x0c241b22 } /*!< OFB mode ciphertext. */ +}; + +/** @internal CBC/CFB/OFB Test modes. */ + +static const BLOWFISH_MODE _BLOWFISH_Tv3Mode [ ] = { BLOWFISH_MODE_CBC, BLOWFISH_MODE_CFB, BLOWFISH_MODE_OFB }; + +/** @internal Throughput test vector */ + +typedef struct __BLOWFISH_THROUGHPUT_TEST +{ + BLOWFISH_MODE Mode; /*!< Mode to use in the test. */ + BLOWFISH_UCHAR Parallel; /*!< Specifies whether the mode can be parallelised. */ + +} _BLOWFISH_THROUGHPUT_TEST; + +/** @internal Throughput test modes */ + +static const _BLOWFISH_THROUGHPUT_TEST _BLOWFISH_ThroughputTv [ ] = { { BLOWFISH_MODE_ECB, 0x01 }, { BLOWFISH_MODE_CBC, 0x01 }, { BLOWFISH_MODE_CFB, 0x01 }, { BLOWFISH_MODE_OFB, 0x00 }, { BLOWFISH_MODE_CTR, 0x01 } }; + +/** @internal Specifies the duration (in seconds) for how long the throughput tests should run (must be greater than 1, and preferably a multiple of 2) */ + +#define _BLOWFISH_THROUGHPUT_DURATION 10 + +#define _BLOWFISH_THROUGHPUT_STREAM_LENGTH ( 128 * 1024 ) + +/** + + @internal + + Display function name and readable return code to stdout. + + @param FunctionName Name of the function called. + + @param ReturnCode Return code from the function. + + @return Return code from printf(). + + */ + +static int _BLOWFISH_PrintReturnCode ( char * FunctionName, BLOWFISH_RC ReturnCode ) +{ + switch ( ReturnCode ) + { + case BLOWFISH_RC_SUCCESS: + { + return 0; + } + case BLOWFISH_RC_INVALID_PARAMETER: + { + return printf ( "%s()=Invalid parameter!\n", FunctionName ); + } + case BLOWFISH_RC_INVALID_KEY: + { + return printf ( "%s()=Invalid key!\n", FunctionName ); + } + case BLOWFISH_RC_WEAK_KEY: + { + return printf ( "%s()=Weak key!\n", FunctionName ); + } + case BLOWFISH_RC_BAD_BUFFER_LENGTH: + { + return printf ( "%s()=Invalid buffer length!\n", FunctionName ); + } + case BLOWFISH_RC_INVALID_MODE: + { + return printf ( "%s()=Invalid mode!\n", FunctionName ); + } + case BLOWFISH_RC_TEST_FAILED: + { + return printf ( "%s()=Self-test failed!\n", FunctionName ); + } + default: + { + return printf ( "%s()=Unknown error!\n", FunctionName ); + } + } +} + +/** + + @internal + + Display the name of the specified mode to stdout. + + @param Mode Mode to display. + + @return Return code from printf(). + + */ + +static int _BLOWFISH_PrintMode ( BLOWFISH_MODE Mode ) +{ + switch ( Mode ) + { + case BLOWFISH_MODE_ECB: + { + return printf ( "Mode=Electronic codebook (ECB)\n" ); + } + case BLOWFISH_MODE_CBC: + { + return printf ( "Mode=Cipher block chaining (CBC)\n" ); + } + case BLOWFISH_MODE_CFB: + { + return printf ( "Mode=Cipher feedback (CFB)\n" ); + } + case BLOWFISH_MODE_OFB: + { + return printf ( "Mode=Output feedback (OFB)\n" ); + } + case BLOWFISH_MODE_CTR: + { + return printf ( "Mode=Counter (CTR)\n" ); + } + default: + { + return printf ( "Mode=Invalid!\n" ); + } + } +} + +/** + + @internal + + Display a buffer as hex to stdout. + + @param Name Name of the buffer. + + @param Buffer Pointer to a buffer of data to display. + + @param Buffer Length of the buffer. + + */ + +static void _BLOWFISH_PrintBuffer ( char * Name, BLOWFISH_PUCHAR Buffer, BLOWFISH_ULONG BufferLength ) +{ + BLOWFISH_ULONG i; + + printf ( "%s=0x", Name ); + + for ( i = 0; i < BufferLength; i++ ) + { + printf ( "%02x", Buffer [ i ] ); + } + + printf ( " (%d bytes)\n", (int)BufferLength ); + + return; +} + +/** + + @internal + + Perform a raw ECB mode encipher/decipher on an 8-byte block of plaintext, and verify results. + + @param Key Pointer to a buffer containing the key to use for cipher operations. + + @param KeyLength Length of the key buffer. + + @param PlainTextHigh32 High 32-bits of plaintext to encipher. + + @param PlainTextLow32 Low 32-bits of plaintext to encipher. + + @param CipherTextHigh32 High 32 bits of expected ciphertext. + + @param CipherTextLow32 Low 32 bits of expected ciphertext. + + @remarks For use with test vectors 1 and 2. + + @return #BLOWFISH_RC_SUCCESS Test passed successfully. + + @return Specific return code, see #BLOWFISH_RC. + + */ + +static BLOWFISH_RC _BLOWFISH_Test_ECB ( BLOWFISH_PUCHAR Key, BLOWFISH_ULONG KeyLength, BLOWFISH_ULONG PlainTextHigh32, BLOWFISH_ULONG PlainTextLow32, BLOWFISH_ULONG CipherTextHigh32, BLOWFISH_ULONG CipherTextLow32 ) +{ + BLOWFISH_RC ReturnCode = BLOWFISH_RC_SUCCESS; + BLOWFISH_CONTEXT Context; + BLOWFISH_ULONG XLeft = PlainTextHigh32; + BLOWFISH_ULONG XRight = PlainTextLow32; + + /* Initialise blowfish */ + + ReturnCode = BLOWFISH_Init ( &Context, Key, KeyLength, BLOWFISH_MODE_ECB, 0, 0 ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_Init", ReturnCode ); + + /* Print key information */ + + _BLOWFISH_PrintMode ( BLOWFISH_MODE_ECB ); + + _BLOWFISH_PrintBuffer ( "Key", Key, KeyLength ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Encipher the 8-byte block of plaintext */ + + BLOWFISH_Encipher ( &Context, &XLeft, &XRight ); + + printf ( "Plaintext=0x%08x%08x (8 bytes)\n", (unsigned int)PlainTextHigh32, (unsigned int)PlainTextLow32 ); + + /* Is the ciphertext as expected? */ + + if ( XLeft == CipherTextHigh32 && XRight == CipherTextLow32 ) + { + /* Decipher the ciphertext */ + + BLOWFISH_Decipher ( &Context, &XLeft, &XRight ); + + printf ( "Ciphertext=0x%08x%08x (8 bytes)\n", (unsigned int)CipherTextHigh32, (unsigned int)CipherTextLow32 ); + + /* Is the plaintext as expected? */ + + if ( XLeft != PlainTextHigh32 && XRight != PlainTextLow32 ) + { + /* Failed to decipher properly */ + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_Decipher", BLOWFISH_RC_TEST_FAILED ); + + printf ( "Invalid plaintext=0x%08x%08x (8 bytes)\n", (unsigned int)XLeft, (unsigned int)XRight ); + + ReturnCode = BLOWFISH_RC_TEST_FAILED; + } + } + else + { + /* Failed to encipher properly */ + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_Encipher", BLOWFISH_RC_TEST_FAILED ); + + printf ( "Ciperhtext=0x%08x%08x (8 bytes)\nInvalid ciphertext=0x%08x%08x (8 bytes)\n", (unsigned int)CipherTextHigh32, (unsigned int)CipherTextLow32, (unsigned int)XLeft, (unsigned int)XRight ); + + ReturnCode = BLOWFISH_RC_TEST_FAILED; + } + } + + printf ( "\n" ); + + /* Overwrite the blowfish context record */ + + BLOWFISH_Exit ( &Context ); + + return ReturnCode; +} + +/** + + @internal + + Perform a CBC/CFB/OFB mode test on a buffer of data, and verify results. + + @param Key Pointer to a buffer containing the key to use for cipher operations. + + @param KeyLength Length of the key buffer. + + @param Mode Mode with which to run the test. Must be either #BLOWFISH_MODE_CBC, #BLOWFISH_MODE_CFB or #BLOWFISH_MODE_OFB. + + @param PlainTextBuffer Pointer to a buffer of plaintext to encipher. + + @param CipherTextBuffer Pointer to a buffer of expected ciphertext. + + @param BufferLength Length of the buffers. + + @remarks For use with test vector 3. + + @return #BLOWFISH_RC_SUCCESS Test passed successfully. + + @return Specific return code, see #BLOWFISH_RC. + + */ + +static BLOWFISH_RC _BLOWFISH_Test_CBC_CFB_OFB ( BLOWFISH_PUCHAR Key, BLOWFISH_ULONG KeyLength, BLOWFISH_MODE Mode, BLOWFISH_PUCHAR PlainTextBuffer, BLOWFISH_PUCHAR CipherTextBuffer, BLOWFISH_ULONG BufferLength ) +{ + BLOWFISH_RC ReturnCode = BLOWFISH_RC_SUCCESS; + BLOWFISH_CONTEXT Context; + BLOWFISH_PUCHAR Buffer = 0; + + /* Initialise blowfish */ + + ReturnCode = BLOWFISH_Init ( &Context, Key, KeyLength, Mode, _BLOWFISH_Tv3Iv [ 0 ], _BLOWFISH_Tv3Iv [ 1 ] ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_Init", ReturnCode ); + + /* Print key information */ + + _BLOWFISH_PrintMode ( Mode ); + + _BLOWFISH_PrintBuffer ( "Key", Key, KeyLength ); + + _BLOWFISH_PrintBuffer ( "Initialisation vector", (BLOWFISH_PUCHAR)_BLOWFISH_Tv3Iv, 8 ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + Buffer = (BLOWFISH_PUCHAR)malloc ( BufferLength ); + + if ( Buffer != 0 ) + { + /* Encipher the plaintext buffer */ + + ReturnCode = BLOWFISH_EncipherBuffer ( &Context, PlainTextBuffer, Buffer, BufferLength ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_EncipherBuffer", ReturnCode ); + + _BLOWFISH_PrintBuffer ( "Plaintext", PlainTextBuffer, BufferLength ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Is the ciphertext as expected? */ + + if ( memcmp ( CipherTextBuffer, Buffer, BufferLength ) == 0 ) + { + /* Decipher the ciphertext buffer */ + + ReturnCode = BLOWFISH_DecipherBuffer ( &Context, CipherTextBuffer, Buffer, BufferLength ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_DecipherBuffer", ReturnCode ); + + _BLOWFISH_PrintBuffer ( "Ciphertext", CipherTextBuffer, BufferLength ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Is the plaintext as expected? */ + + if ( memcmp ( PlainTextBuffer, Buffer, BufferLength ) != 0 ) + { + /* Failed to decipher properly */ + + _BLOWFISH_PrintBuffer ( "Invalid plaintext", Buffer, BufferLength ); + + ReturnCode = BLOWFISH_RC_TEST_FAILED; + } + } + } + else + { + /* Failed to encipher properly */ + + _BLOWFISH_PrintBuffer ( "Ciphertext", CipherTextBuffer, BufferLength ); + + _BLOWFISH_PrintBuffer ( "Invalid ciphertext", Buffer, BufferLength ); + + ReturnCode = BLOWFISH_RC_TEST_FAILED; + } + } + + free ( Buffer ); + } + } + + printf ( "\n" ); + + /* Overwrite the blowfish context record */ + + BLOWFISH_Exit ( &Context ); + + return ReturnCode; +} + +/** + + @internal + + Perform a stream based throughput test for the selected mode. + + @param Mode Mode to use for the test. + + @param StreamBlockSize Size of each chunk of the stream. + + @remarks Enciphers/deciphers data as a stream for #_BLOWFISH_THROUGHPUT_DURATION seconds, and then calculates the throughput. + + @return #BLOWFISH_RC_SUCCESS Test passed successfully. + + @return Specific return code, see #BLOWFISH_RC. + + */ + +static BLOWFISH_RC _BLOWFISH_Test_Throughput ( BLOWFISH_MODE Mode, BLOWFISH_ULONG StreamBlockSize ) +{ + BLOWFISH_RC ReturnCode = BLOWFISH_RC_SUCCESS; + BLOWFISH_CONTEXT EncipherContext; + BLOWFISH_CONTEXT DecipherContext; + BLOWFISH_PUCHAR PlainTextBuffer = 0; + BLOWFISH_PUCHAR CipherTextBuffer = 0; + BLOWFISH_SIZE_T i = 0; + BLOWFISH_SIZE_T j = 0; + BLOWFISH_ULONG Sum = 0; + clock_t StartTime = 0; + clock_t EndTime = 0; + clock_t ElapsedEncipherTime = 0; + clock_t ElapsedDecipherTime = 0; + float BlocksProcessed = 0; +#ifdef _OPENMP + BLOWFISH_SIZE_T Threads = omp_get_max_threads ( ); +#else + BLOWFISH_SIZE_T Threads = 1; +#endif + + /* Initialise blowfish for the encipher stream */ + + ReturnCode = BLOWFISH_Init ( &EncipherContext, (BLOWFISH_PUCHAR)"0123456789abcdef", 16, Mode, _BLOWFISH_Tv3Iv [ 0 ], _BLOWFISH_Tv3Iv [ 1 ] ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_Init", ReturnCode ); + + _BLOWFISH_PrintMode ( Mode ); + + printf ( "Key=\"0123456789abcdef\"\n" ); + + if ( Mode != BLOWFISH_MODE_ECB ) + { + _BLOWFISH_PrintBuffer ( "Initialisation vector", (BLOWFISH_PUCHAR)_BLOWFISH_Tv3Iv, 8 ); + } + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Clone the context for the decipher stream */ + + ReturnCode = BLOWFISH_CloneContext ( &EncipherContext, &DecipherContext ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_CloneContext", ReturnCode ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Allocate the plaintext buffer */ + + PlainTextBuffer = (BLOWFISH_PUCHAR)malloc ( StreamBlockSize ); + + if ( PlainTextBuffer != 0 ) + { + /* Allocate the ciphertext buffer */ + + CipherTextBuffer = (BLOWFISH_PUCHAR)malloc ( StreamBlockSize ); + + if ( CipherTextBuffer != 0 ) + { + /* Create original plaintext buffer (use 0x01 for ease of vectorised verification) */ + + memset ( PlainTextBuffer, 0x01, StreamBlockSize ); + + /* Begin the stream for enciphering */ + + ReturnCode = BLOWFISH_BeginStream ( &EncipherContext ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_BeginStream", ReturnCode ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Begin the stream for deciphering */ + + ReturnCode = BLOWFISH_BeginStream ( &DecipherContext ); + + _BLOWFISH_PrintReturnCode ( "BLOWFISH_BeginStream", ReturnCode ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* While the total elapsed time (in seconds) has not passed the duration threshold, keep enciphering/deciphering the stream */ + + for ( i = 0; ( ( ElapsedEncipherTime + ElapsedDecipherTime ) / Threads ) / CLOCKS_PER_SEC <= _BLOWFISH_THROUGHPUT_DURATION; i++ ) + { + /* Clear the ciphertext buffer */ + + memset ( CipherTextBuffer, 0x00, StreamBlockSize ); + + /* Encipher the plaintext */ + + StartTime = clock ( ); + + ReturnCode = BLOWFISH_EncipherStream ( &EncipherContext, PlainTextBuffer, CipherTextBuffer, StreamBlockSize ); + + EndTime = clock ( ); + + /* Compute the time elapsed enciphering (in milliseconds) */ + + ElapsedEncipherTime += ( EndTime - StartTime ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + _BLOWFISH_PrintReturnCode ( "BLOWFISH_EncipherStream", ReturnCode ); + + break; + } + + /* Clear the plaintext buffer */ + + memset ( PlainTextBuffer, 0x00, StreamBlockSize ); + + /* Decipher the ciphertext */ + + StartTime = clock ( ); + + ReturnCode = BLOWFISH_DecipherStream ( &DecipherContext, CipherTextBuffer, PlainTextBuffer, StreamBlockSize ); + + EndTime = clock ( ); + + /* Compute the time elapsed deciphering (in milliseconds) */ + + ElapsedDecipherTime += ( EndTime - StartTime ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + _BLOWFISH_PrintReturnCode ( "BLOWFISH_DecipherStream", ReturnCode ); + + break; + } + + /* Verify the integrity of the deciphered plaintext (sum of all bytes should equal the buffer length) */ + + for ( j = 0, Sum = 0; j < (BLOWFISH_SIZE_T)StreamBlockSize; j++ ) + { + Sum += PlainTextBuffer [ j ]; + } + + if ( Sum != StreamBlockSize ) + { + printf ( "BLOWFISH_EncipherStream()/BLOWFISH_DecipherStream()=Integrity check failed!\n" ); + + ReturnCode = BLOWFISH_RC_TEST_FAILED; + + break; + } + } + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* Ensure we managed to encipher/decipher enough data to determine the throughput in MB/s */ + + if ( ( i * StreamBlockSize ) > ( 1024 * 1024 ) ) + { + /* Adjust elapsed time based on thread count */ + + ElapsedEncipherTime = ElapsedEncipherTime / Threads; + ElapsedDecipherTime = ElapsedDecipherTime / Threads; + + /* Convert elapsed time from milliseconds to seconds (minimum 1 second) */ + + ElapsedEncipherTime = ElapsedEncipherTime / CLOCKS_PER_SEC > 1 ? ElapsedEncipherTime / CLOCKS_PER_SEC : 1; + ElapsedDecipherTime = ElapsedDecipherTime / CLOCKS_PER_SEC > 1 ? ElapsedDecipherTime / CLOCKS_PER_SEC : 1; + + /* Calculate and display the stream length */ + + BlocksProcessed = (float)( (float)( i * StreamBlockSize ) / ( 1024 * 1024 ) ); + + printf ( "Stream length=%0.2f MB (%d*%d byte blocks)\n", BlocksProcessed, (int)i, (int)StreamBlockSize ); + + /* Calculate and display throughputs */ + + printf ( "Encipher throughput=%0.2f MB/s\n", BlocksProcessed / ElapsedEncipherTime ); + printf ( "Decipher throughput=%0.2f MB/s\n", BlocksProcessed / ElapsedDecipherTime ); + printf ( "Average throughput=%0.2f MB/s\n", ( ( BlocksProcessed / ElapsedDecipherTime ) + ( BlocksProcessed / ElapsedEncipherTime ) ) / 2 ); + } + else + { + printf ( "Failed to process enough data to determine throughput in MB/s!\n" ); + + ReturnCode = BLOWFISH_RC_TEST_FAILED; + } + } + + /* Finished decipering */ + + BLOWFISH_EndStream ( &DecipherContext ); + } + + /* Finished encipering */ + + BLOWFISH_EndStream ( &EncipherContext ); + } + + /* Free the ciphertext */ + + free ( CipherTextBuffer ); + } + + /* Free the plaintext */ + + free ( PlainTextBuffer ); + } + } + + /* Overwrite the deciper stream context record */ + + BLOWFISH_Exit ( &DecipherContext ); + } + + printf ( "\n" ); + + /* Overwrite the encipher stream context record */ + + BLOWFISH_Exit ( &EncipherContext ); + + return ReturnCode; +} + +/** + + @internal + + Perform all self-tests for all supported modes. + + @return #BLOWFISH_RC_SUCCESS All tests passed successfully. + + @return Specific return code, see #BLOWFISH_RC. + + */ + +static BLOWFISH_RC _BLOWFISH_SelfTest ( ) +{ + BLOWFISH_RC ReturnCode; + BLOWFISH_ULONG i = 0; + + printf ( "Standard test vectors...\n\n" ); + + /* Perform ECB mode tests on test vector 1 */ + + for ( i = 0; i < sizeof ( _BLOWFISH_EcbTv1 ) / sizeof ( _BLOWFISH_EcbTv1 [ 0 ] ); i++ ) + { + ReturnCode = _BLOWFISH_Test_ECB ( (BLOWFISH_PUCHAR)&_BLOWFISH_EcbTv1 [ i ].Key, 8, _BLOWFISH_EcbTv1 [ i ].PlainText [ 0 ], _BLOWFISH_EcbTv1 [ i ].PlainText [ 1 ], _BLOWFISH_EcbTv1 [ i ].CipherText [ 0 ], _BLOWFISH_EcbTv1 [ i ].CipherText [ 1 ] ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + return ReturnCode; + } + } + + /* Perform ECB mode tests on test vector 2 */ + + for ( i = 0; i < sizeof ( _BLOWFISH_EcbTv2CipherText ) / sizeof ( _BLOWFISH_EcbTv2CipherText [ 0 ] ); i++ ) + { + ReturnCode = _BLOWFISH_Test_ECB ( (BLOWFISH_PUCHAR)&_BLOWFISH_EcbTv2Key, i + 4, _BLOWFISH_EcbTv2PlainText [ 0 ], _BLOWFISH_EcbTv2PlainText [ 1 ], _BLOWFISH_EcbTv2CipherText [ i ] [ 0 ], _BLOWFISH_EcbTv2CipherText [ i ] [ 1 ] ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + return ReturnCode; + } + } + + /* Perform CBC, CFB and OFB tests on test vector 3 */ + + for ( i = 0; i < sizeof ( _BLOWFISH_Tv3Mode ) / sizeof ( _BLOWFISH_Tv3Mode [ 0 ] ); i++ ) + { + ReturnCode = _BLOWFISH_Test_CBC_CFB_OFB ( (BLOWFISH_PUCHAR)&_BLOWFISH_Tv3Key, sizeof ( _BLOWFISH_Tv3Key ), _BLOWFISH_Tv3Mode [ i ], (BLOWFISH_PUCHAR)&_BLOWFISH_Tv3PlainText, (BLOWFISH_PUCHAR)&_BLOWFISH_Tv3CipherText [ i ], sizeof ( _BLOWFISH_Tv3PlainText ) ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + return ReturnCode; + } + } + +#ifdef _OPENMP + + /* Perform parallelised throughput tests if there is more than 1 available thread */ + + if ( omp_get_max_threads ( ) > 1 ) + { + printf ( "Parallelised throughput tests (using %d threads for ~%d seconds per mode)...\n\n", omp_get_max_threads ( ), _BLOWFISH_THROUGHPUT_DURATION ); + + for ( i = 0; i < sizeof ( _BLOWFISH_ThroughputTv ) / sizeof ( _BLOWFISH_ThroughputTv [ 0 ] ); i++ ) + { + if ( _BLOWFISH_ThroughputTv [ i ].Parallel != 0x00 ) + { + ReturnCode = _BLOWFISH_Test_Throughput ( _BLOWFISH_ThroughputTv [ i ].Mode, _BLOWFISH_THROUGHPUT_STREAM_LENGTH ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + return ReturnCode; + } + } + } + } + + /* Use a single thread for the serialised tests */ + + omp_set_num_threads ( 1 ); + +#endif + + /* Perform serialised throughput tests */ + + printf ( "Serialised throughput tests (using 1 thread for ~%d seconds per mode)...\n\n", _BLOWFISH_THROUGHPUT_DURATION ); + + for ( i = 0; i < sizeof ( _BLOWFISH_ThroughputTv ) / sizeof ( _BLOWFISH_ThroughputTv [ 0 ] ); i++ ) + { + ReturnCode = _BLOWFISH_Test_Throughput ( _BLOWFISH_ThroughputTv [ i ].Mode, _BLOWFISH_THROUGHPUT_STREAM_LENGTH ); + + if ( ReturnCode != BLOWFISH_RC_SUCCESS ) + { + return ReturnCode; + } + } + + return BLOWFISH_RC_SUCCESS; +} + +/** + + @internal + + Main entry point for the blowfish self-test application. + + @param ArgumentCount Number of command line arguments passed to the application. + + @param ArgumentVector Array of command line arguments passed to the application. + + @return #BLOWFISH_RC_SUCCESS All tests passed successfully. + + @return Specific return code, see #BLOWFISH_RC. + + */ + +int main ( int ArgumentCount, char * ArgumentVector [ ] ) +{ + BLOWFISH_RC ReturnCode; + + /* Unreferenced parameters */ + + ArgumentCount = ArgumentCount; + ArgumentVector = ArgumentVector; + + /* Perform all self tests */ + + printf ( "Blowfish selft-test application.\nCopyright (c) 2008, Tom Bonner (tom.bonner@gmail.com)\n\n(For best results close all running applications)\n\n" ); + + ReturnCode = _BLOWFISH_SelfTest ( ); + + if ( ReturnCode == BLOWFISH_RC_SUCCESS ) + { + /* All self test passed successfully */ + + printf ( "All Blowfish self-tests passed successfully!\n" ); + } + else + { + /* One of the self tests failed */ + + printf ( "Blowfish self-test failed!\n" ); + } + + return (int)ReturnCode; +} + +/** @} */ diff --git a/shared/thirdparty/ini/LICENSE b/shared/thirdparty/ini/LICENSE new file mode 100644 index 0000000..5818e8d --- /dev/null +++ b/shared/thirdparty/ini/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2016 rxi + + +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. diff --git a/shared/thirdparty/ini/README.md b/shared/thirdparty/ini/README.md new file mode 100644 index 0000000..e0f330d --- /dev/null +++ b/shared/thirdparty/ini/README.md @@ -0,0 +1,63 @@ + +# ini +A *tiny* ANSI C library for loading .ini config files + +## Usage +The files **[ini.c](src/ini.c?raw=1)** and **[ini.h](src/ini.h?raw=1)** should +be dropped into an existing project. + +The library has support for sections, comment lines and quoted string values +(with escapes). Unquoted values and keys are trimmed of whitespace when loaded. + +```ini +; last modified 1 April 2001 by John Doe +[owner] +name = John Doe +organization = Acme Widgets Inc. + +[database] +; use IP address in case network name resolution is not working +server = 192.0.2.62 +port = 143 +file = "payroll.dat" +``` + +An ini file can be loaded into memory by using the `ini_load()` function. +`NULL` is returned if the file cannot be loaded. +```c +ini_t *config = ini_load("config.ini"); +``` + +The library provides two functions for retrieving values: the first is +`ini_get()`. Given a section and a key the corresponding value is returned if +it exists. If the `section` argument is `NULL` then all sections are searched. +```c +const char *name = ini_get(config, "owner", "name"); +if (name) { + printf("name: %s\n", name); +} +``` + +The second, `ini_sget()`, takes the same arguments as `ini_get()` with the +addition of a scanf format string and a pointer for where to store the value. +```c +const char *server = "default"; +int port = 80; + +ini_sget(config, "database", "server", NULL, &server); +ini_sget(config, "database", "port", "%d", &port); + +printf("server: %s:%d\n", server, port); +``` + +The `ini_free()` function is used to free the memory used by the `ini_t*` +object when we are done with it. Calling this function invalidates all string +pointers returned by the library. +```c +ini_free(config); +``` + + +## License +This library is free software; you can redistribute it and/or modify it under +the terms of the MIT license. See [LICENSE](LICENSE) for details. diff --git a/shared/thirdparty/ini/src/ini.c b/shared/thirdparty/ini/src/ini.c new file mode 100644 index 0000000..ab5f11d --- /dev/null +++ b/shared/thirdparty/ini/src/ini.c @@ -0,0 +1,274 @@ +/** + * Copyright (c) 2016 rxi + * + * 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. + */ + +#include +#include +#include +#include + +#include "ini.h" + +struct ini_t { + char *data; + char *end; +}; + + +/* Case insensitive string compare */ +static int strcmpci(const char *a, const char *b) { + for (;;) { + int d = tolower(*a) - tolower(*b); + if (d != 0 || !*a) { + return d; + } + a++, b++; + } +} + +/* Returns the next string in the split data */ +static char* next(ini_t *ini, char *p) { + p += strlen(p); + while (p < ini->end && *p == '\0') { + p++; + } + return p; +} + +static void trim_back(ini_t *ini, char *p) { + while (p >= ini->data && (*p == ' ' || *p == '\t' || *p == '\r')) { + *p-- = '\0'; + } +} + +static char* discard_line(ini_t *ini, char *p) { + while (p < ini->end && *p != '\n') { + *p++ = '\0'; + } + return p; +} + + +static char *unescape_quoted_value(ini_t *ini, char *p) { + /* Use `q` as write-head and `p` as read-head, `p` is always ahead of `q` + * as escape sequences are always larger than their resultant data */ + char *q = p; + p++; + while (p < ini->end && *p != '"' && *p != '\r' && *p != '\n') { + if (*p == '\\') { + /* Handle escaped char */ + p++; + switch (*p) { + default : *q = *p; break; + case 'r' : *q = '\r'; break; + case 'n' : *q = '\n'; break; + case 't' : *q = '\t'; break; + case '\r' : + case '\n' : + case '\0' : goto end; + } + + } else { + /* Handle normal char */ + *q = *p; + } + q++, p++; + } +end: + return q; +} + + +/* Splits data in place into strings containing section-headers, keys and + * values using one or more '\0' as a delimiter. Unescapes quoted values */ +static void split_data(ini_t *ini) { + char *value_start, *line_start; + char *p = ini->data; + + while (p < ini->end) { + switch (*p) { + case '\r': + case '\n': + case '\t': + case ' ': + *p = '\0'; + /* Fall through */ + + case '\0': + p++; + break; + + case '[': + p += strcspn(p, "]\n"); + *p = '\0'; + break; + + case ';': + p = discard_line(ini, p); + break; + + default: + line_start = p; + p += strcspn(p, "=\n"); + + /* Is line missing a '='? */ + if (*p != '=') { + p = discard_line(ini, line_start); + break; + } + trim_back(ini, p - 1); + + /* Replace '=' and whitespace after it with '\0' */ + do { + *p++ = '\0'; + } while (*p == ' ' || *p == '\r' || *p == '\t'); + + /* Is a value after '=' missing? */ + if (*p == '\n' || *p == '\0') { + p = discard_line(ini, line_start); + break; + } + + if (*p == '"') { + /* Handle quoted string value */ + value_start = p; + p = unescape_quoted_value(ini, p); + + /* Was the string empty? */ + if (p == value_start) { + p = discard_line(ini, line_start); + break; + } + + /* Discard the rest of the line after the string value */ + p = discard_line(ini, p); + + } else { + /* Handle normal value */ + p += strcspn(p, "\n"); + trim_back(ini, p - 1); + } + break; + } + } +} + + + +ini_t* ini_load(const char *filename) { + ini_t *ini = NULL; + FILE *fp = NULL; + int n, sz; + + /* Init ini struct */ + ini = malloc(sizeof(*ini)); + if (!ini) { + goto fail; + } + memset(ini, 0, sizeof(*ini)); + + /* Open file */ + fp = fopen(filename, "rb"); + if (!fp) { + goto fail; + } + + /* Get file size */ + fseek(fp, 0, SEEK_END); + sz = ftell(fp); + rewind(fp); + + /* Load file content into memory, null terminate, init end var */ + ini->data = malloc(sz + 1); + ini->data[sz] = '\0'; + ini->end = ini->data + sz; + n = fread(ini->data, 1, sz, fp); + if (n != sz) { + goto fail; + } + + /* Prepare data */ + split_data(ini); + + /* Clean up and return */ + fclose(fp); + return ini; + +fail: + if (fp) fclose(fp); + if (ini) ini_free(ini); + return NULL; +} + + +void ini_free(ini_t *ini) { + free(ini->data); + free(ini); +} + + +const char* ini_get(ini_t *ini, const char *section, const char *key) { + char *current_section = ""; + char *val; + char *p = ini->data; + + if (*p == '\0') { + p = next(ini, p); + } + + while (p < ini->end) { + if (*p == '[') { + /* Handle section */ + current_section = p + 1; + + } else { + /* Handle key */ + val = next(ini, p); + if (!section || !strcmpci(section, current_section)) { + if (!strcmpci(p, key)) { + return val; + } + } + p = val; + } + + p = next(ini, p); + } + + return NULL; +} + + +int ini_sget( + ini_t *ini, const char *section, const char *key, + const char *scanfmt, void *dst +) { + const char *val = ini_get(ini, section, key); + if (!val) { + return 0; + } + if (scanfmt) { + sscanf(val, scanfmt, dst); + } else { + *((const char**) dst) = val; + } + return 1; +} diff --git a/shared/thirdparty/ini/src/ini.h b/shared/thirdparty/ini/src/ini.h new file mode 100644 index 0000000..cd6af9f --- /dev/null +++ b/shared/thirdparty/ini/src/ini.h @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2016 rxi + * + * This library is free software; you can redistribute it and/or modify it + * under the terms of the MIT license. See `ini.c` for details. + */ + +#ifndef INI_H +#define INI_H + +#define INI_VERSION "0.1.1" + +typedef struct ini_t ini_t; + +ini_t* ini_load(const char *filename); +void ini_free(ini_t *ini); +const char* ini_get(ini_t *ini, const char *section, const char *key); +int ini_sget(ini_t *ini, const char *section, const char *key, const char *scanfmt, void *dst); + +#endif