From 9c67f53902c39a8d53873c219a020b68abb3d539 Mon Sep 17 00:00:00 2001 From: kyoubate-haruka <46010460+kyoubate-haruka@users.noreply.github.com> Date: Thu, 26 Feb 2026 19:31:45 +0000 Subject: [PATCH] Add support for Sangokushi Taisen and Eiketsu Taisen (#85) This adds full support for the Taisen series of games, namely Sangokushi Taisen and Eiketsu Taisen. Games added: * Sangokushi Taisen (SDDD) * Eiketsu Taisen (SDGY) Devices added: * CHC-320 printer (SGT) * "Printer camera" (SGT, unsure what this actually really is) * CX-7000 printer (EKT) * Y3CR BD SIE F720MM (SGT, EKT) Notable changes in the codebase: * Renamed everything printer specific to seperate between CHC and CX. * Many new function and registry hooks were added across the board. * An error is now logged when segatools.ini (or the path in `SEGATOOLS_CONFIG_PATH`) cannot be found. * Netenv now redirects UDP broadcasts targeted at the subnet that is specified in the keychip configuration. The terminal announces it's presence by broadcasting UDP to 192.168.189.255, this will be redirected to 255.255.255.255. * Vfs now seperates between absolute and relative paths in `vfs_fixup_path` via an environment variable called `SEGATOOLS_VFS_RELATIVE_PATH`. This is needed because amcapture accesses files as workingdirectory-relative. * The Y3 board emulation has support for external Y3 I/O dlls. The default implementation (y3ws) that comes with this is a websocket implementation. The docs are available under `doc\y3ws.txt` and a sample card player .html file is under `dist\ekt\card_player.html`. I already know one person that is hosting a massively improved version of it. * For websockets, my own websocket implementation is used as a subproject (MIT license): https://github.com/akechi-haruka/cwinwebsocket * For JSON, cJSON was embedded (MIT license): https://github.com/DaveGamble/cJSON * y3ws reads all printed cards from `DEVICE\print` by default including card back sides. It's up to the client to merge or skip them. Remarks: * SGT takes ~8 minutes to load. This seems to be intentional. * SGT uses some weird TCP network implementation like IDZ. I have not bothered reversing that yet and I have confirmed everything working from the test menu. * EKT will throw a network error if no terminal is found. You must run the terminal on another computer to be able to launch the satellite. * EKT has a very bizzare speed glitch that will speed up the ingame unit movement by several 1000% and also slows down cutscene animations by 90%. When this effect is active, you also take a ton more damage than usual. I do not know what causes this and it seems PC specific. * EKT is very stutter sensitive and will throw error 6401 (I/O timeout) at random when trying to alt+tab or have other things running. * EKT features a livestream system called Enbu (or "Dojo Upload"). While you are in a match, regardless of vs. AI or another player, the game will record your screen and live-stream it to the Enbu server as defined by the game server's startup response. The application responsible for that, "AM Capture" will not limit it's recording to the game window, but also anything that overlays the game window (notifications, popups, alt+tabbed windows, web browsers, etc). Since this is live-streamed, killing the process will have no effect afterwards, as the frames showing unwanted things will already have been transmitted. To make people aware of this, a one-time dialog message will pop up when starting EKT. The flag for that is stored in the DEVICE folder. Closes #25. Co-authored-by: Dniel97 Reviewed-on: https://gitea.tendokyu.moe/TeamTofuShop/segatools/pulls/85 Co-authored-by: kyoubate-haruka <46010460+kyoubate-haruka@users.noreply.github.com> Co-committed-by: kyoubate-haruka <46010460+kyoubate-haruka@users.noreply.github.com> --- .gitignore | 1 + Package.mk | 53 + README.md | 14 +- common/aimeio/aimeio.c | 8 +- common/aimeio/aimeio.h | 8 +- common/board/config.c | 18 +- common/board/config.h | 1 + common/board/meson.build | 2 + common/board/sg-reader-queue.c | 208 ++ common/board/sg-reader-queue.h | 14 + common/hooklib/config.c | 162 +- common/hooklib/config.h | 25 +- common/hooklib/createprocess.c | 118 +- common/hooklib/createprocess.h | 7 +- common/hooklib/imageutil.c | 212 ++ common/hooklib/imageutil.h | 21 + common/hooklib/meson.build | 12 +- common/hooklib/path.c | 350 +- common/hooklib/path.h | 3 + common/hooklib/{printer.c => printer_chc.c} | 597 +-- common/hooklib/{printer.h => printer_chc.h} | 6 +- common/hooklib/printer_cx.c | 906 +++++ common/hooklib/printer_cx.h | 73 + common/hooklib/y3-dll.c | 109 + common/hooklib/y3-dll.h | 19 + common/hooklib/y3.c | 625 ++++ common/hooklib/y3.h | 71 + common/platform/amvideo.c | 10 + common/platform/config.c | 25 + common/platform/netenv.c | 86 +- common/platform/netenv.h | 1 + common/platform/nusec.h | 1 + common/platform/vfs.c | 31 +- common/unityhook/hook.c | 2 +- common/y3io/impl/dummy/y3io.c | 68 + .../impl/websockets/3rdparty/cjson/LICENSE | 20 + .../impl/websockets/3rdparty/cjson/cJSON.c | 3191 +++++++++++++++++ .../impl/websockets/3rdparty/cjson/cJSON.h | 306 ++ .../websockets/3rdparty/cjson/cJSON_Utils.c | 1481 ++++++++ .../websockets/3rdparty/cjson/cJSON_Utils.h | 88 + common/y3io/impl/websockets/config.c | 39 + common/y3io/impl/websockets/config.h | 19 + common/y3io/impl/websockets/y3ws.c | 354 ++ common/y3io/impl/websockets/y3ws.h | 4 + common/y3io/impl/y3io.h | 31 + common/y3io/meson.build | 25 + dist/ekt/card_player.html | 224 ++ dist/ekt/config_hook.json | 13 + dist/ekt/launch_satellite.bat | 24 + dist/ekt/launch_terminal.bat | 13 + dist/ekt/segatools_satellite.ini | 181 + dist/ekt/segatools_terminal.ini | 145 + dist/sekito/card_player.html | 228 ++ dist/sekito/config_hook_satellite.json | 6 + dist/sekito/config_hook_terminal.json | 35 + dist/sekito/launch_satellite.bat | 15 + dist/sekito/launch_terminal.bat | 19 + dist/sekito/segatools_satellite.ini | 207 ++ dist/sekito/segatools_terminal.ini | 174 + doc/config/common.md | 10 + doc/config/taisen.md | 107 + doc/y3ws.txt | 57 + games/apm3hook/config.h | 2 +- games/carolhook/dllmain.c | 2 +- games/cmhook/config.c | 2 +- games/cmhook/config.h | 4 +- games/cmhook/dllmain.c | 2 +- games/ekthook/config.c | 107 + games/ekthook/config.h | 37 + games/ekthook/dllmain.c | 224 ++ games/ekthook/ekt-dll.c | 118 + games/ekthook/ekt-dll.h | 24 + games/ekthook/ekthook.def | 73 + games/ekthook/io4.c | 223 ++ games/ekthook/io4.h | 24 + games/ekthook/meson.build | 31 + games/ektio/backend.h | 10 + games/ektio/config.c | 77 + games/ektio/config.h | 62 + games/ektio/ektio.c | 108 + games/ektio/ektio.h | 106 + games/ektio/keyboard.c | 176 + games/ektio/keyboard.h | 8 + games/ektio/meson.build | 18 + games/fgohook/config.c | 2 +- games/fgohook/config.h | 4 +- games/fgohook/dllmain.c | 6 +- games/fgohook/fgohook.def | 2 +- games/kemonohook/config.c | 2 +- games/kemonohook/config.h | 2 +- games/kemonohook/dllmain.c | 4 +- games/sekitohook/config.c | 113 + games/sekitohook/config.h | 41 + games/sekitohook/dllmain.c | 207 ++ games/sekitohook/jvs.c | 258 ++ games/sekitohook/jvs.h | 18 + games/sekitohook/meson.build | 32 + games/sekitohook/sekito-dll.c | 118 + games/sekitohook/sekito-dll.h | 24 + games/sekitohook/sekitohook.def | 78 + games/sekitoio/backend.h | 10 + games/sekitoio/config.c | 74 + games/sekitoio/config.h | 59 + games/sekitoio/keyboard.c | 168 + games/sekitoio/keyboard.h | 8 + games/sekitoio/meson.build | 18 + games/sekitoio/sekitoio.c | 108 + games/sekitoio/sekitoio.h | 104 + meson.build | 11 + subprojects/cwinwebsocket.wrap | 5 + 110 files changed, 13209 insertions(+), 588 deletions(-) create mode 100644 common/board/sg-reader-queue.c create mode 100644 common/board/sg-reader-queue.h create mode 100644 common/hooklib/imageutil.c create mode 100644 common/hooklib/imageutil.h rename common/hooklib/{printer.c => printer_chc.c} (88%) rename common/hooklib/{printer.h => printer_chc.h} (74%) create mode 100644 common/hooklib/printer_cx.c create mode 100644 common/hooklib/printer_cx.h create mode 100644 common/hooklib/y3-dll.c create mode 100644 common/hooklib/y3-dll.h create mode 100644 common/hooklib/y3.c create mode 100644 common/hooklib/y3.h create mode 100644 common/y3io/impl/dummy/y3io.c create mode 100644 common/y3io/impl/websockets/3rdparty/cjson/LICENSE create mode 100644 common/y3io/impl/websockets/3rdparty/cjson/cJSON.c create mode 100644 common/y3io/impl/websockets/3rdparty/cjson/cJSON.h create mode 100644 common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.c create mode 100644 common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.h create mode 100644 common/y3io/impl/websockets/config.c create mode 100644 common/y3io/impl/websockets/config.h create mode 100644 common/y3io/impl/websockets/y3ws.c create mode 100644 common/y3io/impl/websockets/y3ws.h create mode 100644 common/y3io/impl/y3io.h create mode 100644 common/y3io/meson.build create mode 100644 dist/ekt/card_player.html create mode 100644 dist/ekt/config_hook.json create mode 100644 dist/ekt/launch_satellite.bat create mode 100644 dist/ekt/launch_terminal.bat create mode 100644 dist/ekt/segatools_satellite.ini create mode 100644 dist/ekt/segatools_terminal.ini create mode 100644 dist/sekito/card_player.html create mode 100644 dist/sekito/config_hook_satellite.json create mode 100644 dist/sekito/config_hook_terminal.json create mode 100644 dist/sekito/launch_satellite.bat create mode 100644 dist/sekito/launch_terminal.bat create mode 100644 dist/sekito/segatools_satellite.ini create mode 100644 dist/sekito/segatools_terminal.ini create mode 100644 doc/config/taisen.md create mode 100644 doc/y3ws.txt create mode 100644 games/ekthook/config.c create mode 100644 games/ekthook/config.h create mode 100644 games/ekthook/dllmain.c create mode 100644 games/ekthook/ekt-dll.c create mode 100644 games/ekthook/ekt-dll.h create mode 100644 games/ekthook/ekthook.def create mode 100644 games/ekthook/io4.c create mode 100644 games/ekthook/io4.h create mode 100644 games/ekthook/meson.build create mode 100644 games/ektio/backend.h create mode 100644 games/ektio/config.c create mode 100644 games/ektio/config.h create mode 100644 games/ektio/ektio.c create mode 100644 games/ektio/ektio.h create mode 100644 games/ektio/keyboard.c create mode 100644 games/ektio/keyboard.h create mode 100644 games/ektio/meson.build create mode 100644 games/sekitohook/config.c create mode 100644 games/sekitohook/config.h create mode 100644 games/sekitohook/dllmain.c create mode 100644 games/sekitohook/jvs.c create mode 100644 games/sekitohook/jvs.h create mode 100644 games/sekitohook/meson.build create mode 100644 games/sekitohook/sekito-dll.c create mode 100644 games/sekitohook/sekito-dll.h create mode 100644 games/sekitohook/sekitohook.def create mode 100644 games/sekitoio/backend.h create mode 100644 games/sekitoio/config.c create mode 100644 games/sekitoio/config.h create mode 100644 games/sekitoio/keyboard.c create mode 100644 games/sekitoio/keyboard.h create mode 100644 games/sekitoio/meson.build create mode 100644 games/sekitoio/sekitoio.c create mode 100644 games/sekitoio/sekitoio.h create mode 100644 subprojects/cwinwebsocket.wrap diff --git a/.gitignore b/.gitignore index f5d9008..8e442f9 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ build/ # External dependencies subprojects/capnhook +subprojects/cwinwebsocket # For enabling debug logging on local builds MesonLocalOptions.mk diff --git a/Package.mk b/Package.mk index 3c974e7..f79a357 100644 --- a/Package.mk +++ b/Package.mk @@ -256,6 +256,57 @@ $(BUILD_DIR_ZIP)/apm3.zip: $(V)strip $(BUILD_DIR_ZIP)/apm3/*.{exe,dll} $(V)cd $(BUILD_DIR_ZIP)/apm3 ; zip -r ../apm3.zip * +$(BUILD_DIR_ZIP)/ekt.zip: + $(V)echo ... $@ + $(V)mkdir -p $(BUILD_DIR_ZIP)/ekt + $(V)mkdir -p $(BUILD_DIR_ZIP)/ekt/DEVICE + $(V)cp $(DIST_DIR)/ekt/segatools_terminal.ini \ + $(DIST_DIR)/ekt/segatools_satellite.ini \ + $(DIST_DIR)/ekt/launch_terminal.bat \ + $(DIST_DIR)/ekt/launch_satellite.bat \ + $(DIST_DIR)/ekt/card_player.html \ + $(DIST_DIR)/ekt/config_hook.json \ + $(BUILD_DIR_ZIP)/ekt + $(V)cp pki/billing.pub \ + pki/ca.crt \ + $(BUILD_DIR_ZIP)/ekt/DEVICE + $(V)cp $(BUILD_DIR_32)/subprojects/capnhook/inject/inject.exe \ + $(BUILD_DIR_ZIP)/ekt/inject_x86.exe + $(V)cp $(BUILD_DIR_64)/subprojects/capnhook/inject/inject.exe \ + $(BUILD_DIR_ZIP)/ekt/inject_x64.exe + $(V)cp $(BUILD_DIR_GAMES_32)/ekthook/ekthook.dll \ + $(BUILD_DIR_ZIP)/ekt/ekthook_x86.dll + $(V)cp $(BUILD_DIR_GAMES_64)/ekthook/ekthook.dll \ + $(BUILD_DIR_ZIP)/ekt/ekthook_x64.dll + $(V)strip $(BUILD_DIR_ZIP)/ekt/*.{exe,dll} + $(V)cd $(BUILD_DIR_ZIP)/ekt ; zip -r ../ekt.zip * + +$(BUILD_DIR_ZIP)/sekito.zip: + $(V)echo ... $@ + $(V)mkdir -p $(BUILD_DIR_ZIP)/sekito + $(V)mkdir -p $(BUILD_DIR_ZIP)/sekito/DEVICE + $(V)cp $(DIST_DIR)/sekito/segatools_terminal.ini \ + $(DIST_DIR)/sekito/segatools_satellite.ini \ + $(DIST_DIR)/sekito/launch_terminal.bat \ + $(DIST_DIR)/sekito/launch_satellite.bat \ + $(DIST_DIR)/sekito/card_player.html \ + $(DIST_DIR)/sekito/config_hook_satellite.json \ + $(DIST_DIR)/sekito/config_hook_terminal.json \ + $(BUILD_DIR_ZIP)/sekito + $(V)cp pki/billing.pub \ + pki/ca.crt \ + $(BUILD_DIR_ZIP)/sekito/DEVICE + $(V)cp $(BUILD_DIR_32)/subprojects/capnhook/inject/inject.exe \ + $(BUILD_DIR_ZIP)/sekito/inject_x86.exe + $(V)cp $(BUILD_DIR_64)/subprojects/capnhook/inject/inject.exe \ + $(BUILD_DIR_ZIP)/sekito/inject_x64.exe + $(V)cp $(BUILD_DIR_GAMES_32)/sekitohook/sekitohook.dll \ + $(BUILD_DIR_ZIP)/sekito/sekitohook_x86.dll + $(V)cp $(BUILD_DIR_GAMES_64)/sekitohook/sekitohook.dll \ + $(BUILD_DIR_ZIP)/sekito/sekitohook_x64.dll + $(V)strip $(BUILD_DIR_ZIP)/sekito/*.{exe,dll} + $(V)cd $(BUILD_DIR_ZIP)/sekito ; zip -r ../sekito.zip * + $(BUILD_DIR_ZIP)/doc.zip: \ $(DOC_DIR)/config \ $(DOC_DIR)/chunihook.md \ @@ -282,6 +333,8 @@ $(BUILD_DIR_ZIP)/segatools.zip: \ $(BUILD_DIR_ZIP)/fgo.zip \ $(BUILD_DIR_ZIP)/kemono.zip \ $(BUILD_DIR_ZIP)/apm3.zip \ + $(BUILD_DIR_ZIP)/ekt.zip \ + $(BUILD_DIR_ZIP)/sekito.zip \ CHANGELOG.md \ README.md \ diff --git a/README.md b/README.md index 9a4b29a..484c2c0 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ # Segatools -Version: `2025-11-04` +Version: `2026-02-26` Loaders and hardware emulators for SEGA games that run on the Nu and ALLS platforms. ## List of supported games +* ALL.Net P-ras MULTI Version 3 + * starting from ALL.Net P-ras MULTI Version 3 1.01 * Card Maker * starting from Card Maker * CHUNITHM @@ -13,6 +15,8 @@ Loaders and hardware emulators for SEGA games that run on the Nu and ALLS platfo * starting from CHUNITHM NEW!! * crossbeats REV. * up to crossbeats REV. SUNRISE +* Eiketsu Taisen (英傑大戦) + * starting from Sanzensekai no Hadou (三千世界の波動) * Fate/Grand Order * Fate/Grand Order Arcade * Hatsune Miku: Project DIVA Arcade @@ -20,20 +24,20 @@ Loaders and hardware emulators for SEGA games that run on the Nu and ALLS platfo * Initial D * [Initial D Arcade Stage Zero](doc/idzhook.md) * Initial D THE ARCADE +* Kemono Friends + * Kemono Friends 3: Planet Tours * maimai DX * starting from maimai DX * Mario & Sonic * Mario & Sonic at the Tokyo 2020 Olympics Arcade * O.N.G.E.K.I. * starting from O.N.G.E.K.I. +* Sangokushi Taisen (三国志大戦) + * starting from 1.01 * SEGA World Drivers Championship * SEGA World Drivers Championship 2019 * WACCA * starting from WACCA -* Kemono Friends - * Kemono Friends 3: Planet Tours -* ALL.Net P-ras MULTI Version 3 - * starting from ALL.Net P-ras MULTI Version 3 1.01 ## End-users diff --git a/common/aimeio/aimeio.c b/common/aimeio/aimeio.c index fbb694e..1b26b0d 100644 --- a/common/aimeio/aimeio.c +++ b/common/aimeio/aimeio.c @@ -235,10 +235,6 @@ HRESULT aime_io_nfc_poll(uint8_t unit_no) bool sense; HRESULT hr; - if (unit_no != 0) { - return S_OK; - } - /* Reset presence flags */ aime_io_aime_id_present = false; @@ -324,7 +320,7 @@ HRESULT aime_io_nfc_get_aime_id( assert(luid != NULL); assert(luid_size == sizeof(aime_io_aime_id)); - if (unit_no != 0 || !aime_io_aime_id_present) { + if (!aime_io_aime_id_present) { return S_FALSE; } @@ -340,7 +336,7 @@ HRESULT aime_io_nfc_get_felica_id(uint8_t unit_no, uint64_t *IDm) assert(IDm != NULL); - if (unit_no != 0 || !aime_io_felica_id_present) { + if (!aime_io_felica_id_present) { return S_FALSE; } diff --git a/common/aimeio/aimeio.h b/common/aimeio/aimeio.h index 96dd241..3c15dcf 100644 --- a/common/aimeio/aimeio.h +++ b/common/aimeio/aimeio.h @@ -27,7 +27,7 @@ HRESULT aime_io_init(void); /* Poll for IC cards in the vicinity. - - unit_no: Always 0 as of the current API version + - unit_no: 0 on the primary Aime reader (most games), may be 1 on Sangokushi Taisen for the queue reader Minimum API version: 0x0100 */ @@ -36,7 +36,7 @@ HRESULT aime_io_nfc_poll(uint8_t unit_no); /* Attempt to read out a classic Aime card ID - - unit_no: Always 0 as of the current API version + - unit_no: 0 on the primary Aime reader (most games), may be 1 on Sangokushi Taisen for the queue reader - luid: Pointer to a ten-byte buffer that will receive the ID - luid_size: Size of the buffer at *luid. Always 10. @@ -63,7 +63,7 @@ HRESULT aime_io_nfc_get_aime_id( Parameters: - - unit_no: Always 0 as of the current API version + - unit_no: 0 on the primary Aime reader (most games), may be 1 on Sangokushi Taisen for the queue reader - IDm: Output parameter that will receive the card ID Returns: @@ -213,7 +213,7 @@ HRESULT aime_io_nfc_send_hex_data( /* Change the color and brightness of the card reader's RGB lighting - - unit_no: Always 0 as of the current API version + - unit_no: 0 on the primary Aime reader (most games), may be 1 on Sangokushi Taisen for the queue reader - r, g, b: Primary color intensity, from 0 to 255 inclusive. Minimum API version: 0x0100 diff --git a/common/board/config.c b/common/board/config.c index a36d7c2..cb2f948 100644 --- a/common/board/config.c +++ b/common/board/config.c @@ -65,20 +65,24 @@ static void aime_dll_config_load(struct aime_dll_config *cfg, const wchar_t *fil } } -void aime_config_load(struct aime_config *cfg, const wchar_t *filename) +void aime_config_load(struct aime_config *cfg, const wchar_t *filename) { + aime_config_load_bykey(cfg, filename, L"aime"); +} + +void aime_config_load_bykey(struct aime_config *cfg, const wchar_t *filename, const wchar_t* config_key) { assert(cfg != NULL); assert(filename != NULL); aime_dll_config_load(&cfg->dll, filename); - cfg->enable = GetPrivateProfileIntW(L"aime", L"enable", 1, filename); - cfg->port_no = GetPrivateProfileIntW(L"aime", L"portNo", 0, filename); - cfg->high_baudrate = GetPrivateProfileIntW(L"aime", L"highBaud", 1, filename); - cfg->gen = GetPrivateProfileIntW(L"aime", L"gen", 0, filename); - cfg->proxy_flag = GetPrivateProfileIntW(L"aime", L"proxyFlag", 2, filename); + cfg->enable = GetPrivateProfileIntW(config_key, L"enable", 1, filename); + cfg->port_no = GetPrivateProfileIntW(config_key, L"portNo", 0, filename); + cfg->high_baudrate = GetPrivateProfileIntW(config_key, L"highBaud", 1, filename); + cfg->gen = GetPrivateProfileIntW(config_key, L"gen", 0, filename); + cfg->proxy_flag = GetPrivateProfileIntW(config_key, L"proxyFlag", 2, filename); GetPrivateProfileStringW( - L"aime", + config_key, L"authdataPath", L"DEVICE\\authdata.bin", cfg->authdata_path, diff --git a/common/board/config.h b/common/board/config.h index 34977dc..58fd8e2 100644 --- a/common/board/config.h +++ b/common/board/config.h @@ -9,6 +9,7 @@ #include "board/ffb.h" void aime_config_load(struct aime_config *cfg, const wchar_t *filename); +void aime_config_load_bykey(struct aime_config *cfg, const wchar_t *filename, const wchar_t *config_key); void io4_config_load(struct io4_config *cfg, const wchar_t *filename); void vfd_config_load(struct vfd_config *cfg, const wchar_t *filename); void ffb_config_load(struct ffb_config *cfg, const wchar_t *filename); diff --git a/common/board/meson.build b/common/board/meson.build index ca3c2ca..4931a82 100644 --- a/common/board/meson.build +++ b/common/board/meson.build @@ -44,6 +44,8 @@ board_lib = static_library( 'sg-nfc-cmd.h', 'sg-reader.c', 'sg-reader.h', + 'sg-reader-queue.c', + 'sg-reader-queue.h', 'slider-cmd.h', 'slider-frame.c', 'slider-frame.h', diff --git a/common/board/sg-reader-queue.c b/common/board/sg-reader-queue.c new file mode 100644 index 0000000..29637e7 --- /dev/null +++ b/common/board/sg-reader-queue.c @@ -0,0 +1,208 @@ +#include + +#include +#include +#include + +#include "board/aime-dll.h" +#include "board/sg-led.h" +#include "board/sg-nfc.h" +#include "board/sg-reader.h" +#include "board/sg-reader-queue.h" + +#include "hook/iohook.h" + +#include "hooklib/uart.h" + +#include "util/dprintf.h" +#include "util/dump.h" + +static HRESULT sg_reader_handle_irp(struct irp *irp); +static HRESULT sg_reader_handle_irp_locked(struct irp *irp); +static HRESULT sg_reader_nfc_poll(void *ctx); +static HRESULT sg_reader_nfc_get_aime_id( + void *ctx, + uint8_t *luid, + size_t luid_size); +static HRESULT sg_reader_nfc_get_felica_id(void *ctx, uint64_t *IDm); +static void sg_reader_led_set_color(void *ctx, uint8_t r, uint8_t g, uint8_t b); + +static const struct sg_nfc_ops sg_reader_nfc_ops = { + .poll = sg_reader_nfc_poll, + .get_aime_id = sg_reader_nfc_get_aime_id, + .get_felica_id = sg_reader_nfc_get_felica_id, +}; + +static const struct sg_led_ops sg_reader_led_ops = { + .set_color = sg_reader_led_set_color, +}; + +static CRITICAL_SECTION sg_reader_lock; +static bool sg_reader_started; +static HRESULT sg_reader_start_hr; +static struct uart sg_reader_uart; +static uint8_t sg_reader_written_bytes[520]; +static uint8_t sg_reader_readable_bytes[520]; +static struct sg_nfc sg_reader_nfc; +static struct sg_led sg_reader_led; + +HRESULT sg_reader_queue_hook_init( + const struct aime_config *cfg, + unsigned int default_port_no, + unsigned int gen, + HINSTANCE self) +{ + HRESULT hr; + + assert(cfg != NULL); + assert(self != NULL); + + if (!cfg->enable) { + return S_FALSE; + } + + hr = aime_dll_init(&cfg->dll, self); + + if (FAILED(hr)) { + return hr; + } + + unsigned int port_no = cfg->port_no; + if (port_no == 0){ + port_no = default_port_no; + } + + if (cfg->gen != 0) { + gen = cfg->gen; + } + + if (gen < 1 || gen > 3) { + dprintf("NFC Assembly (Queue): Invalid reader generation: %u\n", gen); + + return E_INVALIDARG; + } + + sg_nfc_init(&sg_reader_nfc, 0x01, &sg_reader_nfc_ops, gen, cfg->proxy_flag, cfg->authdata_path, NULL); + sg_led_init(&sg_reader_led, 0x08, &sg_reader_led_ops, gen, NULL); + + InitializeCriticalSection(&sg_reader_lock); + + if (!cfg->high_baudrate) { + sg_reader_uart.baud.BaudRate = 38400; + } + + dprintf("NFC Assembly (Queue): enabling (port=%d)\n", port_no); + uart_init(&sg_reader_uart, port_no); + sg_reader_uart.written.bytes = sg_reader_written_bytes; + sg_reader_uart.written.nbytes = sizeof(sg_reader_written_bytes); + sg_reader_uart.readable.bytes = sg_reader_readable_bytes; + sg_reader_uart.readable.nbytes = sizeof(sg_reader_readable_bytes); + + return iohook_push_handler(sg_reader_handle_irp); +} + +static HRESULT sg_reader_handle_irp(struct irp *irp) +{ + HRESULT hr; + + assert(irp != NULL); + + if (!uart_match_irp(&sg_reader_uart, irp)) { + return iohook_invoke_next(irp); + } + + EnterCriticalSection(&sg_reader_lock); + hr = sg_reader_handle_irp_locked(irp); + LeaveCriticalSection(&sg_reader_lock); + + return hr; +} + +static HRESULT sg_reader_handle_irp_locked(struct irp *irp) +{ + HRESULT hr; + +#if defined(LOG_NFC) + if (irp->op == IRP_OP_WRITE) { + dprintf("WRITE:\n"); + dump_const_iobuf(&irp->write); + } +#endif + +#if defined(LOG_NFC) + if (irp->op == IRP_OP_READ) { + dprintf("READ:\n"); + dump_iobuf(&sg_reader_uart.readable); + } +#endif + + if (irp->op == IRP_OP_OPEN) { + /* Unfortunately the card reader UART gets opened and closed + repeatedly */ + + if (!sg_reader_started) { + dprintf("NFC Assembly (Queue): Starting backend DLL\n"); + hr = aime_dll.init(); + + sg_reader_started = true; + sg_reader_start_hr = hr; + + if (FAILED(hr)) { + dprintf("NFC Assembly (Queue): Backend error: %x\n", (int) hr); + + return hr; + } + } else { + hr = sg_reader_start_hr; + + if (FAILED(hr)) { + return hr; + } + } + } + + hr = uart_handle_irp(&sg_reader_uart, irp); + + if (FAILED(hr) || irp->op != IRP_OP_WRITE) { + return hr; + } + + sg_nfc_transact( + &sg_reader_nfc, + &sg_reader_uart.readable, + sg_reader_uart.written.bytes, + sg_reader_uart.written.pos); + + sg_led_transact( + &sg_reader_led, + &sg_reader_uart.readable, + sg_reader_uart.written.bytes, + sg_reader_uart.written.pos); + + sg_reader_uart.written.pos = 0; + + return hr; +} + +static HRESULT sg_reader_nfc_poll(void *ctx) +{ + return aime_dll.nfc_poll(1); +} + +static HRESULT sg_reader_nfc_get_aime_id( + void *ctx, + uint8_t *luid, + size_t luid_size) +{ + return aime_dll.nfc_get_aime_id(1, luid, luid_size); +} + +static HRESULT sg_reader_nfc_get_felica_id(void *ctx, uint64_t *IDm) +{ + return aime_dll.nfc_get_felica_id(1, IDm); +} + +static void sg_reader_led_set_color(void *ctx, uint8_t r, uint8_t g, uint8_t b) +{ + aime_dll.led_set_color(1, r, g, b); +} diff --git a/common/board/sg-reader-queue.h b/common/board/sg-reader-queue.h new file mode 100644 index 0000000..d81b41a --- /dev/null +++ b/common/board/sg-reader-queue.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +#include + +#include "board/aime-dll.h" +#include "board/sg-reader.h" + +HRESULT sg_reader_queue_hook_init( + const struct aime_config *cfg, + unsigned int default_port_no, + unsigned int gen, + HINSTANCE self); diff --git a/common/hooklib/config.c b/common/hooklib/config.c index b7a84cf..705dcb1 100644 --- a/common/hooklib/config.c +++ b/common/hooklib/config.c @@ -7,6 +7,8 @@ #include "hooklib/config.h" #include "hooklib/dvd.h" +#include "hooklib/y3.h" +#include "hooklib/y3-dll.h" void dvd_config_load(struct dvd_config *cfg, const wchar_t *filename) { @@ -26,7 +28,7 @@ void touch_screen_config_load(struct touch_screen_config *cfg, const wchar_t *fi cfg->cursor = GetPrivateProfileIntW(L"touch", L"cursor", 1, filename); } -void printer_config_load(struct printer_config *cfg, const wchar_t *filename) +void printer_chc_config_load(struct printer_chc_config *cfg, const wchar_t *filename) { assert(cfg != NULL); assert(filename != NULL); @@ -84,3 +86,161 @@ void printer_config_load(struct printer_config *cfg, const wchar_t *filename) cfg->wait_time = GetPrivateProfileIntW(L"printer", L"waitTime", 0, filename); } + +void printer_cx_config_load(struct printer_cx_config *cfg, const wchar_t *filename){ + assert(cfg != NULL); + assert(filename != NULL); + + char filenameA[MAX_PATH]; + + size_t n = wcstombs(filenameA, filename, MAX_PATH); + for (int i = n; i < MAX_PATH; i++) + { + filenameA[i] = '\0'; + } + + cfg->enable = GetPrivateProfileIntW(L"printer", L"enable", 1, filename); + + GetPrivateProfileStringA( + "printer", + "firmwareVersion", + "V04-03B", + cfg->printer_firm_version, + _countof(cfg->printer_firm_version), + filenameA); + + GetPrivateProfileStringA( + "printer", + "configVersion", + "V01-75", + cfg->printer_config_version, + _countof(cfg->printer_config_version), + filenameA); + + GetPrivateProfileStringA( + "printer", + "tableVersion", + "V01-E0", + cfg->printer_table_version, + _countof(cfg->printer_table_version), + filenameA); + + GetPrivateProfileStringA( + "printer", + "cameraVersion", + "00.19", + cfg->printer_camera_version, + _countof(cfg->printer_camera_version), + filenameA); + + GetPrivateProfileStringW( + L"printer", + L"printerOutPath", + L"DEVICE\\print", + cfg->printer_out_path, + _countof(cfg->printer_out_path), + filename); + + GetPrivateProfileStringW( + L"printer", + L"printerDataPath", + L"DEVICE\\cx7000_data.bin", + cfg->printer_data_path, + _countof(cfg->printer_data_path), + filename); + +} + +void y3_dll_config_load( + struct y3_dll_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + GetPrivateProfileStringW( + L"y3io", + L"path", + L"", + cfg->path, + _countof(cfg->path), + filename); +} + +void y3_config_load( + struct y3_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + wchar_t tmpstr[5]; + + memset(cfg->firm_name_field, ' ', sizeof(cfg->firm_name_field) - 1); + cfg->firm_name_field[sizeof(cfg->firm_name_field) - 1] = '\0'; + + memset(cfg->firm_name_printer, ' ', sizeof(cfg->firm_name_printer) - 1); + cfg->firm_name_printer[sizeof(cfg->firm_name_printer) - 1] = '\0'; + + memset(cfg->target_code_field, ' ', sizeof(cfg->target_code_field) - 1); + cfg->target_code_field[sizeof(cfg->target_code_field) - 1] = '\0'; + + memset(cfg->target_code_printer, ' ', sizeof(cfg->target_code_printer) - 1); + cfg->target_code_printer[sizeof(cfg->target_code_printer) - 1] = '\0'; + + cfg->enable = GetPrivateProfileIntW(L"flatPanelReader", L"enable", 1, filename); + cfg->port_field = GetPrivateProfileIntW(L"flatPanelReader", L"port_field", 10, filename); + cfg->port_printer = GetPrivateProfileIntW(L"flatPanelReader", L"port_printer", 11, filename); + + cfg->dll_version = (float)GetPrivateProfileIntW( + L"flatPanelReader", + L"dllVersion", + 1, + filename); + + cfg->firm_version = (float)GetPrivateProfileIntW( + L"flatPanelReader", + L"firmVersion", + 1, + filename); + + GetPrivateProfileStringW( + L"flatPanelReader", + L"firmNameField", + L"SFPR", + tmpstr, + _countof(tmpstr), + filename); + + wcstombs(cfg->firm_name_field, tmpstr, sizeof(cfg->firm_name_field) - 1); + + GetPrivateProfileStringW( + L"flatPanelReader", + L"firmNamePrinter", + L"SPRT", + tmpstr, + _countof(tmpstr), + filename); + + wcstombs(cfg->firm_name_printer, tmpstr, sizeof(cfg->firm_name_printer) - 1); + + GetPrivateProfileStringW( + L"flatPanelReader", + L"targetCodeField", + L"SFR0", + tmpstr, + _countof(tmpstr), + filename); + + wcstombs(cfg->target_code_field, tmpstr, sizeof(cfg->target_code_field) - 1); + + GetPrivateProfileStringW( + L"flatPanelReader", + L"targetCodePrinter", + L"SPT0", + tmpstr, + _countof(tmpstr), + filename); + + wcstombs(cfg->target_code_printer, tmpstr, sizeof(cfg->target_code_printer) - 1); +} \ No newline at end of file diff --git a/common/hooklib/config.h b/common/hooklib/config.h index 9daed18..b776407 100644 --- a/common/hooklib/config.h +++ b/common/hooklib/config.h @@ -4,8 +4,29 @@ #include "hooklib/dvd.h" #include "hooklib/touch.h" -#include "hooklib/printer.h" +#include "hooklib/printer_chc.h" +#include "hooklib/printer_cx.h" + +struct y3_config { + bool enable; + + float dll_version; + float firm_version; + char firm_name_field[5]; + char firm_name_printer[5]; + char target_code_field[5]; + char target_code_printer[5]; + uint8_t port_field; + uint8_t port_printer; +}; + +struct y3_dll_config { + wchar_t path[MAX_PATH]; +}; void dvd_config_load(struct dvd_config *cfg, const wchar_t *filename); void touch_screen_config_load(struct touch_screen_config *cfg, const wchar_t *filename); -void printer_config_load(struct printer_config *cfg, const wchar_t *filename); +void printer_chc_config_load(struct printer_chc_config *cfg, const wchar_t *filename); +void printer_cx_config_load(struct printer_cx_config *cfg, const wchar_t *filename); +void y3_config_load(struct y3_config *cfg, const wchar_t *filename); +void y3_dll_config_load(struct y3_dll_config *cfg, const wchar_t *filename); \ No newline at end of file diff --git a/common/hooklib/createprocess.c b/common/hooklib/createprocess.c index 6462394..e141aca 100644 --- a/common/hooklib/createprocess.c +++ b/common/hooklib/createprocess.c @@ -5,11 +5,14 @@ #include #include #include +#include #include "hook/table.h" #include "hooklib/createprocess.h" +#include "path.h" +#include "hook/procaddr.h" #include "util/dprintf.h" void createprocess_hook_init(); @@ -36,7 +39,15 @@ BOOL my_CreateProcessW( LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation -); + ); + +BOOL my_ShellExecuteExA(SHELLEXECUTEINFOA *pExecInfo); + +BOOL my_ShellExecuteExW(SHELLEXECUTEINFOW *pExecInfo); + +static BOOL (WINAPI *next_ShellExecuteExA)(SHELLEXECUTEINFOA *pExecInfo); + +static BOOL (WINAPI *next_ShellExecuteExW)(SHELLEXECUTEINFOW *pExecInfo); static BOOL (WINAPI *next_CreateProcessA)( LPCSTR lpApplicationName, @@ -76,6 +87,18 @@ static const struct hook_symbol win32_hooks[] = { .link = (void **) &next_CreateProcessW }, }; +static const struct hook_symbol shell32_hooks[] = { + { + .name = "ShellExecuteExA", + .patch = my_ShellExecuteExA, + .link = (void **) &next_ShellExecuteExA + }, + { + .name = "ShellExecuteExW", + .patch = my_ShellExecuteExW, + .link = (void **) &next_ShellExecuteExW + }, +}; static bool did_init = false; @@ -87,7 +110,7 @@ static size_t process_nsyms_w = 0; static CRITICAL_SECTION createproc_lock; -HRESULT createprocess_push_hook_w(const wchar_t *name, const wchar_t *head, const wchar_t *tail, bool replace_all) { +HRESULT createprocess_push_hook_w(const wchar_t *name, const wchar_t *head, const wchar_t *tail, bool replace_all, bool replace_paths) { struct process_hook_sym_w *new_mem; struct process_hook_sym_w *new_proc; HRESULT hr; @@ -114,6 +137,7 @@ HRESULT createprocess_push_hook_w(const wchar_t *name, const wchar_t *head, cons new_proc->head = head; new_proc->tail = tail; new_proc->replace_all = replace_all; + new_proc->replace_paths = replace_paths; process_syms_w = new_mem; process_nsyms_w++; @@ -122,7 +146,7 @@ HRESULT createprocess_push_hook_w(const wchar_t *name, const wchar_t *head, cons return S_OK; } -HRESULT createprocess_push_hook_a(const char *name, const char *head, const char *tail, bool replace_all) { +HRESULT createprocess_push_hook_a(const char *name, const char *head, const char *tail, bool replace_all, bool replace_paths) { struct process_hook_sym_a *new_mem; struct process_hook_sym_a *new_proc; @@ -149,6 +173,7 @@ HRESULT createprocess_push_hook_a(const char *name, const char *head, const char new_proc->head = head; new_proc->tail = tail; new_proc->replace_all = replace_all; + new_proc->replace_paths = replace_paths; process_syms_a = new_mem; process_nsyms_a++; @@ -157,18 +182,31 @@ HRESULT createprocess_push_hook_a(const char *name, const char *head, const char return S_OK; } +void createprocess_hook_apply_hooks(HMODULE mod) { + hook_table_apply( + mod, + "kernel32.dll", + win32_hooks, + _countof(win32_hooks)); + hook_table_apply( + mod, + "shell32.dll", + shell32_hooks, + _countof(shell32_hooks)); + + proc_addr_table_push(mod, "kernel32.dll", win32_hooks, _countof(win32_hooks)); + proc_addr_table_push(mod, "shell32.dll", shell32_hooks, _countof(shell32_hooks)); + + InitializeCriticalSection(&createproc_lock); +} + void createprocess_hook_init() { if (did_init) { return; } did_init = true; - hook_table_apply( - NULL, - "kernel32.dll", - win32_hooks, - _countof(win32_hooks)); - InitializeCriticalSection(&createproc_lock); + createprocess_hook_apply_hooks(NULL); dprintf("CreateProcess: Init\n"); } @@ -255,4 +293,66 @@ BOOL my_CreateProcessW( lpStartupInfo, lpProcessInformation ); +} + +BOOL my_ShellExecuteExA(SHELLEXECUTEINFOA *pExecInfo) { + for (int i = 0; i < process_nsyms_a; i++) { + if (strncmp(process_syms_a[i].name, pExecInfo->lpFile, strlen(process_syms_a[i].name))) { + continue; + } + + dprintf("CreateProcess: Hooking child process %s %s\n", pExecInfo->lpFile, pExecInfo->lpParameters); + char new_args[MAX_PATH] = {0}; + strcat_s(new_args, MAX_PATH, process_syms_a[i].head); + + if (!process_syms_a[i].replace_all) { + strcat_s(new_args, MAX_PATH, pExecInfo->lpParameters); + } + if (process_syms_a[i].replace_paths) { + char result[MAX_PATH]; + if (path_transform_args_a(pExecInfo->lpParameters, ' ', result, MAX_PATH)) { + strcat_s(new_args, MAX_PATH, result); + } + } + + if (process_syms_a[i].tail != NULL) { + strcat_s(new_args, MAX_PATH, process_syms_a[i].tail); + } + + pExecInfo->lpParameters = new_args; + + dprintf("CreateProcess: Replaced ShellExecuteExA %s %s\n", pExecInfo->lpFile, new_args); + } + return next_ShellExecuteExA(pExecInfo); +} + +BOOL my_ShellExecuteExW(SHELLEXECUTEINFOW *pExecInfo) { + for (int i = 0; i < process_nsyms_w; i++) { + if (wcsncmp(process_syms_w[i].name, pExecInfo->lpFile, wcslen(process_syms_w[i].name))) { + continue; + } + + dprintf("CreateProcess: Hooking child process %ls %ls\n", pExecInfo->lpFile, pExecInfo->lpParameters); + wchar_t new_args[MAX_PATH] = {0}; + wcscat_s(new_args, MAX_PATH, process_syms_w[i].head); + + if (!process_syms_w[i].replace_all) { + wcscat_s(new_args, MAX_PATH, pExecInfo->lpParameters); + } + if (process_syms_w[i].replace_paths) { + wchar_t result[MAX_PATH]; + if (path_transform_args_w(pExecInfo->lpParameters, ' ', result, MAX_PATH)) { + wcscat_s(new_args, MAX_PATH, result); + } + } + + if (process_syms_w[i].tail != NULL) { + wcscat_s(new_args, MAX_PATH, process_syms_w[i].tail); + } + + pExecInfo->lpParameters = new_args; + + dprintf("CreateProcess: Replaced ShellExecuteExW %ls %ls\n", pExecInfo->lpFile, new_args); + } + return next_ShellExecuteExW(pExecInfo); } \ No newline at end of file diff --git a/common/hooklib/createprocess.h b/common/hooklib/createprocess.h index bf226d5..96e0e98 100644 --- a/common/hooklib/createprocess.h +++ b/common/hooklib/createprocess.h @@ -3,14 +3,16 @@ #include #include -HRESULT createprocess_push_hook_w(const wchar_t *name, const wchar_t *head, const wchar_t *tail, bool replace_all); -HRESULT createprocess_push_hook_a(const char *name, const char *head, const char *tail, bool replace_all); +HRESULT createprocess_push_hook_w(const wchar_t *name, const wchar_t *head, const wchar_t *tail, bool replace_all, bool replace_paths); +HRESULT createprocess_push_hook_a(const char *name, const char *head, const char *tail, bool replace_all, bool replace_paths); +void createprocess_hook_apply_hooks(HMODULE mod); struct process_hook_sym_w { const wchar_t *name; const wchar_t *head; const wchar_t *tail; bool replace_all; + bool replace_paths; }; struct process_hook_sym_a { @@ -18,4 +20,5 @@ struct process_hook_sym_a { const char *head; const char *tail; bool replace_all; + bool replace_paths; }; \ No newline at end of file diff --git a/common/hooklib/imageutil.c b/common/hooklib/imageutil.c new file mode 100644 index 0000000..0c38b69 --- /dev/null +++ b/common/hooklib/imageutil.c @@ -0,0 +1,212 @@ +#include +#include +#include + +#include "imageutil.h" + +// copy pasted from https://dev.s-ul.net/domeori/c310emu +#define BITMAPHEADERSIZE 0x36 + +int ConvertDataToBitmap( + DWORD dwBitCount, + DWORD dwWidth, DWORD dwHeight, + PBYTE pbInput, DWORD cbInput, + PBYTE pbOutput, DWORD cbOutput, + PDWORD pcbResult, + bool pFlip) { + if (!pbInput || !pbOutput || dwBitCount < 8) return -3; + + if (cbInput < (dwWidth * dwHeight * dwBitCount / 8)) return -3; + + PBYTE pBuffer = malloc(cbInput); + if (!pBuffer) return -2; + + BYTE dwColors = (BYTE)(dwBitCount / 8); + if (!dwColors) { + free(pBuffer); + return -1; + } + + UINT16 cbColors; + RGBQUAD pbColors[256]; + + switch (dwBitCount) { + case 1: + cbColors = 1; + break; + case 2: + cbColors = 4; + break; + case 4: + cbColors = 16; + break; + case 8: + cbColors = 256; + break; + default: + cbColors = 0; + break; + } + + if (cbColors) { + BYTE dwStep = (BYTE)(256 / cbColors); + + for (UINT16 i = 0; i < cbColors; ++i) { + pbColors[i].rgbRed = dwStep * i; + pbColors[i].rgbGreen = dwStep * i; + pbColors[i].rgbBlue = dwStep * i; + pbColors[i].rgbReserved = 0; + } + } + + DWORD dwTable = cbColors * sizeof(RGBQUAD); + DWORD dwOffset = BITMAPHEADERSIZE + dwTable; + + // calculate the padded row size, again + DWORD dwLineSize = (dwWidth * dwBitCount / 8 + 3) & ~3; + + BITMAPFILEHEADER bFile = {0}; + BITMAPINFOHEADER bInfo = {0}; + + bFile.bfType = 0x4D42; // MAGIC + bFile.bfSize = dwOffset + cbInput; + bFile.bfOffBits = dwOffset; + + bInfo.biSize = sizeof(BITMAPINFOHEADER); + bInfo.biWidth = dwWidth; + bInfo.biHeight = dwHeight; + bInfo.biPlanes = 1; + bInfo.biBitCount = (WORD)dwBitCount; + bInfo.biCompression = BI_RGB; + bInfo.biSizeImage = cbInput; + + if (cbOutput < bFile.bfSize) { + free(pBuffer); + return -1; + } + + // Flip the image (if necessary) and add padding to each row + if (pFlip) { + for (size_t i = 0; i < dwHeight; i++) { + for (size_t j = 0; j < dwWidth; j++) { + for (size_t k = 0; k < dwColors; k++) { + // Calculate the position in the padded buffer + // Make sure to also flip the colors from RGB to BRG + size_t x = (dwHeight - i - 1) * dwLineSize + (dwWidth - j - 1) * dwColors + (dwColors - k - 1); + size_t y = (dwHeight - i - 1) * dwWidth * dwColors + j * dwColors + k; + *(pBuffer + x) = *(pbInput + y); + } + } + } + } else { + for (size_t i = 0; i < dwHeight; i++) { + for (size_t j = 0; j < dwWidth; j++) { + for (size_t k = 0; k < dwColors; k++) { + // Calculate the position in the padded buffer + size_t x = i * dwLineSize + j * dwColors + (dwColors - k - 1); + size_t y = (dwHeight - i - 1) * dwWidth * dwColors + j * dwColors + k; + *(pBuffer + x) = *(pbInput + y); + } + } + } + } + + memcpy(pbOutput, &bFile, sizeof(BITMAPFILEHEADER)); + memcpy(pbOutput + sizeof(BITMAPFILEHEADER), &bInfo, sizeof(BITMAPINFOHEADER)); + if (cbColors) memcpy(pbOutput + BITMAPHEADERSIZE, pbColors, dwTable); + memcpy(pbOutput + dwOffset, pBuffer, cbInput); + + *pcbResult = bFile.bfSize; + + free(pBuffer); + return 0; +} + +int WriteDataToBitmapFile( + LPCWSTR lpFilePath, DWORD dwBitCount, + DWORD dwWidth, DWORD dwHeight, + PBYTE pbInput, DWORD cbInput, + PBYTE pbMetadata, DWORD cbMetadata, + bool pFlip) { + if (!lpFilePath || !pbInput) return -3; + + HANDLE hFile; + DWORD dwBytesWritten; + + hFile = CreateFileW( + lpFilePath, + GENERIC_WRITE, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + if (hFile == INVALID_HANDLE_VALUE) return -1; + + // calculate the padded row size and padded image size + DWORD dwLineSize = (dwWidth * dwBitCount / 8 + 3) & ~3; + DWORD dwImageSize = dwLineSize * dwHeight; + + DWORD cbResult; + DWORD cbBuffer = dwImageSize + 0x500; + PBYTE pbBuffer = calloc(cbBuffer, 1); + if (!pbBuffer) return -2; + + if (ConvertDataToBitmap(dwBitCount, dwWidth, dwHeight, pbInput, dwImageSize, pbBuffer, cbBuffer, &cbResult, pFlip) < 0) { + cbResult = -1; + goto WriteDataToBitmapFile_End; + } + + WriteFile(hFile, pbBuffer, cbResult, &dwBytesWritten, NULL); + + if (pbMetadata) + WriteFile(hFile, pbMetadata, cbMetadata, &dwBytesWritten, NULL); + + CloseHandle(hFile); + + cbResult = dwBytesWritten; + +WriteDataToBitmapFile_End: + free(pbBuffer); + return cbResult; +} + +int WriteArrayToFile(LPCSTR lpOutputFilePath, LPVOID lpDataTemp, DWORD nDataSize, BOOL isAppend) { +#ifdef NDEBUG + + return nDataSize; + +#else + + HANDLE hFile; + DWORD dwBytesWritten; + DWORD dwDesiredAccess; + DWORD dwCreationDisposition; + + if (isAppend) { + dwDesiredAccess = FILE_APPEND_DATA; + dwCreationDisposition = OPEN_ALWAYS; + } else { + dwDesiredAccess = GENERIC_WRITE; + dwCreationDisposition = CREATE_ALWAYS; + } + + hFile = CreateFileA( + lpOutputFilePath, + dwDesiredAccess, + FILE_SHARE_READ, + NULL, + dwCreationDisposition, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + if (hFile == INVALID_HANDLE_VALUE) { + return FALSE; + } + + WriteFile(hFile, lpDataTemp, nDataSize, &dwBytesWritten, NULL); + CloseHandle(hFile); + + return dwBytesWritten; + +#endif +} \ No newline at end of file diff --git a/common/hooklib/imageutil.h b/common/hooklib/imageutil.h new file mode 100644 index 0000000..0c29c45 --- /dev/null +++ b/common/hooklib/imageutil.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +int ConvertDataToBitmap( + DWORD dwBitCount, + DWORD dwWidth, DWORD dwHeight, + PBYTE pbInput, DWORD cbInput, + PBYTE pbOutput, DWORD cbOutput, + PDWORD pcbResult, + bool pFlip); + +int WriteDataToBitmapFile( + LPCWSTR lpFilePath, DWORD dwBitCount, + DWORD dwWidth, DWORD dwHeight, + PBYTE pbInput, DWORD cbInput, + PBYTE pbMetadata, DWORD cbMetadata, + bool pFlip); + +int WriteArrayToFile(LPCSTR lpOutputFilePath, LPVOID lpDataTemp, DWORD nDataSize, BOOL isAppend); \ No newline at end of file diff --git a/common/hooklib/meson.build b/common/hooklib/meson.build index b0ad6c2..de87676 100644 --- a/common/hooklib/meson.build +++ b/common/hooklib/meson.build @@ -21,6 +21,8 @@ hooklib_lib = static_library( 'dvd.h', 'fdshark.c', 'fdshark.h', + 'imageutil.c', + 'imageutil.h', 'path.c', 'path.h', 'reg.c', @@ -31,7 +33,13 @@ hooklib_lib = static_library( 'spike.h', 'touch.c', 'touch.h', - 'printer.c', - 'printer.h', + 'printer_chc.c', + 'printer_chc.h', + 'printer_cx.c', + 'printer_cx.h', + 'y3.c', + 'y3.h', + 'y3-dll.c', + 'y3-dll.h', ], ) diff --git a/common/hooklib/path.c b/common/hooklib/path.c index a6f2342..f480c63 100644 --- a/common/hooklib/path.c +++ b/common/hooklib/path.c @@ -16,7 +16,6 @@ /* Helpers */ static void path_hook_init(void); -static BOOL path_transform_a(char **out, const char *src); /* API hooks */ @@ -110,6 +109,16 @@ static BOOL WINAPI hook_MoveFileW( const wchar_t *lpExistingFileName, const wchar_t *lpNewFileName); +static BOOL WINAPI hook_CopyFileA( + const char *lpExistingFileName, + const char *lpNewFileName, + BOOL bFailIfExists); + +static BOOL WINAPI hook_CopyFileW( + const wchar_t *lpExistingFileName, + const wchar_t *lpNewFileName, + BOOL bFailIfExists); + static BOOL WINAPI hook_MoveFileExA( const char *lpExistingFileName, const char *lpNewFileName, @@ -120,19 +129,6 @@ static BOOL WINAPI hook_MoveFileExW( const wchar_t *lpNewFileName, uint32_t dwFlags); - -static BOOL WINAPI hook_CopyFileA( - const LPCSTR lpExistingFileName, - const LPCSTR lpNewFileName, - BOOL bFailIfExists -); - -static BOOL WINAPI hook_CopyFileW( - const LPCWSTR lpExistingFileName, - const LPCWSTR lpNewFileName, - BOOL bFailIfExists -); - static BOOL WINAPI hook_CopyFileExA( LPCSTR lpExistingFileName, LPCSTR lpNewFileName, @@ -296,6 +292,16 @@ static BOOL (WINAPI *next_MoveFileW)( const wchar_t *lpExistingFileName, const wchar_t *lpNewFileName); +static BOOL (WINAPI *next_CopyFileA)( + const char *lpExistingFileName, + const char *lpNewFileName, + BOOL bFailIfExists); + +static BOOL (WINAPI *next_CopyFileW)( + const wchar_t *lpExistingFileName, + const wchar_t *lpNewFileName, + BOOL bFailIfExists); + static BOOL (WINAPI *next_MoveFileExA)( const char *lpExistingFileName, const char *lpNewFileName, @@ -490,7 +496,7 @@ static const struct hook_symbol path_hook_syms[] = { .link = (void **) &next_CopyFileW, }, { .name = "CopyFileExA", - .patch = hook_CopyFileExW, + .patch = hook_CopyFileExA, .link = (void **) &next_CopyFileExA, }, { .name = "CopyFileExW", @@ -596,7 +602,7 @@ void path_hook_insert_hooks(HMODULE target) _countof(path_hook_syms)); } -static BOOL path_transform_a(char **out, const char *src) +BOOL path_transform_a(char **out, const char *src) { wchar_t *src_w; size_t src_c; @@ -1249,6 +1255,75 @@ static BOOL WINAPI hook_MoveFileW( return ok; } + +static BOOL WINAPI hook_CopyFileA( + const char *lpExistingFileName, + const char *lpNewFileName, + BOOL bFailIfExists) +{ + char *oldTrans; + char *newTrans; + BOOL ok; + + ok = path_transform_a(&oldTrans, lpExistingFileName); + + if (!ok) { + return FALSE; + } + + ok = path_transform_a(&newTrans, lpNewFileName); + + if (!ok) { + free(oldTrans); + + return FALSE; + } + + ok = next_CopyFileA( + oldTrans ? oldTrans : lpExistingFileName, + newTrans ? newTrans : lpNewFileName, + bFailIfExists); + + free(oldTrans); + free(newTrans); + + return ok; +} + +static BOOL WINAPI hook_CopyFileW( + const wchar_t *lpExistingFileName, + const wchar_t *lpNewFileName, + BOOL bFailIfExists) +{ + wchar_t *oldTrans; + wchar_t *newTrans; + BOOL ok; + + ok = path_transform_w(&oldTrans, lpExistingFileName); + + if (!ok) { + return FALSE; + } + + ok = path_transform_w(&newTrans, lpNewFileName); + + if (!ok) { + free(oldTrans); + + return FALSE; + } + + ok = next_CopyFileW( + oldTrans ? oldTrans : lpExistingFileName, + newTrans ? newTrans : lpNewFileName, + bFailIfExists); + + free(oldTrans); + free(newTrans); + + return ok; +} + static BOOL WINAPI hook_MoveFileExA( const char *lpExistingFileName, const char *lpNewFileName, @@ -1317,75 +1392,6 @@ static BOOL WINAPI hook_MoveFileExW( return ok; } -static BOOL WINAPI hook_CopyFileA( - const LPCSTR lpExistingFileName, - const LPCSTR lpNewFileName, - BOOL bFailIfExists -) -{ - char *oldTrans; - char *newTrans; - BOOL ok; - - ok = path_transform_a(&oldTrans, lpExistingFileName); - - if (!ok) { - return FALSE; - } - - ok = path_transform_a(&newTrans, lpNewFileName); - - if (!ok) { - free(oldTrans); - - return FALSE; - } - - ok = next_CopyFileA( - oldTrans ? oldTrans : lpExistingFileName, - newTrans ? newTrans : lpNewFileName, - bFailIfExists); - - free(oldTrans); - free(newTrans); - - return ok; -} - -static BOOL WINAPI hook_CopyFileW( - const LPCWSTR lpExistingFileName, - const LPCWSTR lpNewFileName, - BOOL bFailIfExists -) { - wchar_t *oldTrans; - wchar_t *newTrans; - BOOL ok; - - ok = path_transform_w(&oldTrans, lpExistingFileName); - - if (!ok) { - return FALSE; - } - - ok = path_transform_w(&newTrans, lpNewFileName); - - if (!ok) { - free(oldTrans); - - return FALSE; - } - - ok = next_CopyFileW( - oldTrans ? oldTrans : lpExistingFileName, - newTrans ? newTrans : lpNewFileName, - bFailIfExists); - - free(oldTrans); - free(newTrans); - - return ok; -} - static BOOL WINAPI hook_CopyFileExA( LPCSTR lpExistingFileName, LPCSTR lpNewFileName, @@ -1713,3 +1719,177 @@ static UINT WINAPI hook_GetDriveTypeW( return result; } + +char** str_split_a(char* a_str, const char a_delim) { + char** result = 0; + size_t count = 0; + char* tmp = a_str; + char* last_comma = 0; + char delim[2]; + delim[0] = a_delim; + delim[1] = 0; + + /* Count how many elements will be extracted. */ + while (*tmp) + { + if (a_delim == *tmp) + { + count++; + last_comma = tmp; + } + tmp++; + } + + /* Add space for trailing token. */ + count += last_comma < (a_str + strlen(a_str) - 1); + + /* Add space for terminating null string so caller + knows where the list of returned strings ends. */ + count++; + + result = malloc(sizeof(char*) * count); + + if (result) + { + size_t idx = 0; + char* token = strtok(a_str, delim); + + while (token) + { + assert(idx < count); + *(result + idx++) = strdup(token); + token = strtok(0, delim); + } + assert(idx == count - 1); + *(result + idx) = 0; + } + + return result; +} + +BOOL path_transform_args_a(const char* str, char delimiter, char* buf, size_t size) { + assert(str != NULL); + assert(buf != NULL); + + if (size <= 0) { + return FALSE; + } + + char* copy = strdup(str); + char** tokens = str_split_a(copy, delimiter); + char *trans; + BOOL ok; + BOOL failed = FALSE; + + strcpy(buf, ""); + + if (tokens) { + int j; + for (j = 0; *(tokens + j); j++) { + ok = path_transform_a(&trans, *(tokens + j)); + free(*(tokens + j)); + if (ok) { + strcat_s(buf, size, trans ? trans : *(tokens+j)); + if (*(tokens + j + 1)) { + strcat_s(buf, size, " "); + } + free(trans); + } else { + failed = true; + } + } + free(tokens); + } + + free(copy); + + return !failed; +} + +wchar_t** str_split_w(wchar_t* a_str, const wchar_t a_delim) { + wchar_t** result = 0; + size_t count = 0; + wchar_t* tmp = a_str; + wchar_t* last_comma = 0; + wchar_t delim[2]; + delim[0] = a_delim; + delim[1] = 0; + + /* Count how many elements will be extracted. */ + while (*tmp) + { + if (a_delim == *tmp) + { + count++; + last_comma = tmp; + } + tmp++; + } + + /* Add space for trailing token. */ + count += last_comma < (a_str + wcslen(a_str) - 1); + + /* Add space for terminating null string so caller + knows where the list of returned strings ends. */ + count++; + + result = malloc(sizeof(wchar_t*) * count); + + wchar_t* pt; + + if (result) + { + size_t idx = 0; + wchar_t* token = wcstok_s(a_str, delim, &pt); + + while (token) + { + assert(idx < count); + *(result + idx++) = wcsdup(token); + token = wcstok_s(0, delim, &pt); + } + assert(idx == count - 1); + *(result + idx) = 0; + } + + return result; +} + +BOOL path_transform_args_w(const wchar_t* str, wchar_t delimiter, wchar_t* buf, size_t size) { + assert(str != NULL); + assert(buf != NULL); + + if (size <= 0) { + return FALSE; + } + + wchar_t* copy = wcsdup(str); + wchar_t** tokens = str_split_w(copy, delimiter); + wchar_t *trans; + BOOL ok; + BOOL failed = FALSE; + + wcscpy(buf, L""); + + if (tokens) { + int j; + for (j = 0; *(tokens + j); j++) { + ok = path_transform_w(&trans, *(tokens + j)); + if (ok) { + wcscat_s(buf, size, trans ? trans : *(tokens+j)); + if (*(tokens + j + 1)) { + wcscat_s(buf, size, L" "); + } + free(trans); + } else { + failed = true; + } + free(*(tokens + j)); + } + free(tokens); + } + + free(copy); + + return !failed; +} \ No newline at end of file diff --git a/common/hooklib/path.h b/common/hooklib/path.h index eb55dd7..aca9356 100644 --- a/common/hooklib/path.h +++ b/common/hooklib/path.h @@ -13,7 +13,10 @@ typedef HRESULT (*path_hook_t)( HRESULT path_hook_push(path_hook_t hook); void path_hook_insert_hooks(HMODULE target); int path_compare_w(const wchar_t *string1, const wchar_t *string2, size_t count); +BOOL path_transform_a(char **out, const char *src); BOOL path_transform_w(wchar_t **out, const wchar_t *src); +BOOL path_transform_args_a(const char* str, char delimiter, char* buf, size_t size); +BOOL path_transform_args_w(const wchar_t* str, wchar_t delimiter, wchar_t* buf, size_t size); static inline bool path_is_separator_w(wchar_t c) { diff --git a/common/hooklib/printer.c b/common/hooklib/printer_chc.c similarity index 88% rename from common/hooklib/printer.c rename to common/hooklib/printer_chc.c index dbd56f9..0100f2f 100644 --- a/common/hooklib/printer.c +++ b/common/hooklib/printer_chc.c @@ -9,7 +9,9 @@ chc (emihiok) */ -#include "hooklib/printer.h" +// ReSharper disable CppParameterNeverUsed +// ReSharper disable CppDFAConstantFunctionResult +#include "hooklib/printer_chc.h" #include #include @@ -90,6 +92,7 @@ int WINAPI chcusb_listupPrinterSN(uint64_t *rSerialArray); int WINAPI chcusb_selectPrinter(uint8_t printerId, uint16_t *rResult); int WINAPI chcusb_selectPrinterSN(uint64_t printerSN, uint16_t *rResult); int WINAPI chcusb_getPrinterInfo(uint16_t tagNumber, uint8_t *rBuffer, uint32_t *rLen); +int WINAPI chcusb_getPrinterInfo_300(uint16_t tagNumber, uint8_t *rBuffer, uint32_t *rLen); int WINAPI chcusb_imageformat(uint16_t format, uint16_t ncomp, uint16_t depth, uint16_t width, uint16_t height, uint8_t * image, uint16_t* rResult); int WINAPI chcusb_imageformat_330( uint16_t format, @@ -98,7 +101,7 @@ int WINAPI chcusb_imageformat_330( uint16_t width, uint16_t height, uint16_t *rResult); -int __fastcall chcusb_setmtf(int32_t *mtf); +int WINAPI chcusb_setmtf(int32_t *mtf); int WINAPI chcusb_makeGamma(uint16_t k, uint8_t *intoneR, uint8_t *intoneG, uint8_t *intoneB); int WINAPI chcusb_setIcctable( LPCSTR icc1, @@ -147,6 +150,7 @@ int WINAPI chcusb_getEEPROM(uint8_t index, uint8_t *rData, uint16_t *rResult); int WINAPI chcusb_setParameter(uint8_t a1, uint32_t a2, uint16_t *rResult); int WINAPI chcusb_getParameter(uint8_t a1, uint8_t *a2, uint16_t *rResult); int WINAPI chcusb_universal_command(int32_t a1, uint8_t a2, int32_t a3, uint8_t *a4, uint16_t *rResult); +int WINAPI chcusb_writeIred(uint8_t* a1, uint8_t* a2, uint16_t* rResult); /* PrintDLL API hooks */ @@ -410,217 +414,6 @@ static const struct hook_symbol C3XXFWDLusb_hooks[] = { }, }; -/* C300usb hook tbl */ - -static const struct hook_symbol C300usb_hooks[] = { - { - .name = "chcusb_MakeThread", - .ordinal = 0x0001, - .patch = chcusb_MakeThread, - .link = NULL - }, { - .name = "chcusb_open", - .ordinal = 0x0002, - .patch = chcusb_open, - .link = NULL - }, { - .name = "chcusb_close", - .ordinal = 0x0003, - .patch = chcusb_close, - .link = NULL - }, { - .name = "chcusb_ReleaseThread", - .ordinal = 0x0004, - .patch = chcusb_ReleaseThread, - .link = NULL - }, { - .name = "chcusb_listupPrinter", - .ordinal = 0x0005, - .patch = chcusb_listupPrinter, - .link = NULL - }, { - .name = "chcusb_listupPrinterSN", - .ordinal = 0x0006, - .patch = chcusb_listupPrinterSN, - .link = NULL - }, { - .name = "chcusb_selectPrinter", - .ordinal = 0x0007, - .patch = chcusb_selectPrinter, - .link = NULL - }, { - .name = "chcusb_selectPrinterSN", - .ordinal = 0x0008, - .patch = chcusb_selectPrinterSN, - .link = NULL - }, { - .name = "chcusb_getPrinterInfo", - .ordinal = 0x0009, - .patch = chcusb_getPrinterInfo, - .link = NULL - }, { - .name = "chcusb_imageformat", - .ordinal = 0x000a, - .patch = chcusb_imageformat, - .link = NULL - }, { - .name = "chcusb_setmtf", - .ordinal = 0x000b, - .patch = chcusb_setmtf, - .link = NULL - }, { - .name = "chcusb_makeGamma", - .ordinal = 0x000c, - .patch = chcusb_makeGamma, - .link = NULL - }, { - .name = "chcusb_setIcctable", - .ordinal = 0x000d, - .patch = chcusb_setIcctable, - .link = NULL - }, { - .name = "chcusb_copies", - .ordinal = 0x000e, - .patch = chcusb_copies, - .link = NULL - }, { - .name = "chcusb_status", - .ordinal = 0x000f, - .patch = chcusb_status, - .link = NULL - }, { - .name = "chcusb_statusAll", - .ordinal = 0x0010, - .patch = chcusb_statusAll, - .link = NULL - }, { - .name = "chcusb_startpage", - .ordinal = 0x0011, - .patch = chcusb_startpage_300, - .link = NULL - }, { - .name = "chcusb_endpage", - .ordinal = 0x0012, - .patch = chcusb_endpage, - .link = NULL - }, { - .name = "chcusb_write", - .ordinal = 0x0013, - .patch = chcusb_write, - .link = NULL - }, { - .name = "chcusb_writeLaminate", - .ordinal = 0x0014, - .patch = chcusb_writeLaminate, - .link = NULL - }, { - .name = "chcusb_setPrinterInfo", - .ordinal = 0x0015, - .patch = chcusb_setPrinterInfo, - .link = NULL - }, { - .name = "chcusb_getGamma", - .ordinal = 0x0016, - .patch = chcusb_getGamma, - .link = NULL - }, { - .name = "chcusb_getMtf", - .ordinal = 0x0017, - .patch = chcusb_getMtf, - .link = NULL - }, { - .name = "chcusb_cancelCopies", - .ordinal = 0x0018, - .patch = chcusb_cancelCopies, - .link = NULL - }, { - .name = "chcusb_setPrinterToneCurve", - .ordinal = 0x0019, - .patch = chcusb_setPrinterToneCurve, - .link = NULL - }, { - .name = "chcusb_getPrinterToneCurve", - .ordinal = 0x001a, - .patch = chcusb_getPrinterToneCurve, - .link = NULL - }, { - .name = "chcusb_blinkLED", - .ordinal = 0x001b, - .patch = chcusb_blinkLED, - .link = NULL - }, { - .name = "chcusb_resetPrinter", - .ordinal = 0x001c, - .patch = chcusb_resetPrinter, - .link = NULL - }, { - .name = "chcusb_AttachThreadCount", - .ordinal = 0x001d, - .patch = chcusb_AttachThreadCount, - .link = NULL - }, { - .name = "chcusb_getPrintIDStatus", - .ordinal = 0x001e, - .patch = chcusb_getPrintIDStatus, - .link = NULL - }, { - .name = "chcusb_setPrintStandby", - .ordinal = 0x001f, - .patch = chcusb_setPrintStandby_300, - .link = NULL - }, { - .name = "chcusb_testCardFeed", - .ordinal = 0x0020, - .patch = chcusb_testCardFeed, - .link = NULL - }, { - .name = "chcusb_setParameter", - .ordinal = 0x0021, - .patch = chcusb_setParameter, - .link = NULL - }, { - .name = "chcusb_getParameter", - .ordinal = 0x0022, - .patch = chcusb_getParameter, - .link = NULL - }, { - .name = "chcusb_getErrorStatus", - .ordinal = 0x0023, - .patch = chcusb_getErrorStatus, - .link = NULL - }, { - .name = "chcusb_setCutList", - .ordinal = 0x0028, - .patch = chcusb_setCutList, - .link = NULL - }, { - .name = "chcusb_setLaminatePattern", - .ordinal = 0x0029, - .patch = chcusb_setLaminatePattern, - .link = NULL - }, { - .name = "chcusb_color_adjustment", - .ordinal = 0x002a, - .patch = chcusb_color_adjustment, - .link = NULL - }, { - .name = "chcusb_color_adjustmentEx", - .ordinal = 0x002b, - .patch = chcusb_color_adjustmentEx, - .link = NULL - }, { - .name = "chcusb_getEEPROM", - .ordinal = 0x003a, - .patch = chcusb_getEEPROM, - .link = NULL - }, { - .name = "chcusb_universal_command", - .ordinal = 0x0049, - .patch = chcusb_universal_command, - .link = NULL - }, -}; - /* C310A-Busb/C320Ausb/C330Ausb hook tbl. The ordinals are required, as some games, for example Sekito, will import this library by ordinal and not by name. */ @@ -666,11 +459,6 @@ static const struct hook_symbol C3XXusb_hooks[] = { .ordinal = 0x0008, .patch = chcusb_selectPrinterSN, .link = NULL - }, { - .name = "chcusb_getPrinterInfo", - .ordinal = 0x0009, - .patch = chcusb_getPrinterInfo, - .link = NULL }, { .name = "chcusb_imageformat", .ordinal = 0x000a, @@ -706,11 +494,6 @@ static const struct hook_symbol C3XXusb_hooks[] = { .ordinal = 0x0010, .patch = chcusb_statusAll, .link = NULL - }, { - .name = "chcusb_startpage", - .ordinal = 0x0011, - .patch = chcusb_startpage, - .link = NULL }, { .name = "chcusb_endpage", .ordinal = 0x0012, @@ -781,11 +564,6 @@ static const struct hook_symbol C3XXusb_hooks[] = { .ordinal = 0x001f, .patch = chcusb_getPrintIDStatus, .link = NULL - }, { - .name = "chcusb_setPrintStandby", - .ordinal = 0x0020, - .patch = chcusb_setPrintStandby, - .link = NULL }, { .name = "chcusb_testCardFeed", .ordinal = 0x0021, @@ -841,6 +619,11 @@ static const struct hook_symbol C3XXusb_hooks[] = { .ordinal = 0x002b, .patch = chcusb_color_adjustmentEx, .link = NULL + }, { + .name = "chcusb_writeIred", + .ordinal = 0x0032, + .patch = chcusb_writeIred, + .link = NULL }, { .name = "chcusb_getEEPROM", .ordinal = 0x003a, @@ -864,6 +647,79 @@ static const struct hook_symbol C3XXusb_hooks[] = { }, }; +/* C300A-Busb specific hook tbl. */ + +static const struct hook_symbol C300usb_hooks[] = { + { + .name = "chcusb_getPrinterInfo", + .ordinal = 0x0009, + .patch = chcusb_getPrinterInfo_300, + .link = NULL + }, { + .name = "chcusb_startpage", + .ordinal = 0x0011, + .patch = chcusb_startpage_300, + .link = NULL + }, { + .name = "chcusb_setPrintStandby", + .ordinal = 0x0020, + .patch = chcusb_setPrintStandby_300, + .link = NULL + } +}; + +/* C310A-Busb specific hook tbl. */ + +static const struct hook_symbol C310usb_hooks[] = { + { + .name = "chcusb_getPrinterInfo", + .ordinal = 0x0009, + .patch = chcusb_getPrinterInfo, + .link = NULL + }, { + .name = "chcusb_imageformat", + .ordinal = 0x000a, + .patch = chcusb_imageformat, + .link = NULL + }, { + .name = "chcusb_startpage", + .ordinal = 0x0011, + .patch = chcusb_startpage, + .link = NULL + }, { + .name = "chcusb_setPrintStandby", + .ordinal = 0x0020, + .patch = chcusb_setPrintStandby, + .link = NULL + } +}; + +/* C330Ausb specific hook tbl. */ + +static const struct hook_symbol C330usb_hooks[] = { + { + .name = "chcusb_getPrinterInfo", + .ordinal = 0x0009, + .patch = chcusb_getPrinterInfo, + .link = NULL + }, { + .name = "chcusb_imageformat", + .ordinal = 0x000a, + .patch = chcusb_imageformat_330, + .link = NULL + }, { + .name = "chcusb_startpage", + .ordinal = 0x0011, + .patch = chcusb_startpage, + .link = NULL + }, { + .name = "chcusb_setPrintStandby", + .ordinal = 0x0020, + .patch = chcusb_setPrintStandby, + .link = NULL + } +}; + /* PrintDLL hook tbl */ static struct hook_symbol printdll_hooks[] = { @@ -1150,9 +1006,9 @@ static struct hook_symbol printdll_hooks[] = { }, }; -static struct printer_config printer_config; +static struct printer_chc_config printer_config; -void printer_hook_init(const struct printer_config *cfg, int rfid_port_no, HINSTANCE self) { +void printer_chc_hook_init(const struct printer_chc_config *cfg, int rfid_port_no, HINSTANCE self) { HANDLE fwFile = NULL; DWORD bytesRead = 0; @@ -1170,7 +1026,7 @@ void printer_hook_init(const struct printer_config *cfg, int rfid_port_no, HINST rotate180 = cfg->rotate_180; memcpy(&printer_config, cfg, sizeof(*cfg)); - printer_hook_insert_hooks(NULL); + printer_chc_hook_insert_hooks(NULL); /* if (self != NULL) { @@ -1229,7 +1085,7 @@ void printer_hook_init(const struct printer_config *cfg, int rfid_port_no, HINST dprintf("Printer: hook enabled.\n"); } -void printer_hook_insert_hooks(HMODULE target) { +void printer_chc_hook_insert_hooks(HMODULE target) { hook_table_apply(target, "C310Ausb.dll", C3XXusb_hooks, _countof(C3XXusb_hooks)); hook_table_apply(target, "C310Busb.dll", C3XXusb_hooks, _countof(C3XXusb_hooks)); hook_table_apply(target, "C310FWDLusb.dll", C3XXFWDLusb_hooks, _countof(C3XXFWDLusb_hooks)); @@ -1239,9 +1095,18 @@ void printer_hook_insert_hooks(HMODULE target) { hook_table_apply(target, "C330Ausb.dll", C3XXusb_hooks, _countof(C3XXusb_hooks)); hook_table_apply(target, "C330AFWDLusb.dll", C3XXFWDLusb_hooks, _countof(C3XXFWDLusb_hooks)); + /* specific C300Ausb hooks */ + hook_table_apply(target, "C300usb.dll", C300usb_hooks, _countof(C300usb_hooks)); + proc_addr_table_push(target, "C300usb.dll", C300usb_hooks, _countof(C300usb_hooks)); + + /* specific C310Ausb/C320usb/C330Ausb hooks */ + hook_table_apply(target, "C310Ausb.dll", C330usb_hooks, _countof(C330usb_hooks)); + hook_table_apply(target, "C320Ausb.dll", C330usb_hooks, _countof(C330usb_hooks)); + hook_table_apply(target, "C330Ausb.dll", C330usb_hooks, _countof(C330usb_hooks)); + /* Unity workaround */ proc_addr_table_push(target, "PrintDLL.dll", printdll_hooks, _countof(printdll_hooks)); - proc_addr_table_push(target, "C300usb.dll", C300usb_hooks, _countof(C300usb_hooks)); + proc_addr_table_push(target, "C300usb.dll", C3XXusb_hooks, _countof(C3XXusb_hooks)); proc_addr_table_push(target, "C300FWDLusb.dll", C3XXFWDLusb_hooks, _countof(C3XXFWDLusb_hooks)); } @@ -2160,6 +2025,11 @@ int WINAPI chcusb_getPrinterInfo(uint16_t tagNumber, uint8_t *rBuffer, uint32_t if (rBuffer) memset(rBuffer, 0, *rLen); break; + case 2: // unknown + if (*rLen != 0x17) *rLen = 0x17; + if (rBuffer) memset(rBuffer, 0, *rLen); + break; + case 3: // getFirmwareVersion if (*rLen != 0x99) *rLen = 0x99; if (rBuffer) { @@ -2307,6 +2177,58 @@ int WINAPI chcusb_getPrinterInfo(uint16_t tagNumber, uint8_t *rBuffer, uint32_t return 1; } +int WINAPI chcusb_getPrinterInfo_300(uint16_t tagNumber, uint8_t *rBuffer, uint32_t *rLen) { + // dprintf("Printer: C3XXusb: %s(%d)\n", __func__, tagNumber); + + switch (tagNumber) { + case 3: // getFirmwareVersion + if (*rLen != 0x99) *rLen = 0x99; + if (rBuffer) { + memset(rBuffer, 0, *rLen); + // C300 has 4 firmwares + rBuffer[0] = 4; // firmware count + + // bootFirmware + int i = 1; + memcpy(rBuffer + i, mainFirmware, sizeof(mainFirmware)); + // mainFirmware + i += 0x26; + memcpy(rBuffer + i, mainFirmware, sizeof(mainFirmware)); + // printParameterTable + i += 0x26; + memcpy(rBuffer + i, paramFirmware, sizeof(paramFirmware)); + // dspFirmware (C300 only) + i += 0x26; + memcpy(rBuffer + i, dspFirmware, sizeof(dspFirmware)); + } + return 1; + + case 4: // getPrintCountInfo (C300 only) + if (!rBuffer) { + *rLen = 0x1C; + return 1; + } + int32_t bInfoC300[10] = {0}; + bInfoC300[0] = 22; // printCounter0 + bInfoC300[1] = 23; // printCounter1 + bInfoC300[2] = 33; // feedRollerCount + bInfoC300[3] = 55; // cutterCount + bInfoC300[4] = 88; // headCount + bInfoC300[5] = 999; // ribbonRemain + bInfoC300[6] = 0; // dummy + if (*rLen <= 0x1Cu) { + memcpy(rBuffer, bInfoC300, *rLen); + } else { + bInfoC300[7] = 0; // TODO + if (*rLen > 0x20u) *rLen = 0x20; + memcpy(rBuffer, bInfoC300, *rLen); + } + return 1; + } + + return chcusb_getPrinterInfo(tagNumber, rBuffer, rLen); +} + int WINAPI chcusb_imageformat( uint16_t format, uint16_t ncomp, @@ -2334,7 +2256,7 @@ int WINAPI chcusb_imageformat_330( return 1; } -int __fastcall chcusb_setmtf(int32_t *mtf) { +int WINAPI chcusb_setmtf(int32_t *mtf) { dprintf("Printer: C3XXusb: %s\n", __func__); memcpy(MTF, mtf, sizeof(MTF)); @@ -3147,208 +3069,13 @@ int CHCUSB_writeLaminate(const void *handle, uint8_t *data, uint32_t offset, uin return chcusb_writeLaminate(data, writeSize, rResult); } -// copy pasted from https://dev.s-ul.net/domeori/c310emu -#define BITMAPHEADERSIZE 0x36 - -DWORD ConvertDataToBitmap( - DWORD dwBitCount, - DWORD dwWidth, DWORD dwHeight, - PBYTE pbInput, DWORD cbInput, - PBYTE pbOutput, DWORD cbOutput, - PDWORD pcbResult, - bool pFlip) { - if (!pbInput || !pbOutput || dwBitCount < 8) return -3; - - if (cbInput < (dwWidth * dwHeight * dwBitCount / 8)) return -3; - - PBYTE pBuffer = (PBYTE)malloc(cbInput); - if (!pBuffer) return -2; - - BYTE dwColors = (BYTE)(dwBitCount / 8); - if (!dwColors) return -1; - - UINT16 cbColors; - RGBQUAD pbColors[256]; - - switch (dwBitCount) { - case 1: - cbColors = 1; - break; - case 2: - cbColors = 4; - break; - case 4: - cbColors = 16; - break; - case 8: - cbColors = 256; - break; - default: - cbColors = 0; - break; - } - - if (cbColors) { - BYTE dwStep = (BYTE)(256 / cbColors); - - for (UINT16 i = 0; i < cbColors; ++i) { - pbColors[i].rgbRed = dwStep * i; - pbColors[i].rgbGreen = dwStep * i; - pbColors[i].rgbBlue = dwStep * i; - pbColors[i].rgbReserved = 0; - } - } - - DWORD dwTable = cbColors * sizeof(RGBQUAD); - DWORD dwOffset = BITMAPHEADERSIZE + dwTable; - - // calculate the padded row size, again - DWORD dwLineSize = (dwWidth * dwBitCount / 8 + 3) & ~3; - - BITMAPFILEHEADER bFile = {0}; - BITMAPINFOHEADER bInfo = {0}; - - bFile.bfType = 0x4D42; // MAGIC - bFile.bfSize = dwOffset + cbInput; - bFile.bfOffBits = dwOffset; - - bInfo.biSize = sizeof(BITMAPINFOHEADER); - bInfo.biWidth = dwWidth; - bInfo.biHeight = dwHeight; - bInfo.biPlanes = 1; - bInfo.biBitCount = (WORD)dwBitCount; - bInfo.biCompression = BI_RGB; - bInfo.biSizeImage = cbInput; - - if (cbOutput < bFile.bfSize) return -1; - - // Flip the image (if necessary) and add padding to each row - if (pFlip) { - for (size_t i = 0; i < dwHeight; i++) { - for (size_t j = 0; j < dwWidth; j++) { - for (size_t k = 0; k < dwColors; k++) { - // Calculate the position in the padded buffer - // Make sure to also flip the colors from RGB to BRG - size_t x = (dwHeight - i - 1) * dwLineSize + (dwWidth - j - 1) * dwColors + (dwColors - k - 1); - size_t y = (dwHeight - i - 1) * dwWidth * dwColors + j * dwColors + k; - *(pBuffer + x) = *(pbInput + y); - } - } - } - } else { - for (size_t i = 0; i < dwHeight; i++) { - for (size_t j = 0; j < dwWidth; j++) { - for (size_t k = 0; k < dwColors; k++) { - // Calculate the position in the padded buffer - size_t x = i * dwLineSize + j * dwColors + (dwColors - k - 1); - size_t y = (dwHeight - i - 1) * dwWidth * dwColors + j * dwColors + k; - *(pBuffer + x) = *(pbInput + y); - } - } - } - } - - memcpy(pbOutput, &bFile, sizeof(BITMAPFILEHEADER)); - memcpy(pbOutput + sizeof(BITMAPFILEHEADER), &bInfo, sizeof(BITMAPINFOHEADER)); - if (cbColors) memcpy(pbOutput + BITMAPHEADERSIZE, pbColors, dwTable); - memcpy(pbOutput + dwOffset, pBuffer, cbInput); - - *pcbResult = bFile.bfSize; - - free(pBuffer); - return 0; -} - -DWORD WriteDataToBitmapFile( - LPCWSTR lpFilePath, DWORD dwBitCount, - DWORD dwWidth, DWORD dwHeight, - PBYTE pbInput, DWORD cbInput, - PBYTE pbMetadata, DWORD cbMetadata, - bool pFlip) { - if (!lpFilePath || !pbInput) return -3; - - HANDLE hFile; - DWORD dwBytesWritten; - - hFile = CreateFileW( - lpFilePath, - GENERIC_WRITE, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - if (hFile == INVALID_HANDLE_VALUE) return -1; - - // calculate the padded row size and padded image size - DWORD dwLineSize = (dwWidth * dwBitCount / 8 + 3) & ~3; - DWORD dwImageSize = dwLineSize * dwHeight; - - DWORD cbResult; - DWORD cbBuffer = dwImageSize + 0x500; - PBYTE pbBuffer = (PBYTE)calloc(cbBuffer, 1); - if (!pbBuffer) return -2; - - if (ConvertDataToBitmap(dwBitCount, dwWidth, dwHeight, pbInput, dwImageSize, pbBuffer, cbBuffer, &cbResult, pFlip) < 0) { - cbResult = -1; - goto WriteDataToBitmapFile_End; - } - - WriteFile(hFile, pbBuffer, cbResult, &dwBytesWritten, NULL); - - if (pbMetadata) - WriteFile(hFile, pbMetadata, cbMetadata, &dwBytesWritten, NULL); - - CloseHandle(hFile); - - cbResult = dwBytesWritten; - -WriteDataToBitmapFile_End: - free(pbBuffer); - return cbResult; -} - -DWORD WriteArrayToFile(LPCSTR lpOutputFilePath, LPVOID lpDataTemp, DWORD nDataSize, BOOL isAppend) { -#ifdef NDEBUG - - return nDataSize; - -#else - - HANDLE hFile; - DWORD dwBytesWritten; - DWORD dwDesiredAccess; - DWORD dwCreationDisposition; - - if (isAppend) { - dwDesiredAccess = FILE_APPEND_DATA; - dwCreationDisposition = OPEN_ALWAYS; - } else { - dwDesiredAccess = GENERIC_WRITE; - dwCreationDisposition = CREATE_ALWAYS; - } - - hFile = CreateFileA( - lpOutputFilePath, - dwDesiredAccess, - FILE_SHARE_READ, - NULL, - dwCreationDisposition, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - if (hFile == INVALID_HANDLE_VALUE) { - return FALSE; - } - - WriteFile(hFile, lpDataTemp, nDataSize, &dwBytesWritten, NULL); - CloseHandle(hFile); - - return dwBytesWritten; - -#endif -} - void printer_set_dimensions(int width, int height){ WIDTH = width; HEIGHT = height; } + +int WINAPI chcusb_writeIred(uint8_t* a1, uint8_t* a2, uint16_t* rResult) { + dprintf("Printer: C3XXusb: %s\n", __func__); + *rResult = 0; + return 1; +} diff --git a/common/hooklib/printer.h b/common/hooklib/printer_chc.h similarity index 74% rename from common/hooklib/printer.h rename to common/hooklib/printer_chc.h index 3e451d1..cb6886b 100644 --- a/common/hooklib/printer.h +++ b/common/hooklib/printer_chc.h @@ -4,7 +4,7 @@ #include #include -struct printer_config { +struct printer_chc_config { bool enable; bool rotate_180; char serial_no[8]; @@ -15,8 +15,8 @@ struct printer_config { uint32_t wait_time; }; -void printer_hook_init(const struct printer_config *cfg, int rfid_port_no, HINSTANCE self); -void printer_hook_insert_hooks(HMODULE target); +void printer_chc_hook_init(const struct printer_chc_config *cfg, int rfid_port_no, HINSTANCE self); +void printer_chc_hook_insert_hooks(HMODULE target); void printer_set_dimensions(int width, int height); int WINAPI fwdlusb_updateFirmware_main(uint8_t update, LPCSTR filename, uint16_t *rResult); diff --git a/common/hooklib/printer_cx.c b/common/hooklib/printer_cx.c new file mode 100644 index 0000000..b2f5e3e --- /dev/null +++ b/common/hooklib/printer_cx.c @@ -0,0 +1,906 @@ +// ReSharper disable CppParameterNeverUsed +// ReSharper disable CppParameterMayBeConstPtrOrRef +#include "printer_cx.h" + +#include +#include +#include +#include +#include +#include + +#include "imageutil.h" +#include "hook/procaddr.h" +#include "hook/table.h" +#include "util/dprintf.h" + +#pragma region prototypes +static int WINAPI hook_CXCMD_Retransfer(); + +static bool WINAPI hook_CXCMD_CheckIfConnected(int* pSlotId, int* pId); + +static int WINAPI hook_CXCMD_xImageOut(); + +static int WINAPI hook_CXCMD_MoveCard(int slotId, int id, int dest, int flip, int filmInit, int immed); + +static int WINAPI hook_CXCMD_xWriteMagData(); + +static int WINAPI hook_CXCMD_SecurityPrint(int slotId, int id, int color, int bufferIndex, int immed); + +static int WINAPI hook_CXCMD_ScanPrinterNext(); + +static int WINAPI hook_CXCMD_Print(int slotId, int id, int color, int bufferIndex, int immed); + +static int WINAPI hook_CXCMD_RezeroUnit(int slotId, int id, int action); + +static int WINAPI hook_CXCMD_WriteMagData(); + +static int WINAPI hook_CXCMD_LogSense(int iSlot, int iID, int iPage, uint8_t* pbyBuffer); + +static int WINAPI hook_CXCMD_StandardInquiry(int iSlot, int iID, uint8_t* pbyBuffer); + +static int WINAPI hook_CXCMD_ModeSense(int iSlot, int iID, int iPC, int iPage, uint8_t* pbyBuffer); + +static int WINAPI hook_CXCMD_UpdateFirmware(int iSlot, int iID, char* pFile, int iDataID); + +static int WINAPI hook_CXCMD_ModeSelect(int iSlot, int iID, int iSp, int iPage, uint8_t* pbyData); + +static int WINAPI hook_CXCMD_GetPrintingStatus(); + +static int WINAPI hook_CXCMD_SendDiagnostic(int iSlot, int iID, int iTestMode, int iTestPatten, int iTestCount); + +static int WINAPI hook_CXCMD_RetransferAndTurn(int slotId, int id, int immed); + +static int WINAPI hook_CXCMD_LogSelect(int iSlot, int iID, int iMod); + +static int WINAPI hook_CXCMD_ReadPosition(int slotId, int id, uint8_t* buffer); + +static int WINAPI hook_CXCMD_SecurityLock(); + +static int WINAPI hook_CXCMD_SetPrintingStatus(); + +static int WINAPI hook_CXCMD_xReadISOMagData(); + +static int WINAPI hook_CXCMD_WriteISO3TrackMagData(); + +static int WINAPI hook_CXCMD_PasswordSet(); + +static int WINAPI hook_CXCMD_GetPrinterStatus(); + +static int WINAPI hook_CXCMD_WriteProjectCode(); + +static int WINAPI hook_CXCMD_LoadCard(int slotId, int id, int dest, int flip, int filmInit, int immed); + +static int WINAPI hook_CXCMD_ReadMagData(); + +static int WINAPI hook_CXCMD_ScanPrinter(int* pSlotId, int* pId); + +static int WINAPI hook_CXCMD_xWriteISOMagData(); + +static int WINAPI hook_CXCMD_ICControl(); + +static int WINAPI hook_CXCMD_ImageOut(int slotId, int id, uint8_t* plane, int length, int color, int bufferIndex); + +static int WINAPI hook_CXCMD_ReadBuffer(int iSlot, int iID, int iMode, int iBufferID, uint8_t* pbyData, int iOffset, + int iLength); + +static int WINAPI hook_CXCMD_xReadMagData(); + +static int WINAPI hook_CXCMD_WriteBuffer(int iSlot, int iID, int iMode, int iBufferID, uint8_t* pbyData, int iOffset, + int iLength); + +static int WINAPI hook_CXCMD_DefineLUT(int slotId, int id, int color, int length, uint8_t* buffer); + +static int WINAPI hook_CXCMD_ReadISO3TrackMagData(); + +static int WINAPI hook_CXCMD_TestUnitReady(int slotId, int id); + +static int WINAPI hook_CXCMD_RetransferAndEject(int slotId, int id, int immed); + +static bool WINAPI hook_Lut24_Exchange(const wchar_t* pFile, uint8_t* y, uint8_t* m, uint8_t* c, int sizeY, int sizeM, + int sizeC); + +static bool WINAPI hook_Wdata_create(uint8_t* pbyRdata, uint8_t* pbyGdata, uint8_t* pbyBdata, int iWidth, + int iHeight, bool bPortrait, int iAlgorithim, uint8_t* pbyWdata); +#pragma endregion + +#pragma region hooktables +static const struct hook_symbol hook_pcp_syms[] = { + { + .name = "CXCMD_Retransfer", + .patch = hook_CXCMD_Retransfer, + .ordinal = 19, + }, + { + .name = "CXCMD_CheckIfConnected", + .patch = hook_CXCMD_CheckIfConnected, + .ordinal = 1, + }, + { + .name = "CXCMD_xImageOut", + .patch = hook_CXCMD_xImageOut, + .ordinal = 36, + }, + { + .name = "CXCMD_MoveCard", + .patch = hook_CXCMD_MoveCard, + .ordinal = 12, + }, + { + .name = "CXCMD_xWriteMagData", + .patch = hook_CXCMD_xWriteMagData, + .ordinal = 40, + }, + { + .name = "CXCMD_SecurityPrint", + .patch = hook_CXCMD_SecurityPrint, + .ordinal = 26, + }, + { + .name = "CXCMD_ScanPrinterNext", + .patch = hook_CXCMD_ScanPrinterNext, + .ordinal = 24, + }, + { + .name = "CXCMD_Print", + .patch = hook_CXCMD_Print, + .ordinal = 14, + }, + { + .name = "CXCMD_RezeroUnit", + .patch = hook_CXCMD_RezeroUnit, + .ordinal = 22, + }, + { + .name = "CXCMD_WriteMagData", + .patch = hook_CXCMD_WriteMagData, + .ordinal = 34, + }, + { + .name = "CXCMD_LogSense", + .patch = hook_CXCMD_LogSense, + .ordinal = 9, + }, + { + .name = "CXCMD_StandardInquiry", + .patch = hook_CXCMD_StandardInquiry, + .ordinal = 29, + }, + { + .name = "CXCMD_ModeSense", + .patch = hook_CXCMD_ModeSense, + .ordinal = 11, + }, + { + .name = "CXCMD_UpdateFirmware", + .patch = hook_CXCMD_UpdateFirmware, + .ordinal = 31, + }, + { + .name = "CXCMD_ModeSelect", + .patch = hook_CXCMD_ModeSelect, + .ordinal = 10, + }, + { + .name = "CXCMD_GetPrintingStatus", + .patch = hook_CXCMD_GetPrintingStatus, + .ordinal = 4, + }, + { + .name = "CXCMD_SendDiagnostic", + .patch = hook_CXCMD_SendDiagnostic, + .ordinal = 27, + }, + { + .name = "CXCMD_RetransferAndTurn", + .patch = hook_CXCMD_RetransferAndTurn, + .ordinal = 21, + }, + { + .name = "CXCMD_LogSelect", + .patch = hook_CXCMD_LogSelect, + .ordinal = 8, + }, + { + .name = "CXCMD_ReadPosition", + .patch = hook_CXCMD_ReadPosition, + .ordinal = 18, + }, + { + .name = "CXCMD_SecurityLock", + .patch = hook_CXCMD_SecurityLock, + .ordinal = 25, + }, + { + .name = "CXCMD_SetPrintingStatus", + .patch = hook_CXCMD_SetPrintingStatus, + .ordinal = 28, + }, + { + .name = "CXCMD_xReadISOMagData", + .patch = hook_CXCMD_xReadISOMagData, + .ordinal = 37, + }, + { + .name = "CXCMD_WriteISO3TrackMagData", + .patch = hook_CXCMD_WriteISO3TrackMagData, + .ordinal = 33, + }, + { + .name = "CXCMD_PasswordSet", + .patch = hook_CXCMD_PasswordSet, + .ordinal = 13, + }, + { + .name = "CXCMD_GetPrinterStatus", + .patch = hook_CXCMD_GetPrinterStatus, + .ordinal = 3, + }, + { + .name = "CXCMD_WriteProjectCode", + .patch = hook_CXCMD_WriteProjectCode, + .ordinal = 35, + }, + { + .name = "CXCMD_LoadCard", + .patch = hook_CXCMD_LoadCard, + .ordinal = 7, + }, + { + .name = "CXCMD_ReadMagData", + .patch = hook_CXCMD_ReadMagData, + .ordinal = 17, + }, + { + .name = "CXCMD_ScanPrinter", + .patch = hook_CXCMD_ScanPrinter, + .ordinal = 23, + }, + { + .name = "CXCMD_xWriteISOMagData", + .patch = hook_CXCMD_xWriteISOMagData, + .ordinal = 39, + }, + { + .name = "CXCMD_ICControl", + .patch = hook_CXCMD_ICControl, + .ordinal = 5, + }, + { + .name = "CXCMD_ImageOut", + .patch = hook_CXCMD_ImageOut, + .ordinal = 6, + }, + { + .name = "CXCMD_ReadBuffer", + .patch = hook_CXCMD_ReadBuffer, + .ordinal = 15, + }, + { + .name = "CXCMD_xReadMagData", + .patch = hook_CXCMD_xReadMagData, + .ordinal = 38, + }, + { + .name = "CXCMD_WriteBuffer", + .patch = hook_CXCMD_WriteBuffer, + .ordinal = 32, + }, + { + .name = "CXCMD_DefineLUT", + .patch = hook_CXCMD_DefineLUT, + .ordinal = 2, + }, + { + .name = "CXCMD_ReadISO3TrackMagData", + .patch = hook_CXCMD_ReadISO3TrackMagData, + .ordinal = 16, + }, + { + .name = "CXCMD_TestUnitReady", + .patch = hook_CXCMD_TestUnitReady, + .ordinal = 30, + }, + { + .name = "CXCMD_RetransferAndEject", + .patch = hook_CXCMD_RetransferAndEject, + .ordinal = 20, + }, +}; + +static const struct hook_symbol hook_lut_syms[] = { + { + .name = "Lut24_Exchange", + .patch = hook_Lut24_Exchange, + .ordinal = 1, + }, +}; + +static const struct hook_symbol hook_wdata_syms[] = { + { + .name = "Wdata_create", + .patch = hook_Wdata_create, + .ordinal = 1, + }, +}; +#pragma endregion + +static void write_int(uint8_t* data, int index, int value) { + data[index] = value >> 24; + data[index + 1] = value >> 16; + data[index + 2] = value >> 8; + data[index + 3] = value; +} + +static void write_short(uint8_t* data, int index, short value) { + data[index] = value >> 8; + data[index + 1] = value; +} + +static struct printer_cx_config printer_config; +static wchar_t printer_out_path[MAX_PATH]; +static struct printer_cx_data printer_data; + +#define HEIGHT 664 +#define WIDTH 1036 +#define IMAGE_BUFFER_SIZE WIDTH * HEIGHT +static uint8_t* back_buffer = NULL; +static uint8_t* front_buffer = NULL; +static uint64_t current_card_id; + +DWORD load_printer_data() { + DWORD bytesRead = 0; + HANDLE hSave = CreateFileW(printer_config.printer_data_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hSave != INVALID_HANDLE_VALUE) { + if (!ReadFile(hSave, &printer_data, sizeof(printer_data), &bytesRead, NULL)){ + CloseHandle(hSave); + return GetLastError(); + } + CloseHandle(hSave); + if (bytesRead != sizeof(printer_data)){ + return -1; + } + if (printer_data.version != PRINTER_DATA_VERSION) { + return -2; + } + return 0; + } else { + return GetLastError(); + } +} + +DWORD save_printer_data() { + DWORD bytesWritten = 0; + HANDLE hSave = CreateFileW(printer_config.printer_data_path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (hSave != NULL) { + if (!WriteFile(hSave, &printer_data, sizeof(printer_data), &bytesWritten, NULL)){ + CloseHandle(hSave); + dprintf("CX7000: Failed writing data: %lx\n", GetLastError()); + return GetLastError(); + } + CloseHandle(hSave); + return 0; + } else { + dprintf("CX7000: Failed opening data file for writing: %lx\n", GetLastError()); + return GetLastError(); + } +} + +void printer_cx_hook_init(const struct printer_cx_config* cfg, HINSTANCE self) { + assert(cfg != NULL); + + if (!cfg->enable) { + return; + } + + memcpy(&printer_config, cfg, sizeof(*cfg)); + printer_cx_hook_insert_hooks(NULL); + + CreateDirectoryW(cfg->printer_out_path, NULL); + memcpy(printer_out_path, cfg->printer_out_path, MAX_PATH); + + if (load_printer_data() != 0) { + memset(&printer_data, 0, sizeof(printer_data)); + printer_data.version = PRINTER_DATA_VERSION; + if (save_printer_data() == 0) { + dprintf("CX7000: Printer data initialized.\n"); + } + } + + dprintf("CX7000: hook enabled.\n"); +} + +void printer_cx_hook_insert_hooks(HMODULE target) { + hook_table_apply(target, "PCP21CT64.dll", hook_pcp_syms, _countof(hook_pcp_syms)); + hook_table_apply(target, "LUT24EXG64.dll", hook_lut_syms, _countof(hook_lut_syms)); + hook_table_apply(target, "WCREATE64.dll", hook_wdata_syms, _countof(hook_wdata_syms)); + + /* Unity workaround */ + proc_addr_table_push(target, "PCP21CT64.dll", hook_pcp_syms, _countof(hook_pcp_syms)); + proc_addr_table_push(target, "LUT24EXG64.dll", hook_lut_syms, _countof(hook_lut_syms)); + proc_addr_table_push(target, "WCREATE64.dll", hook_wdata_syms, _countof(hook_wdata_syms)); +} + +static int WINAPI hook_CXCMD_Retransfer() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static bool WINAPI hook_CXCMD_CheckIfConnected(int* pSlotId, int* pId) { + dprintf("CX7000: %s\n", __func__); + return printer_config.enable; +} + +static int WINAPI hook_CXCMD_xImageOut() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_MoveCard(int slotId, int id, int dest, int flip, int filmInit, int immed) { + dprintf("CX7000: %s(%d, %d, %d, %d)\n", __func__, dest, flip, filmInit, immed); + return CX_OK; +} + +static int WINAPI hook_CXCMD_xWriteMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_SecurityPrint(int slotId, int id, int color, int bufferIndex, int immed) { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ScanPrinterNext() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ImageOut(int slotId, int id, uint8_t* plane, int length, int color, int bufferIndex) { + dprintf("CX7000: %s\n", __func__); + + assert(color >= 0 && color <= 3); + assert(bufferIndex >= 0 && bufferIndex <= 1); + assert(length == IMAGE_BUFFER_SIZE); + + // colorIndex: 0 = w, 1 = c, 2 = m, 3 = y + // bufferIndex: 0 = back, 1 = front + + if (bufferIndex == 0) { + if (back_buffer == NULL) { + back_buffer = (uint8_t*) malloc(4 * IMAGE_BUFFER_SIZE); + } + memcpy(back_buffer + color * IMAGE_BUFFER_SIZE, plane, length); + } else { + if (front_buffer == NULL) { + front_buffer = (uint8_t*) malloc(4 * IMAGE_BUFFER_SIZE); + } + memcpy(front_buffer + color * IMAGE_BUFFER_SIZE, plane, length); + } + + return CX_OK; +} + +static int WINAPI hook_CXCMD_Print(int slotId, int id, int color, int bufferIndex, int immed) { + dprintf("CX7000: %s(%d, %d, %d)\n", __func__, color, bufferIndex, immed); + + assert(bufferIndex >= 0 && bufferIndex <= 1); + + SYSTEMTIME t; + GetLocalTime(&t); + + // color: 1 = back, 3 = front + // bufferIndex: 0 = back, 1 = front + + wchar_t dumpPath[MAX_PATH]; + uint8_t metadata[5]; + + metadata[0] = current_card_id >> 32; + write_int(metadata, 1, (int32_t)current_card_id); + + swprintf_s( + dumpPath, MAX_PATH, + L"%s\\CX7000_%04d%02d%02d_%02d%02d%02d_%s.bmp", + printer_out_path, t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, bufferIndex == 0 ? L"back" : L"front"); + + // convert image from seperate CMY arrays to one RGB array + int size = IMAGE_BUFFER_SIZE * 3; + uint8_t* raw_image = (uint8_t*) malloc(size); + for (int i = 0; i < IMAGE_BUFFER_SIZE; i++) { + // 0 is "white" and we don't really care about that + raw_image[i * 3] = 0xFF - *((bufferIndex == 0 ? back_buffer : front_buffer) + IMAGE_BUFFER_SIZE + i); + raw_image[i * 3 + 1] = 0xFF - *((bufferIndex == 0 ? back_buffer : front_buffer) + 2 * IMAGE_BUFFER_SIZE + i); + raw_image[i * 3 + 2] = 0xFF - *((bufferIndex == 0 ? back_buffer : front_buffer) + 3 * IMAGE_BUFFER_SIZE + i); + } + + dprintf("CX7000: Saving %s image to %ls\n", bufferIndex == 0 ? "back" : "front", dumpPath); + + int ret = WriteDataToBitmapFile(dumpPath, 24, WIDTH, HEIGHT, raw_image, size, metadata, 5, false); + + free(raw_image); + if (bufferIndex == 0) { + free(back_buffer); + back_buffer = NULL; + } else { + free(front_buffer); + front_buffer = NULL; + } + + if (ret < 0) { + dprintf("CX7000: WriteDataToBitmapFile returned %d\n", ret); + return CX_ERROR_FATAL_3301; + } + + return CX_OK; +} + +static int WINAPI hook_CXCMD_RezeroUnit(int slotId, int id, int action) { + dprintf("CX7000: %s\n", __func__); + return CX_OK; +} + +static int WINAPI hook_CXCMD_WriteMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_LogSense(int iSlot, int iID, int iPage, uint8_t* pbyBuffer) { + dprintf("CX7000: %s\n", __func__); + + const int size = 108; + memset(pbyBuffer, 0, size); + + + if (iPage == 56) { + dprintf("CX7000: MediumQuantity\n"); + + write_int(pbyBuffer, 8, (int)printer_data.print_counter); // total count + write_int(pbyBuffer, 16, 22); // free count + write_int(pbyBuffer, 24, 33); // head count + write_int(pbyBuffer, 32, (int)printer_data.print_counter_since_clean); // cleaning count + write_int(pbyBuffer, 40, 55); // error count + write_int(pbyBuffer, 48, 66); // cru cleaning count + + return CX_OK; + } else if (iPage == 57) { + dprintf("CX7000: Miscellaneous\n"); + + write_int(pbyBuffer, 16, 234); // re transfer hr power on time + write_int(pbyBuffer, 24, 456); // remedy hr power on time + write_int(pbyBuffer, 40, 789); // unresettable re transfer hr power on time + write_int(pbyBuffer, 48, 1023); // unresettable remedy hr power on time + + return CX_OK; + } + + dprintf("CX7000: Unknown LogSense\n"); + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_StandardInquiry(int iSlot, int iID, uint8_t* pbyBuffer) { + const int size = 96; + dprintf("CX7000: %s\n", __func__); + + memset(pbyBuffer, 0, size); + memcpy(pbyBuffer + 32, printer_config.printer_firm_version, 8); + memcpy(pbyBuffer + 50, printer_config.printer_camera_version, 8); + memcpy(pbyBuffer + 71, printer_config.printer_config_version, 8); + memcpy(pbyBuffer + 79, printer_config.printer_table_version, 8); + //memcpy(pbyBuffer + 58, printer_config.thermal_head_info, 13); // unused + + return CX_OK; +} + +static int WINAPI hook_CXCMD_ModeSense(int iSlot, int iID, int iPC, int iPage, uint8_t* pbyBuffer) { + dprintf("CX7000: %s(%d, %d)\n", __func__, iPC, iPage); + + const int size = 104; + memset(pbyBuffer, 0, size); + + if (iPC == 1 && iPage == 40) { // GetMediaInfo + pbyBuffer[51] = 10; // film count (10=100%) + pbyBuffer[52] = 50; // ink count (50=100%) + return CX_OK; + } else if (iPC == 1 && iPage == 35) { // ReadInkInfo + pbyBuffer[6] = 0; // "b" + write_short(pbyBuffer, 8, 50); // Remain + return CX_OK; + } + + dprintf("CX7000: Unknown ModeSense\n"); + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_UpdateFirmware(int iSlot, int iID, char* pFile, int iDataID) { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // intentionally not implemented + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ModeSelect(int iSlot, int iID, int iSp, int iPage, uint8_t* pbyData) { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_GetPrintingStatus() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_SendDiagnostic(int iSlot, int iID, int iTestMode, int iTestPatten, int iTestCount) { + dprintf("CX7000: %s(%d, %d, %d)\n", __func__, iTestMode, iTestPatten, iTestCount); + if (iTestMode == 19) { + dprintf("CX7000: Printer Front Buttons Enabled: %d\n", iTestPatten); + return CX_OK; + } else if (iTestMode == 17) { + dprintf("CX7000: Printer was cleaned (haha)\n"); + printer_data.print_counter_since_clean = 0; + save_printer_data(); + return CX_OK; + } else if (iTestMode == 18) { + dprintf("CX7000: Transport Mode enabled\n"); + printer_data.is_transport = true; + save_printer_data(); + return CX_OK; + } else if (iTestMode == 20) { + dprintf("CX7000: Transport Mode disabled\n"); + printer_data.is_transport = false; + save_printer_data(); + return CX_OK; + } + + dprintf("CX7000: Unknown SendDiagnostic\n"); + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_RetransferAndTurn(int slotId, int id, int immed) { + dprintf("CX7000: %s\n", __func__); + return CX_OK; +} + +static int WINAPI hook_CXCMD_LogSelect(int iSlot, int iID, int iMod) { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ReadPosition(int slotId, int id, uint8_t* buffer) { + dprintf("CX7000: %s\n", __func__); + const int size = 8; + + memset(buffer, 0, size); + buffer[0] = 1 << 2; // IsExist (0 means YES!) + buffer[7] = 0; // position (of card; 0 = printer, 1 = "IR") + + return CX_OK; +} + +static int WINAPI hook_CXCMD_SecurityLock() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_SetPrintingStatus() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_xReadISOMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_WriteISO3TrackMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_PasswordSet() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_GetPrinterStatus() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_WriteProjectCode() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_LoadCard(int slotId, int id, int dest, int flip, int filmInit, int immed) { + dprintf("CX7000: %s(%d, %d, %d, %d)\n", __func__, dest, flip, filmInit, immed); + return CX_OK; +} + +static int WINAPI hook_CXCMD_ReadMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ScanPrinter(int* pSlotId, int* pId) { + dprintf("CX7000: %s\n", __func__); + + if (!printer_config.enable) { + return CX_ERROR_NOT_CONNECTED_6804; + } + + *pSlotId = 1; + *pId = 1; + + return CX_OK; +} + +static int WINAPI hook_CXCMD_xWriteISOMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ICControl() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ReadBuffer(int iSlot, int iID, int iMode, int iBufferID, uint8_t* pbyData, int iOffset, + int iLength) { + dprintf("CX7000: %s(%d, %d, %d)\n", __func__, iMode, iBufferID, iLength); + + memset(pbyData, 0, iLength); + + if (iMode == 2 && iBufferID == 87 && iLength == 10) { + dprintf("CX7000: ReadCondition\n"); + + pbyData[0] = printer_data.is_transport; // transport mode + pbyData[1] = 0; // head white ink level, unused + pbyData[2] = 0; // main white ink level, unused + pbyData[3] = 0; // total white ink level, unused + + return CX_OK; + } else if (iMode == 2 && iBufferID == 112 && iLength == 6) { + dprintf("CX7000: GetMacAddress\n"); + + pbyData[0] = 0x12; // displays in test menu, else ununused? + pbyData[1] = 0x34; + pbyData[2] = 0x56; + pbyData[3] = 0x78; + pbyData[4] = 0x9A; + pbyData[5] = 0xBC; + + return CX_OK; + } else if (iMode == 2 && iBufferID == 82 && iLength == 4) { + dprintf("CX7000: GetCleaningWaitCount\n"); + + // seemingly unused + write_short(pbyData, 0, 0); + + return CX_OK; + } else if (iMode == 2 && iBufferID == 85 && iLength == 10) { + dprintf("CX7000: GetSensorInfo\n"); + + pbyData[0] = 244; // retransfer heat roller thermistor; must be over 243 + pbyData[1] = 0; // main pwb thermistor; unused + pbyData[2] = 0; // thermal head thermistor; unused + pbyData[3] = 0; // heater cover thermistor; unused + + return CX_OK; + } else if (iMode == 2 && iBufferID == 88 && iLength == 16) { + dprintf("CX7000: ReadErrorStatus\n"); + + pbyData[1] = 0; // is door open? + //pbyData[2...] = // any of the error codes that fit in a byte (from CX_ERROR_FATAL_3301 to CX_ERROR_PRINT_INTERRUPT_6805_3) + + return CX_OK; + } else if (iMode == 2 && iBufferID == 224 && iLength == 10) { + dprintf("CX7000: ReadCode\n"); + + printer_data.print_counter_since_clean++; + current_card_id = ++printer_data.print_counter; + dprintf("CX7000: Generated new card ID: %lld\n", current_card_id); + + save_printer_data(); + + pbyData[0] = current_card_id >> 32; // MSB of card id + write_int(pbyData, 1, (int32_t)current_card_id); // lower 4 bytes of card id + pbyData[5] = 0x0; // Direction (1 = rotate image by 180 degrees) + pbyData[6] = 0x1; // CheckCode (0 = error) + + return CX_OK; + } else if (iMode == 2 && iBufferID == 144 && iLength == 260) { + dprintf("CX7000: ReadErrorLog\n"); + + write_int(pbyData, 0, 0); // LogCount + /*for (int i = 0; false; i++) { // list of error ids + write_int(pbyData, i + 4, 0); + }*/ + + return CX_OK; + } + + dprintf("CX7000: Unknown ReadBuffer\n"); + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_xReadMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_WriteBuffer(int iSlot, int iID, int iMode, int iBufferID, uint8_t* pbyData, int iOffset, // NOLINT(*-non-const-parameter) + int iLength) { + dprintf("CX7000: %s(%d, %d, %d, %d)\n", __func__, iMode, iBufferID, iOffset, iLength); + if (iMode == 2 && iBufferID == 82 && iLength == 4) { + int val = pbyData[0] << 8 | pbyData[1]; + dprintf("CX7000: Set cleaning limit: %d\n", val); + + return CX_OK; + } + + dprintf("CX7000: Unknown WriteBuffer\n"); + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_DefineLUT(int slotId, int id, int color, int length, uint8_t* buffer) { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_ReadISO3TrackMagData() { + dprintf("CX7000: %s\n", __func__); + dprintf("CX7000: Unimplemented\n"); // unused + return CX_ERROR_USB_COM_3201; +} + +static int WINAPI hook_CXCMD_TestUnitReady(int slotId, int id) { + dprintf("CX7000: %s\n", __func__); + + if (!printer_config.enable) { + return CX_ERROR_NOT_CONNECTED_6804; + } + + return CX_OK; +} + +static int WINAPI hook_CXCMD_RetransferAndEject(int slotId, int id, int immed) { + dprintf("CX7000: %s\n", __func__); + return CX_OK; +} + +static bool WINAPI hook_Lut24_Exchange(const wchar_t* pFile, uint8_t* y, uint8_t* m, uint8_t* c, int sizeY, int sizeM, + int sizeC) { + dprintf("CX7000: %s(%ls)\n", __func__, pFile); + + // stub? + + return true; +} + +static bool WINAPI hook_Wdata_create(uint8_t* pbyRdata, uint8_t* pbyGdata, uint8_t* pbyBdata, int iWidth, + int iHeight, bool bPortrait, int iAlgorithim, uint8_t* pbyWdata) { + dprintf("CX7000: %s(%d, %d, %d)\n", __func__, iHeight, bPortrait, iAlgorithim); + + // stub? + + return true; +} \ No newline at end of file diff --git a/common/hooklib/printer_cx.h b/common/hooklib/printer_cx.h new file mode 100644 index 0000000..d86773c --- /dev/null +++ b/common/hooklib/printer_cx.h @@ -0,0 +1,73 @@ +#pragma once +#include +#include +#include + +#define PRINTER_DATA_VERSION 1 + +struct printer_cx_config { + bool enable; + wchar_t printer_out_path[MAX_PATH]; + wchar_t printer_data_path[MAX_PATH]; + char printer_firm_version[8]; + char printer_camera_version[8]; + char printer_config_version[8]; + char printer_table_version[8]; +}; + +struct printer_cx_data { + uint8_t version; + uint64_t print_counter; + uint64_t print_counter_since_clean; + bool is_transport; +}; + +enum { + CX_OK = 0, + CX_ERROR_FATAL_3301 = -1, + CX_ERROR_USB_COM_3201 = -2, + CX_ERROR_PRINT_INTERRUPT_6805_4 = -4, + CX_ERROR_CODE_UNREADABLE_3303 = -5, + CX_ERROR_INK_LOW_3202 = -6, + CX_ERROR_PRINT_INTERRUPT_6805_3 = -7, + CX_ERROR_NO_CARD_6801 = -16961536, + CX_ERROR_DOOR_OPEN_6808 = -16961792, + CX_ERROR_6831 = -16963328, + CX_ERROR_6810 = -16964864, + CX_ERROR_CLEAN_PRINTER_3999 = -16973056, + CX_ERROR_JAM_6805_1 = -17010688, + CX_ERROR_REVERSE_JAM_6805_2 = -17010944, + CX_ERROR_CAMERA_JAM_6805_3 = -17011200, + CX_ERROR_TRANSPORT_JAM_6805_4 = -17011456, + CX_ERROR_PAPER_SENSOR_JAM_6805_5 = -17011712, + CX_ERROR_RETRANSFER_JAM_6805_6 = -17011968, + CX_ERROR_PAPER_RIPPED_6813_3 = -17015040, + CX_ERROR_CODE_READ_6811 = -17018112, + CX_ERROR_UNAUTHORIZED_INK_6803_1 = -17018880, + CX_ERROR_INK_EMPTY_6813_1 = -17019136, + CX_ERROR_PRINT_TIMEOUT_6810_3 = -17056768, + CX_ERROR_CAMERA_HARDWARE_FAULT_6810_5 = -17083136, + CX_ERROR_CAMERA_COM_6810_6 = -17083392, + CX_ERROR_ROLLER_6810_15 = -17088768, + CX_ERROR_OVER_TEMPERATURE_6810_16 = -17089024, + CX_ERROR_POWER_INTERRUPT_6810_1 = -17089280, + CX_ERROR_INITIALIZATION_6810_2 = -17094656, + CX_ERROR_OVER_TEMPERATURE_6810_10 = -17100800, + CX_ERROR_RETRANSFER_ROLLER_6810_11 = -17101056, + CX_ERROR_THERMOSTAT_6810_12 = -17101312, + CX_ERROR_OVER_TEMPERATURE_6810_20 = -17101568, + CX_ERROR_STRAIGHTEN_ROLLER_6810_21 = -17101824, + CX_ERROR_THERMOSTAT_6810_22 = -17102080, + CX_ERROR_PRINTER_TOO_COLD_6833_1 = -16971264, + CX_ERROR_OVER_TEMPERATURE_6810_25 = -17102848, + CX_ERROR_CAMERA_NOT_FOUND_6810_7 = -17116672, + CX_ERROR_RETRANSFER_ROLL_EMPTY_6802_3 = -21144064, + CX_ERROR_INK_ROLL_EMPTY_6802_1 = -21148160, + CX_ERROR_NOT_CONNECTED_6804 = -33554432, + CX_ERROR_CAMERA_JAM_6805_7 = -17012224, + CX_ERROR_INVALID_CLEANING_CARD_6832_1 = -16965376, + CX_ERROR_TEMPERATURE_RESOLVED_6833_2 = -16971520, +}; + +void printer_cx_hook_init(const struct printer_cx_config *cfg, HINSTANCE self); +void printer_cx_hook_insert_hooks(HMODULE target); \ No newline at end of file diff --git a/common/hooklib/y3-dll.c b/common/hooklib/y3-dll.c new file mode 100644 index 0000000..e3f112f --- /dev/null +++ b/common/hooklib/y3-dll.c @@ -0,0 +1,109 @@ +#include + +#include +#include + +#include "hooklib/config.h" + +#include "util/dll-bind.h" +#include "util/dprintf.h" + +#include "y3.h" +#include "y3-dll.h" + +const struct dll_bind_sym y3_dll_syms[] = { + { + .sym = "y3_io_init", + .off = offsetof(struct y3_dll, init), + }, { + .sym = "y3_io_get_cards", + .off = offsetof(struct y3_dll, get_cards), + }, { + .sym = "y3_io_close", + .off = offsetof(struct y3_dll, close), + } +}; + +struct y3_dll y3_dll; + +// Copypasta DLL binding and diagnostic message boilerplate. +// Not much of this lends itself to being easily factored out. Also there +// will be a lot of API-specific branching code here eventually as new API +// versions get defined, so even though these functions all look the same +// now this won't remain the case forever. + +HRESULT y3_dll_init(const struct y3_dll_config *cfg, HINSTANCE self) +{ + uint16_t (*get_api_version)(void); + const struct dll_bind_sym *sym; + HINSTANCE owned; + HINSTANCE src; + HRESULT hr; + + assert(cfg != NULL); + assert(self != NULL); + + if (cfg->path[0] != L'\0') { + owned = LoadLibraryW(cfg->path); + + if (owned == NULL) { + hr = HRESULT_FROM_WIN32(GetLastError()); + dprintf("Y3: Failed to load IO DLL: %lx: %S\n", + hr, + cfg->path); + + goto end; + } + + dprintf("Y3: Using custom IO DLL: %S\n", cfg->path); + src = owned; + } else { + owned = NULL; + src = self; + } + + get_api_version = (void *) GetProcAddress(src, "y3_io_get_api_version"); + + if (get_api_version != NULL) { + y3_dll.api_version = get_api_version(); + } else { + y3_dll.api_version = 0x0100; + dprintf("Custom IO DLL does not expose y3_io_get_api_version, " + "assuming API version 1.0.\n" + "Please ask the developer to update their DLL.\n"); + } + + if (y3_dll.api_version >= 0x0200) { + hr = E_NOTIMPL; + dprintf("Y3: Custom IO DLL implements an unsupported " + "API version (%#04x). Please update Segatools.\n", + y3_dll.api_version); + + goto end; + } + + sym = y3_dll_syms; + hr = dll_bind(&y3_dll, src, &sym, _countof(y3_dll_syms)); + + if (FAILED(hr)) { + if (src != self) { + dprintf("Y3: Custom IO DLL does not provide function " + "\"%s\". Please contact your IO DLL's developer for " + "further assistance.\n", + sym->sym); + + goto end; + } else { + dprintf("Internal error: could not reflect \"%s\"\n", sym->sym); + } + } + + owned = NULL; + +end: + if (owned != NULL) { + FreeLibrary(owned); + } + + return hr; +} diff --git a/common/hooklib/y3-dll.h b/common/hooklib/y3-dll.h new file mode 100644 index 0000000..5b2eec8 --- /dev/null +++ b/common/hooklib/y3-dll.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include + +#include "hooklib/y3.h" + + +struct y3_dll { + uint16_t api_version; + HRESULT (*init)(void); + HRESULT (*close)(void); + HRESULT (*get_cards)(struct CardInfo* cards, int* len); +}; + +extern struct y3_dll y3_dll; + +HRESULT y3_dll_init(const struct y3_dll_config *cfg, HINSTANCE self); diff --git a/common/hooklib/y3.c b/common/hooklib/y3.c new file mode 100644 index 0000000..833d58c --- /dev/null +++ b/common/hooklib/y3.c @@ -0,0 +1,625 @@ +// ReSharper disable CppParameterNeverUsed +#include + +#include +#include +#include +#include + +#include "y3.h" + +#include "hook/table.h" +#include "hook/procaddr.h" + +#include "hooklib/y3-dll.h" + +#include "util/dprintf.h" + +#if _WIN32 || _WIN64 + #if _WIN64 + #define ENV64BIT + #else + #define ENV32BIT + #endif +#endif + +// Check GCC +#if __GNUC__ + #if __x86_64__ || __ppc64__ + #define ENV64BIT + #else + #define ENV32BIT + #endif +#endif + +#ifdef ENV64BIT + #define CALL +#else + #define CALL __cdecl +#endif + +float CALL API_DLLVersion(); +uint32_t CALL API_GetLastError(int* hDevice); +uint32_t CALL API_GetErrorMessage(uint32_t errNo, char* szMessage, int numBytes); +int* CALL API_Connect(char* szPortName); +int CALL API_Close(int* hDevice); +int CALL API_Start(int* hDevice); +int CALL API_Stop(int* hDevice); +float CALL API_GetFirmVersion(int* hDevice); +uint32_t CALL API_GetFirmName(int* hDevice); +uint32_t CALL API_GetTargetCode(int* hDevice); +uint32_t CALL API_GetStatus(int* hDevice); +uint32_t CALL API_GetCounter(int* hDevice); +int CALL API_ClearError(int* hDevice); +int CALL API_Reset(int* hDevice, bool isHardReset); +int CALL API_GetCardInfo(int* hDevice, int numCards, struct CardInfo* pCardInfo); +int CALL API_GetCardInfoCharSize(); +int CALL API_FirmwareUpdate(int* hDevice, uint32_t address, uint32_t size, uint8_t* buffer); +int CALL API_Calibration(int* hDevice, int calib); +int CALL API_GetCalibrationResult(int* hDevice, int calib, uint32_t* result); +uint32_t CALL API_GetProcTime(int* hDevice); +uint32_t CALL API_GetMemStatus(int* hDevice); +uint32_t CALL API_GetMemCounter(int* hDevice); +int CALL API_SetParameter(int* hDevice, uint32_t uParam, uint32_t* pParam); +int CALL API_GetParameter(int* hDevice, uint32_t uParam, uint32_t* pParam); + +signed int CALL API_SetDevice(int a1, int a2); +signed int CALL API_SetCommand(int a1, int a2, int a3, int* a4); +signed int CALL API_SetSysControl(int a1, int a2, int* a3); +signed int CALL API_GetSysControl(int a1, int a2, int* a3); +int CALL API_TestReset(int a1); +signed int API_DebugReset(int a1, ...); +int CALL API_GetBoardType(int a1); +int CALL API_GetCardDataSize(int a1); +int CALL API_GetFirmDate(int a1); +int API_SystemCommand(int a1, char a2, ...); +int CALL API_CalcCheckSum(DWORD* a1, int a2, int a3); +int CALL API_GetCheckSumResult(int a1); +int CALL API_BlockRead(int a1, int a2, int a3, SIZE_T dwBytes); +int CALL API_GetBlockReadResult(int a1, void* a2); +int CALL API_BlockWrite(int a1, int a2, int a3, SIZE_T dwBytes, void* a5); +signed int CALL API_GetDebugParam(int a1, int a2, DWORD* a3); + +uint32_t convert_string_to_uint(const char* firmName); + +static const struct hook_symbol Y3_hooks[] = { + { + .name = "API_DLLVersion", + .patch = API_DLLVersion, + .link = NULL + }, + { + .name = "API_GetLastError", + .patch = API_GetLastError, + .link = NULL + }, + { + .name = "API_GetErrorMessage", + .patch = API_GetErrorMessage, + .link = NULL + }, + { + .name = "API_Connect", + .patch = API_Connect, + .link = NULL + }, + { + .name = "API_Close", + .patch = API_Close, + .link = NULL + }, + { + .name = "API_Start", + .patch = API_Start, + .link = NULL + }, + { + .name = "API_Stop", + .patch = API_Stop, + .link = NULL + }, + { + .name = "API_GetFirmVersion", + .patch = API_GetFirmVersion, + .link = NULL + }, + { + .name = "API_GetFirmName", + .patch = API_GetFirmName, + .link = NULL + }, + { + .name = "API_GetTargetCode", + .patch = API_GetTargetCode, + .link = NULL + }, + { + .name = "API_GetStatus", + .patch = API_GetStatus, + .link = NULL + }, + { + .name = "API_GetCounter", + .patch = API_GetCounter, + .link = NULL + }, + { + .name = "API_Reset", + .patch = API_Reset, + .link = NULL + }, + { + .name = "API_GetCardInfo", + .patch = API_GetCardInfo, + .link = NULL + }, + { + .name = "API_GetCardInfoCharSize", + .patch = API_GetCardInfoCharSize, + .link = NULL + }, + { + .name = "API_FirmwareUpdate", + .patch = API_FirmwareUpdate, + .link = NULL + }, + { + .name = "API_Calibration", + .patch = API_Calibration, + .link = NULL + }, + { + .name = "API_GetCalibrationResult", + .patch = API_GetCalibrationResult, + .link = NULL + }, + { + .name = "API_GetProcTime", + .patch = API_GetProcTime, + .link = NULL + }, + { + .name = "API_GetMemStatus", + .patch = API_GetMemStatus, + .link = NULL + }, + { + .name = "API_GetMemCounter", + .patch = API_GetMemCounter, + .link = NULL + }, + { + .name = "API_SetParameter", + .patch = API_SetParameter, + .link = NULL + }, + { + .name = "API_GetParameter", + .patch = API_GetParameter, + .link = NULL + }, + { + .name = "API_SetDevice", + .patch = API_SetDevice, + .link = NULL + }, + { + .name = "API_SetCommand", + .patch = API_SetCommand, + .link = NULL + }, + { + .name = "API_SetSysControl", + .patch = API_SetSysControl, + .link = NULL + }, + { + .name = "API_GetSysControl", + .patch = API_GetSysControl, + .link = NULL + }, + { + .name = "API_TestReset", + .patch = API_TestReset, + .link = NULL + }, + { + .name = "API_DebugReset", + .patch = API_DebugReset, + .link = NULL + }, + { + .name = "API_GetBoardType", + .patch = API_GetBoardType, + .link = NULL + }, + { + .name = "API_GetCardDataSize", + .patch = API_GetCardDataSize, + .link = NULL + }, + { + .name = "API_GetFirmDate", + .patch = API_GetFirmDate, + .link = NULL + }, + { + .name = "API_SystemCommand", + .patch = API_SystemCommand, + .link = NULL + }, + { + .name = "API_CalcCheckSum", + .patch = API_CalcCheckSum, + .link = NULL + }, + { + .name = "API_GetCheckSumResult", + .patch = API_GetCheckSumResult, + .link = NULL + }, + { + .name = "API_BlockRead", + .patch = API_BlockRead, + .link = NULL + }, + { + .name = "API_GetBlockReadResult", + .patch = API_GetBlockReadResult, + .link = NULL + }, + { + .name = "API_BlockWrite", + .patch = API_BlockWrite, + .link = NULL + }, + { + .name = "API_GetDebugParam", + .patch = API_GetDebugParam, + .link = NULL + }, +}; + +static struct y3_config y3_config; + +#define MAX_CARD_SIZE 32 +static struct CardInfo card_data[MAX_CARD_SIZE]; + +static int* Y3_COM_FIELD = (int*)10; +static int* Y3_COM_PRINT = (int*)11; + +HRESULT y3_hook_init(const struct y3_config* cfg, HINSTANCE self, const wchar_t* config_filename) { + HRESULT hr; + assert(cfg != NULL); + + if (!cfg->enable) { + return S_FALSE; + } + + memcpy(&y3_config, cfg, sizeof(*cfg)); + Y3_COM_FIELD = (int*)(uintptr_t)cfg->port_field; + Y3_COM_PRINT = (int*)(uintptr_t)cfg->port_printer; + + y3_insert_hooks(NULL); + + memset(card_data, 0, sizeof(card_data)); + + struct y3_dll_config config; + y3_dll_config_load(&config, config_filename); + + hr = y3_dll_init(&config, self); + if (FAILED(hr)) { + return hr; + } + + dprintf("Y3: hook enabled (field port = %d, printer port = %d)\n", cfg->port_field, cfg->port_printer); + + return hr; +} + +void y3_insert_hooks(HMODULE target) { + hook_table_apply( + target, + "Y3CodeReaderNE.dll", + Y3_hooks, + _countof(Y3_hooks)); + + proc_addr_table_push( + target, + "Y3CodeReaderNE.dll", + Y3_hooks, + _countof(Y3_hooks)); +} + +float CALL API_DLLVersion() { + dprintf("Y3: %s\n", __func__); + return 1; +} + +uint32_t CALL API_GetLastError(int* hDevice) { + dprintf("Y3: %s\n", __func__); + if (!y3_config.enable) { + return 1; + } + return 0; +} + +uint32_t CALL API_GetErrorMessage(uint32_t errNo, char* szMessage, + int numBytes) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int* CALL API_Connect(char* szPortName) { + HRESULT hr; + + dprintf("Y3: %s(%s)\n", __func__, szPortName); + + if (!y3_config.enable) { + return NULL; + } + + char number[2]; + strncpy(number, szPortName + 3, 2); + int* hDevice = (int*)(uintptr_t)atoi(number); + + if (hDevice == Y3_COM_FIELD) { + hr = y3_dll.init(); + if (FAILED(hr)) { + dprintf("Y3: Hook DLL initialization failed: %lx\n", hr); + return NULL; + } + } + + return hDevice; +} + +int CALL API_Close(int* hDevice) { + dprintf("Y3: %s(%p)\n", __func__, hDevice); + + if (hDevice == Y3_COM_FIELD) { + y3_dll.close(); + } + + return 0; +} + +int CALL API_Start(int* hDevice) { + dprintf("Y3: %s(%p)\n", __func__, hDevice); + return 0; +} + +int CALL API_Stop(int* hDevice) { + dprintf("Y3: %s(%p)\n", __func__, hDevice); + return 0; +} + +float CALL API_GetFirmVersion(int* hDevice) { + dprintf("Y3: %s(%p)\n", __func__, hDevice); + return 1; +} + +uint32_t CALL API_GetFirmName(int* hDevice) { + uint32_t result = 0; + dprintf("Y3: %s(%p)\n", __func__, hDevice); + + if (hDevice == Y3_COM_FIELD) { + result = convert_string_to_uint(y3_config.firm_name_field); + dprintf("Y3: This device is a FIELD: %s\n", y3_config.firm_name_field); + } else if (hDevice == Y3_COM_PRINT) { + result = convert_string_to_uint(y3_config.firm_name_printer); + dprintf("Y3: This device is a PRINTER: %s\n", y3_config.firm_name_printer); + } else { + dprintf("Y3: This device is UNKNOWN\n"); + } + + return result; +} + +uint32_t CALL API_GetTargetCode(int* hDevice) { + uint32_t result = 1162760014; + dprintf("Y3: %s(%p)\n", __func__, hDevice); + + if (hDevice == Y3_COM_FIELD) { + result = convert_string_to_uint(y3_config.target_code_field); + dprintf("Y3: This device is a FIELD: %s\n", y3_config.target_code_field); + } else if (hDevice == Y3_COM_PRINT) { + result = convert_string_to_uint(y3_config.target_code_printer); + dprintf("Y3: This device is a PRINTER: %s\n", y3_config.target_code_printer); + } else { + dprintf("Y3: This Y3 device is UNKNOWN\n"); + } + + return result; +} + +uint32_t CALL API_GetStatus(int* hDevice) { + // dprintf("Y3: %s\n", __func__); + return 0; +} + +uint32_t CALL API_GetCounter(int* hDevice) { + // dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_ClearError(int* hDevice) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_Reset(int* hDevice, bool isHardReset) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_GetCardInfo(int* hDevice, int numCards, struct CardInfo* pCardInfo) { + // dprintf("Y3: %s(%p), %d\n", __func__, hDevice, numCards); + // ret = num cards + // numCards = max cards + + if (hDevice == Y3_COM_FIELD) { + + int cards = numCards; + HRESULT hr = y3_dll.get_cards(pCardInfo, &cards); + if (FAILED(hr)) { + dprintf("Y3: DLL returned error when retrieving cards: %lx\n", hr); + return 0; + } + + return cards; + } else if (hDevice == Y3_COM_PRINT) { + pCardInfo[0].fX = 0; + pCardInfo[0].fY = 0; + pCardInfo[0].fAngle = 0; + pCardInfo[0].eCardType = TYPE0; + pCardInfo[0].eCardStatus = MARKER; + pCardInfo[0].uID = 0x10; + pCardInfo[0].nNumChars = 0; + pCardInfo[0].ubChar0.Data = 0; + pCardInfo[0].ubChar1.Data = 0x4000; + pCardInfo[0].ubChar2.Data = 0; + pCardInfo[0].ubChar3.Data = 0x0; // 40 + pCardInfo[0].ubChar4.Data = 0; + pCardInfo[0].ubChar5.Data = 0; + return 1; + } + + return 0; +} + +int CALL API_GetCardInfoCharSize() { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_FirmwareUpdate(int* hDevice, uint32_t address, uint32_t size, + uint8_t* buffer) { + dprintf("Y3: %s\n", __func__); + return 1; // not supported +} + +int CALL API_Calibration(int* hDevice, int calib) { + dprintf("Y3: %s\n", __func__); + return 1; +} + +int CALL API_GetCalibrationResult(int* hDevice, int calib, uint32_t* result) { + dprintf("Y3: %s\n", __func__); + return 1; +} + +uint32_t CALL API_GetProcTime(int* hDevice) { + // dprintf("Y3: %s\n", __func__); + return 0; +} + +uint32_t CALL API_GetMemStatus(int* hDevice) { + dprintf("Y3: %s\n", __func__); + return 0; +} +uint32_t CALL API_GetMemCounter(int* hDevice) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_SetParameter(int* hDevice, uint32_t uParam, uint32_t* pParam) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_GetParameter(int* hDevice, uint32_t uParam, uint32_t* pParam) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +signed int CALL API_SetDevice(int a1, int a2) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +signed int CALL API_SetCommand(int a1, int a2, int a3, int* a4) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +signed int CALL API_SetSysControl(int a1, int a2, int* a3) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +signed int CALL API_GetSysControl(int a1, int a2, int* a3) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_TestReset(int a1) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +signed int API_DebugReset(int a1, ...) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_GetBoardType(int a1) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_GetCardDataSize(int a1) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_GetFirmDate(int a1) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int API_SystemCommand(int a1, char a2, ...) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_CalcCheckSum(DWORD* a1, int a2, int a3) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_GetCheckSumResult(int a1) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_BlockRead(int a1, int a2, int a3, SIZE_T dwBytes) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_GetBlockReadResult(int a1, void* a2) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +int CALL API_BlockWrite(int a1, int a2, int a3, SIZE_T dwBytes, void* a5) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +signed int CALL API_GetDebugParam(int a1, int a2, DWORD* a3) { + dprintf("Y3: %s\n", __func__); + return 0; +} + +uint32_t convert_string_to_uint(const char* firmName) { + uint32_t result = 0; + + // Iterate over each character in the string and construct the uint32_t + for (int i = 0; i < 4; i++) { + result |= (uint32_t)firmName[i] << (i * 8); + } + + return result; +} diff --git a/common/hooklib/y3.h b/common/hooklib/y3.h new file mode 100644 index 0000000..a42841b --- /dev/null +++ b/common/hooklib/y3.h @@ -0,0 +1,71 @@ +#pragma once + +#include +#include + +#include "hooklib/config.h" + +#pragma pack(push, 1) + +// Value held on a card. +struct CardByteData { + unsigned int Data; +}; + +// Unused +enum CardType { + TYPE0 = 0, + TYPE1, + TYPE2, + TYPE3, + TYPE4, + TYPE5, + TYPE6, + TYPE7 = 7 +}; + +enum CardStatus { + // Unset entry + INVALID = 0, + // Valid card + VALID = 1, + // Not a card but rather infrared interference. Only relevant in test mode. + INFERENCE = 2, + // This is only used by the printer camera. + MARKER = 3 +}; + +struct CardInfo { + // X position of the card. + float fX; // 0x00|0 + // Y position of the card. + float fY; // 0x04|4 + // Rotation of the card in degrees >=0.0 && <360.0 + float fAngle; // 0x08|8 + // Unused + enum CardType eCardType; // 0x0C|12 + // see enum CardStatus + enum CardStatus eCardStatus; // 0x10|16 + // card's BaseCode. used for a reference to the card being tracked as well as part of the IvCode. + unsigned int uID; // 0x14|20 + // Unused + int nNumChars; // 0x18|24 + // Title Code. Is 8589934592 for EKT. + struct CardByteData ubChar0; // 0x1C|28 + // Must be 0x4000 for the printer camera. + struct CardByteData ubChar1; // 0x20|32 + // Unused + struct CardByteData ubChar2; // 0x24|36 + // Must be 0x0 for the printer camera. + struct CardByteData ubChar3; // 0x28|40 + // Unused + struct CardByteData ubChar4; // 0x2C|44 + // Unused + struct CardByteData ubChar5; // 0x30|48 +}; + +#pragma pack(pop) + +HRESULT y3_hook_init(const struct y3_config *cfg, HINSTANCE self, const wchar_t* config_path); + +void y3_insert_hooks(HMODULE target); diff --git a/common/platform/amvideo.c b/common/platform/amvideo.c index 001a52a..e0c51ab 100644 --- a/common/platform/amvideo.c +++ b/common/platform/amvideo.c @@ -18,6 +18,7 @@ static HRESULT amvideo_reg_read_name(void *bytes, uint32_t *nbytes); static HRESULT amvideo_reg_read_port_X(void *bytes, uint32_t *nbytes); static HRESULT amvideo_reg_read_resolution_1(void *bytes, uint32_t *nbytes); +static HRESULT amvideo_reg_read_resolution_2(void *bytes, uint32_t *nbytes); static HRESULT amvideo_reg_read_setting(void *bytes, uint32_t *nbytes); static HRESULT amvideo_reg_read_use_segatiming(void *bytes, uint32_t *nbytes); @@ -81,6 +82,10 @@ static const struct reg_hook_val amvideo_reg_mode_vals[] = { .name = L"resolution_1", .read = amvideo_reg_read_resolution_1, .type = REG_SZ, + }, { + .name = L"resolution_2", + .read = amvideo_reg_read_resolution_2, + .type = REG_SZ, }, { .name = L"use_segatiming", .read = amvideo_reg_read_use_segatiming, @@ -171,6 +176,11 @@ static HRESULT amvideo_reg_read_resolution_1(void *bytes, uint32_t *nbytes) return reg_hook_read_wstr(bytes, nbytes, L"1920x1080"); } +static HRESULT amvideo_reg_read_resolution_2(void *bytes, uint32_t *nbytes) +{ + return reg_hook_read_wstr(bytes, nbytes, L"1920x1080"); +} + static HRESULT amvideo_reg_read_setting(void *bytes, uint32_t *nbytes) { return reg_hook_read_wstr(bytes, nbytes, L"0"); diff --git a/common/platform/config.c b/common/platform/config.c index d089977..e707126 100644 --- a/common/platform/config.c +++ b/common/platform/config.c @@ -12,6 +12,9 @@ #include "platform/amvideo.h" #include "platform/clock.h" #include "platform/config.h" + +#include + #include "platform/dns.h" #include "platform/epay.h" #include "platform/hwmon.h" @@ -23,6 +26,7 @@ #include "platform/platform.h" #include "platform/vfs.h" #include "platform/system.h" +#include "util/dprintf.h" #include "platform/openssl.h" #include "util/dprintf.h" @@ -32,6 +36,14 @@ void platform_config_load(struct platform_config *cfg, const wchar_t *filename) assert(cfg != NULL); assert(filename != NULL); + if (!PathFileExistsW(filename)) { + wchar_t temp[MAX_PATH]; + dprintf("ERROR: Configuration does not exist\n"); + dprintf(" Configured: \"%ls\"\n", filename); + GetFullPathNameW(filename, _countof(temp), temp, NULL); + dprintf(" Expanded: \"%ls\"\n", temp); + } + amvideo_config_load(&cfg->amvideo, filename); clock_config_load(&cfg->clock, filename); dns_config_load(&cfg->dns, filename); @@ -206,6 +218,7 @@ void nusec_config_load(struct nusec_config *cfg, const wchar_t *filename) wchar_t game_id[5]; wchar_t platform_id[5]; wchar_t subnet[16]; + wchar_t bcast[16]; unsigned int ip[4]; size_t i; @@ -217,6 +230,7 @@ void nusec_config_load(struct nusec_config *cfg, const wchar_t *filename) memset(game_id, 0, sizeof(game_id)); memset(platform_id, 0, sizeof(platform_id)); memset(subnet, 0, sizeof(subnet)); + memset(bcast, 0, sizeof(bcast)); cfg->enable = GetPrivateProfileIntW(L"keychip", L"enable", 1, filename); @@ -260,6 +274,14 @@ void nusec_config_load(struct nusec_config *cfg, const wchar_t *filename) _countof(subnet), filename); + GetPrivateProfileStringW( + L"netenv", + L"broadcast", + L"255.255.255.255", + bcast, + _countof(bcast), + filename); + for (i = 0 ; i < 16 ; i++) { cfg->keychip_id[i] = (char) keychip_id[i]; } @@ -275,6 +297,9 @@ void nusec_config_load(struct nusec_config *cfg, const wchar_t *filename) swscanf(subnet, L"%u.%u.%u.%u", &ip[0], &ip[1], &ip[2], &ip[3]); cfg->subnet = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | 0; + swscanf(bcast, L"%u.%u.%u.%u", &ip[0], &ip[1], &ip[2], &ip[3]); + cfg->bcast = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | (ip[3]); + GetPrivateProfileStringW( L"keychip", L"billingCa", diff --git a/common/platform/netenv.c b/common/platform/netenv.c index 4fb77d2..ecf2d7e 100644 --- a/common/platform/netenv.c +++ b/common/platform/netenv.c @@ -16,6 +16,8 @@ #include "hook/table.h" #include "platform/netenv.h" + +#include "hook/procaddr.h" #include "platform/nusec.h" #include "util/dprintf.h" @@ -72,6 +74,14 @@ static uint32_t WINAPI hook_IcmpSendEcho2( uint32_t ReplySize, uint32_t Timeout); +static int WINAPI hook_sendto( + SOCKET s, + const char* buf, + int len, + int flags, + const struct sockaddr *to, + int tolen); + /* Link pointers */ static uint32_t (WINAPI *next_GetAdaptersAddresses)( @@ -108,6 +118,15 @@ static uint32_t (WINAPI *next_IcmpSendEcho2)( uint32_t ReplySize, uint32_t Timeout); +static int (WINAPI *next_sendto)( + SOCKET s, + const char *buf, + int len, + int flags, + const struct sockaddr *to, + int tolen); + + static const struct hook_symbol netenv_hook_syms[] = { { .name = "GetAdaptersAddresses", @@ -132,7 +151,17 @@ static const struct hook_symbol netenv_hook_syms[] = { } }; +static struct hook_symbol netenv_hook_syms_ws2[] = { + { + .name = "sendto", + .patch = hook_sendto, + .ordinal = 20, + .link = (void **) &next_sendto + }, +}; + static uint32_t netenv_ip_prefix; +static uint32_t netenv_ip_bcast; static uint32_t netenv_ip_iface; static uint32_t netenv_ip_router; static uint8_t netenv_mac_addr[6]; @@ -155,17 +184,34 @@ HRESULT netenv_hook_init( } netenv_ip_prefix = kc_cfg->subnet; + netenv_ip_bcast = kc_cfg->bcast; netenv_ip_iface = kc_cfg->subnet | cfg->addr_suffix; netenv_ip_router = kc_cfg->subnet | cfg->router_suffix; memcpy(netenv_mac_addr, cfg->mac_addr, sizeof(netenv_mac_addr)); + netenv_hook_apply_hooks(NULL); + + return S_OK; +} + +void netenv_hook_apply_hooks(HMODULE mod) { hook_table_apply( - NULL, + mod, "iphlpapi.dll", netenv_hook_syms, _countof(netenv_hook_syms)); - return S_OK; + hook_table_apply( + mod, + "ws2_32.dll", + netenv_hook_syms_ws2, + _countof(netenv_hook_syms_ws2)); + + proc_addr_table_push( + mod, + "ws2_32.dll", + netenv_hook_syms_ws2, + _countof(netenv_hook_syms_ws2)); } static uint32_t WINAPI hook_GetAdaptersAddresses( @@ -506,3 +552,39 @@ static uint32_t WINAPI hook_IcmpSendEcho2( return 1; } + +static int WINAPI hook_sendto( + SOCKET s, + const char* buf, + int len, + int flags, + const struct sockaddr* to, + int tolen) { + if (to->sa_family != AF_INET) { + // we only care about IP packets + return next_sendto(s, buf, len, flags, to, tolen); + } + + const struct sockaddr_in* original_to = (struct sockaddr_in*)to; + + uint32_t bc_addr = _byteswap_ulong(netenv_ip_prefix | 0xFF); + + if (original_to->sin_addr.S_un.S_addr == bc_addr) { + + uint32_t src_addr = _byteswap_ulong(original_to->sin_addr.S_un.S_addr); + uint32_t dest_addr = _byteswap_ulong(netenv_ip_bcast); + + dprintf("Netenv: sendTo broadcast %u.%u.%u.%u -> %u.%u.%u.%u\n", + (src_addr >> 24) & 0xff, (src_addr >> 16) & 0xff, (src_addr >> 8) & 0xff, src_addr & 0xff, + (dest_addr >> 24) & 0xff, (dest_addr >> 16) & 0xff, (dest_addr >> 8) & 0xff, dest_addr & 0xff); + + struct sockaddr_in modified_to = {0}; + memcpy(&modified_to, original_to, tolen); + + modified_to.sin_addr.S_un.S_addr = dest_addr; + + return next_sendto(s, buf, len, flags, (struct sockaddr*)&modified_to, sizeof(modified_to)); + } + + return next_sendto(s, buf, len, flags, to, tolen); +} \ No newline at end of file diff --git a/common/platform/netenv.h b/common/platform/netenv.h index 977a3f6..88cae15 100644 --- a/common/platform/netenv.h +++ b/common/platform/netenv.h @@ -18,3 +18,4 @@ HRESULT netenv_hook_init( const struct netenv_config *cfg, const struct nusec_config *kc_cfg); +void netenv_hook_apply_hooks(HMODULE mod); \ No newline at end of file diff --git a/common/platform/nusec.h b/common/platform/nusec.h index 5d3dd4f..5d86f8d 100644 --- a/common/platform/nusec.h +++ b/common/platform/nusec.h @@ -14,6 +14,7 @@ struct nusec_config { uint8_t region; uint8_t system_flag; uint32_t subnet; + uint32_t bcast; uint16_t billing_type; wchar_t billing_ca[MAX_PATH]; wchar_t billing_pub[MAX_PATH]; diff --git a/common/platform/vfs.c b/common/platform/vfs.c index 97f7c13..ae5953e 100644 --- a/common/platform/vfs.c +++ b/common/platform/vfs.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include "hooklib/path.h" @@ -17,7 +18,7 @@ #include "ewf.h" #include "util/dprintf.h" -static void vfs_fixup_path(wchar_t *path, size_t max_count); +static void vfs_fixup_path(wchar_t *path, size_t max_count, bool use_relative_envvar); static HRESULT vfs_mkdir_rec(const wchar_t *path); static HRESULT vfs_path_hook(const wchar_t *src, wchar_t *dest, size_t *count); static HRESULT vfs_path_hook_nthome( @@ -90,6 +91,15 @@ static const struct reg_hook_val vfs_reg_vals[] = { static struct vfs_config vfs_config; +const wchar_t* get_vfs_relative_envvar() { + static wchar_t path[MAX_PATH]; + if (!GetEnvironmentVariableW(L"SEGATOOLS_VFS_RELATIVE_PATH", path, MAX_PATH)) { + return NULL; + } + + return path; +} + HRESULT vfs_hook_init(const struct vfs_config *config, const char* game_id) { wchar_t temp[MAX_PATH]; @@ -150,12 +160,12 @@ HRESULT vfs_hook_init(const struct vfs_config *config, const char* game_id) memcpy(&vfs_config, config, sizeof(*config)); - vfs_fixup_path(vfs_nthome_real, _countof(vfs_nthome_real)); - vfs_fixup_path(vfs_config.amfs, _countof(vfs_config.amfs)); - vfs_fixup_path(vfs_config.appdata, _countof(vfs_config.appdata)); + vfs_fixup_path(vfs_nthome_real, _countof(vfs_nthome_real), false); + vfs_fixup_path(vfs_config.amfs, _countof(vfs_config.amfs), true); + vfs_fixup_path(vfs_config.appdata, _countof(vfs_config.appdata), true); if (vfs_config.option[0] != L'\0') { - vfs_fixup_path(vfs_config.option, _countof(vfs_config.option)); + vfs_fixup_path(vfs_config.option, _countof(vfs_config.option), true); } hr = vfs_mkdir_rec(vfs_config.amfs); @@ -247,7 +257,7 @@ HRESULT vfs_hook_init(const struct vfs_config *config, const char* game_id) return S_OK; } -static void vfs_fixup_path(wchar_t *path, size_t max_count) +static void vfs_fixup_path(wchar_t *path, size_t max_count, bool use_adjustment_envvar) { size_t count; wchar_t abspath[MAX_PATH]; @@ -257,7 +267,14 @@ static void vfs_fixup_path(wchar_t *path, size_t max_count) assert(max_count <= MAX_PATH); if (PathIsRelativeW(path)) { - count = GetFullPathNameW(path, _countof(abspath), abspath, NULL); + const wchar_t* append = get_vfs_relative_envvar(); + if (append != NULL && wcslen(append) > 0 && use_adjustment_envvar) { + wchar_t temp[MAX_PATH]; + swprintf_s(temp, MAX_PATH, L"%ls\\%ls", append, path); + count = GetFullPathNameW(temp, _countof(abspath), abspath, NULL); + } else { + count = GetFullPathNameW(path, _countof(abspath), abspath, NULL); + } /* GetFullPathName's length return value is tricky, because it includes the NUL terminator on failure, but doesn't on success. diff --git a/common/unityhook/hook.c b/common/unityhook/hook.c index 0683a6a..c8b70e0 100644 --- a/common/unityhook/hook.c +++ b/common/unityhook/hook.c @@ -11,7 +11,7 @@ #include "hooklib/dll.h" #include "hooklib/path.h" -#include "hooklib/printer.h" +#include "hooklib/printer_chc.h" #include "hooklib/reg.h" #include "hooklib/touch.h" #include "hooklib/serial.h" diff --git a/common/y3io/impl/dummy/y3io.c b/common/y3io/impl/dummy/y3io.c new file mode 100644 index 0000000..c8ccdc3 --- /dev/null +++ b/common/y3io/impl/dummy/y3io.c @@ -0,0 +1,68 @@ +#include +#include + +#include "util/dprintf.h" + +#include "hooklib/y3.h" + + +uint16_t y3_io_get_api_version() { + return 0x0100; +} + +HRESULT y3_io_init() { + dprintf("Y3 Dummy Cards: initialized\n"); + return S_OK; +} + +HRESULT y3_io_close() { + return S_OK; +} + +HRESULT y3_io_get_cards(struct CardInfo* pCardInfo, int* numCards) { + memset(pCardInfo, 0, sizeof(struct CardInfo) * *numCards); + + const float paddingX = 86.0f; + const float paddingY = 54.0f; + + // Dimensions of the flat panel + const float panelHeight = 1232.0f; + const float panelWidth = 1160.0f; + + // Number of cards in each row and column + const int numRows = 4; + const int numCols = 4; + int activeCards = numRows * numCols; + + if (*numCards < activeCards) { + activeCards = *numCards; + } + *numCards = activeCards; + + + // Calculate spacing between cards + const float cardWidth = (panelWidth - paddingY * 2) / (numCols - 1); + const float cardHeight = (panelHeight - paddingX * 2) / (numRows - 1); + + // Create example card info + for (int i = 0; i < activeCards; i++) { + int row = i / numCols; + int col = i % numCols; + + pCardInfo[i].fX = paddingX + (col * cardHeight); + pCardInfo[i].fY = paddingY + (row * cardWidth); + pCardInfo[i].fAngle = 0.0f; + pCardInfo[i].eCardType = TYPE0; + pCardInfo[i].eCardStatus = VALID; + pCardInfo[i].uID = 1000 + i; + pCardInfo[i].nNumChars = 0; + pCardInfo[i].ubChar0.Data = 0; + pCardInfo[i].ubChar1.Data = 0; + pCardInfo[i].ubChar2.Data = 0; + pCardInfo[i].ubChar3.Data = 0; + pCardInfo[i].ubChar4.Data = 0; + pCardInfo[i].ubChar5.Data = 0; + } + + return S_OK; +} \ No newline at end of file diff --git a/common/y3io/impl/websockets/3rdparty/cjson/LICENSE b/common/y3io/impl/websockets/3rdparty/cjson/LICENSE new file mode 100644 index 0000000..78deb04 --- /dev/null +++ b/common/y3io/impl/websockets/3rdparty/cjson/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + +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/common/y3io/impl/websockets/3rdparty/cjson/cJSON.c b/common/y3io/impl/websockets/3rdparty/cjson/cJSON.c new file mode 100644 index 0000000..ca824f0 --- /dev/null +++ b/common/y3io/impl/websockets/3rdparty/cjson/cJSON.c @@ -0,0 +1,3191 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + 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. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 18) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + item->string = NULL; + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char *number_c_string; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + size_t number_string_length = 0; + cJSON_bool has_decimal_point = false; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_string_length++; + break; + + case '.': + number_string_length++; + has_decimal_point = true; + break; + + default: + goto loop_end; + } + } +loop_end: + /* malloc for temporary buffer, add 1 for '\0' */ + number_c_string = (unsigned char *) input_buffer->hooks.allocate(number_string_length + 1); + if (number_c_string == NULL) + { + return false; /* allocation failure */ + } + + memcpy(number_c_string, buffer_at_offset(input_buffer), number_string_length); + number_c_string[number_string_length] = '\0'; + + if (has_decimal_point) + { + for (i = 0; i < number_string_length; i++) + { + if (number_c_string[i] == '.') + { + /* replace '.' with the decimal point of the current locale (for strtod) */ + number_c_string[i] = decimal_point; + } + } + } + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + size_t v1_len; + size_t v2_len; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted or valuestring is NULL */ + if (object->valuestring == NULL || valuestring == NULL) + { + return NULL; + } + + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); + + if (v1_len <= v2_len) + { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ + if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) + { + return NULL; + } + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + output = NULL; + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + if (printed != NULL) + { + hooks->deallocate(printed); + printed = NULL; + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + p.buffer = NULL; + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + if (cannot_access_at_index(input_buffer, 1)) + { + goto fail; /* nothing comes after the comma */ + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && after_inserted->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); + +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + return cJSON_Duplicate_rec(item, 0, recurse ); +} + +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + if(depth >= CJSON_CIRCULAR_LIMIT) { + goto fail; + } + newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); + object = NULL; +} diff --git a/common/y3io/impl/websockets/3rdparty/cjson/cJSON.h b/common/y3io/impl/websockets/3rdparty/cjson/cJSON.h new file mode 100644 index 0000000..37520bb --- /dev/null +++ b/common/y3io/impl/websockets/3rdparty/cjson/cJSON.h @@ -0,0 +1,306 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 18 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* Limits the length of circular references can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_CIRCULAR_LIMIT +#define CJSON_CIRCULAR_LIMIT 10000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.c b/common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.c new file mode 100644 index 0000000..63651df --- /dev/null +++ b/common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.c @@ -0,0 +1,1481 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + 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. +*/ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUCC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUCC__ +#pragma GCC visibility pop +#endif + +#include "cJSON_Utils.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +static unsigned char* cJSONUtils_strdup(const unsigned char* const string) +{ + size_t length = 0; + unsigned char *copy = NULL; + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*) cJSON_malloc(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +/* string comparison which doesn't consider NULL pointers equal */ +static int compare_strings(const unsigned char *string1, const unsigned char *string2, const cJSON_bool case_sensitive) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + if (case_sensitive) + { + return strcmp((const char*)string1, (const char*)string2); + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + + +/* Compare the next path element of two JSON pointers, two NULL pointers are considered unequal: */ +static cJSON_bool compare_pointers(const unsigned char *name, const unsigned char *pointer, const cJSON_bool case_sensitive) +{ + if ((name == NULL) || (pointer == NULL)) + { + return false; + } + + for (; (*name != '\0') && (*pointer != '\0') && (*pointer != '/'); (void)name++, pointer++) /* compare until next '/' */ + { + if (*pointer == '~') + { + /* check for escaped '~' (~0) and '/' (~1) */ + if (((pointer[1] != '0') || (*name != '~')) && ((pointer[1] != '1') || (*name != '/'))) + { + /* invalid escape sequence or wrong character in *name */ + return false; + } + else + { + pointer++; + } + } + else if ((!case_sensitive && (tolower(*name) != tolower(*pointer))) || (case_sensitive && (*name != *pointer))) + { + return false; + } + } + if (((*pointer != 0) && (*pointer != '/')) != (*name != 0)) + { + /* one string has ended, the other not */ + return false;; + } + + return true; +} + +/* calculate the length of a string if encoded as JSON pointer with ~0 and ~1 escape sequences */ +static size_t pointer_encoded_length(const unsigned char *string) +{ + size_t length; + for (length = 0; *string != '\0'; (void)string++, length++) + { + /* character needs to be escaped? */ + if ((*string == '~') || (*string == '/')) + { + length++; + } + } + + return length; +} + +/* copy a string while escaping '~' and '/' with ~0 and ~1 JSON pointer escape codes */ +static void encode_string_as_pointer(unsigned char *destination, const unsigned char *source) +{ + for (; source[0] != '\0'; (void)source++, destination++) + { + if (source[0] == '/') + { + destination[0] = '~'; + destination[1] = '1'; + destination++; + } + else if (source[0] == '~') + { + destination[0] = '~'; + destination[1] = '0'; + destination++; + } + else + { + destination[0] = source[0]; + } + } + + destination[0] = '\0'; +} + +CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target) +{ + size_t child_index = 0; + cJSON *current_child = 0; + + if ((object == NULL) || (target == NULL)) + { + return NULL; + } + + if (object == target) + { + /* found */ + return (char*)cJSONUtils_strdup((const unsigned char*)""); + } + + /* recursively search all children of the object or array */ + for (current_child = object->child; current_child != NULL; (void)(current_child = current_child->next), child_index++) + { + unsigned char *target_pointer = (unsigned char*)cJSONUtils_FindPointerFromObjectTo(current_child, target); + /* found the target? */ + if (target_pointer != NULL) + { + if (cJSON_IsArray(object)) + { + /* reserve enough memory for a 64 bit integer + '/' and '\0' */ + unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + 20 + sizeof("/")); + /* check if conversion to unsigned long is valid + * This should be eliminated at compile time by dead code elimination + * if size_t is an alias of unsigned long, or if it is bigger */ + if (child_index > ULONG_MAX) + { + cJSON_free(target_pointer); + cJSON_free(full_pointer); + return NULL; + } + sprintf((char*)full_pointer, "/%lu%s", (unsigned long)child_index, target_pointer); /* / */ + cJSON_free(target_pointer); + + return (char*)full_pointer; + } + + if (cJSON_IsObject(object)) + { + unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + pointer_encoded_length((unsigned char*)current_child->string) + 2); + full_pointer[0] = '/'; + encode_string_as_pointer(full_pointer + 1, (unsigned char*)current_child->string); + strcat((char*)full_pointer, (char*)target_pointer); + cJSON_free(target_pointer); + + return (char*)full_pointer; + } + + /* reached leaf of the tree, found nothing */ + cJSON_free(target_pointer); + return NULL; + } + } + + /* not found */ + return NULL; +} + +/* non broken version of cJSON_GetArrayItem */ +static cJSON *get_array_item(const cJSON *array, size_t item) +{ + cJSON *child = array ? array->child : NULL; + while ((child != NULL) && (item > 0)) + { + item--; + child = child->next; + } + + return child; +} + +static cJSON_bool decode_array_index_from_pointer(const unsigned char * const pointer, size_t * const index) +{ + size_t parsed_index = 0; + size_t position = 0; + + if ((pointer[0] == '0') && ((pointer[1] != '\0') && (pointer[1] != '/'))) + { + /* leading zeroes are not permitted */ + return 0; + } + + for (position = 0; (pointer[position] >= '0') && (pointer[0] <= '9'); position++) + { + parsed_index = (10 * parsed_index) + (size_t)(pointer[position] - '0'); + + } + + if ((pointer[position] != '\0') && (pointer[position] != '/')) + { + return 0; + } + + *index = parsed_index; + + return 1; +} + +static cJSON *get_item_from_pointer(cJSON * const object, const char * pointer, const cJSON_bool case_sensitive) +{ + cJSON *current_element = object; + + if (pointer == NULL) + { + return NULL; + } + + /* follow path of the pointer */ + while ((pointer[0] == '/') && (current_element != NULL)) + { + pointer++; + if (cJSON_IsArray(current_element)) + { + size_t index = 0; + if (!decode_array_index_from_pointer((const unsigned char*)pointer, &index)) + { + return NULL; + } + + current_element = get_array_item(current_element, index); + } + else if (cJSON_IsObject(current_element)) + { + current_element = current_element->child; + /* GetObjectItem. */ + while ((current_element != NULL) && !compare_pointers((unsigned char*)current_element->string, (const unsigned char*)pointer, case_sensitive)) + { + current_element = current_element->next; + } + } + else + { + return NULL; + } + + /* skip to the next path token or end of string */ + while ((pointer[0] != '\0') && (pointer[0] != '/')) + { + pointer++; + } + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer) +{ + return get_item_from_pointer(object, pointer, false); +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer) +{ + return get_item_from_pointer(object, pointer, true); +} + +/* JSON Patch implementation. */ +static void decode_pointer_inplace(unsigned char *string) +{ + unsigned char *decoded_string = string; + + if (string == NULL) { + return; + } + + for (; *string; (void)decoded_string++, string++) + { + if (string[0] == '~') + { + if (string[1] == '0') + { + decoded_string[0] = '~'; + } + else if (string[1] == '1') + { + decoded_string[1] = '/'; + } + else + { + /* invalid escape sequence */ + return; + } + + string++; + } + } + + decoded_string[0] = '\0'; +} + +/* non-broken cJSON_DetachItemFromArray */ +static cJSON *detach_item_from_array(cJSON *array, size_t which) +{ + cJSON *c = array->child; + while (c && (which > 0)) + { + c = c->next; + which--; + } + if (!c) + { + /* item doesn't exist */ + return NULL; + } + if (c != array->child) + { + /* not the first element */ + c->prev->next = c->next; + } + if (c->next) + { + c->next->prev = c->prev; + } + if (c == array->child) + { + array->child = c->next; + } + else if (c->next == NULL) + { + array->child->prev = c->prev; + } + /* make sure the detached item doesn't point anywhere anymore */ + c->prev = c->next = NULL; + + return c; +} + +/* detach an item at the given path */ +static cJSON *detach_path(cJSON *object, const unsigned char *path, const cJSON_bool case_sensitive) +{ + unsigned char *parent_pointer = NULL; + unsigned char *child_pointer = NULL; + cJSON *parent = NULL; + cJSON *detached_item = NULL; + + /* copy path and split it in parent and child */ + parent_pointer = cJSONUtils_strdup(path); + if (parent_pointer == NULL) { + goto cleanup; + } + + child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/'); /* last '/' */ + if (child_pointer == NULL) + { + goto cleanup; + } + /* split strings */ + child_pointer[0] = '\0'; + child_pointer++; + + parent = get_item_from_pointer(object, (char*)parent_pointer, case_sensitive); + decode_pointer_inplace(child_pointer); + + if (cJSON_IsArray(parent)) + { + size_t index = 0; + if (!decode_array_index_from_pointer(child_pointer, &index)) + { + goto cleanup; + } + detached_item = detach_item_from_array(parent, index); + } + else if (cJSON_IsObject(parent)) + { + detached_item = cJSON_DetachItemFromObject(parent, (char*)child_pointer); + } + else + { + /* Couldn't find object to remove child from. */ + goto cleanup; + } + +cleanup: + if (parent_pointer != NULL) + { + cJSON_free(parent_pointer); + } + + return detached_item; +} + +/* sort lists using mergesort */ +static cJSON *sort_list(cJSON *list, const cJSON_bool case_sensitive) +{ + cJSON *first = list; + cJSON *second = list; + cJSON *current_item = list; + cJSON *result = list; + cJSON *result_tail = NULL; + + if ((list == NULL) || (list->next == NULL)) + { + /* One entry is sorted already. */ + return result; + } + + while ((current_item != NULL) && (current_item->next != NULL) && (compare_strings((unsigned char*)current_item->string, (unsigned char*)current_item->next->string, case_sensitive) < 0)) + { + /* Test for list sorted. */ + current_item = current_item->next; + } + if ((current_item == NULL) || (current_item->next == NULL)) + { + /* Leave sorted lists unmodified. */ + return result; + } + + /* reset pointer to the beginning */ + current_item = list; + while (current_item != NULL) + { + /* Walk two pointers to find the middle. */ + second = second->next; + current_item = current_item->next; + /* advances current_item two steps at a time */ + if (current_item != NULL) + { + current_item = current_item->next; + } + } + if ((second != NULL) && (second->prev != NULL)) + { + /* Split the lists */ + second->prev->next = NULL; + second->prev = NULL; + } + + /* Recursively sort the sub-lists. */ + first = sort_list(first, case_sensitive); + second = sort_list(second, case_sensitive); + result = NULL; + + /* Merge the sub-lists */ + while ((first != NULL) && (second != NULL)) + { + cJSON *smaller = NULL; + if (compare_strings((unsigned char*)first->string, (unsigned char*)second->string, case_sensitive) < 0) + { + smaller = first; + } + else + { + smaller = second; + } + + if (result == NULL) + { + /* start merged list with the smaller element */ + result_tail = smaller; + result = smaller; + } + else + { + /* add smaller element to the list */ + result_tail->next = smaller; + smaller->prev = result_tail; + result_tail = smaller; + } + + if (first == smaller) + { + first = first->next; + } + else + { + second = second->next; + } + } + + if (first != NULL) + { + /* Append rest of first list. */ + if (result == NULL) + { + return first; + } + result_tail->next = first; + first->prev = result_tail; + } + if (second != NULL) + { + /* Append rest of second list */ + if (result == NULL) + { + return second; + } + result_tail->next = second; + second->prev = result_tail; + } + + return result; +} + +static void sort_object(cJSON * const object, const cJSON_bool case_sensitive) +{ + if (object == NULL) + { + return; + } + object->child = sort_list(object->child, case_sensitive); +} + +static cJSON_bool compare_json(cJSON *a, cJSON *b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + /* mismatched type. */ + return false; + } + switch (a->type & 0xFF) + { + case cJSON_Number: + /* numeric mismatch. */ + if ((a->valueint != b->valueint) || (!compare_double(a->valuedouble, b->valuedouble))) + { + return false; + } + else + { + return true; + } + + case cJSON_String: + /* string mismatch. */ + if (strcmp(a->valuestring, b->valuestring) != 0) + { + return false; + } + else + { + return true; + } + + case cJSON_Array: + for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next) + { + cJSON_bool identical = compare_json(a, b, case_sensitive); + if (!identical) + { + return false; + } + } + + /* array size mismatch? (one of both children is not NULL) */ + if ((a != NULL) || (b != NULL)) + { + return false; + } + else + { + return true; + } + + case cJSON_Object: + sort_object(a, case_sensitive); + sort_object(b, case_sensitive); + for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next) + { + cJSON_bool identical = false; + /* compare object keys */ + if (compare_strings((unsigned char*)a->string, (unsigned char*)b->string, case_sensitive)) + { + /* missing member */ + return false; + } + identical = compare_json(a, b, case_sensitive); + if (!identical) + { + return false; + } + } + + /* object length mismatch (one of both children is not null) */ + if ((a != NULL) || (b != NULL)) + { + return false; + } + else + { + return true; + } + + default: + break; + } + + /* null, true or false */ + return true; +} + +/* non broken version of cJSON_InsertItemInArray */ +static cJSON_bool insert_item_in_array(cJSON *array, size_t which, cJSON *newitem) +{ + cJSON *child = array->child; + while (child && (which > 0)) + { + child = child->next; + which--; + } + if (which > 0) + { + /* item is after the end of the array */ + return 0; + } + if (child == NULL) + { + cJSON_AddItemToArray(array, newitem); + return 1; + } + + /* insert into the linked list */ + newitem->next = child; + newitem->prev = child->prev; + child->prev = newitem; + + /* was it at the beginning */ + if (child == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + + return 1; +} + +static cJSON *get_object_item(const cJSON * const object, const char* name, const cJSON_bool case_sensitive) +{ + if (case_sensitive) + { + return cJSON_GetObjectItemCaseSensitive(object, name); + } + + return cJSON_GetObjectItem(object, name); +} + +enum patch_operation { INVALID, ADD, REMOVE, REPLACE, MOVE, COPY, TEST }; + +static enum patch_operation decode_patch_operation(const cJSON * const patch, const cJSON_bool case_sensitive) +{ + cJSON *operation = get_object_item(patch, "op", case_sensitive); + if (!cJSON_IsString(operation)) + { + return INVALID; + } + + if (strcmp(operation->valuestring, "add") == 0) + { + return ADD; + } + + if (strcmp(operation->valuestring, "remove") == 0) + { + return REMOVE; + } + + if (strcmp(operation->valuestring, "replace") == 0) + { + return REPLACE; + } + + if (strcmp(operation->valuestring, "move") == 0) + { + return MOVE; + } + + if (strcmp(operation->valuestring, "copy") == 0) + { + return COPY; + } + + if (strcmp(operation->valuestring, "test") == 0) + { + return TEST; + } + + return INVALID; +} + +/* overwrite and existing item with another one and free resources on the way */ +static void overwrite_item(cJSON * const root, const cJSON replacement) +{ + if (root == NULL) + { + return; + } + + if (root->string != NULL) + { + cJSON_free(root->string); + } + if (root->valuestring != NULL) + { + cJSON_free(root->valuestring); + } + if (root->child != NULL) + { + cJSON_Delete(root->child); + } + + memcpy(root, &replacement, sizeof(cJSON)); +} + +static int apply_patch(cJSON *object, const cJSON *patch, const cJSON_bool case_sensitive) +{ + cJSON *path = NULL; + cJSON *value = NULL; + cJSON *parent = NULL; + enum patch_operation opcode = INVALID; + unsigned char *parent_pointer = NULL; + unsigned char *child_pointer = NULL; + int status = 0; + + path = get_object_item(patch, "path", case_sensitive); + if (!cJSON_IsString(path)) + { + /* malformed patch. */ + status = 2; + goto cleanup; + } + + opcode = decode_patch_operation(patch, case_sensitive); + if (opcode == INVALID) + { + status = 3; + goto cleanup; + } + else if (opcode == TEST) + { + /* compare value: {...} with the given path */ + status = !compare_json(get_item_from_pointer(object, path->valuestring, case_sensitive), get_object_item(patch, "value", case_sensitive), case_sensitive); + goto cleanup; + } + + /* special case for replacing the root */ + if (path->valuestring[0] == '\0') + { + if (opcode == REMOVE) + { + static const cJSON invalid = { NULL, NULL, NULL, cJSON_Invalid, NULL, 0, 0, NULL}; + + overwrite_item(object, invalid); + + status = 0; + goto cleanup; + } + + if ((opcode == REPLACE) || (opcode == ADD)) + { + value = get_object_item(patch, "value", case_sensitive); + if (value == NULL) + { + /* missing "value" for add/replace. */ + status = 7; + goto cleanup; + } + + value = cJSON_Duplicate(value, 1); + if (value == NULL) + { + /* out of memory for add/replace. */ + status = 8; + goto cleanup; + } + + overwrite_item(object, *value); + + /* delete the duplicated value */ + cJSON_free(value); + value = NULL; + + /* the string "value" isn't needed */ + if (object->string != NULL) + { + cJSON_free(object->string); + object->string = NULL; + } + + status = 0; + goto cleanup; + } + } + + if ((opcode == REMOVE) || (opcode == REPLACE)) + { + /* Get rid of old. */ + cJSON *old_item = detach_path(object, (unsigned char*)path->valuestring, case_sensitive); + if (old_item == NULL) + { + status = 13; + goto cleanup; + } + cJSON_Delete(old_item); + if (opcode == REMOVE) + { + /* For Remove, this job is done. */ + status = 0; + goto cleanup; + } + } + + /* Copy/Move uses "from". */ + if ((opcode == MOVE) || (opcode == COPY)) + { + cJSON *from = get_object_item(patch, "from", case_sensitive); + if (from == NULL) + { + /* missing "from" for copy/move. */ + status = 4; + goto cleanup; + } + + if (opcode == MOVE) + { + value = detach_path(object, (unsigned char*)from->valuestring, case_sensitive); + } + if (opcode == COPY) + { + value = get_item_from_pointer(object, from->valuestring, case_sensitive); + } + if (value == NULL) + { + /* missing "from" for copy/move. */ + status = 5; + goto cleanup; + } + if (opcode == COPY) + { + value = cJSON_Duplicate(value, 1); + } + if (value == NULL) + { + /* out of memory for copy/move. */ + status = 6; + goto cleanup; + } + } + else /* Add/Replace uses "value". */ + { + value = get_object_item(patch, "value", case_sensitive); + if (value == NULL) + { + /* missing "value" for add/replace. */ + status = 7; + goto cleanup; + } + value = cJSON_Duplicate(value, 1); + if (value == NULL) + { + /* out of memory for add/replace. */ + status = 8; + goto cleanup; + } + } + + /* Now, just add "value" to "path". */ + + /* split pointer in parent and child */ + parent_pointer = cJSONUtils_strdup((unsigned char*)path->valuestring); + if (parent_pointer) { + child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/'); + } + if (child_pointer != NULL) + { + child_pointer[0] = '\0'; + child_pointer++; + } + parent = get_item_from_pointer(object, (char*)parent_pointer, case_sensitive); + decode_pointer_inplace(child_pointer); + + /* add, remove, replace, move, copy, test. */ + if ((parent == NULL) || (child_pointer == NULL)) + { + /* Couldn't find object to add to. */ + status = 9; + goto cleanup; + } + else if (cJSON_IsArray(parent)) + { + if (strcmp((char*)child_pointer, "-") == 0) + { + cJSON_AddItemToArray(parent, value); + value = NULL; + } + else + { + size_t index = 0; + if (!decode_array_index_from_pointer(child_pointer, &index)) + { + status = 11; + goto cleanup; + } + + if (!insert_item_in_array(parent, index, value)) + { + status = 10; + goto cleanup; + } + value = NULL; + } + } + else if (cJSON_IsObject(parent)) + { + if (case_sensitive) + { + cJSON_DeleteItemFromObjectCaseSensitive(parent, (char*)child_pointer); + } + else + { + cJSON_DeleteItemFromObject(parent, (char*)child_pointer); + } + cJSON_AddItemToObject(parent, (char*)child_pointer, value); + value = NULL; + } + else /* parent is not an object */ + { + /* Couldn't find object to add to. */ + status = 9; + goto cleanup; + } + +cleanup: + if (value != NULL) + { + cJSON_Delete(value); + } + if (parent_pointer != NULL) + { + cJSON_free(parent_pointer); + } + + return status; +} + +CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches) +{ + const cJSON *current_patch = NULL; + int status = 0; + + if (!cJSON_IsArray(patches)) + { + /* malformed patches. */ + return 1; + } + + if (patches != NULL) + { + current_patch = patches->child; + } + + while (current_patch != NULL) + { + status = apply_patch(object, current_patch, false); + if (status != 0) + { + return status; + } + current_patch = current_patch->next; + } + + return 0; +} + +CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches) +{ + const cJSON *current_patch = NULL; + int status = 0; + + if (!cJSON_IsArray(patches)) + { + /* malformed patches. */ + return 1; + } + + if (patches != NULL) + { + current_patch = patches->child; + } + + while (current_patch != NULL) + { + status = apply_patch(object, current_patch, true); + if (status != 0) + { + return status; + } + current_patch = current_patch->next; + } + + return 0; +} + +static void compose_patch(cJSON * const patches, const unsigned char * const operation, const unsigned char * const path, const unsigned char *suffix, const cJSON * const value) +{ + cJSON *patch = NULL; + + if ((patches == NULL) || (operation == NULL) || (path == NULL)) + { + return; + } + + patch = cJSON_CreateObject(); + if (patch == NULL) + { + return; + } + cJSON_AddItemToObject(patch, "op", cJSON_CreateString((const char*)operation)); + + if (suffix == NULL) + { + cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)path)); + } + else + { + size_t suffix_length = pointer_encoded_length(suffix); + size_t path_length = strlen((const char*)path); + unsigned char *full_path = (unsigned char*)cJSON_malloc(path_length + suffix_length + sizeof("/")); + + sprintf((char*)full_path, "%s/", (const char*)path); + encode_string_as_pointer(full_path + path_length + 1, suffix); + + cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)full_path)); + cJSON_free(full_path); + } + + if (value != NULL) + { + cJSON_AddItemToObject(patch, "value", cJSON_Duplicate(value, 1)); + } + cJSON_AddItemToArray(patches, patch); +} + +CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value) +{ + compose_patch(array, (const unsigned char*)operation, (const unsigned char*)path, NULL, value); +} + +static void create_patches(cJSON * const patches, const unsigned char * const path, cJSON * const from, cJSON * const to, const cJSON_bool case_sensitive) +{ + if ((from == NULL) || (to == NULL)) + { + return; + } + + if ((from->type & 0xFF) != (to->type & 0xFF)) + { + compose_patch(patches, (const unsigned char*)"replace", path, 0, to); + return; + } + + switch (from->type & 0xFF) + { + case cJSON_Number: + if ((from->valueint != to->valueint) || !compare_double(from->valuedouble, to->valuedouble)) + { + compose_patch(patches, (const unsigned char*)"replace", path, NULL, to); + } + return; + + case cJSON_String: + if (strcmp(from->valuestring, to->valuestring) != 0) + { + compose_patch(patches, (const unsigned char*)"replace", path, NULL, to); + } + return; + + case cJSON_Array: + { + size_t index = 0; + cJSON *from_child = from->child; + cJSON *to_child = to->child; + unsigned char *new_path = (unsigned char*)cJSON_malloc(strlen((const char*)path) + 20 + sizeof("/")); /* Allow space for 64bit int. log10(2^64) = 20 */ + + /* generate patches for all array elements that exist in both "from" and "to" */ + for (index = 0; (from_child != NULL) && (to_child != NULL); (void)(from_child = from_child->next), (void)(to_child = to_child->next), index++) + { + /* check if conversion to unsigned long is valid + * This should be eliminated at compile time by dead code elimination + * if size_t is an alias of unsigned long, or if it is bigger */ + if (index > ULONG_MAX) + { + cJSON_free(new_path); + return; + } + sprintf((char*)new_path, "%s/%lu", path, (unsigned long)index); /* path of the current array element */ + create_patches(patches, new_path, from_child, to_child, case_sensitive); + } + + /* remove leftover elements from 'from' that are not in 'to' */ + for (; (from_child != NULL); (void)(from_child = from_child->next)) + { + /* check if conversion to unsigned long is valid + * This should be eliminated at compile time by dead code elimination + * if size_t is an alias of unsigned long, or if it is bigger */ + if (index > ULONG_MAX) + { + cJSON_free(new_path); + return; + } + sprintf((char*)new_path, "%lu", (unsigned long)index); + compose_patch(patches, (const unsigned char*)"remove", path, new_path, NULL); + } + /* add new elements in 'to' that were not in 'from' */ + for (; (to_child != NULL); (void)(to_child = to_child->next), index++) + { + compose_patch(patches, (const unsigned char*)"add", path, (const unsigned char*)"-", to_child); + } + cJSON_free(new_path); + return; + } + + case cJSON_Object: + { + cJSON *from_child = NULL; + cJSON *to_child = NULL; + sort_object(from, case_sensitive); + sort_object(to, case_sensitive); + + from_child = from->child; + to_child = to->child; + /* for all object values in the object with more of them */ + while ((from_child != NULL) || (to_child != NULL)) + { + int diff; + if (from_child == NULL) + { + diff = 1; + } + else if (to_child == NULL) + { + diff = -1; + } + else + { + diff = compare_strings((unsigned char*)from_child->string, (unsigned char*)to_child->string, case_sensitive); + } + + if (diff == 0) + { + /* both object keys are the same */ + size_t path_length = strlen((const char*)path); + size_t from_child_name_length = pointer_encoded_length((unsigned char*)from_child->string); + unsigned char *new_path = (unsigned char*)cJSON_malloc(path_length + from_child_name_length + sizeof("/")); + + sprintf((char*)new_path, "%s/", path); + encode_string_as_pointer(new_path + path_length + 1, (unsigned char*)from_child->string); + + /* create a patch for the element */ + create_patches(patches, new_path, from_child, to_child, case_sensitive); + cJSON_free(new_path); + + from_child = from_child->next; + to_child = to_child->next; + } + else if (diff < 0) + { + /* object element doesn't exist in 'to' --> remove it */ + compose_patch(patches, (const unsigned char*)"remove", path, (unsigned char*)from_child->string, NULL); + + from_child = from_child->next; + } + else + { + /* object element doesn't exist in 'from' --> add it */ + compose_patch(patches, (const unsigned char*)"add", path, (unsigned char*)to_child->string, to_child); + + to_child = to_child->next; + } + } + return; + } + + default: + break; + } +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to) +{ + cJSON *patches = NULL; + + if ((from == NULL) || (to == NULL)) + { + return NULL; + } + + patches = cJSON_CreateArray(); + create_patches(patches, (const unsigned char*)"", from, to, false); + + return patches; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to) +{ + cJSON *patches = NULL; + + if ((from == NULL) || (to == NULL)) + { + return NULL; + } + + patches = cJSON_CreateArray(); + create_patches(patches, (const unsigned char*)"", from, to, true); + + return patches; +} + +CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object) +{ + sort_object(object, false); +} + +CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object) +{ + sort_object(object, true); +} + +static cJSON *merge_patch(cJSON *target, const cJSON * const patch, const cJSON_bool case_sensitive) +{ + cJSON *patch_child = NULL; + + if (!cJSON_IsObject(patch)) + { + /* scalar value, array or NULL, just duplicate */ + cJSON_Delete(target); + return cJSON_Duplicate(patch, 1); + } + + if (!cJSON_IsObject(target)) + { + cJSON_Delete(target); + target = cJSON_CreateObject(); + } + + patch_child = patch->child; + while (patch_child != NULL) + { + if (cJSON_IsNull(patch_child)) + { + /* NULL is the indicator to remove a value, see RFC7396 */ + if (case_sensitive) + { + cJSON_DeleteItemFromObjectCaseSensitive(target, patch_child->string); + } + else + { + cJSON_DeleteItemFromObject(target, patch_child->string); + } + } + else + { + cJSON *replace_me = NULL; + cJSON *replacement = NULL; + + if (case_sensitive) + { + replace_me = cJSON_DetachItemFromObjectCaseSensitive(target, patch_child->string); + } + else + { + replace_me = cJSON_DetachItemFromObject(target, patch_child->string); + } + + replacement = merge_patch(replace_me, patch_child, case_sensitive); + if (replacement == NULL) + { + cJSON_Delete(target); + return NULL; + } + + cJSON_AddItemToObject(target, patch_child->string, replacement); + } + patch_child = patch_child->next; + } + return target; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch) +{ + return merge_patch(target, patch, false); +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch) +{ + return merge_patch(target, patch, true); +} + +static cJSON *generate_merge_patch(cJSON * const from, cJSON * const to, const cJSON_bool case_sensitive) +{ + cJSON *from_child = NULL; + cJSON *to_child = NULL; + cJSON *patch = NULL; + if (to == NULL) + { + /* patch to delete everything */ + return cJSON_CreateNull(); + } + if (!cJSON_IsObject(to) || !cJSON_IsObject(from)) + { + return cJSON_Duplicate(to, 1); + } + + sort_object(from, case_sensitive); + sort_object(to, case_sensitive); + + from_child = from->child; + to_child = to->child; + patch = cJSON_CreateObject(); + if (patch == NULL) + { + return NULL; + } + while (from_child || to_child) + { + int diff; + if (from_child != NULL) + { + if (to_child != NULL) + { + diff = strcmp(from_child->string, to_child->string); + } + else + { + diff = -1; + } + } + else + { + diff = 1; + } + + if (diff < 0) + { + /* from has a value that to doesn't have -> remove */ + cJSON_AddItemToObject(patch, from_child->string, cJSON_CreateNull()); + + from_child = from_child->next; + } + else if (diff > 0) + { + /* to has a value that from doesn't have -> add to patch */ + cJSON_AddItemToObject(patch, to_child->string, cJSON_Duplicate(to_child, 1)); + + to_child = to_child->next; + } + else + { + /* object key exists in both objects */ + if (!compare_json(from_child, to_child, case_sensitive)) + { + /* not identical --> generate a patch */ + cJSON_AddItemToObject(patch, to_child->string, cJSONUtils_GenerateMergePatch(from_child, to_child)); + } + + /* next key in the object */ + from_child = from_child->next; + to_child = to_child->next; + } + } + if (patch->child == NULL) + { + /* no patch generated */ + cJSON_Delete(patch); + return NULL; + } + + return patch; +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to) +{ + return generate_merge_patch(from, to, false); +} + +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to) +{ + return generate_merge_patch(from, to, true); +} diff --git a/common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.h b/common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.h new file mode 100644 index 0000000..a970c65 --- /dev/null +++ b/common/y3io/impl/websockets/3rdparty/cjson/cJSON_Utils.h @@ -0,0 +1,88 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON_Utils__h +#define cJSON_Utils__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "cJSON.h" + +/* Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. */ +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer); +CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer); + +/* Implement RFC6902 (https://tools.ietf.org/html/rfc6902) JSON Patch spec. */ +/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */ +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to); +CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to); +/* Utility for generating patch array entries. */ +CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value); +/* Returns 0 for success. */ +CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches); +CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches); + +/* +// Note that ApplyPatches is NOT atomic on failure. To implement an atomic ApplyPatches, use: +//int cJSONUtils_AtomicApplyPatches(cJSON **object, cJSON *patches) +//{ +// cJSON *modme = cJSON_Duplicate(*object, 1); +// int error = cJSONUtils_ApplyPatches(modme, patches); +// if (!error) +// { +// cJSON_Delete(*object); +// *object = modme; +// } +// else +// { +// cJSON_Delete(modme); +// } +// +// return error; +//} +// Code not added to library since this strategy is a LOT slower. +*/ + +/* Implement RFC7386 (https://tools.ietf.org/html/rfc7396) JSON Merge Patch spec. */ +/* target will be modified by patch. return value is new ptr for target. */ +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch); +CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch); +/* generates a patch to move from -> to */ +/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */ +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to); +CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to); + +/* Given a root object and a target object, construct a pointer from one to the other. */ +CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target); + +/* Sorts the members of the object into alphabetical order. */ +CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object); +CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/y3io/impl/websockets/config.c b/common/y3io/impl/websockets/config.c new file mode 100644 index 0000000..84f0127 --- /dev/null +++ b/common/y3io/impl/websockets/config.c @@ -0,0 +1,39 @@ +#include + +#include +#include +#include +#include + +#include "config.h" + +void y3ws_config_load(struct y3ws_config *cfg, const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + cfg->enable = GetPrivateProfileIntW(L"y3ws", L"enable", 1, filename); + cfg->debug = GetPrivateProfileIntW(L"y3ws", L"debug", 0, filename); + + cfg->port = GetPrivateProfileIntW(L"y3ws", L"port", 3594, filename); + + wchar_t tmpstr[16]; + + GetPrivateProfileStringW( + L"y3ws", + L"gameId", + L"SDEY", + tmpstr, + _countof(tmpstr), + filename); + + wcstombs(cfg->game_id, tmpstr, sizeof(cfg->game_id)); + + GetPrivateProfileStringW( + L"y3ws", + L"cardDirectory", + L"DEVICE\\print", + cfg->card_path, + _countof(cfg->card_path), + filename); +} diff --git a/common/y3io/impl/websockets/config.h b/common/y3io/impl/websockets/config.h new file mode 100644 index 0000000..91ad18f --- /dev/null +++ b/common/y3io/impl/websockets/config.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +#include "hooklib/dvd.h" +#include "hooklib/touch.h" +#include "hooklib/printer_chc.h" +#include "hooklib/printer_cx.h" + +struct y3ws_config { + bool enable; + bool debug; + + uint16_t port; + char game_id[5]; + wchar_t card_path[MAX_PATH]; +}; + +void y3ws_config_load(struct y3ws_config *cfg, const wchar_t *filename); \ No newline at end of file diff --git a/common/y3io/impl/websockets/y3ws.c b/common/y3io/impl/websockets/y3ws.c new file mode 100644 index 0000000..318f8aa --- /dev/null +++ b/common/y3io/impl/websockets/y3ws.c @@ -0,0 +1,354 @@ +#include +#include +#include +#include +#include +#include + +#include "3rdparty/cjson/cJSON.h" + +#include "config.h" +#include "y3ws.h" + +#include + +#include "hooklib/y3.h" + +#include "winwebsocket.h" +#include "lib/base64.h" + +#include "util/dprintf.h" +#include "util/env.h" + +static void onopen(struct wws_connection*); +static void onclose(struct wws_connection*); +static void onmessage(struct wws_connection*, const char*, size_t); +static void onlog(const char*, ...); + +#define PROTOCOL_VERSION 1 +#define GAME_MAX_CARDS 32 +#define MAX_CARDS 500 +#define CARD_ID_LEN 5 +#define OUTPUT_BUFFER_SIZE (1024 * 1024 * 5) + +static struct y3ws_config cfg; + +static bool is_initialized = false; +static struct CardInfo card_info[GAME_MAX_CARDS]; +static int card_info_size = 0; +static CRITICAL_SECTION card_info_lock; + +#pragma region y3-dll functions +uint16_t y3_io_get_api_version() { + return 0x0100; +} + +HRESULT y3_io_init() { + if (is_initialized) { + return S_FALSE; + } + + y3ws_config_load(&cfg, get_config_path()); + + memset(card_info, 0, sizeof(card_info)); + InitializeCriticalSection(&card_info_lock); + + wws_set_callbacks(onopen, onclose, onmessage, onlog); + wws_set_verbose(cfg.debug); + + HRESULT hr = wws_start(cfg.port); + + if (SUCCEEDED(hr)) { + dprintf("Y3WS: Started server on port %d\n", cfg.port); + if (cfg.debug) { + dprintf("Y3WS: WS debug logging is on\n"); + } + is_initialized = true; + } else { + dprintf("Y3WS: Error starting server: %lx\n", hr); + } + + return hr; +} + +HRESULT y3_io_close() { + + HRESULT hr = wws_stop(); + + DeleteCriticalSection(&card_info_lock); + + is_initialized = false; + + return hr; +} + +HRESULT y3_io_get_cards(struct CardInfo* pCardInfo, int* numCards) { + EnterCriticalSection(&card_info_lock); + for (int i = 0; i < card_info_size; i++) { + memcpy(&pCardInfo[i], &card_info[i], sizeof(struct CardInfo)); + } + *numCards = card_info_size; + LeaveCriticalSection(&card_info_lock); + return S_OK; +} +#pragma endregion + +#pragma region y3ws functions +static void y3ws_make_error_packet(const char* message, char* output_data, size_t* output_size) { + dprintf("Y3WS: Error: %s\n", message); + *output_size = sprintf_s((char*)output_data, *output_size, "{\"version\":%d, \"success\":false,\"error\":\"%s\"}", PROTOCOL_VERSION, message); +} + +static void y3ws_make_success_packet(char* output_data, size_t* output_size) { + *output_size = sprintf_s((char*)output_data, *output_size, "{\"version\":%d, \"success\":true}", PROTOCOL_VERSION); +} + +static void y3ws_read_cards(char* output_data, size_t* output_size) { + WIN32_FIND_DATAW ffd; + + wchar_t path[MAX_PATH]; + swprintf(path, MAX_PATH, L"%ls\\*", cfg.card_path); + + HANDLE hFind = FindFirstFileW(path, &ffd); + if (INVALID_HANDLE_VALUE == hFind) { + dprintf("Y3WS: Failed to access directory: %ls (%ld)\n", path, GetLastError()); + y3ws_make_error_packet("Could not read from card directory", output_data, output_size); + return; + } + + cJSON* response = cJSON_CreateObject(); + cJSON* pversion = cJSON_CreateNumber(PROTOCOL_VERSION); + cJSON_AddItemToObject(response, "version", pversion); + cJSON* success = cJSON_CreateBool(true); + cJSON_AddItemToObject(response, "success", success); + cJSON* cards = cJSON_CreateArray(); + cJSON_AddItemToObject(response, "cards", cards); + + int count = 0; + do { + if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + continue; + } + + swprintf(path, MAX_PATH, L"%ls\\%ls", cfg.card_path, ffd.cFileName); + + HANDLE hImage = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hImage == INVALID_HANDLE_VALUE) { + dprintf("Y3WS: Error opening %ls: %ld\n", path, GetLastError()); + continue; + } + DWORD ret = SetFilePointer(hImage, -CARD_ID_LEN, NULL, FILE_END); + if (ret == INVALID_SET_FILE_POINTER) { + dprintf("Y3WS: Error seeking in %ls: %ld\n", path, GetLastError()); + continue; + } + uint8_t buf[CARD_ID_LEN]; + DWORD bytesRead = 0; + if (!ReadFile(hImage, &buf, CARD_ID_LEN, &bytesRead, NULL) || bytesRead != CARD_ID_LEN) { + dprintf("Y3WS: Error reading card ID from %ls: %ld\n", path, GetLastError()); + continue; + } + + cJSON* card = cJSON_CreateObject(); + cJSON_AddItemToArray(cards, card); + + // cJSON isn't wide... + char fpatha[MAX_PATH]; + size_t fpatha_len = 0; + wcstombs_s(&fpatha_len, fpatha, MAX_PATH, ffd.cFileName, MAX_PATH); + fpatha[fpatha_len] = 0; + + // ReSharper disable once CppRedundantCastExpression + cJSON* path_str = cJSON_CreateString(fpatha); + cJSON_AddItemToObject(card, "path", path_str); + cJSON* card_id = cJSON_CreateNumber((double)((uint64_t)buf[0] >> 32 | (uint64_t)buf[1] >> 24 | (uint64_t)buf[2] >> 16 | (uint64_t)buf[3] >> 8 | buf[4])); + cJSON_AddItemToObject(card, "card_id", card_id); + + } while (FindNextFileW(hFind, &ffd) != 0 && count++ < MAX_CARDS); + + cJSON_PrintPreallocated(response, output_data, (int)*output_size, false); + *output_size = strlen(output_data); + + dprintf("Y3WS: Sent %d card(s) to the client\n", count); + + cJSON_Delete(response); + FindClose(hFind); +} + +static void y3ws_read_card_image(char* file_name, char* output_data, size_t* output_size) { + wchar_t path[MAX_PATH]; + swprintf(path, MAX_PATH, L"%ls\\%hs", cfg.card_path, file_name); + + HANDLE hImage = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hImage == INVALID_HANDLE_VALUE) { + dprintf("Y3WS: Failed to access file: %ls (%ld)\n", path, GetLastError()); + y3ws_make_error_packet("Could not read file", output_data, output_size); + return; + } + + DWORD size = GetFileSize(hImage, NULL); + if (size == INVALID_FILE_SIZE) { + dprintf("Y3WS: Failed to access file size: %ls (%ld)\n", path, GetLastError()); + y3ws_make_error_packet("Could not read file", output_data, output_size); + return; + } + + uint8_t* buf = malloc(size); + size_t b64size = ((size * 4) / 3) + (size / 96) + 6; + char* b64buf = malloc(b64size); + if (buf == NULL) { + dprintf("Y3WS: Allocation error for file: %ls (%ld)\n", path, GetLastError()); + y3ws_make_error_packet("Could not read file", output_data, output_size); + goto end; + } + + DWORD bytesRead = 0; + if (!ReadFile(hImage, buf, size, &bytesRead, NULL) || bytesRead != size) { + dprintf("Y3WS: File read failed: %ls (%ld)\n", path, GetLastError()); + y3ws_make_error_packet("Could not read file", output_data, output_size); + goto end; + } + + b64size = base64_encode(buf, size, b64buf); + + if (b64size + 100 > *output_size) { + dprintf("Y3WS: Encoded file size exceeds buffer: %ls (%llu / %llu)\n", path, (uint64_t) b64size, (uint64_t) *output_size); + y3ws_make_error_packet("File too large", output_data, output_size); + } + + *output_size = sprintf_s((char*)output_data, *output_size, "{\"version\":%d, \"success\":true,\"data\":\"%s\"}", PROTOCOL_VERSION, (char*)b64buf); +end: + free(buf); + free(b64buf); +} + +static void y3ws_set_cards_from_json(const cJSON* cards, char* output_data, size_t* output_size) { + + const cJSON* card = NULL; + card_info_size = 0; + + EnterCriticalSection(&card_info_lock); + memset(card_info, 0, sizeof(card_info)); + cJSON_ArrayForEach(card, cards) { + cJSON* x = cJSON_GetObjectItemCaseSensitive(card, "x"); + cJSON* y = cJSON_GetObjectItemCaseSensitive(card, "y"); + cJSON* r = cJSON_GetObjectItemCaseSensitive(card, "rotation"); + cJSON* id = cJSON_GetObjectItemCaseSensitive(card, "card_id"); + + if (cJSON_IsNumber(x) && cJSON_IsNumber(y) && cJSON_IsNumber(r) && cJSON_IsNumber(id)) { + card_info[card_info_size].eCardStatus = VALID; + card_info[card_info_size].fX = (float)x->valuedouble; + card_info[card_info_size].fY = (float)y->valuedouble; + card_info[card_info_size].fAngle = (float)r->valuedouble; + card_info[card_info_size].uID = id->valueint; + } else { + dprintf("Y3WS: Invalid object in card array at index %d\n", card_info_size); + } + + if (++card_info_size >= GAME_MAX_CARDS) { + dprintf("Y3WS: too many cards specified, truncating!\n"); + break; + } + + } + LeaveCriticalSection(&card_info_lock); + y3ws_make_success_packet(output_data, output_size); +} + +static void y3ws_handle(const char* input_data, uint32_t input_length, char* output_data, size_t* output_size) { + cJSON* json = cJSON_ParseWithLength(input_data, input_length); + if (json == NULL) { + const char *error_ptr = cJSON_GetErrorPtr(); + + dprintf("Y3WS: Invalid JSON received!\n"); + dprintf("Y3WS: Message was: %s\n", input_data); + dprintf("Y3WS: Error at: %s\n", error_ptr); + y3ws_make_error_packet("Invalid JSON", output_data, output_size); + goto end; + } + + const cJSON* ver = cJSON_GetObjectItemCaseSensitive(json, "version"); + const cJSON* cmd = cJSON_GetObjectItemCaseSensitive(json, "command"); + + if (!cJSON_IsNumber(ver) || ver->valueint <= 0) { + y3ws_make_error_packet("Missing version attribute", output_data, output_size); + goto end; + } + if (!cJSON_IsString(cmd)) { + y3ws_make_error_packet("Missing command attribute", output_data, output_size); + goto end; + } + if (ver->valueint != PROTOCOL_VERSION) { + y3ws_make_error_packet("Incompatible version", output_data, output_size); + goto end; + } + + if (strcmp(cmd->valuestring, "ping") == 0) { + y3ws_make_success_packet(output_data, output_size); + } else if (strcmp(cmd->valuestring, "get_game_id") == 0) { + *output_size = sprintf_s((char*)output_data, *output_size, "{\"version\":%d, \"success\":true,\"game_id\":\"%s\"}", PROTOCOL_VERSION, cfg.game_id); + } else if (strcmp(cmd->valuestring, "get_cards") == 0) { + y3ws_read_cards(output_data, output_size); + } else if (strcmp(cmd->valuestring, "get_card_image") == 0) { + const cJSON* path = cJSON_GetObjectItemCaseSensitive(json, "path"); + if (cJSON_IsString(path)) { + y3ws_read_card_image(path->valuestring, output_data, output_size); + } else { + y3ws_make_error_packet("Missing attribute", output_data, output_size); + } + } else if (strcmp(cmd->valuestring, "set_field") == 0) { + const cJSON* cards = cJSON_GetObjectItemCaseSensitive(json, "cards"); + if (cJSON_IsArray(cards)) { + y3ws_set_cards_from_json(cards, output_data, output_size); + } else { + y3ws_make_error_packet("Missing attribute", output_data, output_size); + } + } else { + y3ws_make_error_packet("Unknown command", output_data, output_size); + } + +end: + cJSON_Delete(json); +} +#pragma endregion + +#pragma region websocket callbacks + +static void onopen(struct wws_connection* client) { + dprintf("Y3WS: Connection opened, addr: %s\n", client->ip_str); +} + +static void onclose(struct wws_connection* client) { + dprintf("Y3WS: Connection closed, addr: %s\n", client->ip_str); +} + +static void onmessage(struct wws_connection* client, const char* msg, size_t size) { + if (cfg.debug) { + dprintf("Y3WS: Message: %.*s\n", (int)size, msg); + } + char* out_buf = malloc(OUTPUT_BUFFER_SIZE); + if (out_buf == NULL) { + dprintf("Y3WS: out of memory for allocating response buffer\n"); + client->is_connected = false; + return; + } + size_t out_size = OUTPUT_BUFFER_SIZE; + + y3ws_handle(msg, size, out_buf, &out_size); + HRESULT hr = wws_send(client, out_buf, out_size); + if (!SUCCEEDED(hr)) { + dprintf("Y3WS: Error sending message: %lx\n", hr); + } + + free(out_buf); +} + +static void onlog(const char* format, ...) { + va_list args; + va_start (args, format); + dprintf("Websocket: "); + dprintfv(format, args); + va_end (args); +} + +#pragma endregion \ No newline at end of file diff --git a/common/y3io/impl/websockets/y3ws.h b/common/y3io/impl/websockets/y3ws.h new file mode 100644 index 0000000..0b88e80 --- /dev/null +++ b/common/y3io/impl/websockets/y3ws.h @@ -0,0 +1,4 @@ +#pragma once + +#include +#include \ No newline at end of file diff --git a/common/y3io/impl/y3io.h b/common/y3io/impl/y3io.h new file mode 100644 index 0000000..24fe971 --- /dev/null +++ b/common/y3io/impl/y3io.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +#include "hooklib/y3.h" + +/* Get the version of the Y3 IO API that this DLL supports. This + function should return a positive 16-bit integer, where the high byte is + the major version and the low byte is the minor version (as defined by the + Semantic Versioning standard). + + The latest API version as of this writing is 0x0100. */ +uint16_t y3_io_get_api_version(); + +/* Initialize the Y3 board. This function will be called before any other + y3_io_*() function calls. Errors returned from this function will + manifest as a disconnected Y3 board. + + This method may be called multiple times. + + Minimum API version: 0x0100 */ +HRESULT y3_io_init(); + +/* Fills the given buffer with cards that are detected on the play field. + For the values inside CardInfo, see y3.h. + The input value of numCards is the size of the pCardInfo array. + The output value of numCards is how many cards (>=0) have been set in pCardInfo. + + Minimum API version: 0x0100 */ +HRESULT y3_io_get_cards(struct CardInfo* pCardInfo, int* numCards); \ No newline at end of file diff --git a/common/y3io/meson.build b/common/y3io/meson.build new file mode 100644 index 0000000..c998949 --- /dev/null +++ b/common/y3io/meson.build @@ -0,0 +1,25 @@ +y3io_lib = static_library( + 'y3io', + name_prefix : '', + include_directories: inc, + implicit_include_directories : false, + dependencies : [ + capnhook.get_variable('hook_dep'), + capnhook.get_variable('hooklib_dep'), + cwinwebsocket.get_variable('cws_dep'), + ], + link_with : [ + util_lib, + ], + sources : [ + 'impl/websockets/config.c', + 'impl/websockets/config.h', + 'impl/websockets/y3ws.c', + 'impl/websockets/y3ws.h', + 'impl/websockets/3rdparty/cjson/cJSON.c', + 'impl/websockets/3rdparty/cjson/cJSON.h', + 'impl/websockets/3rdparty/cjson/cJSON_Utils.c', + 'impl/websockets/3rdparty/cjson/cJSON_Utils.h', + 'impl/y3io.h', + ], +) diff --git a/dist/ekt/card_player.html b/dist/ekt/card_player.html new file mode 100644 index 0000000..a92696d --- /dev/null +++ b/dist/ekt/card_player.html @@ -0,0 +1,224 @@ + + + + + Taisen Card Field + + + + + +
+ +
+
+
Please wait...
+
+ +
+
+ + \ No newline at end of file diff --git a/dist/ekt/config_hook.json b/dist/ekt/config_hook.json new file mode 100644 index 0000000..6319f45 --- /dev/null +++ b/dist/ekt/config_hook.json @@ -0,0 +1,13 @@ +{ + "common": { + "language": "english" + }, + "network": { + "property": { + "dhcp": true + } + }, + "allnet_auth": { + "type": "1.0" + } +} \ No newline at end of file diff --git a/dist/ekt/launch_satellite.bat b/dist/ekt/launch_satellite.bat new file mode 100644 index 0000000..aa4249d --- /dev/null +++ b/dist/ekt/launch_satellite.bat @@ -0,0 +1,24 @@ +@echo off +set SEGATOOLS_CONFIG_PATH=.\segatools_satellite.ini + +set SEGATOOLS_VFS_RELATIVE_PATH=..\..\exe +set SEGATOOLS_CONFIG_PATH=%SEGATOOLS_VFS_RELATIVE_PATH%\%SEGATOOLS_CONFIG_PATH% + +pushd ..\PackageBase\am_capture +start "AM Capture" /min %SEGATOOLS_VFS_RELATIVE_PATH%\inject_x86.exe -d -k %SEGATOOLS_VFS_RELATIVE_PATH%\ekthook_x86.dll AmCapture.exe +popd + +set SEGATOOLS_CONFIG_PATH=.\segatools_satellite.ini +set SEGATOOLS_VFS_RELATIVE_PATH= + +pushd %~dp0 +start "AM Daemon" /min inject_x64.exe -d -k ekthook_x64.dll ..\PackageBase\amdaemon.exe -c ..\PackageBase\config_sate.json config_hook.json + +inject_x64 -d -k ekthook_x64.dll ekt.exe -logfile satellite.log -screen-fullscreen 1 -screen-width 1920 -screen-height 1080 -screen-quality Ultra -silent-crashes + +taskkill /f /im AmCapture.exe > nul 2>&1 +taskkill /f /im amdaemon.exe > nul 2>&1 + +echo. +echo Game processes have terminated +pause \ No newline at end of file diff --git a/dist/ekt/launch_terminal.bat b/dist/ekt/launch_terminal.bat new file mode 100644 index 0000000..63d0ea8 --- /dev/null +++ b/dist/ekt/launch_terminal.bat @@ -0,0 +1,13 @@ +@echo off +set SEGATOOLS_CONFIG_PATH=.\segatools_terminal.ini + +pushd %~dp0 + +start "AM Daemon" /min inject_x64 -d -k ekthook_x64.dll ..\PackageBase\amdaemon.exe -c ..\PackageBase\config_terminal.json config_hook.json +inject_x64 -d -k ekthook_x64.dll ekt.exe -terminal -logfile terminal.log -screen-fullscreen 1 -screen-width 1920 -screen-height 1080 -screen-quality Ultra -silent-crashes + +taskkill /f /im amdaemon.exe > nul 2>&1 + +echo. +echo Game processes have terminated +pause \ No newline at end of file diff --git a/dist/ekt/segatools_satellite.ini b/dist/ekt/segatools_satellite.ini new file mode 100644 index 0000000..1f3474c --- /dev/null +++ b/dist/ekt/segatools_satellite.ini @@ -0,0 +1,181 @@ +; ----------------------------------------------------------------------------- +; Path settings +; ----------------------------------------------------------------------------- + +[vfs] +; Insert the path to the game AMFS directory here (contains ICF1 and ICF2) +amfs=amfs_satellite +; Insert the path to the game Option directory here (contains Axxx directories) +option= +; Create an empty directory somewhere and insert the path here. +; This directory may be shared between multiple SEGA games. +; NOTE: This has nothing to do with Windows %APPDATA%. +appdata=appdata_satellite + +; ----------------------------------------------------------------------------- +; Device settings +; ----------------------------------------------------------------------------- + +[aime] +; Enable Aime card reader assembly emulation. Disable to use a real SEGA Aime +; reader. +enable=1 +aimePath=DEVICE\aime.txt + +; Virtual-key code. If this button is **held** then the emulated IC card reader +; emulates an IC card in its proximity. A variety of different IC cards can be +; emulated; the exact choice of card that is emulated depends on the presence or +; absence of the configured card ID files. Default is the Return key. +scan=0x0D + +; ----------------------------------------------------------------------------- +; Network settings +; ----------------------------------------------------------------------------- + +[dns] +; Insert the hostname or IP address of the server you wish to use here. +; Note that 127.0.0.1, localhost etc are specifically rejected. +default=127.0.0.1 + +[netenv] +; Simulate an ideal LAN environment. This may interfere with head-to-head play. +; SEGA games are somewhat picky about their LAN environment, so leaving this +; setting enabled is recommended. +enable=1 + +; ----------------------------------------------------------------------------- +; Board settings +; ----------------------------------------------------------------------------- + +[keychip] +; Keychip serial number. Keychip serials observed in the wild follow this +; pattern: `A\d{2}(E|X)-(01|20)[ABCDU]\d{8}`. +id=A69E-01A88888888 + +; The /24 LAN subnet that the emulated keychip will tell the game to expect. +; If you disable netenv then you must set this to your LAN's IP subnet, and +; that subnet must start with 192.168. +subnet=192.168.189.0 + +; Override the game's four-character platform code (e.g. `AAV2` for Nu 2). This +; is actually supposed to be a separate three-character `platformId` and +; integer `modelType` setting, but they are combined here for convenience. +; 1 = Terminal (TM) +; 2 = Satellite (ST) +platformId=ACA2 + +[system] +; Enable ALLS system settings. +enable=1 + +; ----------------------------------------------------------------------------- +; Misc. hooks settings +; ----------------------------------------------------------------------------- + +[unity] +; Path to a .NET DLL that should run before the game. Useful for loading +; modding frameworks such as BepInEx. +targetAssembly= + +[printer] +; G-Printec CX-7000 Printer printer emulation setting. +enable=1 +; Insert the path to the image output directory here. +printerOutPath=DEVICE\print + +[flatPanelReader] +; Enable the Y3 board emulation. +enable=1 + +[y3ws] +; Enable the Y3 websocket server. +enable=1 +; Set the TCP port on which the Y3 websocket server runs. +port=3594 + +; ----------------------------------------------------------------------------- +; LED settings +; ----------------------------------------------------------------------------- + +[led15093] +; Enable the 837-15093-06 board emulation. +enable=1 + +; ----------------------------------------------------------------------------- +; Custom IO settings +; ----------------------------------------------------------------------------- + +[aimeio] +; To use a custom card reader IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard input. +path= + +[ektio] +; To use a custom Eiketsu Taisen IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard/gamepad input. +path= + +[y3io] +; To use a custom Y3 IO DLL enter its path here. +; Leave empty if you want to use ... TBA ... +path= + +; ----------------------------------------------------------------------------- +; Input settings +; ----------------------------------------------------------------------------- + +; Keyboard bindings are as hexadecimal (prefixed with 0x) or decimal +; (not prefixed with 0x) virtual-key codes, a list of which can be found here: +; +; https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes +; +; This is, admittedly, not the most user-friendly configuration method in the +; world. An improved solution will be provided later. + +[io4] +; Test button virtual-key code. Default is the F1 key. +test=0x70 +; Service button virtual-key code. Default is the F2 key. +service=0x71 +; Keyboard button to increment coin counter. Default is the F3 key. +coin=0x72 + +; SW1. Default is the 4 key. +sw1=0x34 +; SW2. Default is the 5 key. +sw2=0x35 + +; Input API selection for IO4 input emulator. +; For now only "keyboard" is supported. +mode=keyboard + +[keyboard] + +menu=0x41 +start=0x42 +stratagem=0x43 +stratagem_lock=0x44 +hougu=0x45 +ryuuha=0x46 + +tenkey_0=0x60 +tenkey_1=0x61 +tenkey_2=0x62 +tenkey_3=0x63 +tenkey_4=0x64 +tenkey_5=0x65 +tenkey_6=0x66 +tenkey_7=0x67 +tenkey_8=0x68 +tenkey_9=0x69 +tenkey_clear=0x6E +tenkey_enter=0x0D + +vol_up=0x21 +vol_down=0x22 + +trackball_up=0x26 +trackball_right=0x27 +trackball_down=0x28 +trackball_left=0x25 +speed_modifier=10 diff --git a/dist/ekt/segatools_terminal.ini b/dist/ekt/segatools_terminal.ini new file mode 100644 index 0000000..bfb74ee --- /dev/null +++ b/dist/ekt/segatools_terminal.ini @@ -0,0 +1,145 @@ +; ----------------------------------------------------------------------------- +; Path settings +; ----------------------------------------------------------------------------- + +[vfs] +; Insert the path to the game AMFS directory here (contains ICF1 and ICF2) +amfs=amfs_terminal +; Insert the path to the game Option directory here (contains Axxx directories) +option= +; Create an empty directory somewhere and insert the path here. +; This directory may be shared between multiple SEGA games. +; NOTE: This has nothing to do with Windows %APPDATA%. +appdata=appdata_terminal + +; ----------------------------------------------------------------------------- +; Device settings +; ----------------------------------------------------------------------------- + +[aime] +; Enable Aime card reader assembly emulation. Disable to use a real SEGA Aime +; reader. +enable=1 +aimePath=DEVICE\aime.txt + +; Virtual-key code. If this button is **held** then the emulated IC card reader +; emulates an IC card in its proximity. A variety of different IC cards can be +; emulated; the exact choice of card that is emulated depends on the presence or +; absence of the configured card ID files. Default is the Return key. +scan=0x0D + +; ----------------------------------------------------------------------------- +; Network settings +; ----------------------------------------------------------------------------- + +[dns] +; Insert the hostname or IP address of the server you wish to use here. +; Note that 127.0.0.1, localhost etc are specifically rejected. +default=127.0.0.1 + +[netenv] +; Simulate an ideal LAN environment. This may interfere with head-to-head play. +; SEGA games are somewhat picky about their LAN environment, so leaving this +; setting enabled is recommended. +enable=1 + +; ----------------------------------------------------------------------------- +; Board settings +; ----------------------------------------------------------------------------- + +[keychip] +; Keychip serial number. Keychip serials observed in the wild follow this +; pattern: `A\d{2}(E|X)-(01|20)[ABCDU]\d{8}`. +id=A69E-01A88888888 + +; The /24 LAN subnet that the emulated keychip will tell the game to expect. +; If you disable netenv then you must set this to your LAN's IP subnet, and +; that subnet must start with 192.168. +subnet=192.168.189.0 + +; Override the game's four-character platform code (e.g. `AAV2` for Nu 2). This +; is actually supposed to be a separate three-character `platformId` and +; integer `modelType` setting, but they are combined here for convenience. +; 1 = Terminal (TM) +; 2 = Satellite (ST) +platformId=ACA1 + +[system] +; Enable ALLS system settings. +enable=1 + +; ----------------------------------------------------------------------------- +; Misc. hooks settings +; ----------------------------------------------------------------------------- + +[unity] +; Enable Unity hook. This will allow you to run custom .NET code before the game +enable=1 + +; Path to a .NET DLL that should run before the game. Useful for loading +; modding frameworks such as BepInEx. +targetAssembly= + +; ----------------------------------------------------------------------------- +; LED settings +; ----------------------------------------------------------------------------- + +[led15093] +; Enable the 837-15093-06 board emulation. +enable=1 + +; ----------------------------------------------------------------------------- +; Custom IO settings +; ----------------------------------------------------------------------------- + +[aimeio] +; To use a custom card reader IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard input. +path= + +[ektio] +; To use a custom Eiketsu Taisen IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard/gamepad input. +path= + +; ----------------------------------------------------------------------------- +; Input settings +; ----------------------------------------------------------------------------- + +; Keyboard bindings are as hexadecimal (prefixed with 0x) or decimal +; (not prefixed with 0x) virtual-key codes, a list of which can be found here: +; +; https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes +; +; This is, admittedly, not the most user-friendly configuration method in the +; world. An improved solution will be provided later. + +[io4] +; Test button virtual-key code. Default is the F1 key. +test=0x70 +; Service button virtual-key code. Default is the F2 key. +service=0x71 +; Keyboard button to increment coin counter. Default is the F3 key. +coin=0x72 + +; SW1. Default is the 4 key. +sw1=0x34 +; SW2. Default is the 5 key. +sw2=0x35 + +; Input API selection for IO4 input emulator. +; For now only "keyboard" is supported. +mode=keyboard + +[keyboard] + +cancel=0x53 +decide=0x41 + +up=0x26 +right=0x27 +down=0x28 +left=0x25 + +left_2=0x4F +right_2=0x57 diff --git a/dist/sekito/card_player.html b/dist/sekito/card_player.html new file mode 100644 index 0000000..20a54fa --- /dev/null +++ b/dist/sekito/card_player.html @@ -0,0 +1,228 @@ + + + + + Taisen Card Field + + + + + +
+ +
+
+
Please wait...
+
+ +
+
+ + \ No newline at end of file diff --git a/dist/sekito/config_hook_satellite.json b/dist/sekito/config_hook_satellite.json new file mode 100644 index 0000000..3680937 --- /dev/null +++ b/dist/sekito/config_hook_satellite.json @@ -0,0 +1,6 @@ +{ + "common": + { + "language": "english" + } +} diff --git a/dist/sekito/config_hook_terminal.json b/dist/sekito/config_hook_terminal.json new file mode 100644 index 0000000..b566e90 --- /dev/null +++ b/dist/sekito/config_hook_terminal.json @@ -0,0 +1,35 @@ +{ + "common": + { + "language": "english" + }, + "network": + { + "property": + { + "dhcp": true + } + }, + "credit" : + { + "coin_selector_AS6DB" : + { + "enable" : false + } + }, + "aime" : + { + "enable" : true, + "unit" : + [ + { + "port" : 1, + "id" : 1 + }, + { + "port" : 12, + "id" : 2 + } + ] + } +} diff --git a/dist/sekito/launch_satellite.bat b/dist/sekito/launch_satellite.bat new file mode 100644 index 0000000..0e42fa8 --- /dev/null +++ b/dist/sekito/launch_satellite.bat @@ -0,0 +1,15 @@ +@echo off +set SEGATOOLS_CONFIG_PATH=.\segatools_satellite.ini + +pushd %~dp0 + +start "AM Daemon" /min inject_x64 -d -k sekitohook_x64.dll bin\amdaemon.exe -c bin\config_new.json -c bin\config_video_single.json -c bin\config_video_multi.json -c bin\config_input_sate.json -c bin\config_input_terminal.json -c bin\config_input_terminal_exp.json -c config_hook_satellite.json + +inject_x86 -d -k sekitohook_x86.dll bin\appSate.exe + +taskkill /f /im appSate.exe > nul 2>&1 +taskkill /f /im amdaemon.exe > nul 2>&1 + +echo. +echo Game processes have terminated +pause \ No newline at end of file diff --git a/dist/sekito/launch_terminal.bat b/dist/sekito/launch_terminal.bat new file mode 100644 index 0000000..89a0084 --- /dev/null +++ b/dist/sekito/launch_terminal.bat @@ -0,0 +1,19 @@ +@echo off +set SEGATOOLS_CONFIG_PATH=.\segatools_terminal.ini + +pushd %~dp0 + +start "AM Daemon" /min inject_x64 -d -k sekitohook_x64.dll bin\amdaemon.exe -c bin\config_new.json -c bin\config_video_single.json -c bin\config_video_multi.json -c bin\config_input_sate.json -c bin\config_input_terminal.json -c bin\config_input_terminal_exp.json -c config_hook_terminal.json + +start "SKT Server Processes" /min cmd /C bin\server\server_start.bat + +inject_x86 -d -k sekitohook_x86.dll bin\appTerminal.exe + +taskkill /f /im appTerminal.exe > nul 2>&1 +taskkill /f /im amdaemon.exe > nul 2>&1 + +call bin\server\server_stop.bat + +echo. +echo Game processes have terminated +pause \ No newline at end of file diff --git a/dist/sekito/segatools_satellite.ini b/dist/sekito/segatools_satellite.ini new file mode 100644 index 0000000..0dd89c6 --- /dev/null +++ b/dist/sekito/segatools_satellite.ini @@ -0,0 +1,207 @@ +; ----------------------------------------------------------------------------- +; Path settings +; ----------------------------------------------------------------------------- + +[vfs] +; Insert the path to the game AMFS directory here (contains ICF1 and ICF2) +amfs= +; Insert the path to the game Option directory here (contains Axxx directories) +option= +; Create an empty directory somewhere and insert the path here. +; This directory may be shared between multiple SEGA games. +; NOTE: This has nothing to do with Windows %APPDATA%. +appdata=appdata_satellite + +; ----------------------------------------------------------------------------- +; Device settings +; ----------------------------------------------------------------------------- + +[aime] +; Enable Aime card reader assembly emulation. Disable to use a real SEGA Aime +; reader. +enable=1 +aimePath=DEVICE\aime.txt + +; Virtual-key code. If this button is **held** then the emulated IC card reader +; emulates an IC card in its proximity. A variety of different IC cards can be +; emulated; the exact choice of card that is emulated depends on the presence or +; absence of the configured card ID files. Default is the Return key. +scan=0x0D + +; ----------------------------------------------------------------------------- +; Network settings +; ----------------------------------------------------------------------------- + +[dns] +; Insert the hostname or IP address of the server you wish to use here. +; Note that 127.0.0.1, localhost etc are specifically rejected. +default=127.0.0.1 + +[netenv] +; Simulate an ideal LAN environment. This may interfere with head-to-head play. +; SEGA games are somewhat picky about their LAN environment, so leaving this +; setting enabled is recommended. +enable=1 + +; ----------------------------------------------------------------------------- +; Board settings +; ----------------------------------------------------------------------------- + +[keychip] +; Keychip serial number. Keychip serials observed in the wild follow this +; pattern: `A\d{2}(E|X)-(01|20)[ABCDU]\d{8}`. +id=A69E-01A88888888 + +; The /24 LAN subnet that the emulated keychip will tell the game to expect. +; If you disable netenv then you must set this to your LAN's IP subnet, and +; that subnet must start with 192.168. +subnet=192.168.189.0 + +; Override the game's four-character platform code (e.g. `AAV2` for Nu 2). This +; is actually supposed to be a separate three-character `platformId` and +; integer `modelType` setting, but they are combined here for convenience. +; 1 = Terminal (TM) +; 2 = Satellite (ST) +platformId=AAV2 + +[pcbid] +; Set the Windows host name. This should be an ALLS MAIN ID, without the +; hyphen (which is not a valid character in a Windows host name). +serialNo=ACAE01A99999999 + +[gpio] +; Emulated Nu DIP switch for Distribution Server setting. +; +; TODO +dipsw1=1 + +[eeprom] +; Path to the storage file for EEPROM emulation. This file is automatically +; created and initialized with a suitable number of zero bytes if it does not +; already exist. +path=appdata_satellite\eeprom.bin + +[sram] +; Path to the storage file for SRAM emulation. +path=appdata_satellite\sram.bin + +; ----------------------------------------------------------------------------- +; Misc. hooks settings +; ----------------------------------------------------------------------------- + +[printer] +; Sinfonia CHC-C320 printer emulation setting. +enable=1 +; Change the printer serial number here. +serial_no="5A-A123" +; Insert the path to the image output directory here. +printerOutPath="DEVICE\print" +; Rotate all printed images by 180 degrees. +rotate180=1 + +[gfx] +; Enables the graphics hook. +enable=1 +; Force the game to run windowed. +windowed=1 +; Add a frame to the game window if running windowed. +framed=0 +; Select the monitor to run the game on. (Fullscreen only, 0 =primary screen) +monitor=0 +; Enable DPI awareness for the game process, preventing Windows from stretching the game window if a DPI scaling higher than 100% is used +dpiAware=1 + +[flatPanelReader] +; Enable the Y3 board emulation. +enable=1 + +[y3ws] +; Enable the Y3 websocket server. +enable=1 +; Set the TCP port on which the Y3 websocket server runs. +port=3594 +; Game ID used for clients. +gameId=SDDD + +; ----------------------------------------------------------------------------- +; LED settings +; ----------------------------------------------------------------------------- + +[led15093] +; Enable the 837-15093-06 board emulation. +enable=1 + +; ----------------------------------------------------------------------------- +; Custom IO settings +; ----------------------------------------------------------------------------- + +[aimeio] +; To use a custom card reader IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard input. +path= + +[sekitoio] +; To use a custom Eiketsu Taisen IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard/gamepad input. +path= + +[y3io] +; To use a custom Y3 IO DLL enter its path here. +; Leave empty if you want to use ... TBA ... +path= + +; ----------------------------------------------------------------------------- +; Input settings +; ----------------------------------------------------------------------------- + +; Keyboard bindings are as hexadecimal (prefixed with 0x) or decimal +; (not prefixed with 0x) virtual-key codes, a list of which can be found here: +; +; https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes +; +; This is, admittedly, not the most user-friendly configuration method in the +; world. An improved solution will be provided later. + +[io4] +; Test button virtual-key code. Default is the F1 key. +test=0x70 +; Service button virtual-key code. Default is the F2 key. +service=0x71 +; Keyboard button to increment coin counter. Default is the F3 key. +coin=0x72 + +; SW1. Default is the 4 key. +sw1=0x34 +; SW2. Default is the 5 key. +sw2=0x35 + +; Input API selection for IO4 input emulator. +; For now only "keyboard" is supported. +mode=keyboard + +[keyboard] + +menu=0x41 +start=0x42 +stratagem=0x43 +stratagem_lock=0x44 +hougu=0x45 + +tenkey_0=0x60 +tenkey_1=0x61 +tenkey_2=0x62 +tenkey_3=0x63 +tenkey_4=0x64 +tenkey_5=0x65 +tenkey_6=0x66 +tenkey_7=0x67 +tenkey_8=0x68 +tenkey_9=0x69 +tenkey_clear=0x6E +tenkey_enter=0x0D + +trackball_up=0x26 +trackball_right=0x27 +trackball_down=0x28 +trackball_left=0x25 +speed_modifier=10 diff --git a/dist/sekito/segatools_terminal.ini b/dist/sekito/segatools_terminal.ini new file mode 100644 index 0000000..fbd0455 --- /dev/null +++ b/dist/sekito/segatools_terminal.ini @@ -0,0 +1,174 @@ +; ----------------------------------------------------------------------------- +; Path settings +; ----------------------------------------------------------------------------- + +[vfs] +; Insert the path to the game AMFS directory here (contains ICF1 and ICF2) +amfs= +; Insert the path to the game Option directory here (contains Axxx directories) +option= +; Create an empty directory somewhere and insert the path here. +; This directory may be shared between multiple SEGA games. +; NOTE: This has nothing to do with Windows %APPDATA%. +appdata=appdata_terminal + +; ----------------------------------------------------------------------------- +; Device settings +; ----------------------------------------------------------------------------- + +[aime] +; Enable Aime card reader assembly emulation. Disable to use a real SEGA Aime +; reader. +enable=1 +aimePath=DEVICE\aime.txt + +; Virtual-key code. If this button is **held** then the emulated IC card reader +; emulates an IC card in its proximity. A variety of different IC cards can be +; emulated; the exact choice of card that is emulated depends on the presence or +; absence of the configured card ID files. Default is the Return key. +scan=0x0D + +; The terminal-specific Aime card reader to queue for a satellite. +[aime2] +; Enable Aime card reader assembly emulation. Disable to use a real SEGA Aime +; reader. +enable=1 +aimePath=DEVICE\aime.txt + +; Virtual-key code. If this button is **held** then the emulated IC card reader +; emulates an IC card in its proximity. A variety of different IC cards can be +; emulated; the exact choice of card that is emulated depends on the presence or +; absence of the configured card ID files. Default is the Return key. +scan=0x0D + +; ----------------------------------------------------------------------------- +; Network settings +; ----------------------------------------------------------------------------- + +[dns] +; Insert the hostname or IP address of the server you wish to use here. +; Note that 127.0.0.1, localhost etc are specifically rejected. +default=127.0.0.1 + +[netenv] +; Simulate an ideal LAN environment. This may interfere with head-to-head play. +; SEGA games are somewhat picky about their LAN environment, so leaving this +; setting enabled is recommended. +enable=1 + +; ----------------------------------------------------------------------------- +; Board settings +; ----------------------------------------------------------------------------- + +[keychip] +; Keychip serial number. Keychip serials observed in the wild follow this +; pattern: `A\d{2}(E|X)-(01|20)[ABCDU]\d{8}`. +id=A69E-01A88888888 + +; The /24 LAN subnet that the emulated keychip will tell the game to expect. +; If you disable netenv then you must set this to your LAN's IP subnet, and +; that subnet must start with 192.168. +subnet=192.168.189.0 + +; Override the game's four-character platform code (e.g. `AAV2` for Nu 2). This +; is actually supposed to be a separate three-character `platformId` and +; integer `modelType` setting, but they are combined here for convenience. +; 1 = Terminal (TM) +; 2 = Satellite (ST) +platformId=AAV1 + +[pcbid] +; Set the Windows host name. This should be an ALLS MAIN ID, without the +; hyphen (which is not a valid character in a Windows host name). +serialNo=ACAE01A99999999 + +[eeprom] +; Path to the storage file for EEPROM emulation. This file is automatically +; created and initialized with a suitable number of zero bytes if it does not +; already exist. +path=appdata_terminal\eeprom.bin + +[sram] +; Path to the storage file for SRAM emulation. +path=appdata_terminal\sram.bin + +; ----------------------------------------------------------------------------- +; Misc. hooks settings +; ----------------------------------------------------------------------------- + +[gfx] +; Enables the graphics hook. +enable=1 +; Force the game to run windowed. +windowed=1 +; Add a frame to the game window if running windowed. +framed=0 +; Select the monitor to run the game on. (Fullscreen only, 0 =primary screen) +monitor=0 +; Enable DPI awareness for the game process, preventing Windows from stretching the game window if a DPI scaling higher than 100% is used +dpiAware=1 + +; ----------------------------------------------------------------------------- +; LED settings +; ----------------------------------------------------------------------------- + +[led15093] +; Enable the 837-15093-06 board emulation. +enable=1 + +; ----------------------------------------------------------------------------- +; Custom IO settings +; ----------------------------------------------------------------------------- + +[aimeio] +; To use a custom card reader IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard input. +path= + +[sekitoio] +; To use a custom Eiketsu Taisen IO DLL enter its path here. +; Leave empty if you want to use Segatools built-in keyboard/gamepad input. +path= + +; ----------------------------------------------------------------------------- +; Input settings +; ----------------------------------------------------------------------------- + +; Keyboard bindings are as hexadecimal (prefixed with 0x) or decimal +; (not prefixed with 0x) virtual-key codes, a list of which can be found here: +; +; https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes +; +; This is, admittedly, not the most user-friendly configuration method in the +; world. An improved solution will be provided later. + +[io4] +; Test button virtual-key code. Default is the F1 key. +test=0x70 +; Service button virtual-key code. Default is the F2 key. +service=0x71 +; Keyboard button to increment coin counter. Default is the F3 key. +coin=0x72 + +; SW1. Default is the 4 key. +sw1=0x34 +; SW2. Default is the 5 key. +sw2=0x35 + +; Input API selection for IO4 input emulator. +; For now only "keyboard" is supported. +mode=keyboard + +[keyboard] + +cancel=0x53 +decide=0x41 +reserve=0x45 + +up=0x26 +right=0x27 +down=0x28 +left=0x25 + +left_2=0x4F +right_2=0x57 diff --git a/doc/config/common.md b/doc/config/common.md index 666be50..a9df591 100644 --- a/doc/config/common.md +++ b/doc/config/common.md @@ -589,6 +589,12 @@ Default: `01:02:03:04:05:06` The MAC address of the virtualized Ethernet adapter. The exact value shouldn't ever matter. +### `broadcast` + +Default: `255.255.255.255` + +The UDP broadcast address that should be used if packets are being sent to the virtual keychip's subnet. This is used for cab-to-cab communication (Local Play, Satellite to Terminal, etc.). Depending on your network adapters (VPNs etc), sometimes you must explicitely specify your real LANs subnet. + ## `[pcbid]` Configure Windows host name virtualization. The ALLS-series platform no longer @@ -633,6 +639,10 @@ Path to the storage file for SRAM emulation. Configure Windows path redirection hooks. +All of these paths can have a path-part prepended to them by setting the environment variable +`SEGATOOLS_VFS_RELATIVE_PATH`. This will only apply if the path set in the configuration is relative. Absolute parts are +not touched. + ### `enable` Default: `1` diff --git a/doc/config/taisen.md b/doc/config/taisen.md new file mode 100644 index 0000000..bc9187d --- /dev/null +++ b/doc/config/taisen.md @@ -0,0 +1,107 @@ +# Taisen configuration settings + +This file describes configuration settings specific to the Taisen series. + +Keyboard binding settings use +[Virtual-Key Codes](https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes). + +## `[ektio]` / `[sekitoio]` + +Controls the input driver. + +### `path` + +Specify a path for a third-party input driver DLL. Default is empty +(use built-in keyboard IO emulation). + +## `[flatPanelReader]` + +Controls settings for the Flat Panel (a.k.a. Y3 Board) + +### `enable` + +Default: `1` + +Whether or not to enable Flat Panel emulation. Disable to use a real board. + +### `port_field` + +Default: `10` + +The COM port on which the emulated Flat Panel is connected to. This differs per game. + +### `port_printer` + +Default: `11` + +The COM port on which the emulated Printer Camera is connected to. This only exists in Sangokushi. + +### `dllVersion` + +Default: `1` + +The version of the emulated Y3CodeReader dll. Unsure if that is used anywhere. + +### `firmVersion` + +Default: `1` + +The version of the emulated Y3CodeReader firmware. Unsure if that is used anywhere. + +### `firmNameField` + +Default: `SFPR` + +The device name of the emulated Flat Panel. This should never need changing. + +### `firmNamePrinter` + +Default: `SPRT` + +The device name of the emulated Printer Camera. This should never need changing. + +### `targetCodeField` + +Default: `SFR0` + +The target name of the emulated Flat Panel. This should never need changing. + +### `targetCodePrinter` + +Default: `SPT0` + +The target name of the emulated Printer Camera. This should never need changing. + +## `[y3ws]` + +Settings for the default implementation of setting cards on the Flat Panel remotely via websockets + +### `enable` + +Default: `1` + +Enable the websocket server. + +### `debug` + +Default: `0` + +Makes y3ws I/O very verbose. For debugging only. May lag the game. + +### `port` + +Default: `3594` + +The TCP port the websocket server listens on. + +### `gameId` + +Default: `SDEY` + +The game ID that the websocket server transmits, so clients can change their behaviour based on that (UI, etc.) + +### `cardDirectory` + +Default: `DEVICE\print` + +The directory where printed card images are placed. Should be the same as in `[printer]`. \ No newline at end of file diff --git a/doc/y3ws.txt b/doc/y3ws.txt new file mode 100644 index 0000000..5689440 --- /dev/null +++ b/doc/y3ws.txt @@ -0,0 +1,57 @@ +Y3WS websocket protocol for card I/O for the Taisen series by Haruka: + +Default listening port: 3594 (san-go-ku-shi) + +All packets are JSON and, unless otherwise specified contain these fields: + +* Requests: +{"version": 1, "command": "..."} + +* Responses: +{"version": 1, "success": , "error": } + +Commands: + +- ping + +Does nothing except answering with a success response. + + +- get_game_id + +Extra response fields: + - game_id: + +Returns the current game ID that is being run (SDDD, SDGY). + + +- get_cards + +Extra response fields: + - cards: + - card_id: + - path: + +Returns all cards that the player has in possession. + + +- get_card_image + +Extra request fields: + - path: +Extra response fields: + - data: + +Returns the card image for the given path (format TBA). + + +- set_field + +Extra request fields: + - array of objects + - card_id: + - x: + - y: + - rotation: + +Sets the given cards onto the given positions on the field. Always replaces the entire board. diff --git a/games/apm3hook/config.h b/games/apm3hook/config.h index 8ff2cc3..d42751d 100644 --- a/games/apm3hook/config.h +++ b/games/apm3hook/config.h @@ -7,7 +7,7 @@ #include "hooklib/dvd.h" #include "hooklib/touch.h" -#include "hooklib/printer.h" +#include "hooklib/printer_chc.h" #include "gfxhook/config.h" diff --git a/games/carolhook/dllmain.c b/games/carolhook/dllmain.c index 35fc7f0..6d18169 100644 --- a/games/carolhook/dllmain.c +++ b/games/carolhook/dllmain.c @@ -156,7 +156,7 @@ static DWORD CALLBACK carol_pre_startup(void) goto fail; } - hr = createprocess_push_hook_a(".\\15312firm\\firmupdate_1113.exe", "inject -d -k carolhook.dll ", NULL, false); + hr = createprocess_push_hook_a(".\\15312firm\\firmupdate_1113.exe", "inject -d -k carolhook.dll ", NULL, false, false); if (FAILED(hr)) { goto fail; diff --git a/games/cmhook/config.c b/games/cmhook/config.c index 47fcfa8..c69a5b9 100644 --- a/games/cmhook/config.c +++ b/games/cmhook/config.c @@ -40,7 +40,7 @@ void cm_hook_config_load( io4_config_load(&cfg->io4, filename); vfd_config_load(&cfg->vfd, filename); touch_screen_config_load(&cfg->touch, filename); - printer_config_load(&cfg->printer, filename); + printer_chc_config_load(&cfg->printer, filename); cm_dll_config_load(&cfg->dll, filename); unity_config_load(&cfg->unity, filename); } diff --git a/games/cmhook/config.h b/games/cmhook/config.h index 26d9a7c..c1e5066 100644 --- a/games/cmhook/config.h +++ b/games/cmhook/config.h @@ -6,7 +6,7 @@ #include "hooklib/dvd.h" #include "hooklib/touch.h" -#include "hooklib/printer.h" +#include "hooklib/printer_chc.h" #include "cmhook/cm-dll.h" @@ -22,7 +22,7 @@ struct cm_hook_config { struct vfd_config vfd; struct cm_dll_config dll; struct touch_screen_config touch; - struct printer_config printer; + struct printer_chc_config printer; struct unity_config unity; }; diff --git a/games/cmhook/dllmain.c b/games/cmhook/dllmain.c index 7d5161d..c1d9c4c 100644 --- a/games/cmhook/dllmain.c +++ b/games/cmhook/dllmain.c @@ -59,7 +59,7 @@ static DWORD CALLBACK cm_pre_startup(void) /* Hook external DLL APIs */ - printer_hook_init(&cm_hook_cfg.printer, 0, cm_hook_mod); + printer_chc_hook_init(&cm_hook_cfg.printer, 0, cm_hook_mod); /* Initialize emulation hooks */ diff --git a/games/ekthook/config.c b/games/ekthook/config.c new file mode 100644 index 0000000..e3f015b --- /dev/null +++ b/games/ekthook/config.c @@ -0,0 +1,107 @@ +#include +#include + +#include "board/config.h" + +#include "ekthook/config.h" +#include "ekthook/ekt-dll.h" + +#include "hooklib/config.h" + +#include "platform/config.h" + +void led15093_config_load(struct led15093_config *cfg, const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + wchar_t tmpstr[16]; + + memset(cfg->board_number, ' ', sizeof(cfg->board_number)); + memset(cfg->chip_number, ' ', sizeof(cfg->chip_number)); + memset(cfg->boot_chip_number, ' ', sizeof(cfg->boot_chip_number)); + + cfg->enable = GetPrivateProfileIntW(L"led15093", L"enable", 1, filename); + cfg->port_no[0] = GetPrivateProfileIntW(L"led15093", L"portNo1", 0, filename); + cfg->port_no[1] = GetPrivateProfileIntW(L"led15093", L"portNo2", 0, filename); + cfg->high_baudrate = GetPrivateProfileIntW(L"led15093", L"highBaud", 0, filename); + cfg->fw_ver = GetPrivateProfileIntW(L"led15093", L"fwVer", 0xA0, filename); + cfg->fw_sum = GetPrivateProfileIntW(L"led15093", L"fwSum", 0xAA53, filename); + + GetPrivateProfileStringW( + L"led15093", + L"boardNumber", + L"15093-06", + tmpstr, + _countof(tmpstr), + filename); + + size_t n = wcstombs(cfg->board_number, tmpstr, sizeof(cfg->board_number)); + for (int i = n; i < sizeof(cfg->board_number); i++) + { + cfg->board_number[i] = ' '; + } + + GetPrivateProfileStringW( + L"led15093", + L"chipNumber", + L"6710A", + tmpstr, + _countof(tmpstr), + filename); + + n = wcstombs(cfg->chip_number, tmpstr, sizeof(cfg->chip_number)); + for (int i = n; i < sizeof(cfg->chip_number); i++) + { + cfg->chip_number[i] = ' '; + } + + GetPrivateProfileStringW( + L"led15093", + L"bootChipNumber", + L"6709 ", + tmpstr, + _countof(tmpstr), + filename); + + n = wcstombs(cfg->boot_chip_number, tmpstr, sizeof(cfg->boot_chip_number)); + for (int i = n; i < sizeof(cfg->boot_chip_number); i++) + { + cfg->boot_chip_number[i] = ' '; + } +} + +void ekt_dll_config_load( + struct ekt_dll_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + GetPrivateProfileStringW( + L"ektio", + L"path", + L"", + cfg->path, + _countof(cfg->path), + filename); +} + + +void ekt_hook_config_load( + struct ekt_hook_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + platform_config_load(&cfg->platform, filename); + aime_config_load(&cfg->aime, filename); + io4_config_load(&cfg->io4, filename); + dvd_config_load(&cfg->dvd, filename); + led15093_config_load(&cfg->led15093, filename); + y3_config_load(&cfg->y3, filename); + printer_cx_config_load(&cfg->printer, filename); + unity_config_load(&cfg->unity, filename); + ekt_dll_config_load(&cfg->dll, filename); +} diff --git a/games/ekthook/config.h b/games/ekthook/config.h new file mode 100644 index 0000000..358e3b9 --- /dev/null +++ b/games/ekthook/config.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include "board/sg-reader.h" +#include "board/config.h" +#include "board/led15093.h" + +#include "ekthook/ekt-dll.h" + +#include "hooklib/config.h" +#include "hooklib/dvd.h" +#include "hooklib/printer_cx.h" + +#include "platform/config.h" + +#include "unityhook/config.h" + +struct ekt_hook_config { + struct platform_config platform; + struct aime_config aime; + struct io4_config io4; + struct dvd_config dvd; + struct led15093_config led15093; + struct y3_config y3; + struct ekt_dll_config dll; + struct unity_config unity; + struct printer_cx_config printer; +}; + +void ekt_dll_config_load( + struct ekt_dll_config *cfg, + const wchar_t *filename); + +void ekt_hook_config_load( + struct ekt_hook_config *cfg, + const wchar_t *filename); diff --git a/games/ekthook/dllmain.c b/games/ekthook/dllmain.c new file mode 100644 index 0000000..a449df4 --- /dev/null +++ b/games/ekthook/dllmain.c @@ -0,0 +1,224 @@ +/* + "Eiketsu Taisen" (ekt) hook + + Devices + + USB: 837-15257-01 "Type 4" I/O Board + + [Satellite] + + USB: 630-00011 G-Printec CX-7000 Printer + COM2: 837-15093-06 LED Controller Board + COM3: 837-15396 "Gen 3" Aime Reader + COM4: 601-13160-01 "Flat Panel Reader" Y3CR BD SIE F720MM Board + + [Terminal] + + COM1: 837-15396 "Gen 3" Aime Reader + COM3: 837-15093-06 LED Controller Board +*/ + +#include +#include +#include +#include + +#include + +#include "ekt-dll.h" +#include "board/sg-reader.h" +#include "board/led15093.h" + +#include "hook/process.h" +#include "hook/iohook.h" + +#include "hooklib/serial.h" +#include "hooklib/spike.h" + +#include "ekthook/config.h" +#include "ekthook/io4.h" +#include "hooklib/createprocess.h" +#include "hooklib/printer_cx.h" + +#include "platform/platform.h" + +#include "unityhook/hook.h" + +#include "util/dprintf.h" +#include "util/env.h" +#include "hooklib/y3-dll.h" +#include "hooklib/y3.h" +#include "util/lib.h" + +static HMODULE ekt_hook_mod; +static process_entry_t ekt_startup; +static struct ekt_hook_config ekt_hook_cfg; + +static void unity_hook_callback(HMODULE hmodule, const wchar_t* p) { + netenv_hook_apply_hooks(hmodule); + createprocess_hook_apply_hooks(hmodule); +} + +static void check_and_display_warning(void) { + wchar_t* module_path; + wchar_t* file_name; + + module_path = module_file_name(NULL); + + if (module_path != NULL) { + file_name = PathFindFileNameW(module_path); + + free(module_path); + module_path = NULL; + + _wcslwr(file_name); + + if (wcsstr(file_name, L"ekt.exe") != NULL) { + wchar_t recording_flag_path[MAX_PATH]; + PathCombineW(recording_flag_path, ekt_hook_cfg.platform.vfs.appdata, L"recording_warning_seen"); + if (!PathFileExistsW(recording_flag_path)) { + if (MessageBoxW( + NULL, + L"This game has an ability during battle to record and upload your entire desktop content (including other windows, task bar, browsers, etc.)\n\nMake sure you trust the server you are playing on.\n\nThis message will not be shown again.", + L"Segatools Privacy Warning", MB_ICONWARNING | MB_OKCANCEL) != IDOK) { + ExitProcess(0); + } + CreateFileW(recording_flag_path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW, 0, NULL); + } + } + } +} + +static DWORD CALLBACK ekt_pre_startup(void) +{ + HRESULT hr; + bool is_terminal; + + dprintf("--- Begin ekt_pre_startup ---\n"); + + /* Load config */ + + ekt_hook_config_load(&ekt_hook_cfg, get_config_path()); + + /* Hook Win32 APIs */ + + dvd_hook_init(&ekt_hook_cfg.dvd, ekt_hook_mod); + serial_hook_init(); + + createprocess_push_hook_w(L"fsutil", L"", L"", true, true); + + /* Hook external DLL APIs */ + + hr = y3_hook_init(&ekt_hook_cfg.y3, ekt_hook_mod, get_config_path()); + + if (FAILED(hr)) { + goto fail; + } + + printer_cx_hook_init(&ekt_hook_cfg.printer, ekt_hook_mod); + + /* Initialize emulation hooks */ + + hr = platform_hook_init( + &ekt_hook_cfg.platform, + "SDGY", + "ACA1", + ekt_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + + /* Initialize Terminal/Satellite hooks */ + if (strncmp(ekt_hook_cfg.platform.nusec.platform_id, "ACA1", 4) == 0) { + // Terminal + is_terminal = true; + } else if (strncmp(ekt_hook_cfg.platform.nusec.platform_id, "ACA2", 4) == 0) { + // Satellite + is_terminal = false; + } else { + // Unknown + dprintf("Unknown platform ID: %s\n", ekt_hook_cfg.platform.nusec.platform_id); + goto fail; + } + + dprintf("System: Cabinet Type: %s\n", is_terminal ? "Terminal" : "Satellite"); + + // LED: terminal uses COM 3 and satellite use COM 2 + unsigned int led_port_no[2] = {is_terminal ? 3 : 2, 0}; + + // AIME: terminal uses COM 1 and satellite use COM 3 + unsigned int aime_port_no = is_terminal ? 1 : 3; + + if (FAILED(hr)) { + goto fail; + } + + hr = ekt_dll_init(&ekt_hook_cfg.dll, ekt_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + + hr = ekt_io4_hook_init(&ekt_hook_cfg.io4, is_terminal); + + if (FAILED(hr)) { + goto fail; + } + + hr = led15093_hook_init(&ekt_hook_cfg.led15093, + ekt_dll.led_init, ekt_dll.led_set_leds, led_port_no); + + if (FAILED(hr)) { + goto fail; + } + + hr = sg_reader_hook_init(&ekt_hook_cfg.aime, aime_port_no, 3, + ekt_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + + /* Initialize Unity native plugin DLL hooks + + There seems to be an issue with other DLL hooks if `LoadLibraryW` is + hooked earlier in the `ekthook` initialization. */ + + unity_hook_init(&ekt_hook_cfg.unity, ekt_hook_mod, unity_hook_callback); + + /* Initialize debug helpers */ + + spike_hook_init(get_config_path()); + + dprintf("--- End ekt_pre_startup ---\n"); + + /* Recording warning */ + check_and_display_warning(); + + /* Jump to EXE start address */ + + return ekt_startup(); + +fail: + ExitProcess(EXIT_FAILURE); +} + +BOOL WINAPI DllMain(HMODULE mod, DWORD cause, void *ctx) +{ + HRESULT hr; + + if (cause != DLL_PROCESS_ATTACH) { + return TRUE; + } + + ekt_hook_mod = mod; + + hr = process_hijack_startup(ekt_pre_startup, &ekt_startup); + + if (!SUCCEEDED(hr)) { + dprintf("Failed to hijack process startup: %x\n", (int) hr); + } + + return SUCCEEDED(hr); +} diff --git a/games/ekthook/ekt-dll.c b/games/ekthook/ekt-dll.c new file mode 100644 index 0000000..95a9fd1 --- /dev/null +++ b/games/ekthook/ekt-dll.c @@ -0,0 +1,118 @@ +#include + +#include +#include + +#include "ekthook/ekt-dll.h" + +#include "util/dll-bind.h" +#include "util/dprintf.h" + +const struct dll_bind_sym ekt_dll_syms[] = { + { + .sym = "ekt_io_init", + .off = offsetof(struct ekt_dll, init), + }, { + .sym = "ekt_io_poll", + .off = offsetof(struct ekt_dll, poll), + }, { + .sym = "ekt_io_get_opbtns", + .off = offsetof(struct ekt_dll, get_opbtns), + }, { + .sym = "ekt_io_get_gamebtns", + .off = offsetof(struct ekt_dll, get_gamebtns), + }, { + .sym = "ekt_io_get_trackball_position", + .off = offsetof(struct ekt_dll, get_trackball_position), + }, { + .sym = "ekt_io_led_init", + .off = offsetof(struct ekt_dll, led_init), + }, { + .sym = "ekt_io_led_set_colors", + .off = offsetof(struct ekt_dll, led_set_leds), + } +}; + +struct ekt_dll ekt_dll; + +// Copypasta DLL binding and diagnostic message boilerplate. +// Not much of this lends itself to being easily factored out. Also there +// will be a lot of API-specific branching code here eventually as new API +// versions get defined, so even though these functions all look the same +// now this won't remain the case forever. + +HRESULT ekt_dll_init(const struct ekt_dll_config *cfg, HINSTANCE self) +{ + uint16_t (*get_api_version)(void); + const struct dll_bind_sym *sym; + HINSTANCE owned; + HINSTANCE src; + HRESULT hr; + + assert(cfg != NULL); + assert(self != NULL); + + if (cfg->path[0] != L'\0') { + owned = LoadLibraryW(cfg->path); + + if (owned == NULL) { + hr = HRESULT_FROM_WIN32(GetLastError()); + dprintf("EKT IO: Failed to load IO DLL: %lx: %S\n", + hr, + cfg->path); + + goto end; + } + + dprintf("EKT IO: Using custom IO DLL: %S\n", cfg->path); + src = owned; + } else { + owned = NULL; + src = self; + } + + get_api_version = (void *) GetProcAddress(src, "ekt_io_get_api_version"); + + if (get_api_version != NULL) { + ekt_dll.api_version = get_api_version(); + } else { + ekt_dll.api_version = 0x0100; + dprintf("Custom IO DLL does not expose ekt_io_get_api_version, " + "assuming API version 1.0.\n" + "Please ask the developer to update their DLL.\n"); + } + + if (ekt_dll.api_version >= 0x0200) { + hr = E_NOTIMPL; + dprintf("EKT IO: Custom IO DLL implements an unsupported " + "API version (%#04x). Please update Segatools.\n", + ekt_dll.api_version); + + goto end; + } + + sym = ekt_dll_syms; + hr = dll_bind(&ekt_dll, src, &sym, _countof(ekt_dll_syms)); + + if (FAILED(hr)) { + if (src != self) { + dprintf("EKT IO: Custom IO DLL does not provide function " + "\"%s\". Please contact your IO DLL's developer for " + "further assistance.\n", + sym->sym); + + goto end; + } else { + dprintf("Internal error: could not reflect \"%s\"\n", sym->sym); + } + } + + owned = NULL; + +end: + if (owned != NULL) { + FreeLibrary(owned); + } + + return hr; +} diff --git a/games/ekthook/ekt-dll.h b/games/ekthook/ekt-dll.h new file mode 100644 index 0000000..d2d324e --- /dev/null +++ b/games/ekthook/ekt-dll.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include "ektio/ektio.h" + +struct ekt_dll { + uint16_t api_version; + HRESULT (*init)(void); + HRESULT (*poll)(void); + void (*get_opbtns)(uint8_t *opbtn); + void (*get_gamebtns)(uint32_t *gamebtn); + void (*get_trackball_position)(uint16_t *x, uint16_t *y); + HRESULT (*led_init)(void); + void (*led_set_leds)(uint8_t board, uint8_t *rgb); +}; + +struct ekt_dll_config { + wchar_t path[MAX_PATH]; +}; + +extern struct ekt_dll ekt_dll; + +HRESULT ekt_dll_init(const struct ekt_dll_config *cfg, HINSTANCE self); diff --git a/games/ekthook/ekthook.def b/games/ekthook/ekthook.def new file mode 100644 index 0000000..f03d8d8 --- /dev/null +++ b/games/ekthook/ekthook.def @@ -0,0 +1,73 @@ +LIBRARY ekthook + +EXPORTS + aime_io_get_api_version + aime_io_init + aime_io_led_set_color + aime_io_vfd_set_text + aime_io_vfd_set_state + aime_io_nfc_get_aime_id + aime_io_nfc_get_felica_id + aime_io_nfc_poll + aime_io_nfc_get_mifare_uid + aime_io_nfc_mifare_select + aime_io_nfc_mifare_set_key + aime_io_nfc_mifare_authenticate + aime_io_nfc_mifare_read_block + aime_io_nfc_felica_transact + aime_io_nfc_radio_on + aime_io_nfc_radio_off + aime_io_nfc_to_update_mode + aime_io_nfc_send_hex_data + ekt_io_get_api_version + ekt_io_get_gamebtns + ekt_io_get_opbtns + ekt_io_get_trackball_position + ekt_io_init + ekt_io_poll + ekt_io_led_init + ekt_io_led_set_colors + y3_io_get_api_version + y3_io_init + y3_io_close + y3_io_get_cards + API_DLLVersion @1 + API_GetLastError @2 + API_GetErrorMessage @3 + API_Connect @4 + API_Close @5 + API_Start @6 + API_Stop @7 + API_GetFirmVersion @8 + API_GetFirmName @9 + API_GetTargetCode @10 + API_GetStatus @11 + API_GetCounter @12 + API_ClearError @13 + API_Reset @14 + API_GetCardInfo @15 + API_GetCardInfoCharSize @16 + API_SetDevice @17 + API_SetCommand @18 + API_FirmwareUpdate @19 + API_Calibration @20 + API_GetCalibrationResult @21 + API_GetProcTime @22 + API_GetMemStatus @23 + API_GetMemCounter @24 + API_SetSysControl @25 + API_GetSysControl @26 + API_SetParameter @27 + API_GetParameter @28 + API_TestReset @29 + API_DebugReset @30 + API_GetBoardType @31 + API_GetCardDataSize @32 + API_GetFirmDate @33 + API_SystemCommand @34 + API_CalcCheckSum @35 + API_GetCheckSumResult @36 + API_BlockRead @37 + API_GetBlockReadResult @38 + API_BlockWrite @39 + API_GetDebugParam @40 diff --git a/games/ekthook/io4.c b/games/ekthook/io4.c new file mode 100644 index 0000000..2eec5e5 --- /dev/null +++ b/games/ekthook/io4.c @@ -0,0 +1,223 @@ +#include "io4.h" + +#include + +#include +#include +#include + +#include "board/io4.h" + +#include "ekthook/ekt-dll.h" + +#include "util/dprintf.h" + +static HRESULT ekt_io4_poll(void *ctx, struct io4_state *state); +static uint16_t coins; + +static const struct io4_ops ekt_io4_ops = { + .poll = ekt_io4_poll, +}; + +static bool io_is_terminal; + +HRESULT ekt_io4_hook_init(const struct io4_config *cfg, bool is_terminal) +{ + HRESULT hr; + + assert(ekt_dll.init != NULL); + + hr = io4_hook_init(cfg, &ekt_io4_ops, NULL, L"ekt", false); + + io_is_terminal = is_terminal; + + if (FAILED(hr)) { + return hr; + } + + return ekt_dll.init(); +} + +static HRESULT ekt_io4_poll(void *ctx, struct io4_state *state) +{ + uint8_t opbtn; + uint16_t x, y; + uint32_t gamebtn; + HRESULT hr; + + assert(ekt_dll.poll != NULL); + assert(ekt_dll.get_opbtns != NULL); + assert(ekt_dll.get_gamebtns != NULL); + assert(ekt_dll.get_trackball_position != NULL); + + memset(state, 0, sizeof(*state)); + + hr = ekt_dll.poll(); + + if (FAILED(hr)) { + return hr; + } + + opbtn = 0; + gamebtn = 0; + x = 0; + y = 0; + + ekt_dll.get_opbtns(&opbtn); + ekt_dll.get_gamebtns(&gamebtn); + ekt_dll.get_trackball_position(&x, &y); + + if (opbtn & EKT_IO_OPBTN_TEST) { + state->buttons[0] |= IO4_BUTTON_TEST; + } + + if (opbtn & EKT_IO_OPBTN_SERVICE) { + state->buttons[0] |= IO4_BUTTON_SERVICE; + } + + if (opbtn & EKT_IO_OPBTN_SW1) { + state->buttons[0] |= 1 << 2; + } + + if (opbtn & EKT_IO_OPBTN_SW2) { + state->buttons[0] |= 1 << 3; + } + + if (opbtn & EKT_IO_OPBTN_COIN) { + coins++; + } + state->chutes[0] = coins << 8; + + if (!io_is_terminal) { + if (gamebtn & EKT_IO_GAMEBTN_HOUGU) { + state->buttons[1] |= 1 << 14; + } + + if (gamebtn & EKT_IO_GAMEBTN_RYUUHA) { + state->buttons[1] |= 1 << 12; + } + + if (gamebtn & EKT_IO_GAMEBTN_MENU) { + state->buttons[0] |= 1 << 13; + } + + if (gamebtn & EKT_IO_GAMEBTN_START) { + state->buttons[0] |= 1 << 7; + } + + if (gamebtn & EKT_IO_GAMEBTN_STRATAGEM) { + state->buttons[1] |= 1 << 15; + } + + if (gamebtn & EKT_IO_GAMEBTN_STRATAGEM_LOCK) { + state->buttons[1] |= 1 << 13; + } + + if (gamebtn & EKT_IO_GAMEBTN_VOL_DOWN) { + state->buttons[1] |= 1 << 10; + } + + if (gamebtn & EKT_IO_GAMEBTN_VOL_UP) { + state->buttons[1] |= 1 << 11; + } + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_0) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C2 : EKT_NUMPAD_TERM_C2; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R4 : EKT_NUMPAD_TERM_R4; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_1) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C1 : EKT_NUMPAD_TERM_C1; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R1 : EKT_NUMPAD_TERM_R1; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_2) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C2 : EKT_NUMPAD_TERM_C2; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R1 : EKT_NUMPAD_TERM_R1; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_3) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C3 : EKT_NUMPAD_TERM_C3; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R1 : EKT_NUMPAD_TERM_R1; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_4) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C1 : EKT_NUMPAD_TERM_C1; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R2 : EKT_NUMPAD_TERM_R2; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_5) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C2 : EKT_NUMPAD_TERM_C2; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R2 : EKT_NUMPAD_TERM_R2; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_6) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C3 : EKT_NUMPAD_TERM_C3; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R2 : EKT_NUMPAD_TERM_R2; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_7) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C1 : EKT_NUMPAD_TERM_C1; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R3 : EKT_NUMPAD_TERM_R3; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_8) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C2 : EKT_NUMPAD_TERM_C2; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R3 : EKT_NUMPAD_TERM_R3; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_9) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C3 : EKT_NUMPAD_TERM_C3; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R3 : EKT_NUMPAD_TERM_R3; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_CLEAR) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C1 : EKT_NUMPAD_TERM_C1; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R4 : EKT_NUMPAD_TERM_R4; + } + + if (gamebtn & EKT_IO_GAMEBTN_NUMPAD_ENTER) { + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_C3 : EKT_NUMPAD_TERM_C3; + state->buttons[0] |= !io_is_terminal ? EKT_NUMPAD_SATE_R4 : EKT_NUMPAD_TERM_R4; + } + + if (io_is_terminal) { + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_CANCEL) { + state->buttons[1] |= 1 << 0; + } + + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_DECIDE) { + state->buttons[1] |= 1 << 1; + } + + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_LEFT) { + state->buttons[0] |= 1 << 3; + } + + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_UP) { + state->buttons[0] |= 1 << 5; + } + + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_RIGHT) { + state->buttons[0] |= 1 << 2; + } + + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_DOWN) { + state->buttons[0] |= 1 << 4; + } + + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_LEFT_2) { + state->buttons[1] |= 1 << 3; + } + + if (gamebtn & EKT_IO_GAMEBTN_TERMINAL_RIGHT_2) { + state->buttons[1] |= 1 << 2; + } + } + + state->spinners[2] = x; + state->spinners[3] = y; + + return S_OK; +} diff --git a/games/ekthook/io4.h b/games/ekthook/io4.h new file mode 100644 index 0000000..4fff5f3 --- /dev/null +++ b/games/ekthook/io4.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include "board/io4.h" + +enum { + EKT_NUMPAD_SATE_R1 = 1 << 1, + EKT_NUMPAD_SATE_R2 = 1 << 0, + EKT_NUMPAD_SATE_R3 = 1 << 15, + EKT_NUMPAD_SATE_R4 = 1 << 14, + EKT_NUMPAD_SATE_C1 = 1 << 12, + EKT_NUMPAD_SATE_C2 = 1 << 11, + EKT_NUMPAD_SATE_C3 = 1 << 10, + EKT_NUMPAD_TERM_R1 = 1 << 1, + EKT_NUMPAD_TERM_R2 = 1 << 0, + EKT_NUMPAD_TERM_R3 = 1 << 15, + EKT_NUMPAD_TERM_R4 = 1 << 14, + EKT_NUMPAD_TERM_C1 = 1 << 13, + EKT_NUMPAD_TERM_C2 = 1 << 12, + EKT_NUMPAD_TERM_C3 = 1 << 11, +}; + +HRESULT ekt_io4_hook_init(const struct io4_config *cfg, bool is_terminal); diff --git a/games/ekthook/meson.build b/games/ekthook/meson.build new file mode 100644 index 0000000..2b3ef34 --- /dev/null +++ b/games/ekthook/meson.build @@ -0,0 +1,31 @@ +shared_library( + 'ekthook', + name_prefix : '', + include_directories : inc, + implicit_include_directories : false, + vs_module_defs : 'ekthook.def', + dependencies : [ + capnhook.get_variable('hook_dep'), + capnhook.get_variable('hooklib_dep') + ], + link_with : [ + aimeio_lib, + board_lib, + ektio_lib, + hooklib_lib, + jvs_lib, + platform_lib, + unityhook_lib, + util_lib, + y3io_lib, + ], + sources : [ + 'config.c', + 'config.h', + 'dllmain.c', + 'ekt-dll.c', + 'ekt-dll.h', + 'io4.c', + 'io4.h', + ], +) diff --git a/games/ektio/backend.h b/games/ektio/backend.h new file mode 100644 index 0000000..4fcf885 --- /dev/null +++ b/games/ektio/backend.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "ektio/ektio.h" + +struct ekt_io_backend { + void (*get_gamebtns)(uint32_t *gamebtn); + void (*get_trackball)(uint16_t *x, uint16_t *y); +}; diff --git a/games/ektio/config.c b/games/ektio/config.c new file mode 100644 index 0000000..7108d66 --- /dev/null +++ b/games/ektio/config.c @@ -0,0 +1,77 @@ +#include + +#include +#include +#include + +#include "ektio/config.h" + +#include + + +void ekt_kb_config_load( + struct ekt_kb_config *cfg, + const wchar_t *filename) { + + cfg->vk_menu = GetPrivateProfileIntW(L"keyboard", L"menu", 'A', filename); + cfg->vk_start = GetPrivateProfileIntW(L"keyboard", L"start", 'S', filename); + cfg->vk_stratagem = GetPrivateProfileIntW(L"keyboard", L"stratagem", 'D', filename); + cfg->vk_stratagem_lock = GetPrivateProfileIntW(L"keyboard", L"stratagem_lock", 'F', filename); + cfg->vk_hougu = GetPrivateProfileIntW(L"keyboard", L"hougu", 'G', filename); + cfg->vk_ryuuha = GetPrivateProfileIntW(L"keyboard", L"ryuuha", 'H', filename); + + cfg->vk_tenkey_0 = GetPrivateProfileIntW(L"keyboard", L"tenkey_0", VK_NUMPAD0, filename); + cfg->vk_tenkey_1 = GetPrivateProfileIntW(L"keyboard", L"tenkey_1", VK_NUMPAD1, filename); + cfg->vk_tenkey_2 = GetPrivateProfileIntW(L"keyboard", L"tenkey_2", VK_NUMPAD2, filename); + cfg->vk_tenkey_3 = GetPrivateProfileIntW(L"keyboard", L"tenkey_3", VK_NUMPAD3, filename); + cfg->vk_tenkey_4 = GetPrivateProfileIntW(L"keyboard", L"tenkey_4", VK_NUMPAD4, filename); + cfg->vk_tenkey_5 = GetPrivateProfileIntW(L"keyboard", L"tenkey_5", VK_NUMPAD5, filename); + cfg->vk_tenkey_6 = GetPrivateProfileIntW(L"keyboard", L"tenkey_6", VK_NUMPAD6, filename); + cfg->vk_tenkey_7 = GetPrivateProfileIntW(L"keyboard", L"tenkey_7", VK_NUMPAD7, filename); + cfg->vk_tenkey_8 = GetPrivateProfileIntW(L"keyboard", L"tenkey_8", VK_NUMPAD8, filename); + cfg->vk_tenkey_9 = GetPrivateProfileIntW(L"keyboard", L"tenkey_9", VK_NUMPAD9, filename); + cfg->vk_tenkey_clear = GetPrivateProfileIntW(L"keyboard", L"tenkey_clear", VK_DECIMAL, filename); + cfg->vk_tenkey_enter = GetPrivateProfileIntW(L"keyboard", L"tenkey_enter", VK_RETURN, filename); + + cfg->vk_vol_down = GetPrivateProfileIntW(L"keyboard", L"vol_down", VK_NEXT, filename); + cfg->vk_vol_up = GetPrivateProfileIntW(L"keyboard", L"vol_up", VK_PRIOR, filename); + + cfg->vk_terminal_decide = GetPrivateProfileIntW(L"keyboard", L"decide", 'A', filename); + cfg->vk_terminal_cancel = GetPrivateProfileIntW(L"keyboard", L"cancel", 'S', filename); + cfg->vk_terminal_up = GetPrivateProfileIntW(L"keyboard", L"up", VK_UP, filename); + cfg->vk_terminal_right = GetPrivateProfileIntW(L"keyboard", L"right", VK_RIGHT, filename); + cfg->vk_terminal_down = GetPrivateProfileIntW(L"keyboard", L"down", VK_DOWN, filename); + cfg->vk_terminal_left = GetPrivateProfileIntW(L"keyboard", L"left", VK_LEFT, filename); + cfg->vk_terminal_left_2 = GetPrivateProfileIntW(L"keyboard", L"left2", 'Q', filename); + cfg->vk_terminal_right_2 = GetPrivateProfileIntW(L"keyboard", L"right2", 'W', filename); + + cfg->x_down = GetPrivateProfileIntW(L"keyboard", L"trackball_left", VK_LEFT, filename); + cfg->x_up = GetPrivateProfileIntW(L"keyboard", L"trackball_right", VK_RIGHT, filename); + cfg->y_down = GetPrivateProfileIntW(L"keyboard", L"trackball_up", VK_UP, filename); + cfg->y_up = GetPrivateProfileIntW(L"keyboard", L"trackball_down", VK_DOWN, filename); + cfg->speed = GetPrivateProfileIntW(L"keyboard", L"speed_modifier", 1, filename); +} + +void ekt_io_config_load( + struct ekt_io_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + cfg->vk_test = GetPrivateProfileIntW(L"io4", L"test", '1', filename); + cfg->vk_service = GetPrivateProfileIntW(L"io4", L"service", '2', filename); + cfg->vk_coin = GetPrivateProfileIntW(L"io4", L"coin", '3', filename); + cfg->vk_sw1 = GetPrivateProfileIntW(L"io4", L"sw1", '4', filename); + cfg->vk_sw2 = GetPrivateProfileIntW(L"io4", L"sw2", '5', filename); + + GetPrivateProfileStringW( + L"io4", + L"mode", + L"keyboard", + cfg->mode, + _countof(cfg->mode), + filename); + + ekt_kb_config_load(&cfg->kb, filename); +} diff --git a/games/ektio/config.h b/games/ektio/config.h new file mode 100644 index 0000000..0f828e7 --- /dev/null +++ b/games/ektio/config.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include + +#include + +struct ekt_kb_config { + uint8_t vk_menu; + uint8_t vk_start; + uint8_t vk_stratagem; + uint8_t vk_stratagem_lock; + uint8_t vk_hougu; + uint8_t vk_ryuuha; + + uint8_t vk_tenkey_0; + uint8_t vk_tenkey_1; + uint8_t vk_tenkey_2; + uint8_t vk_tenkey_3; + uint8_t vk_tenkey_4; + uint8_t vk_tenkey_5; + uint8_t vk_tenkey_6; + uint8_t vk_tenkey_7; + uint8_t vk_tenkey_8; + uint8_t vk_tenkey_9; + uint8_t vk_tenkey_clear; + uint8_t vk_tenkey_enter; + + uint8_t vk_vol_down; + uint8_t vk_vol_up; + + uint8_t vk_terminal_up; + uint8_t vk_terminal_right; + uint8_t vk_terminal_down; + uint8_t vk_terminal_left; + uint8_t vk_terminal_left_2; + uint8_t vk_terminal_right_2; + uint8_t vk_terminal_cancel; + uint8_t vk_terminal_decide; + + uint8_t x_down; + uint8_t x_up; + uint8_t y_down; + uint8_t y_up; + uint8_t speed; +}; + +struct ekt_io_config { + uint8_t vk_test; + uint8_t vk_service; + uint8_t vk_coin; + uint8_t vk_sw1; + uint8_t vk_sw2; + + wchar_t mode[12]; + struct ekt_kb_config kb; +}; + +void ekt_kb_config_load(struct ekt_kb_config *cfg, const wchar_t *filename); +void ekt_io_config_load( + struct ekt_io_config *cfg, + const wchar_t *filename); diff --git a/games/ektio/ektio.c b/games/ektio/ektio.c new file mode 100644 index 0000000..2ebb879 --- /dev/null +++ b/games/ektio/ektio.c @@ -0,0 +1,108 @@ +#include +#include +#include + +#include + +#include "ektio/ektio.h" + +#include + +#include "keyboard.h" +#include "ektio/config.h" +#include "util/dprintf.h" +#include "util/env.h" +#include "util/str.h" + +static uint8_t ekt_opbtn; +static uint32_t ekt_gamebtn; +static uint8_t ekt_stick_x; +static uint8_t ekt_stick_y; +static struct ekt_io_config ekt_io_cfg; +static const struct ekt_io_backend* ekt_io_backend; +static bool ekt_io_coin; + +uint16_t ekt_io_get_api_version(void) { + return 0x0100; +} + +HRESULT ekt_io_init(void) { + ekt_io_config_load(&ekt_io_cfg, get_config_path()); + + HRESULT hr; + + if (wstr_ieq(ekt_io_cfg.mode, L"keyboard")) { + hr = ekt_kb_init(&ekt_io_cfg.kb, &ekt_io_backend); + } else { + hr = E_INVALIDARG; + dprintf("EKT IO: Invalid IO mode \"%S\", use keyboard\n", + ekt_io_cfg.mode); + } + + return hr; +} + +HRESULT ekt_io_poll(void) { + assert(ekt_io_backend != NULL); + + ekt_opbtn = 0; + ekt_gamebtn = 0; + ekt_stick_x = 0; + ekt_stick_y = 0; + + if (GetAsyncKeyState(ekt_io_cfg.vk_test) & 0x8000) { + ekt_opbtn |= EKT_IO_OPBTN_TEST; + } + + if (GetAsyncKeyState(ekt_io_cfg.vk_service) & 0x8000) { + ekt_opbtn |= EKT_IO_OPBTN_SERVICE; + } + + if (GetAsyncKeyState(ekt_io_cfg.vk_sw1) & 0x8000) { + ekt_opbtn |= EKT_IO_OPBTN_SW1; + } + + if (GetAsyncKeyState(ekt_io_cfg.vk_sw2) & 0x8000) { + ekt_opbtn |= EKT_IO_OPBTN_SW2; + } + + if (GetAsyncKeyState(ekt_io_cfg.vk_coin) & 0x8000) { + if (!ekt_io_coin) { + ekt_io_coin = true; + ekt_opbtn |= EKT_IO_OPBTN_COIN; + } + } else { + ekt_io_coin = false; + } + + return S_OK; +} + +void ekt_io_get_opbtns(uint8_t* opbtn) { + if (opbtn != NULL) { + *opbtn = ekt_opbtn; + } +} + +void ekt_io_get_gamebtns(uint32_t* btn) { + assert(ekt_io_backend != NULL); + assert(btn != NULL); + + ekt_io_backend->get_gamebtns(btn); +} + +void ekt_io_get_trackball_position(uint16_t* stick_x, uint16_t* stick_y) { + assert(ekt_io_backend != NULL); + assert(stick_x != NULL); + assert(stick_y != NULL); + + ekt_io_backend->get_trackball(stick_x, stick_y); +} + +HRESULT ekt_io_led_init(void) { + return S_OK; +} + +void ekt_io_led_set_colors(uint8_t board, uint8_t* rgb) { + return; +} diff --git a/games/ektio/ektio.h b/games/ektio/ektio.h new file mode 100644 index 0000000..6915375 --- /dev/null +++ b/games/ektio/ektio.h @@ -0,0 +1,106 @@ +#pragma once + +#include + +#include + +enum { + EKT_IO_OPBTN_TEST = 0x01, + EKT_IO_OPBTN_SERVICE = 0x02, + EKT_IO_OPBTN_COIN = 0x04, + EKT_IO_OPBTN_SW1 = 0x08, + EKT_IO_OPBTN_SW2 = 0x10, +}; + +enum { + EKT_IO_GAMEBTN_MENU = 0x01, + EKT_IO_GAMEBTN_START = 0x02, + EKT_IO_GAMEBTN_STRATAGEM = 0x04, + EKT_IO_GAMEBTN_STRATAGEM_LOCK = 0x08, + EKT_IO_GAMEBTN_HOUGU = 0x10, + EKT_IO_GAMEBTN_RYUUHA = 0x20, + EKT_IO_GAMEBTN_NUMPAD_0 = 0x100, + EKT_IO_GAMEBTN_NUMPAD_1 = 0x200, + EKT_IO_GAMEBTN_NUMPAD_2 = 0x400, + EKT_IO_GAMEBTN_NUMPAD_3 = 0x800, + EKT_IO_GAMEBTN_NUMPAD_4 = 0x1000, + EKT_IO_GAMEBTN_NUMPAD_5 = 0x2000, + EKT_IO_GAMEBTN_NUMPAD_6 = 0x4000, + EKT_IO_GAMEBTN_NUMPAD_7 = 0x8000, + EKT_IO_GAMEBTN_NUMPAD_8 = 0x10000, + EKT_IO_GAMEBTN_NUMPAD_9 = 0x20000, + EKT_IO_GAMEBTN_NUMPAD_CLEAR = 0x40000, + EKT_IO_GAMEBTN_NUMPAD_ENTER = 0x80000, + EKT_IO_GAMEBTN_VOL_UP = 0x100000, + EKT_IO_GAMEBTN_VOL_DOWN = 0x200000, + EKT_IO_GAMEBTN_TERMINAL_LEFT = 0x400000, + EKT_IO_GAMEBTN_TERMINAL_UP = 0x800000, + EKT_IO_GAMEBTN_TERMINAL_RIGHT = 0x1000000, + EKT_IO_GAMEBTN_TERMINAL_DOWN = 0x2000000, + EKT_IO_GAMEBTN_TERMINAL_LEFT_2 = 0x4000000, + EKT_IO_GAMEBTN_TERMINAL_RIGHT_2 = 0x8000000, + EKT_IO_GAMEBTN_TERMINAL_DECIDE = 0x10000000, + EKT_IO_GAMEBTN_TERMINAL_CANCEL = 0x20000000, +}; + +/* Get the version of the Eiketsu Taisen IO API that this DLL supports. This + function should return a positive 16-bit integer, where the high byte is + the major version and the low byte is the minor version (as defined by the + Semantic Versioning standard). + + The latest API version as of this writing is 0x0100. */ + +uint16_t ekt_io_get_api_version(void); + +/* Initialize the IO DLL. This is the second function that will be called on + your DLL, after ekt_io_get_api_version. + + All subsequent calls to this API may originate from arbitrary threads. + + Minimum API version: 0x0100 */ + +HRESULT ekt_io_init(void); + +/* Send any queued outputs (of which there are currently none, though this may + change in subsequent API versions) and retrieve any new inputs. + + Minimum API version: 0x0100 */ + +HRESULT ekt_io_poll(void); + +/* Get the state of the cabinet's operator buttons as of the last poll. See + EKT_IO_OPBTN enum above: this contains bit mask definitions for button + states returned in *opbtn. All buttons are active-high. + + Minimum API version: 0x0100 */ + +void ekt_io_get_opbtns(uint8_t *opbtn); + +/* Get the state of the cabinet's gameplay buttons as of the last poll. See + EKT_IO_GAMEBTN enum above: this contains bit mask definitions for button + states returned in *gamebtn. All buttons are active-high. + + Minimum API version: 0x0100 */ + +void ekt_io_get_gamebtns(uint32_t *gamebtn); + +/* Get the position of the trackball as of the last poll. + + Minimum API version: 0x0100 */ + +void ekt_io_get_trackball_position(uint16_t *stick_x, uint16_t *stick_y); + +/* Initialize LED emulation. This function will be called before any + other ekt_io_led_*() function calls. + + All subsequent calls may originate from arbitrary threads and some may + overlap with each other. Ensuring synchronization inside your IO DLL is + your responsibility. */ + +HRESULT ekt_io_led_init(void); + +/* Update the RGB LEDs. + + Exact layout is TBD. */ + +void ekt_io_led_set_colors(uint8_t board, uint8_t *rgb); diff --git a/games/ektio/keyboard.c b/games/ektio/keyboard.c new file mode 100644 index 0000000..68ee47b --- /dev/null +++ b/games/ektio/keyboard.c @@ -0,0 +1,176 @@ +#include + +#include +#include +#include +#include + +#include "ektio/backend.h" +#include "ektio/config.h" +#include "ektio/ektio.h" +#include "ektio/keyboard.h" + +#include "util/dprintf.h" + +static void ekt_kb_get_gamebtns(uint32_t* gamebtn_out); +static void ekt_kb_get_trackball(uint16_t* x, uint16_t* y); + +static const struct ekt_io_backend ekt_kb_backend = { + .get_gamebtns = ekt_kb_get_gamebtns, + .get_trackball = ekt_kb_get_trackball +}; + +static uint16_t current_x; +static uint16_t current_y; + +static struct ekt_kb_config config; + +HRESULT ekt_kb_init(const struct ekt_kb_config* cfg, const struct ekt_io_backend** backend) { + assert(cfg != NULL); + assert(backend != NULL); + + dprintf("Keyboard: Using keyboard input\n"); + *backend = &ekt_kb_backend; + config = *cfg; + + return S_OK; +} + +static void ekt_kb_get_gamebtns(uint32_t* gamebtn_out) { + assert(gamebtn_out != NULL); + + uint32_t gamebtn = 0; + + if (GetAsyncKeyState(config.vk_hougu) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_HOUGU; + } + + if (GetAsyncKeyState(config.vk_menu) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_MENU; + } + + if (GetAsyncKeyState(config.vk_start) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_START; + } + + if (GetAsyncKeyState(config.vk_stratagem) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_STRATAGEM; + } + + if (GetAsyncKeyState(config.vk_stratagem_lock) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_STRATAGEM_LOCK; + } + + if (GetAsyncKeyState(config.vk_ryuuha) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_RYUUHA; + } + + if (GetAsyncKeyState(config.vk_tenkey_0) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_0; + } + + if (GetAsyncKeyState(config.vk_tenkey_1) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_1; + } + + if (GetAsyncKeyState(config.vk_tenkey_2) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_2; + } + + if (GetAsyncKeyState(config.vk_tenkey_3) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_3; + } + + if (GetAsyncKeyState(config.vk_tenkey_4) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_4; + } + + if (GetAsyncKeyState(config.vk_tenkey_5) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_5; + } + + if (GetAsyncKeyState(config.vk_tenkey_6) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_6; + } + + if (GetAsyncKeyState(config.vk_tenkey_7) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_7; + } + + if (GetAsyncKeyState(config.vk_tenkey_8) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_8; + } + + if (GetAsyncKeyState(config.vk_tenkey_9) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_9; + } + + if (GetAsyncKeyState(config.vk_tenkey_clear) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_CLEAR; + } + + if (GetAsyncKeyState(config.vk_tenkey_enter) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_NUMPAD_ENTER; + } + + if (GetAsyncKeyState(config.vk_vol_down) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_VOL_DOWN; + } + + if (GetAsyncKeyState(config.vk_vol_up) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_VOL_UP; + } + + if (GetAsyncKeyState(config.vk_terminal_cancel) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_CANCEL; + } + + if (GetAsyncKeyState(config.vk_terminal_decide) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_DECIDE; + } + + if (GetAsyncKeyState(config.vk_terminal_up) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_UP; + } + + if (GetAsyncKeyState(config.vk_terminal_right) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_RIGHT; + } + + if (GetAsyncKeyState(config.vk_terminal_down) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_DOWN; + } + + if (GetAsyncKeyState(config.vk_terminal_left) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_LEFT; + } + + if (GetAsyncKeyState(config.vk_terminal_left_2) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_LEFT_2; + } + + if (GetAsyncKeyState(config.vk_terminal_right_2) & 0x8000) { + gamebtn |= EKT_IO_GAMEBTN_TERMINAL_RIGHT_2; + } + + *gamebtn_out = gamebtn; +} + +static void ekt_kb_get_trackball(uint16_t* x, uint16_t* y) { + assert(x != NULL); + assert(y != NULL); + + if (GetAsyncKeyState(config.x_down) & 0x8000) { + current_x -= config.speed; + } else if (GetAsyncKeyState(config.x_up) & 0x8000) { + current_x += config.speed; + } + if (GetAsyncKeyState(config.y_down) & 0x8000) { + current_y += config.speed; + } else if (GetAsyncKeyState(config.y_up) & 0x8000) { + current_y -= config.speed; + } + + *x = current_x; + *y = current_y; +} diff --git a/games/ektio/keyboard.h b/games/ektio/keyboard.h new file mode 100644 index 0000000..d0b25dd --- /dev/null +++ b/games/ektio/keyboard.h @@ -0,0 +1,8 @@ +#pragma once + +#include + +#include "ektio/backend.h" +#include "ektio/config.h" + +HRESULT ekt_kb_init(const struct ekt_kb_config *cfg, const struct ekt_io_backend **backend); diff --git a/games/ektio/meson.build b/games/ektio/meson.build new file mode 100644 index 0000000..4ea0e68 --- /dev/null +++ b/games/ektio/meson.build @@ -0,0 +1,18 @@ +ektio_lib = static_library( + 'ektio', + name_prefix : '', + include_directories : inc, + implicit_include_directories : false, + dependencies : [ + xinput_lib, + ], + sources : [ + 'ektio.c', + 'ektio.h', + 'config.c', + 'config.h', + 'backend.h', + 'keyboard.c', + 'keyboard.h', + ], +) diff --git a/games/fgohook/config.c b/games/fgohook/config.c index 766240c..b5b1d24 100644 --- a/games/fgohook/config.c +++ b/games/fgohook/config.c @@ -120,7 +120,7 @@ void fgo_hook_config_load( io4_config_load(&cfg->io4, filename); vfd_config_load(&cfg->vfd, filename); touch_screen_config_load(&cfg->touch, filename); - printer_config_load(&cfg->printer, filename); + printer_chc_config_load(&cfg->printer, filename); fgo_deck_config_load(&cfg->deck, filename); ftdi_config_load(&cfg->ftdi, filename); led15093_config_load(&cfg->led15093, filename); diff --git a/games/fgohook/config.h b/games/fgohook/config.h index ca8895a..57b8bdd 100644 --- a/games/fgohook/config.h +++ b/games/fgohook/config.h @@ -7,7 +7,7 @@ #include "hooklib/dvd.h" #include "hooklib/touch.h" -#include "hooklib/printer.h" +#include "hooklib/printer_chc.h" #include "gfxhook/config.h" @@ -24,7 +24,7 @@ struct fgo_hook_config { struct io4_config io4; struct vfd_config vfd; struct touch_screen_config touch; - struct printer_config printer; + struct printer_chc_config printer; struct deck_config deck; struct ftdi_config ftdi; struct led15093_config led15093; diff --git a/games/fgohook/dllmain.c b/games/fgohook/dllmain.c index fcf5132..43b36dc 100644 --- a/games/fgohook/dllmain.c +++ b/games/fgohook/dllmain.c @@ -29,7 +29,7 @@ #include "hooklib/dll.h" #include "hooklib/dvd.h" #include "hooklib/touch.h" -#include "hooklib/printer.h" +#include "hooklib/printer_chc.h" #include "hooklib/createprocess.h" #include "hooklib/serial.h" #include "hooklib/spike.h" @@ -81,7 +81,7 @@ static DWORD CALLBACK fgo_pre_startup(void) /* Hook external DLL APIs */ - printer_hook_init(&fgo_hook_cfg.printer, 4, fgo_hook_mod); + printer_chc_hook_init(&fgo_hook_cfg.printer, 4, fgo_hook_mod); if (fgo_hook_cfg.printer.enable) { dll_hook_push(fgo_hook_mod, L"C330Ausb.dll"); dll_hook_push(fgo_hook_mod, L"C330AFWDLusb.dll"); @@ -143,7 +143,7 @@ static DWORD CALLBACK fgo_pre_startup(void) goto fail; } - hr = createprocess_push_hook_a("am/amdaemon.exe", "inject -d -k fgohook.dll ", "", false); + hr = createprocess_push_hook_a("am/amdaemon.exe", "inject -d -k fgohook.dll ", "", false, false); if (FAILED(hr)) { goto fail; diff --git a/games/fgohook/fgohook.def b/games/fgohook/fgohook.def index b341a65..b7dee86 100644 --- a/games/fgohook/fgohook.def +++ b/games/fgohook/fgohook.def @@ -56,7 +56,7 @@ EXPORTS chcusb_selectPrinter chcusb_selectPrinterSN chcusb_getPrinterInfo - chcusb_imageformat=chcusb_imageformat_330 + chcusb_imageformat chcusb_setmtf chcusb_makeGamma chcusb_setIcctable diff --git a/games/kemonohook/config.c b/games/kemonohook/config.c index c008d88..bd539dd 100644 --- a/games/kemonohook/config.c +++ b/games/kemonohook/config.c @@ -126,7 +126,7 @@ void kemono_hook_config_load( vfd_config_load(&cfg->vfd, filename); kemono_dll_config_load(&cfg->dll, filename); unity_config_load(&cfg->unity, filename); - printer_config_load(&cfg->printer, filename); + printer_chc_config_load(&cfg->printer, filename); amex_config_load(&cfg->amex, filename); led15093_config_load(&cfg->led15093, filename); } diff --git a/games/kemonohook/config.h b/games/kemonohook/config.h index bf76cff..2d3e1ea 100644 --- a/games/kemonohook/config.h +++ b/games/kemonohook/config.h @@ -22,7 +22,7 @@ struct kemono_hook_config { struct vfd_config vfd; struct kemono_dll_config dll; struct unity_config unity; - struct printer_config printer; + struct printer_chc_config printer; struct amex_config amex; struct led15093_config led15093; }; diff --git a/games/kemonohook/dllmain.c b/games/kemonohook/dllmain.c index f429299..60d53da 100644 --- a/games/kemonohook/dllmain.c +++ b/games/kemonohook/dllmain.c @@ -7,7 +7,7 @@ #include "hook/iohook.h" #include "hook/process.h" #include "hook/table.h" -#include "hooklib/printer.h" +#include "hooklib/printer_chc.h" #include "hooklib/serial.h" #include "hooklib/spike.h" #include "kemonohook/config.h" @@ -66,7 +66,7 @@ static DWORD CALLBACK kemono_pre_startup(void) { goto fail; } - printer_hook_init(&kemono_hook_cfg.printer, 0, kemono_hook_mod); + printer_chc_hook_init(&kemono_hook_cfg.printer, 0, kemono_hook_mod); printer_set_dimensions(720, 1028); // printer doesn't call setimageformat /* Initialize emulation hooks */ diff --git a/games/sekitohook/config.c b/games/sekitohook/config.c new file mode 100644 index 0000000..4aae6cb --- /dev/null +++ b/games/sekitohook/config.c @@ -0,0 +1,113 @@ +#include "amex/config.h" + +#include +#include + +#include "board/config.h" +#include "gfxhook/config.h" + +#include "sekitohook/config.h" +#include "sekitohook/sekito-dll.h" + +#include "hooklib/config.h" + +#include "platform/config.h" + +void led15093_config_load(struct led15093_config *cfg, const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + wchar_t tmpstr[16]; + + memset(cfg->board_number, ' ', sizeof(cfg->board_number)); + memset(cfg->chip_number, ' ', sizeof(cfg->chip_number)); + memset(cfg->boot_chip_number, ' ', sizeof(cfg->boot_chip_number)); + + cfg->enable = GetPrivateProfileIntW(L"led15093", L"enable", 1, filename); + cfg->port_no[0] = GetPrivateProfileIntW(L"led15093", L"portNo1", 0, filename); + cfg->port_no[1] = GetPrivateProfileIntW(L"led15093", L"portNo2", 0, filename); + cfg->high_baudrate = GetPrivateProfileIntW(L"led15093", L"highBaud", 0, filename); + cfg->fw_ver = GetPrivateProfileIntW(L"led15093", L"fwVer", 0xA0, filename); + cfg->fw_sum = GetPrivateProfileIntW(L"led15093", L"fwSum", 0xAA53, filename); + + GetPrivateProfileStringW( + L"led15093", + L"boardNumber", + L"15093-06", + tmpstr, + _countof(tmpstr), + filename); + + size_t n = wcstombs(cfg->board_number, tmpstr, sizeof(cfg->board_number)); + for (int i = n; i < sizeof(cfg->board_number); i++) + { + cfg->board_number[i] = ' '; + } + + GetPrivateProfileStringW( + L"led15093", + L"chipNumber", + L"6710A", + tmpstr, + _countof(tmpstr), + filename); + + n = wcstombs(cfg->chip_number, tmpstr, sizeof(cfg->chip_number)); + for (int i = n; i < sizeof(cfg->chip_number); i++) + { + cfg->chip_number[i] = ' '; + } + + GetPrivateProfileStringW( + L"led15093", + L"bootChipNumber", + L"6709 ", + tmpstr, + _countof(tmpstr), + filename); + + n = wcstombs(cfg->boot_chip_number, tmpstr, sizeof(cfg->boot_chip_number)); + for (int i = n; i < sizeof(cfg->boot_chip_number); i++) + { + cfg->boot_chip_number[i] = ' '; + } +} + +void sekito_dll_config_load( + struct sekito_dll_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + GetPrivateProfileStringW( + L"sekitoio", + L"path", + L"", + cfg->path, + _countof(cfg->path), + filename); +} + + +void sekito_hook_config_load( + struct sekito_hook_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + platform_config_load(&cfg->platform, filename); + aime_config_load(&cfg->aime, filename); + aime_config_load_bykey(&cfg->aime_queue, filename, L"aime2"); + io4_config_load(&cfg->io4, filename); + dvd_config_load(&cfg->dvd, filename); + led15093_config_load(&cfg->led15093, filename); + y3_config_load(&cfg->y3, filename); + printer_chc_config_load(&cfg->printer, filename); + sekito_dll_config_load(&cfg->dll, filename); + gfx_config_load(&cfg->gfx, filename); + amex_config_load(&cfg->amex, filename); + amvideo_config_load(&cfg->amvideo, filename); +} diff --git a/games/sekitohook/config.h b/games/sekitohook/config.h new file mode 100644 index 0000000..a1274b5 --- /dev/null +++ b/games/sekitohook/config.h @@ -0,0 +1,41 @@ +#pragma once + +#include + +#include "amex/amex.h" +#include "board/sg-reader.h" +#include "board/config.h" +#include "board/led15093.h" +#include "gfxhook/gfx.h" + +#include "sekitohook/sekito-dll.h" + +#include "hooklib/config.h" +#include "hooklib/dvd.h" +#include "hooklib/printer_chc.h" + +#include "platform/config.h" + + +struct sekito_hook_config { + struct platform_config platform; + struct aime_config aime; + struct aime_config aime_queue; + struct io4_config io4; + struct dvd_config dvd; + struct led15093_config led15093; + struct y3_config y3; + struct sekito_dll_config dll; + struct printer_chc_config printer; + struct gfx_config gfx; + struct amex_config amex; + struct amvideo_config amvideo; +}; + +void sekito_dll_config_load( + struct sekito_dll_config *cfg, + const wchar_t *filename); + +void sekito_hook_config_load( + struct sekito_hook_config *cfg, + const wchar_t *filename); diff --git a/games/sekitohook/dllmain.c b/games/sekitohook/dllmain.c new file mode 100644 index 0000000..29b6305 --- /dev/null +++ b/games/sekitohook/dllmain.c @@ -0,0 +1,207 @@ +/* + "Sangokushi Taisen" (sekito) hook + + Devices + + USB: 837-14572 "Type 3" I/O Board + COM12: 837-15084 "Gen 2" Aime Reader + + [Satellite] + + USB: Sinfonia CHC-C320 Printer + COM1: 837-15093-06 LED Controller Board + COM10: 601-13160-01 "Flat Panel Reader" Y3CR BD SIE F720MM Board + COM11: Printer Camera + + [Terminal] + + COM1: 837-15084 "Gen 2" Aime Reader + COM11: 837-15093-06 LED Controller Board +*/ + +#include + +#include + +#include "amex/amex.h" +#include "board/sg-reader.h" +#include "board/led15093.h" +#include "board/sg-reader-queue.h" + +#include "gfxhook/d3d9.h" +#include "gfxhook/gfx.h" + +#include "hook/process.h" +#include "hook/iohook.h" + +#include "hooklib/dll.h" +#include "hooklib/serial.h" +#include "hooklib/spike.h" +#include "hooklib/y3.h" + +#include "sekitohook/config.h" +#include "sekitohook/jvs.h" + +#include "platform/platform.h" + +#include "util/dprintf.h" +#include "util/env.h" +#include "util/fg-detect.h" + +static HMODULE sekito_hook_mod; +static process_entry_t sekito_startup; +static struct sekito_hook_config sekito_hook_cfg; + +static DWORD CALLBACK sekito_pre_startup(void) +{ + HMODULE dbghelp; + HRESULT hr; + bool is_terminal; + + dprintf("--- Begin sekito_pre_startup ---\n"); + + /* Pin dbghelp so the path hooks apply to it. */ + + dbghelp = LoadLibraryW(L"dbghelp.dll"); + + if (dbghelp != NULL) { + dprintf("Pinned debug helper library, hMod=%p\n", dbghelp); + } else { + dprintf("Failed to load debug helper library!\n"); + } + + /* Load config */ + + sekito_hook_config_load(&sekito_hook_cfg, get_config_path()); + + /* Hook Win32 APIs */ + + dvd_hook_init(&sekito_hook_cfg.dvd, sekito_hook_mod); + gfx_hook_init(&sekito_hook_cfg.gfx); + gfx_d3d9_hook_init(&sekito_hook_cfg.gfx, sekito_hook_mod); + serial_hook_init(); + sekito_io_init(); + + /* Hook external DLL APIs */ + + hr = y3_hook_init(&sekito_hook_cfg.y3, sekito_hook_mod, get_config_path()); + + if (FAILED(hr)) { + goto fail; + } + + printer_chc_hook_init(&sekito_hook_cfg.printer, 0, sekito_hook_mod); + if (sekito_hook_cfg.printer.enable) { + dll_hook_push(sekito_hook_mod, L"C320Ausb.dll"); + dll_hook_push(sekito_hook_mod, L"C320AFWDLusb.dll"); + } + + /* Initialize emulation hooks */ + + hr = platform_hook_init( + &sekito_hook_cfg.platform, + "SDDD", + "AAV2", + sekito_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + + /* Initialize Terminal/Satellite hooks */ + if (strncmp(sekito_hook_cfg.platform.nusec.platform_id, "AAV1", 4) == 0) { + // Terminal + is_terminal = true; + } else if (strncmp(sekito_hook_cfg.platform.nusec.platform_id, "AAV2", 4) == 0) { + // Satellite + is_terminal = false; + } else { + // Unknown + dprintf("Unknown platform ID: %s\n", sekito_hook_cfg.platform.nusec.platform_id); + goto fail; + } + + dprintf("System: Cabinet Type: %s\n", is_terminal ? "Terminal" : "Satellite"); + + // LED: terminal uses COM 11 and satellite use COM 1 + unsigned int led_port_no[2] = {is_terminal ? 11 : 1, 0}; + + hr = sekito_dll_init(&sekito_hook_cfg.dll, sekito_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + + hr = led15093_hook_init(&sekito_hook_cfg.led15093, + sekito_dll.led_init, sekito_dll.led_set_leds, led_port_no); + + if (FAILED(hr)) { + goto fail; + } + + if (is_terminal) { + hr = sg_reader_queue_hook_init(&sekito_hook_cfg.aime_queue, 12, 2, + sekito_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + + hr = sg_reader_hook_init(&sekito_hook_cfg.aime, 1, 2, + sekito_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + } else { + hr = sg_reader_hook_init(&sekito_hook_cfg.aime, 12, 2, + sekito_hook_mod); + + if (FAILED(hr)) { + goto fail; + } + } + + sekito_jvs_set_terminal(is_terminal); + hr = amex_hook_init(&sekito_hook_cfg.amex, sekito_jvs_init); + + if (FAILED(hr)) { + goto fail; + } + + if (sekito_hook_cfg.amex.jvs.enable && sekito_hook_cfg.amex.jvs.foreground) { + fgdet_init(L"teaGfx DirectX Release", false); + } + + /* Initialize debug helpers */ + + spike_hook_init(get_config_path()); + + dprintf("--- End sekito_pre_startup ---\n"); + + /* Jump to EXE start address */ + + return sekito_startup(); + +fail: + ExitProcess(EXIT_FAILURE); +} + +BOOL WINAPI DllMain(HMODULE mod, DWORD cause, void *ctx) +{ + HRESULT hr; + + if (cause != DLL_PROCESS_ATTACH) { + return TRUE; + } + + sekito_hook_mod = mod; + + hr = process_hijack_startup(sekito_pre_startup, &sekito_startup); + + if (!SUCCEEDED(hr)) { + dprintf("Failed to hijack process startup: %x\n", (int) hr); + } + + return SUCCEEDED(hr); +} diff --git a/games/sekitohook/jvs.c b/games/sekitohook/jvs.c new file mode 100644 index 0000000..a7c2c0e --- /dev/null +++ b/games/sekitohook/jvs.c @@ -0,0 +1,258 @@ +#include "jvs.h" + +#include + +#include +#include +#include +#include + +#include "amex/jvs.h" + +#include "board/io3.h" + +#include "sekitohook/config.h" + +#include "jvs/jvs-bus.h" + +#include "util/dprintf.h" + +static void sekito_jvs_read_switches(void* ctx, struct io3_switch_state* out); + +static void sekito_jvs_read_coin_counter( + void* ctx, + uint8_t slot_no, + uint16_t* out); + +static void sekito_jvs_read_rotary( + void* ctx, + uint16_t* rotary, + uint8_t nrotary); + +static const struct io3_ops sekito_jvs_io3_ops = { + .read_switches = sekito_jvs_read_switches, + .read_rotarys = sekito_jvs_read_rotary, + .read_coin_counter = sekito_jvs_read_coin_counter, +}; + +static struct io3 sekito_jvs_io3; + +static bool io_is_terminal; + +HRESULT sekito_jvs_init(struct jvs_node** out) { + assert(out != NULL); + + dprintf("JVS I/O: Starting JVS\n"); + + io3_init(&sekito_jvs_io3, NULL, &sekito_jvs_io3_ops, NULL); + *out = io3_to_jvs_node(&sekito_jvs_io3); + + return S_OK; +} + +void sekito_jvs_set_terminal(bool is_terminal) { + dprintf("JVS I/O: Terminal: %d\n", is_terminal); + io_is_terminal = is_terminal; +} + +static void sekito_jvs_read_switches(void* ctx, struct io3_switch_state* out) { + assert(out != NULL); + + uint8_t opbtn; + uint32_t gamebtn; + + assert(sekito_dll.poll != NULL); + assert(sekito_dll.get_opbtns != NULL); + assert(sekito_dll.get_gamebtns != NULL); + + memset(out, 0, sizeof(*out)); + + sekito_dll.poll(); + + opbtn = 0; + gamebtn = 0; + + sekito_dll.get_opbtns(&opbtn); + sekito_dll.get_gamebtns(&gamebtn); + + if (opbtn & SEKITO_IO_OPBTN_TEST) { + out->system = 0x80; + } else { + out->system = 0; + } + + if (opbtn & SEKITO_IO_OPBTN_SERVICE) { + out->p1 |= 1 << 1; + } + + if (opbtn & SEKITO_IO_OPBTN_SW1) { + out->p1 |= 1 << 10; + } + + if (opbtn & SEKITO_IO_OPBTN_SW2) { + out->p1 |= 1 << 11; + } + + if (opbtn & SEKITO_IO_OPBTN_COIN) { + out->p1 |= 1 << 14; + } + + + if (!io_is_terminal) { + if (gamebtn & SEKITO_IO_GAMEBTN_HOUGU) { + out->p2 |= 1 << 6; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_MENU) { + out->p2 |= 1 << 4; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_START) { + out->p1 |= 1 << 15; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_STRATAGEM) { + out->p2 |= 1 << 7; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_STRATAGEM_LOCK) { + out->p2 |= 1 << 5; + } + + out->p1 |= 0 << 2; // card_sensor + out->p2 |= 1 << 2; // open_sensor + out->p2 |= 1 << 3; // lock + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_0) { + out->p1 |= SEKITO_NUMPAD_C2; + out->p1 |= SEKITO_NUMPAD_R4; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_1) { + out->p1 |= SEKITO_NUMPAD_C1; + out->p1 |= SEKITO_NUMPAD_R1; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_2) { + out->p1 |= SEKITO_NUMPAD_C2; + out->p1 |= SEKITO_NUMPAD_R1; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_3) { + out->p1 |= SEKITO_NUMPAD_C3; + out->p1 |= SEKITO_NUMPAD_R1; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_4) { + out->p1 |= SEKITO_NUMPAD_C1; + out->p1 |= SEKITO_NUMPAD_R2; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_5) { + out->p1 |= SEKITO_NUMPAD_C2; + out->p1 |= SEKITO_NUMPAD_R2; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_6) { + out->p1 |= SEKITO_NUMPAD_C3; + out->p1 |= SEKITO_NUMPAD_R2; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_7) { + out->p1 |= SEKITO_NUMPAD_C1; + out->p1 |= SEKITO_NUMPAD_R3; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_8) { + out->p1 |= SEKITO_NUMPAD_C2; + out->p1 |= SEKITO_NUMPAD_R3; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_9) { + out->p1 |= SEKITO_NUMPAD_C3; + out->p1 |= SEKITO_NUMPAD_R3; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_CLEAR) { + out->p1 |= SEKITO_NUMPAD_C1; + out->p1 |= SEKITO_NUMPAD_R4; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_NUMPAD_ENTER) { + out->p1 |= SEKITO_NUMPAD_C3; + out->p1 |= SEKITO_NUMPAD_R4; + } + + if (io_is_terminal) { + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_CANCEL) { + out->p2 |= 1 << 8; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_DECIDE) { + out->p2 |= 1 << 9; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_LEFT) { + out->p1 |= 1 << 11; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_UP) { + out->p1 |= 1 << 13; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_RIGHT) { + out->p1 |= 1 << 10; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_DOWN) { + out->p1 |= 1 << 12; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_LEFT_2) { + out->p2 |= 1 << 11; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_RIGHT_2) { + out->p2 |= 1 << 10; + } + + if (gamebtn & SEKITO_IO_GAMEBTN_TERMINAL_RESERVE) { + out->p2 |= 1 << 3; + } + + } + +} + +static void sekito_jvs_read_rotary( + void* ctx, + uint16_t* rotary, + uint8_t nrotary) { + assert(rotary != NULL); + assert(sekito_dll.get_trackball_position != NULL); + + uint16_t x, y; + + x = 0; + y = 0; + + sekito_dll.get_trackball_position(&x, &y); + + if (nrotary >= 4) { + rotary[2] = x; + rotary[3] = y; + } +} + +static void sekito_jvs_read_coin_counter( + void* ctx, + uint8_t slot_no, + uint16_t* out) { + if (slot_no > 0) { + return; + } + + // unused(!) + *out = 0; +} diff --git a/games/sekitohook/jvs.h b/games/sekitohook/jvs.h new file mode 100644 index 0000000..fa0584e --- /dev/null +++ b/games/sekitohook/jvs.h @@ -0,0 +1,18 @@ +#pragma once + +#include + +#include "jvs/jvs-bus.h" + +enum { + SEKITO_NUMPAD_R1 = 1 << 9, + SEKITO_NUMPAD_R2 = 1 << 8, + SEKITO_NUMPAD_R3 = 1 << 7, + SEKITO_NUMPAD_R4 = 1 << 6, + SEKITO_NUMPAD_C1 = 1 << 5, + SEKITO_NUMPAD_C2 = 1 << 4, + SEKITO_NUMPAD_C3 = 1 << 3 +}; + +HRESULT sekito_jvs_init(struct jvs_node **root); +void sekito_jvs_set_terminal(bool is_terminal); diff --git a/games/sekitohook/meson.build b/games/sekitohook/meson.build new file mode 100644 index 0000000..c8c647d --- /dev/null +++ b/games/sekitohook/meson.build @@ -0,0 +1,32 @@ +shared_library( + 'sekitohook', + name_prefix : '', + include_directories : inc, + implicit_include_directories : false, + vs_module_defs : 'sekitohook.def', + dependencies : [ + capnhook.get_variable('hook_dep'), + capnhook.get_variable('hooklib_dep') + ], + link_with : [ + aimeio_lib, + amex_lib, + board_lib, + hooklib_lib, + gfxhook_lib, + jvs_lib, + platform_lib, + sekitoio_lib, + util_lib, + y3io_lib, + ], + sources : [ + 'config.c', + 'config.h', + 'dllmain.c', + 'jvs.c', + 'jvs.h', + 'sekito-dll.c', + 'sekito-dll.h', + ], +) diff --git a/games/sekitohook/sekito-dll.c b/games/sekitohook/sekito-dll.c new file mode 100644 index 0000000..a0d9b2e --- /dev/null +++ b/games/sekitohook/sekito-dll.c @@ -0,0 +1,118 @@ +#include + +#include +#include + +#include "sekitohook/sekito-dll.h" + +#include "util/dll-bind.h" +#include "util/dprintf.h" + +const struct dll_bind_sym sekito_dll_syms[] = { + { + .sym = "sekito_io_init", + .off = offsetof(struct sekito_dll, init), + }, { + .sym = "sekito_io_poll", + .off = offsetof(struct sekito_dll, poll), + }, { + .sym = "sekito_io_get_opbtns", + .off = offsetof(struct sekito_dll, get_opbtns), + }, { + .sym = "sekito_io_get_gamebtns", + .off = offsetof(struct sekito_dll, get_gamebtns), + }, { + .sym = "sekito_io_get_trackball_position", + .off = offsetof(struct sekito_dll, get_trackball_position), + }, { + .sym = "sekito_io_led_init", + .off = offsetof(struct sekito_dll, led_init), + }, { + .sym = "sekito_io_led_set_colors", + .off = offsetof(struct sekito_dll, led_set_leds), + } +}; + +struct sekito_dll sekito_dll; + +// Copypasta DLL binding and diagnostic message boilerplate. +// Not much of this lends itself to being easily factored out. Also there +// will be a lot of API-specific branching code here eventually as new API +// versions get defined, so even though these functions all look the same +// now this won't remain the case forever. + +HRESULT sekito_dll_init(const struct sekito_dll_config *cfg, HINSTANCE self) +{ + uint16_t (*get_api_version)(void); + const struct dll_bind_sym *sym; + HINSTANCE owned; + HINSTANCE src; + HRESULT hr; + + assert(cfg != NULL); + assert(self != NULL); + + if (cfg->path[0] != L'\0') { + owned = LoadLibraryW(cfg->path); + + if (owned == NULL) { + hr = HRESULT_FROM_WIN32(GetLastError()); + dprintf("Sekito IO: Failed to load IO DLL: %lx: %S\n", + hr, + cfg->path); + + goto end; + } + + dprintf("Sekito IO: Using custom IO DLL: %S\n", cfg->path); + src = owned; + } else { + owned = NULL; + src = self; + } + + get_api_version = (void *) GetProcAddress(src, "sekito_io_get_api_version"); + + if (get_api_version != NULL) { + sekito_dll.api_version = get_api_version(); + } else { + sekito_dll.api_version = 0x0100; + dprintf("Custom IO DLL does not expose sekito_io_get_api_version, " + "assuming API version 1.0.\n" + "Please ask the developer to update their DLL.\n"); + } + + if (sekito_dll.api_version >= 0x0200) { + hr = E_NOTIMPL; + dprintf("Sekito IO: Custom IO DLL implements an unsupported " + "API version (%#04x). Please update Segatools.\n", + sekito_dll.api_version); + + goto end; + } + + sym = sekito_dll_syms; + hr = dll_bind(&sekito_dll, src, &sym, _countof(sekito_dll_syms)); + + if (FAILED(hr)) { + if (src != self) { + dprintf("Sekito IO: Custom IO DLL does not provide function " + "\"%s\". Please contact your IO DLL's developer for " + "further assistance.\n", + sym->sym); + + goto end; + } else { + dprintf("Internal error: could not reflect \"%s\"\n", sym->sym); + } + } + + owned = NULL; + +end: + if (owned != NULL) { + FreeLibrary(owned); + } + + return hr; +} diff --git a/games/sekitohook/sekito-dll.h b/games/sekitohook/sekito-dll.h new file mode 100644 index 0000000..1f2560f --- /dev/null +++ b/games/sekitohook/sekito-dll.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include "sekitoio/sekitoio.h" + +struct sekito_dll { + uint16_t api_version; + HRESULT (*init)(void); + HRESULT (*poll)(void); + void (*get_opbtns)(uint8_t *opbtn); + void (*get_gamebtns)(uint32_t *gamebtn); + void (*get_trackball_position)(uint16_t *x, uint16_t *y); + HRESULT (*led_init)(void); + void (*led_set_leds)(uint8_t board, uint8_t *rgb); +}; + +struct sekito_dll_config { + wchar_t path[MAX_PATH]; +}; + +extern struct sekito_dll sekito_dll; + +HRESULT sekito_dll_init(const struct sekito_dll_config *cfg, HINSTANCE self); diff --git a/games/sekitohook/sekitohook.def b/games/sekitohook/sekitohook.def new file mode 100644 index 0000000..6153e94 --- /dev/null +++ b/games/sekitohook/sekitohook.def @@ -0,0 +1,78 @@ +LIBRARY sekitohook + +EXPORTS + Direct3DCreate9 + aime_io_get_api_version + aime_io_init + aime_io_led_set_color + aime_io_vfd_set_text + aime_io_vfd_set_state + aime_io_nfc_get_aime_id + aime_io_nfc_get_felica_id + aime_io_nfc_poll + aime_io_nfc_get_mifare_uid + aime_io_nfc_mifare_select + aime_io_nfc_mifare_set_key + aime_io_nfc_mifare_authenticate + aime_io_nfc_mifare_read_block + aime_io_nfc_felica_transact + aime_io_nfc_radio_on + aime_io_nfc_radio_off + aime_io_nfc_to_update_mode + aime_io_nfc_send_hex_data + sekito_io_get_api_version + sekito_io_get_gamebtns + sekito_io_get_opbtns + sekito_io_get_trackball_position + sekito_io_init + sekito_io_poll + sekito_io_led_init + sekito_io_led_set_colors + y3_io_get_api_version + y3_io_init + y3_io_close + y3_io_get_cards + amDllVideoClose + amDllVideoGetVBiosVersion + amDllVideoOpen + amDllVideoSetResolution + API_DLLVersion @1 + API_GetLastError @2 + API_GetErrorMessage @3 + API_Connect @4 + API_Close @5 + API_Start @6 + API_Stop @7 + API_GetFirmVersion @8 + API_GetFirmName @9 + API_GetTargetCode @10 + API_GetStatus @11 + API_GetCounter @12 + API_ClearError @13 + API_Reset @14 + API_GetCardInfo @15 + API_GetCardInfoCharSize @16 + API_SetDevice @17 + API_SetCommand @18 + API_FirmwareUpdate @19 + API_Calibration @20 + API_GetCalibrationResult @21 + API_GetProcTime @22 + API_GetMemStatus @23 + API_GetMemCounter @24 + API_SetSysControl @25 + API_GetSysControl @26 + API_SetParameter @27 + API_GetParameter @28 + API_TestReset @29 + API_DebugReset @30 + API_GetBoardType @31 + API_GetCardDataSize @32 + API_GetFirmDate @33 + API_SystemCommand @34 + API_CalcCheckSum @35 + API_GetCheckSumResult @36 + API_BlockRead @37 + API_GetBlockReadResult @38 + API_BlockWrite @39 + API_GetDebugParam @40 diff --git a/games/sekitoio/backend.h b/games/sekitoio/backend.h new file mode 100644 index 0000000..6c84ca5 --- /dev/null +++ b/games/sekitoio/backend.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "sekitoio/sekitoio.h" + +struct sekito_io_backend { + void (*get_gamebtns)(uint32_t *gamebtn); + void (*get_trackball)(uint16_t *x, uint16_t *y); +}; diff --git a/games/sekitoio/config.c b/games/sekitoio/config.c new file mode 100644 index 0000000..bdd94bd --- /dev/null +++ b/games/sekitoio/config.c @@ -0,0 +1,74 @@ +#include + +#include +#include +#include + +#include "sekitoio/config.h" + +#include + + +void sekito_kb_config_load( + struct sekito_kb_config *cfg, + const wchar_t *filename) { + + cfg->vk_menu = GetPrivateProfileIntW(L"keyboard", L"menu", 'A', filename); + cfg->vk_start = GetPrivateProfileIntW(L"keyboard", L"start", 'S', filename); + cfg->vk_stratagem = GetPrivateProfileIntW(L"keyboard", L"stratagem", 'D', filename); + cfg->vk_stratagem_lock = GetPrivateProfileIntW(L"keyboard", L"stratagem_lock", 'F', filename); + cfg->vk_hougu = GetPrivateProfileIntW(L"keyboard", L"hougu", 'G', filename); + + cfg->vk_tenkey_0 = GetPrivateProfileIntW(L"keyboard", L"tenkey_0", VK_NUMPAD0, filename); + cfg->vk_tenkey_1 = GetPrivateProfileIntW(L"keyboard", L"tenkey_1", VK_NUMPAD1, filename); + cfg->vk_tenkey_2 = GetPrivateProfileIntW(L"keyboard", L"tenkey_2", VK_NUMPAD2, filename); + cfg->vk_tenkey_3 = GetPrivateProfileIntW(L"keyboard", L"tenkey_3", VK_NUMPAD3, filename); + cfg->vk_tenkey_4 = GetPrivateProfileIntW(L"keyboard", L"tenkey_4", VK_NUMPAD4, filename); + cfg->vk_tenkey_5 = GetPrivateProfileIntW(L"keyboard", L"tenkey_5", VK_NUMPAD5, filename); + cfg->vk_tenkey_6 = GetPrivateProfileIntW(L"keyboard", L"tenkey_6", VK_NUMPAD6, filename); + cfg->vk_tenkey_7 = GetPrivateProfileIntW(L"keyboard", L"tenkey_7", VK_NUMPAD7, filename); + cfg->vk_tenkey_8 = GetPrivateProfileIntW(L"keyboard", L"tenkey_8", VK_NUMPAD8, filename); + cfg->vk_tenkey_9 = GetPrivateProfileIntW(L"keyboard", L"tenkey_9", VK_NUMPAD9, filename); + cfg->vk_tenkey_clear = GetPrivateProfileIntW(L"keyboard", L"tenkey_clear", VK_DECIMAL, filename); + cfg->vk_tenkey_enter = GetPrivateProfileIntW(L"keyboard", L"tenkey_enter", VK_RETURN, filename); + + cfg->vk_terminal_decide = GetPrivateProfileIntW(L"keyboard", L"decide", 'A', filename); + cfg->vk_terminal_cancel = GetPrivateProfileIntW(L"keyboard", L"cancel", 'S', filename); + cfg->vk_terminal_up = GetPrivateProfileIntW(L"keyboard", L"up", VK_UP, filename); + cfg->vk_terminal_right = GetPrivateProfileIntW(L"keyboard", L"right", VK_RIGHT, filename); + cfg->vk_terminal_down = GetPrivateProfileIntW(L"keyboard", L"down", VK_DOWN, filename); + cfg->vk_terminal_left = GetPrivateProfileIntW(L"keyboard", L"left", VK_LEFT, filename); + cfg->vk_terminal_left_2 = GetPrivateProfileIntW(L"keyboard", L"left2", 'Q', filename); + cfg->vk_terminal_right_2 = GetPrivateProfileIntW(L"keyboard", L"right2", 'W', filename); + cfg->vk_terminal_reserve = GetPrivateProfileIntW(L"keyboard", L"reserve", 'E', filename); + + cfg->x_down = GetPrivateProfileIntW(L"keyboard", L"trackball_left", VK_LEFT, filename); + cfg->x_up = GetPrivateProfileIntW(L"keyboard", L"trackball_right", VK_RIGHT, filename); + cfg->y_down = GetPrivateProfileIntW(L"keyboard", L"trackball_up", VK_UP, filename); + cfg->y_up = GetPrivateProfileIntW(L"keyboard", L"trackball_down", VK_DOWN, filename); + cfg->speed = GetPrivateProfileIntW(L"keyboard", L"speed_modifier", 1, filename); +} + +void sekito_io_config_load( + struct sekito_io_config *cfg, + const wchar_t *filename) +{ + assert(cfg != NULL); + assert(filename != NULL); + + cfg->vk_test = GetPrivateProfileIntW(L"io4", L"test", '1', filename); + cfg->vk_service = GetPrivateProfileIntW(L"io4", L"service", '2', filename); + cfg->vk_coin = GetPrivateProfileIntW(L"io4", L"coin", '3', filename); + cfg->vk_sw1 = GetPrivateProfileIntW(L"io4", L"sw1", '4', filename); + cfg->vk_sw2 = GetPrivateProfileIntW(L"io4", L"sw2", '5', filename); + + GetPrivateProfileStringW( + L"io4", + L"mode", + L"keyboard", + cfg->mode, + _countof(cfg->mode), + filename); + + sekito_kb_config_load(&cfg->kb, filename); +} diff --git a/games/sekitoio/config.h b/games/sekitoio/config.h new file mode 100644 index 0000000..9bfeed7 --- /dev/null +++ b/games/sekitoio/config.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include + +#include + +struct sekito_kb_config { + uint8_t vk_menu; + uint8_t vk_start; + uint8_t vk_stratagem; + uint8_t vk_stratagem_lock; + uint8_t vk_hougu; + + uint8_t vk_tenkey_0; + uint8_t vk_tenkey_1; + uint8_t vk_tenkey_2; + uint8_t vk_tenkey_3; + uint8_t vk_tenkey_4; + uint8_t vk_tenkey_5; + uint8_t vk_tenkey_6; + uint8_t vk_tenkey_7; + uint8_t vk_tenkey_8; + uint8_t vk_tenkey_9; + uint8_t vk_tenkey_clear; + uint8_t vk_tenkey_enter; + + uint8_t vk_terminal_up; + uint8_t vk_terminal_right; + uint8_t vk_terminal_down; + uint8_t vk_terminal_left; + uint8_t vk_terminal_left_2; + uint8_t vk_terminal_right_2; + uint8_t vk_terminal_reserve; + uint8_t vk_terminal_cancel; + uint8_t vk_terminal_decide; + + uint8_t x_down; + uint8_t x_up; + uint8_t y_down; + uint8_t y_up; + uint8_t speed; +}; + +struct sekito_io_config { + uint8_t vk_test; + uint8_t vk_service; + uint8_t vk_coin; + uint8_t vk_sw1; + uint8_t vk_sw2; + + wchar_t mode[12]; + struct sekito_kb_config kb; +}; + +void sekito_kb_config_load(struct sekito_kb_config *cfg, const wchar_t *filename); +void sekito_io_config_load( + struct sekito_io_config *cfg, + const wchar_t *filename); diff --git a/games/sekitoio/keyboard.c b/games/sekitoio/keyboard.c new file mode 100644 index 0000000..d6060d4 --- /dev/null +++ b/games/sekitoio/keyboard.c @@ -0,0 +1,168 @@ +#include + +#include +#include +#include +#include + +#include "sekitoio/backend.h" +#include "sekitoio/config.h" +#include "sekitoio/sekitoio.h" +#include "sekitoio/keyboard.h" + +#include "util/dprintf.h" + +static void sekito_kb_get_gamebtns(uint32_t* gamebtn_out); +static void sekito_kb_get_trackball(uint16_t* x, uint16_t* y); + +static const struct sekito_io_backend sekito_kb_backend = { + .get_gamebtns = sekito_kb_get_gamebtns, + .get_trackball = sekito_kb_get_trackball +}; + +static uint16_t current_x; +static uint16_t current_y; + +static struct sekito_kb_config config; + +HRESULT sekito_kb_init(const struct sekito_kb_config* cfg, const struct sekito_io_backend** backend) { + assert(cfg != NULL); + assert(backend != NULL); + + dprintf("Keyboard: Using keyboard input\n"); + *backend = &sekito_kb_backend; + config = *cfg; + + return S_OK; +} + +static void sekito_kb_get_gamebtns(uint32_t* gamebtn_out) { + assert(gamebtn_out != NULL); + + uint32_t gamebtn = 0; + + if (GetAsyncKeyState(config.vk_hougu) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_HOUGU; + } + + if (GetAsyncKeyState(config.vk_menu) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_MENU; + } + + if (GetAsyncKeyState(config.vk_start) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_START; + } + + if (GetAsyncKeyState(config.vk_stratagem) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_STRATAGEM; + } + + if (GetAsyncKeyState(config.vk_stratagem_lock) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_STRATAGEM_LOCK; + } + + if (GetAsyncKeyState(config.vk_tenkey_0) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_0; + } + + if (GetAsyncKeyState(config.vk_tenkey_1) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_1; + } + + if (GetAsyncKeyState(config.vk_tenkey_2) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_2; + } + + if (GetAsyncKeyState(config.vk_tenkey_3) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_3; + } + + if (GetAsyncKeyState(config.vk_tenkey_4) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_4; + } + + if (GetAsyncKeyState(config.vk_tenkey_5) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_5; + } + + if (GetAsyncKeyState(config.vk_tenkey_6) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_6; + } + + if (GetAsyncKeyState(config.vk_tenkey_7) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_7; + } + + if (GetAsyncKeyState(config.vk_tenkey_8) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_8; + } + + if (GetAsyncKeyState(config.vk_tenkey_9) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_9; + } + + if (GetAsyncKeyState(config.vk_tenkey_clear) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_CLEAR; + } + + if (GetAsyncKeyState(config.vk_tenkey_enter) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_NUMPAD_ENTER; + } + + if (GetAsyncKeyState(config.vk_terminal_cancel) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_CANCEL; + } + + if (GetAsyncKeyState(config.vk_terminal_decide) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_DECIDE; + } + + if (GetAsyncKeyState(config.vk_terminal_up) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_UP; + } + + if (GetAsyncKeyState(config.vk_terminal_right) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_RIGHT; + } + + if (GetAsyncKeyState(config.vk_terminal_down) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_DOWN; + } + + if (GetAsyncKeyState(config.vk_terminal_left) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_LEFT; + } + + if (GetAsyncKeyState(config.vk_terminal_left_2) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_LEFT_2; + } + + if (GetAsyncKeyState(config.vk_terminal_right_2) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_RIGHT_2; + } + + if (GetAsyncKeyState(config.vk_terminal_reserve) & 0x8000) { + gamebtn |= SEKITO_IO_GAMEBTN_TERMINAL_RESERVE; + } + + *gamebtn_out = gamebtn; +} + +static void sekito_kb_get_trackball(uint16_t* x, uint16_t* y) { + assert(x != NULL); + assert(y != NULL); + + if (GetAsyncKeyState(config.x_down) & 0x8000) { + current_x -= config.speed; + } else if (GetAsyncKeyState(config.x_up) & 0x8000) { + current_x += config.speed; + } + if (GetAsyncKeyState(config.y_down) & 0x8000) { + current_y += config.speed; + } else if (GetAsyncKeyState(config.y_up) & 0x8000) { + current_y -= config.speed; + } + + *x = current_x; + *y = current_y; +} diff --git a/games/sekitoio/keyboard.h b/games/sekitoio/keyboard.h new file mode 100644 index 0000000..ae093e8 --- /dev/null +++ b/games/sekitoio/keyboard.h @@ -0,0 +1,8 @@ +#pragma once + +#include + +#include "sekitoio/backend.h" +#include "sekitoio/config.h" + +HRESULT sekito_kb_init(const struct sekito_kb_config *cfg, const struct sekito_io_backend **backend); diff --git a/games/sekitoio/meson.build b/games/sekitoio/meson.build new file mode 100644 index 0000000..15b1e63 --- /dev/null +++ b/games/sekitoio/meson.build @@ -0,0 +1,18 @@ +sekitoio_lib = static_library( + 'sekitoio', + name_prefix : '', + include_directories : inc, + implicit_include_directories : false, + dependencies : [ + xinput_lib, + ], + sources : [ + 'config.c', + 'config.h', + 'backend.h', + 'keyboard.c', + 'keyboard.h', + 'sekitoio.c', + 'sekitoio.h', + ], +) diff --git a/games/sekitoio/sekitoio.c b/games/sekitoio/sekitoio.c new file mode 100644 index 0000000..75ec654 --- /dev/null +++ b/games/sekitoio/sekitoio.c @@ -0,0 +1,108 @@ +#include +#include +#include + +#include + +#include "sekitoio/sekitoio.h" + +#include + +#include "keyboard.h" +#include "sekitoio/config.h" +#include "util/dprintf.h" +#include "util/env.h" +#include "util/str.h" + +static uint8_t sekito_opbtn; +static uint32_t sekito_gamebtn; +static uint8_t sekito_stick_x; +static uint8_t sekito_stick_y; +static struct sekito_io_config sekito_io_cfg; +static const struct sekito_io_backend* sekito_io_backend; +static bool sekito_io_coin; + +uint16_t sekito_io_get_api_version(void) { + return 0x0100; +} + +HRESULT sekito_io_init(void) { + sekito_io_config_load(&sekito_io_cfg, get_config_path()); + + HRESULT hr; + + if (wstr_ieq(sekito_io_cfg.mode, L"keyboard")) { + hr = sekito_kb_init(&sekito_io_cfg.kb, &sekito_io_backend); + } else { + hr = E_INVALIDARG; + dprintf("Sekito IO: Invalid IO mode \"%S\", use keyboard\n", + sekito_io_cfg.mode); + } + + return hr; +} + +HRESULT sekito_io_poll(void) { + assert(sekito_io_backend != NULL); + + sekito_opbtn = 0; + sekito_gamebtn = 0; + sekito_stick_x = 0; + sekito_stick_y = 0; + + if (GetAsyncKeyState(sekito_io_cfg.vk_test) & 0x8000) { + sekito_opbtn |= SEKITO_IO_OPBTN_TEST; + } + + if (GetAsyncKeyState(sekito_io_cfg.vk_service) & 0x8000) { + sekito_opbtn |= SEKITO_IO_OPBTN_SERVICE; + } + + if (GetAsyncKeyState(sekito_io_cfg.vk_sw1) & 0x8000) { + sekito_opbtn |= SEKITO_IO_OPBTN_SW1; + } + + if (GetAsyncKeyState(sekito_io_cfg.vk_sw2) & 0x8000) { + sekito_opbtn |= SEKITO_IO_OPBTN_SW2; + } + + if (GetAsyncKeyState(sekito_io_cfg.vk_coin) & 0x8000) { + if (!sekito_io_coin) { + sekito_io_coin = true; + sekito_opbtn |= SEKITO_IO_OPBTN_COIN; + } + } else { + sekito_io_coin = false; + } + + return S_OK; +} + +void sekito_io_get_opbtns(uint8_t* opbtn) { + if (opbtn != NULL) { + *opbtn = sekito_opbtn; + } +} + +void sekito_io_get_gamebtns(uint32_t* btn) { + assert(sekito_io_backend != NULL); + assert(btn != NULL); + + sekito_io_backend->get_gamebtns(btn); +} + +void sekito_io_get_trackball_position(uint16_t* stick_x, uint16_t* stick_y) { + assert(sekito_io_backend != NULL); + assert(stick_x != NULL); + assert(stick_y != NULL); + + sekito_io_backend->get_trackball(stick_x, stick_y); +} + +HRESULT sekito_io_led_init(void) { + return S_OK; +} + +void sekito_io_led_set_colors(uint8_t board, uint8_t* rgb) { + return; +} diff --git a/games/sekitoio/sekitoio.h b/games/sekitoio/sekitoio.h new file mode 100644 index 0000000..2e19653 --- /dev/null +++ b/games/sekitoio/sekitoio.h @@ -0,0 +1,104 @@ +#pragma once + +#include + +#include + +enum { + SEKITO_IO_OPBTN_TEST = 0x01, + SEKITO_IO_OPBTN_SERVICE = 0x02, + SEKITO_IO_OPBTN_COIN = 0x04, + SEKITO_IO_OPBTN_SW1 = 0x08, + SEKITO_IO_OPBTN_SW2 = 0x10, +}; + +enum { + SEKITO_IO_GAMEBTN_MENU = 0x01, + SEKITO_IO_GAMEBTN_START = 0x02, + SEKITO_IO_GAMEBTN_STRATAGEM = 0x04, + SEKITO_IO_GAMEBTN_STRATAGEM_LOCK = 0x08, + SEKITO_IO_GAMEBTN_HOUGU = 0x10, + SEKITO_IO_GAMEBTN_NUMPAD_0 = 0x100, + SEKITO_IO_GAMEBTN_NUMPAD_1 = 0x200, + SEKITO_IO_GAMEBTN_NUMPAD_2 = 0x400, + SEKITO_IO_GAMEBTN_NUMPAD_3 = 0x800, + SEKITO_IO_GAMEBTN_NUMPAD_4 = 0x1000, + SEKITO_IO_GAMEBTN_NUMPAD_5 = 0x2000, + SEKITO_IO_GAMEBTN_NUMPAD_6 = 0x4000, + SEKITO_IO_GAMEBTN_NUMPAD_7 = 0x8000, + SEKITO_IO_GAMEBTN_NUMPAD_8 = 0x10000, + SEKITO_IO_GAMEBTN_NUMPAD_9 = 0x20000, + SEKITO_IO_GAMEBTN_NUMPAD_CLEAR = 0x40000, + SEKITO_IO_GAMEBTN_NUMPAD_ENTER = 0x80000, + SEKITO_IO_GAMEBTN_TERMINAL_LEFT = 0x400000, + SEKITO_IO_GAMEBTN_TERMINAL_UP = 0x800000, + SEKITO_IO_GAMEBTN_TERMINAL_RIGHT = 0x1000000, + SEKITO_IO_GAMEBTN_TERMINAL_DOWN = 0x2000000, + SEKITO_IO_GAMEBTN_TERMINAL_LEFT_2 = 0x4000000, + SEKITO_IO_GAMEBTN_TERMINAL_RIGHT_2 = 0x8000000, + SEKITO_IO_GAMEBTN_TERMINAL_DECIDE = 0x10000000, + SEKITO_IO_GAMEBTN_TERMINAL_CANCEL = 0x20000000, + SEKITO_IO_GAMEBTN_TERMINAL_RESERVE = 0x40000000, +}; + +/* Get the version of the Eiketsu Taisen IO API that this DLL supports. This + function should return a positive 16-bit integer, where the high byte is + the major version and the low byte is the minor version (as defined by the + Semantic Versioning standard). + + The latest API version as of this writing is 0x0100. */ + +uint16_t sekito_io_get_api_version(void); + +/* Initialize the IO DLL. This is the second function that will be called on + your DLL, after sekito_io_get_api_version. + + All subsequent calls to this API may originate from arbitrary threads. + + Minimum API version: 0x0100 */ + +HRESULT sekito_io_init(void); + +/* Send any queued outputs (of which there are currently none, though this may + change in subsequent API versions) and retrieve any new inputs. + + Minimum API version: 0x0100 */ + +HRESULT sekito_io_poll(void); + +/* Get the state of the cabinet's operator buttons as of the last poll. See + SEKITO_IO_OPBTN enum above: this contains bit mask definitions for button + states returned in *opbtn. All buttons are active-high. + + Minimum API version: 0x0100 */ + +void sekito_io_get_opbtns(uint8_t *opbtn); + +/* Get the state of the cabinet's gameplay buttons as of the last poll. See + SEKITO_IO_GAMEBTN enum above: this contains bit mask definitions for button + states returned in *gamebtn. All buttons are active-high. + + Minimum API version: 0x0100 */ + +void sekito_io_get_gamebtns(uint32_t *gamebtn); + +/* Get the position of the trackball as of the last poll. + + Minimum API version: 0x0100 */ + +void sekito_io_get_trackball_position(uint16_t *stick_x, uint16_t *stick_y); + +/* Initialize LED emulation. This function will be called before any + other sekito_io_led_*() function calls. + + All subsequent calls may originate from arbitrary threads and some may + overlap with each other. Ensuring synchronization inside your IO DLL is + your responsibility. */ + +HRESULT sekito_io_led_init(void); + +/* Update the RGB LEDs. + + Exact layout is TBD. */ + +void sekito_io_led_set_colors(uint8_t board, uint8_t *rgb); diff --git a/meson.build b/meson.build index 1e88269..7d35c79 100644 --- a/meson.build +++ b/meson.build @@ -27,6 +27,11 @@ if cc.get_id() != 'msvc' language: 'c', ) + add_global_arguments( + '-Wno-unknown-pragmas', + language: 'c', + ) + add_project_link_arguments( '-Wl,--enable-stdcall-fixup', '-Wl,--exclude-all-symbols', @@ -103,6 +108,7 @@ bcrypt_lib = cc.find_library('bcrypt') inc = include_directories('common', 'games') capnhook = subproject('capnhook') +cwinwebsocket = subproject('cwinwebsocket') subdir('common/amex') subdir('common/iccard') @@ -112,6 +118,7 @@ subdir('common/jvs') subdir('common/platform') subdir('common/util') subdir('common/aimeio') +subdir('common/y3io') subdir('common/gfxhook') subdir('common/unityhook') @@ -131,6 +138,8 @@ subdir('games/tokyoio') subdir('games/fgoio') subdir('games/kemonoio') subdir('games/apm3io') +subdir('games/sekitoio') +subdir('games/ektio') subdir('games/chunihook') subdir('games/divahook') @@ -148,3 +157,5 @@ subdir('games/tokyohook') subdir('games/fgohook') subdir('games/kemonohook') subdir('games/apm3hook') +subdir('games/ekthook') +subdir('games/sekitohook') diff --git a/subprojects/cwinwebsocket.wrap b/subprojects/cwinwebsocket.wrap new file mode 100644 index 0000000..b23eb43 --- /dev/null +++ b/subprojects/cwinwebsocket.wrap @@ -0,0 +1,5 @@ +[wrap-git] +directory = cwinwebsocket +url = https://github.com/akechi-haruka/cwinwebsocket +revision = HEAD +