diff --git a/CHANGELOG.md b/CHANGELOG.md index f6bd2ad9..25adddd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,18 @@ get in (`HMGAPI_HOMELO`). The guard is checked on every pass, not only when the lease changes, and put back first in INPUT after the stock firewall reloads; `route_localnet` is on only while it's there. +- **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. 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 (2026-11-28) diff --git a/build.sh b/build.sh index 8736fa21..c570d173 100755 --- a/build.sh +++ b/build.sh @@ -34,6 +34,17 @@ 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 + # 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 + 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 \ + -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 +106,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 +131,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 +177,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..95f88451 --- /dev/null +++ b/core/fetch/fetch.c @@ -0,0 +1,357 @@ +/* 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. 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: + * 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. + * + * 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, 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 +#include +#include +#include +#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; +}; +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_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; +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 + +/* 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_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@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, int timeout_ms) { + char host[256]; + 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] != '@' || !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; + + /* 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_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 || !p_get_error) return E_SYM; + + int fd = home_connect(&c, addr, port, SOCK_STREAM, timeout_ms); + if (fd < 0) return fd; + void *ctx = 0, *ssl = 0; + 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; } + 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; + } + 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; } + int total = 0; + for (;;) { + 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 ? E_READ : clean ? total : E_CUT; +done: + 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); + 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, jint timeout_ms) { + (void) cls; + 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, (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); + 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; +} + +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 new file mode 100644 index 00000000..0356883f --- /dev/null +++ b/core/runtime/fetch-test.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# 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 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 new file mode 100644 index 00000000..643f914a --- /dev/null +++ b/core/runtime/java/hmgapi/engine/DnsLookup.java @@ -0,0 +1,110 @@ +package hmgapi.engine; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +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, 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"; + + /** 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, 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); + try { + byte[] r = asker.ask(server, q); + return answers(r, r.length, id); + } catch (IOException e) { + last = e; + } + } + 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); + } +} diff --git a/core/runtime/java/hmgapi/engine/Http.java b/core/runtime/java/hmgapi/engine/Http.java new file mode 100644 index 00000000..7b446492 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Http.java @@ -0,0 +1,225 @@ +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 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; + /** 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 tmpDir; + + Http(Transport transport, File tmpDir) { + this.transport = transport; + this.tmpDir = tmpDir; + } + + /** 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"); + 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 && 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 == 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]); + } catch (NumberFormatException e) { + return new Result(0, "not an HTTP answer"); + } + Map headers = new HashMap(); + 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()); + } + 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); + return body(in, headers, cut, out, maxBytes); + } finally { + in.close(); + } + } finally { + tmp.delete(); + } + } + 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 = 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"); + } + 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; + } + + /** 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 (;;) { + 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 > max - total) return -1; + total += size; + 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; + } + 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 new file mode 100644 index 00000000..a1af989a --- /dev/null +++ b/core/runtime/java/hmgapi/engine/NativeFetch.java @@ -0,0 +1,199 @@ +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; + } + } + + /** 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; + + // 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 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 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(); + + /** + * 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) { + // 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(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, TIMEOUT_MS); + } + + 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"; + 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 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; + + Web(File dir) { + this.dir = dir; + } + + @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"); + 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 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()) { + 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 { + 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(answer, 0, Math.min(n, maxBytes)); + } finally { + o.close(); + } + return big ? -9 : n == 0 ? -10 : cut ? CUT : n; + } 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/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 new file mode 100644 index 00000000..8e431b7a --- /dev/null +++ b/core/runtime/test/hmgapi/engine/FetchTest.java @@ -0,0 +1,236 @@ +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); + 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")); + + 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()); + + // 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..9df3407f 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 @@ -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 @@ -92,6 +104,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 +224,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 +321,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 +358,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/install/common/install.sh b/install/common/install.sh index bc889914..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 diff --git a/tools/test-all.sh b/tools/test-all.sh index 3e72770e..8168b620 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/client/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/client/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/client/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/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/client/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/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" 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