From 9c47c3ecbbd44ff99ff23e5e22ae535f526f8575 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:29:40 -0500 Subject: [PATCH 1/5] The engine's HTTPS: the unit's own libssl, home Wi-Fi only For the catalogue and updates (next). Android 4.4's Java TLS shares no cipher suite with GitHub, and its MessageDigest SHA-256 can be missing under app_process, so: - core/fetch/fetch.c -> /data/hmgapi/lib/libhmgapi_fetch.so (built like the loader: no libc, dlopen/dlsym only; installed into /data, nothing new on /system). One TLS 1.2 request through the unit's libssl.so; the socket carries home Wi-Fi's mark (SO_MARK 0x2951), so it leaves on home Wi-Fi or not at all. The certificate isn't checked (the unit's 2013 roots and its clock can't be relied on): what's downloaded is trusted only through a SHA-256 and a signature. - NativeFetch (with NativeFetch.Web, files standing in for GitHub off the car), Http (https, GitHub's hosts only, redirects between them, a size cap), DnsLookup (home Wi-Fi's DNS server, asked directly), Sha256 (plain Java). - fetch-test.sh. The same C, built for a computer, fetched catalogue entries and packages from GitHub; first run on an Ioniq 5 US 260507 as a mod. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + build.sh | 22 +- core/fetch/fetch.c | 202 ++++++++++++++++++ core/runtime/fetch-test.sh | 9 + .../runtime/java/hmgapi/engine/DnsLookup.java | 114 ++++++++++ core/runtime/java/hmgapi/engine/Http.java | 174 +++++++++++++++ .../java/hmgapi/engine/NativeFetch.java | 128 +++++++++++ core/runtime/java/hmgapi/engine/Sha256.java | 76 +++++++ .../runtime/test/hmgapi/engine/FetchTest.java | 87 ++++++++ install/common/install.sh | 5 + tools/test-all.sh | 4 +- 11 files changed, 820 insertions(+), 6 deletions(-) create mode 100644 core/fetch/fetch.c create mode 100644 core/runtime/fetch-test.sh create mode 100644 core/runtime/java/hmgapi/engine/DnsLookup.java create mode 100644 core/runtime/java/hmgapi/engine/Http.java create mode 100644 core/runtime/java/hmgapi/engine/NativeFetch.java create mode 100644 core/runtime/java/hmgapi/engine/Sha256.java create mode 100644 core/runtime/test/hmgapi/engine/FetchTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fd5a1b4..53f5e802 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,11 @@ HMG-API's redirect to home Wi-Fi's DNS server kept that source address, so no query left the unit. While home Wi-Fi is up, `route_localnet` is on for `wlan0` (the queries are masqueraded) and only the answers may come back in for 127.x (`HMGAPI_HOMELO`). +- **HMG-API's own HTTPS** (`/data/hmgapi/lib/libhmgapi_fetch.so`, `core/fetch`): Android 4.4's + Java TLS can't reach GitHub, so the engine uses the unit's own `libssl.so` (TLS 1.2), on a + socket marked for home Wi-Fi only, with its own DNS lookup on home Wi-Fi's server. Tested + first as a mod on an Ioniq 5 US 260507 (HMG-API rc.10): the catalogue and three packages + over home Wi-Fi, each with its SHA-256. ## 1.1.0-rc.10 (2026-11-25) diff --git a/build.sh b/build.sh index 8736fa21..8907ec09 100755 --- a/build.sh +++ b/build.sh @@ -34,6 +34,20 @@ loader() { md5sum "$OUT/libhmgapi_hook.so" } +fetchlib() { + # libhmgapi_fetch.so (core/fetch/fetch.c): the engine's HTTPS through the unit's own libssl; no libc, + # only dlopen/dlsym from the unit's libdl (the loader's stand-in), and a JDK's jni.h + sh core/loader/syslib-stubs.sh "$OUT/syslib" >/dev/null + J=${JAVA_HOME:-$(cd "$(dirname "$(readlink -f "$(command -v javac)")")/.." && pwd)} + case "$(uname -s)" in Darwin) JOS=darwin ;; *) JOS=linux ;; esac + clang --target=armv7a-linux-androideabi -mthumb -march=armv7-a -mfloat-abi=softfp -Os -fPIC \ + -ffreestanding -fno-builtin -nostdlib -shared -fno-stack-protector -fno-exceptions -fno-asynchronous-unwind-tables -fuse-ld=lld \ + -I"$J/include" -I"$J/include/$JOS" \ + -Wl,-z,now -Wl,--no-rosegment -Wl,--hash-style=sysv -Wl,-z,defs -Wl,--build-id=none -Wl,-soname,libhmgapi_fetch.so \ + -o "$OUT/libhmgapi_fetch.so" core/fetch/fetch.c "$OUT/syslib/libdl.so" + md5sum "$OUT/libhmgapi_fetch.so" +} + runtime() { rm -rf "$OUT/classes" "$OUT/runtime-stubs" && mkdir -p "$OUT/classes" "$OUT/runtime-stubs" # stubs/: signatures of the car's own classes the runtime extends (compile only, never in the jar) @@ -95,7 +109,7 @@ lpatch() { OUT="$OUT" sh tools/lpatch/build.sh; } payload() { P="$OUT/payload" rm -rf "$P" && mkdir -p "$P" - for f in hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk; do + for f in hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk; do [ -f "$OUT/$f" ] || { echo "payload: no out/$f (build it first)"; exit 1; } cp "$OUT/$f" "$P/" done @@ -120,7 +134,7 @@ payload() { (cd "$P" && find maps -type f | LC_ALL=C sort | xargs md5sum > MAPS.md5) sed -n 's/.*HMGAPI_VERSION = "\(.*\)";/\1/p' core/runtime/java/hmgapi/engine/Engine.java > "$P/VERSION" echo "$(git rev-parse --short HEAD 2>/dev/null || echo local)$(git diff --quiet HEAD 2>/dev/null || echo +) $(date -u +%Y-%m-%d)" > "$P/BUILD" - (cd "$P" && md5sum hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 $(find nemesis -type f | LC_ALL=C sort) > MANIFEST) + (cd "$P" && md5sum hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 $(find nemesis -type f | LC_ALL=C sort) > MANIFEST) echo "payload $(cat "$P/VERSION") ($(cat "$P/BUILD")): $P" } @@ -166,11 +180,11 @@ sdk() { } if [ $# -eq 0 ]; then - set -- hmgapid zygote loader runtime client mods app lpatch payload + set -- hmgapid zygote loader fetchlib runtime client mods app lpatch payload fi for part in "$@"; do case $part in - hmgapid|zygote|loader|runtime|client|mods|app|lpatch|payload|sdk) $part ;; + hmgapid|zygote|loader|fetchlib|runtime|client|mods|app|lpatch|payload|sdk) $part ;; *) echo "unknown part: $part"; exit 2 ;; esac done diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c new file mode 100644 index 00000000..c13465aa --- /dev/null +++ b/core/fetch/fetch.c @@ -0,0 +1,202 @@ +/* libhmgapi_fetch.so: one HTTPS request for HMG-API's engine (hmgapi.engine.NativeFetch): the + * catalogue, mod packages and HMG-API releases, over home Wi-Fi only (Catalog). + * + * Android 4.4's Java TLS shares no cipher suite with GitHub, but the unit's own libssl.so + * (OpenSSL 1.0.1) has TLS 1.2 with ECDHE and AES-GCM. This opens a TCP connection, does the + * handshake with that library, sends the request bytes Java made and writes every response + * byte (headers and body) to a file, up to a cap. Java parses the HTTP. + * + * The server's certificate is NOT checked here: the unit's 2013 root store doesn't know GitHub's + * roots and its clock isn't reliable. Nothing fetched is trusted because of where it came from: + * a package must have the SHA-256 its catalogue entry names, and the engine checks its signature + * (the installed mod's author key; HMG-API's release key for HMG-API itself) and refuses a + * downgrade. A hostile network can make a check find nothing, not get code installed. + * + * The socket carries home Wi-Fi's mark (SO_MARK 0x2951: table 95, HomeWifi), so it goes out on home + * Wi-Fi or not at all (table 95 holds an unreachable default while home Wi-Fi is down), never + * on the car's mobile data. Root only (the engine is). + * + * Built with no libc (as the loader): everything comes through dlopen/dlsym from the unit's + * libc.so and libssl.so. On a computer (-DHOST, the off-car tests) it uses the system's headers + * and an OpenSSL 1.1+/3 library, which is why each OpenSSL call has an old and a new name. + * First written as a mod (an update-check proof of concept), run on an Ioniq 5 US 260507. + */ +#include + +#ifdef HOST +#include +#include +#include +#include +#include +#include +#define LIBC_SYM(name) ((void *) name) +typedef socklen_t sock_len; +#else +void *dlopen(const char *path, int flags); +void *dlsym(void *handle, const char *name); +#define RTLD_NOW 2 +typedef unsigned int sock_len; +struct sockaddr; +struct addrinfo { /* bionic, 32-bit ARM */ + int ai_flags, ai_family, ai_socktype, ai_protocol; + sock_len ai_addrlen; + char *ai_canonname; + struct sockaddr *ai_addr; + struct addrinfo *ai_next; +}; +#define AF_INET 2 +#define SOCK_STREAM 1 +#define O_WRONLY 01 +#define O_CREAT 0100 +#define O_TRUNC 01000 +static void *libc_handle; +#define LIBC_SYM(name) dlsym(libc_handle, #name) +static void *memset(void *p, int c, unsigned long n) { unsigned char *b = p; while (n--) *b++ = (unsigned char) c; return p; } +#endif + +/* error codes (negative), so Java can say which step failed */ +enum { E_LIB = -1, E_SYM = -2, E_RESOLVE = -3, E_CONNECT = -4, E_CTX = -5, E_HANDSHAKE = -6, E_SEND = -7, + E_FILE = -8, E_TOO_BIG = -9, E_READ = -10, E_ARGS = -11 }; + +#define SSL_CTRL_OPTIONS 32 +#define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 +#define SSL_OP_NO_SSLv2 0x01000000L +#define SSL_OP_NO_SSLv3 0x02000000L + +/* host is "name" or "name@address": the name goes in the TLS server name, and the connection goes + * to the address when there is one (Java's own lookup, DnsLookup: the unit's resolver can't be + * used by a mod's service on home Wi-Fi, see there) */ +static int fetch(const char *ssl_lib, const char *c_lib, const char *host_arg, const char *port, + const char *request, int request_len, const char *out_path, int max_bytes) { + char host[256]; + const char *addr = host_arg; + int hn = 0; + while (host_arg[hn] && host_arg[hn] != '@' && hn < (int) sizeof host - 1) { host[hn] = host_arg[hn]; hn++; } + host[hn] = 0; + if (host_arg[hn] == '@') addr = host_arg + hn + 1; + else if (host_arg[hn]) return E_ARGS; + else addr = host; + void *ssl_h = dlopen(ssl_lib, RTLD_NOW); + if (!ssl_h) return E_LIB; +#ifndef HOST + libc_handle = dlopen(c_lib, RTLD_NOW); + if (!libc_handle) return E_LIB; +#else + (void) c_lib; +#endif + int (*p_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = LIBC_SYM(getaddrinfo); + void (*p_freeaddrinfo)(struct addrinfo *) = LIBC_SYM(freeaddrinfo); + int (*p_socket)(int, int, int) = LIBC_SYM(socket); + int (*p_connect)(int, const struct sockaddr *, sock_len) = LIBC_SYM(connect); + int (*p_setsockopt)(int, int, int, const void *, sock_len) = LIBC_SYM(setsockopt); + int (*p_close)(int) = LIBC_SYM(close); + int (*p_open)(const char *, int, ...) = LIBC_SYM(open); + long (*p_write)(int, const void *, unsigned long) = LIBC_SYM(write); + if (!p_getaddrinfo || !p_freeaddrinfo || !p_socket || !p_connect || !p_close || !p_open || !p_write) return E_SYM; + + /* OpenSSL 1.0.x names first (the unit), then 1.1+/3 (a computer) */ + int (*p_init_old)(void) = dlsym(ssl_h, "SSL_library_init"); + int (*p_init_new)(unsigned long long, const void *) = dlsym(ssl_h, "OPENSSL_init_ssl"); + const void *(*p_method)(void) = dlsym(ssl_h, "SSLv23_client_method"); + if (!p_method) p_method = dlsym(ssl_h, "TLS_client_method"); + void *(*p_ctx_new)(const void *) = dlsym(ssl_h, "SSL_CTX_new"); + void (*p_ctx_free)(void *) = dlsym(ssl_h, "SSL_CTX_free"); + long (*p_ctx_ctrl)(void *, int, long, void *) = dlsym(ssl_h, "SSL_CTX_ctrl"); + unsigned long (*p_ctx_set_options)(void *, unsigned long) = dlsym(ssl_h, "SSL_CTX_set_options"); + void *(*p_new)(void *) = dlsym(ssl_h, "SSL_new"); + void (*p_free)(void *) = dlsym(ssl_h, "SSL_free"); + long (*p_ctrl)(void *, int, long, void *) = dlsym(ssl_h, "SSL_ctrl"); + int (*p_set_fd)(void *, int) = dlsym(ssl_h, "SSL_set_fd"); + int (*p_ssl_connect)(void *) = dlsym(ssl_h, "SSL_connect"); + int (*p_ssl_write)(void *, const void *, int) = dlsym(ssl_h, "SSL_write"); + int (*p_ssl_read)(void *, void *, int) = dlsym(ssl_h, "SSL_read"); + int (*p_shutdown)(void *) = dlsym(ssl_h, "SSL_shutdown"); + if ((!p_init_old && !p_init_new) || !p_method || !p_ctx_new || !p_ctx_free || !p_new || !p_free || !p_ctrl + || !p_set_fd || !p_ssl_connect || !p_ssl_write || !p_ssl_read) return E_SYM; + + struct addrinfo hints, *res = 0, *a; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_INET; /* home Wi-Fi is IPv4 only for mods */ + hints.ai_socktype = SOCK_STREAM; + if (p_getaddrinfo(addr, port, &hints, &res) != 0 || !res) return E_RESOLVE; + int fd = -1; + for (a = res; a; a = a->ai_next) { + fd = p_socket(a->ai_family, a->ai_socktype, a->ai_protocol); + if (fd < 0) continue; +#ifndef HOST + /* home Wi-Fi's mark on the socket itself, so the connection's route is table 95's from the + * start (home Wi-Fi, or unreachable): never the main table's mobile data */ + if (p_setsockopt) { + unsigned int mark = 0x2951; + p_setsockopt(fd, 1 /* SOL_SOCKET */, 36 /* SO_MARK */, &mark, sizeof mark); + } +#endif + if (p_connect(fd, a->ai_addr, a->ai_addrlen) == 0) break; + p_close(fd); + fd = -1; + } + p_freeaddrinfo(res); + if (fd < 0) return E_CONNECT; + + int rc; + void *ctx = 0, *ssl = 0; + int out = -1; + if (p_init_new) p_init_new(0, 0); else p_init_old(); + ctx = p_ctx_new(p_method()); + if (!ctx) { rc = E_CTX; goto done; } + if (p_ctx_set_options) p_ctx_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); + else if (p_ctx_ctrl) p_ctx_ctrl(ctx, SSL_CTRL_OPTIONS, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3, 0); + ssl = p_new(ctx); + if (!ssl) { rc = E_CTX; goto done; } + p_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *) host); /* server name: GitHub's hosts need it */ + if (p_set_fd(ssl, fd) != 1 || p_ssl_connect(ssl) != 1) { rc = E_HANDSHAKE; goto done; } + int sent = 0; + while (sent < request_len) { + int n = p_ssl_write(ssl, request + sent, request_len - sent); + if (n <= 0) { rc = E_SEND; goto done; } + sent += n; + } + out = p_open(out_path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (out < 0) { rc = E_FILE; goto done; } + static char buf[16384]; + int total = 0; + for (;;) { + int n = p_ssl_read(ssl, buf, sizeof buf); + if (n <= 0) break; /* the server closes after the response (Connection: close) */ + if (total + n > max_bytes) { rc = E_TOO_BIG; goto done; } + int w = 0; + while (w < n) { + long k = p_write(out, buf + w, (unsigned long) (n - w)); + if (k <= 0) { rc = E_FILE; goto done; } + w += (int) k; + } + total += n; + } + rc = total > 0 ? total : E_READ; +done: + if (out >= 0) p_close(out); + if (ssl) { if (p_shutdown) p_shutdown(ssl); p_free(ssl); } + if (ctx) p_ctx_free(ctx); + p_close(fd); + return rc; +} + +JNIEXPORT jint JNICALL Java_hmgapi_engine_NativeFetch_fetch(JNIEnv *env, jclass cls, jstring ssl_lib, jstring c_lib, + jstring host, jstring port, jbyteArray request, jstring out_path, jint max_bytes) { + (void) cls; + if (!ssl_lib || !c_lib || !host || !port || !request || !out_path || max_bytes <= 0) return E_ARGS; + const char *s = (*env)->GetStringUTFChars(env, ssl_lib, 0), *c = (*env)->GetStringUTFChars(env, c_lib, 0); + const char *h = (*env)->GetStringUTFChars(env, host, 0), *p = (*env)->GetStringUTFChars(env, port, 0); + const char *o = (*env)->GetStringUTFChars(env, out_path, 0); + jsize len = (*env)->GetArrayLength(env, request); + jbyte *req = (*env)->GetByteArrayElements(env, request, 0); + int rc = (s && c && h && p && o && req) ? fetch(s, c, h, p, (const char *) req, (int) len, o, (int) max_bytes) : E_ARGS; + if (req) (*env)->ReleaseByteArrayElements(env, request, req, JNI_ABORT); + if (o) (*env)->ReleaseStringUTFChars(env, out_path, o); + if (p) (*env)->ReleaseStringUTFChars(env, port, p); + if (h) (*env)->ReleaseStringUTFChars(env, host, h); + if (c) (*env)->ReleaseStringUTFChars(env, c_lib, c); + if (s) (*env)->ReleaseStringUTFChars(env, ssl_lib, s); + return rc; +} diff --git a/core/runtime/fetch-test.sh b/core/runtime/fetch-test.sh new file mode 100644 index 00000000..9d1fc5d1 --- /dev/null +++ b/core/runtime/fetch-test.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Off-car test of the engine's HTTPS pieces (Http, NativeFetch.Web, Sha256, DnsLookup); the library +# itself (core/fetch/fetch.c) needs the unit's libssl, or a computer's: catalog-test.sh's notes. +set -e +cd "$(dirname "$0")/../.." +CP=$(mktemp -d); trap 'rm -rf "$CP"' EXIT +sh tools/engine-classes.sh "$CP" 2>/dev/null +javac --release 8 -nowarn -cp "$CP" -d "$CP" core/runtime/test/hmgapi/engine/FetchTest.java 2>/dev/null +java -cp "$CP" hmgapi.engine.FetchTest diff --git a/core/runtime/java/hmgapi/engine/DnsLookup.java b/core/runtime/java/hmgapi/engine/DnsLookup.java new file mode 100644 index 00000000..59d40141 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/DnsLookup.java @@ -0,0 +1,114 @@ +package hmgapi.engine; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** + * A host's IPv4 addresses, asked of home Wi-Fi's own DNS server (dhcp.wlan0.dns1) over UDP, for the + * engine's downloads (NativeFetch). Not the system resolver: the engine runs as root outside netd's + * per-app setup, where lookups would go to the car's carrier DNS on mobile data. wifi.sh routes + * wlan0's DNS servers through wlan0, so this query goes out on home Wi-Fi or not at all. + */ +final class DnsLookup { + private DnsLookup() {} + + static final int TRIES = 3, TIMEOUT_MS = 3000; + + /** the server: home Wi-Fi's DHCP DNS, or its gateway; null when home Wi-Fi gave neither */ + static String server(Engine e) { + for (String p : new String[] {"dhcp.wlan0.dns1", "dhcp.wlan0.gateway"}) { + String v = e.getprop(p); + if (v != null && v.matches("\\d{1,3}(\\.\\d{1,3}){3}")) return v; + } + return null; + } + + /** host's A records (dotted), first answer first; empty if none */ + static List lookup(String server, String host) throws IOException { + Random rnd = new Random(); + IOException last = null; + for (int t = 0; t < TRIES; t++) { + int id = rnd.nextInt(0x10000); + byte[] q = query(id, host); + DatagramSocket s = new DatagramSocket(); + try { + s.setSoTimeout(TIMEOUT_MS); + s.connect(InetAddress.getByAddress(dotted(server)), 53); + s.send(new DatagramPacket(q, q.length)); + byte[] r = new byte[1500]; + DatagramPacket p = new DatagramPacket(r, r.length); + s.receive(p); + return answers(r, p.getLength(), id); + } catch (IOException e) { + last = e; + } finally { + s.close(); + } + } + throw last != null ? last : new IOException("no answer"); + } + + static byte[] query(int id, String host) { + ByteArrayOutputStream o = new ByteArrayOutputStream(); + o.write(id >> 8); o.write(id); o.write(1); o.write(0); // recursion desired + o.write(0); o.write(1); for (int i = 0; i < 6; i++) o.write(0); + for (String l : host.split("\\.")) { + if (l.isEmpty() || l.length() > 63) throw new IllegalArgumentException("bad host " + host); + o.write(l.length()); + for (int i = 0; i < l.length(); i++) o.write(l.charAt(i)); + } + o.write(0); o.write(0); o.write(1); o.write(0); o.write(1); // A, IN + return o.toByteArray(); + } + + /** the A records of an answer to query id; a wrong id or an error code is an IOException */ + static List answers(byte[] r, int n, int id) throws IOException { + if (n < 12 || u16(r, 0) != id || (r[2] & 0x80) == 0) throw new IOException("not an answer to this query"); + int rcode = r[3] & 0xf; + if (rcode == 3) return new ArrayList(); // no such name + if (rcode != 0) throw new IOException("DNS error " + rcode); + int qd = u16(r, 4), an = u16(r, 6), off = 12; + for (int i = 0; i < qd; i++) off = skipName(r, n, off) + 4; + List out = new ArrayList(); + for (int i = 0; i < an; i++) { + off = skipName(r, n, off); + if (off + 10 > n) throw new IOException("short answer"); + int type = u16(r, off), klass = u16(r, off + 2), len = u16(r, off + 8); + off += 10; + if (off + len > n) throw new IOException("short answer"); + if (type == 1 && klass == 1 && len == 4) + out.add((r[off] & 0xff) + "." + (r[off + 1] & 0xff) + "." + (r[off + 2] & 0xff) + "." + (r[off + 3] & 0xff)); + off += len; + } + return out; + } + + private static int skipName(byte[] r, int n, int off) throws IOException { + for (int guard = 0; guard < 128; guard++) { + if (off >= n) throw new IOException("short answer"); + int l = r[off] & 0xff; + if (l == 0) return off + 1; + if ((l & 0xc0) == 0xc0) return off + 2; // a pointer ends the name + off += 1 + l; + } + throw new IOException("bad name"); + } + + private static int u16(byte[] r, int off) { + return ((r[off] & 0xff) << 8) | (r[off + 1] & 0xff); + } + + private static byte[] dotted(String a) { + String[] p = a.split("\\."); + byte[] b = new byte[4]; + for (int i = 0; i < 4; i++) b[i] = (byte) Integer.parseInt(p[i]); + return b; + } +} diff --git a/core/runtime/java/hmgapi/engine/Http.java b/core/runtime/java/hmgapi/engine/Http.java new file mode 100644 index 00000000..9ccd7108 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Http.java @@ -0,0 +1,174 @@ +package hmgapi.engine; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * HTTPS GET to a file, for the catalogue and updates (Catalog), over a transport that only moves + * bytes (NativeFetch on the unit, files in the off-car tests). Only https, only GitHub's hosts, + * redirects followed between them, a size cap. Nothing is trusted because of where it came from + * (see NativeFetch). + */ +final class Http { + interface Transport { + /** sends request to host:443 over TLS and writes the whole raw answer to rawOut; bytes written, or a negative error */ + int exchange(String host, byte[] request, File rawOut, int maxBytes); + } + + static final Set HOSTS = new HashSet(Arrays.asList("github.com", "api.github.com", "raw.githubusercontent.com", + "objects.githubusercontent.com", "release-assets.githubusercontent.com", "codeload.github.com")); + static final int MAX_REDIRECTS = 5; + /** headers and chunk framing on top of the body's cap */ + static final int OVERHEAD = 65536; + + static final class Result { + final int status; + final String error; + + Result(int status, String error) { + this.status = status; + this.error = error; + } + + boolean ok() { + return status == 200 && error == null; + } + + @Override + public String toString() { + return error != null ? error : "HTTP " + status; + } + } + + private final Transport transport; + private final File tmp; + + Http(Transport transport, File tmpDir) { + this.transport = transport; + this.tmp = new File(tmpDir, "answer.raw"); + } + + /** GET url into out (replaced only on a 200); maxBytes: the body's cap */ + Result get(String url, File out, int maxBytes) throws IOException { + for (int hop = 0; hop <= MAX_REDIRECTS; hop++) { + if (!url.startsWith("https://")) return new Result(0, "not https: " + url); + String rest = url.substring(8); + int slash = rest.indexOf('/'); + String host = slash < 0 ? rest : rest.substring(0, slash), path = slash < 0 ? "/" : rest.substring(slash); + if (!HOSTS.contains(host)) return new Result(0, "host not allowed: " + host); + if (path.indexOf(' ') >= 0 || path.indexOf('\r') >= 0 || path.indexOf('\n') >= 0) return new Result(0, "bad path"); + byte[] request = ("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\nUser-Agent: HMG-API/" + Engine.HMGAPI_VERSION + "\r\n" + + ("api.github.com".equals(host) ? "Accept: application/vnd.github+json\r\nX-GitHub-Api-Version: 2022-11-28\r\n" : "Accept: */*\r\n") + + "Accept-Encoding: identity\r\nConnection: close\r\n\r\n").getBytes("US-ASCII"); + int n = transport.exchange(host, request, tmp, maxBytes + OVERHEAD); + try { + if (n < 0) return new Result(0, host + ": " + NativeFetch.why(n)); + InputStream in = new BufferedInputStream(new FileInputStream(tmp)); + try { + String statusLine = line(in); + String[] sp = statusLine.split(" "); + if (sp.length < 2 || !sp[0].startsWith("HTTP/1.")) return new Result(0, "not an HTTP answer"); + int status; + try { + status = Integer.parseInt(sp[1]); + } catch (NumberFormatException e) { + return new Result(0, "not an HTTP answer"); + } + Map headers = new HashMap(); + for (String l = line(in); !l.isEmpty(); l = line(in)) { + int c = l.indexOf(':'); + if (c > 0) headers.put(l.substring(0, c).trim().toLowerCase(Locale.US), l.substring(c + 1).trim()); + } + if (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) { + String to = headers.get("location"); + if (to == null) return new Result(status, "redirect without a location"); + url = to.startsWith("/") ? "https://" + host + to : to; + continue; + } + if (status != 200) return new Result(status, null); + File part = new File(out.getPath() + ".part"); + OutputStream o = new FileOutputStream(part); + long got; + try { + got = "chunked".equalsIgnoreCase(headers.get("transfer-encoding")) ? chunked(in, o, maxBytes) : copy(in, o, maxBytes); + } finally { + o.close(); + } + String len = headers.get("content-length"); + if (got < 0 || (len != null && !len.equals(String.valueOf(got)))) { + part.delete(); + return new Result(status, got < 0 ? "larger than " + maxBytes + " bytes" : "cut off: " + got + " of " + len + " bytes"); + } + if (!part.renameTo(out)) { + part.delete(); + return new Result(status, "can't write " + out); + } + return new Result(200, null); + } finally { + in.close(); + } + } finally { + tmp.delete(); + } + } + return new Result(0, "too many redirects"); + } + + private static String line(InputStream in) throws IOException { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + for (int c = in.read(); c >= 0 && c != '\n'; c = in.read()) { + if (c != '\r') b.write(c); + if (b.size() > 8192) throw new IOException("header line too long"); + } + return b.toString("ISO-8859-1"); + } + + /** bytes copied, or -1 past the cap */ + private static long copy(InputStream in, OutputStream out, int max) throws IOException { + byte[] buf = new byte[8192]; + long total = 0; + for (int n = in.read(buf); n > 0; n = in.read(buf)) { + total += n; + if (total > max) return -1; + out.write(buf, 0, n); + } + return total; + } + + private static long chunked(InputStream in, OutputStream out, int max) throws IOException { + long total = 0; + byte[] buf = new byte[8192]; + for (;;) { + String l = line(in); + int semi = l.indexOf(';'); + int size; + try { + size = Integer.parseInt((semi < 0 ? l : l.substring(0, semi)).trim(), 16); + } catch (NumberFormatException e) { + throw new IOException("bad chunk size"); + } + if (size == 0) return total; + total += size; + if (total > max) return -1; + for (int left = size; left > 0; ) { + int n = in.read(buf, 0, Math.min(left, buf.length)); + if (n <= 0) throw new IOException("chunk cut off"); + out.write(buf, 0, n); + left -= n; + } + line(in); // the CRLF after the chunk + } + } +} diff --git a/core/runtime/java/hmgapi/engine/NativeFetch.java b/core/runtime/java/hmgapi/engine/NativeFetch.java new file mode 100644 index 00000000..4c6047fc --- /dev/null +++ b/core/runtime/java/hmgapi/engine/NativeFetch.java @@ -0,0 +1,128 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +/** + * The engine's HTTPS on the unit: /data/hmgapi/lib/libhmgapi_fetch.so (core/fetch/fetch.c), over the + * unit's own libssl, its socket marked for home Wi-Fi. The server's certificate isn't checked + * (the unit's root store and clock can't be relied on): Catalog trusts a download only through + * the SHA-256 its catalogue entry names and the package's signature, which the engine checks. + * + * Off the car (the tests) Web stands in for it: HMGAPI_TEST_WEB= serves //. + */ +final class NativeFetch implements Http.Transport { + static final String LIB = "/data/hmgapi/lib/libhmgapi_fetch.so", SSL = "/system/lib/libssl.so", LIBC = "/system/lib/libc.so"; + + private final Engine e; + private final String sslLib, cLib; + + private NativeFetch(Engine e, String lib, String sslLib, String cLib) { + System.load(lib); + this.e = e; + this.sslLib = sslLib; + this.cLib = cLib; + } + + /** the transport for this engine: the library on the unit, files in the tests; null (said why) when there's none */ + static Http.Transport forEngine(Engine e, List why) { + String web = Engine.env("HMGAPI_TEST_WEB", null); + if (e.host && web != null) return new Web(new File(web)); + File lib = new File(e.root + LIB); + if (!lib.isFile()) { + why.add("HMG-API's HTTPS library isn't installed (" + LIB + "): install HMG-API again"); + return null; + } + try { + // off the car (a live test from a computer): that computer's TLS library + String ssl = e.host ? Engine.env("HMGAPI_TEST_SSL", SSL) : SSL; + return new NativeFetch(e, lib.getPath(), ssl, LIBC); + } catch (Throwable t) { + why.add("HMG-API's HTTPS library didn't load: " + t); + return null; + } + } + + static native int fetch(String sslLib, String cLib, String host, String port, byte[] request, String outPath, int maxBytes); + + @Override + public int exchange(String host, byte[] request, File rawOut, int maxBytes) { + String dns = DnsLookup.server(e); + if (dns == null) return -3; + String target; + try { + List a = DnsLookup.lookup(dns, host); + if (a.isEmpty()) return -3; + target = host + "@" + a.get(0); + } catch (IOException x) { + return -3; + } + return fetch(sslLib, cLib, target, "443", request, rawOut.getPath(), maxBytes); + } + + static String why(int code) { + switch (code) { + case -1: return "the TLS or C library can't be opened"; + case -2: return "a function is missing from the TLS or C library"; + case -3: return "the name didn't resolve (is home Wi-Fi up?)"; + case -4: return "no connection (home Wi-Fi up, with internet?)"; + case -5: return "TLS setup failed"; + case -6: return "TLS handshake failed"; + case -7: return "the request couldn't be sent"; + case -8: return "the file couldn't be written"; + case -9: return "the answer is larger than allowed"; + case -10: return "no answer"; + default: return "error " + code; + } + } + + /** + * Off-car tests: // (a query's '?' as '_'), 200 with its bytes; .redirect holds a + * Location for a 302; .status a status to answer with instead; anything else 404. Each request's + * host and path is appended to /requests.log. + */ + static final class Web implements Http.Transport { + private final File dir; + + Web(File dir) { + this.dir = dir; + } + + @Override + public int exchange(String host, byte[] request, File rawOut, int maxBytes) { + try { + String req = new String(request, "US-ASCII"); + String path = req.substring(4, req.indexOf(' ', 4)); + File log = new File(dir, "requests.log"); + Engine.write(log, (log.isFile() ? Engine.read(log) : "") + host + path + "\n"); + if (new File(dir, host + ".down").exists()) return -4; + File f = new File(dir, host + path.replace('?', '_')); + String head; + byte[] body = new byte[0]; + if (new File(f.getPath() + ".redirect").isFile()) { + head = "HTTP/1.1 302 Found\r\nLocation: " + Engine.read(new File(f.getPath() + ".redirect")).trim() + "\r\nContent-Length: 0\r\n"; + } else if (new File(f.getPath() + ".status").isFile()) { + head = "HTTP/1.1 " + Engine.read(new File(f.getPath() + ".status")).trim() + " X\r\nContent-Length: 0\r\n"; + } else if (f.isFile()) { + body = Engine.readAll(new java.io.FileInputStream(f)); + head = "HTTP/1.1 200 OK\r\nContent-Length: " + body.length + "\r\n"; + } else { + head = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n"; + } + OutputStream o = new FileOutputStream(rawOut); + try { + o.write((head + "\r\n").getBytes("US-ASCII")); + o.write(body); + } finally { + o.close(); + } + return (int) rawOut.length(); + } catch (Exception x) { + return -10; + } + } + } +} diff --git a/core/runtime/java/hmgapi/engine/Sha256.java b/core/runtime/java/hmgapi/engine/Sha256.java new file mode 100644 index 00000000..cf072ff7 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Sha256.java @@ -0,0 +1,76 @@ +package hmgapi.engine; + +/** + * SHA-256 (FIPS 180-4) in plain Java, for the catalogue's package checksums. Under app_process, + * Android 4.4's MessageDigest SHA-256 can be missing (Conscrypt's class didn't load in a mod's + * service on an Ioniq 5 US 260507), so the downloads don't depend on it. + */ +final class Sha256 { + private static final int[] K = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + + private final int[] h = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + private final byte[] block = new byte[64]; + private final int[] w = new int[64]; + private int fill; + private long bytes; + + void update(byte[] b, int off, int len) { + bytes += len; + while (len > 0) { + int n = Math.min(len, 64 - fill); + System.arraycopy(b, off, block, fill, n); + fill += n; off += n; len -= n; + if (fill == 64) { compress(); fill = 0; } + } + } + + byte[] digest() { + long bits = bytes * 8; + byte[] pad = new byte[(fill < 56 ? 56 - fill : 120 - fill) + 8]; + pad[0] = (byte) 0x80; + for (int i = 0; i < 8; i++) pad[pad.length - 1 - i] = (byte) (bits >>> (8 * i)); + update(pad, 0, pad.length); + byte[] out = new byte[32]; + for (int i = 0; i < 8; i++) for (int j = 0; j < 4; j++) out[i * 4 + j] = (byte) (h[i] >>> (24 - 8 * j)); + return out; + } + + private void compress() { + for (int i = 0; i < 16; i++) + w[i] = ((block[i * 4] & 0xff) << 24) | ((block[i * 4 + 1] & 0xff) << 16) | ((block[i * 4 + 2] & 0xff) << 8) | (block[i * 4 + 3] & 0xff); + for (int i = 16; i < 64; i++) { + int s0 = Integer.rotateRight(w[i - 15], 7) ^ Integer.rotateRight(w[i - 15], 18) ^ (w[i - 15] >>> 3); + int s1 = Integer.rotateRight(w[i - 2], 17) ^ Integer.rotateRight(w[i - 2], 19) ^ (w[i - 2] >>> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + int a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + for (int i = 0; i < 64; i++) { + int t1 = hh + (Integer.rotateRight(e, 6) ^ Integer.rotateRight(e, 11) ^ Integer.rotateRight(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]; + int t2 = (Integer.rotateRight(a, 2) ^ Integer.rotateRight(a, 13) ^ Integer.rotateRight(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); + hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + + static String hex(java.io.File f) throws java.io.IOException { + Sha256 d = new Sha256(); + java.io.InputStream in = new java.io.FileInputStream(f); + try { + byte[] buf = new byte[16384]; + for (int n; (n = in.read(buf)) > 0; ) d.update(buf, 0, n); + } finally { + in.close(); + } + StringBuilder sb = new StringBuilder(); + for (byte x : d.digest()) sb.append(Character.forDigit((x >> 4) & 0xf, 16)).append(Character.forDigit(x & 0xf, 16)); + return sb.toString(); + } +} diff --git a/core/runtime/test/hmgapi/engine/FetchTest.java b/core/runtime/test/hmgapi/engine/FetchTest.java new file mode 100644 index 00000000..9d0d5ae5 --- /dev/null +++ b/core/runtime/test/hmgapi/engine/FetchTest.java @@ -0,0 +1,87 @@ +package hmgapi.engine; + +import java.io.File; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Random; + +/** The engine's HTTPS pieces without a network: Http over NativeFetch.Web (files), Sha256, DnsLookup's reader. */ +public final class FetchTest { + static int failed; + + static void check(String what, boolean ok) { + System.out.println((ok ? "ok " : "FAIL ") + what); + if (!ok) failed++; + } + + static void put(File web, String path, String body) throws Exception { + File f = new File(web, path); + f.getParentFile().mkdirs(); + Files.write(f.toPath(), body.getBytes("UTF-8")); + } + + public static void main(String[] args) throws Exception { + File d = Files.createTempDirectory("fetch").toFile(), web = new File(d, "web"), tmp = new File(d, "tmp"); + tmp.mkdirs(); + Http http = new Http(new NativeFetch.Web(web), tmp); + File out = new File(d, "out"); + + put(web, "raw.githubusercontent.com/a.txt", "hello, car"); + check("200: written", http.get("https://raw.githubusercontent.com/a.txt", out, 100).ok() && "hello, car".equals(Engine.read(out))); + put(web, "github.com/r.zip.redirect", "https://objects.githubusercontent.com/x.zip"); + put(web, "objects.githubusercontent.com/x.zip", "zip bytes"); + check("a redirect to GitHub's asset host: followed", http.get("https://github.com/r.zip", out, 100).ok() && "zip bytes".equals(Engine.read(out))); + put(web, "github.com/evil.redirect", "https://example.com/x"); + Http.Result r = http.get("https://github.com/evil", out, 100); + check("a redirect to another host: refused (" + r + ")", !r.ok() && r.toString().contains("host not allowed")); + check("plain http: refused", !http.get("http://github.com/a", out, 100).ok()); + check("another host: refused", !http.get("https://example.com/a", out, 100).ok()); + put(web, "api.github.com/repos/x/y/contents/c_ref=main", "[]"); + check("the API, with a query", http.get("https://api.github.com/repos/x/y/contents/c?ref=main", out, 100).ok()); + put(web, "raw.githubusercontent.com/big", new String(new char[500]).replace('\0', 'x')); + File big = new File(d, "big"); + r = http.get("https://raw.githubusercontent.com/big", big, 100); + check("over the cap: refused, nothing left (" + r + ")", !r.ok() && !big.exists() && !new File(d, "big.part").exists()); + check("404: reported", http.get("https://raw.githubusercontent.com/none", out, 100).status == 404); + new File(web, "raw.githubusercontent.com.down").createNewFile(); + r = http.get("https://raw.githubusercontent.com/a.txt", out, 100); + check("no connection: said (" + r + ")", !r.ok() && r.toString().contains("no connection")); + + boolean same = true; + Random rnd = new Random(7); + for (int len : new int[] {0, 1, 55, 56, 63, 64, 65, 119, 120, 1000, 100000}) { + byte[] data = new byte[len]; + rnd.nextBytes(data); + Sha256 s = new Sha256(); + s.update(data, 0, Math.min(len, 7)); + if (len > 7) s.update(data, 7, len - 7); + same &= Arrays.equals(s.digest(), MessageDigest.getInstance("SHA-256").digest(data)); + } + check("SHA-256: the JDK's at every length tried", same); + Files.write(out.toPath(), "abc".getBytes("US-ASCII")); + check("SHA-256 of a file, hex", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".equals(Sha256.hex(out))); + + byte[] q = DnsLookup.query(0x1234, "raw.githubusercontent.com"); + java.io.ByteArrayOutputStream a = new java.io.ByteArrayOutputStream(); + a.write(q, 0, q.length); + byte[] ans = a.toByteArray(); + ans[2] = (byte) 0x81; ans[3] = (byte) 0x80; ans[7] = 3; + a.reset(); a.write(ans, 0, ans.length); + for (int[] rr : new int[][] {{0xc0, 12, 0, 5, 0, 1, 0, 0, 0, 60, 0, 2, 0xc0, 12}, + {0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 185, 199, 108, 133}, {0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 185, 199, 109, 133}}) { + for (int b : rr) a.write(b); + } + byte[] dr = a.toByteArray(); + check("DNS: A records read, a CNAME skipped", DnsLookup.answers(dr, dr.length, 0x1234).toString().equals("[185.199.108.133, 185.199.109.133]")); + boolean refused = false; + try { DnsLookup.answers(dr, dr.length, 0x4321); } catch (java.io.IOException x) { refused = true; } + check("DNS: an answer to another query refused", refused); + refused = false; + try { DnsLookup.answers(dr, dr.length - 3, 0x1234); } catch (java.io.IOException x) { refused = true; } + check("DNS: a cut-off answer refused", refused); + dr[3] = (byte) 0x83; + check("DNS: no such name: none", DnsLookup.answers(dr, dr.length, 0x1234).isEmpty()); + System.exit(failed == 0 ? 0 : 1); + } +} diff --git a/install/common/install.sh b/install/common/install.sh index bc889914..d56e153e 100644 --- a/install/common/install.sh +++ b/install/common/install.sh @@ -304,6 +304,11 @@ cp "$P/uninstall.sh" "$P/lib.sh" "$P/stock.txt" "$P/app-pending.sh" "$P/hook-che # open.sh (NEMESIS Manager's Launch, adb) installs the app from this copy if it's missing, then opens it cp "$P/app-open.sh" "$D/open.sh" && chmod 700 "$D/open.sh" || fail "keep open.sh" cp "$P/HmgApi.apk" "$D/HmgApi.apk" && chmod 644 "$D/HmgApi.apk" || fail "keep a copy of the app" +# the engine's HTTPS (the catalogue and updates over home Wi-Fi, Catalog): in /data, nothing on /system for it +if [ -f "$P/libhmgapi_fetch.so" ]; then + mkdir -p "$D/lib" && cp "$P/libhmgapi_fetch.so" "$D/lib/libhmgapi_fetch.so.new" && chmod 644 "$D/lib/libhmgapi_fetch.so.new" \ + && mv "$D/lib/libhmgapi_fetch.so.new" "$D/lib/libhmgapi_fetch.so" || fail "keep the engine's HTTPS library" +fi # HMG-API's NEMESIS scripts and incompatible packages: engine nemesis-sync lists HMG-API and its mods in NEMESIS with them if [ -d "$P/nemesis" ]; then rm -rf "$D/nemesis" && cp -r "$P/nemesis" "$D/nemesis" && chmod -R 700 "$D/nemesis" || fail "keep the NEMESIS scripts" diff --git a/tools/test-all.sh b/tools/test-all.sh index 0d50eb41..3464b82e 100755 --- a/tools/test-all.sh +++ b/tools/test-all.sh @@ -7,9 +7,9 @@ # Each test: "ok" (its checks, and how many it skipped), "skip" (it skipped everything, # and why) or "FAIL" (its failed checks). cd "$(dirname "$0")/.." -ALL="core/hmgapid/test.sh core/zygote/test.sh tools/lpatch/test.sh core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/common/install-test.sh install/common/orders-test.sh install/usb/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/cars-test.sh tools/sdk-test.sh tools/check-scripts.sh" +ALL="core/hmgapid/test.sh core/zygote/test.sh tools/lpatch/test.sh core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/fetch-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/common/install-test.sh install/common/orders-test.sh install/usb/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/cars-test.sh tools/sdk-test.sh tools/check-scripts.sh" # no build, no ARM toolchain: all but hmgapid, the zygote wrapper, lpatch, the installers and the SDK -FAST="core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/check-scripts.sh" +FAST="core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/fetch-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/check-scripts.sh" # these write out/ (usb: out/payload and out/dist; sdk: out/mods, out/packages, out/dist) or read # what another writes (install-test: out/payload), so they run one after another SERIAL="install/common/install-test.sh install/usb/test.sh tools/sdk-test.sh" From 65577e1fe0216c913a1dc978dd3525168a50b748 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:36:01 -0500 Subject: [PATCH 2/5] fetch.c: no jni.h on the unit's build (it pulls in the build machine's libc headers) The few JNI pieces it uses are declared at their places in the standard table, checked at compile time; the library is byte-for-byte the same. CI's Linux headers failed for the ARM target. Co-Authored-By: Claude Opus 5.5 --- build.sh | 7 ++----- core/fetch/fetch.c | 28 ++++++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/build.sh b/build.sh index 8907ec09..c570d173 100755 --- a/build.sh +++ b/build.sh @@ -35,14 +35,11 @@ loader() { } fetchlib() { - # libhmgapi_fetch.so (core/fetch/fetch.c): the engine's HTTPS through the unit's own libssl; no libc, - # only dlopen/dlsym from the unit's libdl (the loader's stand-in), and a JDK's jni.h + # libhmgapi_fetch.so (core/fetch/fetch.c): the engine's HTTPS through the unit's own libssl; no libc + # or system headers, only dlopen/dlsym from the unit's libdl (the loader's stand-in) sh core/loader/syslib-stubs.sh "$OUT/syslib" >/dev/null - J=${JAVA_HOME:-$(cd "$(dirname "$(readlink -f "$(command -v javac)")")/.." && pwd)} - case "$(uname -s)" in Darwin) JOS=darwin ;; *) JOS=linux ;; esac clang --target=armv7a-linux-androideabi -mthumb -march=armv7-a -mfloat-abi=softfp -Os -fPIC \ -ffreestanding -fno-builtin -nostdlib -shared -fno-stack-protector -fno-exceptions -fno-asynchronous-unwind-tables -fuse-ld=lld \ - -I"$J/include" -I"$J/include/$JOS" \ -Wl,-z,now -Wl,--no-rosegment -Wl,--hash-style=sysv -Wl,-z,defs -Wl,--build-id=none -Wl,-soname,libhmgapi_fetch.so \ -o "$OUT/libhmgapi_fetch.so" core/fetch/fetch.c "$OUT/syslib/libdl.so" md5sum "$OUT/libhmgapi_fetch.so" diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c index c13465aa..020be2d5 100644 --- a/core/fetch/fetch.c +++ b/core/fetch/fetch.c @@ -21,9 +21,8 @@ * and an OpenSSL 1.1+/3 library, which is why each OpenSSL call has an old and a new name. * First written as a mod (an update-check proof of concept), run on an Ioniq 5 US 260507. */ -#include - #ifdef HOST +#include #include #include #include @@ -52,6 +51,31 @@ struct addrinfo { /* bionic, 32-bit ARM */ #define O_TRUNC 01000 static void *libc_handle; #define LIBC_SYM(name) dlsym(libc_handle, #name) +/* the few JNI pieces used here, at their places in the standard function table (as jni.h has + * them), so the unit's build needs no system headers (jni.h pulls in the build machine's libc) */ +typedef int jint; +typedef jint jsize; +typedef signed char jbyte; +typedef unsigned char jboolean; +typedef void *jobject; +typedef jobject jclass, jstring, jbyteArray; +struct JNINativeInterface_ { + void *before169[169]; + const char *(*GetStringUTFChars)(void *, jstring, jboolean *); /* 169 */ + void (*ReleaseStringUTFChars)(void *, jstring, const char *); /* 170 */ + jsize (*GetArrayLength)(void *, jbyteArray); /* 171 */ + void *before184[184 - 172]; + jbyte *(*GetByteArrayElements)(void *, jbyteArray, jboolean *); /* 184 */ + void *before192[192 - 185]; + void (*ReleaseByteArrayElements)(void *, jbyteArray, jbyte *, jint); /* 192 */ +}; +_Static_assert(__builtin_offsetof(struct JNINativeInterface_, GetStringUTFChars) == 169 * sizeof(void *), "JNI table"); +_Static_assert(__builtin_offsetof(struct JNINativeInterface_, GetByteArrayElements) == 184 * sizeof(void *), "JNI table"); +_Static_assert(__builtin_offsetof(struct JNINativeInterface_, ReleaseByteArrayElements) == 192 * sizeof(void *), "JNI table"); +typedef const struct JNINativeInterface_ *JNIEnv; +#define JNIEXPORT __attribute__((visibility("default"))) +#define JNICALL +#define JNI_ABORT 2 static void *memset(void *p, int c, unsigned long n) { unsigned char *b = p; while (n--) *b++ = (unsigned char) c; return p; } #endif From afc47630819414639af593201dec16c261a332ad Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:41:22 -0500 Subject: [PATCH 3/5] The engine's HTTPS: timeouts, home Wi-Fi or nothing, whole answers only fetch.c: every socket gets 20 s send and receive timeouts (connect, the handshake, each read and write), home Wi-Fi's mark and SO_BINDTODEVICE wlan0, or the call fails (E_ROUTE): no unmarked socket on the main table, even before the fwmark rule is in. setsockopt is required. The DNS query goes out through the library too (NativeFetch.dns, UDP, the same socket setup), and the connection only goes to an address (AI_NUMERICHOST: never the system resolver). An answer ends whole only on the server's TLS close; a drop, read error or timeout is E_CUT with what came kept. No static buffer (malloc'd per call); the answer file is opened O_EXCL | O_NOFOLLOW. DnsLookup takes the server from wifi.sh's lease (there only while home Wi-Fi's route is up) instead of dhcp.wlan0.dns1, and asks through an Asker (the library's socket) instead of an unmarked DatagramSocket. Http: one answer file per call (NativeFetch.fresh); a cut answer counts only if its Content-Length is met or its last chunk read; headers cut off are an error; chunk sizes are hex digits only, at most 7 (a negative size passed the cap), each chunk must end in CRLF; a body that fails for any reason leaves no .part. Content-Length must be a number and within the cap. Tests: NativeFetch.Web honours maxBytes and O_EXCL, and serves chunked, no-length, raw and cut answers; FetchTest adds cap, chunked, cut, redirect, lease and eight-threads cases. fetch-test.sh builds the library for the computer (-DHOST) and runs it against a local TLS server: a TLS close, a drop, a quiet server (timeouts), the cap, O_EXCL and O_NOFOLLOW, and the DNS exchange. libhmgapi_fetch.so is in install-test.sh's and zygote-orders.py's MANIFESTs, and install-test checks it lands in /data/hmgapi/lib, 644, nothing on /system. Tested off-car only (fetch-test.sh with Homebrew OpenSSL 3 on macOS, install-test.sh, orders-test.sh; ./build.sh fetchlib links with only dlopen and dlsym undefined). Not yet run on a car. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +- core/fetch/fetch.c | 286 +++++++++++++----- core/runtime/fetch-test.sh | 23 +- .../runtime/java/hmgapi/engine/DnsLookup.java | 58 ++-- core/runtime/java/hmgapi/engine/Http.java | 123 +++++--- .../java/hmgapi/engine/NativeFetch.java | 110 +++++-- .../test/hmgapi/engine/FetchNativeTest.java | 179 +++++++++++ .../runtime/test/hmgapi/engine/FetchTest.java | 149 +++++++++ install/common/install-test.sh | 13 +- tools/zygote-orders.py | 4 +- 10 files changed, 777 insertions(+), 177 deletions(-) create mode 100644 core/runtime/test/hmgapi/engine/FetchNativeTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ef7d99e..58e6449f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,7 +35,14 @@ Java TLS can't reach GitHub, so the engine uses the unit's own `libssl.so` (TLS 1.2), on a socket marked for home Wi-Fi only, with its own DNS lookup on home Wi-Fi's server. Tested first as a mod on an Ioniq 5 US 260507 (HMG-API rc.10): the catalogue and three packages - over home Wi-Fi, each with its SHA-256. + over home Wi-Fi, each with its SHA-256. Each socket has home Wi-Fi's mark and is bound to + `wlan0`, or the call fails (never an unmarked socket on the main table's mobile data, even + before the fwmark rule is in), with 20 s send and receive timeouts (connect, the handshake, + each read). The DNS server comes from home Wi-Fi's lease (there only while its route is up, + not a leftover `dhcp.wlan0.dns1`), asked on the same kind of socket. An answer the server + didn't end with a TLS close counts only when its Content-Length or last chunk says it is + whole; chunk sizes are hex digits only (a negative one passed the cap), and a broken body + leaves no `.part`. Each call has its own answer file, opened `O_EXCL` and `O_NOFOLLOW`. ## 1.1.0-rc.10 (2026-11-25) diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c index 020be2d5..10bc561f 100644 --- a/core/fetch/fetch.c +++ b/core/fetch/fetch.c @@ -1,10 +1,11 @@ -/* libhmgapi_fetch.so: one HTTPS request for HMG-API's engine (hmgapi.engine.NativeFetch): the - * catalogue, mod packages and HMG-API releases, over home Wi-Fi only (Catalog). +/* libhmgapi_fetch.so: one HTTPS request, or one DNS query, for HMG-API's engine (hmgapi.engine.NativeFetch): + * the catalogue, mod packages and HMG-API releases, over home Wi-Fi only (Catalog). * * Android 4.4's Java TLS shares no cipher suite with GitHub, but the unit's own libssl.so * (OpenSSL 1.0.1) has TLS 1.2 with ECDHE and AES-GCM. This opens a TCP connection, does the * handshake with that library, sends the request bytes Java made and writes every response - * byte (headers and body) to a file, up to a cap. Java parses the HTTP. + * byte (headers and body) to a file, up to a cap. Java parses the HTTP. The DNS query (Java's + * bytes, DnsLookup) goes out the same way, over UDP, so it is held to home Wi-Fi too. * * The server's certificate is NOT checked here: the unit's 2013 root store doesn't know GitHub's * roots and its clock isn't reliable. Nothing fetched is trusted because of where it came from: @@ -12,13 +13,22 @@ * (the installed mod's author key; HMG-API's release key for HMG-API itself) and refuses a * downgrade. A hostile network can make a check find nothing, not get code installed. * - * The socket carries home Wi-Fi's mark (SO_MARK 0x2951: table 95, HomeWifi), so it goes out on home - * Wi-Fi or not at all (table 95 holds an unreachable default while home Wi-Fi is down), never - * on the car's mobile data. Root only (the engine is). + * Every socket carries home Wi-Fi's mark (SO_MARK 0x2951: table 95, HomeWifi) and is bound to + * wlan0 (SO_BINDTODEVICE), or isn't used at all: a socket that can't have both is an error. The + * mark makes its route table 95's (home Wi-Fi, or the unreachable default while home Wi-Fi is + * down); the binding holds it to wlan0 even before the network keeper has added the fwmark rule + * (priority 900), when the mark alone would leave it on the main table's mobile data. Root only + * (the engine is). Each socket has send and receive timeouts (connect, the handshake and every + * read and write), so a network that goes away mid-answer (route_down) ends the call. + * + * How the answer ended matters: a TLS close (close_notify) is a whole answer; anything else + * (the connection dropped, a read error, a timeout) is E_CUT with what came written to the file, + * which Java takes only if the HTTP framing says it is whole (Http). * * Built with no libc (as the loader): everything comes through dlopen/dlsym from the unit's * libc.so and libssl.so. On a computer (-DHOST, the off-car tests) it uses the system's headers * and an OpenSSL 1.1+/3 library, which is why each OpenSSL call has an old and a new name. + * No static buffers: calls may come from several threads. * First written as a mod (an update-check proof of concept), run on an Ioniq 5 US 260507. */ #ifdef HOST @@ -26,8 +36,10 @@ #include #include #include +#include #include #include +#include #include #define LIBC_SYM(name) ((void *) name) typedef socklen_t sock_len; @@ -44,13 +56,22 @@ struct addrinfo { /* bionic, 32-bit ARM */ struct sockaddr *ai_addr; struct addrinfo *ai_next; }; +struct timeval { long tv_sec, tv_usec; }; /* 32-bit ARM: two 32-bit longs */ +_Static_assert(sizeof(struct timeval) == 8, "ARM timeval"); #define AF_INET 2 #define SOCK_STREAM 1 +#define SOCK_DGRAM 2 +#define AI_NUMERICHOST 4 +#define SOL_SOCKET 1 +#define SO_RCVTIMEO 20 +#define SO_SNDTIMEO 21 +#define SO_BINDTODEVICE 25 +#define SO_MARK 36 #define O_WRONLY 01 #define O_CREAT 0100 -#define O_TRUNC 01000 -static void *libc_handle; -#define LIBC_SYM(name) dlsym(libc_handle, #name) +#define O_EXCL 0200 +#define O_NOFOLLOW 0100000 /* ARM's value (x86's is 0400000) */ +#define LIBC_SYM(name) dlsym(libc_h, #name) /* the few JNI pieces used here, at their places in the standard function table (as jni.h has * them), so the unit's build needs no system headers (jni.h pulls in the build machine's libc) */ typedef int jint; @@ -79,45 +100,132 @@ typedef const struct JNINativeInterface_ *JNIEnv; static void *memset(void *p, int c, unsigned long n) { unsigned char *b = p; while (n--) *b++ = (unsigned char) c; return p; } #endif -/* error codes (negative), so Java can say which step failed */ +/* error codes (negative), so Java can say which step failed (NativeFetch.why) */ enum { E_LIB = -1, E_SYM = -2, E_RESOLVE = -3, E_CONNECT = -4, E_CTX = -5, E_HANDSHAKE = -6, E_SEND = -7, - E_FILE = -8, E_TOO_BIG = -9, E_READ = -10, E_ARGS = -11 }; + E_FILE = -8, E_TOO_BIG = -9, E_READ = -10, E_ARGS = -11, E_ROUTE = -12, E_CUT = -13, E_SOCKET = -14 }; #define SSL_CTRL_OPTIONS 32 #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 #define SSL_OP_NO_SSLv2 0x01000000L #define SSL_OP_NO_SSLv3 0x02000000L +#define SSL_ERROR_ZERO_RETURN 6 +#define HOME_MARK 0x2951 +#define HOME_IFACE "wlan0" +#define BUF 16384 + +/* the C library's functions this needs, looked up once per call */ +struct libc { + int (*getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **); + void (*freeaddrinfo)(struct addrinfo *); + int (*socket)(int, int, int); + int (*connect)(int, const struct sockaddr *, sock_len); + int (*setsockopt)(int, int, int, const void *, sock_len); + int (*close)(int); + int (*open)(const char *, int, ...); + long (*write)(int, const void *, unsigned long); + long (*read)(int, void *, unsigned long); + void *(*malloc)(unsigned long); + void (*free)(void *); +}; + +static int libc_load(struct libc *c, const char *c_lib) { +#ifndef HOST + void *libc_h = dlopen(c_lib, RTLD_NOW); + if (!libc_h) return E_LIB; +#else + (void) c_lib; +#endif + c->getaddrinfo = LIBC_SYM(getaddrinfo); + c->freeaddrinfo = LIBC_SYM(freeaddrinfo); + c->socket = LIBC_SYM(socket); + c->connect = LIBC_SYM(connect); + c->setsockopt = LIBC_SYM(setsockopt); + c->close = LIBC_SYM(close); + c->open = LIBC_SYM(open); + c->write = LIBC_SYM(write); + c->read = LIBC_SYM(read); + c->malloc = LIBC_SYM(malloc); + c->free = LIBC_SYM(free); + if (!c->getaddrinfo || !c->freeaddrinfo || !c->socket || !c->connect || !c->setsockopt || !c->close || !c->open + || !c->write || !c->read || !c->malloc || !c->free) return E_SYM; + return 0; +} + +/* a socket for a: timeouts set, and (on the unit) home Wi-Fi's mark and wlan0, or none at all */ +static int home_socket(struct libc *c, const struct addrinfo *a, int timeout_ms) { + int fd = c->socket(a->ai_family, a->ai_socktype, a->ai_protocol); + if (fd < 0) return E_SOCKET; + struct timeval tv; + memset(&tv, 0, sizeof tv); + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; + if (c->setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv) != 0 + || c->setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv) != 0) { /* SO_SNDTIMEO bounds connect too */ + c->close(fd); + return E_SOCKET; + } +#ifndef HOST + unsigned int mark = HOME_MARK; + static const char iface[] = HOME_IFACE; + if (c->setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof mark) != 0 + || c->setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface, sizeof iface) != 0) { + c->close(fd); + return E_ROUTE; + } +#endif + return fd; +} + +/* connected to the first of addr:port that answers; or a negative error */ +static int home_connect(struct libc *c, const char *addr, const char *port, int type, int timeout_ms) { + struct addrinfo hints, *res = 0, *a; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_INET; /* home Wi-Fi is IPv4 only for mods */ + hints.ai_socktype = type; + hints.ai_flags = AI_NUMERICHOST; /* an address (DnsLookup's): never the system resolver, which uses mobile data */ + if (c->getaddrinfo(addr, port, &hints, &res) != 0 || !res) return E_RESOLVE; + int fd = E_CONNECT; + for (a = res; a; a = a->ai_next) { + fd = home_socket(c, a, timeout_ms); + if (fd < 0) break; /* no socket held to home Wi-Fi: no connection */ + if (c->connect(fd, a->ai_addr, a->ai_addrlen) == 0) break; + c->close(fd); + fd = E_CONNECT; + } + c->freeaddrinfo(res); + return fd; +} + +/* the answer's file: new, ours (O_EXCL), never through a link */ +static int open_new(struct libc *c, const char *path) { + return c->open(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600); +} + +static int write_all(struct libc *c, int fd, const char *p, int n) { + int w = 0; + while (w < n) { + long k = c->write(fd, p + w, (unsigned long) (n - w)); + if (k <= 0) return -1; + w += (int) k; + } + return 0; +} -/* host is "name" or "name@address": the name goes in the TLS server name, and the connection goes - * to the address when there is one (Java's own lookup, DnsLookup: the unit's resolver can't be - * used by a mod's service on home Wi-Fi, see there) */ +/* host is "name@address": the name goes in the TLS server name, the connection goes to the + * address (Java's own lookup, DnsLookup: the unit's resolver would ask the car's carrier DNS) */ static int fetch(const char *ssl_lib, const char *c_lib, const char *host_arg, const char *port, - const char *request, int request_len, const char *out_path, int max_bytes) { + const char *request, int request_len, const char *out_path, int max_bytes, int timeout_ms) { char host[256]; - const char *addr = host_arg; int hn = 0; while (host_arg[hn] && host_arg[hn] != '@' && hn < (int) sizeof host - 1) { host[hn] = host_arg[hn]; hn++; } host[hn] = 0; - if (host_arg[hn] == '@') addr = host_arg + hn + 1; - else if (host_arg[hn]) return E_ARGS; - else addr = host; + if (host_arg[hn] != '@' || !host_arg[hn + 1]) return E_ARGS; + const char *addr = host_arg + hn + 1; + struct libc c; + int rc = libc_load(&c, c_lib); + if (rc) return rc; void *ssl_h = dlopen(ssl_lib, RTLD_NOW); if (!ssl_h) return E_LIB; -#ifndef HOST - libc_handle = dlopen(c_lib, RTLD_NOW); - if (!libc_handle) return E_LIB; -#else - (void) c_lib; -#endif - int (*p_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = LIBC_SYM(getaddrinfo); - void (*p_freeaddrinfo)(struct addrinfo *) = LIBC_SYM(freeaddrinfo); - int (*p_socket)(int, int, int) = LIBC_SYM(socket); - int (*p_connect)(int, const struct sockaddr *, sock_len) = LIBC_SYM(connect); - int (*p_setsockopt)(int, int, int, const void *, sock_len) = LIBC_SYM(setsockopt); - int (*p_close)(int) = LIBC_SYM(close); - int (*p_open)(const char *, int, ...) = LIBC_SYM(open); - long (*p_write)(int, const void *, unsigned long) = LIBC_SYM(write); - if (!p_getaddrinfo || !p_freeaddrinfo || !p_socket || !p_connect || !p_close || !p_open || !p_write) return E_SYM; /* OpenSSL 1.0.x names first (the unit), then 1.1+/3 (a computer) */ int (*p_init_old)(void) = dlsym(ssl_h, "SSL_library_init"); @@ -135,37 +243,16 @@ static int fetch(const char *ssl_lib, const char *c_lib, const char *host_arg, c int (*p_ssl_connect)(void *) = dlsym(ssl_h, "SSL_connect"); int (*p_ssl_write)(void *, const void *, int) = dlsym(ssl_h, "SSL_write"); int (*p_ssl_read)(void *, void *, int) = dlsym(ssl_h, "SSL_read"); + int (*p_get_error)(const void *, int) = dlsym(ssl_h, "SSL_get_error"); int (*p_shutdown)(void *) = dlsym(ssl_h, "SSL_shutdown"); if ((!p_init_old && !p_init_new) || !p_method || !p_ctx_new || !p_ctx_free || !p_new || !p_free || !p_ctrl - || !p_set_fd || !p_ssl_connect || !p_ssl_write || !p_ssl_read) return E_SYM; - - struct addrinfo hints, *res = 0, *a; - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_INET; /* home Wi-Fi is IPv4 only for mods */ - hints.ai_socktype = SOCK_STREAM; - if (p_getaddrinfo(addr, port, &hints, &res) != 0 || !res) return E_RESOLVE; - int fd = -1; - for (a = res; a; a = a->ai_next) { - fd = p_socket(a->ai_family, a->ai_socktype, a->ai_protocol); - if (fd < 0) continue; -#ifndef HOST - /* home Wi-Fi's mark on the socket itself, so the connection's route is table 95's from the - * start (home Wi-Fi, or unreachable): never the main table's mobile data */ - if (p_setsockopt) { - unsigned int mark = 0x2951; - p_setsockopt(fd, 1 /* SOL_SOCKET */, 36 /* SO_MARK */, &mark, sizeof mark); - } -#endif - if (p_connect(fd, a->ai_addr, a->ai_addrlen) == 0) break; - p_close(fd); - fd = -1; - } - p_freeaddrinfo(res); - if (fd < 0) return E_CONNECT; + || !p_set_fd || !p_ssl_connect || !p_ssl_write || !p_ssl_read || !p_get_error) return E_SYM; - int rc; + int fd = home_connect(&c, addr, port, SOCK_STREAM, timeout_ms); + if (fd < 0) return fd; void *ctx = 0, *ssl = 0; - int out = -1; + int out = -1, clean = 0; + char *buf = 0; if (p_init_new) p_init_new(0, 0); else p_init_old(); ctx = p_ctx_new(p_method()); if (!ctx) { rc = E_CTX; goto done; } @@ -181,41 +268,67 @@ static int fetch(const char *ssl_lib, const char *c_lib, const char *host_arg, c if (n <= 0) { rc = E_SEND; goto done; } sent += n; } - out = p_open(out_path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + buf = c.malloc(BUF); + if (!buf) { rc = E_CTX; goto done; } + out = open_new(&c, out_path); if (out < 0) { rc = E_FILE; goto done; } - static char buf[16384]; int total = 0; for (;;) { - int n = p_ssl_read(ssl, buf, sizeof buf); - if (n <= 0) break; /* the server closes after the response (Connection: close) */ - if (total + n > max_bytes) { rc = E_TOO_BIG; goto done; } - int w = 0; - while (w < n) { - long k = p_write(out, buf + w, (unsigned long) (n - w)); - if (k <= 0) { rc = E_FILE; goto done; } - w += (int) k; + int n = p_ssl_read(ssl, buf, BUF); + if (n <= 0) { + /* the server's TLS close (Connection: close) ends a whole answer; a dropped connection, + * a read error or a timeout doesn't: Java decides from the HTTP framing (E_CUT) */ + clean = p_get_error(ssl, n) == SSL_ERROR_ZERO_RETURN; + break; } + if (n > max_bytes - total) { rc = E_TOO_BIG; goto done; } + if (write_all(&c, out, buf, n)) { rc = E_FILE; goto done; } total += n; } - rc = total > 0 ? total : E_READ; + rc = total == 0 ? E_READ : clean ? total : E_CUT; done: - if (out >= 0) p_close(out); - if (ssl) { if (p_shutdown) p_shutdown(ssl); p_free(ssl); } + if (out >= 0) c.close(out); + if (buf) c.free(buf); + if (ssl) { if (clean && p_shutdown) p_shutdown(ssl); p_free(ssl); } /* no shutdown after an error (OpenSSL) */ if (ctx) p_ctx_free(ctx); - p_close(fd); + c.close(fd); + return rc; +} + +/* one UDP query to server:port (DnsLookup's bytes) on a socket held to home Wi-Fi; the answer to out_path */ +static int dns(const char *c_lib, const char *server, const char *port, const char *query, int query_len, + const char *out_path, int timeout_ms) { + struct libc c; + int rc = libc_load(&c, c_lib); + if (rc) return rc; + int fd = home_connect(&c, server, port, SOCK_DGRAM, timeout_ms); + if (fd < 0) return fd; + char *buf = c.malloc(1500); + int out = -1; + if (!buf) { rc = E_CTX; goto done; } + if (c.write(fd, query, (unsigned long) query_len) != query_len) { rc = E_SEND; goto done; } + long n = c.read(fd, buf, 1500); + if (n <= 0) { rc = E_READ; goto done; } + out = open_new(&c, out_path); + if (out < 0 || write_all(&c, out, buf, (int) n)) { rc = E_FILE; goto done; } + rc = (int) n; +done: + if (out >= 0) c.close(out); + if (buf) c.free(buf); + c.close(fd); return rc; } JNIEXPORT jint JNICALL Java_hmgapi_engine_NativeFetch_fetch(JNIEnv *env, jclass cls, jstring ssl_lib, jstring c_lib, - jstring host, jstring port, jbyteArray request, jstring out_path, jint max_bytes) { + jstring host, jstring port, jbyteArray request, jstring out_path, jint max_bytes, jint timeout_ms) { (void) cls; - if (!ssl_lib || !c_lib || !host || !port || !request || !out_path || max_bytes <= 0) return E_ARGS; + if (!ssl_lib || !c_lib || !host || !port || !request || !out_path || max_bytes <= 0 || timeout_ms <= 0) return E_ARGS; const char *s = (*env)->GetStringUTFChars(env, ssl_lib, 0), *c = (*env)->GetStringUTFChars(env, c_lib, 0); const char *h = (*env)->GetStringUTFChars(env, host, 0), *p = (*env)->GetStringUTFChars(env, port, 0); const char *o = (*env)->GetStringUTFChars(env, out_path, 0); jsize len = (*env)->GetArrayLength(env, request); jbyte *req = (*env)->GetByteArrayElements(env, request, 0); - int rc = (s && c && h && p && o && req) ? fetch(s, c, h, p, (const char *) req, (int) len, o, (int) max_bytes) : E_ARGS; + int rc = (s && c && h && p && o && req) ? fetch(s, c, h, p, (const char *) req, (int) len, o, (int) max_bytes, (int) timeout_ms) : E_ARGS; if (req) (*env)->ReleaseByteArrayElements(env, request, req, JNI_ABORT); if (o) (*env)->ReleaseStringUTFChars(env, out_path, o); if (p) (*env)->ReleaseStringUTFChars(env, port, p); @@ -224,3 +337,20 @@ JNIEXPORT jint JNICALL Java_hmgapi_engine_NativeFetch_fetch(JNIEnv *env, jclass if (s) (*env)->ReleaseStringUTFChars(env, ssl_lib, s); return rc; } + +JNIEXPORT jint JNICALL Java_hmgapi_engine_NativeFetch_dns(JNIEnv *env, jclass cls, jstring c_lib, jstring server, + jstring port, jbyteArray query, jstring out_path, jint timeout_ms) { + (void) cls; + if (!c_lib || !server || !port || !query || !out_path || timeout_ms <= 0) return E_ARGS; + const char *c = (*env)->GetStringUTFChars(env, c_lib, 0), *sv = (*env)->GetStringUTFChars(env, server, 0); + const char *p = (*env)->GetStringUTFChars(env, port, 0), *o = (*env)->GetStringUTFChars(env, out_path, 0); + jsize len = (*env)->GetArrayLength(env, query); + jbyte *q = (*env)->GetByteArrayElements(env, query, 0); + int rc = (c && sv && p && o && q) ? dns(c, sv, p, (const char *) q, (int) len, o, (int) timeout_ms) : E_ARGS; + if (q) (*env)->ReleaseByteArrayElements(env, query, q, JNI_ABORT); + if (o) (*env)->ReleaseStringUTFChars(env, out_path, o); + if (p) (*env)->ReleaseStringUTFChars(env, port, p); + if (sv) (*env)->ReleaseStringUTFChars(env, server, sv); + if (c) (*env)->ReleaseStringUTFChars(env, c_lib, c); + return rc; +} diff --git a/core/runtime/fetch-test.sh b/core/runtime/fetch-test.sh index 9d1fc5d1..0356883f 100644 --- a/core/runtime/fetch-test.sh +++ b/core/runtime/fetch-test.sh @@ -1,9 +1,26 @@ #!/bin/sh -# Off-car test of the engine's HTTPS pieces (Http, NativeFetch.Web, Sha256, DnsLookup); the library -# itself (core/fetch/fetch.c) needs the unit's libssl, or a computer's: catalog-test.sh's notes. +# Off-car test of the engine's HTTPS pieces (Http, NativeFetch.Web, Sha256, DnsLookup), then the +# library itself (core/fetch/fetch.c) built for this computer (-DHOST: no SO_MARK or wlan0 here) +# against a local TLS server, when there's a C compiler, the JDK's jni.h and an OpenSSL 1.1+/3 +# libssl (HMGAPI_TEST_SSL, or Homebrew's or the system's); skipped otherwise. set -e cd "$(dirname "$0")/../.." CP=$(mktemp -d); trap 'rm -rf "$CP"' EXIT sh tools/engine-classes.sh "$CP" 2>/dev/null -javac --release 8 -nowarn -cp "$CP" -d "$CP" core/runtime/test/hmgapi/engine/FetchTest.java 2>/dev/null +javac --release 8 -nowarn -cp "$CP" -d "$CP" core/runtime/test/hmgapi/engine/FetchTest.java core/runtime/test/hmgapi/engine/FetchNativeTest.java 2>/dev/null java -cp "$CP" hmgapi.engine.FetchTest + +JH=$(java -XshowSettings:properties -version 2>&1 | sed -n 's/^ *java.home = //p') +SSL=${HMGAPI_TEST_SSL:-} +for s in /opt/homebrew/opt/openssl@3/lib/libssl.dylib /usr/local/opt/openssl@3/lib/libssl.dylib /usr/lib/x86_64-linux-gnu/libssl.so.3 /usr/lib/aarch64-linux-gnu/libssl.so.3 /usr/lib64/libssl.so.3; do + [ -n "$SSL" ] || { [ -f "$s" ] && SSL=$s; } +done +case $(uname) in Darwin) OS=darwin EXT=dylib ;; *) OS=linux EXT=so ;; esac +if ! command -v cc >/dev/null || [ ! -f "$JH/include/jni.h" ] || [ -z "$SSL" ] || ! command -v keytool >/dev/null; then + echo "skip the library on this computer: needs cc, the JDK's jni.h, keytool and an OpenSSL 1.1+/3 libssl (HMGAPI_TEST_SSL)" + exit 0 +fi +cc -DHOST -shared -fPIC -Wall -Werror -I"$JH/include" -I"$JH/include/$OS" -o "$CP/libhmgapi_fetch.$EXT" core/fetch/fetch.c +keytool -genkeypair -alias t -keyalg EC -groupname secp256r1 -dname CN=localhost -validity 2 -storetype PKCS12 \ + -keystore "$CP/ks.p12" -storepass fetchtest -keypass fetchtest >/dev/null 2>&1 +java -cp "$CP" hmgapi.engine.FetchNativeTest "$CP/libhmgapi_fetch.$EXT" "$SSL" "$CP/ks.p12" fetchtest diff --git a/core/runtime/java/hmgapi/engine/DnsLookup.java b/core/runtime/java/hmgapi/engine/DnsLookup.java index 59d40141..643f914a 100644 --- a/core/runtime/java/hmgapi/engine/DnsLookup.java +++ b/core/runtime/java/hmgapi/engine/DnsLookup.java @@ -1,55 +1,58 @@ package hmgapi.engine; import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; -import java.lang.reflect.Method; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.Random; /** - * A host's IPv4 addresses, asked of home Wi-Fi's own DNS server (dhcp.wlan0.dns1) over UDP, for the - * engine's downloads (NativeFetch). Not the system resolver: the engine runs as root outside netd's - * per-app setup, where lookups would go to the car's carrier DNS on mobile data. wifi.sh routes - * wlan0's DNS servers through wlan0, so this query goes out on home Wi-Fi or not at all. + * A host's IPv4 addresses, asked of home Wi-Fi's own DNS server, for the engine's downloads + * (NativeFetch). Not the system resolver: the engine runs as root outside netd's per-app setup, + * where lookups would go to the car's carrier DNS on mobile data. The server is the one in + * wifi.sh's lease (/data/hmgapi/wifi/lease, " "), which is there only while home + * Wi-Fi's route is up (dhcp.wlan0.dns1 can be left from an earlier join), and the query goes + * through an Asker: on the unit the fetch library's socket, marked for home Wi-Fi and bound to + * wlan0, so it goes out on home Wi-Fi or not at all. */ final class DnsLookup { private DnsLookup() {} static final int TRIES = 3, TIMEOUT_MS = 3000; + static final String LEASE = "/data/hmgapi/wifi/lease"; - /** the server: home Wi-Fi's DHCP DNS, or its gateway; null when home Wi-Fi gave neither */ - static String server(Engine e) { - for (String p : new String[] {"dhcp.wlan0.dns1", "dhcp.wlan0.gateway"}) { - String v = e.getprop(p); - if (v != null && v.matches("\\d{1,3}(\\.\\d{1,3}){3}")) return v; + /** one query's exchange: the answer's bytes, or an IOException */ + interface Asker { + byte[] ask(String server, byte[] query) throws IOException; + } + + /** the server: home Wi-Fi's DNS from wifi.sh's lease (its gateway when the lease has none); null while home Wi-Fi's route isn't up */ + static String server(String root) { + String[] f; + try { + f = Engine.read(new File(root + LEASE)).trim().split("\\s+"); + } catch (IOException x) { + return null; + } + for (int i = f.length - 1; i >= 0; i--) { + if (f[i].matches("\\d{1,3}(\\.\\d{1,3}){3}")) return f[i]; } return null; } /** host's A records (dotted), first answer first; empty if none */ - static List lookup(String server, String host) throws IOException { + static List lookup(String server, String host, Asker asker) throws IOException { Random rnd = new Random(); IOException last = null; for (int t = 0; t < TRIES; t++) { int id = rnd.nextInt(0x10000); byte[] q = query(id, host); - DatagramSocket s = new DatagramSocket(); try { - s.setSoTimeout(TIMEOUT_MS); - s.connect(InetAddress.getByAddress(dotted(server)), 53); - s.send(new DatagramPacket(q, q.length)); - byte[] r = new byte[1500]; - DatagramPacket p = new DatagramPacket(r, r.length); - s.receive(p); - return answers(r, p.getLength(), id); + byte[] r = asker.ask(server, q); + return answers(r, r.length, id); } catch (IOException e) { last = e; - } finally { - s.close(); } } throw last != null ? last : new IOException("no answer"); @@ -104,11 +107,4 @@ private static int skipName(byte[] r, int n, int off) throws IOException { private static int u16(byte[] r, int off) { return ((r[off] & 0xff) << 8) | (r[off + 1] & 0xff); } - - private static byte[] dotted(String a) { - String[] p = a.split("\\."); - byte[] b = new byte[4]; - for (int i = 0; i < 4; i++) b[i] = (byte) Integer.parseInt(p[i]); - return b; - } } diff --git a/core/runtime/java/hmgapi/engine/Http.java b/core/runtime/java/hmgapi/engine/Http.java index 9ccd7108..7b446492 100644 --- a/core/runtime/java/hmgapi/engine/Http.java +++ b/core/runtime/java/hmgapi/engine/Http.java @@ -23,10 +23,17 @@ */ final class Http { interface Transport { - /** sends request to host:443 over TLS and writes the whole raw answer to rawOut; bytes written, or a negative error */ + /** + * sends request to host:443 over TLS and writes the raw answer to rawOut (a new file: it must not + * exist yet). Bytes written when the server ended the answer itself (a TLS close); CUT when the + * connection ended any other way (dropped, a read error, a timeout), what came in rawOut; any + * other negative: an error, nothing to read + */ int exchange(String host, byte[] request, File rawOut, int maxBytes); } + static final int CUT = NativeFetch.CUT; + static final Set HOSTS = new HashSet(Arrays.asList("github.com", "api.github.com", "raw.githubusercontent.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com", "codeload.github.com")); static final int MAX_REDIRECTS = 5; @@ -53,11 +60,11 @@ public String toString() { } private final Transport transport; - private final File tmp; + private final File tmpDir; Http(Transport transport, File tmpDir) { this.transport = transport; - this.tmp = new File(tmpDir, "answer.raw"); + this.tmpDir = tmpDir; } /** GET url into out (replaced only on a 200); maxBytes: the body's cap */ @@ -72,14 +79,16 @@ Result get(String url, File out, int maxBytes) throws IOException { byte[] request = ("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\nUser-Agent: HMG-API/" + Engine.HMGAPI_VERSION + "\r\n" + ("api.github.com".equals(host) ? "Accept: application/vnd.github+json\r\nX-GitHub-Api-Version: 2022-11-28\r\n" : "Accept: */*\r\n") + "Accept-Encoding: identity\r\nConnection: close\r\n\r\n").getBytes("US-ASCII"); + File tmp = NativeFetch.fresh(tmpDir, "answer"); // one per call: gets may run at once int n = transport.exchange(host, request, tmp, maxBytes + OVERHEAD); try { - if (n < 0) return new Result(0, host + ": " + NativeFetch.why(n)); + if (n < 0 && n != CUT) return new Result(0, host + ": " + NativeFetch.why(n)); + boolean cut = n == CUT; InputStream in = new BufferedInputStream(new FileInputStream(tmp)); try { String statusLine = line(in); - String[] sp = statusLine.split(" "); - if (sp.length < 2 || !sp[0].startsWith("HTTP/1.")) return new Result(0, "not an HTTP answer"); + String[] sp = statusLine == null ? new String[0] : statusLine.split(" "); + if (sp.length < 2 || !sp[0].startsWith("HTTP/1.")) return new Result(0, cut ? host + ": " + NativeFetch.why(CUT) : "not an HTTP answer"); int status; try { status = Integer.parseInt(sp[1]); @@ -87,7 +96,9 @@ Result get(String url, File out, int maxBytes) throws IOException { return new Result(0, "not an HTTP answer"); } Map headers = new HashMap(); - for (String l = line(in); !l.isEmpty(); l = line(in)) { + for (String l = line(in); ; l = line(in)) { + if (l == null) return new Result(0, host + ": " + NativeFetch.why(CUT) + " (in its headers)"); + if (l.isEmpty()) break; int c = l.indexOf(':'); if (c > 0) headers.put(l.substring(0, c).trim().toLowerCase(Locale.US), l.substring(c + 1).trim()); } @@ -98,24 +109,7 @@ Result get(String url, File out, int maxBytes) throws IOException { continue; } if (status != 200) return new Result(status, null); - File part = new File(out.getPath() + ".part"); - OutputStream o = new FileOutputStream(part); - long got; - try { - got = "chunked".equalsIgnoreCase(headers.get("transfer-encoding")) ? chunked(in, o, maxBytes) : copy(in, o, maxBytes); - } finally { - o.close(); - } - String len = headers.get("content-length"); - if (got < 0 || (len != null && !len.equals(String.valueOf(got)))) { - part.delete(); - return new Result(status, got < 0 ? "larger than " + maxBytes + " bytes" : "cut off: " + got + " of " + len + " bytes"); - } - if (!part.renameTo(out)) { - part.delete(); - return new Result(status, "can't write " + out); - } - return new Result(200, null); + return body(in, headers, cut, out, maxBytes); } finally { in.close(); } @@ -126,9 +120,50 @@ Result get(String url, File out, int maxBytes) throws IOException { return new Result(0, "too many redirects"); } + /** + * a 200's body into out, only if it is whole: its Content-Length met, or its last chunk read, or + * (with neither) the server ended the answer itself. A connection that ended any other way (cut) + * with no length to check is not a whole answer. Nothing is left behind when it isn't. + */ + private static Result body(InputStream in, Map headers, boolean cut, File out, int maxBytes) throws IOException { + boolean chunked = "chunked".equalsIgnoreCase(headers.get("transfer-encoding")); + String len = chunked ? null : headers.get("content-length"); + long want = -1; + if (len != null) { + if (!len.matches("\\d{1,12}")) return new Result(200, "bad Content-Length: " + len); + want = Long.parseLong(len); + if (want > maxBytes) return new Result(200, "larger than " + maxBytes + " bytes"); + } + File part = new File(out.getPath() + ".part"); + part.delete(); + boolean done = false; + try { + long got; + OutputStream o = new FileOutputStream(part); + try { + got = chunked ? chunked(in, o, maxBytes) : copy(in, o, maxBytes); + } finally { + o.close(); + } + if (got == -1) return new Result(200, "larger than " + maxBytes + " bytes"); + if (want >= 0 && got != want) return new Result(200, "cut off: " + got + " of " + want + " bytes"); + if (want < 0 && !chunked && cut) return new Result(200, "cut off: the connection ended after " + got + " bytes, with no length to check"); + if (!part.renameTo(out)) return new Result(200, "can't write " + out); + done = true; + return new Result(200, null); + } catch (IOException x) { + return new Result(200, "cut off: " + x.getMessage()); + } finally { + if (!done) part.delete(); + } + } + + /** a line without its CRLF; null at the end of the answer with no line break (a cut-off line) */ private static String line(InputStream in) throws IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); - for (int c = in.read(); c >= 0 && c != '\n'; c = in.read()) { + for (int c = in.read(); ; c = in.read()) { + if (c < 0) return null; + if (c == '\n') break; if (c != '\r') b.write(c); if (b.size() > 8192) throw new IOException("header line too long"); } @@ -147,28 +182,44 @@ private static long copy(InputStream in, OutputStream out, int max) throws IOExc return total; } + /** a chunk's size: hex digits only (no sign, no 0x), at most 7 of them; anything else is an IOException */ + static int chunkSize(String l) throws IOException { + if (l == null) throw new IOException("the chunks ended early"); + int semi = l.indexOf(';'); + String h = (semi < 0 ? l : l.substring(0, semi)).trim(); + if (h.isEmpty() || h.length() > 7) throw new IOException("bad chunk size"); + int size = 0; + for (int i = 0; i < h.length(); i++) { + char ch = h.charAt(i); + int d = ch >= '0' && ch <= '9' ? ch - '0' : ch >= 'a' && ch <= 'f' ? ch - 'a' + 10 : ch >= 'A' && ch <= 'F' ? ch - 'A' + 10 : -1; + if (d < 0) throw new IOException("bad chunk size"); + size = size * 16 + d; + } + return size; + } + + /** body bytes, -1 past the cap; an IOException unless every chunk and the last (0) one are there */ private static long chunked(InputStream in, OutputStream out, int max) throws IOException { long total = 0; byte[] buf = new byte[8192]; for (;;) { - String l = line(in); - int semi = l.indexOf(';'); - int size; - try { - size = Integer.parseInt((semi < 0 ? l : l.substring(0, semi)).trim(), 16); - } catch (NumberFormatException e) { - throw new IOException("bad chunk size"); + int size = chunkSize(line(in)); + if (size == 0) { + for (String t = line(in); t == null || !t.isEmpty(); t = line(in)) { // trailers, then the blank line + if (t == null) throw new IOException("the chunks ended early"); + } + return total; } - if (size == 0) return total; + if (size > max - total) return -1; total += size; - if (total > max) return -1; for (int left = size; left > 0; ) { int n = in.read(buf, 0, Math.min(left, buf.length)); if (n <= 0) throw new IOException("chunk cut off"); out.write(buf, 0, n); left -= n; } - line(in); // the CRLF after the chunk + String crlf = line(in); + if (crlf == null || !crlf.isEmpty()) throw new IOException("bad chunk end"); } } } diff --git a/core/runtime/java/hmgapi/engine/NativeFetch.java b/core/runtime/java/hmgapi/engine/NativeFetch.java index 4c6047fc..4320613e 100644 --- a/core/runtime/java/hmgapi/engine/NativeFetch.java +++ b/core/runtime/java/hmgapi/engine/NativeFetch.java @@ -46,21 +46,59 @@ static Http.Transport forEngine(Engine e, List why) { } } - static native int fetch(String sslLib, String cLib, String host, String port, byte[] request, String outPath, int maxBytes); + /** each socket's send and receive timeout (connect, the handshake, every read and write) */ + static final int TIMEOUT_MS = 20000; + static final int CUT = -13; + + /** host is "name@address"; outPath must not exist yet. Bytes written for an answer the server closed cleanly, CUT, or an error */ + static native int fetch(String sslLib, String cLib, String host, String port, byte[] request, String outPath, int maxBytes, int timeoutMs); + + /** one UDP query to server:port on a socket held to home Wi-Fi, its answer to outPath (must not exist yet): its length, or an error */ + static native int dns(String cLib, String server, String port, byte[] query, String outPath, int timeoutMs); + + private static final java.util.concurrent.atomic.AtomicInteger SEQ = new java.util.concurrent.atomic.AtomicInteger(); + private static final java.util.Random RND = new java.util.Random(); + + /** + * a name in dir for one call's file (several calls, threads or engines may run at once): not there + * yet, and the library opens it O_EXCL and O_NOFOLLOW, so a name that is taken is an error, never + * someone else's file written over + */ + static File fresh(File dir, String what) { + int r; + synchronized (RND) { + r = RND.nextInt() & 0x7fffffff; + } + return new File(dir, what + "." + SEQ.incrementAndGet() + "." + Integer.toHexString(r) + "." + Long.toHexString(System.nanoTime())); + } @Override public int exchange(String host, byte[] request, File rawOut, int maxBytes) { - String dns = DnsLookup.server(e); - if (dns == null) return -3; + // home Wi-Fi's DNS server while its route is up (wifi.sh's lease), asked on a marked, bound socket + String server = DnsLookup.server(e.root); + if (server == null) return -15; + final File dir = rawOut.getParentFile(); String target; try { - List a = DnsLookup.lookup(dns, host); + List a = DnsLookup.lookup(server, host, new DnsLookup.Asker() { + @Override + public byte[] ask(String srv, byte[] query) throws IOException { + File f = fresh(dir, "dns"); + try { + int n = dns(cLib, srv, "53", query, f.getPath(), DnsLookup.TIMEOUT_MS); + if (n < 0) throw new IOException(why(n)); + return Engine.readAll(new java.io.FileInputStream(f)); + } finally { + f.delete(); + } + } + }); if (a.isEmpty()) return -3; target = host + "@" + a.get(0); } catch (IOException x) { return -3; } - return fetch(sslLib, cLib, target, "443", request, rawOut.getPath(), maxBytes); + return fetch(sslLib, cLib, target, "443", request, rawOut.getPath(), maxBytes, TIMEOUT_MS); } static String why(int code) { @@ -75,14 +113,22 @@ static String why(int code) { case -8: return "the file couldn't be written"; case -9: return "the answer is larger than allowed"; case -10: return "no answer"; + case -12: return "the connection can't be held to home Wi-Fi (its mark or wlan0 refused)"; + case CUT: return "the answer was cut off (the connection ended before it was whole)"; + case -14: return "the connection couldn't be set up (its timeouts)"; + case -15: return "home Wi-Fi isn't up (no lease)"; default: return "error " + code; } } /** - * Off-car tests: // (a query's '?' as '_'), 200 with its bytes; .redirect holds a - * Location for a 302; .status a status to answer with instead; anything else 404. Each request's - * host and path is appended to /requests.log. + * Off-car tests: // (a query's '?' as '_'), 200 with its bytes and a Content-Length; + * beside the file, .redirect holds a Location for a 302; .status a status to answer + * with instead; .chunked serves it chunked (7-byte chunks); .nolength with no length; + * .raw is the whole answer as it is (headers too, for broken framing); .cut holds N: only + * the first N bytes of the answer come, then the connection drops (CUT). Anything else 404. As the + * library: rawOut must be new, and past maxBytes it stops with what fit (-9). Each request's host and + * path is appended to /requests.log. */ static final class Web implements Http.Transport { private final File dir; @@ -94,32 +140,54 @@ static final class Web implements Http.Transport { @Override public int exchange(String host, byte[] request, File rawOut, int maxBytes) { try { + if (rawOut.exists()) return -8; // the library's O_EXCL String req = new String(request, "US-ASCII"); String path = req.substring(4, req.indexOf(' ', 4)); File log = new File(dir, "requests.log"); - Engine.write(log, (log.isFile() ? Engine.read(log) : "") + host + path + "\n"); + synchronized (Web.class) { // the tests' log, read and written whole: one call at a time + Engine.write(log, (log.isFile() ? Engine.read(log) : "") + host + path + "\n"); + } if (new File(dir, host + ".down").exists()) return -4; File f = new File(dir, host + path.replace('?', '_')); - String head; - byte[] body = new byte[0]; - if (new File(f.getPath() + ".redirect").isFile()) { - head = "HTTP/1.1 302 Found\r\nLocation: " + Engine.read(new File(f.getPath() + ".redirect")).trim() + "\r\nContent-Length: 0\r\n"; - } else if (new File(f.getPath() + ".status").isFile()) { - head = "HTTP/1.1 " + Engine.read(new File(f.getPath() + ".status")).trim() + " X\r\nContent-Length: 0\r\n"; + String p = f.getPath(); + java.io.ByteArrayOutputStream a = new java.io.ByteArrayOutputStream(); + if (new File(p + ".redirect").isFile()) { + a.write(("HTTP/1.1 302 Found\r\nLocation: " + Engine.read(new File(p + ".redirect")).trim() + "\r\nContent-Length: 0\r\n\r\n").getBytes("US-ASCII")); + } else if (new File(p + ".status").isFile()) { + a.write(("HTTP/1.1 " + Engine.read(new File(p + ".status")).trim() + " X\r\nContent-Length: 0\r\n\r\n").getBytes("US-ASCII")); + } else if (new File(p + ".raw").isFile()) { + a.write(Engine.readAll(new java.io.FileInputStream(p + ".raw"))); } else if (f.isFile()) { - body = Engine.readAll(new java.io.FileInputStream(f)); - head = "HTTP/1.1 200 OK\r\nContent-Length: " + body.length + "\r\n"; + byte[] body = Engine.readAll(new java.io.FileInputStream(f)); + if (new File(p + ".chunked").isFile()) { + a.write("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n".getBytes("US-ASCII")); + for (int i = 0; i < body.length; i += 7) { + int n = Math.min(7, body.length - i); + a.write((Integer.toHexString(n) + "\r\n").getBytes("US-ASCII")); + a.write(body, i, n); + a.write("\r\n".getBytes("US-ASCII")); + } + a.write("0\r\n\r\n".getBytes("US-ASCII")); + } else { + boolean noLength = new File(p + ".nolength").isFile(); + a.write(("HTTP/1.1 200 OK\r\n" + (noLength ? "" : "Content-Length: " + body.length + "\r\n") + "\r\n").getBytes("US-ASCII")); + a.write(body); + } } else { - head = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n"; + a.write("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".getBytes("US-ASCII")); } + byte[] answer = a.toByteArray(); + int n = answer.length; + boolean cut = new File(p + ".cut").isFile(); + if (cut) n = Math.min(n, Integer.parseInt(Engine.read(new File(p + ".cut")).trim())); + boolean big = n > maxBytes; OutputStream o = new FileOutputStream(rawOut); try { - o.write((head + "\r\n").getBytes("US-ASCII")); - o.write(body); + o.write(answer, 0, Math.min(n, maxBytes)); } finally { o.close(); } - return (int) rawOut.length(); + return big ? -9 : n == 0 ? -10 : cut ? CUT : n; } catch (Exception x) { return -10; } diff --git a/core/runtime/test/hmgapi/engine/FetchNativeTest.java b/core/runtime/test/hmgapi/engine/FetchNativeTest.java new file mode 100644 index 00000000..f2d1e3e2 --- /dev/null +++ b/core/runtime/test/hmgapi/engine/FetchNativeTest.java @@ -0,0 +1,179 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.file.Files; +import java.security.KeyStore; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; + +/** + * libhmgapi_fetch built for this computer (-DHOST: no mark or wlan0 here) against a local TLS + * server: how an answer ends (a TLS close, a dropped connection, a server that goes quiet), the + * cap, the answer file (O_EXCL, O_NOFOLLOW), and the DNS query's UDP exchange. + * FetchNativeTest + */ +public final class FetchNativeTest { + static int failed; + + static void check(String what, boolean ok) { + System.out.println((ok ? "ok " : "FAIL ") + what); + if (!ok) failed++; + } + + interface Mode { + void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception; + } + + static SSLContext ctx; + + /** one TLS connection on a local port, served by mode; the port */ + static int server(final Mode mode) throws Exception { + final ServerSocket ss = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); + Thread t = new Thread() { + @Override + public void run() { + try { + Socket raw = ss.accept(); + SSLSocket s = (SSLSocket) ctx.getSocketFactory().createSocket(raw, (InputStream) null, false); + s.setUseClientMode(false); + s.startHandshake(); + InputStream in = s.getInputStream(); + int st = 0; + while (st < 4) { // the request, to its blank line + int c = in.read(); + if (c < 0) break; + st = (c == '\r' || c == '\n') ? st + 1 : 0; + } + mode.serve(raw, s, s.getOutputStream()); + } catch (Exception x) { + // the client went away: that's some tests' point + } finally { + try { ss.close(); } catch (Exception x) { } + } + } + }; + t.setDaemon(true); + t.start(); + return ss.getLocalPort(); + } + + /** the server's end of an answer: its TLS close (close_notify), then, a moment later, the TCP close */ + static void closeTls(SSLSocket s, Socket raw) throws Exception { + s.shutdownOutput(); + Thread.sleep(300); + raw.close(); + } + + static String lib, ssl; + + static int fetch(int port, File out, int max, int timeoutMs) { + byte[] req = "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".getBytes(); + return NativeFetch.fetch(ssl, "libc", "localhost@127.0.0.1", String.valueOf(port), req, out.getPath(), max, timeoutMs); + } + + public static void main(String[] args) throws Exception { + System.load(new File(args[0]).getAbsolutePath()); + ssl = args[1]; + KeyStore ks = KeyStore.getInstance("PKCS12"); + ks.load(new FileInputStream(args[2]), args[3].toCharArray()); + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, args[3].toCharArray()); + ctx = SSLContext.getInstance("TLS"); + ctx.init(kmf.getKeyManagers(), null, null); + File d = Files.createTempDirectory("fetchnative").toFile(); + final byte[] whole = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".getBytes(); + + File out = new File(d, "a1"); + int n = fetch(server(new Mode() { + public void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception { o.write(whole); o.flush(); closeTls(s, raw); } + }), out, 1000, 5000); + check("the server's TLS close: a whole answer, its length (" + n + ")", n == whole.length && new String(Files.readAllBytes(out.toPath())).endsWith("hello")); + + out = new File(d, "a2"); + n = fetch(server(new Mode() { + public void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception { o.write(whole, 0, 30); o.flush(); Thread.sleep(200); raw.close(); } + }), out, 1000, 5000); + check("the connection dropped with no TLS close: CUT, what came kept (" + n + ")", n == NativeFetch.CUT && out.length() == 30); + + out = new File(d, "a3"); + long t0 = System.nanoTime(); + n = fetch(server(new Mode() { + public void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception { Thread.sleep(8000); } + }), out, 1000, 1500); + long ms = (System.nanoTime() - t0) / 1000000; + check("a server that goes quiet: the read times out (" + n + ", " + ms + " ms)", n == -10 && ms < 6000); + + out = new File(d, "a4"); + t0 = System.nanoTime(); + n = fetch(server(new Mode() { + public void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception { o.write(whole, 0, 20); o.flush(); Thread.sleep(8000); } + }), out, 1000, 1500); + ms = (System.nanoTime() - t0) / 1000000; + check("quiet mid-answer: times out, CUT (" + n + ", " + ms + " ms)", n == NativeFetch.CUT && ms < 6000 && out.length() == 20); + + out = new File(d, "a5"); + final byte[] big = new byte[50000]; + n = fetch(server(new Mode() { + public void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception { o.write(big); o.flush(); closeTls(s, raw); } + }), out, 1000, 5000); + check("past the cap: -9 (" + n + ")", n == -9 && out.length() <= 1000); + + out = new File(d, "a6"); + Files.write(out.toPath(), "mine".getBytes()); + n = fetch(server(new Mode() { + public void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception { o.write(whole); o.flush(); closeTls(s, raw); } + }), out, 1000, 5000); + check("an answer file that's there: not written over (O_EXCL, " + n + ")", n == -8 && "mine".equals(new String(Files.readAllBytes(out.toPath())))); + + File target = new File(d, "target"), link = new File(d, "link"); + Files.createSymbolicLink(link.toPath(), target.toPath()); + n = fetch(server(new Mode() { + public void serve(Socket raw, SSLSocket s, OutputStream o) throws Exception { o.write(whole); o.flush(); closeTls(s, raw); } + }), link, 1000, 5000); + check("an answer file that's a link: not followed (" + n + ")", n == -8 && !target.exists()); + + n = NativeFetch.fetch(ssl, "libc", "localhost", "443", whole, new File(d, "a7").getPath(), 1000, 5000); + check("no address (the system resolver is never used): refused (" + n + ")", n == -11); + + // DNS: one UDP exchange + final DatagramSocket us = new DatagramSocket(0, InetAddress.getByName("127.0.0.1")); + Thread t = new Thread() { + @Override + public void run() { + try { + byte[] b = new byte[1500]; + DatagramPacket p = new DatagramPacket(b, b.length); + us.receive(p); + byte[] r = new byte[p.getLength() + 1]; + System.arraycopy(b, 0, r, 0, p.getLength()); + r[p.getLength()] = 42; + us.send(new DatagramPacket(r, r.length, p.getSocketAddress())); + } catch (Exception x) { } + } + }; + t.setDaemon(true); + t.start(); + out = new File(d, "dns1"); + n = NativeFetch.dns("libc", "127.0.0.1", String.valueOf(us.getLocalPort()), "query".getBytes(), out.getPath(), 2000); + check("DNS: the answer written (" + n + ")", n == 6 && "query*".equals(new String(Files.readAllBytes(out.toPath())))); + us.close(); + final DatagramSocket quiet = new DatagramSocket(0, InetAddress.getByName("127.0.0.1")); + t0 = System.nanoTime(); + n = NativeFetch.dns("libc", "127.0.0.1", String.valueOf(quiet.getLocalPort()), "query".getBytes(), new File(d, "dns2").getPath(), 1000); + ms = (System.nanoTime() - t0) / 1000000; + check("DNS: no answer times out (" + n + ", " + ms + " ms)", n == -10 && ms < 5000 && !new File(d, "dns2").exists()); + quiet.close(); + n = NativeFetch.dns("libc", "dns.example", "53", "q".getBytes(), new File(d, "dns3").getPath(), 1000); + check("DNS: a server that isn't an address refused (" + n + ")", n == -3); + System.exit(failed == 0 ? 0 : 1); + } +} diff --git a/core/runtime/test/hmgapi/engine/FetchTest.java b/core/runtime/test/hmgapi/engine/FetchTest.java index 9d0d5ae5..8e431b7a 100644 --- a/core/runtime/test/hmgapi/engine/FetchTest.java +++ b/core/runtime/test/hmgapi/engine/FetchTest.java @@ -44,6 +44,123 @@ public static void main(String[] args) throws Exception { r = http.get("https://raw.githubusercontent.com/big", big, 100); check("over the cap: refused, nothing left (" + r + ")", !r.ok() && !big.exists() && !new File(d, "big.part").exists()); check("404: reported", http.get("https://raw.githubusercontent.com/none", out, 100).status == 404); + String body500 = new String(new char[500]).replace('\0', 'y'); + + // the transport's own cap (the body's plus headers): past it, what fit and -9, nothing kept + put(web, "raw.githubusercontent.com/huge", new String(new char[70000]).replace('\0', 'z')); + File huge = new File(d, "huge"); + r = http.get("https://raw.githubusercontent.com/huge", huge, 100); + check("past the transport's cap: refused (" + r + ")", !r.ok() && r.toString().contains("larger than allowed") && !huge.exists()); + + // chunked + put(web, "raw.githubusercontent.com/ch.txt", "hello, chunked car, in pieces"); + put(web, "raw.githubusercontent.com/ch.txt.chunked", ""); + check("chunked: joined", http.get("https://raw.githubusercontent.com/ch.txt", out, 100).ok() && "hello, chunked car, in pieces".equals(Engine.read(out))); + put(web, "raw.githubusercontent.com/chbig", body500); + put(web, "raw.githubusercontent.com/chbig.chunked", ""); + File chbig = new File(d, "chbig"); + r = http.get("https://raw.githubusercontent.com/chbig", chbig, 100); + check("chunked over the cap: refused, nothing left (" + r + ")", !r.ok() && r.toString().contains("larger than 100") && !chbig.exists() && !new File(d, "chbig.part").exists()); + String head = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"; + // a negative size took the running total down, so the next chunk passed the cap (wrote past it) + put(web, "raw.githubusercontent.com/neg.raw", head + "a\r\n0123456789\r\n-a\r\n\r\n64\r\n" + body500.substring(0, 100) + "\r\n0\r\n\r\n"); + File neg = new File(d, "neg"); + r = http.get("https://raw.githubusercontent.com/neg", neg, 20); + check("chunked: a negative size refused, nothing left (" + r + ")", !r.ok() && r.toString().contains("bad chunk size") && !neg.exists() && !new File(d, "neg.part").exists()); + for (String bad : new String[] {"zz", "0x5", "+5", "", "10000000", " "}) { + put(web, "raw.githubusercontent.com/bad.raw", head + "5\r\nhello\r\n" + bad + "\r\nxx\r\n0\r\n\r\n"); + File b = new File(d, "bad"); + r = http.get("https://raw.githubusercontent.com/bad", b, 100); + check("chunked: size [" + bad + "] refused, no .part left (" + r + ")", !r.ok() && !b.exists() && !new File(d, "bad.part").exists()); + } + put(web, "raw.githubusercontent.com/noend.raw", head + "5\r\nhello\r\n"); + r = http.get("https://raw.githubusercontent.com/noend", new File(d, "noend"), 100); + check("chunked: no last chunk refused (" + r + ")", !r.ok() && !new File(d, "noend").exists() && !new File(d, "noend.part").exists()); + put(web, "raw.githubusercontent.com/glued.raw", head + "5\r\nhelloXX0\r\n\r\n"); + r = http.get("https://raw.githubusercontent.com/glued", new File(d, "glued"), 100); + check("chunked: a chunk not ended by CRLF refused (" + r + ")", !r.ok() && !new File(d, "glued.part").exists()); + put(web, "raw.githubusercontent.com/trail.raw", head + "5;x=y\r\nhello\r\n0\r\nX-Trailer: 1\r\n\r\n"); + check("chunked: an extension and a trailer read", http.get("https://raw.githubusercontent.com/trail", out, 100).ok() && "hello".equals(Engine.read(out))); + + // how the answer ended (the library: a TLS close, or CUT) + put(web, "raw.githubusercontent.com/nl.txt", "no length, closed by the server"); + put(web, "raw.githubusercontent.com/nl.txt.nolength", ""); + check("no length, the server's close: whole", http.get("https://raw.githubusercontent.com/nl.txt", out, 100).ok() && "no length, closed by the server".equals(Engine.read(out))); + put(web, "raw.githubusercontent.com/nl.txt.cut", "45"); + Files.write(out.toPath(), "before".getBytes("US-ASCII")); + r = http.get("https://raw.githubusercontent.com/nl.txt", out, 100); + check("no length, the connection dropped: cut off, not ok (" + r + ")", !r.ok() && r.toString().contains("cut off") && "before".equals(Engine.read(out))); + put(web, "raw.githubusercontent.com/cl.txt", "0123456789"); + put(web, "raw.githubusercontent.com/cl.txt.cut", "1000"); + check("its Content-Length met, then dropped (no TLS close): whole", http.get("https://raw.githubusercontent.com/cl.txt", out, 100).ok() && "0123456789".equals(Engine.read(out))); + put(web, "raw.githubusercontent.com/cl.txt.cut", "42"); + r = http.get("https://raw.githubusercontent.com/cl.txt", out, 100); + check("its Content-Length short, dropped: cut off (" + r + ")", !r.ok() && r.toString().contains("cut off")); + put(web, "raw.githubusercontent.com/ch.txt.cut", "1000"); + check("chunked to its last chunk, then dropped: whole", http.get("https://raw.githubusercontent.com/ch.txt", out, 100).ok()); + put(web, "raw.githubusercontent.com/ch.txt.cut", "60"); + r = http.get("https://raw.githubusercontent.com/ch.txt", out, 100); + check("chunked, dropped before its last chunk: cut off (" + r + ")", !r.ok() && r.toString().contains("cut off")); + put(web, "raw.githubusercontent.com/a.txt.cut", "20"); + r = http.get("https://raw.githubusercontent.com/a.txt", out, 100); + check("dropped in the headers: cut off (" + r + ")", !r.ok() && r.toString().contains("cut off")); + new File(web, "raw.githubusercontent.com/a.txt.cut").delete(); + put(web, "raw.githubusercontent.com/badlen.raw", "HTTP/1.1 200 OK\r\nContent-Length: -5\r\n\r\nhello"); + r = http.get("https://raw.githubusercontent.com/badlen", new File(d, "badlen"), 100); + check("a Content-Length that isn't a number refused (" + r + ")", !r.ok() && r.toString().contains("bad Content-Length")); + put(web, "raw.githubusercontent.com/biglen.raw", "HTTP/1.1 200 OK\r\nContent-Length: 5000\r\n\r\nhello"); + r = http.get("https://raw.githubusercontent.com/biglen", new File(d, "biglen"), 100); + check("a Content-Length over the cap refused at once (" + r + ")", !r.ok() && r.toString().contains("larger than 100")); + + // redirects + put(web, "github.com/rel.redirect", "/a.txt"); + put(web, "github.com/a.txt", "on github"); + check("a redirect to a path on the same host", http.get("https://github.com/rel", out, 100).ok() && "on github".equals(Engine.read(out))); + put(web, "github.com/loop.redirect", "https://github.com/loop"); + r = http.get("https://github.com/loop", out, 100); + check("a redirect loop: stops (" + r + ")", !r.ok() && r.toString().contains("too many redirects")); + put(web, "github.com/plain.redirect", "http://github.com/a.txt"); + r = http.get("https://github.com/plain", out, 100); + check("a redirect to plain http refused (" + r + ")", !r.ok() && r.toString().contains("not https")); + put(web, "github.com/r307.raw", "HTTP/1.1 307 Temporary Redirect\r\nLocation: https://raw.githubusercontent.com/a.txt\r\n\r\n"); + check("a 307 followed", http.get("https://github.com/r307", out, 100).ok() && "hello, car".equals(Engine.read(out))); + put(web, "github.com/noloc.raw", "HTTP/1.1 302 Found\r\nContent-Length: 0\r\n\r\n"); + check("a redirect without a location refused", !http.get("https://github.com/noloc", out, 100).ok()); + + // one answer file per call, none left; a name that's taken is the library's O_EXCL error + check("nothing left in the download folder", tmp.list().length == 0); + File f1 = NativeFetch.fresh(tmp, "answer"), f2 = NativeFetch.fresh(tmp, "answer"); + check("each call's answer file its own name", !f1.equals(f2) && !f1.exists()); + Files.write(f1.toPath(), "x".getBytes("US-ASCII")); + check("an answer file that's there already: not written over (O_EXCL)", new NativeFetch.Web(web).exchange("raw.githubusercontent.com", "GET /a.txt HTTP/1.1\r\n".getBytes("US-ASCII"), f1, 1000) == -8 && "x".equals(Engine.read(f1))); + f1.delete(); + final Http shared = http; + final File base = d; + final boolean[] fine = {true}; + Thread[] ts = new Thread[8]; + for (int i = 0; i < ts.length; i++) { + final int k = i; + put(web, "raw.githubusercontent.com/t" + k, "thread " + k + " " + body500.substring(0, 50 * k)); + ts[i] = new Thread() { + @Override + public void run() { + try { + for (int j = 0; j < 20; j++) { + File o = new File(base, "t" + k); + boolean ok = shared.get("https://raw.githubusercontent.com/t" + k, o, 1000).ok() + && Engine.read(o).equals("thread " + k + " " + body500.substring(0, 50 * k)); + synchronized (fine) { fine[0] &= ok; } + } + } catch (Exception x) { + synchronized (fine) { fine[0] = false; } + } + } + }; + ts[i].start(); + } + for (Thread t : ts) t.join(); + check("eight gets at once on one Http: each its own answer", fine[0] && tmp.list().length == 0); + new File(web, "raw.githubusercontent.com.down").createNewFile(); r = http.get("https://raw.githubusercontent.com/a.txt", out, 100); check("no connection: said (" + r + ")", !r.ok() && r.toString().contains("no connection")); @@ -82,6 +199,38 @@ public static void main(String[] args) throws Exception { check("DNS: a cut-off answer refused", refused); dr[3] = (byte) 0x83; check("DNS: no such name: none", DnsLookup.answers(dr, dr.length, 0x1234).isEmpty()); + + // the server: wifi.sh's lease (there only while home Wi-Fi's route is up), never a leftover dhcp prop + File root = new File(d, "root"); + check("DNS server: no lease, none (home Wi-Fi isn't up)", DnsLookup.server(root.getPath()) == null); + put(root, "data/hmgapi/wifi/lease", "10.4.0.1 10.10.10.100\n"); + check("DNS server: the lease's", "10.10.10.100".equals(DnsLookup.server(root.getPath()))); + put(root, "data/hmgapi/wifi/lease", "garbage"); + check("DNS server: a lease that isn't one, none", DnsLookup.server(root.getPath()) == null); + // lookup asks through the Asker (the library's marked, bound socket): tries again, then gives up + final int[] asked = {0}; + java.util.List got = DnsLookup.lookup("10.10.10.100", "raw.githubusercontent.com", new DnsLookup.Asker() { + @Override + public byte[] ask(String server, byte[] query) throws java.io.IOException { + if (asked[0]++ == 0) throw new java.io.IOException("timed out"); + java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream(); + b.write(query, 0, query.length); + byte[] r2 = b.toByteArray(); + r2[2] = (byte) 0x81; r2[3] = (byte) 0x80; r2[7] = 1; + b.reset(); b.write(r2, 0, r2.length); + for (int x : new int[] {0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 185, 199, 110, 133}) b.write(x); + return b.toByteArray(); + } + }); + check("DNS: asked again after a failure, then the answer", asked[0] == 2 && "[185.199.110.133]".equals(got.toString())); + refused = false; + try { + DnsLookup.lookup("10.10.10.100", "github.com", new DnsLookup.Asker() { + @Override + public byte[] ask(String server, byte[] query) throws java.io.IOException { throw new java.io.IOException("no route"); } + }); + } catch (java.io.IOException x) { refused = true; } + check("DNS: no answer in " + DnsLookup.TRIES + " tries: an error", refused); System.exit(failed == 0 ? 0 : 1); } } diff --git a/install/common/install-test.sh b/install/common/install-test.sh index dd8aa7da..9f3b819f 100644 --- a/install/common/install-test.sh +++ b/install/common/install-test.sh @@ -62,7 +62,7 @@ rm -rf $P/nemesis; mkdir -p $P/nemesis/mod $P/nemesis/bin cp -r install/nemesis/scripts $P/nemesis/scripts; cp -r install/nemesis/mod/scripts $P/nemesis/mod/scripts cp install/nemesis/bin/open.sh install/nemesis/bin/start.sh $P/nemesis/bin/; cp install/nemesis/conflicts.txt $P/nemesis/ [ -f "$STOCK" ] || echo "$(md5sum < $R/system/bin/app_process | cut -c1-32) test stock" > $P/stock.txt -(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) +(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) # refusals first: nothing may change cp $R/system/bin/app_process $T/real; echo x >> $R/system/bin/app_process @@ -92,6 +92,9 @@ check "stock app_process backed up" "$(md5sum < $T/real)" "$(md5sum < $R/data/hm for f in bin/hmgapid bin/lpatch lib/libhmgapi_hook.so framework/hmgapi-hook.jar; do check "installed $f" "$(md5sum < $P/${f##*/})" "$(md5sum < $R/system/$f 2>/dev/null)" done +check "the engine's HTTPS library in /data (nothing on /system for it)" "$(md5sum < $P/libhmgapi_fetch.so)" "$(md5sum < $R/data/hmgapi/lib/libhmgapi_fetch.so 2>/dev/null)" +check "... readable, not writable by others" "-rw-r--r--" "$(ls -l $R/data/hmgapi/lib/libhmgapi_fetch.so | cut -c1-10)" +check "... not under /system" no "$([ -e $R/system/lib/libhmgapi_fetch.so ] && echo yes || echo no)" check "boot hook in install-recovery.sh" 1 "$(grep -c 'HMGAPI_HOOK begin' $R/system/etc/install-recovery.sh)" check "boot hook in qb_runtime.sh" 1 "$(grep -c 'HMGAPI_HOOK begin' $R/system/etc/qb_runtime.sh)" check "boot hook: only hmgapid boot, which returns at once (NEMESIS's start comes after it)" "if [ -x /system/bin/hmgapid ]; then /system/bin/hmgapid boot; fi" "$(sed -n 3p $R/system/etc/install-recovery.sh)" @@ -209,7 +212,7 @@ firmware_update() { } { printf '\177ELF'; head -c 9000 /dev/urandom; } > $T/newfw; chmod 755 $T/newfw echo "$(md5sum < $T/newfw | cut -c1-32) test new firmware" >> $P/stock.txt -(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) +(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) export HMGAPI_TEST_ENGINE=$T/bin/engine run $P/install.sh $P mkdir -p $R/data/hmgapi/state; echo '{"files": {}, "settings": {}}' > $R/data/hmgapi/state/files.json @@ -306,7 +309,7 @@ nemesis_boot check "HMG-API, then NEMESIS 1.17: the zygote start ends at stock" "$STK" "$(chain)" # an update under NEMESIS's script: the new wrapper goes where NEMESIS runs it cp $P/app_process $T/wrapper.old; echo update >> $P/app_process; WRAPPERS="$WRAPPERS $(md5sum < $P/app_process | cut -c1-32)" -(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) +(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) run $P/install.sh $P has "... an update under NEMESIS's script finishes" "installed. Restart the head unit" "$out" check "... the new wrapper is app_process.real" "$(md5sum < $P/app_process)" "$(md5sum < $R/system/bin/app_process.real)" @@ -343,14 +346,14 @@ check "... and after NEMESIS's next boot the zygote still starts: stock" "$STK" # release's update, and then its uninstall, with no boot in between mkdir -p $R/data/hmgapi; rm -rf $R/data/hmgapi cp $T/wrapper.old $P/app_process # an older wrapper first -(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) +(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) run $P/install.sh $P # into .real, under NEMESIS's script cp $P/app_process $T/wrapper.older; echo older >> $T/wrapper.older cp $T/wrapper.older $R/system/bin/app_process.real # the wrapper before the old update... cp $P/app_process $R/system/bin/app_process # ...and the old update's, over NEMESIS's script WRAPPERS="$WRAPPERS $(md5sum < $T/wrapper.older | cut -c1-32)" echo update >> $P/app_process; WRAPPERS="$WRAPPERS $(md5sum < $P/app_process | cut -c1-32)" -(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) +(cd $P && md5sum hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 > MANIFEST) run $P/install.sh $P has "older update over NEMESIS's script, then this one: finishes" "installed. Restart the head unit" "$out" check "... app_process.real gets the new wrapper (not left stale)" "$(md5sum < $P/app_process)" "$(md5sum < $R/system/bin/app_process.real)" diff --git a/tools/zygote-orders.py b/tools/zygote-orders.py index 74cf4380..7e85b5a5 100755 --- a/tools/zygote-orders.py +++ b/tools/zygote-orders.py @@ -132,14 +132,14 @@ def payload(work, name, scripts, wrapper, known): os.makedirs(P) for f, b in scripts.items(): wr(os.path.join(P, f), b) - for f in ('hmgapid', 'lpatch', 'libhmgapi_hook.so', 'hmgapi-hook.jar', 'HmgApi.apk'): + for f in ('hmgapid', 'lpatch', 'libhmgapi_hook.so', 'libhmgapi_fetch.so', 'hmgapi-hook.jar', 'HmgApi.apk'): wr(os.path.join(P, f), blob(name + f, 500)) wr(os.path.join(P, 'app_process'), wrapper) for f, b in (('VERSION', name.encode()), ('BUILD', b'test'), ('MAPS.md5', b'')): wr(os.path.join(P, f), b) lines = ['%s test stock\n' % hashlib.md5(b).hexdigest() for b in (STOCK, STOCK2)] if known else ['0 no build\n'] wr(os.path.join(P, 'stock.txt'), ''.join(lines).encode()) - names = ['hmgapid', 'lpatch', 'app_process', 'libhmgapi_hook.so', 'hmgapi-hook.jar', 'HmgApi.apk', 'MAPS.md5'] + sorted(scripts) + ['stock.txt'] + names = ['hmgapid', 'lpatch', 'app_process', 'libhmgapi_hook.so', 'libhmgapi_fetch.so', 'hmgapi-hook.jar', 'HmgApi.apk', 'MAPS.md5'] + sorted(scripts) + ['stock.txt'] wr(os.path.join(P, 'MANIFEST'), ''.join('%s %s\n' % (hashlib.md5(rd(os.path.join(P, n))).hexdigest(), n) for n in names).encode()) return P From d817b231f9672147a0b7e03afa9ef5627a7dde2e Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 10:06:45 -0500 Subject: [PATCH 4/5] Installer: keep the engine's HTTPS library before /system changes It went into /data after the wrapper and boot hook were written, so a failure there stopped the install with the maps, the app and the records after it skipped. It's now kept right after the backups, before remount rw, and a failure says nothing on /system was changed. Test: a file where its folder goes: refused, /system unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 34b9624731f965a94a9ad52360cfb504fb624d5a) --- install/common/install-test.sh | 12 ++++++++++++ install/common/install.sh | 12 +++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/install/common/install-test.sh b/install/common/install-test.sh index 9f3b819f..9df3407f 100644 --- a/install/common/install-test.sh +++ b/install/common/install-test.sh @@ -82,6 +82,18 @@ run $P/install.sh $P has "payload without its hook maps refused" "the hook maps folder (payload/maps) is missing" "$out" has "... before anything changed" "Nothing was changed." "$out" mv $T/maps.away $P/maps +# the engine's HTTPS library goes into /data before /system changes: when it can't, the +# install stops with /system as it was (not with the wrapper in and the maps and app skipped) +if [ -f $P/libhmgapi_fetch.so ]; then + mkdir -p $R/data/hmgapi; : > $R/data/hmgapi/lib # a file where its folder goes + run $P/install.sh $P + check "HTTPS library can't be kept: refused" 1 $rc + has "... said, before /system" "keep the engine's HTTPS library in $R/data/hmgapi/lib, so nothing on /system was changed" "$out" + check "... /system unchanged" "$BEFORE" "$(tree)" + rm -rf $R/data/hmgapi +else + echo "skip HTTPS library before /system (no libhmgapi_fetch.so in the payload)" +fi check "still stock after refusals" "$BEFORE" "$(tree)" run $P/install.sh $P diff --git a/install/common/install.sh b/install/common/install.sh index d56e153e..d7210f91 100644 --- a/install/common/install.sh +++ b/install/common/install.sh @@ -254,6 +254,13 @@ fi [ -s "$BAK" ] && not_stock "$BAK" && fail "the app_process backup isn't a stock binary (an HMG-API wrapper, NEMESIS LivePatch's script or not a binary), so nothing on /system was changed. Please send this line to the HMG-API maintainers." backup /system/etc/install-recovery.sh backup /system/etc/qb_runtime.sh +# the engine's HTTPS (the catalogue and updates over home Wi-Fi, Catalog): in /data, nothing on +# /system for it. Before /system changes: a failure here would otherwise stop the install with +# the wrapper and boot hook in but the maps, the app and the records after it skipped +if [ -f "$P/libhmgapi_fetch.so" ]; then + mkdir -p "$D/lib" && cp "$P/libhmgapi_fetch.so" "$D/lib/libhmgapi_fetch.so.new" && chmod 644 "$D/lib/libhmgapi_fetch.so.new" \ + && mv "$D/lib/libhmgapi_fetch.so.new" "$D/lib/libhmgapi_fetch.so" || fail "keep the engine's HTTPS library in $D/lib, so nothing on /system was changed" +fi remount rw || fail "can't remount /system rw (needs NEMESIS or a running hmgapid)" REMOUNTED=1 @@ -304,11 +311,6 @@ cp "$P/uninstall.sh" "$P/lib.sh" "$P/stock.txt" "$P/app-pending.sh" "$P/hook-che # open.sh (NEMESIS Manager's Launch, adb) installs the app from this copy if it's missing, then opens it cp "$P/app-open.sh" "$D/open.sh" && chmod 700 "$D/open.sh" || fail "keep open.sh" cp "$P/HmgApi.apk" "$D/HmgApi.apk" && chmod 644 "$D/HmgApi.apk" || fail "keep a copy of the app" -# the engine's HTTPS (the catalogue and updates over home Wi-Fi, Catalog): in /data, nothing on /system for it -if [ -f "$P/libhmgapi_fetch.so" ]; then - mkdir -p "$D/lib" && cp "$P/libhmgapi_fetch.so" "$D/lib/libhmgapi_fetch.so.new" && chmod 644 "$D/lib/libhmgapi_fetch.so.new" \ - && mv "$D/lib/libhmgapi_fetch.so.new" "$D/lib/libhmgapi_fetch.so" || fail "keep the engine's HTTPS library" -fi # HMG-API's NEMESIS scripts and incompatible packages: engine nemesis-sync lists HMG-API and its mods in NEMESIS with them if [ -d "$P/nemesis" ]; then rm -rf "$D/nemesis" && cp -r "$P/nemesis" "$D/nemesis" && chmod -R 700 "$D/nemesis" || fail "keep the NEMESIS scripts" From 5053a7f3370f37a879424d404fc2e9e4704d711b Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Mon, 30 Nov 2026 16:39:51 -0500 Subject: [PATCH 5/5] HTTPS: one call at a time (the unit's OpenSSL 1.0.1 has no locking callbacks) NativeFetch.fetch and dns are synchronized on one lock, so later parallel use can't run two OpenSSL calls at once; fetch.c's comment now says calls are serialized (review). The installer fix that keeps this library before /system changes moved here from #424 (cherry-picked). Co-Authored-By: Claude Opus 5.5 --- core/fetch/fetch.c | 3 ++- core/runtime/java/hmgapi/engine/NativeFetch.java | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c index 10bc561f..95f88451 100644 --- a/core/fetch/fetch.c +++ b/core/fetch/fetch.c @@ -28,7 +28,8 @@ * Built with no libc (as the loader): everything comes through dlopen/dlsym from the unit's * libc.so and libssl.so. On a computer (-DHOST, the off-car tests) it uses the system's headers * and an OpenSSL 1.1+/3 library, which is why each OpenSSL call has an old and a new name. - * No static buffers: calls may come from several threads. + * No static buffers, but OpenSSL 1.0.1 (the unit's) isn't thread-safe without locking callbacks, + * which this doesn't install: NativeFetch serializes every call (fetch and dns hold one lock). * First written as a mod (an update-check proof of concept), run on an Ioniq 5 US 260507. */ #ifdef HOST diff --git a/core/runtime/java/hmgapi/engine/NativeFetch.java b/core/runtime/java/hmgapi/engine/NativeFetch.java index 4320613e..a1af989a 100644 --- a/core/runtime/java/hmgapi/engine/NativeFetch.java +++ b/core/runtime/java/hmgapi/engine/NativeFetch.java @@ -50,11 +50,14 @@ static Http.Transport forEngine(Engine e, List why) { static final int TIMEOUT_MS = 20000; static final int CUT = -13; + // Both are synchronized (one lock, the class): the unit's OpenSSL 1.0.1 isn't thread-safe without + // locking callbacks, which fetch.c doesn't install, so no two calls ever run at once. + /** host is "name@address"; outPath must not exist yet. Bytes written for an answer the server closed cleanly, CUT, or an error */ - static native int fetch(String sslLib, String cLib, String host, String port, byte[] request, String outPath, int maxBytes, int timeoutMs); + static synchronized native int fetch(String sslLib, String cLib, String host, String port, byte[] request, String outPath, int maxBytes, int timeoutMs); /** one UDP query to server:port on a socket held to home Wi-Fi, its answer to outPath (must not exist yet): its length, or an error */ - static native int dns(String cLib, String server, String port, byte[] query, String outPath, int timeoutMs); + static synchronized native int dns(String cLib, String server, String port, byte[] query, String outPath, int timeoutMs); private static final java.util.concurrent.atomic.AtomicInteger SEQ = new java.util.concurrent.atomic.AtomicInteger(); private static final java.util.Random RND = new java.util.Random();