Added update support, library alphabet ribbon, release signing, extra settings around server connection, general fixes

This commit is contained in:
Soliton committed 2026-10-03 11:58:51 -04:00
1 parent 5c9e5f866d
commit 200b3eecb0
31 files changed
+5077 -44

No files matched your search

+1 -1
View File
@@ -12,5 +12,5 @@ jobs:
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev zlib1g-dev
- run: make host
- run: make host tools
- run: tests/e2e.sh
+63 -7
View File
@@ -1,25 +1,58 @@
# Builds the PS5 payload and publishes a GitHub release when a version tag is pushed.
# Builds the PS5 payload and publishes a GitHub release. Triggered either by:
#
# git tag v1.0.0 && git push origin v1.0.0
# - merging a PR into main from a branch named with a version, e.g.
# release/v1.0.2 or v1.0.2-some-fix (the tag is created on the merge commit)
# - pushing a version tag manually: git tag v1.0.0 && git push origin v1.0.0
name: Release
on:
push:
tags: ["v*.*.*"]
pull_request:
types: [closed]
branches: [main]
permissions:
contents: write
jobs:
release:
if: >-
github.event_name == 'push' ||
(github.event.pull_request.merged &&
contains(github.event.pull_request.head.ref, 'v'))
runs-on: ubuntu-latest
steps:
- name: Resolve version
id: version
env:
HEAD_REF: ${{ github.event.pull_request.head.ref }}
run: |
if [ "$GITHUB_EVENT_NAME" = push ]; then
tag="$GITHUB_REF_NAME"
sha="$GITHUB_SHA"
else
tag=$(grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' <<< "$HEAD_REF" | head -n1 || true)
sha="${{ github.event.pull_request.merge_commit_sha }}"
fi
if [ -z "$tag" ]; then
echo "Branch '$HEAD_REF' has no vX.Y.Z version; skipping release."
exit 0
fi
echo "tag=$tag" >> "$GITHUB_OUTPUT"
echo "sha=$sha" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v4
if: steps.version.outputs.tag
with:
ref: ${{ steps.version.outputs.sha }}
- uses: docker/setup-buildx-action@v3
if: steps.version.outputs.tag
# Same image tools/ps5-build.sh uses, cached between runs.
- uses: docker/build-push-action@v6
if: steps.version.outputs.tag
with:
context: tools/docker
tags: romm-sync-ps5sdk:v0.43
@@ -28,17 +61,40 @@ jobs:
cache-to: type=gha,mode=max
- name: Build payload
run: tools/ps5-build.sh VERSION="${GITHUB_REF_NAME#v}"
if: steps.version.outputs.tag
env:
TAG: ${{ steps.version.outputs.tag }}
run: tools/ps5-build.sh VERSION="${TAG#v}"
- name: Package
# manifest.json + manifest.sig let the payload verify in-app updates
# (src/update.c). The secret is the 64-hex-character key from
# tools/release-sign.c; "check" fails unless the payload trusts that key.
- name: Package and sign
if: steps.version.outputs.tag
env:
RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }}
TAG: ${{ steps.version.outputs.tag }}
run: |
if [ -z "$RELEASE_SIGNING_KEY" ]; then
echo "::error::RELEASE_SIGNING_KEY secret is not set; in-app updates need a signed release."
exit 1
fi
make tools
mkdir dist
cp build/ps5/romm-sync.elf build/ps5/cacert.pem dist/
cp build/ps5/romm-sync.elf dist/
build/host/release-sign manifest "$TAG" dist/romm-sync.elf > dist/manifest.json
build/host/release-sign sign dist/manifest.json > dist/manifest.sig
build/host/release-sign check dist/manifest.json dist/manifest.sig
cd dist && sha256sum * > SHA256SUMS
# Creates the tag on the target commit if it doesn't exist yet. A tag pushed
# by GITHUB_TOKEN does not re-trigger this workflow, so there's no double release.
- name: Publish release
if: steps.version.outputs.tag
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.version.outputs.tag }}
SHA: ${{ steps.version.outputs.sha }}
run: |
gh release create "$GITHUB_REF_NAME" dist/* \
--title "$GITHUB_REF_NAME" --generate-notes --verify-tag
gh release create "$TAG" dist/* \
--target "$SHA" --title "$TAG" --generate-notes
+22 -8
View File
@@ -6,21 +6,23 @@
# make deploy PS5_HOST=<ip> send the payload to the loader on port 9021
# make install PS5_HOST=<ip> same, plus copy it into etaHEN's autostart over FTP
# make ps5 VERSION=1.2.3 override the version baked into the build
# make tools release-sign, for signing releases (tools/release-sign.c)
SRCS := src/main.c src/util.c src/http.c src/romm.c src/config.c src/state.c \
src/profiles.c src/sync.c src/watch.c src/detect.c src/autostart.c src/memcard.c src/zip.c src/bundle.c src/gameid.c src/library.c src/pair.c src/web.c \
third_party/cJSON.c third_party/md5.c
HDRS := $(wildcard src/*.h) third_party/cJSON.h third_party/md5.h
src/profiles.c src/sync.c src/watch.c src/detect.c src/autostart.c src/memcard.c src/zip.c src/bundle.c src/gameid.c src/library.c src/pair.c src/web.c src/update.c \
third_party/cJSON.c third_party/md5.c third_party/monocypher.c third_party/monocypher-ed25519.c
HDRS := $(wildcard src/*.h) third_party/cJSON.h third_party/md5.h third_party/monocypher.h third_party/monocypher-ed25519.h
UI_HEADER := build/gen/ui_index.h build/gen/icon_png.h
COMMON_CFLAGS := -std=gnu11 -O2 -Wall -Wextra -Wno-unused-parameter -Wno-unknown-warning-option -Wno-unreachable-code-generic-assoc -Isrc -Ithird_party -Ibuild/gen
ifdef VERSION
COMMON_CFLAGS += -DAPP_VERSION='"$(VERSION)"'
endif
COMMON_CFLAGS += $(EXTRA_CFLAGS)
PS5_HOST ?= ps5
PS5_PORT ?= 9021
.PHONY: all host ps5 deploy install run clean
.PHONY: all host ps5 tools deploy install run clean
all: host
@@ -38,9 +40,16 @@ HOST_BIN := build/host/romm-sync
host: $(HOST_BIN)
# Host builds also trust the test key in tests/, so the e2e test can sign updates.
$(HOST_BIN): $(SRCS) src/platform_host.c $(HDRS) $(UI_HEADER)
@mkdir -p $(dir $@)
$(HOST_CC) $(COMMON_CFLAGS) -o $@ $(SRCS) src/platform_host.c -lcurl -lz -lpthread
$(HOST_CC) $(COMMON_CFLAGS) -DROMM_UPDATE_TEST_KEY -o $@ $(SRCS) src/platform_host.c -lcurl -lz -lpthread
tools: build/host/release-sign
build/host/release-sign: tools/release-sign.c src/update_keys.h third_party/monocypher.c third_party/monocypher-ed25519.c
@mkdir -p $(dir $@)
$(HOST_CC) -std=gnu11 -O2 -Wall -Isrc -Ithird_party -o $@ $(filter %.c,$^)
run: host
ROMM_SYNC_DATA=$${ROMM_SYNC_DATA:-./host-data} $(HOST_BIN)
@@ -50,15 +59,20 @@ PS5_PAYLOAD_SDK ?= /opt/ps5-payload-sdk
PS5_CC := $(PS5_PAYLOAD_SDK)/bin/prospero-clang
PS5_PKGCONF := $(PS5_PAYLOAD_SDK)/bin/prospero-pkg-config
PS5_ELF := build/ps5/romm-sync.elf
# The SDK's Mozilla CA bundle, built into the payload so HTTPS works out of the box.
PS5_CA := $(PS5_PAYLOAD_SDK)/target/user/homebrew/etc/ca-bundle.crt
ps5: $(PS5_ELF)
$(PS5_ELF): $(SRCS) src/platform_ps5.c $(HDRS) $(UI_HEADER)
build/gen/cacert_pem.h: $(PS5_CA) tools/embed.py
@mkdir -p $(dir $@)
$(PS5_CC) $(COMMON_CFLAGS) $$($(PS5_PKGCONF) --cflags libcurl) -DCURL_STATICLIB \
python3 tools/embed.py $< $@ CACERT_PEM
$(PS5_ELF): $(SRCS) src/platform_ps5.c $(HDRS) $(UI_HEADER) build/gen/cacert_pem.h
@mkdir -p $(dir $@)
$(PS5_CC) $(COMMON_CFLAGS) -DROMM_EMBED_CA $$($(PS5_PKGCONF) --cflags libcurl) -DCURL_STATICLIB \
-o $@ $(SRCS) src/platform_ps5.c \
$$($(PS5_PKGCONF) --static --libs libcurl) -pthread -lSceSystemService -lSceAppInstUtil
@cp $(PS5_PAYLOAD_SDK)/target/user/homebrew/etc/ca-bundle.crt build/ps5/cacert.pem 2>/dev/null || true
deploy: $(PS5_ELF)
nc -w 1 $(PS5_HOST) $(PS5_PORT) < $(PS5_ELF)
+15 -3
View File
@@ -36,7 +36,13 @@ If you are interested in downloading PS4 and PS5 games from your RomM server, Ro
To start RomM Sync with the console, copy the payload to etaHEN's autostart folder or use the autoloader. You can do this from the last setup step, or with `make install PS5_HOST=<ps5-ip>` if you build it yourself.
If your RomM server uses HTTPS, copy `cacert.pem` from the release to `/data/romm-sync/cacert.pem`.
HTTP and HTTPS servers both work. Common certificate authorities (the Mozilla list) are built in, so there's nothing to copy for HTTPS. If your server uses a self-signed certificate, tick _Skip certificate checks_ during setup, or turn off _Verify TLS certificates_ in Settings. If it uses a certificate from your own CA, you can instead put that CA's certificate in `/data/romm-sync/cacert.pem`; it's trusted in addition to the built-in list.
## Updates
Settings shows when a new version is out (it checks GitHub once a day, which you can turn off) and can install it for you. Nothing installs on its own. The update waits until no sync, download or game is running, replaces the payload in etaHEN's autostart folder (keeping the old one as `romm-sync.elf.bak`), and restarts RomM Sync.
Each release is signed. RomM Sync only installs an update whose signature matches a key built into it and whose file matches the signed checksum, so a modified download is rejected.
## Setup
@@ -85,11 +91,17 @@ For RetroArch, it reads save and state folders from its own config, including it
## Building
```sh
make host # macOS or Linux build for development
make host tools # macOS or Linux build for development, plus tools/release-sign
tools/ps5-build.sh # PS5 build in Docker, output in build/ps5/
tests/e2e.sh # end-to-end tests against a mock RomM server
```
## Releasing
Merge a pull request from a branch named with the version, such as `release/v1.0.2`. The release workflow tags the merge commit, builds the payload, signs it and publishes the release. You can also push a `v1.2.3` tag yourself.
Signing needs the `RELEASE_SIGNING_KEY` repository secret: the 64-character hex key printed by `build/host/release-sign keygen`. Its public half must be in `src/update_keys.h`, which also holds a backup key that is kept offline. If the release key is ever lost or leaked, sign the next release with the backup key, and ship a new key pair in that release.
## License
GPL-3.0. Parts of the PS5 code are adapted from [ftpsrv](https://github.com/ps5-payload-dev/ftpsrv) and [websrv](https://github.com/ps5-payload-dev/websrv) by John Törnblom. [cJSON](https://github.com/DaveGamble/cJSON) and [qrcode-generator](https://github.com/kazuhikoarase/qrcode-generator) are MIT licensed.
GPL-3.0. Parts of the PS5 code are adapted from [ftpsrv](https://github.com/ps5-payload-dev/ftpsrv) and [websrv](https://github.com/ps5-payload-dev/websrv) by John Törnblom. [cJSON](https://github.com/DaveGamble/cJSON) and [qrcode-generator](https://github.com/kazuhikoarase/qrcode-generator) are MIT licensed. [Monocypher](https://monocypher.org) is CC0 or BSD-2-Clause.
+26 -1
View File
@@ -3,6 +3,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "util.h"
@@ -13,6 +14,13 @@ static const char *etahen_dir(void) {
return e && *e ? e : "/data/etaHEN";
}
/* Same mode "make install" leaves over FTP. */
static int write_payload(const char *elf, const void *data, size_t len) {
if (write_file_atomic(elf, data, len) != 0) return -1;
chmod(elf, 0777);
return 0;
}
static void paths(char *elf, char *flag, size_t n) {
snprintf(elf, n, "%s/payloads/romm-sync.elf", etahen_dir());
snprintf(flag, n, "%s/payloads/romm-sync.elf.auto_start", etahen_dir());
@@ -29,6 +37,23 @@ cJSON *autostart_status(void) {
return j;
}
int autostart_replace(const void *data, size_t len, char *err, int en) {
char elf[PATH_MAX_LEN], flag[PATH_MAX_LEN], bak[PATH_MAX_LEN + 8];
paths(elf, flag, sizeof elf);
if (!file_exists(elf)) return 0;
snprintf(bak, sizeof bak, "%s.bak", elf);
if (copy_file(elf, bak) != 0) {
snprintf(err, (size_t)en, "cannot back up %s", elf);
return -1;
}
if (write_payload(elf, data, len) != 0) {
snprintf(err, (size_t)en, "cannot write %s", elf);
return -1;
}
LOGI("replaced %s (%zu bytes), previous version kept as %s", elf, len, bak);
return 1;
}
int autostart_set(int enable, const void *data, size_t len, char *err, int en) {
char elf[PATH_MAX_LEN], flag[PATH_MAX_LEN];
paths(elf, flag, sizeof elf);
@@ -42,7 +67,7 @@ int autostart_set(int enable, const void *data, size_t len, char *err, int en) {
snprintf(err, (size_t)en, "that file is not an ELF payload");
return -1;
}
if (write_file_atomic(elf, data, len) != 0) {
if (write_payload(elf, data, len) != 0) {
snprintf(err, (size_t)en, "cannot write %s", elf);
return -1;
}
+3
View File
@@ -9,5 +9,8 @@
cJSON *autostart_status(void); /* {etahen, installed, enabled, path} */
/* Turns autostart on or off, installing the payload first if one is given. */
int autostart_set(int enable, const void *elf, size_t elf_len, char *err, int en);
/* Replaces an installed payload, keeping the old one as romm-sync.elf.bak.
* 1 if replaced, 0 if none is installed, -1 on error. */
int autostart_replace(const void *elf, size_t elf_len, char *err, int en);
#endif
+3
View File
@@ -57,6 +57,7 @@ static void set_defaults(void) {
g_cfg.exit_delay_sec = 5;
g_cfg.sync_states = 1;
g_cfg.notify = 1;
g_cfg.update_check = 1;
g_cfg.keep_backups = 5;
g_cfg.server_versions = 10;
g_cfg.download_concurrency = 3;
@@ -85,6 +86,7 @@ void config_apply_json(const cJSON *j) {
else if (!strcmp(states, "upload")) g_cfg.sync_states = 1;
else if (!strcmp(states, "sync")) g_cfg.sync_states = 2;
get_int(j, "notify", &g_cfg.notify);
get_int(j, "update_check", &g_cfg.update_check);
get_int(j, "keep_backups", &g_cfg.keep_backups);
get_int(j, "server_versions", &g_cfg.server_versions);
if (g_cfg.server_versions < 0) g_cfg.server_versions = 0;
@@ -165,6 +167,7 @@ cJSON *config_to_json(int include_secrets) {
cJSON_AddNumberToObject(j, "exit_delay_sec", g_cfg.exit_delay_sec);
cJSON_AddStringToObject(j, "states", g_cfg.sync_states == 2 ? "sync" : g_cfg.sync_states ? "upload" : "off");
cJSON_AddBoolToObject(j, "notify", g_cfg.notify);
cJSON_AddBoolToObject(j, "update_check", g_cfg.update_check);
cJSON_AddNumberToObject(j, "keep_backups", g_cfg.keep_backups);
cJSON_AddNumberToObject(j, "server_versions", g_cfg.server_versions);
cJSON_AddNumberToObject(j, "download_concurrency", g_cfg.download_concurrency);
+1
View File
@@ -23,6 +23,7 @@ typedef struct {
int exit_delay_sec;
int sync_states; /* 0 off, 1 upload, 2 upload and download */
int notify;
int update_check; /* look for new releases once a day */
int keep_backups; /* local copies kept per save */
int server_versions; /* versions RomM keeps per save, 0 keeps all */
int download_concurrency; /* library downloads running at once */
+72 -11
View File
@@ -7,16 +7,41 @@
#include <unistd.h>
#include "util.h"
#ifdef ROMM_EMBED_CA
#include "cacert_pem.h" /* generated from the SDK's Mozilla CA bundle */
#endif
static char g_ca_bundle[PATH_MAX_LEN];
/* Built-in roots plus the user's cacert.pem, if any. Only on the PS5, which
* has no system CA store. */
static char *g_ca_blob;
static size_t g_ca_blob_len;
static int g_tls_verify = 1;
void http_global_init(const char *ca_bundle, int tls_verify) {
curl_global_init(CURL_GLOBAL_ALL);
if (ca_bundle && file_exists(ca_bundle)) str_copy(g_ca_bundle, sizeof g_ca_bundle, ca_bundle);
g_tls_verify = tls_verify;
#ifdef ROMM_EMBED_CA
/* A cacert.pem is added to the built-in roots, so a private CA works too. */
size_t ulen = 0;
char *user = g_ca_bundle[0] ? read_file(g_ca_bundle, &ulen) : NULL;
g_ca_blob_len = sizeof CACERT_PEM - 1 + (user ? ulen + 1 : 0);
g_ca_blob = malloc(g_ca_blob_len);
if (g_ca_blob) {
memcpy(g_ca_blob, CACERT_PEM, sizeof CACERT_PEM - 1);
if (user) {
g_ca_blob[sizeof CACERT_PEM - 1] = '\n';
memcpy(g_ca_blob + sizeof CACERT_PEM, user, ulen);
}
}
free(user);
LOGI("libcurl %s, CA bundle: built-in%s%s", curl_version_info(CURLVERSION_NOW)->version,
g_ca_bundle[0] ? " + " : "", g_ca_bundle);
#else
LOGI("libcurl %s, CA bundle: %s", curl_version_info(CURLVERSION_NOW)->version,
g_ca_bundle[0] ? g_ca_bundle : "(default)");
#endif
}
void http_set_tls_verify(int verify) { g_tls_verify = verify; }
@@ -49,7 +74,7 @@ static size_t mem_write(char *ptr, size_t size, size_t nmemb, void *ud) {
return n;
}
static CURL *easy_new(const char *url, struct curl_slist **hdrs, const char *auth) {
static CURL *easy_new(const char *url, struct curl_slist **hdrs, const char *auth, int verify) {
CURL *c = curl_easy_init();
if (!c) return NULL;
curl_easy_setopt(c, CURLOPT_URL, url);
@@ -61,8 +86,13 @@ static CURL *easy_new(const char *url, struct curl_slist **hdrs, const char *aut
/* Give up on stalled transfers rather than using a total timeout. */
curl_easy_setopt(c, CURLOPT_LOW_SPEED_LIMIT, 1L);
curl_easy_setopt(c, CURLOPT_LOW_SPEED_TIME, 60L);
if (g_ca_bundle[0]) curl_easy_setopt(c, CURLOPT_CAINFO, g_ca_bundle);
if (!g_tls_verify) {
if (g_ca_blob) {
struct curl_blob blob = {g_ca_blob, g_ca_blob_len, CURL_BLOB_NOCOPY};
curl_easy_setopt(c, CURLOPT_CAINFO_BLOB, &blob);
} else if (g_ca_bundle[0]) {
curl_easy_setopt(c, CURLOPT_CAINFO, g_ca_bundle);
}
if (!verify) {
curl_easy_setopt(c, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(c, CURLOPT_SSL_VERIFYHOST, 0L);
}
@@ -95,11 +125,11 @@ static int finish(CURL *c, CURLcode rc, membuf *m, http_resp *out, const char *u
return 0;
}
int http_request(const char *method, const char *url, const char *auth, const char *content_type,
const void *body, size_t body_len, http_resp *out) {
static int request_impl(const char *method, const char *url, const char *auth, const char *content_type,
const void *body, size_t body_len, int verify, http_resp *out) {
struct curl_slist *hdrs = NULL;
membuf m = {0};
CURL *c = easy_new(url, &hdrs, auth);
CURL *c = easy_new(url, &hdrs, auth, verify);
if (!c) return -1;
if (content_type) {
char h[256];
@@ -122,11 +152,32 @@ int http_request(const char *method, const char *url, const char *auth, const ch
return r;
}
int http_request(const char *method, const char *url, const char *auth, const char *content_type,
const void *body, size_t body_len, http_resp *out) {
return request_impl(method, url, auth, content_type, body, body_len, g_tls_verify, out);
}
int http_get_verified(const char *url, http_resp *out) {
return request_impl("GET", url, NULL, NULL, NULL, 0, 1, out);
}
int http_tls_untrusted(const char *url) {
struct curl_slist *hdrs = NULL;
CURL *c = easy_new(url, &hdrs, NULL, 1);
if (!c) return 0;
curl_easy_setopt(c, CURLOPT_NOBODY, 1L);
curl_easy_setopt(c, CURLOPT_TIMEOUT, 20L);
CURLcode rc = curl_easy_perform(c);
curl_slist_free_all(hdrs);
curl_easy_cleanup(c);
return rc == CURLE_PEER_FAILED_VERIFICATION;
}
int http_upload_file(const char *method, const char *url, const char *auth, const char *field,
const char *file_path, const char *upload_name, http_resp *out) {
struct curl_slist *hdrs = NULL;
membuf m = {0};
CURL *c = easy_new(url, &hdrs, auth);
CURL *c = easy_new(url, &hdrs, auth, g_tls_verify);
if (!c) return -1;
curl_mime *mime = curl_mime_init(c);
curl_mimepart *part = curl_mime_addpart(mime);
@@ -164,8 +215,8 @@ static int xfer_cb(void *ud, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ul
return p->fn(p->ud, p->offset + dlnow, dltotal ? p->offset + dltotal : 0);
}
int http_download(const char *url, const char *auth, const char *dest, int resume,
http_progress_fn progress, void *ud, http_resp *out) {
static int download_impl(const char *url, const char *auth, const char *dest, int resume, int verify,
http_progress_fn progress, void *ud, http_resp *out) {
char part[PATH_MAX_LEN];
snprintf(part, sizeof part, "%s.part", dest);
mkdir_parent(dest);
@@ -180,7 +231,7 @@ int http_download(const char *url, const char *auth, const char *dest, int resum
}
struct curl_slist *hdrs = NULL;
CURL *c = easy_new(url, &hdrs, auth);
CURL *c = easy_new(url, &hdrs, auth, verify);
if (!c) {
fclose(f);
return -1;
@@ -203,7 +254,7 @@ int http_download(const char *url, const char *auth, const char *dest, int resum
curl_slist_free_all(hdrs);
curl_easy_cleanup(c);
unlink(part);
return http_download(url, auth, dest, 0, progress, ud, out);
return download_impl(url, auth, dest, 0, verify, progress, ud, out);
}
if (r == 0 && out->status >= 200 && out->status < 300) {
if (move_file(part, dest) != 0) {
@@ -219,6 +270,16 @@ int http_download(const char *url, const char *auth, const char *dest, int resum
return r;
}
int http_download(const char *url, const char *auth, const char *dest, int resume,
http_progress_fn progress, void *ud, http_resp *out) {
return download_impl(url, auth, dest, resume, g_tls_verify, progress, ud, out);
}
int http_download_verified(const char *url, const char *dest, http_progress_fn progress, void *ud,
http_resp *out) {
return download_impl(url, NULL, dest, 0, 1, progress, ud, out);
}
char *http_escape(const char *s) {
char *e = curl_easy_escape(NULL, s, 0);
char *r = e ? strdup(e) : strdup("");
+8
View File
@@ -31,6 +31,14 @@ int http_upload_file(const char *method, const char *url, const char *auth, cons
int http_download(const char *url, const char *auth, const char *dest, int resume,
http_progress_fn progress, void *ud, http_resp *out);
/* 1 if url's TLS certificate fails verification (self-signed, private CA). */
int http_tls_untrusted(const char *url);
/* For updates: always verify TLS certificates, whatever tls_verify says. */
int http_get_verified(const char *url, http_resp *out);
int http_download_verified(const char *url, const char *dest, http_progress_fn progress, void *ud,
http_resp *out);
/* URL-encode a query/path component into a malloc'd string. */
char *http_escape(const char *s);
+11
View File
@@ -312,6 +312,14 @@ void library_init(void) {
}
}
int library_busy(void) {
int busy = 0;
pthread_mutex_lock(&g_q_lock);
for (job *j = g_jobs; j && !busy; j = j->next) busy = j->status == JOB_QUEUED || j->status == JOB_RUNNING;
pthread_mutex_unlock(&g_q_lock);
return busy;
}
void library_wake(void) {
pthread_mutex_lock(&g_q_lock);
pthread_cond_broadcast(&g_q_cond);
@@ -501,6 +509,9 @@ cJSON *library_roms(int platform_id, const char *search, int offset, int limit,
}
cJSON *out = cJSON_CreateObject();
cJSON_AddNumberToObject(out, "total", jget_num(j, "total", 0));
/* First letter -> offset of its first game, for the A-Z ribbon. */
const cJSON *ci = cJSON_GetObjectItemCaseSensitive(j, "char_index");
if (cJSON_IsObject(ci)) cJSON_AddItemToObject(out, "char_index", cJSON_Duplicate(ci, 1));
cJSON *items = cJSON_AddArrayToObject(out, "items");
const cJSON *it;
state_lock();
+1
View File
@@ -16,5 +16,6 @@ int library_cancel(int id, char *err, int en);
int library_clear_finished(void);
int library_delete_rom(int rom_id, char *err, int en);
cJSON *library_downloads(void);
int library_busy(void); /* a download is queued or running */
#endif
+2
View File
@@ -17,6 +17,7 @@
#include "romm.h"
#include "state.h"
#include "sync.h"
#include "update.h"
#include "util.h"
#include "watch.h"
#include "web.h"
@@ -182,6 +183,7 @@ int main(void) {
now - sync_last_run() >= (time_t)interval * 60) {
sync_request("periodic");
}
update_tick();
}
return 0;
}
+13 -1
View File
@@ -6,6 +6,7 @@
#include <unistd.h>
#include "config.h"
#include "http.h"
#include "platform.h"
#include "romm.h"
#include "state.h"
@@ -36,9 +37,18 @@ static void normalize_url(const char *in, char *out, size_t n) {
while (l && (out[l - 1] == '/' || out[l - 1] == ' ')) out[--l] = 0;
}
/* -2 if the server's certificate isn't trusted, so the caller doesn't fall back to http. */
static int check_server(const char *base, char *err, int en) {
char version[32] = "";
if (romm_heartbeat(base, version, sizeof version) != 0) {
config_lock();
int verify = g_cfg.tls_verify;
config_unlock();
if (verify && !strncmp(base, "https://", 8) && http_tls_untrusted(base)) {
snprintf(err, (size_t)en, "%s has a certificate this console doesn't trust (self-signed or from a private CA). "
"Tick \"Skip certificate checks\" to connect anyway.", base);
return -2;
}
snprintf(err, (size_t)en, "no RomM server answered at %s", base);
return -1;
}
@@ -110,7 +120,9 @@ static void *poll_thread(void *arg) {
/* Checks the server. An address without a scheme is tried as https, then http. */
static int resolve_server(const char *server_url, char *base, size_t n, char *err, int en) {
normalize_url(server_url, base, n);
if (check_server(base, err, en) == 0) return 0;
int rc = check_server(base, err, en);
if (rc == 0) return 0;
if (rc == -2) return -1;
const char *s = server_url;
while (*s == ' ') s++;
if (!strncmp(s, "http://", 7) || !strncmp(s, "https://", 8)) return -1;
+5
View File
@@ -23,6 +23,11 @@ const char *plat_ca_bundle(void);
* Returns 0 on success, -1 if unsupported/failed. */
int plat_install_tile(int port);
/* Starts a payload through the ELF loader on 127.0.0.1:9021. The new copy
* stops this one when it starts (plat_init). -1 with errno set on failure.
* Host: writes <data>/launched.elf. */
int plat_launch_elf(const void *elf, size_t len);
/* "ps5" or "host". */
const char *plat_name(void);
+6
View File
@@ -55,6 +55,12 @@ int plat_install_tile(int port) {
return -1;
}
int plat_launch_elf(const void *elf, size_t len) {
char p[PATH_MAX_LEN];
path_join(p, sizeof p, g_data, "launched.elf");
return write_file_atomic(p, elf, len);
}
const char *plat_name(void) { return "host"; }
void plat_local_ip(char *buf, size_t n) {
+34
View File
@@ -320,6 +320,40 @@ int plat_install_tile(int port) {
return 0;
}
/* etaHEN's loader runs whatever arrives on port 9021, loopback included
* (checked on 12.70 with etaHEN). */
int plat_launch_elf(const void *elf, size_t len) {
struct sockaddr_in sa;
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_port = htons(9021);
sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) return -1;
if (connect(fd, (struct sockaddr *)&sa, sizeof sa) != 0) {
int e = errno;
close(fd);
errno = e;
return -1;
}
const char *p = elf;
while (len) {
ssize_t w = write(fd, p, len);
if (w < 0 && errno == EINTR) continue;
if (w <= 0) {
int e = w < 0 ? errno : EPIPE;
close(fd);
errno = e;
return -1;
}
p += w;
len -= (size_t)w;
}
shutdown(fd, SHUT_WR);
close(fd);
return 0;
}
const char *plat_name(void) {
return "ps5";
}
+331
View File
@@ -0,0 +1,331 @@
/* Updates from GitHub releases. Nothing installs by itself: the UI checks,
* shows the release notes and installs when the user asks.
*
* A release carries romm-sync.elf, manifest.json ({version, file, size, sha512})
* and manifest.sig, an Ed25519 signature of manifest.json by one of the keys in
* update_keys.h. The payload is only installed if all of that checks out.
* tools/release-sign.c makes the manifest and signature in CI.
*
* ROMM_SYNC_UPDATE_URL points the check somewhere else, for tests. */
#include "update.h"
#include <errno.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "autostart.h"
#include "config.h"
#include "http.h"
#include "library.h"
#include "monocypher-ed25519.h"
#include "platform.h"
#include "state.h"
#include "sync.h"
#include "update_keys.h"
#include "util.h"
#ifndef RELEASES_URL /* overridable for test builds */
#define RELEASES_URL "https://api.github.com/repos/s0liton/ps5-romm/releases/latest"
#endif
#define CHECK_EVERY_SEC (24 * 60 * 60)
/* A failed daily check (no network yet after boot, say) is retried sooner. */
#define RETRY_AFTER_SEC (60 * 60)
/* The new copy stops this one within a few seconds of starting. */
#define RESTART_TIMEOUT_SEC 60
typedef enum { U_IDLE, U_CHECKING, U_DOWNLOADING, U_WAITING, U_INSTALLING, U_RESTARTING, U_ERROR } ustate;
static const char *const STATE_NAMES[] = {"idle", "checking", "downloading", "waiting", "installing", "restarting", "error"};
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static ustate g_state;
static char g_error[256], g_message[128];
static char g_latest[32], g_published[32], g_page_url[512];
static char g_elf_url[512], g_manifest_url[512], g_sig_url[512];
static char *g_notes;
static time_t g_checked_at, g_auto_checked_at;
static char g_notified[32];
static int64_t g_done, g_total;
static const char *release_url(void) {
const char *u = getenv("ROMM_SYNC_UPDATE_URL");
return u && *u ? u : RELEASES_URL;
}
/* "v1.2.3" or "1.2.3-dev" into numbers. Anything after the patch is ignored. */
static int parse_version(const char *s, int v[3]) {
v[0] = v[1] = v[2] = 0;
if (*s == 'v') s++;
return sscanf(s, "%d.%d.%d", &v[0], &v[1], &v[2]) >= 2 ? 0 : -1;
}
static int newer_than(const char *a, const char *b) {
int x[3], y[3];
if (parse_version(a, x) || parse_version(b, y)) return 0;
for (int i = 0; i < 3; i++)
if (x[i] != y[i]) return x[i] > y[i];
return 0;
}
static int busy(ustate s) { return s != U_IDLE && s != U_ERROR; }
/* Call with g_lock held. */
static void set_error(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(g_error, sizeof g_error, fmt, ap);
va_end(ap);
g_state = U_ERROR;
g_message[0] = 0;
LOGE("update: %s", g_error);
}
static void set_message(ustate st, const char *msg) {
pthread_mutex_lock(&g_lock);
g_state = st;
str_copy(g_message, sizeof g_message, msg);
pthread_mutex_unlock(&g_lock);
}
static void asset_url(const cJSON *assets, const char *name, char *out, size_t n) {
const cJSON *a;
out[0] = 0;
cJSON_ArrayForEach(a, assets) {
if (!strcmp(jget_str(a, "name", ""), name)) str_copy(out, n, jget_str(a, "browser_download_url", ""));
}
}
static void *check_thread(void *arg) {
int notify = (int)(long)arg;
http_resp r = {0};
cJSON *j = NULL;
char err[256] = "";
if (http_get_verified(release_url(), &r) != 0) snprintf(err, sizeof err, "can't reach GitHub: %s", r.error);
else if (r.status == 404) snprintf(err, sizeof err, "no releases published yet");
else if (r.status != 200) snprintf(err, sizeof err, "GitHub answered with HTTP %ld", r.status);
else if (!(j = cJSON_Parse(r.body)) || !jget_str(j, "tag_name", "")[0]) snprintf(err, sizeof err, "unexpected reply from GitHub");
http_resp_free(&r);
pthread_mutex_lock(&g_lock);
g_checked_at = time(NULL);
if (err[0]) {
set_error("%s", err);
} else {
const cJSON *assets = cJSON_GetObjectItemCaseSensitive(j, "assets");
const char *tag = jget_str(j, "tag_name", "");
str_copy(g_latest, sizeof g_latest, tag[0] == 'v' ? tag + 1 : tag);
str_copy(g_published, sizeof g_published, jget_str(j, "published_at", ""));
str_copy(g_page_url, sizeof g_page_url, jget_str(j, "html_url", ""));
asset_url(assets, "romm-sync.elf", g_elf_url, sizeof g_elf_url);
asset_url(assets, "manifest.json", g_manifest_url, sizeof g_manifest_url);
asset_url(assets, "manifest.sig", g_sig_url, sizeof g_sig_url);
free(g_notes);
g_notes = strdup(jget_str(j, "body", ""));
g_state = U_IDLE;
g_error[0] = g_message[0] = 0;
int available = newer_than(g_latest, APP_VERSION);
LOGI("update check: latest release %s, running %s", g_latest, APP_VERSION);
if (notify && available && strcmp(g_notified, g_latest) != 0) {
str_copy(g_notified, sizeof g_notified, g_latest);
plat_notify("RomM Sync %s is available. Update it from Settings.", g_latest);
}
}
pthread_mutex_unlock(&g_lock);
cJSON_Delete(j);
return NULL;
}
int update_check(int notify) {
pthread_mutex_lock(&g_lock);
if (busy(g_state)) {
pthread_mutex_unlock(&g_lock);
return -1;
}
g_state = U_CHECKING;
g_message[0] = 0;
pthread_mutex_unlock(&g_lock);
if (thread_start(check_thread, (void *)(long)notify) != 0) {
pthread_mutex_lock(&g_lock);
set_error("cannot start the update check");
pthread_mutex_unlock(&g_lock);
return -1;
}
return 0;
}
void update_tick(void) {
config_lock();
int on = g_cfg.update_check;
config_unlock();
time_t now = time(NULL);
pthread_mutex_lock(&g_lock);
time_t every = g_state == U_ERROR ? RETRY_AFTER_SEC : CHECK_EVERY_SEC;
pthread_mutex_unlock(&g_lock);
if (!on || now - g_auto_checked_at < every) return;
g_auto_checked_at = now;
update_check(1);
}
/* The manifest must carry a valid signature by a trusted key, name the release
* being installed, and match the downloaded payload byte for byte. */
static int verify(const http_resp *man, const http_resp *sig, const unsigned char *elf, size_t elf_len,
const char *want, char *err, size_t en) {
int trusted = 0;
if (sig->len != 64) {
snprintf(err, en, "the release signature is missing or malformed");
return -1;
}
for (size_t i = 0; i < sizeof UPDATE_KEYS / sizeof UPDATE_KEYS[0] && !trusted; i++)
trusted = crypto_ed25519_check((const uint8_t *)sig->body, UPDATE_KEYS[i], (const uint8_t *)man->body, man->len) == 0;
if (!trusted) {
snprintf(err, en, "the release signature doesn't match; not installing it");
return -1;
}
cJSON *m = cJSON_ParseWithLength(man->body, man->len);
int rc = -1;
uint8_t hash[64];
char hex[129];
crypto_sha512(hash, elf, elf_len);
for (int i = 0; i < 64; i++) snprintf(hex + 2 * i, 3, "%02x", hash[i]);
if (!m) snprintf(err, en, "the release manifest is not valid JSON");
else if (strcmp(jget_str(m, "version", ""), want) != 0) snprintf(err, en, "the manifest is for version %s, not %s", jget_str(m, "version", "?"), want);
else if (!newer_than(want, APP_VERSION)) snprintf(err, en, "%s is not newer than this version", want);
else if (jget_num(m, "size", -1) != (double)elf_len) snprintf(err, en, "the download is incomplete");
else if (strcmp(jget_str(m, "sha512", ""), hex) != 0) snprintf(err, en, "the download doesn't match the signed checksum");
else if (elf_len < 4 || memcmp(elf, "\x7f" "ELF", 4) != 0) snprintf(err, en, "the download is not an ELF payload");
else rc = 0;
cJSON_Delete(m);
return rc;
}
static int progress_cb(void *ud, int64_t done, int64_t total) {
(void)ud;
pthread_mutex_lock(&g_lock);
g_done = done;
g_total = total;
pthread_mutex_unlock(&g_lock);
return 0;
}
static void *install_thread(void *arg) {
(void)arg;
char want[32], elf_url[512], man_url[512], sig_url[512], path[PATH_MAX_LEN], err[256] = "";
pthread_mutex_lock(&g_lock);
str_copy(want, sizeof want, g_latest);
str_copy(elf_url, sizeof elf_url, g_elf_url);
str_copy(man_url, sizeof man_url, g_manifest_url);
str_copy(sig_url, sizeof sig_url, g_sig_url);
pthread_mutex_unlock(&g_lock);
path_join(path, sizeof path, plat_data_dir(), "tmp/update.elf");
http_resp man = {0}, sig = {0}, dl = {0};
unsigned char *elf = NULL;
size_t elf_len = 0;
LOGI("update: downloading %s", want);
if (http_get_verified(man_url, &man) != 0 || man.status != 200)
snprintf(err, sizeof err, "can't download the release manifest: %s", man.error);
else if (http_get_verified(sig_url, &sig) != 0 || sig.status != 200)
snprintf(err, sizeof err, "can't download the release signature: %s", sig.error);
else if (http_download_verified(elf_url, path, progress_cb, NULL, &dl) != 0)
snprintf(err, sizeof err, "can't download romm-sync.elf: %s", dl.error);
else if (!(elf = (unsigned char *)read_file(path, &elf_len)))
snprintf(err, sizeof err, "can't read the download");
else if (verify(&man, &sig, elf, elf_len, want, err, sizeof err) == 0)
LOGI("update: %s verified (%zu bytes)", want, elf_len);
http_resp_free(&man);
http_resp_free(&sig);
http_resp_free(&dl);
unlink(path);
if (err[0]) goto fail;
/* Restarting mid-sync or mid-game could miss a save, so wait for a quiet moment. */
for (;;) {
const char *why = sync_game_running() ? "Waiting for the game to close"
: sync_is_running() ? "Waiting for the sync to finish"
: library_busy() ? "Waiting for downloads to finish"
: NULL;
if (!why) break;
set_message(U_WAITING, why);
sleep(2);
}
set_message(U_INSTALLING, "Installing");
int persisted = autostart_replace(elf, elf_len, err, sizeof err);
if (persisted < 0) goto fail;
set_message(U_RESTARTING, persisted ? "Restarting" : "Restarting (until the next reboot, autostart isn't set up)");
plat_notify("Updating RomM Sync to %s", want);
sleep(1); /* lets the UI see the restart coming */
if (plat_launch_elf(elf, elf_len) != 0) {
snprintf(err, sizeof err, "couldn't start the new version (%s).%s", strerror(errno),
persisted ? " It starts with the next reboot." : "");
goto fail;
}
free(elf);
LOGI("update: started %s, waiting to be replaced", want);
sleep(RESTART_TIMEOUT_SEC);
pthread_mutex_lock(&g_lock);
set_error("the new version didn't start. %s", persisted ? "It starts with the next reboot." : "Send romm-sync.elf to the console again.");
pthread_mutex_unlock(&g_lock);
return NULL;
fail:
free(elf);
pthread_mutex_lock(&g_lock);
set_error("%s", err);
pthread_mutex_unlock(&g_lock);
return NULL;
}
int update_install(char *err, int en) {
pthread_mutex_lock(&g_lock);
int rc = -1;
if (busy(g_state)) snprintf(err, (size_t)en, "an update check or install is already running");
else if (!g_latest[0] || !newer_than(g_latest, APP_VERSION)) snprintf(err, (size_t)en, "no newer version found, check again first");
else if (!g_elf_url[0] || !g_manifest_url[0] || !g_sig_url[0])
snprintf(err, (size_t)en, "release %s isn't signed for in-app updates, download it from GitHub instead", g_latest);
else rc = 0;
if (rc == 0) {
g_state = U_DOWNLOADING;
g_error[0] = 0;
str_copy(g_message, sizeof g_message, "Downloading");
g_done = g_total = 0;
}
pthread_mutex_unlock(&g_lock);
if (rc == 0 && thread_start(install_thread, NULL) != 0) {
pthread_mutex_lock(&g_lock);
set_error("cannot start the update");
pthread_mutex_unlock(&g_lock);
snprintf(err, (size_t)en, "cannot start the update");
return -1;
}
return rc;
}
cJSON *update_status(void) {
cJSON *j = cJSON_CreateObject();
cJSON *as = autostart_status();
cJSON_AddStringToObject(j, "current", APP_VERSION);
pthread_mutex_lock(&g_lock);
cJSON_AddStringToObject(j, "state", STATE_NAMES[g_state]);
cJSON_AddStringToObject(j, "message", g_message);
cJSON_AddStringToObject(j, "error", g_error);
cJSON_AddStringToObject(j, "latest", g_latest);
cJSON_AddBoolToObject(j, "available", g_latest[0] && newer_than(g_latest, APP_VERSION));
cJSON_AddBoolToObject(j, "signed", g_manifest_url[0] && g_sig_url[0] && g_elf_url[0]);
cJSON_AddStringToObject(j, "notes", g_notes ? g_notes : "");
cJSON_AddStringToObject(j, "published_at", g_published);
cJSON_AddStringToObject(j, "release_url", g_page_url);
cJSON_AddNumberToObject(j, "checked_at", (double)g_checked_at);
cJSON_AddNumberToObject(j, "done", (double)g_done);
cJSON_AddNumberToObject(j, "total", (double)g_total);
pthread_mutex_unlock(&g_lock);
cJSON_AddBoolToObject(j, "autostart", cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(as, "installed")));
cJSON_Delete(as);
return j;
}
+19
View File
@@ -0,0 +1,19 @@
/* Updating the payload from GitHub releases, when the user asks for it. */
#ifndef ROMM_UPDATE_H
#define ROMM_UPDATE_H
#include "cJSON.h"
/* Looks for a newer release in the background. notify shows a toast if one is found.
* -1 if a check or install is already running. */
int update_check(int notify);
/* The daily check, if turned on. Call it from the main loop. */
void update_tick(void);
/* Downloads, verifies and starts the newer release in the background. */
int update_install(char *err, int en);
cJSON *update_status(void);
#endif
+32
View File
@@ -0,0 +1,32 @@
/* Ed25519 public keys that may sign updates (manifest.sig). The secrets are
* not in the repo: "release" signs in CI, "backup" stays offline in case the
* release key is lost or leaked. tools/release-sign.c makes and uses them. */
#ifndef ROMM_UPDATE_KEYS_H
#define ROMM_UPDATE_KEYS_H
#include <stdint.h>
static const uint8_t UPDATE_KEYS[][32] = {
/* release 95c07581c32ad30b788e1192630149b1c26154175a27e630961e8f8f61e99869 */
{
0x95, 0xc0, 0x75, 0x81, 0xc3, 0x2a, 0xd3, 0x0b,
0x78, 0x8e, 0x11, 0x92, 0x63, 0x01, 0x49, 0xb1,
0xc2, 0x61, 0x54, 0x17, 0x5a, 0x27, 0xe6, 0x30,
0x96, 0x1e, 0x8f, 0x8f, 0x61, 0xe9, 0x98, 0x69},
/* backup 22a0f7402855a956485f884d5cfc42e8efbe01abb10c7d8bf48004a649e384ba */
{
0x22, 0xa0, 0xf7, 0x40, 0x28, 0x55, 0xa9, 0x56,
0x48, 0x5f, 0x88, 0x4d, 0x5c, 0xfc, 0x42, 0xe8,
0xef, 0xbe, 0x01, 0xab, 0xb1, 0x0c, 0x7d, 0x8b,
0xf4, 0x80, 0x04, 0xa6, 0x49, 0xe3, 0x84, 0xba},
#ifdef ROMM_UPDATE_TEST_KEY
/* host builds only: tests/update-test.key, for tests/e2e.sh */
{
0x3a, 0x40, 0x75, 0x35, 0x76, 0x56, 0xd8, 0x24,
0x47, 0x14, 0x8d, 0x05, 0x7d, 0x1e, 0xe0, 0x19,
0xda, 0xc4, 0x05, 0x08, 0xae, 0x62, 0x05, 0x32,
0x42, 0xd9, 0xbc, 0xfd, 0xcd, 0x36, 0x51, 0x7f},
#endif
};
#endif
+15
View File
@@ -24,6 +24,7 @@
#include "state.h"
#include "sync.h"
#include "ui_index.h" /* generated from ui/index.html */
#include "update.h"
#include "util.h"
#define MAX_HEADER (16 * 1024)
@@ -366,6 +367,20 @@ static void route(request *r) {
send_ok(fd);
return;
}
if (is_get && !strcmp(r->path, "/api/update")) {
send_json(fd, 200, update_status());
return;
}
if (is_post && !strcmp(r->path, "/api/update/check")) {
if (update_check(0) != 0) send_error(fd, 409, "an update check or install is already running");
else send_json(fd, 200, update_status());
return;
}
if (is_post && !strcmp(r->path, "/api/update/install")) {
if (update_install(err, sizeof err) != 0) send_error(fd, 409, err);
else send_json(fd, 200, update_status());
return;
}
if (!config_is_paired() && !strncmp(r->path, "/api/", 5)) {
send_error(fd, 409, "not paired with a RomM server yet");
return;
+62 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# End-to-end test of the host build against tests/mock_romm.py.
# make host && tests/e2e.sh
# make host tools && tests/e2e.sh
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
T="$(mktemp -d)"
@@ -19,7 +19,13 @@ wait_sync() { # waits for the history length to reach $1
}
last() { curl -sf "$API/api/status" | python3 -c "import json,sys; h=json.load(sys.stdin)['sync']['history'][-1]; print(h.get('$1', h.get('error','')))"; }
python3 "$ROOT/tests/mock_romm.py" $MOCK_PORT 2>"$T/mock.log" &
REL="$T/release"; mkdir -p "$REL"
MOCK_RELEASE_DIR="$REL" python3 "$ROOT/tests/mock_romm.py" $MOCK_PORT 2>"$T/mock.log" &
# The same mock over HTTPS with a self-signed certificate.
TLS_PORT=8898
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=127.0.0.1 -keyout "$T/tls.pem" -out "$T/tls.crt" 2>/dev/null
cat "$T/tls.crt" >> "$T/tls.pem"
python3 "$ROOT/tests/mock_romm.py" $TLS_PORT "$T/tls.pem" 2>"$T/mock-tls.log" &
RA="$T/RetroArch"; mkdir -p "$RA/roms/snes" "$RA/saves/Snes9x" "$T/data"
# RetroArch defaults: saves sorted into a folder per core name.
printf 'savefile_directory = ":/saves"\nsort_savefiles_enable = "true"\n' > "$RA/retroarch.cfg"
@@ -42,9 +48,22 @@ echo 'savefile_directory = ":/savefiles"' > "$HB/config/retroarch.cfg"
printf 'corename = "Snes9x"\ndatabase = "Nintendo - Super Nintendo Entertainment System|Nintendo - Satellaview"\n' > "$HB/cores/snes9x_libretro.info"
printf 'corename = "LRPS2"\ndatabase = "Sony - PlayStation 2"\n' > "$HB/cores/pcsx2_libretro.info"
echo '{"titleId":"PPSA12345","localizedParameters":{"defaultLanguage":"en-US","en-US":{"titleName":"RetroArch"}}}' > "$HB/sce_sys/param.json"
ROMM_SYNC_HOMEBREW="$T/homebrew" ROMM_SYNC_DATA="$T/data" "$ROOT/build/host/romm-sync" >"$T/daemon.log" 2>&1 &
# An installed payload in a stand-in etaHEN folder, for the update test.
mkdir -p "$T/etaHEN/payloads"; echo "old-payload" > "$T/etaHEN/payloads/romm-sync.elf"
ROMM_SYNC_HOMEBREW="$T/homebrew" ROMM_SYNC_DATA="$T/data" ROMM_SYNC_ETAHEN="$T/etaHEN" \
ROMM_SYNC_UPDATE_URL="http://127.0.0.1:$MOCK_PORT/_github/release" "$ROOT/build/host/romm-sync" >"$T/daemon.log" 2>&1 &
sleep 6 # let the (unpaired, skipped) startup sync pass
echo "0. self-signed HTTPS needs certificate checks turned off"
r=$(curl -s -X POST "$API/api/pair/start" -d "{\"server_url\":\"https://127.0.0.1:$TLS_PORT\"}")
[[ "$r" == *"doesn't trust"* ]] || fail "untrusted certificate not reported: $r"
r=$(curl -s -X POST "$API/api/pair/start" -d "{\"server_url\":\"127.0.0.1:$TLS_PORT\"}")
[[ "$r" == *"doesn't trust"* ]] || fail "an address without a scheme must not fall back to http on a certificate error: $r"
post /api/config '{"tls_verify":false}' >/dev/null
r=$(curl -s -X POST "$API/api/pair/start" -d "{\"server_url\":\"https://127.0.0.1:$TLS_PORT\"}")
[[ "$r" == *pending* ]] || fail "pairing with checks off failed: $r"
post /api/pair/forget >/dev/null; post /api/config '{"tls_verify":true}' >/dev/null
echo "1. setup: pair, detect emulators, preview, first sync"
post /api/pair/start "{\"server_url\":\"http://127.0.0.1:$MOCK_PORT\"}" >/dev/null
for _ in $(seq 1 20); do [[ "$(curl -sf "$API/api/status" | python3 -c "import json,sys; print(json.load(sys.stdin)['paired'])")" == True ]] && break; sleep 0.5; done
@@ -66,6 +85,9 @@ curl -sf -X POST "http://127.0.0.1:$MOCK_PORT/_admin/save" -d '{"rom_id":11,"slo
post /api/sync >/dev/null; wait_sync 2
[[ "$(cat "$RA/saves/Snes9x/Super Metroid (USA).srm")" == "server-save" ]] || fail "server save not downloaded"
ci=$(curl -sf "$API/api/roms?platform_id=1" | python3 -c "import json,sys; print(sorted(json.load(sys.stdin)['char_index'].items()))")
[[ "$ci" == "[('c', 0), ('e', 1), ('s', 2)]" ]] || fail "library char_index for the A-Z ribbon: $ci"
echo "3. nothing changed, nothing transferred"
post /api/sync >/dev/null; wait_sync 3
[[ "$(last uploaded)$(last downloaded)" == "00" ]] || fail "expected nothing to transfer"
@@ -202,4 +224,41 @@ syncnow
[[ -f "$SD/ULUS10336GAMEDATA/BIG.BIN" ]] || fail "game data folder must be left alone"
ls "$T/data/backups/30/" | grep -q "ULUS10336.zip" || fail "no backup of the PSP save"
echo "13. in-app update: only a correctly signed release installs"
SIGN="$ROOT/build/host/release-sign"
upd() { curl -sf "$API/api/update" | python3 -c "import json,sys; u=json.load(sys.stdin); print(u['$1'])"; }
# Publishes a release; $1 says what to break: tamper, wrongkey, unsigned or nothing.
publish() {
rm -f "$REL"/*; printf '\x7fELF new-payload %s' "$RANDOM" > "$REL/romm-sync.elf"
"$SIGN" manifest v9.9.9 "$REL/romm-sync.elf" > "$REL/manifest.json"
local key; key="$(cat "$ROOT/tests/update-test.key")"
[[ "$1" == wrongkey ]] && key="$("$SIGN" keygen | sed -n 's/^secret: //p')"
RELEASE_SIGNING_KEY="$key" "$SIGN" sign "$REL/manifest.json" > "$REL/manifest.sig" 2>/dev/null
[[ "$1" == tamper ]] && python3 -c "import sys; p=sys.argv[1]; b=bytearray(open(p,'rb').read()); b[-1]^=1; open(p,'wb').write(b)" "$REL/romm-sync.elf"
local names='"romm-sync.elf", "manifest.json", "manifest.sig"'; [[ "$1" == unsigned ]] && names='"romm-sync.elf"'
python3 - "$REL" "http://127.0.0.1:$MOCK_PORT/_github/assets" "$names" <<'PY'
import json, sys
d, base, names = sys.argv[1], sys.argv[2], json.loads("[" + sys.argv[3] + "]")
json.dump({"tag_name": "v9.9.9", "body": "Test notes", "html_url": "https://example.invalid/r",
"assets": [{"name": n, "browser_download_url": base + "/" + n} for n in names]}, open(d + "/release.json", "w"))
PY
post /api/update/check >/dev/null || fail "update check refused"
for _ in $(seq 1 20); do [[ "$(upd state)" != checking ]] && break; sleep 0.5; done
[[ "$(upd available)" == True && "$(upd latest)" == 9.9.9 ]] || fail "release 9.9.9 not found: $(upd error)"
}
install_err() { # installs and prints the error it ends with, or the state it reached
post /api/update/install >/dev/null || { echo refused; return; }
for _ in $(seq 1 40); do local s; s="$(upd state)"; [[ "$s" == error ]] && { upd error; return; }; [[ "$s" == restarting ]] && { echo restarting; return; }; sleep 0.5; done
echo "timeout: $(upd state)"
}
publish tamper; r="$(install_err)"; [[ "$r" == *"signed checksum"* ]] || fail "tampered payload: $r"
publish wrongkey; r="$(install_err)"; [[ "$r" == *"signature doesn't match"* ]] || fail "untrusted key: $r"
publish unsigned; r="$(install_err)"; [[ "$r" == refused ]] || fail "unsigned release must be refused: $r"
[[ "$(cat "$T/etaHEN/payloads/romm-sync.elf")" == old-payload && ! -f "$T/data/launched.elf" ]] || fail "a rejected update touched the payload"
publish ok; r="$(install_err)"; [[ "$r" == restarting ]] || fail "good update: $r"
for _ in $(seq 1 10); do [[ -f "$T/data/launched.elf" ]] && break; sleep 0.5; done
cmp -s "$REL/romm-sync.elf" "$T/data/launched.elf" || fail "the new payload was not launched"
cmp -s "$REL/romm-sync.elf" "$T/etaHEN/payloads/romm-sync.elf" || fail "the installed payload was not replaced"
[[ "$(cat "$T/etaHEN/payloads/romm-sync.elf.bak")" == old-payload ]] || fail "no backup of the old payload"
echo "PASS"
+27 -5
View File
@@ -4,15 +4,18 @@ It is not RomM. Please don't point anything real at it.
Negotiate follows backend/endpoints/sync.py from RomM 5.2.0.
python3 tests/mock_romm.py 8899
python3 tests/mock_romm.py 8899 [cert.pem] (with a cert+key PEM, serves HTTPS)
POST /_admin/save adds a save as if another device uploaded it.
GET /_admin/dump returns everything the mock holds.
GET /_github/release stands in for GitHub's latest-release API: it serves
release.json from $MOCK_RELEASE_DIR, and /_github/assets/<name> the files next to it.
"""
import email.parser
import email.policy
import hashlib
import json
import os
import sys
import threading
from datetime import datetime, timezone
@@ -183,6 +186,13 @@ class H(BaseHTTPRequestHandler):
if pend["polls"] < 2:
return self.reply(400, {"detail": "authorization_pending"})
return self.reply(200, {"access_token": TOKEN, "device_id": DEVICE_ID, "scopes": [], "expires_at": None})
if parts[0] == "_github":
d = os.environ.get("MOCK_RELEASE_DIR", "")
name = "release.json" if p == "/_github/release" else parts[-1] if parts[1:2] == ["assets"] else ""
f = os.path.join(d, os.path.basename(name)) if d and name else ""
if not f or not os.path.isfile(f):
return self.reply(404, {"message": "Not Found"})
return self.reply(200, raw=open(f, "rb").read(), ctype="application/octet-stream")
if p == "/_admin/save" and method == "POST":
b = self.json_body()
import base64
@@ -216,10 +226,16 @@ class H(BaseHTTPRequestHandler):
if p == "/api/roms":
ids = [int(x) for x in q.get("platform_ids", [])]
term = (qs("search_term") or "").lower()
items = [rom_public(r) for r in DB["roms"].values()
if (not ids or r["platform_id"] in ids) and term in r["name"].lower() + r["fs_name"].lower()]
items = sorted((rom_public(r) for r in DB["roms"].values()
if (not ids or r["platform_id"] in ids) and term in r["name"].lower() + r["fs_name"].lower()),
key=lambda r: r["name"].lower())
char_index = {}
for i, r in enumerate(items):
c = r["name"][:1].lower()
char_index.setdefault(c if c.isalpha() else "0", i)
off, lim = int(qs("offset", 0)), int(qs("limit", 50))
return self.reply(200, {"items": items[off:off + lim], "total": len(items), "limit": lim, "offset": off})
return self.reply(200, {"items": items[off:off + lim], "total": len(items), "limit": lim, "offset": off,
"char_index": char_index})
if len(parts) == 3 and parts[:2] == ["api", "roms"]:
return self.reply(200, rom_public(DB["roms"][int(parts[2])]))
if len(parts) == 5 and parts[:2] == ["api", "roms"] and parts[3] == "content":
@@ -368,4 +384,10 @@ class H(BaseHTTPRequestHandler):
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8899
ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever()
srv = ThreadingHTTPServer((os.environ.get("MOCK_HOST", "127.0.0.1"), port), H)
if len(sys.argv) > 2:
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(sys.argv[2])
srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
srv.serve_forever()
+1
View File
@@ -0,0 +1 @@
61c58ae98af2a8ed08dcf8778696bab7b33f3f684bfdf89bdab1147bbf717760
+500
View File
@@ -0,0 +1,500 @@
// Monocypher version 4.0.2
//
// This file is dual-licensed. Choose whichever licence you want from
// the two licences listed below.
//
// The first licence is a regular 2-clause BSD licence. The second licence
// is the CC-0 from Creative Commons. It is intended to release Monocypher
// to the public domain. The BSD licence serves as a fallback option.
//
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
//
// ------------------------------------------------------------------------
//
// Copyright (c) 2017-2019, Loup Vaillant
// All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ------------------------------------------------------------------------
//
// Written in 2017-2019 by Loup Vaillant
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <https://creativecommons.org/publicdomain/zero/1.0/>
#include "monocypher-ed25519.h"
#ifdef MONOCYPHER_CPP_NAMESPACE
namespace MONOCYPHER_CPP_NAMESPACE {
#endif
/////////////////
/// Utilities ///
/////////////////
#define FOR(i, min, max) for (size_t i = min; i < max; i++)
#define COPY(dst, src, size) FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_]
#define ZERO(buf, size) FOR(_i_, 0, size) (buf)[_i_] = 0
#define WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx)))
#define WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer))
#define MIN(a, b) ((a) <= (b) ? (a) : (b))
typedef uint8_t u8;
typedef uint64_t u64;
// Returns the smallest positive integer y such that
// (x + y) % pow_2 == 0
// Basically, it's how many bytes we need to add to "align" x.
// Only works when pow_2 is a power of 2.
// Note: we use ~x+1 instead of -x to avoid compiler warnings
static size_t align(size_t x, size_t pow_2)
{
return (~x + 1) & (pow_2 - 1);
}
static u64 load64_be(const u8 s[8])
{
return((u64)s[0] << 56)
| ((u64)s[1] << 48)
| ((u64)s[2] << 40)
| ((u64)s[3] << 32)
| ((u64)s[4] << 24)
| ((u64)s[5] << 16)
| ((u64)s[6] << 8)
| (u64)s[7];
}
static void store64_be(u8 out[8], u64 in)
{
out[0] = (in >> 56) & 0xff;
out[1] = (in >> 48) & 0xff;
out[2] = (in >> 40) & 0xff;
out[3] = (in >> 32) & 0xff;
out[4] = (in >> 24) & 0xff;
out[5] = (in >> 16) & 0xff;
out[6] = (in >> 8) & 0xff;
out[7] = in & 0xff;
}
static void load64_be_buf (u64 *dst, const u8 *src, size_t size) {
FOR(i, 0, size) { dst[i] = load64_be(src + i*8); }
}
///////////////
/// SHA 512 ///
///////////////
static u64 rot(u64 x, int c ) { return (x >> c) | (x << (64 - c)); }
static u64 ch (u64 x, u64 y, u64 z) { return (x & y) ^ (~x & z); }
static u64 maj(u64 x, u64 y, u64 z) { return (x & y) ^ ( x & z) ^ (y & z); }
static u64 big_sigma0(u64 x) { return rot(x, 28) ^ rot(x, 34) ^ rot(x, 39); }
static u64 big_sigma1(u64 x) { return rot(x, 14) ^ rot(x, 18) ^ rot(x, 41); }
static u64 lit_sigma0(u64 x) { return rot(x, 1) ^ rot(x, 8) ^ (x >> 7); }
static u64 lit_sigma1(u64 x) { return rot(x, 19) ^ rot(x, 61) ^ (x >> 6); }
static const u64 K[80] = {
0x428a2f98d728ae22,0x7137449123ef65cd,0xb5c0fbcfec4d3b2f,0xe9b5dba58189dbbc,
0x3956c25bf348b538,0x59f111f1b605d019,0x923f82a4af194f9b,0xab1c5ed5da6d8118,
0xd807aa98a3030242,0x12835b0145706fbe,0x243185be4ee4b28c,0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f,0x80deb1fe3b1696b1,0x9bdc06a725c71235,0xc19bf174cf692694,
0xe49b69c19ef14ad2,0xefbe4786384f25e3,0x0fc19dc68b8cd5b5,0x240ca1cc77ac9c65,
0x2de92c6f592b0275,0x4a7484aa6ea6e483,0x5cb0a9dcbd41fbd4,0x76f988da831153b5,
0x983e5152ee66dfab,0xa831c66d2db43210,0xb00327c898fb213f,0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2,0xd5a79147930aa725,0x06ca6351e003826f,0x142929670a0e6e70,
0x27b70a8546d22ffc,0x2e1b21385c26c926,0x4d2c6dfc5ac42aed,0x53380d139d95b3df,
0x650a73548baf63de,0x766a0abb3c77b2a8,0x81c2c92e47edaee6,0x92722c851482353b,
0xa2bfe8a14cf10364,0xa81a664bbc423001,0xc24b8b70d0f89791,0xc76c51a30654be30,
0xd192e819d6ef5218,0xd69906245565a910,0xf40e35855771202a,0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8,0x1e376c085141ab53,0x2748774cdf8eeb99,0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63,0x4ed8aa4ae3418acb,0x5b9cca4f7763e373,0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc,0x78a5636f43172f60,0x84c87814a1f0ab72,0x8cc702081a6439ec,
0x90befffa23631e28,0xa4506cebde82bde9,0xbef9a3f7b2c67915,0xc67178f2e372532b,
0xca273eceea26619c,0xd186b8c721c0c207,0xeada7dd6cde0eb1e,0xf57d4f7fee6ed178,
0x06f067aa72176fba,0x0a637dc5a2c898a6,0x113f9804bef90dae,0x1b710b35131c471b,
0x28db77f523047d84,0x32caab7b40c72493,0x3c9ebe0a15c9bebc,0x431d67c49c100d4c,
0x4cc5d4becb3e42b6,0x597f299cfc657e2a,0x5fcb6fab3ad6faec,0x6c44198c4a475817
};
static void sha512_compress(crypto_sha512_ctx *ctx)
{
u64 a = ctx->hash[0]; u64 b = ctx->hash[1];
u64 c = ctx->hash[2]; u64 d = ctx->hash[3];
u64 e = ctx->hash[4]; u64 f = ctx->hash[5];
u64 g = ctx->hash[6]; u64 h = ctx->hash[7];
FOR (j, 0, 16) {
u64 in = K[j] + ctx->input[j];
u64 t1 = big_sigma1(e) + ch (e, f, g) + h + in;
u64 t2 = big_sigma0(a) + maj(a, b, c);
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
size_t i16 = 0;
FOR(i, 1, 5) {
i16 += 16;
FOR (j, 0, 16) {
ctx->input[j] += lit_sigma1(ctx->input[(j- 2) & 15]);
ctx->input[j] += lit_sigma0(ctx->input[(j-15) & 15]);
ctx->input[j] += ctx->input[(j- 7) & 15];
u64 in = K[i16 + j] + ctx->input[j];
u64 t1 = big_sigma1(e) + ch (e, f, g) + h + in;
u64 t2 = big_sigma0(a) + maj(a, b, c);
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
}
ctx->hash[0] += a; ctx->hash[1] += b;
ctx->hash[2] += c; ctx->hash[3] += d;
ctx->hash[4] += e; ctx->hash[5] += f;
ctx->hash[6] += g; ctx->hash[7] += h;
}
// Write 1 input byte
static void sha512_set_input(crypto_sha512_ctx *ctx, u8 input)
{
size_t word = ctx->input_idx >> 3;
size_t byte = ctx->input_idx & 7;
ctx->input[word] |= (u64)input << (8 * (7 - byte));
}
// Increment a 128-bit "word".
static void sha512_incr(u64 x[2], u64 y)
{
x[1] += y;
if (x[1] < y) {
x[0]++;
}
}
void crypto_sha512_init(crypto_sha512_ctx *ctx)
{
ctx->hash[0] = 0x6a09e667f3bcc908;
ctx->hash[1] = 0xbb67ae8584caa73b;
ctx->hash[2] = 0x3c6ef372fe94f82b;
ctx->hash[3] = 0xa54ff53a5f1d36f1;
ctx->hash[4] = 0x510e527fade682d1;
ctx->hash[5] = 0x9b05688c2b3e6c1f;
ctx->hash[6] = 0x1f83d9abfb41bd6b;
ctx->hash[7] = 0x5be0cd19137e2179;
ctx->input_size[0] = 0;
ctx->input_size[1] = 0;
ctx->input_idx = 0;
ZERO(ctx->input, 16);
}
void crypto_sha512_update(crypto_sha512_ctx *ctx,
const u8 *message, size_t message_size)
{
// Avoid undefined NULL pointer increments with empty messages
if (message_size == 0) {
return;
}
// Align ourselves with word boundaries
if ((ctx->input_idx & 7) != 0) {
size_t nb_bytes = MIN(align(ctx->input_idx, 8), message_size);
FOR (i, 0, nb_bytes) {
sha512_set_input(ctx, message[i]);
ctx->input_idx++;
}
message += nb_bytes;
message_size -= nb_bytes;
}
// Align ourselves with block boundaries
if ((ctx->input_idx & 127) != 0) {
size_t nb_words = MIN(align(ctx->input_idx, 128), message_size) >> 3;
load64_be_buf(ctx->input + (ctx->input_idx >> 3), message, nb_words);
ctx->input_idx += nb_words << 3;
message += nb_words << 3;
message_size -= nb_words << 3;
}
// Compress block if needed
if (ctx->input_idx == 128) {
sha512_incr(ctx->input_size, 1024); // size is in bits
sha512_compress(ctx);
ctx->input_idx = 0;
ZERO(ctx->input, 16);
}
// Process the message block by block
FOR (i, 0, message_size >> 7) { // number of blocks
load64_be_buf(ctx->input, message, 16);
sha512_incr(ctx->input_size, 1024); // size is in bits
sha512_compress(ctx);
ctx->input_idx = 0;
ZERO(ctx->input, 16);
message += 128;
}
message_size &= 127;
if (message_size != 0) {
// Remaining words
size_t nb_words = message_size >> 3;
load64_be_buf(ctx->input, message, nb_words);
ctx->input_idx += nb_words << 3;
message += nb_words << 3;
message_size -= nb_words << 3;
// Remaining bytes
FOR (i, 0, message_size) {
sha512_set_input(ctx, message[i]);
ctx->input_idx++;
}
}
}
void crypto_sha512_final(crypto_sha512_ctx *ctx, u8 hash[64])
{
// Add padding bit
if (ctx->input_idx == 0) {
ZERO(ctx->input, 16);
}
sha512_set_input(ctx, 128);
// Update size
sha512_incr(ctx->input_size, ctx->input_idx * 8);
// Compress penultimate block (if any)
if (ctx->input_idx > 111) {
sha512_compress(ctx);
ZERO(ctx->input, 14);
}
// Compress last block
ctx->input[14] = ctx->input_size[0];
ctx->input[15] = ctx->input_size[1];
sha512_compress(ctx);
// Copy hash to output (big endian)
FOR (i, 0, 8) {
store64_be(hash + i*8, ctx->hash[i]);
}
WIPE_CTX(ctx);
}
void crypto_sha512(u8 hash[64], const u8 *message, size_t message_size)
{
crypto_sha512_ctx ctx;
crypto_sha512_init (&ctx);
crypto_sha512_update(&ctx, message, message_size);
crypto_sha512_final (&ctx, hash);
}
////////////////////
/// HMAC SHA 512 ///
////////////////////
void crypto_sha512_hmac_init(crypto_sha512_hmac_ctx *ctx,
const u8 *key, size_t key_size)
{
// hash key if it is too long
if (key_size > 128) {
crypto_sha512(ctx->key, key, key_size);
key = ctx->key;
key_size = 64;
}
// Compute inner key: padded key XOR 0x36
FOR (i, 0, key_size) { ctx->key[i] = key[i] ^ 0x36; }
FOR (i, key_size, 128) { ctx->key[i] = 0x36; }
// Start computing inner hash
crypto_sha512_init (&ctx->ctx);
crypto_sha512_update(&ctx->ctx, ctx->key, 128);
}
void crypto_sha512_hmac_update(crypto_sha512_hmac_ctx *ctx,
const u8 *message, size_t message_size)
{
crypto_sha512_update(&ctx->ctx, message, message_size);
}
void crypto_sha512_hmac_final(crypto_sha512_hmac_ctx *ctx, u8 hmac[64])
{
// Finish computing inner hash
crypto_sha512_final(&ctx->ctx, hmac);
// Compute outer key: padded key XOR 0x5c
FOR (i, 0, 128) {
ctx->key[i] ^= 0x36 ^ 0x5c;
}
// Compute outer hash
crypto_sha512_init (&ctx->ctx);
crypto_sha512_update(&ctx->ctx, ctx->key , 128);
crypto_sha512_update(&ctx->ctx, hmac, 64);
crypto_sha512_final (&ctx->ctx, hmac); // outer hash
WIPE_CTX(ctx);
}
void crypto_sha512_hmac(u8 hmac[64], const u8 *key, size_t key_size,
const u8 *message, size_t message_size)
{
crypto_sha512_hmac_ctx ctx;
crypto_sha512_hmac_init (&ctx, key, key_size);
crypto_sha512_hmac_update(&ctx, message, message_size);
crypto_sha512_hmac_final (&ctx, hmac);
}
////////////////////
/// HKDF SHA 512 ///
////////////////////
void crypto_sha512_hkdf_expand(u8 *okm, size_t okm_size,
const u8 *prk, size_t prk_size,
const u8 *info, size_t info_size)
{
int not_first = 0;
u8 ctr = 1;
u8 blk[64];
while (okm_size > 0) {
size_t out_size = MIN(okm_size, sizeof(blk));
crypto_sha512_hmac_ctx ctx;
crypto_sha512_hmac_init(&ctx, prk , prk_size);
if (not_first) {
// For some reason HKDF uses some kind of CBC mode.
// For some reason CTR mode alone wasn't enough.
// Like what, they didn't trust HMAC in 2010? Really??
crypto_sha512_hmac_update(&ctx, blk , sizeof(blk));
}
crypto_sha512_hmac_update(&ctx, info, info_size);
crypto_sha512_hmac_update(&ctx, &ctr, 1);
crypto_sha512_hmac_final(&ctx, blk);
COPY(okm, blk, out_size);
not_first = 1;
okm += out_size;
okm_size -= out_size;
ctr++;
}
}
void crypto_sha512_hkdf(u8 *okm , size_t okm_size,
const u8 *ikm , size_t ikm_size,
const u8 *salt, size_t salt_size,
const u8 *info, size_t info_size)
{
// Extract
u8 prk[64];
crypto_sha512_hmac(prk, salt, salt_size, ikm, ikm_size);
// Expand
crypto_sha512_hkdf_expand(okm, okm_size, prk, sizeof(prk), info, info_size);
}
///////////////
/// Ed25519 ///
///////////////
void crypto_ed25519_key_pair(u8 secret_key[64], u8 public_key[32], u8 seed[32])
{
u8 a[64];
COPY(a, seed, 32); // a[ 0..31] = seed
crypto_wipe(seed, 32);
COPY(secret_key, a, 32); // secret key = seed
crypto_sha512(a, a, 32); // a[ 0..31] = scalar
crypto_eddsa_trim_scalar(a, a); // a[ 0..31] = trimmed scalar
crypto_eddsa_scalarbase(public_key, a); // public key = [trimmed scalar]B
COPY(secret_key + 32, public_key, 32); // secret key includes public half
WIPE_BUFFER(a);
}
static void hash_reduce(u8 h[32],
const u8 *a, size_t a_size,
const u8 *b, size_t b_size,
const u8 *c, size_t c_size,
const u8 *d, size_t d_size)
{
u8 hash[64];
crypto_sha512_ctx ctx;
crypto_sha512_init (&ctx);
crypto_sha512_update(&ctx, a, a_size);
crypto_sha512_update(&ctx, b, b_size);
crypto_sha512_update(&ctx, c, c_size);
crypto_sha512_update(&ctx, d, d_size);
crypto_sha512_final (&ctx, hash);
crypto_eddsa_reduce(h, hash);
}
static void ed25519_dom_sign(u8 signature [64], const u8 secret_key[32],
const u8 *dom, size_t dom_size,
const u8 *message, size_t message_size)
{
u8 a[64]; // secret scalar and prefix
u8 r[32]; // secret deterministic "random" nonce
u8 h[32]; // publically verifiable hash of the message (not wiped)
u8 R[32]; // first half of the signature (allows overlapping inputs)
const u8 *pk = secret_key + 32;
crypto_sha512(a, secret_key, 32);
crypto_eddsa_trim_scalar(a, a);
hash_reduce(r, dom, dom_size, a + 32, 32, message, message_size, 0, 0);
crypto_eddsa_scalarbase(R, r);
hash_reduce(h, dom, dom_size, R, 32, pk, 32, message, message_size);
COPY(signature, R, 32);
crypto_eddsa_mul_add(signature + 32, h, a, r);
WIPE_BUFFER(a);
WIPE_BUFFER(r);
}
void crypto_ed25519_sign(u8 signature [64], const u8 secret_key[64],
const u8 *message, size_t message_size)
{
ed25519_dom_sign(signature, secret_key, 0, 0, message, message_size);
}
int crypto_ed25519_check(const u8 signature[64], const u8 public_key[32],
const u8 *msg, size_t msg_size)
{
u8 h_ram[32];
hash_reduce(h_ram, signature, 32, public_key, 32, msg, msg_size, 0, 0);
return crypto_eddsa_check_equation(signature, public_key, h_ram);
}
static const u8 domain[34] = "SigEd25519 no Ed25519 collisions\1";
void crypto_ed25519_ph_sign(uint8_t signature[64], const uint8_t secret_key[64],
const uint8_t message_hash[64])
{
ed25519_dom_sign(signature, secret_key, domain, sizeof(domain),
message_hash, 64);
}
int crypto_ed25519_ph_check(const uint8_t sig[64], const uint8_t pk[32],
const uint8_t msg_hash[64])
{
u8 h_ram[32];
hash_reduce(h_ram, domain, sizeof(domain), sig, 32, pk, 32, msg_hash, 64);
return crypto_eddsa_check_equation(sig, pk, h_ram);
}
#ifdef MONOCYPHER_CPP_NAMESPACE
}
#endif
+140
View File
@@ -0,0 +1,140 @@
// Monocypher version 4.0.2
//
// This file is dual-licensed. Choose whichever licence you want from
// the two licences listed below.
//
// The first licence is a regular 2-clause BSD licence. The second licence
// is the CC-0 from Creative Commons. It is intended to release Monocypher
// to the public domain. The BSD licence serves as a fallback option.
//
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
//
// ------------------------------------------------------------------------
//
// Copyright (c) 2017-2019, Loup Vaillant
// All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ------------------------------------------------------------------------
//
// Written in 2017-2019 by Loup Vaillant
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <https://creativecommons.org/publicdomain/zero/1.0/>
#ifndef ED25519_H
#define ED25519_H
#include "monocypher.h"
#ifdef MONOCYPHER_CPP_NAMESPACE
namespace MONOCYPHER_CPP_NAMESPACE {
#elif defined(__cplusplus)
extern "C" {
#endif
////////////////////////
/// Type definitions ///
////////////////////////
// Do not rely on the size or content on any of those types,
// they may change without notice.
typedef struct {
uint64_t hash[8];
uint64_t input[16];
uint64_t input_size[2];
size_t input_idx;
} crypto_sha512_ctx;
typedef struct {
uint8_t key[128];
crypto_sha512_ctx ctx;
} crypto_sha512_hmac_ctx;
// SHA 512
// -------
void crypto_sha512_init (crypto_sha512_ctx *ctx);
void crypto_sha512_update(crypto_sha512_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_sha512_final (crypto_sha512_ctx *ctx, uint8_t hash[64]);
void crypto_sha512(uint8_t hash[64],
const uint8_t *message, size_t message_size);
// SHA 512 HMAC
// ------------
void crypto_sha512_hmac_init(crypto_sha512_hmac_ctx *ctx,
const uint8_t *key, size_t key_size);
void crypto_sha512_hmac_update(crypto_sha512_hmac_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_sha512_hmac_final(crypto_sha512_hmac_ctx *ctx, uint8_t hmac[64]);
void crypto_sha512_hmac(uint8_t hmac[64],
const uint8_t *key , size_t key_size,
const uint8_t *message, size_t message_size);
// SHA 512 HKDF
// ------------
void crypto_sha512_hkdf_expand(uint8_t *okm, size_t okm_size,
const uint8_t *prk, size_t prk_size,
const uint8_t *info, size_t info_size);
void crypto_sha512_hkdf(uint8_t *okm , size_t okm_size,
const uint8_t *ikm , size_t ikm_size,
const uint8_t *salt, size_t salt_size,
const uint8_t *info, size_t info_size);
// Ed25519
// -------
// Signatures (EdDSA with curve25519 + SHA-512)
// --------------------------------------------
void crypto_ed25519_key_pair(uint8_t secret_key[64],
uint8_t public_key[32],
uint8_t seed[32]);
void crypto_ed25519_sign(uint8_t signature [64],
const uint8_t secret_key[64],
const uint8_t *message, size_t message_size);
int crypto_ed25519_check(const uint8_t signature [64],
const uint8_t public_key[32],
const uint8_t *message, size_t message_size);
// Pre-hash variants
void crypto_ed25519_ph_sign(uint8_t signature [64],
const uint8_t secret_key [64],
const uint8_t message_hash[64]);
int crypto_ed25519_ph_check(const uint8_t signature [64],
const uint8_t public_key [32],
const uint8_t message_hash[64]);
#ifdef __cplusplus
}
#endif
#endif // ED25519_H
+167
View File
@@ -0,0 +1,167 @@
Monocypher as a whole is dual-licensed. Choose whichever licence you
want from the two licences listed below.
The first licence is a regular 2-clause BSD licence. The second licence
is the CC-0 from Creative Commons. It is intended to release Monocypher
to the public domain. The BSD licence serves as a fallback option.
See the individual files for specific information about who contributed
to what file during which years. See below for special notes.
Licence 1 (2-clause BSD)
------------------------
Copyright (c) 2017-2023, Loup Vaillant
Copyright (c) 2017-2019, Michael Savage
Copyright (c) 2017-2023, Fabio Scotoni
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Licence 2 (CC-0)
----------------
> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
> LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
> ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
> INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
> REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
> PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
> THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
> HEREUNDER.
### Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work
of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without
fear of later claims of infringement build upon, modify, incorporate in
other works, reuse and redistribute as freely as possible in any form
whatsoever and for any purposes, including without limitation commercial
purposes. These owners may contribute to the Commons to promote the
ideal of a free culture and the further production of creative, cultural
and scientific works, or to gain reputation or greater distribution for
their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or
she is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under
its terms, with knowledge of his or her Copyright and Related Rights in
the Work and the meaning and intended legal effect of CC0 on those
rights.
1. **Copyright and Related Rights.** A Work made available under CC0 may
be protected by copyright and related or neighboring rights
("Copyright and Related Rights"). Copyright and Related Rights
include, but are not limited to, the following:
- the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
- moral rights retained by the original author(s) and/or
performer(s); publicity and privacy rights pertaining to a person's
image or likeness depicted in a Work;
- rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
- rights protecting the extraction, dissemination, use and reuse of
data in a Work;
- database rights (such as those arising under Directive 96/9/EC of
the European Parliament and of the Council of 11 March 1996 on the
legal protection of databases, and under any national
implementation thereof, including any amended or successor version
of such directive); and
- other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. **Waiver.** To the greatest extent permitted by, but not in
contravention of, applicable law, Affirmer hereby overtly, fully,
permanently, irrevocably and unconditionally waives, abandons, and
surrenders all of Affirmer's Copyright and Related Rights and
associated claims and causes of action, whether now known or unknown
(including existing as well as future claims and causes of action),
in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"Waiver"). Affirmer makes the Waiver for the benefit of each member
of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal
or equitable action to disrupt the quiet enjoyment of the Work by the
public as contemplated by Affirmer's express Statement of Purpose.
3. **Public License Fallback.** Should any part of the Waiver for any
reason be judged legally invalid or ineffective under applicable law,
then the Waiver shall be preserved to the maximum extent permitted
taking into account Affirmer's express Statement of Purpose. In
addition, to the extent the Waiver is so judged Affirmer hereby
grants to each affected person a royalty-free, non transferable, non
sublicensable, non exclusive, irrevocable and unconditional license
to exercise Affirmer's Copyright and Related Rights in the Work (i)
in all territories worldwide, (ii) for the maximum duration provided
by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and
(iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "License"). The
License shall be deemed effective as of the date CC0 was applied by
Affirmer to the Work. Should any part of the License for any reason
be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the
remainder of the License, and in such case Affirmer hereby affirms
that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any
associated claims and causes of action with respect to the Work, in
either case contrary to Affirmer's express Statement of Purpose.
4. **Limitations and Disclaimers.**
- No trademark or patent rights held by Affirmer are waived,
abandoned, surrendered, licensed or otherwise affected by this
document.
- Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy,
or the present or absence of errors, whether or not discoverable,
all to the greatest extent permissible under applicable law.
- Affirmer disclaims responsibility for clearing rights of other
persons that may apply to the Work or any use thereof, including
without limitation any person's Copyright and Related Rights in the
Work. Further, Affirmer disclaims responsibility for obtaining any
necessary consents, permissions or other rights required for any
use of the Work.
- Affirmer understands and acknowledges that Creative Commons is not
a party to this document and has no duty or obligation with respect
to this CC0 or use of the Work.
+2956
View File
File diff suppressed because it is too large. Load diff
+321
View File
@@ -0,0 +1,321 @@
// Monocypher version 4.0.2
//
// This file is dual-licensed. Choose whichever licence you want from
// the two licences listed below.
//
// The first licence is a regular 2-clause BSD licence. The second licence
// is the CC-0 from Creative Commons. It is intended to release Monocypher
// to the public domain. The BSD licence serves as a fallback option.
//
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
//
// ------------------------------------------------------------------------
//
// Copyright (c) 2017-2019, Loup Vaillant
// All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ------------------------------------------------------------------------
//
// Written in 2017-2019 by Loup Vaillant
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <https://creativecommons.org/publicdomain/zero/1.0/>
#ifndef MONOCYPHER_H
#define MONOCYPHER_H
#include <stddef.h>
#include <stdint.h>
#ifdef MONOCYPHER_CPP_NAMESPACE
namespace MONOCYPHER_CPP_NAMESPACE {
#elif defined(__cplusplus)
extern "C" {
#endif
// Constant time comparisons
// -------------------------
// Return 0 if a and b are equal, -1 otherwise
int crypto_verify16(const uint8_t a[16], const uint8_t b[16]);
int crypto_verify32(const uint8_t a[32], const uint8_t b[32]);
int crypto_verify64(const uint8_t a[64], const uint8_t b[64]);
// Erase sensitive data
// --------------------
void crypto_wipe(void *secret, size_t size);
// Authenticated encryption
// ------------------------
void crypto_aead_lock(uint8_t *cipher_text,
uint8_t mac [16],
const uint8_t key [32],
const uint8_t nonce[24],
const uint8_t *ad, size_t ad_size,
const uint8_t *plain_text, size_t text_size);
int crypto_aead_unlock(uint8_t *plain_text,
const uint8_t mac [16],
const uint8_t key [32],
const uint8_t nonce[24],
const uint8_t *ad, size_t ad_size,
const uint8_t *cipher_text, size_t text_size);
// Authenticated stream
// --------------------
typedef struct {
uint64_t counter;
uint8_t key[32];
uint8_t nonce[8];
} crypto_aead_ctx;
void crypto_aead_init_x(crypto_aead_ctx *ctx,
const uint8_t key[32], const uint8_t nonce[24]);
void crypto_aead_init_djb(crypto_aead_ctx *ctx,
const uint8_t key[32], const uint8_t nonce[8]);
void crypto_aead_init_ietf(crypto_aead_ctx *ctx,
const uint8_t key[32], const uint8_t nonce[12]);
void crypto_aead_write(crypto_aead_ctx *ctx,
uint8_t *cipher_text,
uint8_t mac[16],
const uint8_t *ad , size_t ad_size,
const uint8_t *plain_text, size_t text_size);
int crypto_aead_read(crypto_aead_ctx *ctx,
uint8_t *plain_text,
const uint8_t mac[16],
const uint8_t *ad , size_t ad_size,
const uint8_t *cipher_text, size_t text_size);
// General purpose hash (BLAKE2b)
// ------------------------------
// Direct interface
void crypto_blake2b(uint8_t *hash, size_t hash_size,
const uint8_t *message, size_t message_size);
void crypto_blake2b_keyed(uint8_t *hash, size_t hash_size,
const uint8_t *key, size_t key_size,
const uint8_t *message, size_t message_size);
// Incremental interface
typedef struct {
// Do not rely on the size or contents of this type,
// for they may change without notice.
uint64_t hash[8];
uint64_t input_offset[2];
uint64_t input[16];
size_t input_idx;
size_t hash_size;
} crypto_blake2b_ctx;
void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size);
void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size,
const uint8_t *key, size_t key_size);
void crypto_blake2b_update(crypto_blake2b_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_blake2b_final(crypto_blake2b_ctx *ctx, uint8_t *hash);
// Password key derivation (Argon2)
// --------------------------------
#define CRYPTO_ARGON2_D 0
#define CRYPTO_ARGON2_I 1
#define CRYPTO_ARGON2_ID 2
typedef struct {
uint32_t algorithm; // Argon2d, Argon2i, Argon2id
uint32_t nb_blocks; // memory hardness, >= 8 * nb_lanes
uint32_t nb_passes; // CPU hardness, >= 1 (>= 3 recommended for Argon2i)
uint32_t nb_lanes; // parallelism level (single threaded anyway)
} crypto_argon2_config;
typedef struct {
const uint8_t *pass;
const uint8_t *salt;
uint32_t pass_size;
uint32_t salt_size; // 16 bytes recommended
} crypto_argon2_inputs;
typedef struct {
const uint8_t *key; // may be NULL if no key
const uint8_t *ad; // may be NULL if no additional data
uint32_t key_size; // 0 if no key (32 bytes recommended otherwise)
uint32_t ad_size; // 0 if no additional data
} crypto_argon2_extras;
extern const crypto_argon2_extras crypto_argon2_no_extras;
void crypto_argon2(uint8_t *hash, uint32_t hash_size, void *work_area,
crypto_argon2_config config,
crypto_argon2_inputs inputs,
crypto_argon2_extras extras);
// Key exchange (X-25519)
// ----------------------
// Shared secrets are not quite random.
// Hash them to derive an actual shared key.
void crypto_x25519_public_key(uint8_t public_key[32],
const uint8_t secret_key[32]);
void crypto_x25519(uint8_t raw_shared_secret[32],
const uint8_t your_secret_key [32],
const uint8_t their_public_key [32]);
// Conversion to EdDSA
void crypto_x25519_to_eddsa(uint8_t eddsa[32], const uint8_t x25519[32]);
// scalar "division"
// Used for OPRF. Be aware that exponential blinding is less secure
// than Diffie-Hellman key exchange.
void crypto_x25519_inverse(uint8_t blind_salt [32],
const uint8_t private_key[32],
const uint8_t curve_point[32]);
// "Dirty" versions of x25519_public_key().
// Use with crypto_elligator_rev().
// Leaks 3 bits of the private key.
void crypto_x25519_dirty_small(uint8_t pk[32], const uint8_t sk[32]);
void crypto_x25519_dirty_fast (uint8_t pk[32], const uint8_t sk[32]);
// Signatures
// ----------
// EdDSA with curve25519 + BLAKE2b
void crypto_eddsa_key_pair(uint8_t secret_key[64],
uint8_t public_key[32],
uint8_t seed[32]);
void crypto_eddsa_sign(uint8_t signature [64],
const uint8_t secret_key[64],
const uint8_t *message, size_t message_size);
int crypto_eddsa_check(const uint8_t signature [64],
const uint8_t public_key[32],
const uint8_t *message, size_t message_size);
// Conversion to X25519
void crypto_eddsa_to_x25519(uint8_t x25519[32], const uint8_t eddsa[32]);
// EdDSA building blocks
void crypto_eddsa_trim_scalar(uint8_t out[32], const uint8_t in[32]);
void crypto_eddsa_reduce(uint8_t reduced[32], const uint8_t expanded[64]);
void crypto_eddsa_mul_add(uint8_t r[32],
const uint8_t a[32],
const uint8_t b[32],
const uint8_t c[32]);
void crypto_eddsa_scalarbase(uint8_t point[32], const uint8_t scalar[32]);
int crypto_eddsa_check_equation(const uint8_t signature[64],
const uint8_t public_key[32],
const uint8_t h_ram[32]);
// Chacha20
// --------
// Specialised hash.
// Used to hash X25519 shared secrets.
void crypto_chacha20_h(uint8_t out[32],
const uint8_t key[32],
const uint8_t in [16]);
// Unauthenticated stream cipher.
// Don't forget to add authentication.
uint64_t crypto_chacha20_djb(uint8_t *cipher_text,
const uint8_t *plain_text,
size_t text_size,
const uint8_t key[32],
const uint8_t nonce[8],
uint64_t ctr);
uint32_t crypto_chacha20_ietf(uint8_t *cipher_text,
const uint8_t *plain_text,
size_t text_size,
const uint8_t key[32],
const uint8_t nonce[12],
uint32_t ctr);
uint64_t crypto_chacha20_x(uint8_t *cipher_text,
const uint8_t *plain_text,
size_t text_size,
const uint8_t key[32],
const uint8_t nonce[24],
uint64_t ctr);
// Poly 1305
// ---------
// This is a *one time* authenticator.
// Disclosing the mac reveals the key.
// See crypto_lock() on how to use it properly.
// Direct interface
void crypto_poly1305(uint8_t mac[16],
const uint8_t *message, size_t message_size,
const uint8_t key[32]);
// Incremental interface
typedef struct {
// Do not rely on the size or contents of this type,
// for they may change without notice.
uint8_t c[16]; // chunk of the message
size_t c_idx; // How many bytes are there in the chunk.
uint32_t r [4]; // constant multiplier (from the secret key)
uint32_t pad[4]; // random number added at the end (from the secret key)
uint32_t h [5]; // accumulated hash
} crypto_poly1305_ctx;
void crypto_poly1305_init (crypto_poly1305_ctx *ctx, const uint8_t key[32]);
void crypto_poly1305_update(crypto_poly1305_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_poly1305_final (crypto_poly1305_ctx *ctx, uint8_t mac[16]);
// Elligator 2
// -----------
// Elligator mappings proper
void crypto_elligator_map(uint8_t curve [32], const uint8_t hidden[32]);
int crypto_elligator_rev(uint8_t hidden[32], const uint8_t curve [32],
uint8_t tweak);
// Easy to use key pair generation
void crypto_elligator_key_pair(uint8_t hidden[32], uint8_t secret_key[32],
uint8_t seed[32]);
#ifdef __cplusplus
}
#endif
#endif // MONOCYPHER_H
+107
View File
@@ -0,0 +1,107 @@
/* Signs releases for in-app updates (see src/update.c). Built with "make tools".
*
* release-sign keygen new key: secret seed and public key, hex
* release-sign manifest VERSION romm-sync.elf > manifest.json
* RELEASE_SIGNING_KEY=<seed hex> release-sign sign manifest.json > manifest.sig
* release-sign check manifest.json manifest.sig signed by a key the payload trusts?
*
* The secret is the 32-byte Ed25519 seed as 64 hex characters. It never goes
* in the repo, only in the RELEASE_SIGNING_KEY secret and an offline backup. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "monocypher-ed25519.h"
#include "update_keys.h"
static unsigned char *slurp(const char *path, size_t *len) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(1); }
size_t cap = 1 << 20, n = 0, r;
unsigned char *buf = malloc(cap);
while (buf && (r = fread(buf + n, 1, cap - n, f)) > 0) {
n += r;
if (n == cap) buf = realloc(buf, cap *= 2);
}
fclose(f);
if (!buf) { fprintf(stderr, "out of memory\n"); exit(1); }
*len = n;
return buf;
}
static void hex(const uint8_t *b, size_t n, char *out) {
for (size_t i = 0; i < n; i++) sprintf(out + 2 * i, "%02x", b[i]);
}
static int unhex(const char *s, uint8_t *out, size_t n) {
if (!s || strlen(s) != 2 * n) return -1;
for (size_t i = 0; i < n; i++) {
unsigned v;
if (sscanf(s + 2 * i, "%2x", &v) != 1) return -1;
out[i] = (uint8_t)v;
}
return 0;
}
static int usage(void) {
fprintf(stderr, "usage: release-sign keygen | manifest VERSION ELF | sign FILE | check FILE SIG\n");
return 2;
}
int main(int argc, char **argv) {
if (argc < 2) return usage();
if (!strcmp(argv[1], "keygen")) {
uint8_t seed[32], keep[32], sk[64], pk[32];
char sh[65], ph[65];
FILE *r = fopen("/dev/urandom", "rb");
if (!r || fread(seed, 1, 32, r) != 32) { fprintf(stderr, "no randomness\n"); return 1; }
fclose(r);
memcpy(keep, seed, 32);
crypto_ed25519_key_pair(sk, pk, seed); /* wipes seed */
hex(keep, 32, sh);
hex(pk, 32, ph);
printf("secret: %s\npublic: %s\n", sh, ph);
return 0;
}
if (!strcmp(argv[1], "manifest") && argc == 4) {
size_t len;
unsigned char *elf = slurp(argv[3], &len);
uint8_t h[64];
char hh[129];
crypto_sha512(h, elf, len);
hex(h, 64, hh);
const char *v = argv[2][0] == 'v' ? argv[2] + 1 : argv[2];
printf("{\"version\":\"%s\",\"file\":\"romm-sync.elf\",\"size\":%zu,\"sha512\":\"%s\"}\n", v, len, hh);
return 0;
}
if (!strcmp(argv[1], "sign") && argc == 3) {
uint8_t seed[32], sk[64], pk[32], sig[64];
if (unhex(getenv("RELEASE_SIGNING_KEY"), seed, 32)) {
fprintf(stderr, "RELEASE_SIGNING_KEY must hold the 64-character hex secret\n");
return 1;
}
crypto_ed25519_key_pair(sk, pk, seed);
size_t len;
unsigned char *msg = slurp(argv[2], &len);
crypto_ed25519_sign(sig, sk, msg, len);
fwrite(sig, 1, 64, stdout);
char ph[65];
hex(pk, 32, ph);
fprintf(stderr, "signed %s with key %s\n", argv[2], ph);
return 0;
}
if (!strcmp(argv[1], "check") && argc == 4) {
size_t len, slen;
unsigned char *msg = slurp(argv[2], &len), *sig = slurp(argv[3], &slen);
for (size_t i = 0; slen == 64 && i < sizeof UPDATE_KEYS / sizeof UPDATE_KEYS[0]; i++) {
if (crypto_ed25519_check(sig, UPDATE_KEYS[i], msg, len) == 0) {
fprintf(stderr, "signature OK (trusted key %zu)\n", i);
return 0;
}
}
fprintf(stderr, "signature does NOT match any key in src/update_keys.h\n");
return 1;
}
return usage();
}
+113 -4
View File
@@ -100,6 +100,12 @@ code { background: var(--panel2); padding: 2px 6px; border-radius: 6px; word-bre
[data-collapse].collapsed .collapsible { display: none; }
.notice { border-left: 4px solid var(--warn); background: #2a2210; border-radius: 8px; padding: 12px 16px; margin: 14px 0; }
.notice b { color: #fcd34d; }
a { color: var(--accent2); }
.ribbon { display: flex; flex-wrap: wrap; gap: 4px; margin: -4px 0 14px; }
.ribbon button { min-width: 38px; padding: 6px 0; font-size: 15px; }
.ribbon button:disabled { opacity: .3; }
.ribbon, [data-rom] { scroll-margin-top: 90px; } /* clear of the sticky header */
#updBody details { margin-top: 14px; }
</style>
</head>
<body>
@@ -125,6 +131,7 @@ code { background: var(--panel2); padding: 2px 6px; border-radius: 6px; word-bre
<p class="muted">RomM 5.2.0 or newer.</p>
<label for="srv">Server address</label>
<input id="srv" placeholder="https://romm.example.com or 192.168.1.10:8080" autocomplete="off">
<div class="toggle"><input type="checkbox" id="wzInsecure"><label for="wzInsecure">Skip certificate checks (for self-signed HTTPS)</label></div>
<div class="row" style="margin-top:14px"><button class="primary" id="pairStart">Continue</button></div>
<details style="margin-top:18px">
<summary class="muted">Use a pairing code instead</summary>
@@ -201,6 +208,7 @@ code { background: var(--panel2); padding: 2px 6px; border-radius: 6px; word-bre
</section>
<section id="home" class="active">
<div class="notice" id="updNotice" style="display:none"></div>
<div class="card">
<div class="row">
<h2 style="margin:0">Saves</h2>
@@ -245,6 +253,8 @@ code { background: var(--panel2); padding: 2px 6px; border-radius: 6px; word-bre
<p class="muted" id="platInfo"></p>
<div class="row" style="margin-bottom:14px"><input id="search" placeholder="Search" style="flex:1 1 200px;width:auto"><button id="searchBtn">Search</button>
<div class="seg fixed"><button id="viewGrid">Grid</button><button id="viewTable">Table</button></div></div>
<div class="ribbon" id="ribbon" style="display:none"></div>
<div class="row" id="jumpInfo" style="display:none;margin-bottom:12px"><span class="muted" id="jumpText"></span><button class="small" id="jumpStart">From the start</button></div>
<div id="roms"></div>
<div class="row" style="margin-top:14px"><button id="more" style="display:none">Load more</button></div>
</div>
@@ -269,6 +279,11 @@ code { background: var(--panel2); padding: 2px 6px; border-radius: 6px; word-bre
<p class="muted">Add these feeds to FPKGi. They use your RomM username and password.</p>
<p><code id="feed4"></code><br><code id="feed5"></code></p>
</div>
<div class="card">
<div class="row"><h2 style="margin:0">Updates</h2><button id="updCheck">Check now</button></div>
<div id="updBody"><p class="muted">Checking</p></div>
<div class="toggle"><input type="checkbox" id="updAuto"><label for="updAuto">Check for updates once a day</label></div>
</div>
<div class="card">
<h2>Sync</h2>
<label for="devname">Device name</label><input id="devname">
@@ -431,6 +446,8 @@ function renderStatus(s) {
$("unmatched").innerHTML = sy.unmatched.map(function (u) { return "<li>" + esc(u) + "</li>"; }).join("");
}
function poll() {
poll.n = (poll.n || 0) + 1;
if (poll.n % 10 === 0) loadUpdate();
api("GET", "/api/status").then(renderStatus).catch(function () { $("conn").innerHTML = '<span class="err">&#9679;</span> Can\'t reach RomM Sync'; });
if (document.querySelector("#downloads.active")) loadDownloads();
if (document.querySelector("#library.active") && $("romCard").style.display !== "none") pollLibraryDownloads();
@@ -479,15 +496,17 @@ function wizardFromStatus(s) {
}
if (wz.step < 3) { toast(p.message || "Paired"); wzGo(3); }
}
// The certificate setting has to be in place before the server is first contacted.
function saveTls() { return api("POST", "/api/config", { tls_verify: !$("wzInsecure").checked }); }
$("pairStart").onclick = function () {
$("pairErr").textContent = ""; $("pairStart").disabled = true;
api("POST", "/api/pair/start", { server_url: $("srv").value }).then(function (p) {
saveTls().then(function () { return api("POST", "/api/pair/start", { server_url: $("srv").value }); }).then(function (p) {
$("pairStart").disabled = false; wizardFromStatus({ paired: false, pairing: p });
}).catch(function (e) { $("pairStart").disabled = false; $("pairErr").textContent = e.message; });
};
$("pairCode2").onclick = function () {
$("pairErr").textContent = "";
api("POST", "/api/pair/code", { server_url: $("srv").value, code: $("pcode").value.trim() }).then(poll).catch(function (e) { $("pairErr").textContent = e.message; });
saveTls().then(function () { return api("POST", "/api/pair/code", { server_url: $("srv").value, code: $("pcode").value.trim() }); }).then(poll).catch(function (e) { $("pairErr").textContent = e.message; });
};
$("wzBack2").onclick = function () { api("POST", "/api/pair/forget").then(function () { wzGo(1); }); };
@@ -686,18 +705,58 @@ function renderRoms() {
return '<div class="rom" data-rom="' + g.id + '"><div class="cover" ' + cover + ">" + badge + '</div><div class="t">' + esc(g.name) + '</div><div class="s">' + fmtSize(g.size) + "</div>" + (g.installed && !romJob(g) ? '<div class="btns">' + romButton(g) + "</div>" : romButton(g)) + "</div>";
}).join("") + "</div>";
}
function loadRoms(append) {
// The list is a window of games starting at state.start; the A-Z ribbon either
// scrolls within it or, for a letter not loaded yet, restarts it at that letter.
function loadRoms(append, start) {
var p = state.platform;
if (!append) { state.offset = 0; state.items = []; state.loading = true; renderRoms(); }
if (!append) { state.start = state.offset = start || 0; state.items = []; state.loading = true; renderRoms(); }
api("GET", "/api/roms?platform_id=" + p.id + "&offset=" + state.offset + "&limit=60&search=" + encodeURIComponent($("search").value)).then(function (r) {
state.loading = false;
state.total = r.total; state.offset += r.items.length;
state.items = (append ? state.items : []).concat(r.items);
state.letters = letterOffsets(r.char_index);
renderRoms();
renderRibbon();
$("more").style.display = state.offset < state.total ? "" : "none";
if (!append && state.start > 0 && state.items.length) scrollToRom(state.items[0], true);
pollLibraryDownloads();
}).catch(function (e) { state.loading = false; $("roms").innerHTML = '<p class="err">' + esc(e.message) + "</p>"; });
}
// RomM's char_index maps a first character to the offset of its first game.
// Anything that isn't A-Z goes under "#".
function letterOffsets(ci) {
var out = {};
Object.keys(ci || {}).forEach(function (k) {
var l = /^[a-z]$/i.test(k) ? k.toUpperCase() : "#";
if (!(l in out) || ci[k] < out[l]) out[l] = ci[k];
});
return out;
}
function renderRibbon() {
var offs = state.letters || {};
$("ribbon").style.display = state.total > 60 && Object.keys(offs).length > 1 ? "" : "none";
$("ribbon").innerHTML = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").map(function (l) {
return '<button class="small" data-letter="' + l + '"' + (l in offs ? "" : " disabled") + ">" + l + "</button>";
}).join("");
var first = state.items[0];
$("jumpInfo").style.display = state.start > 0 && first ? "" : "none";
if (first) $("jumpText").textContent = "Showing games from " + first.name.charAt(0).toUpperCase() + " on.";
}
// After a jump the ribbon stays in view, so the "from the start" note shows too.
function scrollToRom(g, showRibbon) {
var el = document.querySelector('[data-rom="' + g.id + '"]');
if (!el) return;
(showRibbon ? $("ribbon") : el).scrollIntoView({ block: "start" });
var b = el.querySelector("button"); if (b) b.focus({ preventScroll: true });
}
$("ribbon").onclick = function (ev) {
var b = ev.target.closest("button[data-letter]"), offs = state.letters || {};
if (!b || !(b.dataset.letter in offs)) return;
var i = offs[b.dataset.letter] - state.start;
if (i >= 0 && i < state.items.length) scrollToRom(state.items[i]);
else loadRoms(false, offs[b.dataset.letter]);
};
$("jumpStart").onclick = function () { loadRoms(); };
$("searchBtn").onclick = function () { loadRoms(); };
$("search").onkeydown = function (e) { if (e.key === "Enter") loadRoms(); };
$("more").onclick = function () { loadRoms(true); };
@@ -779,7 +838,9 @@ function loadSettings() {
$("states").value = c.states; $("serverVersions").value = c.server_versions; $("notify").checked = c.notify; $("tls").checked = c.tls_verify;
$("policy").value = c.conflict_policy; $("slot").value = c.slot; $("concurrency").value = c.download_concurrency; $("backups").value = c.keep_backups;
$("profiles").value = JSON.stringify(c.profiles, null, 2);
$("updAuto").checked = c.update_check;
});
loadUpdate();
api("GET", "/api/paths").then(function (list) {
$("paths").innerHTML = list.map(function (m) {
var layouts = { psp: "PSP save folders", gci: "GameCube memory card files", wii: "Wii save folder" };
@@ -836,6 +897,52 @@ $("saveProfiles").onclick = function () {
$("resetProfiles").onclick = function () {
if (confirm("Replace your profiles with the defaults?")) api("POST", "/api/config", { reset_profiles: true }).then(function () { toast("Reset"); $("platforms").innerHTML = ""; loadSettings(); });
};
// Updates
function updBusy(u) { return ["checking", "downloading", "waiting", "installing", "restarting"].indexOf(u.state) >= 0; }
function renderUpdate(u) {
state.update = u;
var busy = updBusy(u), h = "<p>This is version <b>" + esc(u.current) + "</b>." + (u.checked_at ? ' <small class="muted">Checked ' + ago(u.checked_at) + "</small>" : "") + "</p>";
$("updCheck").disabled = busy;
if (u.state === "checking") h += '<p class="muted">Checking GitHub</p>';
else if (busy) {
var pct = u.total ? Math.round(u.done * 100 / u.total) : 0;
h += "<p>" + esc(u.message || u.state) + (u.state === "downloading" && u.total ? " (" + pct + "%)" : "") + "</p>";
if (u.state === "downloading") h += '<div class="bar"><i style="width:' + pct + '%"></i></div>';
} else if (u.available) {
h += '<p class="ok">Version ' + esc(u.latest) + " is available.</p>";
if (!u.autostart) h += '<p class="warn">Autostart isn\'t set up, so the update only lasts until the console restarts.</p>';
h += u.signed ? '<div class="row"><button class="primary" id="updInstall">Update to ' + esc(u.latest) + "</button></div>"
: '<p class="muted">This release can\'t be installed from here. Download it from GitHub instead.</p>';
} else if (u.latest) h += '<p class="muted">You have the latest version.</p>';
if (u.state === "error" && u.error) h += '<p class="err">' + esc(u.error) + "</p>";
if (u.notes && (u.available || busy)) h += '<details open><summary>What\'s new in ' + esc(u.latest) + "</summary><pre>" + esc(u.notes) + "</pre></details>";
if (u.release_url && u.available) h += '<p><small><a href="' + esc(u.release_url) + '" target="_blank" rel="noopener">Release page on GitHub</a></small></p>';
$("updBody").innerHTML = h;
if ($("updInstall")) $("updInstall").onclick = installUpdate;
$("updNotice").style.display = u.available && !busy ? "" : "none";
$("updNotice").innerHTML = "<b>RomM Sync " + esc(u.latest) + ' is available.</b> <button class="small" id="updGo">See what\'s new</button>';
$("updGo").onclick = function () { showTab("settings"); };
}
function loadUpdate() { return api("GET", "/api/update").then(renderUpdate).catch(function () {}); }
// Polls while a check or install runs. After the restart, the new version answers and the page reloads.
function watchUpdate() {
clearTimeout(watchUpdate.t);
var target = state.update && state.update.latest;
api("GET", "/api/status").then(function (s) {
if (target && s.version === target) { toast("Updated to " + s.version); setTimeout(function () { location.reload(); }, 1500); return "done"; }
return loadUpdate();
}).catch(function () {}).then(function (r) {
if (r !== "done" && state.update && updBusy(state.update)) watchUpdate.t = setTimeout(watchUpdate, 1500);
});
}
function installUpdate() {
if (!confirm("Update RomM Sync to " + state.update.latest + "? It restarts once no sync, download or game is running.")) return;
api("POST", "/api/update/install").then(function (u) { renderUpdate(u); watchUpdate(); }).catch(function (e) { toast(e.message, 1); });
}
$("updCheck").onclick = function () { api("POST", "/api/update/check").then(function (u) { renderUpdate(u); watchUpdate(); }).catch(function (e) { toast(e.message, 1); }); };
$("updAuto").onchange = function () { api("POST", "/api/config", { update_check: this.checked }).then(function () { toast("Saved"); }).catch(function (e) { toast(e.message, 1); }); };
$("tileBtn").onclick = function () { api("POST", "/api/tile").then(function () { toast("Tile added"); }).catch(function (e) { toast(e.message, 1); }); };
$("forget").onclick = function () { if (confirm("Unpair from this RomM server? Files on the console are kept.")) api("POST", "/api/pair/forget").then(function () { poll(); showTab("pair"); }); };
@@ -905,6 +1012,8 @@ api("GET", "/api/status").then(function (s) {
var ready = s.paired && s.setup_complete;
showTab(ready ? (t === "pair" ? "home" : t) : "pair");
if (!ready) { wzGo(s.paired ? 3 : 1); wizardFromStatus(s); }
api("GET", "/api/config").then(function (c) { $("wzInsecure").checked = !c.tls_verify; }).catch(function () {});
loadUpdate().then(function () { if (state.update && updBusy(state.update)) watchUpdate(); });
}).catch(function () { $("conn").textContent = "Can't reach RomM Sync"; });
setInterval(poll, 3000);
</script>