├── source ├── aptextension.c ├── Archives.h ├── clock.h ├── clock.c ├── vshader.v.pica ├── Unicode.h ├── graphics.h ├── appInfo.h ├── common_functions.c ├── csvc.s ├── drawableObject.h ├── graphics.c ├── files.c ├── draw.h ├── main.h ├── png.c ├── drawableObject.c ├── main.c ├── appInfo.c ├── csvc.h ├── parson.h ├── draw.c ├── updater.c └── Archives.c ├── resources ├── icon.png ├── audio.cwav ├── banner.png ├── logo.bcma.lz └── Nasalization.ttf ├── intellisense ├── vshader_shbin.h └── forced_include.h ├── romfs └── sprites │ ├── topBackground.png │ ├── bottomBackground.png │ └── topInfoBackground.png ├── EzB9SUpdater.code-workspace ├── ezb9supdater_config.json ├── .vscode └── c_cpp_properties.json ├── LICENSE ├── README.md ├── Makefile ├── .gitignore └── LICENSE_lpp3ds /source/aptextension.c: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | 3 | -------------------------------------------------------------------------------- /resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/resources/icon.png -------------------------------------------------------------------------------- /source/Archives.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/source/Archives.h -------------------------------------------------------------------------------- /resources/audio.cwav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/resources/audio.cwav -------------------------------------------------------------------------------- /resources/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/resources/banner.png -------------------------------------------------------------------------------- /resources/logo.bcma.lz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/resources/logo.bcma.lz -------------------------------------------------------------------------------- /intellisense/vshader_shbin.h: -------------------------------------------------------------------------------- 1 | extern const u8 vshader_shbin[]; 2 | extern const u32 vshader_shbin_len; 3 | -------------------------------------------------------------------------------- /resources/Nasalization.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/resources/Nasalization.ttf -------------------------------------------------------------------------------- /intellisense/forced_include.h: -------------------------------------------------------------------------------- 1 | #define APP_VERSION_MAJOR 0 2 | #define APP_VERSION_MINOR 0 3 | #define APP_VERSION_MICRO 0 -------------------------------------------------------------------------------- /romfs/sprites/topBackground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/romfs/sprites/topBackground.png -------------------------------------------------------------------------------- /romfs/sprites/bottomBackground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/romfs/sprites/bottomBackground.png -------------------------------------------------------------------------------- /romfs/sprites/topInfoBackground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PabloMK7/EzB9SUpdater/HEAD/romfs/sprites/topInfoBackground.png -------------------------------------------------------------------------------- /source/clock.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include <3ds.h> 3 | 4 | u64 Timer_Restart(void); 5 | bool Timer_HasTimePassed(float nbmsecToWait, u64 timer); 6 | u64 getTimeInMsec(u64 timer); -------------------------------------------------------------------------------- /EzB9SUpdater.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ], 7 | "settings": { 8 | "files.associations": { 9 | "sound.h": "c", 10 | "main.h": "c", 11 | "graphics.h": "c" 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /ezb9supdater_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "canrun": "1", 3 | "sb9si": "https://github.com/d0k3/SafeB9SInstaller/releases/download/v0.0.7/SafeB9SInstaller-20170605-122940.zip", 4 | "sb9si_firm": "SafeB9SInstaller.firm", 5 | "b9sf": "https://github.com/SciresM/boot9strap/releases/download/1.4/boot9strap-1.4.zip", 6 | "b9sf_firm": "boot9strap.firm", 7 | "b9sf_sha": "boot9strap.firm.sha" 8 | } -------------------------------------------------------------------------------- /source/clock.c: -------------------------------------------------------------------------------- 1 | #include "clock.h" 2 | 3 | #define CPU_TICKS_PER_MSEC (SYSCLOCK_ARM11 / 1000.0) 4 | #define CPU_TICKS_PER_USEC (SYSCLOCK_ARM11 / 1000000.0) 5 | 6 | extern bool g_isNew3DS; 7 | 8 | u64 Timer_Restart(void) 9 | { 10 | return (svcGetSystemTick()); 11 | } 12 | u64 getTimeInMsec(u64 timer) { 13 | return timer / CPU_TICKS_PER_MSEC; 14 | } 15 | bool Timer_HasTimePassed(float nbmsecToWait, u64 timer) 16 | { 17 | u64 seconds = (u64)(nbmsecToWait * CPU_TICKS_PER_MSEC); 18 | u64 current = svcGetSystemTick(); 19 | u64 diff = current - timer; 20 | 21 | return (diff >= seconds); 22 | } -------------------------------------------------------------------------------- /source/vshader.v.pica: -------------------------------------------------------------------------------- 1 | ; Uniforms 2 | .fvec projection[4] 3 | 4 | ; Constants 5 | .constf myconst(0.0, 1.0, -1.0, 0.1) 6 | .constf RGBA_TO_FLOAT4(0.00392156862, 0, 0, 0) 7 | .alias ones myconst.yyyy ; Vector full of ones 8 | .alias zeros myconst.xxxx ; Vector full of zeros 9 | 10 | ; Outputs 11 | .out outpos position 12 | .out outclr color 13 | .out outtc0 texcoord0 14 | 15 | ; Inputs (defined as aliases for convenience) 16 | .alias inpos v0 17 | .alias intex v1 18 | 19 | .proc main 20 | ; Force the zw component of inpos to be 1.0 21 | mov r0.xy, inpos 22 | mov r0.z, zeros 23 | mov r0.w, ones 24 | 25 | ; outpos = projectionMatrix * inpos 26 | dp4 outpos.x, projection[0], r0 27 | dp4 outpos.y, projection[1], r0 28 | mov outpos.z, zeros 29 | mov outpos.w, ones 30 | 31 | ;outtc0 = intexcoord 32 | mov outtc0, intex 33 | 34 | ;outclr 35 | mul outclr, RGBA_TO_FLOAT4.xxxx, intex 36 | 37 | end 38 | .end -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "3ds", 5 | "includePath": [ 6 | "${default}", 7 | "C:\\devkitPro\\libcwav\\include", 8 | "C:\\devkitPro\\libctru\\include", 9 | "C:\\devkitPro\\portlibs\\3ds\\include", 10 | "C:\\devkitPro\\libncsnd\\include", 11 | "${workspaceFolder}\\intellisense" 12 | ], 13 | "defines": [ 14 | "_DEBUG", 15 | "UNICODE", 16 | "_UNICODE" 17 | ], 18 | "windowsSdkVersion": "10.0.18362.0", 19 | "compilerPath": "C:\\devkitPro\\devkitARM\\bin\\arm-none-eabi-gcc.exe", 20 | "cStandard": "c17", 21 | "cppStandard": "c++11", 22 | "forcedInclude": [ 23 | "${workspaceFolder}/intellisense/forced_include.h" 24 | ] 25 | } 26 | ], 27 | "version": 4 28 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /source/Unicode.h: -------------------------------------------------------------------------------- 1 | #ifndef UNICODE_H 2 | #define UNICODE_H 3 | 4 | // HID Symbols 5 | #define FONT_A "\uE000" // System Font A button 6 | #define FONT_B "\uE001" // System Font B button 7 | #define FONT_X "\uE002" // System Font X button 8 | #define FONT_Y "\uE003" // System Font Y button 9 | #define FONT_L "\uE052" // System Font L button 10 | #define FONT_R "\uE053" // System Font R button 11 | #define FONT_ZL "\uE054" // System Font ZL button 12 | #define FONT_ZR "\uE055" // System Font ZR button 13 | #define FONT_DU "\uE079" // System Font D-Pad Up button 14 | #define FONT_DD "\uE07A" // System Font D-Pad Down button 15 | #define FONT_DL "\uE07B" // System Font D-Pad Left button 16 | #define FONT_DR "\uE07C" // System Font D-Pad Right button 17 | #define FONT_DUD "\uE07D" // System Font D-Pad Up and Down button 18 | #define FONT_DLR "\uE07E" // System Font D-Pad Left and Right button 19 | #define FONT_CP "\uE077" // System Font Circle Pad button 20 | #define FONT_T "\uE058" // System Font Touch button 21 | #define FONT_POWER "\uE078" // System Font POWER button 22 | #define FONT_HOME "\uE073" // System Font HOME button 23 | 24 | #endif -------------------------------------------------------------------------------- /source/graphics.h: -------------------------------------------------------------------------------- 1 | #ifndef GRAPHICS_H 2 | #define GRAPHICS_H 3 | 4 | #include "draw.h" 5 | #include "main.h" 6 | #include "appInfo.h" 7 | 8 | #define STACKSIZE 0x1000 9 | 10 | void initUI(void); 11 | void exitUI(void); 12 | int updateUI(void); 13 | void greyExit(); 14 | void setExTopObject(void *object); 15 | void addTopObject(void *object); 16 | void addBottomObject(void *object); 17 | void changeTopFooter(sprite_t *footer); 18 | void changeTopHeader(sprite_t *header); 19 | void changeBottomFooter(sprite_t *footer); 20 | void changeBottomHeader(sprite_t *header); 21 | void clearTopScreen(void); 22 | void clearBottomScreen(void); 23 | 24 | extern appInfoObject_t *appTop; 25 | extern appInfoObject_t *appBottom; 26 | 27 | #define newAppTop(...) newAppInfoEntry(appTop, __VA_ARGS__) 28 | #define newAppTopMultiline(color, flags, text) drawMultilineText(color, flags, text) 29 | #define removeAppTop() removeAppInfoEntry(appTop) 30 | #define clearTop() clearAppInfo(appTop) 31 | 32 | #define TRACE() {newAppTop(DEFAULT_COLOR, SMALL, "%s:%d",__FUNCTION__, __LINE__); svcSleepThread(1000000000); updateUI(); svcSleepThread(1000000000);} 33 | #define XTRACE(str, ...) {newAppTop(DEFAULT_COLOR, SMALL, str, __VA_ARGS__); updateUI(); svcSleepThread(500000000);} 34 | 35 | #endif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EzB9SUpdater - Easy Boot9Strap Updater 2 | A 3DS tool to update B9S to the latest version (currently v1.4) without the need of a computer or SD card reader. 3 | 4 | This tool uses [SafeB9SInstaller](https://github.com/d0k3/SafeB9SInstaller) and [Boot9Strap](https://github.com/SciresM/boot9strap). 5 | 6 | ## Usage 7 | 1. Install the EzB9SUpdater cia file from the [Releases](https://github.com/PabloMK7/EzB9SUpdater/releases/latest) page. Alternatively use [this QR code](https://user-images.githubusercontent.com/10946643/170087006-a46d23f2-a15c-45ac-aaf3-d539533960b9.png) with FBI remote install. 8 | 2. Launch the EzB9SUpdater app from the Home Menu. 9 | 3. Follow the instructions in the app. At some point, you will be asked to press and hold the START button to reboot into SafeB9SInstaller. It is important that you keep holding the button until you see the SafeB9SInstaller screen. Otherwise, the console will just reboot into EzB9SUpdater again and no update will be performed. 10 | 4. Once you finish the B9S update, you can exit the app and uninstall it from FBI. 11 | 5. In order to check if you updated B9S from 1.3 to 1.4 do the following steps: 12 | 1. Power off your console. 13 | 2. Press and hold the following button combination: `X + START + SELECT`. 14 | 3. Without releasing those buttons, power on your device. 15 | 4. Your notification LED should lit up for a second ([status codes](https://github.com/SciresM/boot9strap#led-status-codes)). If it doesn't, the update wasn't installed properly. 16 | 17 | ## Credits 18 | - [@Rinnegatamante](https://github.com/Rinnegatamante) : Zip extracting code from [lpp-3ds](https://github.com/Rinnegatamante/lpp-3ds). 19 | - [@Krzysztof Gabis](https://github.com/kgabis) : JSON parsing utility [parson](https://github.com/kgabis/parson). 20 | - [@Steveice10](https://github.com/Steveice10) : buildtools 21 | - [@Nanquitas](https://github.com/Nanquitas) : BootNTRSelector, from which this app is based. 22 | - [@Kartik](https://github.com/hax0kartik) : Little help with reboot code. 23 | -------------------------------------------------------------------------------- /source/appInfo.h: -------------------------------------------------------------------------------- 1 | #ifndef APPINFO_H 2 | #define APPINFO_H 3 | 4 | #include "draw.h" 5 | 6 | #define MAX_ENTRIES 10 7 | #define BUFFER_SIZE 100 8 | #define DEFAULT_COLOR 0xFFFFFFFF 9 | #define RED 0xFFFF0000 10 | #define GREEN 0xFF00FF00 11 | 12 | 13 | typedef enum 14 | { 15 | BOLD = BIT(0), 16 | SKINNY = BIT(1), 17 | TINY = BIT(2), 18 | SMALL = BIT(3), 19 | MEDIUM = BIT(4), 20 | BIG = BIT(5), 21 | CENTER = BIT(6), 22 | RIGHT_ALIGN = BIT(7), 23 | NEWLINE = BIT(8), 24 | SCROLL = BIT(9) 25 | } appInfoEntryFlags; 26 | 27 | typedef struct appInfoEntry_s 28 | { 29 | u32 color; 30 | u32 flags; 31 | char buffer[BUFFER_SIZE]; 32 | } appInfoEntry_t; 33 | 34 | typedef struct appInfoObject_s 35 | { 36 | u32 entryCount; 37 | u32 maxEntryCount; 38 | u32 *entryList; 39 | cursor_t cursor; 40 | float boundX; 41 | float boundY; 42 | sprite_t *sprite; 43 | float spritePosX; 44 | float spritePosY; 45 | 46 | } appInfoObject_t; 47 | 48 | appInfoObject_t *newAppInfoObject(sprite_t *sprite, u32 maxEntryCount, u32 posX, u32 posY); 49 | void deleteAppInfoObject(appInfoObject_t *object); 50 | void appInfoSetTextBoundaries(appInfoObject_t *object, float posX, float posY); 51 | void appInfoSetSpritePosition(appInfoObject_t *object, float posX, float posY); 52 | void newAppInfoEntry(appInfoObject_t *object, u32 color, u32 flags, char *text, ...); 53 | void removeAppInfoEntry(appInfoObject_t *object); 54 | void clearAppInfo(appInfoObject_t *object); 55 | void drawMultilineText(u32 color, u32 flags, char* txt); 56 | void drawAppInfo(appInfoObject_t *object); 57 | void appInfoDisableAutoUpdate(void); 58 | void appInfoEnableAutoUpdate(void); 59 | void appInfoHideBackground(void); 60 | void appInfoShowBackground(void); 61 | /* 62 | ** graphic.h 63 | */ 64 | int updateUI(void); 65 | #endif -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # TARGET # 2 | 3 | 4 | TARGET := 3DS 5 | LIBRARY := 0 6 | 7 | ifeq ($(TARGET),$(filter $(TARGET),3DS WIIU)) 8 | ifeq ($(strip $(DEVKITPRO)),) 9 | $(error "Please set DEVKITPRO in your environment. export DEVKITPRO=devkitPro") 10 | endif 11 | endif 12 | 13 | # COMMON CONFIGURATION # 14 | 15 | NAME := EzB9SUpdater 16 | 17 | BUILD_DIR := build 18 | OUTPUT_DIR := output 19 | SOURCE_DIRS := source source/json source/allocator source/bootntr 20 | INCLUDE_DIRS := $(SOURCE_DIRS) include 21 | 22 | EXTRA_OUTPUT_FILES := 23 | 24 | LIBRARY_DIRS := $(PORTLIBS) $(CTRULIB) $(DEVKITPRO)/libcwav $(DEVKITPRO)/libncsnd 25 | LIBRARIES := citro3d ctru png z m curl mbedtls mbedx509 mbedcrypto cwav ncsnd 26 | 27 | VERSION_MAJOR := 1 28 | VERSION_MINOR := 0 29 | VERSION_MICRO := 1 30 | 31 | ifndef EZB9S_CONFIG_LINK 32 | $(error You must pass EZB9S_CONFIG_LINK on the make command line, e.g. 'make EZB9S_CONFIG_LINK="https://example.com"') 33 | endif 34 | 35 | BUILD_FLAGS := -march=armv6k -mtune=mpcore -mfloat-abi=hard 36 | BUILD_FLAGS_CC := -g -Wall -Wno-strict-aliasing -O3 -mword-relocations \ 37 | -fomit-frame-pointer -ffast-math $(ARCH) $(INCLUDE) -D__3DS__ $(BUILD_FLAGS) \ 38 | -DAPP_VERSION_MAJOR=${VERSION_MAJOR} \ 39 | -DAPP_VERSION_MINOR=${VERSION_MINOR} \ 40 | -DAPP_VERSION_MICRO=${VERSION_MICRO} \ 41 | -DEZB9S_CONFIG_LINK=\"${EZB9S_CONFIG_LINK}\" 42 | 43 | BUILD_FLAGS_CXX := $(COMMON_FLAGS) -std=gnu++11 44 | RUN_FLAGS := 45 | 46 | 47 | 48 | 49 | 50 | # 3DS/Wii U CONFIGURATION # 51 | 52 | ifeq ($(TARGET),$(filter $(TARGET),3DS WIIU)) 53 | TITLE := EzB9SUpdater 54 | DESCRIPTION := Easy Updater For B9S 55 | AUTHOR := PabloMK7 56 | endif 57 | 58 | # 3DS CONFIGURATION # 59 | 60 | ifeq ($(TARGET),3DS) 61 | LIBRARY_DIRS += $(DEVKITPRO)/libctru $(DEVKITPRO)/portlibs/3ds/ 62 | LIBRARIES += citro3d ctru png z m curl mbedtls mbedx509 mbedcrypto 63 | 64 | PRODUCT_CODE := CTR-P-EZB9 65 | UNIQUE_ID := 0xECB95 66 | 67 | CATEGORY := Application 68 | USE_ON_SD := true 69 | 70 | MEMORY_TYPE := Application 71 | SYSTEM_MODE := 64MB 72 | SYSTEM_MODE_EXT := Legacy 73 | CPU_SPEED := 268MHz 74 | ENABLE_L2_CACHE := true 75 | 76 | ICON_FLAGS := --flags visible,recordusage 77 | 78 | ROMFS_DIR := romfs 79 | 80 | BANNER_AUDIO := resources/audio.cwav 81 | 82 | BANNER_IMAGE := resources/banner.png 83 | 84 | ICON := resources/icon.png 85 | 86 | endif 87 | 88 | # INTERNAL # 89 | 90 | include buildtools/make_base 91 | 92 | cleanupdater: 93 | @rm -f $(BUILD_DIR)/3ds-arm/source/updater.d $(BUILD_DIR)/3ds-arm/source/updater.o 94 | 95 | re : clean all 96 | .PHONY: re -------------------------------------------------------------------------------- /source/common_functions.c: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | 3 | extern u8 *tmpBuffer; 4 | extern char *g_primary_error; 5 | extern char *g_secondary_error; 6 | extern bool g_exit; 7 | 8 | void flushDataCache(void) 9 | { 10 | u32 *ptr = (u32 *)tmpBuffer; 11 | u32 i; 12 | 13 | for (i = 0; i < (0x20000 / 4); i++) 14 | { 15 | ptr[i] += 0x11111111; 16 | } 17 | } 18 | 19 | void doStallCpu(void) 20 | { 21 | vu32 i; 22 | for (i = 0; i < 0x00100000; i++) 23 | { 24 | } 25 | } 26 | 27 | void doWait(void) 28 | { 29 | svcSleepThread(500000000); 30 | } 31 | 32 | void strJoin(char *dst, const char *s1, const char *s2) 33 | { 34 | if (!dst || !s1 || !s2) return; 35 | 36 | while (*s1) 37 | *dst++ = *s1++; 38 | while (*s2) 39 | *dst++ = *s2++; 40 | *dst = '\0'; 41 | } 42 | 43 | void strInsert(char *dst, char *src, int index) 44 | { 45 | char *bak; 46 | int srcSize; 47 | 48 | if (!dst || !src) return; 49 | 50 | bak = strdup(dst + index); 51 | strcpy(dst + index, src); 52 | srcSize = strlen(src); 53 | strcpy(dst + srcSize, bak); 54 | free(bak); 55 | } 56 | 57 | void strncpyFromTail(char *dst, char *src, int nb) 58 | { 59 | if (!src || !dst || nb == 0) return; 60 | while (*src) src++; 61 | src--; 62 | nb--; 63 | dst += nb; 64 | while (nb-- >= 0) 65 | *dst-- = *src--; 66 | } 67 | 68 | bool inputPathKeyboard(char *dst, char *hintText, char *initialText, int bufSize) 69 | { 70 | static SwkbdState keyboard; 71 | u32 features = 0; 72 | SwkbdButton button = SWKBD_BUTTON_NONE; 73 | 74 | swkbdInit(&keyboard, SWKBD_TYPE_QWERTY, 2, -1); 75 | swkbdSetFeatures(&keyboard, features); 76 | swkbdSetHintText(&keyboard, hintText); 77 | if (initialText) 78 | swkbdSetInitialText(&keyboard, initialText); 79 | swkbdSetButton(&keyboard, SWKBD_BUTTON_LEFT, "Cancel", false); 80 | swkbdSetButton(&keyboard, SWKBD_BUTTON_RIGHT, "Ok", true); 81 | button = swkbdInputText(&keyboard, dst, bufSize); 82 | if (button == SWKBD_BUTTON_LEFT) 83 | return (false); 84 | else 85 | return (true); 86 | } 87 | 88 | void customBreak(u32 r0, u32 r1, u32 r2, u32 r3) { 89 | __asm__ __volatile__("svc 0x3C"); 90 | for (;;); 91 | } 92 | 93 | void waitAllKeysReleased(void) 94 | { 95 | while (1) 96 | { 97 | hidScanInput(); 98 | if ((hidKeysDown() | hidKeysHeld() | hidKeysUp()) == 0) 99 | return; 100 | } 101 | } 102 | 103 | void debug(char *str, int seconds) 104 | { 105 | time_t t; 106 | 107 | newAppTop(DEFAULT_COLOR, 0, "%s", str); 108 | t = time(NULL); 109 | while (t + seconds != time(NULL)) 110 | updateUI(); 111 | } 112 | 113 | void wait(int seconds) 114 | { 115 | time_t t; 116 | 117 | t = time(NULL); 118 | while (t + seconds != time(NULL)); 119 | } 120 | -------------------------------------------------------------------------------- /source/csvc.s: -------------------------------------------------------------------------------- 1 | @ This paricular file is licensed under the following terms: 2 | 3 | @ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable 4 | @ for any damages arising from the use of this software. 5 | @ 6 | @ Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it 7 | @ and redistribute it freely, subject to the following restrictions: 8 | @ 9 | @ The origin of this software must not be misrepresented; you must not claim that you wrote the original software. 10 | @ If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 11 | @ 12 | @ Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 13 | @ This notice may not be removed or altered from any source distribution. 14 | 15 | .arm 16 | .balign 4 17 | 18 | .macro SVC_BEGIN name 19 | .section .text.\name, "ax", %progbits 20 | .global \name 21 | .type \name, %function 22 | .align 2 23 | .cfi_startproc 24 | \name: 25 | .endm 26 | 27 | .macro SVC_END 28 | .cfi_endproc 29 | .endm 30 | 31 | SVC_BEGIN svcCustomBackdoor 32 | svc 0x80 33 | bx lr 34 | SVC_END 35 | 36 | SVC_BEGIN svcConvertVAToPA 37 | svc 0x90 38 | bx lr 39 | SVC_END 40 | 41 | SVC_BEGIN svcFlushDataCacheRange 42 | svc 0x91 43 | bx lr 44 | SVC_END 45 | 46 | SVC_BEGIN svcFlushEntireDataCache 47 | svc 0x92 48 | bx lr 49 | SVC_END 50 | 51 | SVC_BEGIN svcInvalidateInstructionCacheRange 52 | svc 0x93 53 | bx lr 54 | SVC_END 55 | 56 | SVC_BEGIN svcInvalidateEntireInstructionCache 57 | svc 0x94 58 | bx lr 59 | SVC_END 60 | 61 | SVC_BEGIN svcMapProcessMemoryEx 62 | str r4, [sp, #-4]! 63 | ldr r4, [sp, #4] 64 | svc 0xA0 65 | ldr r4, [sp], #4 66 | bx lr 67 | SVC_END 68 | 69 | SVC_BEGIN svcUnmapProcessMemoryEx 70 | svc 0xA1 71 | bx lr 72 | SVC_END 73 | 74 | SVC_BEGIN svcControlMemoryEx 75 | push {r0, r4, r5} 76 | ldr r0, [sp, #0xC] 77 | ldr r4, [sp, #0xC+0x4] 78 | ldr r5, [sp, #0xC+0x8] 79 | svc 0xA2 80 | pop {r2, r4, r5} 81 | str r1, [r2] 82 | bx lr 83 | SVC_END 84 | 85 | SVC_BEGIN svcControlMemoryUnsafe 86 | str r4, [sp, #-4]! 87 | ldr r4, [sp, #4] 88 | svc 0xA3 89 | ldr r4, [sp], #4 90 | bx lr 91 | SVC_END 92 | 93 | SVC_BEGIN svcFreeMemory 94 | svc 0xA3 95 | bx lr 96 | SVC_END 97 | 98 | SVC_BEGIN svcControlService 99 | svc 0xB0 100 | bx lr 101 | SVC_END 102 | 103 | SVC_BEGIN svcCopyHandle 104 | str r0, [sp, #-4]! 105 | svc 0xB1 106 | ldr r2, [sp], #4 107 | str r1, [r2] 108 | bx lr 109 | SVC_END 110 | 111 | SVC_BEGIN svcTranslateHandle 112 | str r0, [sp, #-4]! 113 | svc 0xB2 114 | ldr r2, [sp], #4 115 | str r1, [r2] 116 | bx lr 117 | SVC_END 118 | 119 | SVC_BEGIN svcControlProcess 120 | svc 0xB3 121 | bx lr 122 | SVC_END 123 | -------------------------------------------------------------------------------- /source/drawableObject.h: -------------------------------------------------------------------------------- 1 | #ifndef DRAWABLEOBJECT_H 2 | #define DRAWABLEOBJECT_H 3 | #define MAX_ELEMENTS 15 4 | 5 | #include "draw.h" 6 | 7 | typedef struct drawableObject_s 8 | { 9 | bool (*draw)(void *self); 10 | } drawableObject_t; 11 | 12 | typedef struct drawableSprite_s 13 | { 14 | bool (*draw)(void* self); 15 | sprite_t *sprite; 16 | } drawableSprite_t; 17 | 18 | typedef struct text_s 19 | { 20 | /* herited from drawableObject_t */ 21 | bool (*draw)(void *self); 22 | 23 | char *str; 24 | int color; 25 | float posX; 26 | float posY; 27 | float scaleX; 28 | float scaleY; 29 | bool visible; 30 | } text_t; 31 | 32 | typedef struct image_s 33 | { 34 | /* herited from drawableObject_t */ 35 | bool (*draw)(void *self); 36 | 37 | sprite_t *sprite; 38 | } image_t; 39 | 40 | typedef struct window_s 41 | { 42 | /* herited from drawableObject_t */ 43 | bool (*draw)(void *self); 44 | 45 | sprite_t *title; 46 | sprite_t *content; 47 | sprite_t *background; 48 | } window_t; 49 | 50 | typedef struct backgroundScreen_s 51 | { 52 | /* herited from drawableObject_t */ 53 | bool (*draw)(void *self); 54 | 55 | sprite_t *background; 56 | sprite_t *headerText; 57 | sprite_t *footerText; 58 | 59 | } backgroundScreen_t; 60 | 61 | typedef struct drawableScreen_s 62 | { 63 | /* herited from drawableObject_t */ 64 | bool (*draw)(void *self); 65 | 66 | backgroundScreen_t *background; 67 | int elementsCount; 68 | int elementList[MAX_ELEMENTS]; 69 | } drawableScreen_t; 70 | 71 | void initDrawableSprite(drawableSprite_t* object, sprite_t* sprite); 72 | 73 | backgroundScreen_t *newBackgroundObject(sprite_t *background, \ 74 | sprite_t *header, sprite_t *footer); 75 | bool drawBackground(void *self); 76 | void changeBackgroundHeader(backgroundScreen_t *bg, sprite_t *header); 77 | void changeBackgroundFooter(backgroundScreen_t *bg, sprite_t *footer); 78 | 79 | drawableScreen_t *newDrawableScreen(backgroundScreen_t *background); 80 | bool drawScreen(void *self); 81 | void addObjectToScreen(drawableScreen_t *screen, void *object); 82 | void setExTopObjectToScreen(drawableScreen_t *screen, void *object); 83 | void *removeLastObjectFromScreen(drawableScreen_t *screen); 84 | void clearObjectListFromScreen(drawableScreen_t *screen); 85 | 86 | bool drawImage(void *self); 87 | 88 | window_t *newWindow(sprite_t *background, sprite_t *title, \ 89 | sprite_t *content); 90 | bool drawWindow(void *self); 91 | void changeWindowContent(window_t *window, sprite_t *content); 92 | void changeWindowTitle(window_t *window, sprite_t *title); 93 | 94 | text_t *newText(char *str, float posX, float posY, float scaleX, float scaleY, int color); 95 | bool drawTextObject(void *self); 96 | void hideText(text_t *text); 97 | void showText(text_t *text); 98 | 99 | rectangle_t *newRectangle(float posX, float posY, float width, float height, float initialamount, sprite_t* sprite); 100 | bool drawRectangleObject(void *self); 101 | 102 | #endif 103 | -------------------------------------------------------------------------------- /source/graphics.c: -------------------------------------------------------------------------------- 1 | #include "graphics.h" 2 | #include "drawableObject.h" 3 | 4 | sprite_t *bottomSprite = NULL; 5 | sprite_t *topSprite = NULL; 6 | 7 | sprite_t *topInfoSprite = NULL; 8 | 9 | drawableScreen_t *botScreen = NULL; 10 | drawableScreen_t *topScreen = NULL; 11 | appInfoObject_t *appTop = NULL; 12 | 13 | char textVersion[20] = { 0 }; 14 | 15 | void initUI(void) 16 | { 17 | backgroundScreen_t *bg; 18 | 19 | newSpriteFromPNG(&topSprite, "romfs:/sprites/topBackground.png"); 20 | newSpriteFromPNG(&bottomSprite, "romfs:/sprites/bottomBackground.png"); 21 | 22 | newSpriteFromPNG(&topInfoSprite, "romfs:/sprites/topInfoBackground.png"); 23 | 24 | setSpritePos(topSprite, 0, 0); 25 | setSpritePos(bottomSprite, 0, 0); 26 | 27 | bg = newBackgroundObject(bottomSprite, NULL, NULL); 28 | botScreen = newDrawableScreen(bg); 29 | bg = newBackgroundObject(topSprite, NULL, NULL); 30 | topScreen = newDrawableScreen(bg); 31 | 32 | setSpritePos(topInfoSprite, 50, 20); 33 | appTop = newAppInfoObject(topInfoSprite, 14, 58.0f, 30.0f); 34 | appInfoSetTextBoundaries(appTop, 343.0f, 220.0f); 35 | } 36 | 37 | void exitUI(void) 38 | { 39 | deleteAppInfoObject(appTop); 40 | deleteSprite(bottomSprite); 41 | deleteSprite(topSprite); 42 | deleteSprite(topInfoSprite); 43 | } 44 | 45 | void greyExit() { 46 | botScreen->background->background->isGreyedOut = true; 47 | topScreen->background->background->isGreyedOut = true; 48 | if (topInfoSprite) topInfoSprite->isGreyedOut = true; 49 | } 50 | 51 | static inline void drawUITop(void) 52 | { 53 | setScreen(GFX_TOP); 54 | 55 | topScreen->draw(topScreen); 56 | 57 | setTextColor(COLOR_BLANK); 58 | if (textVersion[0] == '\0') { 59 | sprintf(textVersion, "Ver. %d.%d.%d", APP_VERSION_MAJOR, APP_VERSION_MINOR, APP_VERSION_MICRO); 60 | } 61 | renderText(1.0f, 1.0f, 0.4f, 0.45f, false, textVersion, NULL, 0.0f); 62 | 63 | drawAppInfo(appTop); 64 | } 65 | 66 | static inline void drawUIBottom(void) 67 | { 68 | setScreen(GFX_BOTTOM); 69 | 70 | botScreen->draw(botScreen); 71 | } 72 | 73 | int updateUI(void) 74 | { 75 | hidScanInput(); 76 | if (aptMainLoop()) { 77 | drawUITop(); 78 | drawUIBottom(); 79 | updateScreen(); 80 | } 81 | return (1); 82 | } 83 | 84 | void addTopObject(void *object) 85 | { 86 | addObjectToScreen(topScreen, object); 87 | } 88 | 89 | void setExTopObject(void *object) 90 | { 91 | setExTopObjectToScreen(topScreen, object); 92 | } 93 | 94 | void addBottomObject(void *object) 95 | { 96 | addObjectToScreen(botScreen, object); 97 | } 98 | 99 | void changeTopFooter(sprite_t *footer) 100 | { 101 | changeBackgroundFooter(topScreen->background, footer); 102 | } 103 | 104 | void changeTopHeader(sprite_t *header) 105 | { 106 | changeBackgroundHeader(topScreen->background, header); 107 | } 108 | 109 | void changeBottomFooter(sprite_t *footer) 110 | { 111 | changeBackgroundFooter(botScreen->background, footer); 112 | } 113 | 114 | void changeBottomHeader(sprite_t *header) 115 | { 116 | changeBackgroundHeader(botScreen->background, header); 117 | } 118 | 119 | void clearTopScreen(void) 120 | { 121 | clearObjectListFromScreen(topScreen); 122 | } 123 | 124 | void clearBottomScreen(void) 125 | { 126 | clearObjectListFromScreen(botScreen); 127 | } -------------------------------------------------------------------------------- /source/files.c: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | #include 3 | #include 4 | #include 5 | 6 | extern char *g_primary_error; 7 | 8 | bool fileExists(const char *path) 9 | { 10 | int exists; 11 | 12 | if (!path) goto error; 13 | exists = access(path, F_OK); 14 | if (exists == 0) 15 | return (true); 16 | error: 17 | return (false); 18 | } 19 | 20 | int copy_file(char *old_filename, char *new_filename) 21 | { 22 | FILE *old_file = NULL; 23 | FILE *new_file = NULL; 24 | u8* buffer = NULL; 25 | 26 | old_file = fopen(old_filename, "rb"); 27 | new_file = fopen_mkdir(new_filename, "wb"); 28 | u32 buffsize = 0x60000; 29 | buffer = memalign(0x1000, buffsize); 30 | if (!new_file || !old_file || !buffer) 31 | { 32 | if (old_file) fclose(old_file); 33 | if (new_file) fclose(new_file); 34 | if (buffer) free(buffer); 35 | return 1; 36 | } 37 | fseek(old_file, 0, SEEK_END); 38 | u32 totFile = ftell(old_file); 39 | fseek(old_file, 0, SEEK_SET); 40 | u32 currFile = 0; 41 | while (currFile < totFile) 42 | { 43 | if (totFile - currFile < buffsize) buffsize = totFile - currFile; 44 | fread(buffer, 1, buffsize, old_file); 45 | fwrite(buffer, 1, buffsize, new_file); 46 | currFile += buffsize; 47 | fseek(old_file, currFile, SEEK_SET); 48 | fseek(new_file, currFile, SEEK_SET); 49 | } 50 | fclose(new_file); 51 | fclose(old_file); 52 | free(buffer); 53 | return (0); 54 | } 55 | 56 | int createDir(const char *path) 57 | { 58 | u32 len = strlen(path); 59 | char _path[0x100]; 60 | char *p; 61 | 62 | errno = 0; 63 | if (len > 0x100) goto error; 64 | strcpy(_path, path); 65 | for (p = _path + 1; *p; p++) 66 | { 67 | if (*p == '/') 68 | { 69 | *p = '\0'; 70 | if (mkdir(_path, 777) != 0) 71 | if (errno != EEXIST) goto error; 72 | *p = '/'; 73 | } 74 | } 75 | if (mkdir(_path, 777) != 0) 76 | if (errno != EEXIST) goto error; 77 | return (0); 78 | error: 79 | return (-1); 80 | } 81 | 82 | 83 | Result deleteDirectory(char* sdDir) { 84 | FS_Archive sd; 85 | FS_Path sd_path = { PATH_EMPTY, 0, NULL }; 86 | Result ret = 0; 87 | ret = FSUSER_OpenArchive(&sd, ARCHIVE_SDMC, sd_path); 88 | if (ret < 0) return ret; 89 | ret = FSUSER_DeleteDirectoryRecursively(sd, fsMakePath(PATH_ASCII, sdDir)); 90 | FSUSER_CloseArchive(sd); 91 | return ret; 92 | } 93 | 94 | Result existsDirectory(char *sdDir) { 95 | FS_Archive sd; 96 | FS_Path sd_path = { PATH_EMPTY, 0, NULL }; 97 | Result ret = 0; 98 | Handle dir = 0; 99 | ret = FSUSER_OpenArchive(&sd, ARCHIVE_SDMC, sd_path); 100 | if (ret < 0) return false; 101 | ret = FSUSER_OpenDirectory(&dir, sd, fsMakePath(PATH_ASCII, sdDir)); 102 | if (ret >= 0) { 103 | FSDIR_Close(dir); 104 | FSUSER_CloseArchive(sd); 105 | return true; 106 | } 107 | FSUSER_CloseArchive(sd); 108 | return false; 109 | } 110 | 111 | Result renameDir(char* src, char* dst) { 112 | FS_Archive sd; 113 | FS_Path sd_path = { PATH_EMPTY, 0, NULL }; 114 | Result ret = 0; 115 | ret = FSUSER_OpenArchive(&sd, ARCHIVE_SDMC, sd_path); 116 | if (ret < 0) return ret; 117 | ret = FSUSER_RenameDirectory(sd, fsMakePath(PATH_ASCII, src), sd, fsMakePath(PATH_ASCII, dst)); 118 | FSUSER_CloseArchive(sd); 119 | return ret; 120 | } 121 | 122 | Result getFreeSpace(u64* out) { 123 | FS_ArchiveResource resource = { 0 }; 124 | int ret = FSUSER_GetArchiveResource(&resource, SYSTEM_MEDIATYPE_SD); 125 | if (ret < 0) return ret; 126 | *out = (u64)resource.freeClusters * (u64)resource.clusterSize; 127 | return ret; 128 | } -------------------------------------------------------------------------------- /source/draw.h: -------------------------------------------------------------------------------- 1 | #ifndef DRAW_H 2 | #define DRAW_H 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include <3ds.h> 9 | #include 10 | 11 | typedef struct sprite_s 12 | { 13 | C3D_Tex texture; 14 | float posX; 15 | float posY; 16 | float height; 17 | float width; 18 | u32 drawColor; 19 | bool isGreyedOut; 20 | bool isHidden; 21 | float depth; 22 | float amount; // from 0 to 1 23 | } sprite_t; 24 | 25 | typedef struct rectangle_s 26 | { 27 | /* herited from drawableObject_t */ 28 | bool(*draw)(void *self); 29 | 30 | float posX; 31 | float posY; 32 | float width; 33 | float height; 34 | sprite_t* sprite; 35 | float amount; //Range from 0 to 1 36 | float depth; 37 | } rectangle_t; 38 | 39 | #include "drawableObject.h" 40 | 41 | // These headers are generated by the build process 42 | #include "vshader_shbin.h" 43 | 44 | //#define CITRA //Citra doesn't like the setTextColor 45 | 46 | #define CLEAR_COLOR 0x68B0D8FF 47 | #define SCREEN_POS(x, y) (screenPos_t)((x << 16) | (y)) 48 | #define POS_X(screenPos) (float)(screenPos >> 16) 49 | #define POS_Y(screenPos) (float)(screenPos & 0xFFFF) 50 | 51 | // Used to transfer the final rendered display to the framebuffer 52 | #define DISPLAY_TRANSFER_FLAGS \ 53 | (GX_TRANSFER_FLIP_VERT(0) | GX_TRANSFER_OUT_TILED(0) | GX_TRANSFER_RAW_COPY(0) | \ 54 | GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGBA8) | GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGB8) | \ 55 | GX_TRANSFER_SCALING(GX_TRANSFER_SCALE_NO)) 56 | 57 | // Used to convert textures to 3DS tiled format 58 | // Note: vertical flip flag set so 0,0 is top left of texture 59 | #define TEXTURE_TRANSFER_FLAGS \ 60 | (GX_TRANSFER_FLIP_VERT(1) | GX_TRANSFER_OUT_TILED(1) | GX_TRANSFER_RAW_COPY(0) | \ 61 | GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGBA8) | GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGBA8) | \ 62 | GX_TRANSFER_SCALING(GX_TRANSFER_SCALE_NO)) 63 | 64 | typedef struct 65 | { 66 | float position[3]; 67 | float texcoord[2]; 68 | } textVertex_s; 69 | 70 | typedef struct drawTarget_s 71 | { 72 | C3D_RenderTarget *target; 73 | C3D_Mtx projection; 74 | } drawTarget_t; 75 | typedef struct 76 | { 77 | float posX; 78 | float posY; 79 | } cursor_t; 80 | 81 | 82 | typedef u32 screenPos_t; 83 | 84 | void drawInit(void); 85 | void drawExit(void); 86 | void getTextSizeInfos(float *width, float scaleX, float scaleY, const char *text); 87 | void setTextColor(u32 color); 88 | void renderText(float x, float y, float scaleX, float scaleY, bool baseline, const char *text, cursor_t *cursor, float depth); 89 | void findBestSize(float *sizeX, float *sizeY, float posXMin, float posXMax, float sizeMax, const char *text); 90 | void setScreen(gfxScreen_t screen); 91 | void updateScreen(void); 92 | 93 | sprite_t *newSprite(int width, int height); 94 | Result newSpriteFromPNG(sprite_t **out, const char *filename); 95 | void deleteSprite(sprite_t *sprite); 96 | void setSpritePos(sprite_t *sprite, float posX, float posY); 97 | void drawSprite(sprite_t *sprite); 98 | void drawRectangle(rectangle_t *rect); 99 | 100 | #define COLOR_BLUE 0xFFFF0000 101 | #define COLOR_RED 0xFF0000FF 102 | #define COLOR_GREEN 0xFF00FF00 103 | #define COLOR_YELLOW 0xFF00FFFF 104 | #define COLOR_CYAN 0xFFFFFF00 105 | #define COLOR_PURPLE 0xFF800080 106 | #define COLOR_FUCHSIA 0xFFFF00FF 107 | #define COLOR_BLANK 0xFFFFFFFF 108 | #define COLOR_BLACK 0xFF000000 109 | #define COLOR_GREY 0xFF989898 110 | #define COLOR_ORANGE 0xFF00A5FF 111 | #define COLOR_LIMEGREEN 0xFF32CD32 112 | #define COLOR_SALMON 0xFF7280FA 113 | #define COLOR_SILVER 0xFFC0C0C0 114 | #define COLOR_CORAL 0xFF507FFF 115 | 116 | #define COLOR_DARKGREEN 0xFF006400 117 | 118 | 119 | 120 | #endif -------------------------------------------------------------------------------- /source/main.h: -------------------------------------------------------------------------------- 1 | #ifndef MAIN_H 2 | #define MAIN_H 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "3ds.h" 13 | #include "3ds/types.h" 14 | #include "graphics.h" 15 | #include "drawableObject.h" 16 | #include "csvc.h" 17 | #include "curl/curl.h" 18 | 19 | 20 | #define check_prim(result, err) if ((result) != 0) {g_primary_error = err; \ 21 | goto error; } 22 | #define check_sec(result, err) if ((result) != 0) {g_secondary_error = err; \ 23 | goto error; } 24 | #define check_third(result, err) if ((result) != 0) {g_third_error = err; \ 25 | goto error; } 26 | 27 | #define CURRENT_PROCESS_HANDLE (0xffff8001) 28 | #define RESULT_ERROR (1) 29 | #define TMPBUFFER_SIZE (0x20000) 30 | #define URL_MAX 1024 31 | 32 | #define READREMOTEMEMORY_TIMEOUT (char *)s_error[0] 33 | #define OPENPROCESS_FAILURE (char *)s_error[1] 34 | #define PROTECTMEMORY_FAILURE (char *)s_error[2] 35 | #define REMOTECOPY_FAILURE (char *)s_error[3] 36 | #define CFGU_INIT_FAILURE (char *)s_error[4] 37 | #define CFGU_SECURE_FAILURE (char *)s_error[5] 38 | #define WRONGREGION (char *)s_error[6] 39 | #define SMPATCH_FAILURE (char *)s_error[7] 40 | #define FSPATCH_FAILURE (char *)s_error[8] 41 | #define FILEOPEN_FAILURE (char *)s_error[9] 42 | #define NULLSIZE (char *)s_error[10] 43 | #define LINEARMEMALIGN_FAILURE (char *)s_error[11] 44 | #define ACCESSPATCH_FAILURE (char *)s_error[12] 45 | #define UNKNOWN_FIRM (char *)s_error[13] 46 | #define UNKNOWN_HOMEMENU (char *)s_error[14] 47 | #define USER_ABORT (char *)s_error[15] 48 | #define FILE_COPY_ERROR (char *)s_error[16] 49 | #define LOAD_FAILED (char *)s_error[17] 50 | #define NTR_ALREADY_LAUNCHED (char *)s_error[18] 51 | #define CUSTOM_PM_PATCH_FAIL (char *)s_error[19] 52 | 53 | static const char* const s_error[] = 54 | { 55 | "READREMOTEMEMORY_TIMEOUT", 56 | "OPENPROCESS_FAILURE", 57 | "PROTECTMEMORY_FAILURE", 58 | "REMOTECOPY_FAILURE", 59 | "CFGU_INIT_FAILURE", 60 | "CFGU_SECURE_FAILURE", 61 | "WRONGREGION", 62 | "SMPATCH_FAILURE", 63 | "FSPATCH_FAILURE", 64 | "FILEOPEN_FAILURE", 65 | "NULL SIZE", 66 | "LINEARMEMALIGN_FAILURE", 67 | "ACCESSPATCH_FAILURE", 68 | "UNKNOWN_FIRM", 69 | "UNKNOWN_HOMEMENU", 70 | "USER_ABORT", 71 | "FILE_COPY_ERROR", 72 | "LOAD_AND_EXECUTE", 73 | "NTR is already running", 74 | "CUSTOM_PM_PATCH_FAIL" 75 | }; 76 | 77 | #define CIA_ALREADY_EXISTS 0xC8E083FC 78 | 79 | typedef struct updateData_s 80 | { 81 | char url[URL_MAX]; 82 | u32 responseCode; 83 | } updateData_t; 84 | 85 | typedef void(*funcType)(); 86 | typedef struct s_BLOCK 87 | { 88 | u32 buffer[4]; 89 | } t_BLOCK; 90 | 91 | typedef enum version_e 92 | { 93 | V32 = 0, 94 | V33 = 1, 95 | V36 = 2, 96 | } version_t; 97 | /* 98 | * main.c 99 | */ 100 | extern bool isN3DS; 101 | /* 102 | ** misc.s 103 | */ 104 | void kFlushDataCache(void *, u32); 105 | void flushDataCache(void); 106 | void FlushAllCache(void); 107 | void InvalidateEntireInstructionCache(void); 108 | void InvalidateEntireDataCache(void); 109 | s32 backdoorHandler(); 110 | 111 | /* 112 | ** files.c 113 | */ 114 | int copy_file(char *old_filename, char *new_filename); 115 | bool fileExists(const char *path); 116 | int createDir(const char *path); 117 | Result deleteDirectory(char* sdDir); 118 | Result existsDirectory(char *sdDir); 119 | Result renameDir(char* src, char* dst); 120 | Result getFreeSpace(u64* out); 121 | 122 | /* 123 | ** common_functions.c 124 | */ 125 | bool abort_and_exit(void); 126 | u32 getCurrentProcessHandle(void); 127 | void flushDataCache(void); 128 | void doFlushCache(void); 129 | void doStallCpu(void); 130 | void doWait(void); 131 | void strJoin(char *dst, const char *s1, const char *s2); 132 | void strInsert(char *dst, char *src, int index); 133 | void strncpyFromTail(char *dst, char *src, int nb); 134 | bool inputPathKeyboard(char *dst, char *hintText, char *initialText, int bufSize); 135 | void waitAllKeysReleased(void); 136 | void wait(int seconds); 137 | void debug(char *str, int seconds); 138 | void customBreak(u32 r0, u32 r1, u32 r2, u32 r3); 139 | 140 | /* 141 | ** updater.c 142 | */ 143 | extern char CURL_lastErrorCode[CURL_ERROR_SIZE]; 144 | int downloadFile(const char* URL, char* filepath); 145 | int downloadString(const char* URL, char** out); 146 | char* getProgText(float prog, int index); 147 | FILE* fopen_mkdir(const char* name, const char* mode); 148 | u64 ezB9SPerform(); 149 | void ezB9SCleanup(); 150 | 151 | /* 152 | * stubsvc.c 153 | */ 154 | void StubDebugSvc(); 155 | void UnStubDebugSvc(); 156 | extern bool beingDebugged; 157 | 158 | /* 159 | * aptextension.c 160 | */ 161 | u32 APT_Reboot(u64 titleID, FS_MediaType mediatype, u32 firmtidlow); 162 | 163 | 164 | #endif -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | /Tools 25 | /11.2 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # DNX 46 | project.lock.json 47 | artifacts/ 48 | 49 | *_i.c 50 | *_p.c 51 | *_i.h 52 | *.ilk 53 | *.meta 54 | *.obj 55 | *.pch 56 | *.pdb 57 | *.pgc 58 | *.pgd 59 | *.rsp 60 | *.sbr 61 | *.tlb 62 | *.tli 63 | *.tlh 64 | *.tmp 65 | *.tmp_proj 66 | *.log 67 | *.vspscc 68 | *.vssscc 69 | .builds 70 | *.pidb 71 | *.svclog 72 | *.scc 73 | 74 | # Chutzpah Test files 75 | _Chutzpah* 76 | 77 | # Visual C++ cache files 78 | ipch/ 79 | *.aps 80 | *.ncb 81 | *.opendb 82 | *.opensdf 83 | *.sdf 84 | *.cachefile 85 | *.VC.db 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | 145 | # TODO: Un-comment the next line if you do not want to checkin 146 | # your web deploy settings because they may include unencrypted 147 | # passwords 148 | #*.pubxml 149 | *.publishproj 150 | 151 | # NuGet Packages 152 | *.nupkg 153 | # The packages folder can be ignored because of Package Restore 154 | **/packages/* 155 | # except build/, which is used as an MSBuild target. 156 | !**/packages/build/ 157 | # Uncomment if necessary however generally it will be regenerated when needed 158 | #!**/packages/repositories.config 159 | # NuGet v3's project.json files produces more ignoreable files 160 | *.nuget.props 161 | *.nuget.targets 162 | 163 | # Microsoft Azure Build Output 164 | csx/ 165 | *.build.csdef 166 | 167 | # Microsoft Azure Emulator 168 | ecf/ 169 | rcf/ 170 | 171 | # Microsoft Azure ApplicationInsights config file 172 | ApplicationInsights.config 173 | 174 | # Windows Store app package directory 175 | AppPackages/ 176 | BundleArtifacts/ 177 | 178 | # Visual Studio cache files 179 | # files ending in .cache can be ignored 180 | *.[Cc]ache 181 | # but keep track of directories ending in .cache 182 | !*.[Cc]ache/ 183 | 184 | # Others 185 | ClientBin/ 186 | [Ss]tyle[Cc]op.* 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | [Tt]humbs.db 196 | 197 | # RIA/Silverlight projects 198 | Generated_Code/ 199 | 200 | # Backup & report files from converting an old project file 201 | # to a newer Visual Studio version. Backup files are not needed, 202 | # because we have git ;-) 203 | _UpgradeReport_Files/ 204 | Backup*/ 205 | UpgradeLog*.XML 206 | UpgradeLog*.htm 207 | 208 | # SQL Server files 209 | *.mdf 210 | *.ldf 211 | 212 | # Business Intelligence projects 213 | *.rdl.data 214 | *.bim.layout 215 | *.bim_*.settings 216 | 217 | # Microsoft Fakes 218 | FakesAssemblies/ 219 | 220 | # GhostDoc plugin setting file 221 | *.GhostDoc.xml 222 | 223 | # Node.js Tools for Visual Studio 224 | .ntvs_analysis.dat 225 | 226 | # Visual Studio 6 build log 227 | *.plg 228 | 229 | # Visual Studio 6 workspace options file 230 | *.opt 231 | 232 | # Visual Studio LightSwitch build output 233 | **/*.HTMLClient/GeneratedArtifacts 234 | **/*.DesktopClient/GeneratedArtifacts 235 | **/*.DesktopClient/ModelManifest.xml 236 | **/*.Server/GeneratedArtifacts 237 | **/*.Server/ModelManifest.xml 238 | _Pvt_Extensions 239 | 240 | # LightSwitch generated files 241 | GeneratedArtifacts/ 242 | ModelManifest.xml 243 | 244 | # Paket dependency manager 245 | .paket/paket.exe 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | #3DS 251 | *.elf 252 | *.cia 253 | *.3dsx 254 | *.map 255 | output/ 256 | romfs_installer/ 257 | -------------------------------------------------------------------------------- /source/png.c: -------------------------------------------------------------------------------- 1 | #include "draw.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define PNG_SIGSIZE (8) 8 | 9 | Result textureTile32(C3D_Tex *texture) 10 | { 11 | u8 *tmp; 12 | int i; 13 | int height; 14 | int width; 15 | u32 pixel; 16 | u32 size; 17 | 18 | height = (int)texture->height; 19 | width = (int)texture->width; 20 | tmp = linearAlloc(width * height * 4); 21 | if (!tmp) goto error; 22 | size = width * height * 4; 23 | for (i = 0; i < size; i += 4) 24 | { 25 | pixel = *(u32 *)(texture->data + i); 26 | *(u32 *)(tmp + i) = __builtin_bswap32(pixel); 27 | } 28 | GSPGPU_FlushDataCache(tmp, width * height * 4); 29 | GSPGPU_FlushDataCache(texture->data, width * height * 4); 30 | C3D_SyncDisplayTransfer((u32 *)tmp, GX_BUFFER_DIM(width, height), \ 31 | (u32*)texture->data, GX_BUFFER_DIM(width, height), TEXTURE_TRANSFER_FLAGS); 32 | linearFree(tmp); 33 | return (MAKERESULT(RL_SUCCESS, RS_SUCCESS, RM_COMMON, RD_SUCCESS)); 34 | error: 35 | return (MAKERESULT(RL_TEMPORARY, RS_OUTOFRESOURCE, RM_COMMON, RD_OUT_OF_MEMORY)); 36 | } 37 | 38 | static void readPNGFile(png_structp pngPtr, png_bytep data, png_size_t length) 39 | { 40 | FILE *file = (FILE *)png_get_io_ptr(pngPtr); 41 | fread(data, length, 1, file); 42 | } 43 | 44 | static Result loadPNGGeneric(sprite_t **out, const void *ioPtr) 45 | { 46 | png_structp pngPtr; 47 | png_infop infoPtr; 48 | png_bytep *rowPtrs; 49 | sprite_t *sprite; 50 | Result result; 51 | unsigned int width; 52 | unsigned int height; 53 | int bitDepth; 54 | int colorType; 55 | int stride; 56 | int i; 57 | 58 | rowPtrs = NULL; 59 | pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); 60 | if (pngPtr == NULL) 61 | { 62 | result = MAKERESULT(RL_PERMANENT, RS_INTERNAL, RM_APPLICATION, RD_INVALID_RESULT_VALUE); 63 | goto errorCreateRead; 64 | } 65 | infoPtr = png_create_info_struct(pngPtr); 66 | if (infoPtr == NULL) 67 | { 68 | result = MAKERESULT(RL_PERMANENT, RS_INTERNAL, RM_APPLICATION, RD_INVALID_RESULT_VALUE); 69 | goto errorCreateInfo; 70 | } 71 | if (setjmp(png_jmpbuf(pngPtr))) 72 | { 73 | png_destroy_read_struct(&pngPtr, &infoPtr, (png_infopp)0); 74 | if (rowPtrs != NULL) 75 | free(rowPtrs); 76 | result = MAKERESULT(RL_PERMANENT, RS_INTERNAL, RM_APPLICATION, RD_INVALID_RESULT_VALUE); 77 | return (result); 78 | } 79 | png_set_read_fn(pngPtr, (png_voidp)ioPtr, readPNGFile); 80 | png_set_sig_bytes(pngPtr, PNG_SIGSIZE); 81 | png_read_info(pngPtr, infoPtr); 82 | png_get_IHDR(pngPtr, infoPtr, &width, &height, &bitDepth, &colorType, NULL, NULL, NULL); 83 | if ((colorType == PNG_COLOR_TYPE_PALETTE && bitDepth <= 8) 84 | || (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) 85 | || png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS) 86 | || (bitDepth == 16)) 87 | { 88 | png_set_expand(pngPtr); 89 | } 90 | 91 | if (bitDepth == 16) png_set_scale_16(pngPtr); 92 | if (bitDepth == 8 && colorType == PNG_COLOR_TYPE_RGB) png_set_filler(pngPtr, 0xFF, PNG_FILLER_AFTER); 93 | if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) 94 | png_set_gray_to_rgb(pngPtr); 95 | if (colorType == PNG_COLOR_TYPE_PALETTE) 96 | { 97 | png_set_palette_to_rgb(pngPtr); 98 | png_set_filler(pngPtr, 0xFF, PNG_FILLER_AFTER); 99 | } 100 | if (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) png_set_expand_gray_1_2_4_to_8(pngPtr); 101 | if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(pngPtr); 102 | if (bitDepth < 8) png_set_packing(pngPtr); 103 | png_read_update_info(pngPtr, infoPtr); 104 | rowPtrs = (png_bytep *)malloc(sizeof(png_bytep) * height); 105 | if (!rowPtrs) 106 | { 107 | result = MAKERESULT(RL_PERMANENT, RS_OUTOFRESOURCE, RM_APPLICATION, RD_OUT_OF_MEMORY); 108 | goto errorAllocRows; 109 | } 110 | sprite = newSprite(width, height); 111 | if (!sprite) 112 | { 113 | result = MAKERESULT(RL_PERMANENT, RS_OUTOFRESOURCE, RM_APPLICATION, RD_OUT_OF_MEMORY); 114 | goto errorCreateSprite; 115 | } 116 | else 117 | *out = sprite; 118 | stride = sprite->texture.width * 4; 119 | 120 | for (i = 0; i < height; i++) 121 | { 122 | rowPtrs[i] = (png_bytep)(sprite->texture.data + i * stride); 123 | } 124 | png_read_image(pngPtr, rowPtrs); 125 | textureTile32(&sprite->texture); 126 | result = MAKERESULT(RL_SUCCESS, RS_SUCCESS, RM_APPLICATION, RD_SUCCESS); 127 | errorCreateSprite: 128 | free(rowPtrs); 129 | errorAllocRows: 130 | png_destroy_info_struct(pngPtr, &infoPtr); 131 | errorCreateInfo: 132 | png_destroy_read_struct(&pngPtr, (png_infopp)0, (png_infopp)0); 133 | errorCreateRead: 134 | return (result); 135 | } 136 | 137 | 138 | Result newSpriteFromPNG(sprite_t **out, const char *filename) 139 | { 140 | FILE *file; 141 | Result result; 142 | png_byte pngsig[PNG_SIGSIZE]; 143 | 144 | if (!(file = fopen(filename, "rb"))) 145 | { 146 | result = MAKERESULT(RL_PERMANENT, RS_NOTFOUND, RM_APPLICATION, RD_NOT_FOUND); 147 | goto exitError; 148 | } 149 | if (fread(pngsig, 1, PNG_SIGSIZE, file) != PNG_SIGSIZE) 150 | { 151 | result = MAKERESULT(RL_PERMANENT, RS_INVALIDARG, RM_APPLICATION, RD_INVALID_SIZE); 152 | goto exitClose; 153 | } 154 | if (png_sig_cmp(pngsig, 0, PNG_SIGSIZE) != 0) 155 | { 156 | result = MAKERESULT(RL_PERMANENT, RS_INVALIDARG, RM_APPLICATION, RD_INVALID_SELECTION); 157 | goto exitClose; 158 | } 159 | result = loadPNGGeneric(out, (void *)file); 160 | exitClose: 161 | fclose(file); 162 | exitError: 163 | return (result); 164 | } 165 | -------------------------------------------------------------------------------- /source/drawableObject.c: -------------------------------------------------------------------------------- 1 | #include "drawableObject.h" 2 | #include "draw.h" 3 | 4 | backgroundScreen_t *newBackgroundObject(sprite_t *background, \ 5 | sprite_t *header, sprite_t *footer) 6 | { 7 | backgroundScreen_t *ret; 8 | 9 | ret = (backgroundScreen_t *)calloc(1, sizeof(backgroundScreen_t)); 10 | if (!ret) goto error; 11 | 12 | if (background) ret->background = background; 13 | if (header) ret->headerText = header; 14 | if (footer) ret->footerText = footer; 15 | ret->draw = drawBackground; 16 | return (ret); 17 | error: 18 | return (NULL); 19 | } 20 | 21 | static bool drawableSpriteDraw(void* self) { 22 | if (((drawableSprite_t*)self)->sprite) { 23 | drawSprite(((drawableSprite_t*)self)->sprite); 24 | return true; 25 | } 26 | return false; 27 | } 28 | 29 | void initDrawableSprite(drawableSprite_t* object, sprite_t* sprite) { 30 | object->sprite = sprite; 31 | object->draw = drawableSpriteDraw; 32 | } 33 | 34 | bool drawBackground(void *self) 35 | { 36 | backgroundScreen_t *bg; 37 | 38 | if (!self) goto error; 39 | bg = (backgroundScreen_t *)self; 40 | drawSprite(bg->background); 41 | drawSprite(bg->headerText); 42 | drawSprite(bg->footerText); 43 | error: 44 | return (false); 45 | } 46 | 47 | void changeBackgroundHeader(backgroundScreen_t *bg, sprite_t *header) 48 | 49 | { 50 | if (!bg) goto error; 51 | bg->headerText = header; 52 | error: 53 | return; 54 | } 55 | 56 | void changeBackgroundFooter(backgroundScreen_t *bg, sprite_t *footer) 57 | { 58 | if (!bg) goto error; 59 | bg->footerText = footer; 60 | error: 61 | return; 62 | } 63 | drawableScreen_t *newDrawableScreen(backgroundScreen_t *background) 64 | { 65 | drawableScreen_t *ret; 66 | 67 | ret = (drawableScreen_t *)calloc(1, sizeof(drawableScreen_t)); 68 | if (!ret) goto error; 69 | if (background) ret->background = background; 70 | ret->draw = drawScreen; 71 | return (ret); 72 | error: 73 | return (NULL); 74 | } 75 | 76 | bool drawScreen(void *self) 77 | { 78 | drawableScreen_t *screen; 79 | drawableObject_t *obj; 80 | int i; 81 | 82 | if (!self) goto error; 83 | screen = (drawableScreen_t *)self; 84 | if (screen->background) 85 | screen->background->draw(screen->background); 86 | for (i = 0; i < MAX_ELEMENTS; i++) 87 | { 88 | obj = (drawableObject_t *)screen->elementList[i]; 89 | if (!obj) continue; 90 | obj->draw(obj); 91 | } 92 | return (true); 93 | error: 94 | return (false); 95 | } 96 | 97 | void setExTopObjectToScreen(drawableScreen_t *screen, void *object) 98 | { 99 | screen->elementList[MAX_ELEMENTS-1] = (int)object; 100 | return; 101 | } 102 | 103 | void addObjectToScreen(drawableScreen_t *screen, void *object) 104 | { 105 | if (!screen || !object || screen->elementsCount > MAX_ELEMENTS) goto error; 106 | screen->elementList[screen->elementsCount] = (int)object; 107 | screen->elementsCount++; 108 | error: 109 | return; 110 | } 111 | 112 | void *removeLastObjectFromScreen(drawableScreen_t *screen) 113 | { 114 | void *ret; 115 | if (!screen || !screen->elementsCount) goto error; 116 | ret = (void *)screen->elementList[screen->elementsCount - 1]; 117 | screen->elementList[screen->elementsCount - 1] = 0; 118 | screen->elementsCount--; 119 | return (ret); 120 | error: 121 | return (NULL); 122 | } 123 | 124 | void clearObjectListFromScreen(drawableScreen_t *screen) 125 | { 126 | void *ret; 127 | 128 | if (!screen) goto error; 129 | while (1) 130 | { 131 | ret = removeLastObjectFromScreen(screen); 132 | if (!ret) 133 | break; 134 | } 135 | error: 136 | return; 137 | } 138 | 139 | bool drawImage(void *self) 140 | { 141 | image_t *img; 142 | 143 | if (!self) goto error; 144 | img = (image_t *)self; 145 | drawSprite(img->sprite); 146 | return (true); 147 | error: 148 | return (false); 149 | } 150 | 151 | window_t *newWindow(sprite_t *background, sprite_t *title, \ 152 | sprite_t *content) 153 | { 154 | window_t *window; 155 | 156 | window = (window_t *)calloc(1, sizeof(window_t)); 157 | if (!window) goto error; 158 | if (background) window->background = background; 159 | if (title) window->title = title; 160 | if (content) window->content = content; 161 | window->draw = drawWindow; 162 | return (window); 163 | error: 164 | return (NULL); 165 | } 166 | 167 | bool drawWindow(void *self) 168 | { 169 | window_t *window; 170 | 171 | if (!self) goto error; 172 | window = (window_t *)self; 173 | if (window->background) drawSprite(window->background); 174 | if (window->title) drawSprite(window->title); 175 | if (window->content) drawSprite(window->content); 176 | return (true); 177 | error: 178 | return (false); 179 | } 180 | 181 | void changeWindowContent(window_t *window, sprite_t *content) 182 | { 183 | if (!window) goto error; 184 | window->content = content; 185 | error: 186 | return; 187 | } 188 | 189 | void changeWindowTitle(window_t *window, sprite_t *title) 190 | { 191 | if (!window) goto error; 192 | window->title = title; 193 | error: 194 | return; 195 | } 196 | 197 | text_t *newText(char *str, float posX, float posY, float scaleX, float scaleY, int color) 198 | { 199 | text_t *ret; 200 | 201 | ret = (text_t *)calloc(1, sizeof(text_t)); 202 | if (!ret) goto error; 203 | ret->str = str; 204 | ret->posX = posX; 205 | ret->posY = posY; 206 | ret->scaleX = scaleX; 207 | ret->scaleY = scaleY; 208 | ret->color = color; 209 | ret->visible = false; 210 | ret->draw = drawTextObject; 211 | return (ret); 212 | error: 213 | return (NULL); 214 | } 215 | 216 | bool drawTextObject(void *self) 217 | { 218 | text_t *t; 219 | 220 | if (!self) goto error; 221 | t = (text_t *)self; 222 | if (!t->str || !t->visible) goto error; 223 | setTextColor(t->color); 224 | renderText(t->posX, t->posY, t->scaleX, t->scaleY, false, t->str, NULL, 0.0f); 225 | return (true); 226 | error: 227 | return (false); 228 | } 229 | 230 | void hideText(text_t *text) 231 | { 232 | if (text) 233 | text->visible = false; 234 | } 235 | 236 | void showText(text_t *text) 237 | { 238 | if (text) 239 | text->visible = true; 240 | } 241 | 242 | bool drawRectangleObject(void* self) { 243 | if (!self) return false; 244 | drawRectangle((rectangle_t*)self); 245 | return true; 246 | } 247 | 248 | void deleteRectangle(rectangle_t* rec) { 249 | if (!rec) return; 250 | deleteSprite(rec->sprite); 251 | free(rec); 252 | rec = NULL; 253 | } 254 | 255 | rectangle_t *newRectangle(float posX, float posY, float width, float height, float initialamount, sprite_t* sprite) { 256 | rectangle_t* ret; 257 | ret = (rectangle_t *)calloc(1, sizeof(rectangle_t)); 258 | if (!ret) goto error; 259 | if (initialamount < 0) initialamount = 0; 260 | if (initialamount > 1) initialamount = 1; 261 | ret->amount = initialamount; 262 | ret->sprite = sprite; 263 | ret->posX = posX; 264 | ret->posY = posY; 265 | ret->height = height; 266 | ret->width = width; 267 | ret->draw = drawRectangleObject; 268 | return ret; 269 | error: 270 | return NULL; 271 | } 272 | -------------------------------------------------------------------------------- /source/main.c: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | #include "draw.h" 3 | #include 4 | #include "Unicode.h" 5 | 6 | bool g_exit = false; 7 | bool restartneeded = false; 8 | extern sprite_t* topInfoSprite; 9 | 10 | aptHookCookie aptCookie; 11 | 12 | bool checkRunningUnsupported() { 13 | s64 out = 0; 14 | svcGetSystemInfo(&out, 0x10000, 0); 15 | return GET_VERSION_MAJOR(out) <= 8; 16 | } 17 | 18 | u8 firmLaunchParams[0x1000]; 19 | bool isReboot() { 20 | Result res = pmAppInit(); 21 | if (R_SUCCEEDED(res)) { 22 | res = PMAPP_GetFIRMLaunchParams(firmLaunchParams, sizeof(firmLaunchParams)); 23 | pmAppExit(); 24 | if (R_SUCCEEDED(res)) { 25 | u64 mytid = 0x000400000ECB9500; 26 | return memcmp(firmLaunchParams + 0x440, &mytid, sizeof(mytid)) == 0; 27 | } 28 | } 29 | return false; 30 | } 31 | 32 | int main() 33 | { 34 | gfxInitDefault(); 35 | romfsInit(); 36 | ptmSysmInit(); 37 | drawInit(); 38 | 39 | initUI(); 40 | bool continueInstall = true; 41 | bool rebootintoitself = false; 42 | bool totalreboot = false; 43 | bool unsupported = checkRunningUnsupported(); 44 | clearTop(); 45 | if (isReboot()) { 46 | clearTop(); 47 | newAppTop(DEFAULT_COLOR, MEDIUM | BOLD | CENTER, "EzB9SUpdater"); 48 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "You should have returned from"); 49 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "SafeB9SInstaller. If that wasn't the"); 50 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "case, you probably released the START"); 51 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "button too early. If you installed"); 52 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "B9S properly you can exit this app."); 53 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Having issues? Ask here:"); 54 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "https://discord.gg/C29hYvh"); 55 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "\nHold START: Launch SafeB9SInstaller"); 56 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, FONT_B": Exit"); 57 | u32 keys = 0; 58 | bool warningloop = true; 59 | while (warningloop && aptMainLoop()) 60 | { 61 | if (keys & KEY_B) { 62 | warningloop = false; 63 | totalreboot = true; 64 | ezB9SCleanup(); 65 | } 66 | if (keys & KEY_START) { 67 | warningloop = false; 68 | rebootintoitself = true; 69 | } 70 | updateUI(); 71 | keys = hidKeysDown(); 72 | } 73 | } else { 74 | if (unsupported) { 75 | clearTop(); 76 | newAppTop(COLOR_RED, MEDIUM | BOLD | CENTER, "Fatal Error"); 77 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Unsupported environment."); 78 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Very outdated custom firmware"); 79 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "or Citra detected. Please ask"); 80 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "for help in the Nintendo"); 81 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Homebrew discord server:"); 82 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "https://discord.gg/C29hYvh"); 83 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "\n"FONT_B": Exit"); 84 | u32 keys = 0; 85 | bool warningloop = true; 86 | while (warningloop && aptMainLoop()) 87 | { 88 | if (keys & KEY_B) { 89 | warningloop = false; 90 | continueInstall = false; 91 | } 92 | updateUI(); 93 | keys = hidKeysDown(); 94 | } 95 | } 96 | if (continueInstall && !aptShouldClose()) { 97 | clearTop(); 98 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "EzB9SUpdater"); 99 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Use this tool to update"); 100 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "B9S to the latest version."); 101 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Running this tool with the"); 102 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "latest version already installed"); 103 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "has no effect, so feel free to try"); 104 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "to update it anyways.\n"); 105 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, FONT_A": Proceed"); 106 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, FONT_B": Exit"); 107 | u32 keys = 0; 108 | bool installLoop = true; 109 | while (installLoop && aptMainLoop()) { 110 | if ((keys & KEY_A)) { 111 | CURL_lastErrorCode[0] = '\0'; 112 | u64 ret = ezB9SPerform(); 113 | u32 retlow = (u32)ret; 114 | u32 rethigh = (u32)(ret >> 32); 115 | clearTop(); 116 | if (!rethigh) { 117 | 118 | newAppTop(COLOR_GREEN, BOLD | MEDIUM | CENTER, "Download successful!"); 119 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "You will now reboot into"); 120 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "SafeB9SInstaller to complete"); 121 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "the update procedure."); 122 | updateUI(); 123 | svcSleepThread(10000000000); 124 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "\nPress and hold START until you"); 125 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "see the SafeB9SInstaller menu and"); 126 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "follow the instructions. Don't release"); 127 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "the START button until you see"); 128 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "SafeB9SInstaller. Do not power off"); 129 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "the device during the installation."); 130 | } 131 | else 132 | { 133 | if (rethigh == 1) { 134 | newAppTop(COLOR_RED, BOLD | MEDIUM | CENTER, "Download failed!"); 135 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Unable to connect to the internet,"); 136 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "please try again. If this problem"); 137 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "keeps happening look for an updated"); 138 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "version of this app."); 139 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "\nYou can ask for help here"); 140 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "https://discord.gg/C29hYvh\n"); 141 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, FONT_B": Exit"); 142 | } else if (rethigh == 4) { 143 | newAppTop(COLOR_RED, BOLD | MEDIUM | CENTER, "Download failed!"); 144 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "The author of this app has marked"); 145 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "it as \"obsolete\". Please look"); 146 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "for an updated version of this app."); 147 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "\nYou can ask for help here"); 148 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "https://discord.gg/C29hYvh\n"); 149 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, FONT_B": Exit"); 150 | } else { 151 | newAppTop(COLOR_RED, BOLD | MEDIUM | CENTER, "Download failed!"); 152 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "An error has occurred:"); 153 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "%08X %08X", rethigh, retlow); 154 | if (CURL_lastErrorCode[0]) 155 | newAppTopMultiline(DEFAULT_COLOR, SMALL | CENTER, CURL_lastErrorCode); 156 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "\nYou can ask for help here"); 157 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "https://discord.gg/C29hYvh\n"); 158 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, FONT_B": Exit"); 159 | } 160 | } 161 | u32 keys2 = 0; 162 | bool installLoop2 = true; 163 | while (installLoop2 && aptMainLoop()) 164 | { 165 | if ((rethigh && (keys2 & KEY_B)) || (!rethigh && (keys2 & KEY_START))) { 166 | installLoop2 = false; 167 | if (!rethigh && (keys2 & KEY_START)) 168 | rebootintoitself = true; 169 | } 170 | updateUI(); 171 | keys2 = hidKeysDown(); 172 | } 173 | installLoop = false; 174 | } 175 | if (keys & KEY_B) { 176 | installLoop = false; 177 | } 178 | updateUI(); 179 | keys = hidKeysDown(); 180 | } 181 | } 182 | } 183 | 184 | greyExit(); 185 | updateUI(); 186 | svcSleepThread(500000000); 187 | 188 | exitUI(); 189 | drawExit(); 190 | httpcExit(); 191 | romfsExit(); 192 | 193 | gfxExit(); 194 | ptmSysmExit(); 195 | if (rebootintoitself) { 196 | nsInit(); 197 | NS_RebootToTitle(MEDIATYPE_SD, 0x000400000ECB9500); 198 | for(;;); 199 | } 200 | if (totalreboot) { 201 | svcKernelSetState(7); 202 | for(;;); 203 | } 204 | return (0); 205 | } -------------------------------------------------------------------------------- /source/appInfo.c: -------------------------------------------------------------------------------- 1 | #include "appInfo.h" 2 | #include "graphics.h" 3 | 4 | static bool showBackground = true; 5 | extern appInfoObject_t *appTop; 6 | 7 | void appInfoHideBackground(void) 8 | { 9 | showBackground = false; 10 | } 11 | 12 | void appInfoShowBackground(void) 13 | { 14 | showBackground = true; 15 | } 16 | 17 | appInfoObject_t *newAppInfoObject(sprite_t *sprite, u32 maxEntryCount, u32 posX, u32 posY) 18 | { 19 | appInfoObject_t *object; 20 | 21 | if (!sprite) goto error; 22 | 23 | object = (appInfoObject_t *)calloc(1, sizeof(appInfoObject_t)); 24 | if (!object) goto error; 25 | object->entryList = (u32 *)calloc(maxEntryCount, sizeof(u32 *)); 26 | if (!object->entryList) goto allocError; 27 | object->sprite = sprite; 28 | object->spritePosX = sprite->posX; 29 | object->spritePosY = sprite->posY; 30 | object->maxEntryCount = maxEntryCount; 31 | object->entryCount = 0; 32 | object->cursor.posX = (float)posX; 33 | object->cursor.posY = (float)posY; 34 | object->boundX = 0; 35 | object->boundY = 0; 36 | return (object); 37 | allocError: 38 | free(object); 39 | error: 40 | return (NULL); 41 | } 42 | 43 | void deleteAppInfoObject(appInfoObject_t *object) 44 | { 45 | if (!object) return; 46 | free(object->entryList); 47 | free(object); 48 | } 49 | 50 | void appInfoSetTextBoundaries(appInfoObject_t *object, float posX, float posY) 51 | { 52 | 53 | if (!object) return; 54 | object->boundX = posX; 55 | object->boundY = posY; 56 | } 57 | 58 | void appInfoSetSpritePosition(appInfoObject_t *object, float posX, float posY) 59 | { 60 | if (!object) return; 61 | object->spritePosX = posX; 62 | object->spritePosY = posY; 63 | } 64 | 65 | static void scrollDown(appInfoObject_t *object) 66 | { 67 | appInfoEntry_t *entry; 68 | int index; 69 | u32 entryCount; 70 | u32 *entryList; 71 | 72 | if (!object) goto exit; 73 | entryCount = object->entryCount; 74 | if (entryCount <= 0) goto exit; 75 | entryList = object->entryList; 76 | entry = (appInfoEntry_t *)entryList[0]; 77 | free(entry); 78 | entryCount--; 79 | for (index = 0; index < entryCount; index++) 80 | { 81 | entryList[index] = entryList[index + 1]; 82 | } 83 | entryList[index] = 0; 84 | object->entryCount = entryCount; 85 | exit: 86 | return; 87 | } 88 | 89 | void newAppInfoEntry(appInfoObject_t *object, u32 color, u32 flags, char *text, ...) 90 | { 91 | u32 entryCount; 92 | u32 *entryList; 93 | appInfoEntry_t *entry; 94 | va_list vaList; 95 | 96 | if (!text || !object) goto exit; 97 | if (flags & SCROLL) 98 | { 99 | scrollDown(object); 100 | if (flags & NEWLINE) 101 | scrollDown(object); 102 | } 103 | entryCount = object->entryCount; 104 | entryList = object->entryList; 105 | if (entryCount >= object->maxEntryCount) 106 | { 107 | scrollDown(object); 108 | entryCount = object->entryCount; 109 | } 110 | entry = (appInfoEntry_t *)calloc(1, sizeof(appInfoEntry_t)); 111 | if (!entry) goto exit; 112 | va_start(vaList, text); 113 | vsnprintf(entry->buffer, BUFFER_SIZE, text, vaList); 114 | va_end(vaList); 115 | entry->color = color; 116 | entry->flags = flags; 117 | entryList[entryCount] = (u32)entry; 118 | object->entryCount++; 119 | exit: 120 | return; 121 | } 122 | 123 | static void deleteLastEntry(appInfoObject_t *object) 124 | { 125 | u32 entryCount; 126 | appInfoEntry_t *entry; 127 | 128 | if (!object) goto exit; 129 | entryCount = object->entryCount; 130 | if (entryCount <= 0) goto exit; 131 | entryCount--; 132 | entry = (appInfoEntry_t *)object->entryList[entryCount]; 133 | object->entryList[entryCount] = 0; 134 | free(entry); 135 | object->entryCount = entryCount; 136 | exit: 137 | return; 138 | 139 | } 140 | 141 | void removeAppInfoEntry(appInfoObject_t *object) 142 | { 143 | deleteLastEntry(object); 144 | } 145 | 146 | void clearAppInfo(appInfoObject_t *object) 147 | { 148 | u32 entryCount; 149 | int i; 150 | 151 | entryCount = object->entryCount; 152 | for (i = entryCount; i > 0; i--) 153 | deleteLastEntry(object); 154 | } 155 | 156 | void drawMultilineText(u32 color, u32 flags, char* txt) { 157 | float textWidth; 158 | float totalWidth = appTop->boundX - appTop->cursor.posX; 159 | float scaleX, scaleY; 160 | //Set the font size 161 | if (flags & BIG) scaleX = scaleY = 0.6f; 162 | else if (flags & MEDIUM) scaleX = scaleY = 0.55f; 163 | else if (flags & SMALL) scaleX = scaleY = 0.45f; 164 | else if (flags & TINY) scaleX = scaleY = 0.4f; 165 | else scaleX = scaleY = 0.5f; 166 | 167 | int textLen = strlen(txt) + 1; 168 | char* copy = malloc(textLen); 169 | char* copyCurr = copy; 170 | memset(copy, 0, textLen); 171 | char* breakpos = copy; 172 | char* txtCurr = txt; 173 | while (*txtCurr != '\0') { 174 | *copyCurr = *txtCurr; 175 | if (*copyCurr == ' ') breakpos = copyCurr; 176 | getTextSizeInfos(&textWidth, scaleX, scaleY, copy); 177 | if (textWidth >= totalWidth) { 178 | if (breakpos == copy) { 179 | *(copyCurr - 1) = '\0'; 180 | newAppTop(color, flags, copy); 181 | memset(copy, 0, textLen); 182 | copyCurr = copy; 183 | breakpos = copy; 184 | txtCurr--; 185 | } 186 | else { 187 | *breakpos = '\0'; 188 | newAppTop(color, flags, copy); 189 | memset(copy, 0, textLen); 190 | txtCurr = (txtCurr - (copyCurr - breakpos)) + 1; 191 | copyCurr = copy; 192 | breakpos = copy; 193 | } 194 | } 195 | else { 196 | copyCurr++; 197 | txtCurr++; 198 | } 199 | } 200 | if (copy != copyCurr) { 201 | newAppTop(color, flags, copy); 202 | } 203 | free(copy); 204 | } 205 | 206 | static void getDrawParameters(appInfoObject_t *object, int index, float *sizeX, float *sizeY) 207 | { 208 | appInfoEntry_t *entry; 209 | float textWidth; 210 | float scaleX; 211 | float scaleY; 212 | float temp; 213 | u32 flags; 214 | cursor_t *cursor; 215 | 216 | if (!object || !sizeX || !sizeY) return; 217 | entry = (appInfoEntry_t *)object->entryList[index]; 218 | flags = entry->flags; 219 | cursor = &object->cursor; 220 | 221 | //Set the font size 222 | if (flags & BIG) scaleX = scaleY = 0.6f; 223 | else if (flags & MEDIUM) scaleX = scaleY = 0.55f; 224 | else if (flags & SMALL) scaleX = scaleY = 0.45f; 225 | else if (flags & TINY) scaleX = scaleY = 0.4f; 226 | 227 | else scaleX = scaleY = 0.5f; 228 | 229 | //Set the type 230 | if (flags & BOLD) scaleX += 0.05f; 231 | else if (flags & SKINNY) scaleY += 0.05f; 232 | 233 | //Set the alignment 234 | getTextSizeInfos(&textWidth, scaleX, scaleY, entry->buffer); 235 | if (flags & CENTER) 236 | { 237 | temp = object->boundX - cursor->posX; 238 | temp -= textWidth; 239 | if (temp > 0) 240 | { 241 | temp /= 2; 242 | cursor->posX += temp; 243 | } 244 | } 245 | if (flags & RIGHT_ALIGN) 246 | { 247 | cursor->posX = 297.0f; 248 | cursor->posX -= textWidth; 249 | } 250 | 251 | if (flags & NEWLINE) 252 | cursor->posY += 0.3f * fontGetInfo(NULL)->lineFeed; 253 | 254 | //Return the size 255 | *sizeX = scaleX; 256 | *sizeY = scaleY; 257 | } 258 | void drawAppInfoEntry(appInfoObject_t *object, int index) 259 | { 260 | float sizeX; 261 | float sizeY; 262 | float lineFeed; 263 | appInfoEntry_t *entry; 264 | cursor_t *cursor; 265 | 266 | if (!object || index >= object->entryCount) goto exit; 267 | entry = (appInfoEntry_t *)object->entryList[index]; 268 | cursor = &object->cursor; 269 | sizeX = sizeY = 0.0f; 270 | getDrawParameters(object, index, &sizeX, &sizeY); 271 | lineFeed = sizeY * fontGetInfo(NULL)->lineFeed; 272 | setTextColor(entry->color); 273 | renderText(cursor->posX, cursor->posY, sizeX, sizeY, false, entry->buffer, cursor, 0.0f); 274 | cursor->posY += lineFeed; 275 | exit: 276 | return; 277 | } 278 | 279 | void drawAppInfo(appInfoObject_t *object) 280 | { 281 | int i; 282 | u32 entryCount; 283 | float boundY; 284 | float cursorXBak; 285 | float cursorYBak; 286 | cursor_t *cursor; 287 | 288 | if (!object) return; 289 | entryCount = object->entryCount; 290 | if (entryCount <= 0) return; 291 | boundY = object->boundY; 292 | cursor = &object->cursor; 293 | cursorXBak = cursor->posX; 294 | cursorYBak = cursor->posY; 295 | setSpritePos(object->sprite, object->spritePosX, object->spritePosY); 296 | if (showBackground) 297 | drawSprite(object->sprite); 298 | for (i = 0; i < entryCount; i++) 299 | { 300 | if (cursor->posY >= boundY) break; 301 | cursor->posX = cursorXBak; 302 | drawAppInfoEntry(object, i); 303 | } 304 | cursor->posX = cursorXBak; 305 | cursor->posY = cursorYBak; 306 | } -------------------------------------------------------------------------------- /source/csvc.h: -------------------------------------------------------------------------------- 1 | /* This paricular file is licensed under the following terms: */ 2 | 3 | /* 4 | * This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable 5 | * for any damages arising from the use of this software. 6 | * 7 | * Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it 8 | * and redistribute it freely, subject to the following restrictions: 9 | * 10 | * The origin of this software must not be misrepresented; you must not claim that you wrote the original software. 11 | * If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 12 | * 13 | * Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 14 | * This notice may not be removed or altered from any source distribution. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include <3ds/types.h> 20 | 21 | /// Operations for svcControlService 22 | typedef enum ServiceOp 23 | { 24 | SERVICEOP_STEAL_CLIENT_SESSION = 0, ///< Steal a client session given a service or global port name 25 | SERVICEOP_GET_NAME, ///< Get the name of a service or global port given a client or session handle 26 | } ServiceOp; 27 | 28 | /** 29 | * @brief Executes a function in supervisor mode, using the supervisor-mode stack. 30 | * @param func Function to execute. 31 | * @param ... Function parameters, up to 3 registers. 32 | */ 33 | Result svcCustomBackdoor(void *func, ...); 34 | 35 | ///@name I/O 36 | ///@{ 37 | /** 38 | * @brief Gives the physical address corresponding to a virtual address. 39 | * @param VA Virtual address. 40 | * @param writeCheck whether to check if the VA is writable in supervisor mode 41 | * @return The corresponding physical address, or NULL. 42 | */ 43 | u32 svcConvertVAToPA(const void *VA, bool writeCheck); 44 | 45 | /** 46 | * @brief Flushes a range of the data cache (L2C included). 47 | * @param addr Start address. 48 | * @param len Length of the range. 49 | */ 50 | void svcFlushDataCacheRange(void *addr, u32 len); 51 | 52 | /** 53 | * @brief Flushes the data cache entirely (L2C included). 54 | */ 55 | void svcFlushEntireDataCache(void); 56 | 57 | /** 58 | * @brief Invalidates a range of the instruction cache. 59 | * @param addr Start address. 60 | * @param len Length of the range. 61 | */ 62 | void svcInvalidateInstructionCacheRange(void *addr, u32 len); 63 | 64 | /** 65 | * @brief Invalidates the data cache entirely. 66 | */ 67 | void svcInvalidateEntireInstructionCache(void); 68 | ///@} 69 | 70 | ///@name Memory management 71 | ///@{ 72 | /** 73 | * @brief Maps a block of process memory. 74 | * @param dstProcessHandle Handle of the process to map the memory in (destination) 75 | * @param destAddress Start address of the memory block in the destination process 76 | * @param srcProcessHandle Handle of the process to map the memory from (source) 77 | * @param srcAddress Start address of the memory block in the source process 78 | * @param size Size of the block of the memory to map (truncated to a multiple of 0x1000 bytes) 79 | */ 80 | Result svcMapProcessMemoryEx(Handle dstProcessHandle, u32 destAddress, Handle srcProcessHandle, u32 srcAddress, u32 size); 81 | 82 | /** 83 | * @brief Unmaps a block of process memory. 84 | * @param process Handle of the process to unmap the memory from 85 | * @param destAddress Address of the block of memory to unmap 86 | * @param size Size of the block of memory to unmap (truncated to a multiple of 0x1000 bytes). 87 | * This function should only be used to unmap memory mapped with svcMapProcessMemoryEx 88 | */ 89 | Result svcUnmapProcessMemoryEx(Handle process, u32 destAddress, u32 size); 90 | 91 | /** 92 | * @brief Controls memory mapping, with the choice to use region attributes or not. 93 | * @param[out] addr_out The virtual address resulting from the operation. Usually the same as addr0. 94 | * @param addr0 The virtual address to be used for the operation. 95 | * @param addr1 The virtual address to be (un)mirrored by @p addr0 when using @ref MEMOP_MAP or @ref MEMOP_UNMAP. 96 | * It has to be pointing to a RW memory. 97 | * Use NULL if the operation is @ref MEMOP_FREE or @ref MEMOP_ALLOC. 98 | * @param size The requested size for @ref MEMOP_ALLOC and @ref MEMOP_ALLOC_LINEAR. 99 | * @param op Operation flags. See @ref MemOp. 100 | * @param perm A combination of @ref MEMPERM_READ and @ref MEMPERM_WRITE. Using MEMPERM_EXECUTE will return an error. 101 | * Value 0 is used when unmapping memory. 102 | * @param isLoader Whether to use the region attributes 103 | * If a memory is mapped for two or more addresses, you have to use MEMOP_UNMAP before being able to MEMOP_FREE it. 104 | * MEMOP_MAP will fail if @p addr1 was already mapped to another address. 105 | * 106 | * @sa svcControlMemory 107 | */ 108 | Result svcControlMemoryEx(u32* addr_out, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader); 109 | 110 | /** 111 | * @brief Controls memory mapping, this version removes all checks which were being done 112 | * The only operations supported are MEMOP_FREE, MEMOP_ALLOC and MEMOP_ALLOC_LINEAR 113 | * All memory allocated with this svc, must be freed with this svc as well 114 | * @param[out] addr_out The virtual address resulting from the operation. Usually the same as addr0. 115 | * @param addr0 The virtual address to be used for the operation. 116 | * @param size The requested size for @ref MEMOP_ALLOC and @ref MEMOP_ALLOC_LINEAR. 117 | * @param op Operation flags. See @ref MemOp. 118 | * @param perm A combination of @ref MEMPERM_READ and @ref MEMPERM_WRITE 119 | * Value 0 is used when unmapping memory. 120 | * @sa svcControlMemory 121 | */ 122 | Result svcControlMemoryUnsafe(u32 *out, u32 addr0, u32 size, MemOp op, MemPerm perm); 123 | ///@} 124 | 125 | ///@name System 126 | ///@{ 127 | /** 128 | * @brief Performs actions related to services or global handles. 129 | * @param op The operation to perform, see @ref ServiceOp. 130 | * 131 | * Examples: 132 | * svcControlService(SERVICEOP_GET_NAME, (char [12])outName, (Handle)clientOrSessionHandle); 133 | * svcControlService(SERVICEOP_STEAL_CLIENT_SESSION, (Handle *)&outHandle, (const char *)name); 134 | */ 135 | Result svcControlService(ServiceOp op, ...); 136 | 137 | /** 138 | * @brief Copy a handle from a process to another one. 139 | * @param[out] out The output handle. 140 | * @param outProcess Handle of the process of the output handle. 141 | * @param in The input handle. Pseudo-handles are not accepted. 142 | * @param inProcess Handle of the process of the input handle. 143 | */ 144 | Result svcCopyHandle(Handle *out, Handle outProcess, Handle in, Handle inProcess); 145 | 146 | /** 147 | * @brief Get the address and class name of the underlying kernel object corresponding to a handle. 148 | * @param[out] outKAddr The output kernel address. 149 | * @param[out] outName Output class name. The buffer should be large enough to contain it. 150 | * @param in The input handle. 151 | */ 152 | Result svcTranslateHandle(u32 *outKAddr, char *outClassName, Handle in); 153 | 154 | /// Operations for svcControlProcess 155 | typedef enum ProcessOp 156 | { 157 | PROCESSOP_GET_ALL_HANDLES, ///< List all handles of the process, varg3 can be either 0 to fetch all handles, or token of the type to fetch 158 | ///< s32 count = svcControlProcess(handle, PROCESSOP_GET_ALL_HANDLES, (u32)&outBuf, 0) 159 | ///< Returns how many handles were found 160 | 161 | PROCESSOP_SET_MMU_TO_RWX, ///< Set the whole memory of the process with rwx access (in the mmu table only) 162 | ///< svcControlProcess(handle, PROCESSOP_SET_MMU_TO_RWX, 0, 0) 163 | 164 | PROCESSOP_GET_ON_MEMORY_CHANGE_EVENT, ///< Get the handle of an event which will be signaled each time the memory layout of this process changes 165 | ///< svcControlProcess(handle, PROCESSOP_GET_ON_MEMORY_CHANGE_EVENT, &eventHandleOut, 0) 166 | 167 | PROCESSOP_SIGNAL_ON_EXIT, ///< Set a flag to be signaled when the process will be exited 168 | ///< svcControlProcess(handle, PROCESSOP_SIGNAL_ON_EXIT, 0, 0) 169 | PROCESSOP_GET_PA_FROM_VA, ///< Get the physical address of the VAddr within the process 170 | ///< svcControlProcess(handle, PROCESSOP_GET_PA_FROM_VA, (u32)&PAOut, VAddr) 171 | 172 | PROCESSOP_SCHEDULE_THREADS, ///< Lock / Unlock the process's threads 173 | ///< svcControlProcess(handle, PROCESSOP_SCHEDULE_THREADS, lock, threadPredicate) 174 | ///< lock: 0 to unlock threads, any other value to lock threads 175 | ///< threadPredicate: can be NULL or a funcptr to a predicate (typedef bool (*ThreadPredicate)(KThread *thread);) 176 | ///< The predicate must return true to operate on the thread 177 | } ProcessOp; 178 | 179 | Result svcControlProcess(Handle process, ProcessOp op, u32 varg2, u32 varg3); 180 | ///@} 181 | 182 | -------------------------------------------------------------------------------- /source/parson.h: -------------------------------------------------------------------------------- 1 | /* 2 | SPDX-License-Identifier: MIT 3 | 4 | Parson 1.4.0 (https://github.com/kgabis/parson) 5 | Copyright (c) 2012 - 2022 Krzysztof Gabis 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in 15 | all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | THE SOFTWARE. 24 | */ 25 | 26 | #ifndef parson_parson_h 27 | #define parson_parson_h 28 | 29 | #ifdef __cplusplus 30 | extern "C" 31 | { 32 | #endif 33 | #if 0 34 | } /* unconfuse xcode */ 35 | #endif 36 | 37 | #define PARSON_VERSION_MAJOR 1 38 | #define PARSON_VERSION_MINOR 4 39 | #define PARSON_VERSION_PATCH 0 40 | 41 | #define PARSON_VERSION_STRING "1.4.0" 42 | 43 | #include /* size_t */ 44 | 45 | /* Types and enums */ 46 | typedef struct json_object_t JSON_Object; 47 | typedef struct json_array_t JSON_Array; 48 | typedef struct json_value_t JSON_Value; 49 | 50 | enum json_value_type { 51 | JSONError = -1, 52 | JSONNull = 1, 53 | JSONString = 2, 54 | JSONNumber = 3, 55 | JSONObject = 4, 56 | JSONArray = 5, 57 | JSONBoolean = 6 58 | }; 59 | typedef int JSON_Value_Type; 60 | 61 | enum json_result_t { 62 | JSONSuccess = 0, 63 | JSONFailure = -1 64 | }; 65 | typedef int JSON_Status; 66 | 67 | typedef void * (*JSON_Malloc_Function)(size_t); 68 | typedef void (*JSON_Free_Function)(void *); 69 | 70 | /* Call only once, before calling any other function from parson API. If not called, malloc and free 71 | from stdlib will be used for all allocations */ 72 | void json_set_allocation_functions(JSON_Malloc_Function malloc_fun, JSON_Free_Function free_fun); 73 | 74 | /* Sets if slashes should be escaped or not when serializing JSON. By default slashes are escaped. 75 | This function sets a global setting and is not thread safe. */ 76 | void json_set_escape_slashes(int escape_slashes); 77 | 78 | /* Sets float format used for serialization of numbers. 79 | Make sure it can't serialize to a string longer than PARSON_NUM_BUF_SIZE. 80 | If format is null then the default format is used. */ 81 | void json_set_float_serialization_format(const char *format); 82 | 83 | /* Parses first JSON value in a file, returns NULL in case of error */ 84 | JSON_Value * json_parse_file(const char *filename); 85 | 86 | /* Parses first JSON value in a file and ignores comments (/ * * / and //), 87 | returns NULL in case of error */ 88 | JSON_Value * json_parse_file_with_comments(const char *filename); 89 | 90 | /* Parses first JSON value in a string, returns NULL in case of error */ 91 | JSON_Value * json_parse_string(const char *string); 92 | 93 | /* Parses first JSON value in a string and ignores comments (/ * * / and //), 94 | returns NULL in case of error */ 95 | JSON_Value * json_parse_string_with_comments(const char *string); 96 | 97 | /* Serialization */ 98 | size_t json_serialization_size(const JSON_Value *value); /* returns 0 on fail */ 99 | JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes); 100 | JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename); 101 | char * json_serialize_to_string(const JSON_Value *value); 102 | 103 | /* Pretty serialization */ 104 | size_t json_serialization_size_pretty(const JSON_Value *value); /* returns 0 on fail */ 105 | JSON_Status json_serialize_to_buffer_pretty(const JSON_Value *value, char *buf, size_t buf_size_in_bytes); 106 | JSON_Status json_serialize_to_file_pretty(const JSON_Value *value, const char *filename); 107 | char * json_serialize_to_string_pretty(const JSON_Value *value); 108 | 109 | void json_free_serialized_string(char *string); /* frees string from json_serialize_to_string and json_serialize_to_string_pretty */ 110 | 111 | /* Comparing */ 112 | int json_value_equals(const JSON_Value *a, const JSON_Value *b); 113 | 114 | /* Validation 115 | This is *NOT* JSON Schema. It validates json by checking if object have identically 116 | named fields with matching types. 117 | For example schema {"name":"", "age":0} will validate 118 | {"name":"Joe", "age":25} and {"name":"Joe", "age":25, "gender":"m"}, 119 | but not {"name":"Joe"} or {"name":"Joe", "age":"Cucumber"}. 120 | In case of arrays, only first value in schema is checked against all values in tested array. 121 | Empty objects ({}) validate all objects, empty arrays ([]) validate all arrays, 122 | null validates values of every type. 123 | */ 124 | JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value); 125 | 126 | /* 127 | * JSON Object 128 | */ 129 | JSON_Value * json_object_get_value (const JSON_Object *object, const char *name); 130 | const char * json_object_get_string (const JSON_Object *object, const char *name); 131 | size_t json_object_get_string_len(const JSON_Object *object, const char *name); /* doesn't account for last null character */ 132 | JSON_Object * json_object_get_object (const JSON_Object *object, const char *name); 133 | JSON_Array * json_object_get_array (const JSON_Object *object, const char *name); 134 | double json_object_get_number (const JSON_Object *object, const char *name); /* returns 0 on fail */ 135 | int json_object_get_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */ 136 | 137 | /* dotget functions enable addressing values with dot notation in nested objects, 138 | just like in structs or c++/java/c# objects (e.g. objectA.objectB.value). 139 | Because valid names in JSON can contain dots, some values may be inaccessible 140 | this way. */ 141 | JSON_Value * json_object_dotget_value (const JSON_Object *object, const char *name); 142 | const char * json_object_dotget_string (const JSON_Object *object, const char *name); 143 | size_t json_object_dotget_string_len(const JSON_Object *object, const char *name); /* doesn't account for last null character */ 144 | JSON_Object * json_object_dotget_object (const JSON_Object *object, const char *name); 145 | JSON_Array * json_object_dotget_array (const JSON_Object *object, const char *name); 146 | double json_object_dotget_number (const JSON_Object *object, const char *name); /* returns 0 on fail */ 147 | int json_object_dotget_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */ 148 | 149 | /* Functions to get available names */ 150 | size_t json_object_get_count (const JSON_Object *object); 151 | const char * json_object_get_name (const JSON_Object *object, size_t index); 152 | JSON_Value * json_object_get_value_at(const JSON_Object *object, size_t index); 153 | JSON_Value * json_object_get_wrapping_value(const JSON_Object *object); 154 | 155 | /* Functions to check if object has a value with a specific name. Returned value is 1 if object has 156 | * a value and 0 if it doesn't. dothas functions behave exactly like dotget functions. */ 157 | int json_object_has_value (const JSON_Object *object, const char *name); 158 | int json_object_has_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type); 159 | 160 | int json_object_dothas_value (const JSON_Object *object, const char *name); 161 | int json_object_dothas_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type); 162 | 163 | /* Creates new name-value pair or frees and replaces old value with a new one. 164 | * json_object_set_value does not copy passed value so it shouldn't be freed afterwards. */ 165 | JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value); 166 | JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string); 167 | JSON_Status json_object_set_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len); /* length shouldn't include last null character */ 168 | JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number); 169 | JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean); 170 | JSON_Status json_object_set_null(JSON_Object *object, const char *name); 171 | 172 | /* Works like dotget functions, but creates whole hierarchy if necessary. 173 | * json_object_dotset_value does not copy passed value so it shouldn't be freed afterwards. */ 174 | JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value); 175 | JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string); 176 | JSON_Status json_object_dotset_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len); /* length shouldn't include last null character */ 177 | JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number); 178 | JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean); 179 | JSON_Status json_object_dotset_null(JSON_Object *object, const char *name); 180 | 181 | /* Frees and removes name-value pair */ 182 | JSON_Status json_object_remove(JSON_Object *object, const char *name); 183 | 184 | /* Works like dotget function, but removes name-value pair only on exact match. */ 185 | JSON_Status json_object_dotremove(JSON_Object *object, const char *key); 186 | 187 | /* Removes all name-value pairs in object */ 188 | JSON_Status json_object_clear(JSON_Object *object); 189 | 190 | /* 191 | *JSON Array 192 | */ 193 | JSON_Value * json_array_get_value (const JSON_Array *array, size_t index); 194 | const char * json_array_get_string (const JSON_Array *array, size_t index); 195 | size_t json_array_get_string_len(const JSON_Array *array, size_t index); /* doesn't account for last null character */ 196 | JSON_Object * json_array_get_object (const JSON_Array *array, size_t index); 197 | JSON_Array * json_array_get_array (const JSON_Array *array, size_t index); 198 | double json_array_get_number (const JSON_Array *array, size_t index); /* returns 0 on fail */ 199 | int json_array_get_boolean(const JSON_Array *array, size_t index); /* returns -1 on fail */ 200 | size_t json_array_get_count (const JSON_Array *array); 201 | JSON_Value * json_array_get_wrapping_value(const JSON_Array *array); 202 | 203 | /* Frees and removes value at given index, does nothing and returns JSONFailure if index doesn't exist. 204 | * Order of values in array may change during execution. */ 205 | JSON_Status json_array_remove(JSON_Array *array, size_t i); 206 | 207 | /* Frees and removes from array value at given index and replaces it with given one. 208 | * Does nothing and returns JSONFailure if index doesn't exist. 209 | * json_array_replace_value does not copy passed value so it shouldn't be freed afterwards. */ 210 | JSON_Status json_array_replace_value(JSON_Array *array, size_t i, JSON_Value *value); 211 | JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string); 212 | JSON_Status json_array_replace_string_with_len(JSON_Array *array, size_t i, const char *string, size_t len); /* length shouldn't include last null character */ 213 | JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number); 214 | JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean); 215 | JSON_Status json_array_replace_null(JSON_Array *array, size_t i); 216 | 217 | /* Frees and removes all values from array */ 218 | JSON_Status json_array_clear(JSON_Array *array); 219 | 220 | /* Appends new value at the end of array. 221 | * json_array_append_value does not copy passed value so it shouldn't be freed afterwards. */ 222 | JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value); 223 | JSON_Status json_array_append_string(JSON_Array *array, const char *string); 224 | JSON_Status json_array_append_string_with_len(JSON_Array *array, const char *string, size_t len); /* length shouldn't include last null character */ 225 | JSON_Status json_array_append_number(JSON_Array *array, double number); 226 | JSON_Status json_array_append_boolean(JSON_Array *array, int boolean); 227 | JSON_Status json_array_append_null(JSON_Array *array); 228 | 229 | /* 230 | *JSON Value 231 | */ 232 | JSON_Value * json_value_init_object (void); 233 | JSON_Value * json_value_init_array (void); 234 | JSON_Value * json_value_init_string (const char *string); /* copies passed string */ 235 | JSON_Value * json_value_init_string_with_len(const char *string, size_t length); /* copies passed string, length shouldn't include last null character */ 236 | JSON_Value * json_value_init_number (double number); 237 | JSON_Value * json_value_init_boolean(int boolean); 238 | JSON_Value * json_value_init_null (void); 239 | JSON_Value * json_value_deep_copy (const JSON_Value *value); 240 | void json_value_free (JSON_Value *value); 241 | 242 | JSON_Value_Type json_value_get_type (const JSON_Value *value); 243 | JSON_Object * json_value_get_object (const JSON_Value *value); 244 | JSON_Array * json_value_get_array (const JSON_Value *value); 245 | const char * json_value_get_string (const JSON_Value *value); 246 | size_t json_value_get_string_len(const JSON_Value *value); /* doesn't account for last null character */ 247 | double json_value_get_number (const JSON_Value *value); 248 | int json_value_get_boolean(const JSON_Value *value); 249 | JSON_Value * json_value_get_parent (const JSON_Value *value); 250 | 251 | /* Same as above, but shorter */ 252 | JSON_Value_Type json_type (const JSON_Value *value); 253 | JSON_Object * json_object (const JSON_Value *value); 254 | JSON_Array * json_array (const JSON_Value *value); 255 | const char * json_string (const JSON_Value *value); 256 | size_t json_string_len(const JSON_Value *value); /* doesn't account for last null character */ 257 | double json_number (const JSON_Value *value); 258 | int json_boolean(const JSON_Value *value); 259 | 260 | #ifdef __cplusplus 261 | } 262 | #endif 263 | 264 | #endif 265 | -------------------------------------------------------------------------------- /source/draw.c: -------------------------------------------------------------------------------- 1 | #include "draw.h" 2 | 3 | static DVLB_s *vshader_dvlb; 4 | static shaderProgram_s program; 5 | static int uLoc_projection; 6 | static C3D_Tex *glyphSheets; 7 | static textVertex_s *textVtxArray; 8 | static int textVtxArrayPos; 9 | static drawTarget_t top; 10 | static drawTarget_t bottom; 11 | static bool frameStarted = false; 12 | static gfxScreen_t currentScreen = -1; 13 | 14 | #define TEXT_VTX_ARRAY_COUNT (8 * 1024) 15 | 16 | #define TEX_MIN_SIZE 64 17 | 18 | //Grabbed from: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 19 | unsigned int nextPow2(unsigned int v) 20 | { 21 | v--; 22 | v |= v >> 1; 23 | v |= v >> 2; 24 | v |= v >> 4; 25 | v |= v >> 8; 26 | v |= v >> 16; 27 | v++; 28 | return (v >= TEX_MIN_SIZE ? v : TEX_MIN_SIZE); 29 | } 30 | 31 | static void addTextVertex(float vx, float vy, float vz, float tx, float ty) 32 | { 33 | textVertex_s *vtx; 34 | 35 | vtx = &textVtxArray[textVtxArrayPos++]; 36 | vtx->position[0] = vx; 37 | vtx->position[1] = vy; 38 | vtx->position[2] = 0.0f; 39 | vtx->texcoord[0] = tx; 40 | vtx->texcoord[1] = ty; 41 | } 42 | 43 | static void resetC3Denv() { 44 | C3D_TexEnv *env; 45 | for (int i = 0; i < 4; i++) { 46 | env = C3D_GetTexEnv(i); 47 | C3D_TexEnvInit(env); 48 | } 49 | } 50 | 51 | static void bindImageGreyScale(C3D_Tex *texture, u32 texture_color) { 52 | //((0.3 * R) + (0.59 * G) + (0.11 * B)). -> 0xFF1C964C 53 | C3D_TexEnv *env; 54 | u32 greyMask = 0xFF1C964C; 55 | resetC3Denv(); 56 | 57 | C3D_TexBind(0, texture); 58 | env = C3D_GetTexEnv(0); 59 | C3D_TexEnvSrc(env, C3D_RGB, GPU_TEXTURE0, GPU_CONSTANT, 0); 60 | C3D_TexEnvSrc(env, C3D_Alpha, GPU_TEXTURE0, 0, 0); 61 | C3D_TexEnvOpRgb(env, 0, 0, 0); 62 | C3D_TexEnvOpAlpha(env, 0, 0, 0); 63 | C3D_TexEnvFunc(env, C3D_RGB, GPU_MODULATE); 64 | C3D_TexEnvFunc(env, C3D_Alpha, GPU_REPLACE); 65 | C3D_TexEnvColor(env, texture_color); 66 | env = C3D_GetTexEnv(1); 67 | C3D_TexEnvSrc(env, C3D_RGB, GPU_PREVIOUS, GPU_CONSTANT, 0); 68 | C3D_TexEnvSrc(env, C3D_Alpha, GPU_PREVIOUS, 0, 0); 69 | C3D_TexEnvOpRgb(env, 0, 0, 0); 70 | C3D_TexEnvOpAlpha(env, 0, 0, 0); 71 | C3D_TexEnvFunc(env, C3D_RGB, GPU_MODULATE); 72 | C3D_TexEnvFunc(env, C3D_Alpha, GPU_REPLACE); 73 | C3D_TexEnvColor(env, greyMask); 74 | C3D_TexEnvBufUpdate(C3D_RGB, 0b0010); 75 | env = C3D_GetTexEnv(2); 76 | C3D_TexEnvSrc(env, C3D_RGB, GPU_PREVIOUS, GPU_PREVIOUS, 0); 77 | C3D_TexEnvSrc(env, C3D_Alpha, GPU_PREVIOUS, 0, 0); 78 | C3D_TexEnvOpRgb(env, GPU_TEVOP_RGB_SRC_R, GPU_TEVOP_RGB_SRC_G, 0); 79 | C3D_TexEnvOpAlpha(env, 0, 0, 0); 80 | C3D_TexEnvFunc(env, C3D_RGB, GPU_ADD); 81 | C3D_TexEnvFunc(env, C3D_Alpha, GPU_REPLACE); 82 | env = C3D_GetTexEnv(3); 83 | C3D_TexEnvSrc(env, C3D_RGB, GPU_PREVIOUS, GPU_PREVIOUS_BUFFER, 0); 84 | C3D_TexEnvSrc(env, C3D_Alpha, GPU_PREVIOUS, 0, 0); 85 | C3D_TexEnvOpRgb(env, 0, GPU_TEVOP_RGB_SRC_B, 0); 86 | C3D_TexEnvOpAlpha(env, 0, 0, 0); 87 | C3D_TexEnvFunc(env, C3D_RGB, GPU_ADD); 88 | C3D_TexEnvFunc(env, C3D_Alpha, GPU_REPLACE); 89 | } 90 | 91 | static void bindTexture(C3D_Tex *texture, u32 texture_color) 92 | { 93 | C3D_TexEnv *env; 94 | resetC3Denv(); 95 | 96 | C3D_TexBind(0, texture); 97 | env = C3D_GetTexEnv(0); 98 | C3D_TexEnvBufUpdate(C3D_RGB, 0); 99 | C3D_TexEnvSrc(env, C3D_RGB, GPU_TEXTURE0, GPU_CONSTANT, 0); 100 | C3D_TexEnvSrc(env, C3D_Alpha, GPU_TEXTURE0, 0, 0); 101 | C3D_TexEnvOpRgb(env, 0, 0, 0); 102 | C3D_TexEnvOpAlpha(env, 0, 0, 0); 103 | C3D_TexEnvFunc(env, C3D_RGB, GPU_MODULATE); 104 | C3D_TexEnvFunc(env, C3D_Alpha, GPU_REPLACE); 105 | C3D_TexEnvColor(env, texture_color); 106 | } 107 | 108 | void setSpritePos(sprite_t *sprite, float posX, float posY) 109 | { 110 | if (!sprite) return; 111 | sprite->posX = posX; 112 | sprite->posY = posY; 113 | } 114 | 115 | void drawSprite(sprite_t *sprite) 116 | { 117 | float height; 118 | float width; 119 | float u; 120 | float v; 121 | float x; 122 | float y; 123 | int arrayIndex; 124 | C3D_Tex *texture; 125 | if (!frameStarted) return; 126 | 127 | if (!sprite || sprite->isHidden) return; 128 | texture = &sprite->texture; 129 | height = sprite->height; 130 | width = sprite->width; 131 | x = sprite->posX; 132 | y = sprite->posY; 133 | u = width / (float)texture->width; 134 | v = height / (float)texture->height; 135 | 136 | width = floor(width * sprite->amount); 137 | u *= sprite->amount; 138 | 139 | C3D_BufInfo *bufInfo = C3D_GetBufInfo(); 140 | BufInfo_Init(bufInfo); 141 | BufInfo_Add(bufInfo, textVtxArray, sizeof(textVertex_s), 2, 0x10); 142 | //Set the vertices 143 | arrayIndex = textVtxArrayPos; 144 | addTextVertex(x, y + height, sprite->depth, 0.0f, v); //left bottom 145 | addTextVertex(x + width, y + height, sprite->depth, u, v); //right bottom 146 | addTextVertex(x, y, sprite->depth, 0.0f, 0.0f); //left top 147 | addTextVertex(x + width, y, sprite->depth, u, 0.0f); //right top 148 | 149 | //Bind the sprite's texture 150 | if (sprite->isGreyedOut) { 151 | bindImageGreyScale(texture, sprite->drawColor); 152 | } 153 | else { 154 | bindTexture(texture, sprite->drawColor); 155 | } 156 | 157 | //Draw 158 | C3D_DrawArrays(GPU_TRIANGLE_STRIP, arrayIndex, 4); 159 | } 160 | 161 | void drawRectangle(rectangle_t *rectangle) 162 | { 163 | float height; 164 | float width; 165 | float x; 166 | float y; 167 | int arrayIndex; 168 | C3D_TexEnv *env; 169 | 170 | if (!frameStarted) return; 171 | 172 | if (!rectangle) return; 173 | height = rectangle->height; 174 | width = ceil(rectangle->width * rectangle->amount); 175 | x = rectangle->posX; 176 | y = rectangle->posY; 177 | 178 | C3D_BufInfo *bufInfo = C3D_GetBufInfo(); 179 | BufInfo_Init(bufInfo); 180 | BufInfo_Add(bufInfo, textVtxArray, sizeof(textVertex_s), 2, 0x10); 181 | //Set the vertices 182 | arrayIndex = textVtxArrayPos; 183 | addTextVertex(x, y + height, rectangle->depth, 0.0f, 1.f); //left bottom 184 | addTextVertex(x + width, y + height, rectangle->depth, 1.f, 1.f); //right bottom 185 | addTextVertex(x, y, rectangle->depth, 0.0f, 0.0f); //left top 186 | addTextVertex(x + width, y, rectangle->depth, 1.f, 0.0f); //right top 187 | 188 | resetC3Denv(); 189 | env = C3D_GetTexEnv(0); 190 | C3D_TexBind(0, &(rectangle->sprite->texture)); 191 | C3D_TexEnvBufUpdate(C3D_RGB, 0); 192 | C3D_TexEnvSrc(env, C3D_RGB, GPU_TEXTURE0, 0, 0); 193 | C3D_TexEnvSrc(env, C3D_Alpha, GPU_CONSTANT, 0, 0); 194 | C3D_TexEnvOpRgb(env, 0, 0, 0); 195 | C3D_TexEnvOpAlpha(env, 0, 0, 0); 196 | C3D_TexEnvFunc(env, C3D_Both, GPU_REPLACE); 197 | C3D_TexEnvColor(env, 0xFFFFFFFF); 198 | 199 | //Draw 200 | C3D_DrawArrays(GPU_TRIANGLE_STRIP, arrayIndex, 4); 201 | } 202 | 203 | sprite_t *newSprite(int width, int height) 204 | { 205 | sprite_t *sprite; 206 | C3D_Tex *texture; 207 | bool result; 208 | 209 | //Alloc the sprite 210 | sprite = (sprite_t *)calloc(1, sizeof(sprite_t)); 211 | if (!sprite) goto allocError; 212 | texture = &sprite->texture; 213 | 214 | //Create and init the sprite's texture 215 | result = C3D_TexInit(texture, nextPow2(width), nextPow2(height), GPU_RGBA8); 216 | if (!result) goto texInitError; 217 | //C3D_TexSetWrap(texture, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER); 218 | texture->param = GPU_TEXTURE_MAG_FILTER(GPU_LINEAR) | GPU_TEXTURE_MIN_FILTER(GPU_LINEAR) 219 | | GPU_TEXTURE_WRAP_S(GPU_CLAMP_TO_BORDER) | GPU_TEXTURE_WRAP_T(GPU_CLAMP_TO_BORDER); 220 | 221 | sprite->width = (float)width; 222 | sprite->height = (float)height; 223 | sprite->drawColor = 0xFFFFFFFF; 224 | sprite->isGreyedOut = false; 225 | sprite->isHidden = false; 226 | sprite->depth = 0.0f; 227 | sprite->amount = 1.f; 228 | return (sprite); 229 | texInitError: 230 | free(sprite); 231 | allocError: 232 | return (NULL); 233 | } 234 | 235 | void deleteSprite(sprite_t *sprite) 236 | { 237 | if (!sprite) return; 238 | C3D_TexDelete(&sprite->texture); 239 | free(sprite); 240 | sprite = NULL; 241 | } 242 | 243 | static void sceneInit(void) 244 | { 245 | int i; 246 | TGLP_s *glyphInfo; 247 | C3D_Tex *tex; 248 | C3D_AttrInfo *attrInfo; 249 | 250 | // Load the vertex shader, create a shader program and bind it 251 | vshader_dvlb = DVLB_ParseFile((u32*)vshader_shbin, vshader_shbin_len); 252 | shaderProgramInit(&program); 253 | shaderProgramSetVsh(&program, &vshader_dvlb->DVLE[0]); 254 | C3D_BindProgram(&program); 255 | 256 | // Get the location of the uniforms 257 | uLoc_projection = shaderInstanceGetUniformLocation(program.vertexShader, "projection"); 258 | 259 | // Configure attributes for use with the vertex shader 260 | attrInfo = C3D_GetAttrInfo(); 261 | AttrInfo_Init(attrInfo); 262 | AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); // v0=position 263 | AttrInfo_AddLoader(attrInfo, 1, GPU_FLOAT, 2); // v1=texcoord 264 | 265 | // Compute the projection matrix 266 | Mtx_OrthoTilt(&top.projection, 0.0f, 400.0f, 240.0f, 0.0f, 0.0f, 1.0f, true); 267 | Mtx_OrthoTilt(&bottom.projection, 0.0f, 320.0f, 240.0f, 0.0f, 0.0f, 1.0f, true); 268 | 269 | // Configure depth test to overwrite pixels with the same depth (needed to draw overlapping glyphs) 270 | C3D_DepthTest(true, GPU_GEQUAL, GPU_WRITE_ALL); 271 | 272 | // Load the glyph texture sheets 273 | glyphInfo = fontGetGlyphInfo(NULL); 274 | glyphSheets = malloc(sizeof(C3D_Tex) * glyphInfo->nSheets); 275 | for (i = 0; i < glyphInfo->nSheets; i++) 276 | { 277 | tex = &glyphSheets[i]; 278 | tex->data = fontGetGlyphSheetTex(NULL, i); 279 | tex->fmt = glyphInfo->sheetFmt; 280 | tex->size = glyphInfo->sheetSize; 281 | tex->width = glyphInfo->sheetWidth; 282 | tex->height = glyphInfo->sheetHeight; 283 | tex->param = GPU_TEXTURE_MAG_FILTER(GPU_LINEAR) | GPU_TEXTURE_MIN_FILTER(GPU_LINEAR) 284 | | GPU_TEXTURE_WRAP_S(GPU_CLAMP_TO_EDGE) | GPU_TEXTURE_WRAP_T(GPU_CLAMP_TO_EDGE); 285 | } 286 | // Create the text vertex array 287 | textVtxArray = (textVertex_s*)linearAlloc(sizeof(textVertex_s)*TEXT_VTX_ARRAY_COUNT); 288 | } 289 | 290 | static void sceneExit(void) 291 | { 292 | // Free the textures 293 | free(glyphSheets); 294 | 295 | // Free the shader program 296 | shaderProgramFree(&program); 297 | DVLB_Free(vshader_dvlb); 298 | } 299 | 300 | void drawInit(void) 301 | { 302 | C3D_RenderTarget *target; 303 | 304 | //Init Citro3D 305 | C3D_Init(C3D_DEFAULT_CMDBUF_SIZE); 306 | 307 | // Initialize the top render target 308 | target = C3D_RenderTargetCreate(240, 400, GPU_RB_RGBA8, GPU_RB_DEPTH24_STENCIL8); 309 | C3D_RenderTargetClear(target, C3D_CLEAR_ALL, CLEAR_COLOR, 0); 310 | C3D_RenderTargetSetOutput(target, GFX_TOP, GFX_LEFT, DISPLAY_TRANSFER_FLAGS); 311 | top.target = target; 312 | 313 | // Initialize the bottom render target 314 | target = C3D_RenderTargetCreate(240, 320, GPU_RB_RGBA8, GPU_RB_DEPTH24_STENCIL8); 315 | C3D_RenderTargetClear(target, C3D_CLEAR_ALL, CLEAR_COLOR, 0); 316 | C3D_RenderTargetSetOutput(target, GFX_BOTTOM, GFX_LEFT, DISPLAY_TRANSFER_FLAGS); 317 | bottom.target = target; 318 | 319 | //Initialize the system font 320 | fontEnsureMapped(); 321 | 322 | // Initialize the scene 323 | sceneInit(); 324 | } 325 | 326 | void drawExit(void) 327 | { 328 | sceneExit(); 329 | C3D_Fini(); 330 | } 331 | 332 | void setTextColor(u32 color) 333 | { 334 | #ifndef CITRA 335 | C3D_TexEnv *env; 336 | 337 | env = C3D_GetTexEnv(0); 338 | C3D_TexEnvSrc(env, C3D_RGB, GPU_CONSTANT, 0, 0); 339 | C3D_TexEnvSrc(env, C3D_Alpha, GPU_TEXTURE0, GPU_CONSTANT, 0); 340 | C3D_TexEnvOpRgb(env, 0, 0, 0); 341 | C3D_TexEnvOpAlpha(env, 0, 0, 0); 342 | C3D_TexEnvFunc(env, C3D_RGB, GPU_REPLACE); 343 | C3D_TexEnvFunc(env, C3D_Alpha, GPU_MODULATE); 344 | C3D_TexEnvColor(env, color); 345 | #endif 346 | } 347 | 348 | void getTextSizeInfos(float *width, float scaleX, float scaleY, const char *text) 349 | { 350 | float w; 351 | u8 *c; 352 | u32 code; 353 | ssize_t units; 354 | int glyphIndex; 355 | fontGlyphPos_s data; 356 | 357 | w = 0.0f; 358 | c = (u8 *)text; 359 | if (!text) return; 360 | while (*c == '\n') c++; 361 | do 362 | { 363 | if (!*c) break; 364 | units = decode_utf8(&code, c); 365 | if (units == -1) break; 366 | c += units; 367 | if (code > 0) 368 | { 369 | glyphIndex = fontGlyphIndexFromCodePoint(NULL, code); 370 | fontCalcGlyphPos(&data, NULL, glyphIndex, GLYPH_POS_CALC_VTXCOORD, scaleX, scaleY); 371 | w += data.xAdvance; 372 | } 373 | } while (code > 0); 374 | *width = w; 375 | } 376 | 377 | void findBestSize(float *sizeX, float *sizeY, float posXMin, float posXMax, float sizeMax, const char *text) 378 | { 379 | float scale; 380 | float originalTextWidth; 381 | float margin; //in pixels 382 | float textWidth; 383 | float bounds; 384 | 385 | if (!text | !sizeX) return; 386 | getTextSizeInfos(&originalTextWidth, 1.0f, 1.0f, text); 387 | scale = sizeMax; 388 | margin = 1.0f; 389 | bounds = posXMax - posXMin; 390 | bounds -= (margin * 2); 391 | while (1) 392 | { 393 | textWidth = scale * originalTextWidth; 394 | if (textWidth > bounds) scale -= 0.01f; 395 | else break; 396 | if (scale <= 0.0f) break; 397 | } 398 | *sizeX = scale; 399 | if (sizeY) *sizeY = scale; 400 | } 401 | 402 | 403 | void renderText(float x, float y, float scaleX, float scaleY, bool baseline, const char *text, cursor_t *cursor, float depth) 404 | { 405 | u32 flags; 406 | u32 code; 407 | int lastSheet; 408 | int glyphIdx; 409 | int arrayIndex; 410 | ssize_t units; 411 | float firstX; 412 | C3D_BufInfo *bufInfo; 413 | fontGlyphPos_s data; 414 | const u8 *p = (const u8 *)text; 415 | if (!frameStarted) return; 416 | 417 | // Configure buffers 418 | bufInfo = C3D_GetBufInfo(); 419 | BufInfo_Init(bufInfo); 420 | BufInfo_Add(bufInfo, textVtxArray, sizeof(textVertex_s), 2, 0x10); 421 | firstX = x; 422 | flags = GLYPH_POS_CALC_VTXCOORD | (baseline ? GLYPH_POS_AT_BASELINE : 0); 423 | lastSheet = -1; 424 | do 425 | { 426 | if (!*p) 427 | break; 428 | units = decode_utf8(&code, p); 429 | if (units == -1) 430 | break; 431 | p += units; 432 | if (code == '\n') 433 | { 434 | x = firstX; 435 | y += scaleY * fontGetInfo(NULL)->lineFeed; 436 | } 437 | else if (code > 0) 438 | { 439 | glyphIdx = fontGlyphIndexFromCodePoint(NULL, code); 440 | fontCalcGlyphPos(&data, NULL, glyphIdx, flags, scaleX, scaleY); 441 | 442 | // Bind the correct texture sheet 443 | if (data.sheetIndex != lastSheet) 444 | { 445 | lastSheet = data.sheetIndex; 446 | C3D_TexBind(0, &glyphSheets[lastSheet]); 447 | } 448 | 449 | arrayIndex = textVtxArrayPos; 450 | if ((arrayIndex + 4) >= TEXT_VTX_ARRAY_COUNT) 451 | break; // We can't render more characters 452 | 453 | // Add the vertices to the array 454 | addTextVertex(x + data.vtxcoord.left, y + data.vtxcoord.bottom, depth, data.texcoord.left, data.texcoord.bottom); 455 | addTextVertex(x + data.vtxcoord.right, y + data.vtxcoord.bottom, depth, data.texcoord.right, data.texcoord.bottom); 456 | addTextVertex(x + data.vtxcoord.left, y + data.vtxcoord.top, depth, data.texcoord.left, data.texcoord.top); 457 | addTextVertex(x + data.vtxcoord.right, y + data.vtxcoord.top, depth, data.texcoord.right, data.texcoord.top); 458 | 459 | // Draw the glyph 460 | C3D_DrawArrays(GPU_TRIANGLE_STRIP, arrayIndex, 4); 461 | 462 | x += data.xAdvance; 463 | 464 | } 465 | } while (code > 0); 466 | if (cursor) 467 | { 468 | cursor->posX = x; 469 | cursor->posY = y; 470 | } 471 | } 472 | 473 | void updateScreen(void) 474 | { 475 | if (frameStarted) { 476 | C3D_FrameEnd(0); 477 | frameStarted = false; 478 | } 479 | textVtxArrayPos = 0; 480 | currentScreen = -1; 481 | } 482 | 483 | void setScreen(gfxScreen_t screen) 484 | { 485 | if (!frameStarted) 486 | { 487 | C3D_FrameBegin(C3D_FRAME_SYNCDRAW); 488 | frameStarted = true; 489 | } 490 | if (screen == currentScreen) return; 491 | currentScreen = screen; 492 | if (screen == GFX_TOP) 493 | { 494 | C3D_FrameDrawOn(top.target); 495 | C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, uLoc_projection, &top.projection); 496 | } 497 | else if (screen == GFX_BOTTOM) 498 | { 499 | C3D_FrameDrawOn(bottom.target); 500 | C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, uLoc_projection, &bottom.projection); 501 | } 502 | else return; 503 | } 504 | -------------------------------------------------------------------------------- /source/updater.c: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | #include "errno.h" 3 | #include "sys/stat.h" 4 | #include "graphics.h" 5 | #include "drawableObject.h" 6 | #include "clock.h" 7 | #include 8 | #include "Unicode.h" 9 | #include "parson.h" 10 | #include "Archives.h" 11 | 12 | typedef struct downFileInfo_s 13 | { 14 | char* fileName; 15 | u32 updateIndex; 16 | char mode; 17 | } downFileInfo_t; 18 | 19 | static char *str_result_buf = NULL; 20 | static size_t str_result_sz = 0; 21 | static size_t str_result_written = 0; 22 | 23 | char CURL_lastErrorCode[CURL_ERROR_SIZE]; 24 | static u64 showTimer = -1; 25 | static u32 alreadyGotFile = 0; 26 | static int fileDownCnt = 0; 27 | static int totFileDownCnt = 0; 28 | char updatingVer[30] = { 0 }; 29 | char* updatingFile = NULL; 30 | FILE *downfile = NULL; 31 | static int retryingFromError = 0; 32 | char progTextBuf[2][20]; 33 | 34 | char* versionList[100] = { NULL }; 35 | extern char g_modversion[15]; 36 | char* changelogList[100][100] = { NULL }; 37 | char* baseDataURL = NULL; 38 | char* baseFilelistURL = NULL; 39 | 40 | bool g_ciaInstallFailed = false; 41 | bool g_allowUserCancel = false; 42 | bool g_userHasCancelled = false; 43 | bool g_hasInstalledCiaFile = false; 44 | 45 | s64 g_sdFreeSpace = 0; 46 | bool g_fileDontFit = false; 47 | 48 | bool isWifiAvailable() { 49 | return osGetWifiStrength() > 0; 50 | } 51 | 52 | void DisableSleep(void) 53 | { 54 | u8 reg; 55 | 56 | if (R_FAILED(mcuHwcInit())) 57 | return; 58 | 59 | if (R_FAILED(MCUHWC_ReadRegister(0x18, ®, 1))) 60 | return; 61 | 62 | reg |= 0x6C; ///< Disable home btn & shell state events 63 | MCUHWC_WriteRegister(0x18, ®, 1); 64 | mcuHwcExit(); 65 | } 66 | 67 | void EnableSleep(void) 68 | { 69 | u8 reg; 70 | 71 | if (R_FAILED(mcuHwcInit())) 72 | return; 73 | 74 | if (R_FAILED(MCUHWC_ReadRegister(0x18, ®, 1))) 75 | return; 76 | 77 | reg &= ~0x6C; ///< Enable home btn & shell state events 78 | MCUHWC_WriteRegister(0x18, ®, 1); 79 | mcuHwcExit(); 80 | } 81 | 82 | char* getProgText(float prog, int index) { 83 | if (prog < (1024 * 1024)) { 84 | sprintf(progTextBuf[index], "%.2f KB", prog / 1024); 85 | return progTextBuf[index]; 86 | } 87 | else { 88 | sprintf(progTextBuf[index], "%.2f MB", prog / (1024 * 1024)); 89 | return progTextBuf[index]; 90 | } 91 | } 92 | 93 | void updateTop(curl_off_t dlnow, curl_off_t dltot, float speed) { 94 | clearTop(); 95 | newAppTop(DEFAULT_COLOR, CENTER | BOLD | MEDIUM, updatingVer); 96 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "Downloading Files"); 97 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "%d / %d", fileDownCnt, totFileDownCnt); 98 | if (retryingFromError) { 99 | newAppTop(COLOR_YELLOW, CENTER | MEDIUM, "\nRecovered from error. Retries: %d/30", retryingFromError); 100 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "%s / %s", getProgText(dlnow, 0), getProgText(dltot, 1)); 101 | } 102 | else { 103 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "\n%s / %s", getProgText(dlnow, 0), getProgText(dltot, 1)); 104 | } 105 | if (g_allowUserCancel) { 106 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "%.2f KB/s", speed); 107 | } 108 | else 109 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "%.2f KB/s\n", speed); 110 | if (updatingFile) newAppTopMultiline(DEFAULT_COLOR, CENTER | SMALL, updatingFile); 111 | } 112 | 113 | static size_t handle_data(char *ptr, size_t size, size_t nmemb, void *userdata) { 114 | (void)userdata; 115 | const size_t bsz = size * nmemb; 116 | 117 | if (!str_result_buf) { 118 | str_result_sz = 1 << 9; 119 | str_result_buf = memalign(0x1000, 1 << 9); 120 | } 121 | bool needrealloc = false; 122 | while (bsz + str_result_written >= str_result_sz) { 123 | str_result_sz <<= 1; 124 | needrealloc = true; 125 | } 126 | if (needrealloc) { 127 | str_result_buf = realloc(str_result_buf, str_result_sz); 128 | if (!str_result_buf) { 129 | return 0; 130 | } 131 | } 132 | if (!str_result_buf) return 0; 133 | memcpy(str_result_buf + str_result_written, ptr, bsz); 134 | str_result_written += bsz; 135 | return bsz; 136 | } 137 | 138 | int file_progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { 139 | if (!(dltotal && dlnow) || dltotal < 1024) return 0; 140 | static float oldprogress = 0; 141 | static u64 timer = 0; 142 | static u64 timer2 = 0; 143 | dltotal += alreadyGotFile; 144 | dlnow += alreadyGotFile; 145 | if (showTimer == -1) { //Not initialized 146 | oldprogress = 0; 147 | timer2 = 0; 148 | timer = Timer_Restart(); 149 | showTimer = Timer_Restart(); 150 | } 151 | if (getTimeInMsec(Timer_Restart() - showTimer) > 100) { 152 | timer2 = showTimer = Timer_Restart(); 153 | u64 progmsec = getTimeInMsec(timer2 - timer); 154 | timer = Timer_Restart(); 155 | if (!progmsec) progmsec = 1; 156 | curl_off_t progbytes = dlnow - oldprogress; 157 | updateTop(dlnow, dltotal, ((float)progbytes) / ((float)progmsec)); 158 | updateUI(); 159 | oldprogress = dlnow; 160 | } 161 | if (dltotal > (g_sdFreeSpace - 10000000)) { 162 | g_fileDontFit = true; 163 | return 1; 164 | } 165 | if (aptMainLoop()) return 0; 166 | else return 1; 167 | }; 168 | 169 | char* getFileFromPath(char* file) { 170 | char* ret = file; 171 | while (*file) { 172 | if (*file++ == '/') ret = file; 173 | } 174 | return ret; 175 | } 176 | 177 | char *strdup(const char *s) { 178 | char *d = malloc(strlen(s) + 1); // Space for length plus nul 179 | if (d == NULL) return NULL; // No memory 180 | strcpy(d, s); // Copy the characters 181 | return d; // Return the new string 182 | } 183 | 184 | FILE* fopen_mkdir(const char* name, const char* mode) 185 | { 186 | char* _path = strdup(name); 187 | char *p; 188 | FILE* retfile = NULL; 189 | 190 | errno = 0; 191 | for (p = _path + 1; *p; p++) 192 | { 193 | if (*p == '/') 194 | { 195 | *p = '\0'; 196 | if (mkdir(_path, 777) != 0) 197 | if (errno != EEXIST) goto error; 198 | *p = '/'; 199 | } 200 | } 201 | retfile = fopen(name, mode); 202 | error: 203 | free(_path); 204 | return retfile; 205 | } 206 | 207 | void memcpy32(void *dest, const void *src, size_t count) 208 | { 209 | u32 lastbytes = count & 3; 210 | u32 *dest_ = (u32 *)dest; 211 | const u32 *src_ = (u32*)src; 212 | 213 | count >>= 2; 214 | 215 | while (count--) 216 | *dest_++ = *src_++; 217 | 218 | u8 *dest8_ = (u8 *)dest_; 219 | u8 *src8_ = (u8 *)src_; 220 | 221 | while (lastbytes--) 222 | *dest8_++ = *src8_++; 223 | } 224 | 225 | static size_t file_buffer_pos = 0; 226 | static size_t file_toCommit_size = 0; 227 | static char* g_buffers[2] = { NULL }; 228 | static u8 g_index = 0; 229 | static Thread fsCommitThread; 230 | static LightEvent readyToCommit; 231 | static LightEvent waitCommit; 232 | static bool killThread = false; 233 | static bool writeError = false; 234 | #define FILE_ALLOC_SIZE 0x20000 235 | 236 | bool filecommit() { 237 | if (!downfile) return false; 238 | if (!file_toCommit_size) return true; 239 | fseek(downfile, 0, SEEK_END); 240 | u32 byteswritten = fwrite(g_buffers[!g_index], 1, file_toCommit_size, downfile); 241 | if (byteswritten != file_toCommit_size) return false; 242 | file_toCommit_size = 0; 243 | return true; 244 | } 245 | 246 | static void commitToFileThreadFunc(void* args) { 247 | LightEvent_Signal(&waitCommit); 248 | while (true) { 249 | LightEvent_Wait(&readyToCommit); 250 | LightEvent_Clear(&readyToCommit); 251 | if (killThread) threadExit(0); 252 | writeError = !filecommit(); 253 | LightEvent_Signal(&waitCommit); 254 | } 255 | } 256 | 257 | static size_t file_handle_data(char *ptr, size_t size, size_t nmemb, void *userdata) { 258 | (void)userdata; 259 | const size_t bsz = size * nmemb; 260 | size_t tofill = 0; 261 | if (writeError) return 0; 262 | if (!g_buffers[g_index]) { 263 | 264 | LightEvent_Init(&waitCommit, RESET_STICKY); 265 | LightEvent_Init(&readyToCommit, RESET_STICKY); 266 | 267 | s32 prio = 0; 268 | svcGetThreadPriority(&prio, CUR_THREAD_HANDLE); 269 | fsCommitThread = threadCreate(commitToFileThreadFunc, NULL, 0x8000, prio - 1, -2, true); 270 | 271 | g_buffers[0] = memalign(0x1000, FILE_ALLOC_SIZE); 272 | g_buffers[1] = memalign(0x1000, FILE_ALLOC_SIZE); 273 | 274 | if (!fsCommitThread || !g_buffers[0] || !g_buffers[1]) return 0; 275 | } 276 | if (file_buffer_pos + bsz >= FILE_ALLOC_SIZE) { 277 | tofill = FILE_ALLOC_SIZE - file_buffer_pos; 278 | memcpy(g_buffers[g_index] + file_buffer_pos, ptr, tofill); 279 | 280 | LightEvent_Wait(&waitCommit); 281 | LightEvent_Clear(&waitCommit); 282 | file_toCommit_size = file_buffer_pos + tofill; 283 | file_buffer_pos = 0; 284 | svcFlushProcessDataCache(CURRENT_PROCESS_HANDLE, (u32)g_buffers[g_index], file_toCommit_size); 285 | g_index = !g_index; 286 | LightEvent_Signal(&readyToCommit); 287 | } 288 | memcpy(g_buffers[g_index] + file_buffer_pos, ptr + tofill, bsz - tofill); 289 | file_buffer_pos += bsz - tofill; 290 | return bsz; 291 | } 292 | 293 | int downloadFile(const char* URL, char* filepath) { 294 | 295 | int retcode = 0; 296 | aptSetHomeAllowed(false); 297 | aptSetSleepAllowed(false); 298 | 299 | void *socubuf = memalign(0x1000, 0x100000); 300 | if (!socubuf) { 301 | sprintf(CURL_lastErrorCode, "Failed to allocate memory."); 302 | retcode = 1; 303 | goto exit; 304 | } 305 | 306 | downfile = fopen_mkdir(filepath, "wb"); 307 | if (!downfile) { 308 | sprintf(CURL_lastErrorCode, "Failed to create file."); 309 | retcode = 4; 310 | goto exit; 311 | } 312 | CURL_lastErrorCode[0] = 0; 313 | retryingFromError = 0; 314 | g_userHasCancelled = false; 315 | alreadyGotFile = 0; 316 | g_fileDontFit = false; 317 | getFreeSpace((u64*)&g_sdFreeSpace); 318 | updatingFile = getFileFromPath(filepath); 319 | clearTop(); 320 | newAppTop(DEFAULT_COLOR, CENTER | BOLD | MEDIUM, updatingVer); 321 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "Downloading Files"); 322 | newAppTop(DEFAULT_COLOR, CENTER | MEDIUM, "%d / %d", fileDownCnt, totFileDownCnt); 323 | updateUI(); 324 | 325 | while (true) { 326 | int res = socInit(socubuf, 0x100000); 327 | CURLcode cres; 328 | if (R_FAILED(res)) { 329 | sprintf(CURL_lastErrorCode, "socInit returned: 0x%08X", res); 330 | cres = 0xFF; 331 | } 332 | else { 333 | CURL* hnd = curl_easy_init(); 334 | curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, FILE_ALLOC_SIZE); 335 | curl_easy_setopt(hnd, CURLOPT_URL, URL); 336 | curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 0L); 337 | curl_easy_setopt(hnd, CURLOPT_USERAGENT, "Mozilla/5.0 (Nintendo 3DS; U; ; en) AppleWebKit/536.30 (KHTML, like Gecko) CTGP-7/1.0 CTGP-7/1.0"); 338 | curl_easy_setopt(hnd, CURLOPT_FOLLOWLOCATION, 1L); 339 | curl_easy_setopt(hnd, CURLOPT_FAILONERROR, 1L); 340 | curl_easy_setopt(hnd, CURLOPT_ACCEPT_ENCODING, "gzip"); 341 | if (retryingFromError) { 342 | u32 gotSize = ftell(downfile); 343 | if (gotSize) { 344 | alreadyGotFile = gotSize; 345 | char tmpRange[0x30]; 346 | sprintf(tmpRange, "%ld-", gotSize); 347 | curl_easy_setopt(hnd, CURLOPT_RANGE, tmpRange); 348 | } 349 | } 350 | curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L); 351 | curl_easy_setopt(hnd, CURLOPT_XFERINFOFUNCTION, file_progress_callback); 352 | curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2TLS); 353 | curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, file_handle_data); 354 | curl_easy_setopt(hnd, CURLOPT_ERRORBUFFER, CURL_lastErrorCode); 355 | curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); 356 | curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); 357 | curl_easy_setopt(hnd, CURLOPT_STDERR, stdout); 358 | 359 | cres = curl_easy_perform(hnd); 360 | curl_easy_cleanup(hnd); 361 | } 362 | if (cres != CURLE_OK) { 363 | if (retryingFromError < 30 && aptMainLoop() && !g_userHasCancelled && !g_fileDontFit) { 364 | svcSleepThread(1000000000); 365 | clearTop(); 366 | newAppTop(DEFAULT_COLOR, CENTER | BOLD | MEDIUM, updatingVer); 367 | newAppTop(COLOR_YELLOW, CENTER | MEDIUM, "Download failed with error code:"); 368 | newAppTop(COLOR_YELLOW, CENTER | MEDIUM, "\n0x%08X", cres); 369 | newAppTopMultiline(COLOR_YELLOW, CENTER | SMALL, CURL_lastErrorCode); 370 | newAppTop(COLOR_YELLOW, CENTER | MEDIUM, "\nRetrying in 10 seconds..."); 371 | newAppTop(COLOR_YELLOW, CENTER | MEDIUM, "Retry count: (%d / 30)", retryingFromError + 1); 372 | updateUI(); 373 | svcSleepThread(10000000000); 374 | retryingFromError++; 375 | } 376 | else { 377 | retryingFromError = 0; 378 | retcode = cres; 379 | goto exit; 380 | } 381 | } 382 | else retryingFromError = 0; 383 | 384 | if (fsCommitThread) { 385 | LightEvent_Wait(&waitCommit); 386 | LightEvent_Clear(&waitCommit); 387 | } 388 | 389 | if (cres == CURLE_OK) { 390 | file_toCommit_size = file_buffer_pos; 391 | svcFlushProcessDataCache(CURRENT_PROCESS_HANDLE, (u32)g_buffers[g_index], file_toCommit_size); 392 | g_index = !g_index; 393 | if (!filecommit()) { 394 | sprintf(CURL_lastErrorCode, "Couldn't commit to file."); 395 | retcode = 2; 396 | goto exit; 397 | } 398 | } 399 | fflush(downfile); 400 | 401 | exit: 402 | if (fsCommitThread) { 403 | killThread = true; 404 | LightEvent_Signal(&readyToCommit); 405 | threadJoin(fsCommitThread, U64_MAX); 406 | killThread = false; 407 | fsCommitThread = NULL; 408 | } 409 | 410 | socExit(); 411 | 412 | if (!retryingFromError) { 413 | 414 | if (socubuf) { 415 | free(socubuf); 416 | } 417 | if (downfile) { 418 | fclose(downfile); 419 | downfile = NULL; 420 | } 421 | updatingFile = NULL; 422 | } 423 | 424 | if (g_buffers[0]) { 425 | free(g_buffers[0]); 426 | g_buffers[0] = NULL; 427 | } 428 | if (g_buffers[1]) { 429 | free(g_buffers[1]); 430 | g_buffers[1] = NULL; 431 | } 432 | file_buffer_pos = 0; 433 | file_toCommit_size = 0; 434 | writeError = false; 435 | g_index = 0; 436 | showTimer = -1; 437 | 438 | if (!retryingFromError) 439 | return retcode; 440 | else svcSleepThread(1000000000); 441 | } 442 | aptSetHomeAllowed(true); 443 | aptSetSleepAllowed(true); 444 | } 445 | 446 | 447 | int downloadString(const char* URL, char** out) { 448 | 449 | DisableSleep(); 450 | 451 | *out = NULL; 452 | int retcode = 0; 453 | 454 | void *socubuf = memalign(0x1000, 0x100000); 455 | if (!socubuf) { 456 | sprintf(CURL_lastErrorCode, "Failed to allocate memory."); 457 | retcode = 1; 458 | goto exit; 459 | } 460 | int res = socInit(socubuf, 0x100000); 461 | if (R_FAILED(res)) { 462 | sprintf(CURL_lastErrorCode, "socInit returned: 0x%08X", res); 463 | retcode = 2; 464 | goto exit; 465 | } 466 | 467 | CURL *hnd = curl_easy_init(); 468 | curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L); 469 | curl_easy_setopt(hnd, CURLOPT_URL, URL); 470 | curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L); 471 | curl_easy_setopt(hnd, CURLOPT_USERAGENT, "Mozilla/5.0 (Nintendo 3DS; U; ; en) AppleWebKit/536.30 (KHTML, like Gecko) CTGP-7/1.0 CTGP-7/1.0"); 472 | curl_easy_setopt(hnd, CURLOPT_FOLLOWLOCATION, 1L); 473 | curl_easy_setopt(hnd, CURLOPT_ACCEPT_ENCODING, "gzip"); 474 | curl_easy_setopt(hnd, CURLOPT_FAILONERROR, 1L); 475 | curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L); 476 | curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2TLS); 477 | curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, handle_data); 478 | curl_easy_setopt(hnd, CURLOPT_ERRORBUFFER, CURL_lastErrorCode); 479 | curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); 480 | curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); 481 | curl_easy_setopt(hnd, CURLOPT_STDERR, stdout); 482 | 483 | CURL_lastErrorCode[0] = 0; 484 | CURLcode cres = curl_easy_perform(hnd); 485 | curl_easy_cleanup(hnd); 486 | 487 | if (cres != CURLE_OK) { 488 | retcode = cres; 489 | goto exit; 490 | } 491 | 492 | str_result_buf[str_result_written] = '\0'; 493 | *out = str_result_buf; 494 | 495 | exit: 496 | socExit(); 497 | 498 | if (socubuf) { 499 | free(socubuf); 500 | } 501 | 502 | str_result_buf = NULL; 503 | str_result_written = 0; 504 | str_result_sz = 0; 505 | 506 | EnableSleep(); 507 | 508 | return retcode; 509 | } 510 | 511 | static void restorepayloadsdir() { 512 | remove("/luma/payloads/SafeB9SInstaller.firm"); 513 | rmdir("/luma/payloads"); 514 | renameDir("/luma/payloado", "/luma/payloads"); 515 | } 516 | 517 | u64 ezB9SPerform() { 518 | clearTop(); 519 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "EzB9SUpdater"); 520 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Preparing files..."); 521 | updateUI(); 522 | 523 | deleteDirectory("/ezb9stemp"); 524 | 525 | char* outJsonConfig = NULL; 526 | // This uses a dynamic link, so that the URL to the config json can be changed. 527 | u32 ret = downloadString(EZB9S_CONFIG_LINK, &outJsonConfig); 528 | if (ret) { 529 | if (outJsonConfig) free(outJsonConfig); 530 | return (1ULL << 32) | ret; 531 | } 532 | 533 | if (createDir("/ezb9stemp")) { 534 | if (outJsonConfig) free(outJsonConfig); 535 | sprintf(CURL_lastErrorCode, "Failed to create /ezb9stemp"); 536 | return (2ULL << 32) | ret; 537 | } 538 | 539 | JSON_Value *root_value = json_parse_string(outJsonConfig); 540 | if (json_value_get_type(root_value) != JSONObject) { 541 | json_value_free(root_value); 542 | if (outJsonConfig) free(outJsonConfig); 543 | sprintf(CURL_lastErrorCode, "Invalid JSON config file."); 544 | return (3ULL << 32) | ret; 545 | } 546 | const char* canRun = json_object_get_string(json_value_get_object(root_value), "canrun"); 547 | if (strcmp(canRun, "1") != 0) { 548 | json_value_free(root_value); 549 | if (outJsonConfig) free(outJsonConfig); 550 | return (4ULL << 32) | ret; 551 | } 552 | const char* sb9si = json_object_get_string(json_value_get_object(root_value), "sb9si"); 553 | const char* sb9si_firm = json_object_get_string(json_value_get_object(root_value), "sb9si_firm"); 554 | const char* b9sf = json_object_get_string(json_value_get_object(root_value), "b9sf"); 555 | const char* b9sf_firm = json_object_get_string(json_value_get_object(root_value), "b9sf_firm"); 556 | const char* b9sf_sha = json_object_get_string(json_value_get_object(root_value), "b9sf_sha"); 557 | if (!sb9si || !sb9si_firm || !b9sf || !b9sf_firm || !b9sf_sha) 558 | { 559 | json_value_free(root_value); 560 | if (outJsonConfig) free(outJsonConfig); 561 | sprintf(CURL_lastErrorCode, "Invalid JSON config file."); 562 | return (5ULL << 32) | ret; 563 | } 564 | 565 | clearTop(); 566 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "EzB9SUpdater"); 567 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Downloading files..."); 568 | updateUI(); 569 | 570 | fileDownCnt = 1; 571 | totFileDownCnt = 2; 572 | strcpy(updatingVer, "EzB9SUpdater"); 573 | ret = downloadFile(sb9si, "/ezb9stemp/sb9si.zip"); 574 | if (ret) { 575 | json_value_free(root_value); 576 | if (outJsonConfig) free(outJsonConfig); 577 | return (6ULL << 32) | ret; 578 | } 579 | 580 | fileDownCnt = 2; 581 | totFileDownCnt = 2; 582 | ret = downloadFile(b9sf, "/ezb9stemp/b9sf.zip"); 583 | if (ret) { 584 | json_value_free(root_value); 585 | if (outJsonConfig) free(outJsonConfig); 586 | return (7ULL << 32) | ret; 587 | } 588 | 589 | clearTop(); 590 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "EzB9SUpdater"); 591 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Extracting files..."); 592 | updateUI(); 593 | 594 | Zip* b9sf_zip = ZipOpen("/ezb9stemp/b9sf.zip"); 595 | if (!b9sf_zip) { 596 | json_value_free(root_value); 597 | if (outJsonConfig) free(outJsonConfig); 598 | sprintf(CURL_lastErrorCode, "Failed to open b9sf.zip"); 599 | return (8ULL << 32) | ret; 600 | } 601 | 602 | ZipFile* b9sf_firm_data = ZipFileRead(b9sf_zip, b9sf_firm, NULL); 603 | if (!b9sf_firm_data || !b9sf_firm_data->data) { 604 | json_value_free(root_value); 605 | if (outJsonConfig) free(outJsonConfig); 606 | ZipClose(b9sf_zip); 607 | sprintf(CURL_lastErrorCode, "Failed to find \"%s\" in zip file", b9sf_firm); 608 | return (9ULL << 32) | ret; 609 | } 610 | FILE* b9sf_firm_file = fopen_mkdir("/boot9strap/boot9strap.firm", "w"); 611 | if (!b9sf_firm_file) { 612 | json_value_free(root_value); 613 | if (outJsonConfig) free(outJsonConfig); 614 | ZipFileFree(b9sf_firm_data); 615 | ZipClose(b9sf_zip); 616 | sprintf(CURL_lastErrorCode, "Failed to open output file"); 617 | return (0xAULL << 32) | ret; 618 | } 619 | if (fwrite(b9sf_firm_data->data, 1, b9sf_firm_data->size, b9sf_firm_file) != b9sf_firm_data->size) { 620 | json_value_free(root_value); 621 | if (outJsonConfig) free(outJsonConfig); 622 | ZipFileFree(b9sf_firm_data); 623 | ZipClose(b9sf_zip); 624 | fclose(b9sf_firm_file); 625 | sprintf(CURL_lastErrorCode, "Failed to write output file"); 626 | return (0xBULL << 32) | ret; 627 | } 628 | ZipFileFree(b9sf_firm_data); 629 | fclose(b9sf_firm_file); 630 | 631 | ZipFile* b9sf_sha_data = ZipFileRead(b9sf_zip, b9sf_sha, NULL); 632 | if (!b9sf_sha_data || !b9sf_sha_data->data) { 633 | json_value_free(root_value); 634 | if (outJsonConfig) free(outJsonConfig); 635 | ZipClose(b9sf_zip); 636 | sprintf(CURL_lastErrorCode, "Failed to find \"%s\" in zip file", b9sf_sha); 637 | return (0xCULL << 32) | ret; 638 | } 639 | FILE* b9sf_sha_file = fopen_mkdir("/boot9strap/boot9strap.firm.sha", "w"); 640 | if (!b9sf_sha_file) { 641 | json_value_free(root_value); 642 | if (outJsonConfig) free(outJsonConfig); 643 | ZipFileFree(b9sf_sha_data); 644 | ZipClose(b9sf_zip); 645 | sprintf(CURL_lastErrorCode, "Failed to open output file"); 646 | return (0xDULL << 32) | ret; 647 | } 648 | if (fwrite(b9sf_sha_data->data, 1, b9sf_sha_data->size, b9sf_sha_file) != b9sf_sha_data->size) { 649 | json_value_free(root_value); 650 | if (outJsonConfig) free(outJsonConfig); 651 | ZipFileFree(b9sf_sha_data); 652 | ZipClose(b9sf_zip); 653 | fclose(b9sf_sha_file); 654 | sprintf(CURL_lastErrorCode, "Failed to write output file"); 655 | return (0xEULL << 32) | ret; 656 | } 657 | ZipFileFree(b9sf_sha_data); 658 | fclose(b9sf_sha_file); 659 | ZipClose(b9sf_zip); 660 | 661 | renameDir("/luma/payloads", "/luma/payloado"); 662 | Zip* sb9si_zip = ZipOpen("/ezb9stemp/sb9si.zip"); 663 | if (!sb9si_zip) { 664 | json_value_free(root_value); 665 | if (outJsonConfig) free(outJsonConfig); 666 | restorepayloadsdir(); 667 | sprintf(CURL_lastErrorCode, "Failed to open sb9si.zip"); 668 | return (0xFULL << 32) | ret; 669 | } 670 | ZipFile* sb9si_data = ZipFileRead(sb9si_zip, sb9si_firm, NULL); 671 | if (!sb9si_data || !sb9si_data->data) { 672 | json_value_free(root_value); 673 | if (outJsonConfig) free(outJsonConfig); 674 | ZipClose(sb9si_zip); 675 | restorepayloadsdir(); 676 | sprintf(CURL_lastErrorCode, "Failed to find \"%s\" in zip file", sb9si_firm); 677 | return (0x10ULL << 32) | ret; 678 | } 679 | FILE* sb9si_file = fopen_mkdir("/luma/payloads/SafeB9SInstaller.firm", "w"); 680 | if (!sb9si_file) { 681 | json_value_free(root_value); 682 | if (outJsonConfig) free(outJsonConfig); 683 | ZipFileFree(sb9si_data); 684 | ZipClose(sb9si_zip); 685 | restorepayloadsdir(); 686 | sprintf(CURL_lastErrorCode, "Failed to open output file"); 687 | return (0x11ULL << 32) | ret; 688 | } 689 | if (fwrite(sb9si_data->data, 1, sb9si_data->size, sb9si_file) != sb9si_data->size) { 690 | json_value_free(root_value); 691 | if (outJsonConfig) free(outJsonConfig); 692 | ZipFileFree(sb9si_data); 693 | ZipClose(sb9si_zip); 694 | fclose(sb9si_file); 695 | restorepayloadsdir(); 696 | sprintf(CURL_lastErrorCode, "Failed to write output file"); 697 | return (0x12ULL << 32) | ret; 698 | } 699 | ZipFileFree(sb9si_data); 700 | fclose(sb9si_file); 701 | ZipClose(sb9si_zip); 702 | 703 | json_value_free(root_value); 704 | if (outJsonConfig) free(outJsonConfig); 705 | return 0; 706 | } 707 | 708 | void ezB9SCleanup() { 709 | clearTop(); 710 | newAppTop(DEFAULT_COLOR, BOLD | MEDIUM | CENTER, "EzB9SUpdater"); 711 | newAppTop(DEFAULT_COLOR, MEDIUM | CENTER, "Cleaning up files..."); 712 | updateUI(); 713 | deleteDirectory("/ezb9stemp"); 714 | restorepayloadsdir(); 715 | // Keep boot9strap firm files 716 | } -------------------------------------------------------------------------------- /LICENSE_lpp3ds: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /source/Archives.c: -------------------------------------------------------------------------------- 1 | /*----------------------------------------------------------------------------------------------------------------------# 2 | #-----------------------------------------------------------------------------------------------------------------------# 3 | #------ This File is Part Of : ----------------------------------------------------------------------------------------# 4 | #------- _ ------------------- ______ _ --------------------------------------------------------------------------# 5 | #------ | | ------------------- (_____ \ | | --------------------------------------------------------------------------# 6 | #------ | | --- _ _ ____ _____) )| | ____ _ _ ____ ____ ----------------------------------------------# 7 | #------ | | --- | | | | / _ | | ____/ | | / _ || | | | / _ ) / ___) ----------------------------------------------# 8 | #------ | |_____| |_| |( ( | | | | | |( ( | || |_| |( (/ / | | --------------------------------------------------# 9 | #------ |_______)\____| \_||_| |_| |_| \_||_| \__ | \____)|_| --------------------------------------------------# 10 | #------------------------------------------------- (____/ -------------------------------------------------------------# 11 | #------------------------ ______ _ -------------------------------------------------------------------------------# 12 | #------------------------ (_____ \ | | -------------------------------------------------------------------------------# 13 | #------------------------ _____) )| | _ _ ___ ------------------------------------------------------------------# 14 | #------------------------ | ____/ | || | | | /___) ------------------------------------------------------------------# 15 | #------------------------ | | | || |_| ||___ | ------------------------------------------------------------------# 16 | #------------------------ |_| |_| \____|(___/ ------------------------------------------------------------------# 17 | #-----------------------------------------------------------------------------------------------------------------------# 18 | #-----------------------------------------------------------------------------------------------------------------------# 19 | #- Licensed under the GPL License --------------------------------------------------------------------------------------# 20 | #-----------------------------------------------------------------------------------------------------------------------# 21 | #- Copyright (c) Nanni ---------------------------------------------------------------------------# 22 | #- Copyright (c) Rinnegatamante -------------------------------------------------------------# 23 | #-----------------------------------------------------------------------------------------------------------------------# 24 | #-----------------------------------------------------------------------------------------------------------------------# 25 | #- Credits : -----------------------------------------------------------------------------------------------------------# 26 | #-----------------------------------------------------------------------------------------------------------------------# 27 | #- Smealum for ctrulib -------------------------------------------------------------------------------------------------# 28 | #- StapleButter for debug font -----------------------------------------------------------------------------------------# 29 | #- Lode Vandevenne for lodepng -----------------------------------------------------------------------------------------# 30 | #- Sean Barrett for stb_truetype ---------------------------------------------------------------------------------------# 31 | #- Special thanks to Aurelio for testing, bug-fixing and various help with codes and implementations -------------------# 32 | #-----------------------------------------------------------------------------------------------------------------------*/ 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | 47 | #include "Archives.h" 48 | 49 | /****************************************************************************** 50 | ** UnZip ********************************************************************* 51 | *******************************************************************************/ 52 | 53 | #define _ZIP_BUFFER_SIZE (16384) 54 | #define _ZIP_MAX_FILENAME_SIZE (256) 55 | #define _ZIP_CENTRALDIR_ITEM_SIZE (0x2e) 56 | #define _ZIP_LOCALHEADER_SIZE (0x1e) 57 | 58 | #define _ZIP_OK (0) 59 | #define _ZIP_EOF_LIST (-100) 60 | #define _ZIP_ERRNO (Z_ERRNO) 61 | #define _ZIP_EOF (0) 62 | #define _ZIP_PARAM_ERROR (-102) 63 | #define _ZIP_BAD_FILE (-103) 64 | #define _ZIP_INTERNAL_ERROR (-104) 65 | #define _ZIP_CRC_ERROR (-105) 66 | 67 | #define CRC32(c, b) ((*(crc32tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) 68 | #define zdecode(pkeys, crc32tab, c) (ZipUpdateKeys(pkeys, crc32tab, c ^= ZipDecryptByte(pkeys, crc32tab))) 69 | #define _ZIP_BUF_READ_COMMENT (0x400) 70 | 71 | #define TMPBUF_SIZE 1048576 72 | 73 | typedef struct 74 | { 75 | unsigned long version; 76 | unsigned long versionneeded; 77 | unsigned long flag; 78 | unsigned long compressionmethod; 79 | unsigned long dosdate; 80 | unsigned long crc; 81 | unsigned long compressedsize; 82 | unsigned long uncompressedsize; 83 | unsigned long filenamesize; 84 | unsigned long fileextrasize; 85 | unsigned long filecommentsize; 86 | unsigned long disknumstart; 87 | unsigned long internalfileattr; 88 | unsigned long externalfileattr; 89 | 90 | } zipFileInfo; 91 | 92 | typedef struct 93 | { 94 | unsigned long currentfileoffset; 95 | 96 | } zipFileInternalInfo; 97 | 98 | typedef struct 99 | { 100 | char *buffer; 101 | z_stream stream; 102 | unsigned long posinzip; 103 | unsigned long streaminitialised; 104 | unsigned long localextrafieldoffset; 105 | unsigned int localextrafieldsize; 106 | unsigned long localextrafieldpos; 107 | unsigned long crc32; 108 | unsigned long crc32wait; 109 | unsigned long restreadcompressed; 110 | unsigned long restreaduncompressed; 111 | FILE* file; 112 | unsigned long compressionmethod; 113 | unsigned long bytebeforezip; 114 | 115 | } zipFileInfoInternal; 116 | 117 | typedef struct 118 | { 119 | unsigned long countentries; 120 | unsigned long commentsize; 121 | 122 | } zipGlobalInfo; 123 | 124 | typedef struct 125 | { 126 | FILE* file; 127 | zipGlobalInfo gi; 128 | unsigned long bytebeforezip; 129 | unsigned long numfile; 130 | unsigned long posincentraldir; 131 | unsigned long currentfileok; 132 | unsigned long centralpos; 133 | unsigned long centraldirsize; 134 | unsigned long centraldiroffset; 135 | zipFileInfo currentfileinfo; 136 | zipFileInternalInfo currentfileinfointernal; 137 | zipFileInfoInternal* currentzipfileinfo; 138 | int encrypted; 139 | unsigned long keys[3]; 140 | const unsigned long* crc32tab; 141 | 142 | } _zip; 143 | 144 | void *MallocPatch(int size) 145 | { 146 | void *ptr = malloc(size); 147 | return ptr; 148 | } 149 | 150 | void FreePatch(void *ptr) 151 | { 152 | if(ptr != NULL) 153 | free(ptr); 154 | } 155 | 156 | static int ZitByte(FILE *file, int *pi) 157 | { 158 | unsigned char c; 159 | 160 | int err = fread(&c, 1, 1, file); 161 | 162 | if(err == 1) 163 | { 164 | *pi = (int)c; 165 | return _ZIP_OK; 166 | } 167 | else 168 | { 169 | if(ferror(file)) 170 | return _ZIP_ERRNO; 171 | else 172 | return _ZIP_EOF; 173 | } 174 | } 175 | 176 | static int ZitShort(FILE *file, unsigned long *px) 177 | { 178 | unsigned long x; 179 | int i = 0; 180 | int err; 181 | 182 | err = ZitByte(file, &i); 183 | x = (unsigned long)i; 184 | 185 | if(err == _ZIP_OK) 186 | err = ZitByte(file, &i); 187 | 188 | x += ((unsigned long)i)<<8; 189 | 190 | if(err == _ZIP_OK) 191 | *px = x; 192 | else 193 | *px = 0; 194 | 195 | return err; 196 | } 197 | 198 | static int ZitLong(FILE *file, unsigned long *px) 199 | { 200 | unsigned long x; 201 | int i = 0; 202 | int err; 203 | 204 | err = ZitByte(file, &i); 205 | x = (unsigned long)i; 206 | 207 | if(err == _ZIP_OK) 208 | err = ZitByte(file, &i); 209 | 210 | x += ((unsigned long)i)<<8; 211 | 212 | if(err == _ZIP_OK) 213 | err = ZitByte(file,&i); 214 | 215 | x += ((unsigned long)i)<<16; 216 | 217 | if(err == _ZIP_OK) 218 | err = ZitByte(file,&i); 219 | 220 | x += ((unsigned long)i)<<24; 221 | 222 | if(err == _ZIP_OK) 223 | *px = x; 224 | else 225 | *px = 0; 226 | 227 | return err; 228 | } 229 | 230 | static int ZipDecryptByte(unsigned long* pkeys, const unsigned long* crc32tab) 231 | { 232 | (void)crc32tab; 233 | 234 | unsigned temp; 235 | 236 | temp = ((unsigned)(*(pkeys + 2)) & 0xffff) | 2; 237 | 238 | return (int)(((temp * (temp ^ 1)) >> 8) & 0xff); 239 | } 240 | 241 | static int ZipUpdateKeys(unsigned long* pkeys, const unsigned long* crc32tab, int c) 242 | { 243 | (*(pkeys + 0)) = CRC32((*(pkeys + 0)), c); 244 | (*(pkeys + 1)) += (*(pkeys + 0)) & 0xff; 245 | (*(pkeys + 1)) = (*(pkeys + 1)) * 134775813L + 1; 246 | 247 | { 248 | register int keyshift = (int)((*(pkeys + 1)) >> 24); 249 | (*(pkeys + 2)) = CRC32((*(pkeys + 2)), keyshift); 250 | } 251 | 252 | return c; 253 | } 254 | 255 | static void ZipInitKeys(const char* passwd, unsigned long* pkeys, const unsigned long* crc32tab) 256 | { 257 | *(pkeys + 0) = 305419896L; 258 | *(pkeys + 1) = 591751049L; 259 | *(pkeys + 2) = 878082192L; 260 | 261 | while(*passwd != '\0') 262 | { 263 | ZipUpdateKeys(pkeys, crc32tab, (int)*passwd); 264 | passwd++; 265 | } 266 | } 267 | 268 | static unsigned long ZipLocateCentralDir(FILE *file) 269 | { 270 | unsigned char* buf; 271 | unsigned long usizefile; 272 | unsigned long ubackread; 273 | unsigned long umaxback = 0xffff; 274 | unsigned long uposfound = 0; 275 | 276 | if(fseek(file, 0, SEEK_END) != 0) 277 | return 0; 278 | 279 | usizefile = ftell(file); 280 | 281 | if(umaxback > usizefile) 282 | umaxback = usizefile; 283 | 284 | buf = (unsigned char*)MallocPatch(_ZIP_BUF_READ_COMMENT + 4); 285 | 286 | if(buf == NULL) 287 | return 0; 288 | 289 | ubackread = 4; 290 | 291 | while(ubackread < umaxback) 292 | { 293 | unsigned long ureadsize, ureadpos; 294 | int i; 295 | 296 | if(ubackread + _ZIP_BUF_READ_COMMENT > umaxback) 297 | ubackread = umaxback; 298 | else 299 | ubackread += _ZIP_BUF_READ_COMMENT; 300 | 301 | ureadpos = usizefile - ubackread; 302 | 303 | ureadsize = ((_ZIP_BUF_READ_COMMENT + 4) < (usizefile - ureadpos)) ? (_ZIP_BUF_READ_COMMENT+ 4) : (usizefile - ureadpos); 304 | 305 | if(fseek(file, ureadpos, SEEK_SET) != 0) 306 | break; 307 | 308 | if(fread(buf, (unsigned int)ureadsize, 1, file) != 1) 309 | break; 310 | 311 | for(i = (int)ureadsize - 3; (i--) > 0;) 312 | 313 | if(((*(buf + i)) == 0x50) && ((*(buf + i + 1)) == 0x4b) && ((*(buf + i + 2)) == 0x05) && ((*(buf + i + 3)) == 0x06)) 314 | { 315 | uposfound = ureadpos + i; 316 | break; 317 | } 318 | 319 | if (uposfound != 0) 320 | break; 321 | } 322 | 323 | FreePatch(buf); 324 | 325 | return uposfound; 326 | } 327 | 328 | static int ZitZipFileInfoInternal(Zip* file, zipFileInfo *pfileinfo, zipFileInternalInfo *pfileinfointernal, char *filename, unsigned long filenamebuffersize, void *extrafield, unsigned long extrafieldbuffersize, char *comment, unsigned long commentbuffersize) 329 | { 330 | _zip* s; 331 | zipFileInfo fileinfo; 332 | zipFileInternalInfo fileinfointernal; 333 | int err = _ZIP_OK; 334 | unsigned long umagic; 335 | long lseek = 0; 336 | 337 | if(file == NULL) 338 | return _ZIP_PARAM_ERROR; 339 | 340 | s = (_zip*)file; 341 | 342 | if(fseek(s->file, s->posincentraldir + s->bytebeforezip, SEEK_SET) != 0) 343 | err = _ZIP_ERRNO; 344 | 345 | if(err == _ZIP_OK) 346 | { 347 | if(ZitLong(s->file, &umagic) != _ZIP_OK) 348 | err = _ZIP_ERRNO; 349 | else if(umagic != 0x02014b50) 350 | err = _ZIP_BAD_FILE; 351 | } 352 | 353 | if (ZitShort(s->file, &fileinfo.version) != _ZIP_OK) 354 | err = _ZIP_ERRNO; 355 | 356 | if (ZitShort(s->file, &fileinfo.versionneeded) != _ZIP_OK) 357 | err = _ZIP_ERRNO; 358 | 359 | if (ZitShort(s->file, &fileinfo.flag) != _ZIP_OK) 360 | err = _ZIP_ERRNO; 361 | 362 | if (ZitShort(s->file, &fileinfo.compressionmethod) != _ZIP_OK) 363 | err = _ZIP_ERRNO; 364 | 365 | if (ZitLong(s->file, &fileinfo.dosdate) != _ZIP_OK) 366 | err = _ZIP_ERRNO; 367 | 368 | if (ZitLong(s->file, &fileinfo.crc) != _ZIP_OK) 369 | err = _ZIP_ERRNO; 370 | 371 | if (ZitLong(s->file, &fileinfo.compressedsize) != _ZIP_OK) 372 | err = _ZIP_ERRNO; 373 | 374 | if (ZitLong(s->file, &fileinfo.uncompressedsize) != _ZIP_OK) 375 | err = _ZIP_ERRNO; 376 | 377 | if (ZitShort(s->file, &fileinfo.filenamesize) != _ZIP_OK) 378 | err = _ZIP_ERRNO; 379 | 380 | if (ZitShort(s->file, &fileinfo.fileextrasize) != _ZIP_OK) 381 | err = _ZIP_ERRNO; 382 | 383 | if (ZitShort(s->file, &fileinfo.filecommentsize) != _ZIP_OK) 384 | err = _ZIP_ERRNO; 385 | 386 | if (ZitShort(s->file, &fileinfo.disknumstart) != _ZIP_OK) 387 | err = _ZIP_ERRNO; 388 | 389 | if (ZitShort(s->file, &fileinfo.internalfileattr) != _ZIP_OK) 390 | err = _ZIP_ERRNO; 391 | 392 | if (ZitLong(s->file, &fileinfo.externalfileattr) != _ZIP_OK) 393 | err = _ZIP_ERRNO; 394 | 395 | if (ZitLong(s->file, &fileinfointernal.currentfileoffset) != _ZIP_OK) 396 | err = _ZIP_ERRNO; 397 | 398 | lseek += fileinfo.filenamesize; 399 | 400 | if((err == _ZIP_OK) && (filename != NULL)) 401 | { 402 | unsigned long usizeread; 403 | 404 | if(fileinfo.filenamesize < filenamebuffersize) 405 | { 406 | *(filename + fileinfo.filenamesize) = '\0'; 407 | usizeread = fileinfo.filenamesize; 408 | } 409 | else 410 | usizeread = filenamebuffersize; 411 | 412 | if((fileinfo.filenamesize > 0) && (filenamebuffersize > 0)) 413 | { 414 | if(fread(filename, (unsigned int)usizeread, 1, s->file) != 1) 415 | err = _ZIP_ERRNO; 416 | } 417 | 418 | lseek -= usizeread; 419 | } 420 | 421 | if((err == _ZIP_OK) && (extrafield != NULL)) 422 | { 423 | unsigned long usizeread; 424 | 425 | if (fileinfo.fileextrasize < extrafieldbuffersize) 426 | usizeread = fileinfo.fileextrasize; 427 | else 428 | usizeread = extrafieldbuffersize; 429 | 430 | if(lseek != 0) 431 | { 432 | if(fseek(s->file, lseek, SEEK_CUR) == 0) 433 | lseek = 0; 434 | else 435 | err = _ZIP_ERRNO; 436 | } 437 | 438 | if((fileinfo.fileextrasize > 0) && (extrafieldbuffersize > 0)) 439 | { 440 | if(fread(extrafield, (unsigned int)usizeread, 1, s->file) != 1) 441 | err = _ZIP_ERRNO; 442 | } 443 | 444 | lseek += fileinfo.fileextrasize - usizeread; 445 | } 446 | else 447 | lseek += fileinfo.fileextrasize; 448 | 449 | if((err == _ZIP_OK) && (comment != NULL)) 450 | { 451 | unsigned long usizeread; 452 | 453 | if(fileinfo.filecommentsize < commentbuffersize) 454 | { 455 | *(comment + fileinfo.filecommentsize) = '\0'; 456 | usizeread = fileinfo.filecommentsize; 457 | } 458 | else 459 | usizeread = commentbuffersize; 460 | 461 | if(lseek != 0) 462 | { 463 | if(fseek(s->file, lseek, SEEK_CUR) == 0) 464 | lseek = 0; 465 | else 466 | err = _ZIP_ERRNO; 467 | } 468 | 469 | if((fileinfo.filecommentsize > 0) && (commentbuffersize > 0)) 470 | { 471 | if(fread(comment, (unsigned int)usizeread, 1, s->file) != 1) 472 | err = _ZIP_ERRNO; 473 | } 474 | 475 | lseek += fileinfo.filecommentsize - usizeread; 476 | } 477 | else 478 | lseek += fileinfo.filecommentsize; 479 | 480 | if((err == _ZIP_OK) && (pfileinfo != NULL)) 481 | *pfileinfo = fileinfo; 482 | 483 | if((err == _ZIP_OK) && (pfileinfointernal != NULL)) 484 | *pfileinfointernal = fileinfointernal; 485 | 486 | return err; 487 | } 488 | 489 | static int ZitGlobalInfo(Zip* file, zipGlobalInfo *zipinfo) 490 | { 491 | _zip* s; 492 | 493 | if(file == NULL) 494 | return _ZIP_PARAM_ERROR; 495 | 496 | s = (_zip*)file; 497 | 498 | *zipinfo = s->gi; 499 | 500 | return _ZIP_OK; 501 | } 502 | 503 | static int ZipGotoFirstFile(Zip* file) 504 | { 505 | int err = _ZIP_OK; 506 | 507 | _zip* s; 508 | 509 | if(file == NULL) 510 | return _ZIP_PARAM_ERROR; 511 | 512 | s = (_zip*)file; 513 | s->posincentraldir = s->centraldiroffset; 514 | s->numfile = 0; 515 | err = ZitZipFileInfoInternal(file, &s->currentfileinfo, &s->currentfileinfointernal, NULL, 0, NULL, 0, NULL, 0); 516 | s->currentfileok = (err == _ZIP_OK); 517 | 518 | return err; 519 | } 520 | 521 | static int ZipCloseCurrentFile(Zip* file) 522 | { 523 | int err = _ZIP_OK; 524 | 525 | _zip* s; 526 | zipFileInfoInternal *pfileinzipreadinfo; 527 | 528 | if(file == NULL) 529 | return _ZIP_PARAM_ERROR; 530 | 531 | s = (_zip*)file; 532 | pfileinzipreadinfo = s->currentzipfileinfo; 533 | 534 | if(pfileinzipreadinfo == NULL) 535 | return _ZIP_PARAM_ERROR; 536 | 537 | if(pfileinzipreadinfo->restreaduncompressed == 0) 538 | { 539 | if(pfileinzipreadinfo->crc32 != pfileinzipreadinfo->crc32wait) 540 | err = _ZIP_CRC_ERROR; 541 | } 542 | 543 | FreePatch(pfileinzipreadinfo->buffer); 544 | pfileinzipreadinfo->buffer = NULL; 545 | 546 | if(pfileinzipreadinfo->streaminitialised) 547 | inflateEnd(&pfileinzipreadinfo->stream); 548 | 549 | pfileinzipreadinfo->streaminitialised = 0; 550 | 551 | FreePatch(pfileinzipreadinfo); 552 | 553 | s->currentzipfileinfo = NULL; 554 | 555 | return err; 556 | } 557 | 558 | static int ZitCurrentFileInfo(Zip* file, zipFileInfo *pfileinfo, char *filename, unsigned long filenamebuffersize, void *extrafield, unsigned long extrafieldbuffersize, char *comment, unsigned long commentbuffersize) 559 | { 560 | return ZitZipFileInfoInternal(file, pfileinfo, NULL, filename, filenamebuffersize, extrafield, extrafieldbuffersize, comment, commentbuffersize); 561 | } 562 | 563 | static int ZipGotoNextFile(Zip* file) 564 | { 565 | _zip* s; 566 | int err; 567 | 568 | if(file == NULL) 569 | return _ZIP_PARAM_ERROR; 570 | 571 | s = (_zip*)file; 572 | 573 | if(!s->currentfileok) 574 | return _ZIP_EOF_LIST; 575 | 576 | if(s->numfile + 1 == s->gi.countentries) 577 | return _ZIP_EOF_LIST; 578 | 579 | s->posincentraldir += _ZIP_CENTRALDIR_ITEM_SIZE + s->currentfileinfo.filenamesize + s->currentfileinfo.fileextrasize + s->currentfileinfo.filecommentsize ; 580 | s->numfile++; 581 | 582 | err = ZitZipFileInfoInternal(file, &s->currentfileinfo, &s->currentfileinfointernal, NULL, 0, NULL, 0, NULL, 0); 583 | 584 | s->currentfileok = (err == _ZIP_OK); 585 | 586 | return err; 587 | } 588 | 589 | static int ZipLocateFile(Zip* file, const char *filename, int casesensitive) 590 | { 591 | (void)casesensitive; 592 | 593 | _zip* s; 594 | int err; 595 | 596 | unsigned long numfilesaved; 597 | unsigned long posincentraldirsaved; 598 | 599 | if(file == NULL) 600 | return _ZIP_PARAM_ERROR; 601 | 602 | if(strlen(filename) >= _ZIP_MAX_FILENAME_SIZE) 603 | return _ZIP_PARAM_ERROR; 604 | 605 | s = (_zip*)file; 606 | 607 | if(!s->currentfileok) 608 | return _ZIP_EOF_LIST; 609 | 610 | numfilesaved = s->numfile; 611 | posincentraldirsaved = s->posincentraldir; 612 | 613 | err = ZipGotoFirstFile(file); 614 | 615 | char currentfilename[_ZIP_MAX_FILENAME_SIZE + 1]; 616 | 617 | while(err == _ZIP_OK) 618 | { 619 | ZitCurrentFileInfo(file,NULL, currentfilename, sizeof(currentfilename) - 1, NULL, 0, NULL, 0); 620 | 621 | if(strcmp(currentfilename, filename) == 0) 622 | return _ZIP_OK; 623 | 624 | err = ZipGotoNextFile(file); 625 | } 626 | 627 | s->numfile = numfilesaved; 628 | s->posincentraldir = posincentraldirsaved; 629 | 630 | return err; 631 | } 632 | 633 | static int ZipCheckCurrentFileCoherencyHeader(_zip *s, unsigned int *pisizevar, unsigned long *poffsetstaticextrafield, unsigned int *psizestaticextrafield) 634 | { 635 | unsigned long umagic, udata, uflags; 636 | unsigned long filenamesize; 637 | unsigned long sizeextrafield; 638 | int err = _ZIP_OK; 639 | 640 | *pisizevar = 0; 641 | *poffsetstaticextrafield = 0; 642 | *psizestaticextrafield = 0; 643 | 644 | if(fseek(s->file, s->currentfileinfointernal.currentfileoffset + s->bytebeforezip, SEEK_SET) != 0) 645 | return _ZIP_ERRNO; 646 | 647 | if(err == _ZIP_OK) 648 | { 649 | if(ZitLong(s->file, &umagic) != _ZIP_OK) 650 | err = _ZIP_ERRNO; 651 | else if(umagic != 0x04034b50) 652 | err = _ZIP_BAD_FILE; 653 | } 654 | 655 | if(ZitShort(s->file, &udata) != _ZIP_OK) 656 | err = _ZIP_ERRNO; 657 | 658 | if(ZitShort(s->file, &uflags) != _ZIP_OK) 659 | err = _ZIP_ERRNO; 660 | 661 | if(ZitShort(s->file, &udata) != _ZIP_OK) 662 | err = _ZIP_ERRNO; 663 | else if((err == _ZIP_OK) && (udata != s->currentfileinfo.compressionmethod)) 664 | err = _ZIP_BAD_FILE; 665 | 666 | if((err == _ZIP_OK) && (s->currentfileinfo.compressionmethod != 0) && (s->currentfileinfo.compressionmethod != Z_DEFLATED)) 667 | err = _ZIP_BAD_FILE; 668 | 669 | if(ZitLong(s->file, &udata) != _ZIP_OK) 670 | err = _ZIP_ERRNO; 671 | 672 | if(ZitLong(s->file, &udata) != _ZIP_OK) 673 | err = _ZIP_ERRNO; 674 | else if((err == _ZIP_OK) && (udata != s->currentfileinfo.crc) && ((uflags & 8) == 0)) 675 | err = _ZIP_BAD_FILE; 676 | 677 | if(ZitLong(s->file, &udata) != _ZIP_OK) 678 | err = _ZIP_ERRNO; 679 | else if((err == _ZIP_OK) && (udata != s->currentfileinfo.compressedsize) && ((uflags & 8) == 0)) 680 | err = _ZIP_BAD_FILE; 681 | 682 | if(ZitLong(s->file, &udata) != _ZIP_OK) 683 | err = _ZIP_ERRNO; 684 | else if((err == _ZIP_OK) && (udata != s->currentfileinfo.uncompressedsize) && ((uflags & 8) == 0)) 685 | err = _ZIP_BAD_FILE; 686 | 687 | if(ZitShort(s->file, &filenamesize) != _ZIP_OK) 688 | err = _ZIP_ERRNO; 689 | else if((err==_ZIP_OK) && (filenamesize != s->currentfileinfo.filenamesize)) 690 | err = _ZIP_BAD_FILE; 691 | 692 | *pisizevar += (unsigned int)filenamesize; 693 | 694 | if(ZitShort(s->file, &sizeextrafield) != _ZIP_OK) 695 | err = _ZIP_ERRNO; 696 | 697 | *poffsetstaticextrafield = s->currentfileinfointernal.currentfileoffset + _ZIP_LOCALHEADER_SIZE + filenamesize; 698 | *psizestaticextrafield = (unsigned int)sizeextrafield; 699 | *pisizevar += (unsigned int)sizeextrafield; 700 | 701 | return err; 702 | } 703 | 704 | static int ZipOpenCurrentFile(Zip* file, const char *password) 705 | { 706 | int err = _ZIP_OK; 707 | int store; 708 | unsigned int isizevar; 709 | _zip* s; 710 | zipFileInfoInternal* pfileinzipreadinfo; 711 | unsigned long localextrafieldoffset; 712 | unsigned int localextrafieldsize; 713 | 714 | char source[12]; 715 | 716 | if(file == NULL) 717 | return _ZIP_PARAM_ERROR; 718 | 719 | s = (_zip*)file; 720 | 721 | if(!s->currentfileok) 722 | return _ZIP_PARAM_ERROR; 723 | 724 | if(s->currentzipfileinfo != NULL) 725 | ZipCloseCurrentFile(file); 726 | 727 | if(ZipCheckCurrentFileCoherencyHeader(s, &isizevar, &localextrafieldoffset, &localextrafieldsize) != _ZIP_OK) 728 | return _ZIP_BAD_FILE; 729 | 730 | pfileinzipreadinfo = (zipFileInfoInternal*) MallocPatch(sizeof(zipFileInfoInternal)); 731 | 732 | if(pfileinzipreadinfo == NULL) 733 | return _ZIP_INTERNAL_ERROR; 734 | 735 | pfileinzipreadinfo->buffer = (char*)MallocPatch(_ZIP_BUFFER_SIZE); 736 | pfileinzipreadinfo->localextrafieldoffset = localextrafieldoffset; 737 | pfileinzipreadinfo->localextrafieldsize = localextrafieldsize; 738 | pfileinzipreadinfo->localextrafieldpos = 0; 739 | 740 | if(pfileinzipreadinfo->buffer == NULL) 741 | { 742 | FreePatch(pfileinzipreadinfo); 743 | return _ZIP_INTERNAL_ERROR; 744 | } 745 | 746 | pfileinzipreadinfo->streaminitialised = 0; 747 | 748 | if((s->currentfileinfo.compressionmethod != 0) && (s->currentfileinfo.compressionmethod != Z_DEFLATED)) 749 | err = _ZIP_BAD_FILE; 750 | 751 | store = s->currentfileinfo.compressionmethod == 0; 752 | 753 | pfileinzipreadinfo->crc32wait = s->currentfileinfo.crc; 754 | pfileinzipreadinfo->crc32 = 0; 755 | pfileinzipreadinfo->compressionmethod = s->currentfileinfo.compressionmethod; 756 | pfileinzipreadinfo->file = s->file; 757 | pfileinzipreadinfo->bytebeforezip = s->bytebeforezip; 758 | 759 | pfileinzipreadinfo->stream.total_out = 0; 760 | 761 | if(!store) 762 | { 763 | pfileinzipreadinfo->stream.zalloc = (alloc_func)0; 764 | pfileinzipreadinfo->stream.zfree = (free_func)0; 765 | pfileinzipreadinfo->stream.opaque = (voidpf)0; 766 | 767 | err = inflateInit2(&pfileinzipreadinfo->stream, -MAX_WBITS); 768 | 769 | if(err == Z_OK) 770 | pfileinzipreadinfo->streaminitialised = 1; 771 | } 772 | 773 | pfileinzipreadinfo->restreadcompressed = s->currentfileinfo.compressedsize; 774 | pfileinzipreadinfo->restreaduncompressed = s->currentfileinfo.uncompressedsize; 775 | 776 | pfileinzipreadinfo->posinzip = s->currentfileinfointernal.currentfileoffset + _ZIP_LOCALHEADER_SIZE + isizevar; 777 | 778 | pfileinzipreadinfo->stream.avail_in = (unsigned int)0; 779 | 780 | s->currentzipfileinfo = pfileinzipreadinfo; 781 | 782 | if(password != NULL) 783 | { 784 | int i; 785 | s->crc32tab = (const unsigned long*)get_crc_table(); 786 | ZipInitKeys(password, s->keys, s->crc32tab); 787 | 788 | if(fseek(pfileinzipreadinfo->file, s->currentzipfileinfo->posinzip + s->currentzipfileinfo->bytebeforezip, SEEK_SET) != 0) 789 | { 790 | FreePatch(pfileinzipreadinfo->buffer); 791 | FreePatch(pfileinzipreadinfo); 792 | 793 | return _ZIP_INTERNAL_ERROR; 794 | } 795 | 796 | if(fread(source, 1, 12, pfileinzipreadinfo->file) < 12) 797 | { 798 | FreePatch(pfileinzipreadinfo->buffer); 799 | FreePatch(pfileinzipreadinfo); 800 | 801 | return _ZIP_INTERNAL_ERROR; 802 | } 803 | 804 | for(i = 0; i < 12; i++) 805 | zdecode(s->keys, s->crc32tab, source[i]); 806 | 807 | s->currentzipfileinfo->posinzip += 12; 808 | s->encrypted = 1; 809 | } 810 | 811 | return _ZIP_OK; 812 | } 813 | 814 | static int ZipReadCurrentFile(Zip* file, void* buf, unsigned int len) 815 | { 816 | int err = _ZIP_OK; 817 | unsigned int iread = 0; 818 | _zip* s; 819 | zipFileInfoInternal* pfileinzipreadinfo; 820 | 821 | if(file == NULL) 822 | return _ZIP_PARAM_ERROR; 823 | 824 | s = (_zip*)file; 825 | pfileinzipreadinfo = s->currentzipfileinfo; 826 | 827 | if(pfileinzipreadinfo == NULL) 828 | return _ZIP_PARAM_ERROR; 829 | 830 | if((pfileinzipreadinfo->buffer == NULL)) 831 | return _ZIP_EOF_LIST; 832 | 833 | if(len == 0) 834 | return 0; 835 | 836 | pfileinzipreadinfo->stream.next_out = (Bytef*)buf; 837 | 838 | pfileinzipreadinfo->stream.avail_out = (unsigned int)len; 839 | 840 | if(len > pfileinzipreadinfo->restreaduncompressed) 841 | pfileinzipreadinfo->stream.avail_out = (unsigned int)pfileinzipreadinfo->restreaduncompressed; 842 | 843 | while(pfileinzipreadinfo->stream.avail_out > 0) 844 | { 845 | if((pfileinzipreadinfo->stream.avail_in == 0) && (pfileinzipreadinfo->restreadcompressed > 0)) 846 | { 847 | unsigned int ureadthis = _ZIP_BUFFER_SIZE; 848 | 849 | if(pfileinzipreadinfo->restreadcompressed < ureadthis) 850 | ureadthis = (unsigned int)pfileinzipreadinfo->restreadcompressed; 851 | 852 | if(ureadthis == 0) 853 | return _ZIP_EOF; 854 | 855 | if(fseek(pfileinzipreadinfo->file, pfileinzipreadinfo->posinzip + pfileinzipreadinfo->bytebeforezip, SEEK_SET) != 0) 856 | return _ZIP_ERRNO; 857 | 858 | if(fread(pfileinzipreadinfo->buffer, ureadthis, 1, pfileinzipreadinfo->file) != 1) 859 | return _ZIP_ERRNO; 860 | 861 | if(s->encrypted) 862 | { 863 | unsigned int i; 864 | 865 | for(i = 0;i < ureadthis;i++) 866 | pfileinzipreadinfo->buffer[i] = zdecode(s->keys, s->crc32tab, pfileinzipreadinfo->buffer[i]); 867 | } 868 | 869 | pfileinzipreadinfo->posinzip += ureadthis; 870 | 871 | pfileinzipreadinfo->restreadcompressed -= ureadthis; 872 | 873 | pfileinzipreadinfo->stream.next_in = (Bytef*)pfileinzipreadinfo->buffer; 874 | pfileinzipreadinfo->stream.avail_in = (unsigned int)ureadthis; 875 | } 876 | 877 | if(pfileinzipreadinfo->compressionmethod == 0) 878 | { 879 | unsigned int udocopy, i; 880 | 881 | if((pfileinzipreadinfo->stream.avail_in == 0) && (pfileinzipreadinfo->restreadcompressed == 0)) 882 | return (iread == 0) ? _ZIP_EOF : iread; 883 | 884 | if(pfileinzipreadinfo->stream.avail_out < pfileinzipreadinfo->stream.avail_in) 885 | udocopy = pfileinzipreadinfo->stream.avail_out; 886 | else 887 | udocopy = pfileinzipreadinfo->stream.avail_in; 888 | 889 | for(i = 0;i < udocopy; i++) 890 | *(pfileinzipreadinfo->stream.next_out + i) = *(pfileinzipreadinfo->stream.next_in + i); 891 | 892 | pfileinzipreadinfo->crc32 = crc32(pfileinzipreadinfo->crc32, pfileinzipreadinfo->stream.next_out, udocopy); 893 | pfileinzipreadinfo->restreaduncompressed -= udocopy; 894 | pfileinzipreadinfo->stream.avail_in -= udocopy; 895 | pfileinzipreadinfo->stream.avail_out -= udocopy; 896 | pfileinzipreadinfo->stream.next_out += udocopy; 897 | pfileinzipreadinfo->stream.next_in += udocopy; 898 | pfileinzipreadinfo->stream.total_out += udocopy; 899 | iread += udocopy; 900 | } 901 | else 902 | { 903 | unsigned long utotaloutbefore, utotaloutafter; 904 | const Bytef *bufbefore; 905 | unsigned long uoutthis; 906 | int flush = Z_SYNC_FLUSH; 907 | 908 | utotaloutbefore = pfileinzipreadinfo->stream.total_out; 909 | bufbefore = pfileinzipreadinfo->stream.next_out; 910 | 911 | err = inflate(&pfileinzipreadinfo->stream, flush); 912 | 913 | utotaloutafter = pfileinzipreadinfo->stream.total_out; 914 | uoutthis = utotaloutafter - utotaloutbefore; 915 | 916 | pfileinzipreadinfo->crc32 = crc32(pfileinzipreadinfo->crc32, bufbefore, (unsigned int)(uoutthis)); 917 | 918 | pfileinzipreadinfo->restreaduncompressed -= uoutthis; 919 | 920 | iread += (unsigned int)(utotaloutafter - utotaloutbefore); 921 | 922 | if(err == Z_STREAM_END) 923 | return (iread == 0) ? _ZIP_EOF : iread; 924 | 925 | if(err != Z_OK) 926 | break; 927 | } 928 | } 929 | 930 | if(err == Z_OK) 931 | return iread; 932 | 933 | return err; 934 | } 935 | 936 | Zip* ZipOpen(const char *filename) 937 | { 938 | //; 939 | _zip us; 940 | _zip *s; 941 | unsigned long centralpos, ul; 942 | FILE *file; 943 | 944 | unsigned long numberdisk; 945 | unsigned long numberdiskwithCD; 946 | unsigned long numberentryCD; 947 | 948 | int err = _ZIP_OK; 949 | 950 | file = fopen(filename, "rb"); 951 | 952 | if(file == NULL) 953 | return NULL; 954 | 955 | centralpos = ZipLocateCentralDir(file); 956 | 957 | if(centralpos == 0) 958 | err = _ZIP_ERRNO; 959 | 960 | if(fseek(file, centralpos, SEEK_SET) != 0) 961 | err = _ZIP_ERRNO; 962 | 963 | if(ZitLong(file, &ul) != _ZIP_OK) 964 | err = _ZIP_ERRNO; 965 | 966 | if(ZitShort(file, &numberdisk) != _ZIP_OK) 967 | err = _ZIP_ERRNO; 968 | 969 | if(ZitShort(file, &numberdiskwithCD) != _ZIP_OK) 970 | err = _ZIP_ERRNO; 971 | 972 | if(ZitShort(file, &us.gi.countentries) != _ZIP_OK) 973 | err = _ZIP_ERRNO; 974 | 975 | if(ZitShort(file, &numberentryCD) != _ZIP_OK) 976 | err = _ZIP_ERRNO; 977 | 978 | if((numberentryCD != us.gi.countentries) || (numberdiskwithCD != 0) || (numberdisk != 0)) 979 | err = _ZIP_BAD_FILE; 980 | 981 | if(ZitLong(file, &us.centraldirsize) != _ZIP_OK) 982 | err = _ZIP_ERRNO; 983 | 984 | if(ZitLong(file, &us.centraldiroffset) != _ZIP_OK) 985 | err = _ZIP_ERRNO; 986 | 987 | if(ZitShort(file, &us.gi.commentsize) != _ZIP_OK) 988 | err = _ZIP_ERRNO; 989 | 990 | if((centralpos < us.centraldiroffset + us.centraldirsize) && (err == _ZIP_OK)) 991 | err = _ZIP_BAD_FILE; 992 | 993 | if(err != _ZIP_OK) 994 | { 995 | fclose(file); 996 | return NULL; 997 | } 998 | 999 | us.file = file; 1000 | us.bytebeforezip = centralpos - (us.centraldiroffset + us.centraldirsize); 1001 | us.centralpos = centralpos; 1002 | us.currentzipfileinfo = NULL; 1003 | us.encrypted = 0; 1004 | 1005 | s = (_zip*)MallocPatch(sizeof(_zip)); 1006 | 1007 | *s = us; 1008 | 1009 | ZipGotoFirstFile((Zip*)s); 1010 | 1011 | return(Zip*)s; 1012 | } 1013 | 1014 | int ZipClose(Zip* zip) 1015 | { 1016 | _zip* s; 1017 | 1018 | if(zip == NULL) 1019 | return 0; 1020 | 1021 | s = (_zip*)zip; 1022 | 1023 | if(s->currentzipfileinfo != NULL) 1024 | ZipCloseCurrentFile(zip); 1025 | 1026 | fclose(s->file); 1027 | 1028 | FreePatch(s); 1029 | 1030 | return 1; 1031 | } 1032 | 1033 | int ZipExtractCurrentFile(Zip *zip, int *nopath, const char *password) 1034 | { 1035 | //void(overwrite); 1036 | 1037 | char filenameinzip[256]; 1038 | char *filenameWithoutPath; 1039 | char *p; 1040 | void *buffer; 1041 | unsigned int buffersize = TMPBUF_SIZE; 1042 | int err = 0; 1043 | 1044 | FILE *fout = NULL; 1045 | 1046 | zipFileInfo fileInfo; 1047 | 1048 | err = ZitCurrentFileInfo(zip, &fileInfo, filenameinzip, sizeof(filenameinzip), NULL, 0, NULL, 0); 1049 | 1050 | if(err != 0) 1051 | { 1052 | ; 1053 | return -1; 1054 | } 1055 | 1056 | buffer = (void *)MallocPatch(buffersize); 1057 | 1058 | if(!buffer) 1059 | { 1060 | ; 1061 | 1062 | return 0; 1063 | } 1064 | 1065 | p = filenameWithoutPath = filenameinzip; 1066 | 1067 | while((*p) != '\0') 1068 | { 1069 | if(((*p) == '/') || ((*p) == '\\')) 1070 | filenameWithoutPath = p + 1; 1071 | 1072 | p++; 1073 | } 1074 | 1075 | if((*filenameWithoutPath) == '\0') 1076 | { 1077 | if((*nopath) == 0) 1078 | { 1079 | //; 1080 | mkdir(filenameinzip, 0777); 1081 | } 1082 | } 1083 | else 1084 | { 1085 | const char *writeFilename; 1086 | 1087 | if((*nopath) == 0) 1088 | writeFilename = filenameinzip; 1089 | else 1090 | writeFilename = filenameWithoutPath; 1091 | 1092 | err = ZipOpenCurrentFile(zip, password); 1093 | 1094 | if(err != _ZIP_OK) 1095 | ; 1096 | 1097 | fout = fopen(writeFilename, "wb"); 1098 | 1099 | if((fout == NULL) && ((*nopath) == 0) && (filenameWithoutPath != (char *)filenameinzip)) 1100 | { 1101 | char c = *(filenameWithoutPath - 1); 1102 | *(filenameWithoutPath - 1) = '\0'; 1103 | mkdir(writeFilename, 0777); 1104 | *(filenameWithoutPath - 1) = c; 1105 | fout = fopen(writeFilename, "wb"); 1106 | } 1107 | 1108 | if(fout == NULL) 1109 | ; 1110 | 1111 | void* extractBuffer = buffer; 1112 | unsigned int remainingSize = buffersize; 1113 | 1114 | do 1115 | { 1116 | 1117 | err = ZipReadCurrentFile(zip, extractBuffer, remainingSize); 1118 | 1119 | if(err < 0) 1120 | { 1121 | ; 1122 | break; 1123 | } 1124 | 1125 | if(err > 0) 1126 | { 1127 | remainingSize = remainingSize - err; 1128 | if (remainingSize == 0){ 1129 | fwrite(buffer, 1, buffersize, fout); 1130 | remainingSize = buffersize; 1131 | extractBuffer = buffer; 1132 | }else extractBuffer = extractBuffer+err; 1133 | } 1134 | 1135 | } while (err > 0); 1136 | 1137 | if (remainingSize != buffersize) fwrite(buffer, 1, buffersize-remainingSize, fout); 1138 | fclose(fout); 1139 | 1140 | err = ZipCloseCurrentFile(zip); 1141 | 1142 | if(err != _ZIP_OK) 1143 | ; 1144 | } 1145 | 1146 | if(buffer) 1147 | FreePatch(buffer); 1148 | 1149 | return err; 1150 | } 1151 | 1152 | int ZipExtract(Zip* zip, const char *password, int(*callback)(u32, u32)) 1153 | { 1154 | unsigned int i; 1155 | zipGlobalInfo gi; 1156 | memset(&gi, 0, sizeof(zipGlobalInfo)); 1157 | int err; 1158 | int nopath = 0; 1159 | 1160 | err = ZitGlobalInfo(zip, &gi); 1161 | 1162 | if(err != _ZIP_OK) 1163 | ; 1164 | 1165 | for(i = 0;i < gi.countentries;i++) 1166 | { 1167 | if(ZipExtractCurrentFile(zip, &nopath, password) != _ZIP_OK) 1168 | break; 1169 | if (callback(i + 1, gi.countentries) != 0) { 1170 | err = _ZIP_INTERNAL_ERROR; 1171 | break; 1172 | } 1173 | if((i + 1) < gi.countentries) 1174 | { 1175 | err = ZipGotoNextFile(zip); 1176 | 1177 | if(err != _ZIP_OK) 1178 | ; 1179 | } 1180 | } 1181 | callback(gi.countentries, gi.countentries); 1182 | return err; 1183 | } 1184 | 1185 | ZipFile* ZipFileRead(Zip* zip, const char *filename, const char *password) 1186 | { 1187 | char filenameinzip[256]; 1188 | int err = 0; 1189 | 1190 | ZipFile* zipfile = (ZipFile*) MallocPatch(sizeof(ZipFile)); 1191 | 1192 | if(!zipfile) 1193 | return NULL; 1194 | 1195 | if(ZipLocateFile(zip, filename, 0) != 0) 1196 | { 1197 | FreePatch(zipfile); 1198 | return NULL; 1199 | } 1200 | 1201 | zipFileInfo fileinfo; 1202 | 1203 | err = ZitCurrentFileInfo(zip, &fileinfo, filenameinzip, sizeof(filenameinzip), NULL, 0, NULL, 0); 1204 | 1205 | if(err != 0) 1206 | { 1207 | ; 1208 | FreePatch(zipfile); 1209 | return NULL; 1210 | } 1211 | 1212 | err = ZipOpenCurrentFile(zip, password); 1213 | 1214 | if(err != 0) 1215 | { 1216 | ; 1217 | FreePatch(zipfile); 1218 | return NULL; 1219 | } 1220 | 1221 | zipfile->size = fileinfo.uncompressedsize; 1222 | 1223 | zipfile->data = (unsigned char*)MallocPatch(fileinfo.uncompressedsize); 1224 | 1225 | if(!zipfile->data) 1226 | { 1227 | ; 1228 | FreePatch(zipfile); 1229 | return NULL; 1230 | } 1231 | 1232 | unsigned int count = 0; 1233 | err = 1; 1234 | 1235 | while(err > 0) 1236 | { 1237 | err = ZipReadCurrentFile(zip, &zipfile->data[count], fileinfo.uncompressedsize); 1238 | 1239 | if(err < 0) 1240 | { 1241 | ; 1242 | break; 1243 | } 1244 | else 1245 | count += err; 1246 | } 1247 | 1248 | if(err == 0) 1249 | { 1250 | err = ZipCloseCurrentFile(zip); 1251 | 1252 | if(err != 0) 1253 | { 1254 | ; 1255 | FreePatch(zipfile->data); 1256 | FreePatch(zipfile); 1257 | return NULL; 1258 | } 1259 | 1260 | return zipfile; 1261 | } 1262 | else 1263 | { 1264 | ZipCloseCurrentFile(zip); 1265 | FreePatch(zipfile->data); 1266 | FreePatch(zipfile); 1267 | 1268 | return NULL; 1269 | } 1270 | } 1271 | 1272 | void ZipFileFree(ZipFile* file) 1273 | { 1274 | if(file->data) 1275 | FreePatch(file->data); 1276 | 1277 | if(file) 1278 | FreePatch(file); 1279 | } 1280 | 1281 | #ifdef __cplusplus 1282 | } 1283 | #endif 1284 | --------------------------------------------------------------------------------