Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Connect finds speakers on the Wi-Fi without the multicast entitlement
My-Name-Is-Jeffe6de8df1fc31
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex c2565e94..21798ab5 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -25,7 +25,8 @@dump-log.sh, extract-flags.pytrees/ recorded view trees, one per screen; the input for every new hook. trees/clean/ holdsthe numbered snapshots per screen of record-session.py, taken of Spotify as it came- plist/ Info.plist overrides merged into the app (turns UIDesignRequiresCompatibility off)+ plist/ Info.plist overrides merged into the app (turns UIDesignRequiresCompatibility off; the+ Bonjour services are added to Spotify's own list by pipeline.sh)vendor/ AutoFLEX deb; audio/, the third-party C of the audio effects (libbs2b, WDL's EEL2) andthe EEL2 parser of the mod's own, built by its own Makefile into a static library thetweak links (its README names the upstream commits and the licenses)@@ -217,6 +218,13 @@ Shared:already there skipped (SGPlayLog.m), and a page of the top tracks, artists and albums of a week, a month,a year and all time. Tested on the Mac against harness/listening-stats/, the page and the recorder in thesimulator against its sim/+ Connect/ Connect speakers on the Wi-Fi for a build signed without the multicast entitlement (Connect.h lists+ its files): Bonjour, which needs only NSBonjourServices (plist/, merged with Spotify's own list by+ pipeline.sh) and the Local Network permission, finds and resolves _spotify-connect._tcp; Spotify's+ imports of sendto, sendmsg and recvfrom are rebound, a Connect query the system refused is sent by+ unicast to each receiver's port 5353 instead, and each answer is passed to Spotify's socket over+ loopback with recvfrom reporting the receiver as its source. No setting. Tested on the Mac against+ harness/connect/Native:diff --git a/harness/connect/README.md b/harness/connect/README.mdnew file mode 100644index 00000000..ab49b19f--- /dev/null+++ b/harness/connect/README.md@@ -0,0 +1,33 @@+# Connect discovery harness++`SGMDNS.m` and `SGConnectRelay.m` (Shared/Connect) as the tweak compiles them, on the Mac.++- The packet checks over queries and answers made by hand: the service type, a subtype, upper case, a+ compressed name, and the ones to turn away (Cast only, a label that only ends like Connect's, QR or+ opcode wrong, too many questions, cut short, compression loops, pointers and labels past the end, a name+ over 255 bytes; in answers another transaction ID, TC, an RCODE, class CH, data or a PTR target running+ past its end). Then 200,000 packets with random bytes changed, read by both checks.+- The gate of the sendto and sendmsg replacements, with the system's send stood in for by one that fails+ with the error given: a refused Connect query to 224.0.0.251:5353 or [ff02::fb]:5353 is reported sent with+ errno as it was, and anything else (another error, a Cast query, another group or port, a socket with no+ port, a connected one, TCP) keeps the failure.+- A whole round over loopback, for an IPv4 socket and for an IPv6 one: a stand-in receiver on 127.0.0.1+ gets the query once (the same query sent again while the round runs starts no second round), answers it+ with a wrong ID and the right one while a stranger answers too, and the stand-in for Spotify's socket reads+ only the right one, from the receiver's address (`::ffff:127.0.0.1` for the IPv6 socket), through a+ `MSG_PEEK` and again after it. Other loopback traffic keeps its source.++The receivers here listen on ephemeral ports rather than 5353, which the Mac's mDNSResponder holds; the+round answers to whatever port it sent to, which on the phone is always 5353.++ ./build.sh && build/connect # binds loopback ports, so not inside a sandbox without local binding++With the sanitizers, which turn any read past a packet's end into a stop:++ xcrun clang -fobjc-arc -O1 -g -fsanitize=address,undefined -I ../../tweak/Sources -framework Foundation \+ main.m ../../tweak/Sources/Shared/Connect/SGMDNS.m ../../tweak/Sources/Shared/Connect/SGConnectRelay.m \+ -o build/connect-asan && build/connect-asan++Not covered: the Bonjour browse in Connect.x, the rebinding of Spotify's imports, and whether the phone+hands a loopback datagram for port 5353 to Spotify's socket rather than mDNSResponder's. Those need a+phone on a network with a Connect receiver.diff --git a/harness/connect/build.sh b/harness/connect/build.shnew file mode 100755index 00000000..c3f906b6--- /dev/null+++ b/harness/connect/build.sh@@ -0,0 +1,9 @@+#!/bin/sh+# Builds the Connect discovery harness for the Mac: SGMDNS.m and SGConnectRelay.m as the tweak compiles+# them, and main.m.+set -e+cd "$(dirname "$0")"+mkdir -p build+xcrun clang -fobjc-arc -O2 -Wall -Werror -I ../../tweak/Sources -framework Foundation \+ main.m ../../tweak/Sources/Shared/Connect/SGMDNS.m ../../tweak/Sources/Shared/Connect/SGConnectRelay.m -o build/connect+echo "built build/connect"diff --git a/harness/connect/main.m b/harness/connect/main.mnew file mode 100644index 00000000..626b9abb--- /dev/null+++ b/harness/connect/main.m@@ -0,0 +1,368 @@+// Connect discovery's packet checks and relay (Shared/Connect) on the Mac. The checks run over packets+// made by hand, the bad ones included; the relay runs over loopback with a stand-in receiver and a+// stand-in for Spotify's socket, the system's sendto made to fail the way it does without the+// multicast entitlement.+#import <arpa/inet.h>+#import <errno.h>+#import <netinet/in.h>+#import <unistd.h>+#import "Shared/Connect/Connect.h"++static int failures;+#define CHECK(condition, what) do { if (!(condition)) { failures++; printf("FAIL %s\n", what); } else printf("ok %s\n", what); } while (0)++#pragma mark - packets++typedef struct { uint8_t bytes[SGMDNSMaxLength + 64]; size_t length; } Packet;++static void put8(Packet *p, uint8_t value) { p->bytes[p->length++] = value; }+static void put16(Packet *p, uint16_t value) { put8(p, value >> 8); put8(p, value & 0xFF); }+static void header(Packet *p, uint16_t id, uint16_t flags, uint16_t qd, uint16_t an, uint16_t ns, uint16_t ar) {+ p->length = 0;+ put16(p, id); put16(p, flags); put16(p, qd); put16(p, an); put16(p, ns); put16(p, ar);+}+// Labels separated by '|', so a label may hold a dot; ends with the root.+static void name(Packet *p, const char *labels) {+ char copy[256];+ strlcpy(copy, labels, sizeof copy);+ char *rest = copy, *label;+ while ((label = strsep(&rest, "|"))) {+ put8(p, (uint8_t)strlen(label));+ memcpy(p->bytes + p->length, label, strlen(label));+ p->length += strlen(label);+ }+ put8(p, 0);+}+static void pointer(Packet *p, uint16_t to) { put16(p, 0xC000 | to); }+static void question(Packet *p, const char *labels) { name(p, labels); put16(p, 12); put16(p, 1); }+// A record's type, class, TTL and data length, after its owner name.+static void record(Packet *p, uint16_t type, uint16_t class, uint16_t dataLength) {+ put16(p, type); put16(p, class); put16(p, 0); put16(p, 120); put16(p, dataLength);+}++static const char *kConnect = "_spotify-connect|_tcp|local";++static Packet query(void) {+ Packet p;+ header(&p, 0, 0, 1, 0, 0, 0);+ question(&p, kConnect);+ return p;+}++// A legacy unicast answer: the question again, then a PTR from the service type to an instance whose+// name points back at the question's.+static Packet reply(uint16_t id) {+ Packet p;+ header(&p, id, 0x8400, 1, 1, 0, 0);+ question(&p, kConnect);+ pointer(&p, 12);+ record(&p, 12, 1, 2 + 1 + 7);+ name(&p, "Kitchen");+ p.length -= 1; // the instance label, then a pointer instead of the root+ pointer(&p, 12);+ return p;+}++static void checkQueries(void) {+ Packet p = query();+ CHECK(SGMDNSIsConnectQuery(p.bytes, p.length), "query: the service type");+ header(&p, 0, 0, 1, 0, 0, 0); question(&p, "_living._sub|_spotify-connect|_tcp|local");+ CHECK(SGMDNSIsConnectQuery(p.bytes, p.length), "query: a subtype");+ header(&p, 0, 0, 1, 0, 0, 0); question(&p, "_SPOTIFY-CONNECT|_TCP|LOCAL");+ CHECK(SGMDNSIsConnectQuery(p.bytes, p.length), "query: upper case");+ header(&p, 0, 0, 2, 0, 0, 0); question(&p, "_googlecast|_tcp|local"); question(&p, kConnect);+ CHECK(SGMDNSIsConnectQuery(p.bytes, p.length), "query: Connect second of two");+ header(&p, 0, 0, 2, 0, 0, 0); question(&p, "a|_tcp|local"); put8(&p, 16); memcpy(p.bytes + p.length, "_spotify-connect", 16); p.length += 16; pointer(&p, 14); put16(&p, 12); put16(&p, 1);+ CHECK(SGMDNSIsConnectQuery(p.bytes, p.length), "query: a compressed name");+ header(&p, 0, 0, 1, 0, 0, 0); question(&p, "_googlecast|_tcp|local");+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: Cast only is not relayed");+ header(&p, 0, 0, 1, 0, 0, 0); question(&p, "x_spotify-connect|_tcp|local");+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: a label that only ends like it");+ header(&p, 0, 0, 1, 0, 0, 0); question(&p, "_spotify-connect._tcp.local");+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: one label holding the dots");+ p = query(); p.bytes[2] = 0x80;+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: QR set");+ p = query(); p.bytes[2] = 0x08;+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: opcode 1");+ p = query(); p.bytes[5] = 0;+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: no question");+ p = query(); p.bytes[5] = 41;+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: 41 questions");+ p = query(); p.bytes[5] = 2;+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: a question missing");+ p = query();+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length - 1), "query: cut short");+ CHECK(!SGMDNSIsConnectQuery(p.bytes, 11), "query: shorter than a header");+ CHECK(!SGMDNSIsConnectQuery(p.bytes, SGMDNSMaxLength + 1), "query: longer than 9000 bytes");+ header(&p, 0, 0, 1, 0, 0, 0); pointer(&p, 12); put16(&p, 12); put16(&p, 1);+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: a name pointing at itself");+ header(&p, 0, 0, 1, 0, 0, 0); pointer(&p, 14); pointer(&p, 12); put16(&p, 12); put16(&p, 1);+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: two pointers in a loop");+ header(&p, 0, 0, 1, 0, 0, 0); pointer(&p, 4000); put16(&p, 12); put16(&p, 1);+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: a pointer past the end");+ header(&p, 0, 0, 1, 0, 0, 0); put8(&p, 63); p.length += 63;+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: a label running off the end");+ header(&p, 0, 0, 1, 0, 0, 0); put8(&p, 0x40); put8(&p, 0); put16(&p, 12); put16(&p, 1);+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: an extended label type");+ header(&p, 0, 0, 1, 0, 0, 0);+ for (int i = 0; i < 5; i++) { put8(&p, 63); memset(p.bytes + p.length, 'a', 63); p.length += 63; }+ put8(&p, 0); put16(&p, 12); put16(&p, 1);+ CHECK(!SGMDNSIsConnectQuery(p.bytes, p.length), "query: a name over 255 bytes");+}++static void checkReplies(void) {+ Packet p = reply(0x1234);+ CHECK(SGMDNSIsConnectReply(p.bytes, p.length, 0x1234), "reply: a PTR to an instance");+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 0x1235), "reply: another transaction ID");+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length - 1, 0x1234), "reply: cut short");+ p = reply(0x1234); p.bytes[2] |= 0x02;+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 0x1234), "reply: truncated (TC)");+ p = reply(0x1234); p.bytes[3] |= 0x03;+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 0x1234), "reply: RCODE 3");+ p = reply(0x1234); p.bytes[2] &= 0x7F;+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 0x1234), "reply: QR clear");+ p = reply(0x1234); p.bytes[2] |= 0x10;+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 0x1234), "reply: opcode 2");+ p = reply(0x1234); p.bytes[7] = 0;+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 0x1234), "reply: no records");+ p = reply(0x1234); p.bytes[7] = 2;+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 0x1234), "reply: a record missing");+ header(&p, 1, 0x8400, 0, 401, 0, 0);+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: 401 records");++ // An SRV owned by the instance, with mDNS's cache flush bit on its class.+ header(&p, 1, 0x8400, 0, 1, 0, 0); name(&p, "Living.Room|_spotify-connect|_tcp|local"); record(&p, 33, 0x8001, 0);+ CHECK(SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: an instance's record, cache flush set, a dot in its name");+ header(&p, 1, 0x8400, 0, 1, 0, 0); name(&p, "Living|_spotify-connect|_tcp|local"); record(&p, 33, 3, 0);+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: class CH");+ header(&p, 1, 0x8400, 0, 0, 0, 1); name(&p, "tv|_googlecast|_tcp|local"); record(&p, 1, 1, 4); put16(&p, 0); put16(&p, 0);+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: Cast only");+ header(&p, 1, 0x8400, 0, 1, 0, 1); name(&p, "tv|_googlecast|_tcp|local"); record(&p, 1, 1, 4); put16(&p, 0); put16(&p, 0);+ name(&p, "Desk|_spotify-connect|_tcp|local"); record(&p, 16, 1, 0);+ CHECK(SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: Connect in the additional section");+ header(&p, 1, 0x8400, 0, 1, 0, 0); name(&p, "Desk|_spotify-connect|_tcp|local"); record(&p, 16, 1, 50);+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: data running off the end");+ header(&p, 1, 0x8400, 0, 1, 0, 0); pointer(&p, 12); record(&p, 16, 1, 0);+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: an owner pointing at itself");+ header(&p, 1, 0x8400, 0, 1, 0, 0); name(&p, "_services|_dns-sd|_udp|local"); record(&p, 12, 1, 2); pointer(&p, 3000);+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: a PTR target past the end");+ header(&p, 1, 0x8400, 0, 1, 0, 0); name(&p, "_services|_dns-sd|_udp|local"); record(&p, 12, 1, 1); put8(&p, 5); put8(&p, 'a');+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: a PTR target longer than its data");+ header(&p, 1, 0x8400, 0, 2, 0, 0); name(&p, "Desk|_spotify-connect|_tcp|local"); record(&p, 16, 1, 0);+ name(&p, "x|local"); record(&p, 12, 1, 2); pointer(&p, 5000);+ CHECK(!SGMDNSIsConnectReply(p.bytes, p.length, 1), "reply: a Connect record, then a name that does not decode");+}++// Random bytes changed in a good query and a good answer, read by both checks: under the sanitizers+// (README) any read past a packet's end stops the run.+static void checkMutations(void) {+ srandom(159);+ int accepted = 0;+ for (int round = 0; round < 200000; round++) {+ Packet p = round & 1 ? reply(7) : query();+ for (int k = 0, changes = 1 + (int)(random() % 4); k < changes; k++) p.bytes[random() % p.length] = (uint8_t)random();+ size_t length = p.length - (size_t)(random() % 3);+ uint8_t *copy = malloc(length); // exactly the packet's size, so the sanitizer sees a read past it+ memcpy(copy, p.bytes, length);+ accepted += SGMDNSIsConnectQuery(copy, length) + SGMDNSIsConnectReply(copy, length, 7);+ free(copy);+ }+ printf("ok 200000 changed packets read, %d still accepted\n", accepted);+}++#pragma mark - the hook's gate++static int sg_fakeErrno;+static int sg_fakeCalls;+static ssize_t failingSendto(int s, const void *b, size_t l, int f, const struct sockaddr *to, socklen_t tl) {+ sg_fakeCalls++;+ if (!sg_fakeErrno) return (ssize_t)l;+ errno = sg_fakeErrno;+ return -1;+}+static ssize_t failingSendmsg(int s, const struct msghdr *m, int f) {+ sg_fakeCalls++;+ errno = sg_fakeErrno;+ return -1;+}++static struct sockaddr_in loopbackV4(in_port_t port) {+ return (struct sockaddr_in){.sin_len = sizeof(struct sockaddr_in), .sin_family = AF_INET, .sin_port = port, .sin_addr.s_addr = htonl(INADDR_LOOPBACK)};+}+static struct sockaddr_in6 loopbackV6(in_port_t port) {+ return (struct sockaddr_in6){.sin6_len = sizeof(struct sockaddr_in6), .sin6_family = AF_INET6, .sin6_port = port, .sin6_addr = in6addr_loopback};+}++// A UDP socket bound to an ephemeral loopback port, reads timing out after `timeout` s.+static int boundSocket(int family, double timeout, in_port_t *port) {+ int s = socket(family, SOCK_DGRAM, IPPROTO_UDP);+ struct sockaddr_storage address = {0};+ if (family == AF_INET6) *(struct sockaddr_in6 *)&address = loopbackV6(0);+ else *(struct sockaddr_in *)&address = loopbackV4(0);+ if (bind(s, (struct sockaddr *)&address, address.ss_len) != 0) { perror("bind"); exit(2); }+ socklen_t length = sizeof address;+ getsockname(s, (struct sockaddr *)&address, &length);+ if (port) *port = family == AF_INET6 ? ((struct sockaddr_in6 *)&address)->sin6_port : ((struct sockaddr_in *)&address)->sin_port;+ struct timeval wait = {(int)timeout, (int)((timeout - (int)timeout) * 1e6)};+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof wait);+ return s;+}++static void checkGate(void) {+ SGConnectRealSendto = failingSendto;+ SGConnectRealSendmsg = failingSendmsg;+ Packet q = query();+ struct sockaddr_in group = {.sin_len = sizeof group, .sin_family = AF_INET, .sin_port = htons(5353), .sin_addr.s_addr = inet_addr("224.0.0.251")};+ struct sockaddr_in6 group6 = {.sin6_len = sizeof group6, .sin6_family = AF_INET6, .sin6_port = htons(5353)};+ inet_pton(AF_INET6, "ff02::fb", &group6.sin6_addr);+ int bound = boundSocket(AF_INET, 1, NULL), bound6 = boundSocket(AF_INET6, 1, NULL);++ sg_fakeErrno = EHOSTUNREACH;+ errno = 0;+ ssize_t sent = SGConnectSendto(bound, q.bytes, q.length, 0, (struct sockaddr *)&group, sizeof group);+ CHECK(sent == (ssize_t)q.length && errno == EHOSTUNREACH, "sendto: refused Connect query reported sent, errno kept");+ sent = SGConnectSendto(bound6, q.bytes, q.length, 0, (struct sockaddr *)&group6, sizeof group6);+ CHECK(sent == (ssize_t)q.length, "sendto: the same over IPv6 to ff02::fb");+ sg_fakeErrno = EINVAL;+ sent = SGConnectSendto(bound, q.bytes, q.length, 0, (struct sockaddr *)&group, sizeof group);+ CHECK(sent == -1 && errno == EINVAL, "sendto: another error stays");+ sg_fakeErrno = EPERM;+ Packet notConnect;+ header(¬Connect, 0, 0, 1, 0, 0, 0); question(¬Connect, "_googlecast|_tcp|local");+ sent = SGConnectSendto(bound, notConnect.bytes, notConnect.length, 0, (struct sockaddr *)&group, sizeof group);+ CHECK(sent == -1 && errno == EPERM, "sendto: a Cast query stays refused");+ struct sockaddr_in elsewhere = group;+ elsewhere.sin_addr.s_addr = inet_addr("224.0.0.252");+ sent = SGConnectSendto(bound, q.bytes, q.length, 0, (struct sockaddr *)&elsewhere, sizeof elsewhere);+ CHECK(sent == -1, "sendto: another group stays refused");+ elsewhere = group;+ elsewhere.sin_port = htons(5354);+ sent = SGConnectSendto(bound, q.bytes, q.length, 0, (struct sockaddr *)&elsewhere, sizeof elsewhere);+ CHECK(sent == -1, "sendto: another port stays refused");+ sent = SGConnectSendto(bound, q.bytes, q.length, 0, (struct sockaddr *)&group, 4);+ CHECK(sent == -1, "sendto: an address too short to read stays refused");++ int unbound = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);+ sent = SGConnectSendto(unbound, q.bytes, q.length, 0, (struct sockaddr *)&group, sizeof group);+ CHECK(sent == -1 && errno == EPERM, "sendto: a socket with no port stays refused");+ int connected = boundSocket(AF_INET, 1, NULL);+ struct sockaddr_in peer = loopbackV4(htons(9));+ connect(connected, (struct sockaddr *)&peer, sizeof peer);+ sent = SGConnectSendto(connected, q.bytes, q.length, 0, (struct sockaddr *)&group, sizeof group);+ CHECK(sent == -1 && errno == EPERM, "sendto: a connected socket stays refused");+ int stream = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+ sent = SGConnectSendto(stream, q.bytes, q.length, 0, (struct sockaddr *)&group, sizeof group);+ CHECK(sent == -1 && errno == EPERM, "sendto: a TCP socket stays refused");++ sg_fakeErrno = 0;+ sent = SGConnectSendto(bound, q.bytes, 3, 0, (struct sockaddr *)&group, sizeof group);+ CHECK(sent == 3, "sendto: a send that worked is left alone");++ sg_fakeErrno = ENETUNREACH;+ struct iovec parts[2] = {{q.bytes, 5}, {q.bytes + 5, q.length - 5}};+ struct msghdr message = {.msg_name = &group, .msg_namelen = sizeof group, .msg_iov = parts, .msg_iovlen = 2};+ sent = SGConnectSendmsg(bound, &message, 0);+ CHECK(sent == (ssize_t)q.length && errno == ENETUNREACH, "sendmsg: a query in two parts reported sent, errno kept");+ message.msg_name = NULL;+ sent = SGConnectSendmsg(bound, &message, 0);+ CHECK(sent == -1, "sendmsg: no destination stays refused");+ close(bound); close(bound6); close(unbound); close(connected); close(stream);+ usleep(1300000); // the rounds started above end+}++#pragma mark - the relay over loopback++static void checkRelay(int family) {+ const char *label = family == AF_INET6 ? "relay (IPv6 socket, IPv4 receiver)" : "relay (IPv4)";+ char what[160];+ in_port_t receiverPort, strangerPort;+ int spotify = boundSocket(family, 1.5, NULL);+ int receiver = boundSocket(AF_INET, 1, &receiverPort), stranger = boundSocket(AF_INET, 1, &strangerPort);+ struct sockaddr_in receiverAddress = loopbackV4(receiverPort);+ SGConnectSetReceiver(@"Kitchen", @[[NSData dataWithBytes:&receiverAddress length:sizeof receiverAddress]]);++ sg_fakeErrno = EHOSTUNREACH;+ Packet q = query();+ q.bytes[0] = 0x12; q.bytes[1] = 0x34;+ struct sockaddr_in group = {.sin_len = sizeof group, .sin_family = AF_INET, .sin_port = htons(5353), .sin_addr.s_addr = inet_addr("224.0.0.251")};+ struct sockaddr_in6 group6 = {.sin6_len = sizeof group6, .sin6_family = AF_INET6, .sin6_port = htons(5353)};+ inet_pton(AF_INET6, "ff02::fb", &group6.sin6_addr);+ const struct sockaddr *to = family == AF_INET6 ? (struct sockaddr *)&group6 : (struct sockaddr *)&group;+ SGConnectSendto(spotify, q.bytes, q.length, 0, to, to->sa_len);+ SGConnectSendto(spotify, q.bytes, q.length, 0, to, to->sa_len); // the same again while the round runs++ uint8_t buffer[SGMDNSMaxLength];+ struct sockaddr_in relay;+ socklen_t relayLength = sizeof relay;+ ssize_t got = recvfrom(receiver, buffer, sizeof buffer, 0, (struct sockaddr *)&relay, &relayLength);+ snprintf(what, sizeof what, "%s: the receiver gets the query", label);+ CHECK(got == (ssize_t)q.length && memcmp(buffer, q.bytes, q.length) == 0, what);++ // Answered at once: the round, having sent all it had to, ends 0.7 s in.+ Packet wrong = reply(0x4321), good = reply(0x1234), fromStranger = reply(0x1234);+ fromStranger.bytes[fromStranger.length - 3] = 'X'; // told apart from the good one+ sendto(receiver, wrong.bytes, wrong.length, 0, (struct sockaddr *)&relay, relayLength);+ sendto(stranger, fromStranger.bytes, fromStranger.length, 0, (struct sockaddr *)&relay, relayLength);+ sendto(receiver, good.bytes, good.length, 0, (struct sockaddr *)&relay, relayLength);++ got = recvfrom(receiver, buffer, sizeof buffer, 0, NULL, NULL);+ snprintf(what, sizeof what, "%s: and only once", label);+ CHECK(got < 0, what);++ struct sockaddr_storage from;+ socklen_t fromLength = sizeof from;+ got = SGConnectRecvfrom(spotify, buffer, sizeof buffer, MSG_PEEK, (struct sockaddr *)&from, &fromLength);+ snprintf(what, sizeof what, "%s: Spotify's socket gets the answer", label);+ CHECK(got == (ssize_t)good.length && memcmp(buffer, good.bytes, good.length) == 0, what);+ BOOL fromReceiver;+ if (family == AF_INET6) {+ struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)&from;+ fromReceiver = fromLength == sizeof *v6 && v6->sin6_family == AF_INET6 && v6->sin6_port == receiverPort+ && IN6_IS_ADDR_V4MAPPED(&v6->sin6_addr) && v6->sin6_addr.s6_addr[12] == 127 && v6->sin6_addr.s6_addr[15] == 1;+ } else {+ struct sockaddr_in *v4 = (struct sockaddr_in *)&from;+ fromReceiver = fromLength == sizeof *v4 && v4->sin_port == receiverPort && v4->sin_addr.s_addr == htonl(INADDR_LOOPBACK);+ }+ snprintf(what, sizeof what, "%s: from the receiver's address (peeked)", label);+ CHECK(fromReceiver, what);++ struct sockaddr_storage again = {0};+ socklen_t againLength = sizeof again;+ got = SGConnectRecvfrom(spotify, buffer, sizeof buffer, 0, (struct sockaddr *)&again, &againLength);+ snprintf(what, sizeof what, "%s: read again, kept after the peek", label);+ CHECK(got == (ssize_t)good.length && againLength == fromLength && memcmp(&again, &from, fromLength) == 0, what);++ got = SGConnectRecvfrom(spotify, buffer, sizeof buffer, 0, (struct sockaddr *)&from, &fromLength);+ snprintf(what, sizeof what, "%s: nothing else reaches Spotify (wrong ID, a stranger)", label);+ CHECK(got < 0, what);++ // A datagram from loopback that was never handed over keeps its source.+ in_port_t otherPort;+ int other = boundSocket(family, 1, &otherPort);+ struct sockaddr_storage spotifyAddress;+ socklen_t spotifyLength = sizeof spotifyAddress;+ getsockname(spotify, (struct sockaddr *)&spotifyAddress, &spotifyLength);+ sendto(other, good.bytes, good.length - 1, 0, (struct sockaddr *)&spotifyAddress, spotifyLength);+ fromLength = sizeof from;+ got = SGConnectRecvfrom(spotify, buffer, sizeof buffer, 0, (struct sockaddr *)&from, &fromLength);+ in_port_t seenPort = family == AF_INET6 ? ((struct sockaddr_in6 *)&from)->sin6_port : ((struct sockaddr_in *)&from)->sin_port;+ snprintf(what, sizeof what, "%s: other loopback traffic keeps its source", label);+ CHECK(got == (ssize_t)good.length - 1 && seenPort == otherPort, what);++ SGConnectSetReceiver(@"Kitchen", nil);+ close(spotify); close(receiver); close(stranger); close(other);+ usleep(1300000);+}++int main(void) {+ @autoreleasepool {+ checkQueries();+ checkReplies();+ checkMutations();+ checkGate();+ checkRelay(AF_INET);+ checkRelay(AF_INET6);+ }+ printf(failures ? "%d FAILED\n" : "all passed\n", failures);+ return failures ? 1 : 0;+}diff --git a/plist/liquid-glass.plist b/plist/liquid-glass.plistindex 81ff3b23..d4f98fb0 100644--- a/plist/liquid-glass.plist+++ b/plist/liquid-glass.plist@@ -10,6 +10,14 @@<true/><key>MusicHapticsSupported</key><true/>+ <key>NSBonjourServices</key>+ <array>+ <string>_spotify-ln-check._tcp</string>+ <string>_spotify-connect._tcp</string>+ <string>_googlecast._tcp</string>+ </array>+ <key>NSLocalNetworkUsageDescription</key>+ <string>Find nearby speakers and devices for Spotify Connect and Cast.</string><key>NSMotionUsageDescription</key><string>AirPods gestures read how your head moves, so a double nod can like a song and a shake can skip it.</string></dict>diff --git a/scripts/pipeline.sh b/scripts/pipeline.shindex e5c27a3e..3d6f24ae 100755--- a/scripts/pipeline.sh+++ b/scripts/pipeline.sh@@ -109,9 +109,27 @@ xcrun --sdk iphoneos clang -target arm64-apple-ios16.0 -dynamiclib -fobjc-arc -O-install_name @rpath/SpotifyGlassAppGroups.dylib -o "$GROUPS_DYLIB" "$ROOT/extension/AppGroups/AppGroups.m"FILES+=("$GROUPS_DYLIB")+# A key in plist/ replaces Spotify's own of that name, so the Bonjour services Connect discovery+# (Shared/Connect) browses go in after the ones Spotify lists, and Spotify's own local network wording+# is kept where it has one.+OVERLAY="$ROOT/out/.overlay.plist"+unzip -p "$IN" "${APP_DIR}Info.plist" > "$ROOT/out/.info.plist"+python3 - "$ROOT/plist/liquid-glass.plist" "$ROOT/out/.info.plist" "$OVERLAY" <<'PY'+import plistlib, sys+with open(sys.argv[1], 'rb') as f: overlay = plistlib.load(f)+with open(sys.argv[2], 'rb') as f: app = plistlib.load(f)+services = list(app.get('NSBonjourServices', []))+services += [s for s in overlay.get('NSBonjourServices', []) if s not in services]+overlay['NSBonjourServices'] = services+if app.get('NSLocalNetworkUsageDescription'): overlay.pop('NSLocalNetworkUsageDescription', None)+with open(sys.argv[3], 'wb') as f: plistlib.dump(overlay, f)+PY+rm -f "$ROOT/out/.info.plist"+echo "==> injecting"# -w drops the Watch app: its companion-app key would still name com.spotify.client and block the install.-cyan -i "$IN" -o "$OUT" -f "${FILES[@]}" -l "$ROOT/plist/liquid-glass.plist" ${BUNDLE_ID:+-b "$BUNDLE_ID"} ${NAME:+-n "$NAME"} ${ICON:+-k "$ICON"} -w -s --overwrite+cyan -i "$IN" -o "$OUT" -f "${FILES[@]}" -l "$OVERLAY" ${BUNDLE_ID:+-b "$BUNDLE_ID"} ${NAME:+-n "$NAME"} ${ICON:+-k "$ICON"} -w -s --overwrite+rm -f "$OVERLAY"echo "==> loading the App Group shim in the home screen widget"WIDGET_BIN="${APP_DIR}PlugIns/WidgetExtension.appex/WidgetExtension"diff --git a/tweak/Sources/Shared/Connect/Connect.h b/tweak/Sources/Shared/Connect/Connect.hnew file mode 100644index 00000000..aa04a191--- /dev/null+++ b/tweak/Sources/Shared/Connect/Connect.h@@ -0,0 +1,54 @@+// Spotify Connect devices on the local network for a build re-signed without Apple's multicast+// entitlement. Spotify finds the speakers, TVs and desktop apps on the Wi-Fi with an mDNS query of its+// own to 224.0.0.251:5353 (or [ff02::fb]:5353), and without the entitlement iOS refuses that send, so+// only the devices Spotify's cloud knows show. Bonjour needs no entitlement, only Info.plist's+// NSBonjourServices (plist/liquid-glass.plist, merged with Spotify's own by scripts/pipeline.sh) and the+// Local Network permission. So:+//+// Connect.x browses for _spotify-connect._tcp with Bonjour and resolves each receiver to+// its addresses, and rebinds Spotify's imports of sendto, sendmsg and recvfrom+// SGConnectRelay.m a Connect query whose multicast send failed is sent again by unicast to each+// receiver's mDNS port from a socket of the mod's own; each answer is passed on+// to Spotify's socket over loopback, and Spotify's recvfrom is told it came from+// the receiver, so Spotify's own discovery goes on unchanged+// SGMDNS.m the checks on the packets, bounds-checked against what the network sends+//+// No setting: with the entitlement the real send works and nothing is relayed, and with Local Network+// denied Bonjour finds nothing to send to. Checked on the Mac against harness/connect/.+#import <Foundation/Foundation.h>+#import <sys/socket.h>++// The mDNS port, and the longest datagram either check reads.+#define SGMDNSPort 5353+#define SGMDNSMaxLength 9000++// A standard query (QR clear, opcode 0) of 1 to 40 questions, at least one of them for a name under+// _spotify-connect._tcp.local (a subtype too).+BOOL SGMDNSIsConnectQuery(const uint8_t *packet, size_t length);++// An answer to the query of that transaction ID: QR set, opcode 0, not truncated, RCODE 0, 1 to 400+// records that all decode, and at least one class IN record owned by a Connect name, or a PTR to one.+BOOL SGMDNSIsConnectReply(const uint8_t *packet, size_t length, uint16_t queryID);++// The browser's addresses for one receiver, each a struct sockaddr_in or sockaddr_in6 with the mDNS+// port; nil or empty forgets the receiver.+void SGConnectSetReceiver(NSString *name, NSArray<NSData *> *addresses);+// Every receiver's addresses, from any thread.+NSArray<NSData *> *SGConnectReceiverAddresses(void);+// The address's IP as text, for the log.+NSString *SGConnectAddressText(const struct sockaddr *address);++// Starts a relay round for this query sent on `socket` (Spotify's), unless one for the same socket and+// bytes is running or four are. Returns NO when the socket is not one a round can answer: not UDP,+// connected, or with no local port.+BOOL SGConnectRelayQuery(int socket, const void *query, size_t length);++// The replacements Connect.x rebinds Spotify's imports to.+ssize_t SGConnectSendto(int socket, const void *buffer, size_t length, int flags, const struct sockaddr *to, socklen_t toLength);+ssize_t SGConnectSendmsg(int socket, const struct msghdr *message, int flags);+ssize_t SGConnectRecvfrom(int socket, void *buffer, size_t length, int flags, struct sockaddr *from, socklen_t *fromLength);+// Where they find the system's functions; Connect.x fills these through SGRebindImport, and while one+// is NULL the replacement calls the system's own.+extern ssize_t (*SGConnectRealSendto)(int, const void *, size_t, int, const struct sockaddr *, socklen_t);+extern ssize_t (*SGConnectRealSendmsg)(int, const struct msghdr *, int);+extern ssize_t (*SGConnectRealRecvfrom)(int, void *, size_t, int, struct sockaddr *, socklen_t *);diff --git a/tweak/Sources/Shared/Connect/Connect.x b/tweak/Sources/Shared/Connect/Connect.xnew file mode 100644index 00000000..5e52a7ce--- /dev/null+++ b/tweak/Sources/Shared/Connect/Connect.x@@ -0,0 +1,146 @@+// Connect receivers found with Bonjour for the relay (Connect.h), and Spotify's imports of sendto,+// sendmsg and recvfrom rebound to it. The browse runs from launch on the main thread, so the receivers+// are known by the time Spotify asks; each one found is resolved to its addresses, kept with the mDNS+// port in place of the service's own, and forgotten when Bonjour says it went.+#import <arpa/inet.h>+#import <netinet/in.h>+#import "Core/SGLog.h"+#import "Core/SGRebind.h"+#import "Connect.h"++// A resolve that fails or finds nothing to send to is tried again kFirstRetry later, doubling up to+// kLastRetry; a browse that fails starts again after kBrowseRetry.+static const NSTimeInterval kResolveTimeout = 5, kFirstRetry = 2, kLastRetry = 30, kBrowseRetry = 3;++// The address with the mDNS port, or nil for one no query can go to: unspecified, loopback, multicast.+static NSData *queryAddress(NSData *data) {+ if (data.length >= sizeof(struct sockaddr_in) && ((const struct sockaddr *)data.bytes)->sa_family == AF_INET) {+ struct sockaddr_in v4;+ memcpy(&v4, data.bytes, sizeof v4);+ uint32_t ip = ntohl(v4.sin_addr.s_addr);+ if (ip == INADDR_ANY || ip >> 24 == IN_LOOPBACKNET || IN_MULTICAST(ip)) return nil;+ v4.sin_len = sizeof v4;+ v4.sin_port = htons(SGMDNSPort);+ return [NSData dataWithBytes:&v4 length:sizeof v4];+ }+ if (data.length >= sizeof(struct sockaddr_in6) && ((const struct sockaddr *)data.bytes)->sa_family == AF_INET6) {+ struct sockaddr_in6 v6;+ memcpy(&v6, data.bytes, sizeof v6);+ if (IN6_IS_ADDR_UNSPECIFIED(&v6.sin6_addr) || IN6_IS_ADDR_LOOPBACK(&v6.sin6_addr) || IN6_IS_ADDR_MULTICAST(&v6.sin6_addr)) return nil;+ v6.sin6_len = sizeof v6;+ v6.sin6_port = htons(SGMDNSPort);+ return [NSData dataWithBytes:&v6 length:sizeof v6];+ }+ return nil;+}++@interface SGConnectBrowser : NSObject <NSNetServiceBrowserDelegate, NSNetServiceDelegate>+- (void)start;+@end++@implementation SGConnectBrowser {+ NSNetServiceBrowser *_browser;+ NSMutableDictionary<NSString *, NSNetService *> *_services;+ NSMutableDictionary<NSString *, NSNumber *> *_retries;+}++- (void)start {+ _services = [NSMutableDictionary dictionary];+ _retries = [NSMutableDictionary dictionary];+ _browser = [NSNetServiceBrowser new];+ _browser.delegate = self;+ [_browser searchForServicesOfType:@"_spotify-connect._tcp." inDomain:@"local."];+}++- (void)forget:(NSString *)name {+ NSNetService *service = _services[name];+ service.delegate = nil;+ [service stop];+ [_services removeObjectForKey:name];+ [_retries removeObjectForKey:name];+ SGConnectSetReceiver(name, nil);+}++- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindService:(NSNetService *)service moreComing:(BOOL)moreComing {+ if (_services[service.name] == service) return;+ [self forget:service.name];+ _services[service.name] = service;+ service.delegate = self;+ [service resolveWithTimeout:kResolveTimeout];+}++- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didRemoveService:(NSNetService *)service moreComing:(BOOL)moreComing {+ [self forget:service.name];+}++- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didNotSearch:(NSDictionary<NSString *, NSNumber *> *)error {+ SGLog(@"connect: Bonjour browse failed (%@), again in %.0f s", error[NSNetServicesErrorCode], kBrowseRetry);+ _browser.delegate = nil;+ [_browser stop];+ for (NSString *name in _services.allKeys) [self forget:name];+ __weak SGConnectBrowser *weakSelf = self;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kBrowseRetry * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ [weakSelf start];+ });+}++// Called again as more of a receiver's addresses come in, each time with all of them.+- (void)netServiceDidResolveAddress:(NSNetService *)service {+ if (_services[service.name] != service) return;+ NSMutableArray<NSData *> *addresses = [NSMutableArray array];+ NSMutableArray<NSString *> *texts = [NSMutableArray array];+ for (NSData *data in service.addresses) {+ NSData *address = queryAddress(data);+ if (!address || [addresses containsObject:address]) continue;+ [addresses addObject:address];+ [texts addObject:SGConnectAddressText(address.bytes)];+ }+ if (!addresses.count) {+ [self retry:service];+ return;+ }+ [_retries removeObjectForKey:service.name];+ SGConnectSetReceiver(service.name, addresses);+ SGLog(@"connect: %@ at %@", service.name, [texts componentsJoinedByString:@", "]);+}++- (void)netService:(NSNetService *)service didNotResolve:(NSDictionary<NSString *, NSNumber *> *)error {+ if (_services[service.name] == service) [self retry:service];+}++- (void)retry:(NSNetService *)service {+ NSString *name = service.name;+ NSNumber *last = _retries[name];+ NSTimeInterval delay = last ? MIN(last.doubleValue * 2, kLastRetry) : kFirstRetry;+ _retries[name] = @(delay);+ __weak SGConnectBrowser *weakSelf = self;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ SGConnectBrowser *browser = weakSelf;+ if (!browser || browser->_services[name] != service) return;+ [service stop];+ [service resolveWithTimeout:kResolveTimeout];+ });+}++@end++static SGConnectBrowser *sg_browser;++%ctor {+ // recvfrom first: without it the receivers' answers would reach Spotify from loopback, so nothing+ // is relayed at all.+ if (!SGRebindImport("recvfrom", SGConnectRecvfrom, (void **)&SGConnectRealRecvfrom) || !SGConnectRealRecvfrom) {+ SGLog(@"connect: Spotify does not import recvfrom, Connect discovery is Spotify's own");+ return;+ }+ BOOL sends = SGRebindImport("sendto", SGConnectSendto, (void **)&SGConnectRealSendto);+ BOOL messages = SGRebindImport("sendmsg", SGConnectSendmsg, (void **)&SGConnectRealSendmsg);+ if (!sends && !messages) {+ SGLog(@"connect: Spotify imports neither sendto nor sendmsg, Connect discovery is Spotify's own");+ return;+ }+ dispatch_async(dispatch_get_main_queue(), ^{+ sg_browser = [SGConnectBrowser new];+ [sg_browser start];+ });+}diff --git a/tweak/Sources/Shared/Connect/SGConnectRelay.m b/tweak/Sources/Shared/Connect/SGConnectRelay.mnew file mode 100644index 00000000..0db3c329--- /dev/null+++ b/tweak/Sources/Shared/Connect/SGConnectRelay.m@@ -0,0 +1,357 @@+// The relay of Connect.h. Spotify's multicast query, refused for want of the entitlement, is reported+// sent, and a round on a utility queue sends it by unicast to each receiver Bonjour found, at its mDNS+// port, from a socket of the mod's own per address family. A receiver answers a query from a port other+// than 5353 straight to that port (RFC 6762's legacy unicast), with the query's ID. Each answer that+// checks out is sent on over loopback to the local port of Spotify's socket, and recorded, so that when+// Spotify's recvfrom reads it there the source it is given is the receiver's rather than loopback's.+//+// A round knows Spotify's socket only by its number, its family and its port, read when it starts, so+// Spotify closing the socket halfway does it no harm: the loopback sends then just go nowhere.+#import <arpa/inet.h>+#import <errno.h>+#import <fcntl.h>+#import <netinet/in.h>+#import <os/lock.h>+#import <poll.h>+#import <stdatomic.h>+#import <string.h>+#import <time.h>+#import <unistd.h>+#import "Core/SGLog.h"+#import "Connect.h"++ssize_t (*SGConnectRealSendto)(int, const void *, size_t, int, const struct sockaddr *, socklen_t);+ssize_t (*SGConnectRealSendmsg)(int, const struct msghdr *, int);+ssize_t (*SGConnectRealRecvfrom)(int, void *, size_t, int, struct sockaddr *, socklen_t *);++// A round ends after kRoundLength, after kQuietRoundLength having sent nothing, after kQuietRoundLength+// once nothing has been sent for kSendGap, or after kMaxReplies answers. Answers handed over are kept for+// recvfrom kRecordLife at most, kMaxRecords of them.+static const uint64_t kMillisecond = NSEC_PER_MSEC;+static const uint64_t kRoundLength = 1200 * kMillisecond, kQuietRoundLength = 700 * kMillisecond, kSendGap = 450 * kMillisecond;+static const uint64_t kRecordLife = 15 * NSEC_PER_SEC;+enum { kMaxRounds = 4, kMaxAddresses = 64, kMaxReplies = 32, kMaxRecords = 64 };++static uint64_t now(void) { return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW); }++static os_unfair_lock sg_lock = OS_UNFAIR_LOCK_INIT;++#pragma mark - receivers++static NSMutableDictionary<NSString *, NSArray<NSData *> *> *sg_receivers;++void SGConnectSetReceiver(NSString *name, NSArray<NSData *> *addresses) {+ if (!name) return;+ NSArray<NSData *> *kept = addresses.count ? [addresses copy] : nil;+ os_unfair_lock_lock(&sg_lock);+ if (!sg_receivers) sg_receivers = [NSMutableDictionary dictionary];+ sg_receivers[name] = kept;+ os_unfair_lock_unlock(&sg_lock);+}++NSArray<NSData *> *SGConnectReceiverAddresses(void) {+ NSMutableArray<NSData *> *all = [NSMutableArray array];+ os_unfair_lock_lock(&sg_lock);+ for (NSArray<NSData *> *addresses in sg_receivers.allValues) [all addObjectsFromArray:addresses];+ os_unfair_lock_unlock(&sg_lock);+ return all;+}++#pragma mark - addresses++static socklen_t lengthOf(int family) {+ return family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);+}++static BOOL sameAddress(const struct sockaddr *a, const struct sockaddr *b) {+ if (a->sa_family != b->sa_family) return NO;+ if (a->sa_family == AF_INET) {+ const struct sockaddr_in *x = (const void *)a, *y = (const void *)b;+ return x->sin_port == y->sin_port && x->sin_addr.s_addr == y->sin_addr.s_addr;+ }+ const struct sockaddr_in6 *x = (const void *)a, *y = (const void *)b;+ // A scope is left out by whoever does not know it; two that are known have to agree.+ BOOL scopes = !x->sin6_scope_id || !y->sin6_scope_id || x->sin6_scope_id == y->sin6_scope_id;+ return x->sin6_port == y->sin6_port && scopes && memcmp(&x->sin6_addr, &y->sin6_addr, sizeof x->sin6_addr) == 0;+}++static BOOL isLoopback(const struct sockaddr *address, socklen_t length) {+ if (address->sa_family == AF_INET && length >= sizeof(struct sockaddr_in)) {+ return ((const struct sockaddr_in *)address)->sin_addr.s_addr == htonl(INADDR_LOOPBACK);+ }+ if (address->sa_family != AF_INET6 || length < sizeof(struct sockaddr_in6)) return NO;+ const struct in6_addr *ip = &((const struct sockaddr_in6 *)address)->sin6_addr;+ return IN6_IS_ADDR_LOOPBACK(ip) || (IN6_IS_ADDR_V4MAPPED(ip) && ip->s6_addr[12] == 127 && ip->s6_addr[15] == 1);+}++// 224.0.0.251:5353 or [ff02::fb]:5353.+static BOOL isMDNSGroup(const struct sockaddr *to, socklen_t length) {+ if (!to) return NO;+ if (to->sa_family == AF_INET && length >= sizeof(struct sockaddr_in)) {+ const struct sockaddr_in *v4 = (const void *)to;+ return v4->sin_port == htons(SGMDNSPort) && v4->sin_addr.s_addr == htonl(0xE00000FB);+ }+ if (to->sa_family != AF_INET6 || length < sizeof(struct sockaddr_in6)) return NO;+ const struct sockaddr_in6 *v6 = (const void *)to;+ static const uint8_t group[16] = {0xFF, 0x02, [15] = 0xFB};+ return v6->sin6_port == htons(SGMDNSPort) && memcmp(&v6->sin6_addr, group, sizeof group) == 0;+}++NSString *SGConnectAddressText(const struct sockaddr *address) {+ char text[INET6_ADDRSTRLEN] = "?";+ const void *ip = address->sa_family == AF_INET6 ? (const void *)&((const struct sockaddr_in6 *)address)->sin6_addr+ : (const void *)&((const struct sockaddr_in *)address)->sin_addr;+ inet_ntop(address->sa_family, ip, text, sizeof text);+ return @(text);+}++#pragma mark - answers handed over++typedef struct {+ int socket;+ uint64_t made;+ uint8_t *bytes;+ size_t length;+ struct sockaddr_storage from;+} Record;++static Record sg_records[kMaxRecords];+static int sg_recordCount;+// recvfrom's fast path: nothing to look at unless an answer was handed over in the last kRecordLife.+static _Atomic uint64_t sg_lastRecord;++static void dropRecord(int index) {+ free(sg_records[index].bytes);+ sg_records[index] = sg_records[--sg_recordCount];+}++static void dropExpired(uint64_t time) {+ for (int i = sg_recordCount - 1; i >= 0; i--) {+ if (sg_records[i].made + kRecordLife < time) dropRecord(i); // made may be later than time, from another thread+ }+}++static void handOver(int spotify, const uint8_t *reply, size_t length, const struct sockaddr_storage *from, int sender, const struct sockaddr_storage *loopback) {+ uint8_t *bytes = malloc(length);+ if (!bytes) return;+ memcpy(bytes, reply, length);+ uint64_t time = now();+ os_unfair_lock_lock(&sg_lock);+ dropExpired(time);+ if (sg_recordCount == kMaxRecords) dropRecord(0);+ sg_records[sg_recordCount++] = (Record){spotify, time, bytes, length, *from};+ atomic_store(&sg_lastRecord, time);+ os_unfair_lock_unlock(&sg_lock);++ if (sendto(sender, reply, length, 0, (const struct sockaddr *)loopback, loopback->ss_len) >= 0) {+ SGLog(@"connect: relayed %zu bytes from %@", length, SGConnectAddressText((const struct sockaddr *)from));+ return;+ }+ os_unfair_lock_lock(&sg_lock);+ for (int i = 0; i < sg_recordCount; i++) {+ if (sg_records[i].bytes == bytes) {+ dropRecord(i);+ break;+ }+ }+ os_unfair_lock_unlock(&sg_lock);+}++// The receiver's address in place of loopback's for an answer read on `socket`, in the family the socket+// reported (an IPv4 receiver as ::ffff:a.b.c.d to an IPv6 socket).+static void fixSource(int socket, const void *buffer, size_t length, int flags, struct sockaddr *from, socklen_t *fromLength) {+ struct sockaddr_storage real = {0};+ BOOL found = NO;+ os_unfair_lock_lock(&sg_lock);+ dropExpired(now());+ for (int i = 0; i < sg_recordCount; i++) {+ Record *record = &sg_records[i];+ if (record->socket != socket || record->length != length || memcmp(record->bytes, buffer, length) != 0) continue;+ real = record->from;+ found = YES;+ if (!(flags & MSG_PEEK)) dropRecord(i);+ break;+ }+ os_unfair_lock_unlock(&sg_lock);+ if (!found) return;++ struct sockaddr_storage reported = {0};+ if (from->sa_family == real.ss_family) {+ reported = real;+ } else if (from->sa_family == AF_INET6 && real.ss_family == AF_INET) {+ struct sockaddr_in6 *mapped = (struct sockaddr_in6 *)&reported;+ const struct sockaddr_in *v4 = (const struct sockaddr_in *)ℜ+ mapped->sin6_len = sizeof *mapped;+ mapped->sin6_family = AF_INET6;+ mapped->sin6_port = v4->sin_port;+ mapped->sin6_addr.s6_addr[10] = mapped->sin6_addr.s6_addr[11] = 0xFF;+ memcpy(&mapped->sin6_addr.s6_addr[12], &v4->sin_addr, 4);+ } else {+ return;+ }+ socklen_t size = lengthOf(reported.ss_family);+ memcpy(from, &reported, MIN(*fromLength, size));+ *fromLength = size;+}++#pragma mark - rounds++static NSMutableSet<NSData *> *sg_rounds;++static int openSocket(int family) {+ int s = socket(family, SOCK_DGRAM, IPPROTO_UDP);+ if (s < 0) return -1;+ int on = 1;+ setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof on);+ if (family == AF_INET6) setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof on);+ fcntl(s, F_SETFL, fcntl(s, F_GETFL) | O_NONBLOCK);+ return s;+}++static void runRound(int spotify, int family, in_port_t port, NSData *query) {+ // An IPv4 socket cannot be told an IPv6 source, so it hears from IPv4 receivers only.+ int sockets[2] = {openSocket(AF_INET), family == AF_INET6 ? openSocket(AF_INET6) : -1};+ int sender = sockets[family == AF_INET6];+ struct sockaddr_storage loopback = {0};+ if (family == AF_INET6) {+ struct sockaddr_in6 *to = (struct sockaddr_in6 *)&loopback;+ *to = (struct sockaddr_in6){.sin6_len = sizeof *to, .sin6_family = AF_INET6, .sin6_port = port, .sin6_addr = in6addr_loopback};+ } else {+ struct sockaddr_in *to = (struct sockaddr_in *)&loopback;+ *to = (struct sockaddr_in){.sin_len = sizeof *to, .sin_family = AF_INET, .sin_port = port, .sin_addr.s_addr = htonl(INADDR_LOOPBACK)};+ }++ const uint8_t *bytes = query.bytes;+ uint16_t queryID = (uint16_t)(bytes[0] << 8 | bytes[1]);+ struct sockaddr_storage sent[kMaxAddresses];+ int sentCount = 0, replies = 0;+ uint64_t start = now(), lastSend = 0;+ uint8_t buffer[SGMDNSMaxLength + 1];++ while (sender >= 0) {+ // Receivers resolved while the round runs are sent to as well.+ for (NSData *address in SGConnectReceiverAddresses()) {+ if (sentCount == kMaxAddresses) break;+ const struct sockaddr *to = address.bytes;+ if (address.length < lengthOf(to->sa_family)) continue;+ int s = sockets[to->sa_family == AF_INET6];+ BOOL known = NO;+ for (int i = 0; i < sentCount && !known; i++) known = sameAddress((const struct sockaddr *)&sent[i], to);+ if (s < 0 || known) continue;+ memcpy(&sent[sentCount++], to, lengthOf(to->sa_family));+ if (sendto(s, bytes, query.length, 0, to, lengthOf(to->sa_family)) >= 0) lastSend = now();+ }++ uint64_t time = now(), elapsed = time - start;+ if (elapsed >= kRoundLength || replies >= kMaxReplies) break;+ if (elapsed >= kQuietRoundLength && (!lastSend || time - lastSend >= kSendGap)) break;++ struct pollfd ready[2] = {{sockets[0], POLLIN, 0}, {sockets[1], POLLIN, 0}};+ if (poll(ready, 2, 50) <= 0) continue;+ for (int k = 0; k < 2; k++) {+ if (!(ready[k].revents & POLLIN)) continue;+ while (replies < kMaxReplies) {+ struct sockaddr_storage from = {0};+ struct iovec part = {buffer, sizeof buffer};+ struct msghdr message = {.msg_name = &from, .msg_namelen = sizeof from, .msg_iov = &part, .msg_iovlen = 1};+ ssize_t length = recvmsg(sockets[k], &message, 0);+ if (length < 0) break;+ if (message.msg_flags & MSG_TRUNC || length > SGMDNSMaxLength) continue;+ BOOL known = NO;+ for (int i = 0; i < sentCount && !known; i++) known = sameAddress((const struct sockaddr *)&sent[i], (const struct sockaddr *)&from);+ if (!known || !SGMDNSIsConnectReply(buffer, (size_t)length, queryID)) continue;+ replies++;+ handOver(spotify, buffer, (size_t)length, &from, sender, &loopback);+ }+ }+ }+ for (int k = 0; k < 2; k++) {+ if (sockets[k] >= 0) close(sockets[k]);+ }+}++BOOL SGConnectRelayQuery(int socket, const void *query, size_t length) {+ int type = 0;+ socklen_t typeLength = sizeof type;+ if (getsockopt(socket, SOL_SOCKET, SO_TYPE, &type, &typeLength) != 0 || type != SOCK_DGRAM) return NO;+ struct sockaddr_storage address;+ socklen_t addressLength = sizeof address;+ if (getpeername(socket, (struct sockaddr *)&address, &addressLength) == 0 || errno != ENOTCONN) return NO;+ addressLength = sizeof address;+ if (getsockname(socket, (struct sockaddr *)&address, &addressLength) != 0) return NO;+ in_port_t port;+ if (address.ss_family == AF_INET) port = ((struct sockaddr_in *)&address)->sin_port;+ else if (address.ss_family == AF_INET6) port = ((struct sockaddr_in6 *)&address)->sin6_port;+ else return NO;+ if (!port) return NO;++ NSData *bytes = [NSData dataWithBytes:query length:length];+ NSMutableData *key = [NSMutableData dataWithBytes:&socket length:sizeof socket];+ [key appendData:bytes];+ os_unfair_lock_lock(&sg_lock);+ if (!sg_rounds) sg_rounds = [NSMutableSet set];+ BOOL start = sg_rounds.count < kMaxRounds && ![sg_rounds containsObject:key];+ if (start) [sg_rounds addObject:key];+ os_unfair_lock_unlock(&sg_lock);+ if (!start) return YES;++ int family = address.ss_family;+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{+ runRound(socket, family, port, bytes);+ os_unfair_lock_lock(&sg_lock);+ [sg_rounds removeObject:key];+ os_unfair_lock_unlock(&sg_lock);+ });+ return YES;+}++#pragma mark - the replacements++// The errors a send to the multicast group meets without the entitlement.+static BOOL refusedMulticast(int error) {+ return error == EACCES || error == EPERM || error == ENETUNREACH || error == EHOSTUNREACH || error == EADDRNOTAVAIL;+}++ssize_t SGConnectSendto(int socket, const void *buffer, size_t length, int flags, const struct sockaddr *to, socklen_t toLength) {+ ssize_t sent = (SGConnectRealSendto ?: sendto)(socket, buffer, length, flags, to, toLength);+ if (sent >= 0) return sent;+ int error = errno;+ BOOL relayed = refusedMulticast(error) && isMDNSGroup(to, toLength) && SGMDNSIsConnectQuery(buffer, length)+ && SGConnectRelayQuery(socket, buffer, length);+ errno = error;+ return relayed ? (ssize_t)length : sent;+}++// The message's parts gathered and relayed: their length, or -1. Out of line, so the buffer is no part+// of the frame of every sendmsg Spotify makes.+__attribute__((noinline)) static ssize_t relayMessage(int socket, const struct msghdr *message) {+ uint8_t packet[SGMDNSMaxLength];+ size_t length = 0;+ for (int i = 0; i < message->msg_iovlen; i++) {+ const struct iovec *part = &message->msg_iov[i];+ if (part->iov_len > sizeof packet - length) return -1;+ if (part->iov_len) memcpy(packet + length, part->iov_base, part->iov_len);+ length += part->iov_len;+ }+ return SGMDNSIsConnectQuery(packet, length) && SGConnectRelayQuery(socket, packet, length) ? (ssize_t)length : -1;+}++ssize_t SGConnectSendmsg(int socket, const struct msghdr *message, int flags) {+ ssize_t sent = (SGConnectRealSendmsg ?: sendmsg)(socket, message, flags);+ if (sent >= 0 || !message || !message->msg_iov) return sent;+ int error = errno;+ ssize_t relayed = refusedMulticast(error) && isMDNSGroup(message->msg_name, message->msg_namelen) ? relayMessage(socket, message) : -1;+ errno = error;+ return relayed >= 0 ? relayed : sent;+}++ssize_t SGConnectRecvfrom(int socket, void *buffer, size_t length, int flags, struct sockaddr *from, socklen_t *fromLength) {+ ssize_t received = (SGConnectRealRecvfrom ?: recvfrom)(socket, buffer, length, flags, from, fromLength);+ if (received < 0 || !from || !fromLength || !buffer) return received;+ uint64_t last = atomic_load(&sg_lastRecord);+ if (!last || now() - last > kRecordLife) return received;+ int error = errno;+ if (isLoopback(from, *fromLength)) fixSource(socket, buffer, (size_t)received, flags, from, fromLength);+ errno = error;+ return received;+}diff --git a/tweak/Sources/Shared/Connect/SGMDNS.m b/tweak/Sources/Shared/Connect/SGMDNS.mnew file mode 100644index 00000000..34d8f1f7--- /dev/null+++ b/tweak/Sources/Shared/Connect/SGMDNS.m@@ -0,0 +1,105 @@+// The mDNS packet checks of Connect.h, in plain C over the bytes as they came: every read is checked+// against the packet's end, a name follows at most 32 compression pointers, and a name is matched by+// its labels, since an instance name may itself hold dots.+#import <strings.h>+#import "Connect.h"++enum { kHeader = 12, kMaxQuestions = 40, kMaxRecords = 400, kMaxLabels = 128, kMaxHops = 32 };++static uint16_t read16(const uint8_t *p) { return (uint16_t)(p[0] << 8 | p[1]); }++typedef struct {+ const uint8_t *label[kMaxLabels];+ uint8_t length[kMaxLabels];+ size_t count;+} Name;++// Reads the name at *offset into `name` and moves *offset past it, which for a compressed name is past+// its first pointer. NO for a name that runs off the packet, loops, or is longer than DNS allows.+static BOOL readName(const uint8_t *packet, size_t length, size_t *offset, Name *name) {+ size_t at = *offset, end = 0, total = 0, hops = 0;+ BOOL jumped = NO;+ name->count = 0;+ while (YES) {+ if (at >= length) return NO;+ uint8_t byte = packet[at];+ if ((byte & 0xC0) == 0xC0) {+ if (at + 1 >= length || ++hops > kMaxHops) return NO;+ if (!jumped) end = at + 2;+ jumped = YES;+ at = (size_t)(byte & 0x3F) << 8 | packet[at + 1];+ continue;+ }+ if (byte & 0xC0) return NO; // the 0x40 and 0x80 label types are not in use+ if (byte == 0) {+ if (!jumped) end = at + 1;+ break;+ }+ total += byte + 1;+ if (at + 1 + byte > length || total > 255 || name->count == kMaxLabels) return NO;+ name->label[name->count] = packet + at + 1;+ name->length[name->count++] = byte;+ at += 1 + byte;+ }+ *offset = end;+ return YES;+}++static BOOL labelIs(const Name *name, size_t fromEnd, const char *text) {+ size_t index = name->count - 1 - fromEnd, length = strlen(text);+ return name->length[index] == length && strncasecmp((const char *)name->label[index], text, length) == 0;+}++// _spotify-connect._tcp.local, or a name under it (an instance, a subtype).+static BOOL isConnectName(const Name *name) {+ return name->count >= 3 && labelIs(name, 0, "local") && labelIs(name, 1, "_tcp") && labelIs(name, 2, "_spotify-connect");+}++BOOL SGMDNSIsConnectQuery(const uint8_t *packet, size_t length) {+ if (!packet || length < kHeader || length > SGMDNSMaxLength) return NO;+ uint16_t flags = read16(packet + 2), questions = read16(packet + 4);+ if (flags & 0x8000 || (flags >> 11 & 0xF) != 0 || questions == 0 || questions > kMaxQuestions) return NO;+ size_t offset = kHeader;+ BOOL connect = NO;+ for (uint16_t i = 0; i < questions; i++) {+ Name name;+ if (!readName(packet, length, &offset, &name) || offset + 4 > length) return NO;+ offset += 4;+ connect = connect || isConnectName(&name);+ }+ return connect;+}++BOOL SGMDNSIsConnectReply(const uint8_t *packet, size_t length, uint16_t queryID) {+ if (!packet || length < kHeader || length > SGMDNSMaxLength || read16(packet) != queryID) return NO;+ uint16_t flags = read16(packet + 2);+ // QR set, opcode 0, TC clear, RCODE 0.+ if (!(flags & 0x8000) || (flags >> 11 & 0xF) != 0 || flags & 0x0200 || (flags & 0xF) != 0) return NO;+ size_t questions = read16(packet + 4);+ size_t records = (size_t)read16(packet + 6) + read16(packet + 8) + read16(packet + 10);+ if (questions > kMaxQuestions || records == 0 || records > kMaxRecords) return NO;+ size_t offset = kHeader;+ Name name;+ for (size_t i = 0; i < questions; i++) {+ if (!readName(packet, length, &offset, &name) || offset + 4 > length) return NO;+ offset += 4;+ }+ BOOL connect = NO;+ for (size_t i = 0; i < records; i++) {+ if (!readName(packet, length, &offset, &name) || offset + 10 > length) return NO;+ // The top bit of the class is mDNS's cache flush.+ uint16_t type = read16(packet + offset);+ BOOL in = (read16(packet + offset + 2) & 0x7FFF) == 1;+ size_t data = offset + 10, dataLength = read16(packet + offset + 8);+ if (data + dataLength > length) return NO;+ if (in && isConnectName(&name)) connect = YES;+ if (type == 12) {+ size_t target = data;+ Name pointed;+ if (!readName(packet, length, &target, &pointed) || target > data + dataLength) return NO;+ if (in && isConnectName(&pointed)) connect = YES;+ }+ offset = data + dataLength;+ }+ return connect;+}