mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-06 17:00:41 +08:00
534 lines
15 KiB
C
534 lines
15 KiB
C
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// Guest side of test/bluetooth.test.ts: drives hci0 (kwbt) on raw
|
|
// AF_BLUETOOTH sockets, without BlueZ: the kernel's management interface
|
|
// (HCI_CHANNEL_CONTROL) to power the adapter and to discover LE devices,
|
|
// then an L2CAP socket on the ATT fixed channel (CID 4), on which it is the
|
|
// GATT client of the host's emulated controller (js/core/bluetooth-le.ts)
|
|
// and its fake peripheral (FakeGattCentral's demo device). Static aarch64
|
|
// musl, built by the test:
|
|
//
|
|
// zig cc -target aarch64-linux-musl -mcpu=generic -static -O2 -s -o kwbt test/bluetooth/kwbt.c
|
|
//
|
|
// kwbt run ADDR [CPU] the whole sequence below, on CPU if given
|
|
// kwbt find ADDR power on and discover ADDR; "found ADDR" or exit 1
|
|
// kwbt park ADDR OUT connect, say "ready", block in recv(); then
|
|
// write what recv() returned to OUT
|
|
//
|
|
// `run` prints one line per check, "ok NAME ..." or "FAIL NAME: ...", and
|
|
// at each "step NAME" line waits for a line on stdin: the host acts (a
|
|
// notification, a remote disconnect, a detach, an attach) and answers. The
|
|
// last line is "done N failure(s)", exit 0 without one. The steps: power on,
|
|
// LE discovery (Device Found with the name and the flags), an LE connection
|
|
// through the socket's connect(), MTU exchange, primary service discovery,
|
|
// characteristic and descriptor discovery in the loopback service, read,
|
|
// write and read back, the CCCD and a write command looped back as a
|
|
// notification, a notification from the host, a remote disconnect (recv()
|
|
// fails), a reconnect, the adapter detached while connected (recv() fails,
|
|
// hci0 goes), and a new controller attached (hci0 comes back, and it all
|
|
// works again on it).
|
|
#define _GNU_SOURCE
|
|
#include <dirent.h>
|
|
#include <errno.h>
|
|
#include <poll.h>
|
|
#include <sched.h>
|
|
#include <stdarg.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
#define AF_BT 31
|
|
#define BTPROTO_L2CAP 0
|
|
#define BTPROTO_HCI 1
|
|
#define HCI_CHANNEL_CONTROL 3
|
|
#define HCI_DEV_NONE 0xffff
|
|
#define BDADDR_LE_PUBLIC 1
|
|
#define BDADDR_LE_RANDOM 2
|
|
#define ATT_CID 4
|
|
#define SOL_BLUETOOTH 274
|
|
#define BT_SECURITY 4
|
|
|
|
struct sockaddr_hci {
|
|
sa_family_t hci_family;
|
|
unsigned short hci_dev;
|
|
unsigned short hci_channel;
|
|
};
|
|
|
|
struct sockaddr_l2 {
|
|
sa_family_t l2_family;
|
|
unsigned short l2_psm;
|
|
uint8_t l2_bdaddr[6];
|
|
unsigned short l2_cid;
|
|
uint8_t l2_bdaddr_type;
|
|
};
|
|
|
|
static int failures;
|
|
|
|
static void say(const char *fmt, ...)
|
|
{
|
|
va_list ap;
|
|
|
|
va_start(ap, fmt);
|
|
vprintf(fmt, ap);
|
|
va_end(ap);
|
|
putchar('\n');
|
|
fflush(stdout);
|
|
}
|
|
|
|
#define CHECK(name, cond, ...) do { \
|
|
if (cond) say("ok " name); \
|
|
else { failures++; say("FAIL " name ": " __VA_ARGS__); } \
|
|
} while (0)
|
|
|
|
static void step(const char *name)
|
|
{
|
|
char line[64];
|
|
|
|
say("step %s", name);
|
|
if (!fgets(line, sizeof(line), stdin))
|
|
exit(2);
|
|
}
|
|
|
|
static double now(void)
|
|
{
|
|
struct timespec ts;
|
|
|
|
clock_gettime(CLOCK_MONOTONIC, &ts);
|
|
return ts.tv_sec + ts.tv_nsec / 1e9;
|
|
}
|
|
|
|
static int parse_addr(const char *s, uint8_t out[6])
|
|
{
|
|
unsigned int b[6];
|
|
|
|
if (sscanf(s, "%x:%x:%x:%x:%x:%x", &b[5], &b[4], &b[3], &b[2], &b[1], &b[0]) != 6)
|
|
return -1;
|
|
for (int i = 0; i < 6; i++)
|
|
out[i] = b[i];
|
|
return 0;
|
|
}
|
|
|
|
/* The first hciN in sysfs, or -1. */
|
|
static int hci_index(void)
|
|
{
|
|
DIR *d = opendir("/sys/class/bluetooth");
|
|
struct dirent *e;
|
|
int idx = -1;
|
|
|
|
if (!d)
|
|
return -1;
|
|
while ((e = readdir(d)))
|
|
if (!strncmp(e->d_name, "hci", 3) && e->d_name[3] >= '0' && e->d_name[3] <= '9' && !strchr(e->d_name, ':')) {
|
|
idx = atoi(e->d_name + 3);
|
|
break;
|
|
}
|
|
closedir(d);
|
|
return idx;
|
|
}
|
|
|
|
/* Wait until hci0 is there (want 1) or gone (want 0). */
|
|
static int wait_hci(int want, double secs)
|
|
{
|
|
for (double end = now() + secs; now() < end; usleep(50000))
|
|
if ((hci_index() >= 0) == want)
|
|
return 0;
|
|
return -1;
|
|
}
|
|
|
|
/* Management: a command and its Command Complete or Status; returns the status, or -1. */
|
|
static int mgmt_fd = -1;
|
|
|
|
static int mgmt_open(void)
|
|
{
|
|
struct sockaddr_hci a = { .hci_family = AF_BT, .hci_dev = HCI_DEV_NONE, .hci_channel = HCI_CHANNEL_CONTROL };
|
|
|
|
if (mgmt_fd >= 0)
|
|
close(mgmt_fd);
|
|
mgmt_fd = socket(AF_BT, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI);
|
|
if (mgmt_fd < 0 || bind(mgmt_fd, (struct sockaddr *)&a, sizeof(a)) < 0)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
|
|
/* Read one management event within ms; returns its length or -1. */
|
|
static int mgmt_event(uint8_t *buf, size_t max, int ms)
|
|
{
|
|
struct pollfd p = { .fd = mgmt_fd, .events = POLLIN };
|
|
|
|
if (poll(&p, 1, ms) <= 0)
|
|
return -1;
|
|
return read(mgmt_fd, buf, max);
|
|
}
|
|
|
|
static int mgmt_cmd(uint16_t op, uint16_t idx, const void *param, uint16_t len)
|
|
{
|
|
uint8_t buf[512];
|
|
int n;
|
|
|
|
buf[0] = op;
|
|
buf[1] = op >> 8;
|
|
buf[2] = idx;
|
|
buf[3] = idx >> 8;
|
|
buf[4] = len;
|
|
buf[5] = len >> 8;
|
|
memcpy(buf + 6, param, len);
|
|
/* A command refused at once (an error status) is written as 0 bytes. */
|
|
if (write(mgmt_fd, buf, 6 + len) < 0) {
|
|
say("# mgmt 0x%04x: write: %s", op, strerror(errno));
|
|
return -1;
|
|
}
|
|
for (double end = now() + 10; now() < end;) {
|
|
n = mgmt_event(buf, sizeof(buf), 1000);
|
|
if (n < 9)
|
|
continue;
|
|
uint16_t ev = buf[0] | buf[1] << 8, cop = buf[6] | buf[7] << 8;
|
|
if ((ev == 1 || ev == 2) && cop == op)
|
|
return buf[8];
|
|
}
|
|
say("# mgmt 0x%04x: no answer", op);
|
|
return -1;
|
|
}
|
|
|
|
/* Set Powered; an adapter still in its setup is an invalid index for a moment. */
|
|
static int power(int idx, int on)
|
|
{
|
|
uint8_t v = on;
|
|
int st;
|
|
|
|
for (double end = now() + 10;; usleep(100000)) {
|
|
st = mgmt_cmd(0x0005, idx, &v, 1);
|
|
if (st != 0x11 || now() > end)
|
|
return st;
|
|
}
|
|
}
|
|
|
|
/* LE discovery until ADDR shows up; fills its name. 0, or -1 on a timeout. */
|
|
static int discover(int idx, const uint8_t addr[6], char *name, size_t namelen)
|
|
{
|
|
uint8_t type = (1 << 1) | (1 << 2), buf[512];
|
|
int st, n, found = -1;
|
|
|
|
name[0] = 0;
|
|
st = mgmt_cmd(0x0023, idx, &type, 1);
|
|
if (st) {
|
|
say("# start discovery: status %d", st);
|
|
return -1;
|
|
}
|
|
for (double end = now() + 20; now() < end && found;) {
|
|
n = mgmt_event(buf, sizeof(buf), 1000);
|
|
if (n < 6 + 14 || (buf[0] | buf[1] << 8) != 0x0012)
|
|
continue;
|
|
if (memcmp(buf + 6, addr, 6))
|
|
continue;
|
|
found = 0;
|
|
/* The EIR: the name, if it is there. */
|
|
int eir = buf[6 + 12] | buf[6 + 13] << 8;
|
|
for (int i = 6 + 14; i + 1 < 6 + 14 + eir && i < n;) {
|
|
int l = buf[i], t = buf[i + 1];
|
|
if (!l)
|
|
break;
|
|
if ((t == 0x09 || t == 0x08) && (size_t)(l - 1) < namelen) {
|
|
memcpy(name, buf + i + 2, l - 1);
|
|
name[l - 1] = 0;
|
|
}
|
|
i += l + 1;
|
|
}
|
|
}
|
|
mgmt_cmd(0x0024, idx, &type, 1);
|
|
return found;
|
|
}
|
|
|
|
/* ATT over an L2CAP socket. */
|
|
static int att_connect(const uint8_t addr[6])
|
|
{
|
|
struct sockaddr_l2 local = { .l2_family = AF_BT, .l2_cid = ATT_CID, .l2_bdaddr_type = BDADDR_LE_PUBLIC };
|
|
struct sockaddr_l2 peer = { .l2_family = AF_BT, .l2_cid = ATT_CID, .l2_bdaddr_type = BDADDR_LE_RANDOM };
|
|
int s = socket(AF_BT, SOCK_SEQPACKET | SOCK_CLOEXEC, BTPROTO_L2CAP);
|
|
|
|
if (s < 0)
|
|
return -1;
|
|
memcpy(peer.l2_bdaddr, addr, 6);
|
|
if (bind(s, (struct sockaddr *)&local, sizeof(local)) < 0 ||
|
|
connect(s, (struct sockaddr *)&peer, sizeof(peer)) < 0) {
|
|
int e = errno;
|
|
close(s);
|
|
errno = e;
|
|
return -1;
|
|
}
|
|
return s;
|
|
}
|
|
|
|
/* The next PDU within ms that is not a notification (those go to *notif); length or -1. */
|
|
static uint8_t notif[600];
|
|
static int notif_len = -1;
|
|
|
|
static int att_recv(int s, uint8_t *buf, size_t max, int ms, int want_notif)
|
|
{
|
|
struct pollfd p = { .fd = s, .events = POLLIN };
|
|
double end = now() + ms / 1000.0;
|
|
|
|
for (;;) {
|
|
int left = (int)((end - now()) * 1000);
|
|
if (left < 0 || poll(&p, 1, left) <= 0)
|
|
return -1;
|
|
int n = recv(s, buf, max, 0);
|
|
if (n <= 0)
|
|
return n < 0 ? -1 : 0;
|
|
if (buf[0] == 0x1b && !want_notif) {
|
|
memcpy(notif, buf, n);
|
|
notif_len = n;
|
|
continue;
|
|
}
|
|
return n;
|
|
}
|
|
}
|
|
|
|
static int att_req(int s, const uint8_t *req, size_t len, uint8_t *rsp, size_t max)
|
|
{
|
|
if (send(s, req, len, 0) != (ssize_t)len)
|
|
return -1;
|
|
return att_recv(s, rsp, max, 10000, 0);
|
|
}
|
|
|
|
static uint16_t rd16(const uint8_t *b)
|
|
{
|
|
return b[0] | b[1] << 8;
|
|
}
|
|
|
|
/* The loopback service (7b6b0001-6b77-4274-8000-000000000001), little-endian. */
|
|
static const uint8_t LOOP_SVC[16] = { 1, 0, 0, 0, 0, 0, 0, 0x80, 0x74, 0x42, 0x77, 0x6b, 1, 0, 0x6b, 0x7b };
|
|
|
|
struct gatt {
|
|
int services;
|
|
uint16_t start, end; /* the loopback service */
|
|
uint16_t value, cccd; /* its characteristic's value and CCCD */
|
|
};
|
|
|
|
static int discover_gatt(int s, struct gatt *g)
|
|
{
|
|
uint8_t rsp[600];
|
|
int n;
|
|
|
|
memset(g, 0, sizeof(*g));
|
|
for (uint16_t start = 1;;) {
|
|
uint8_t req[] = { 0x10, start, start >> 8, 0xff, 0xff, 0x00, 0x28 };
|
|
n = att_req(s, req, sizeof(req), rsp, sizeof(rsp));
|
|
if (n < 2 || rsp[0] != 0x11)
|
|
break;
|
|
int len = rsp[1];
|
|
for (int i = 2; i + len <= n; i += len) {
|
|
g->services++;
|
|
if (len == 20 && !memcmp(rsp + i + 4, LOOP_SVC, 16)) {
|
|
g->start = rd16(rsp + i);
|
|
g->end = rd16(rsp + i + 2);
|
|
}
|
|
start = rd16(rsp + i + 2) + 1;
|
|
}
|
|
if (!start)
|
|
break;
|
|
}
|
|
if (!g->start)
|
|
return -1;
|
|
uint8_t chr[] = { 0x08, g->start, g->start >> 8, g->end, g->end >> 8, 0x03, 0x28 };
|
|
n = att_req(s, chr, sizeof(chr), rsp, sizeof(rsp));
|
|
if (n < 9 || rsp[0] != 0x09)
|
|
return -1;
|
|
g->value = rd16(rsp + 2 + 3);
|
|
uint8_t fi[] = { 0x04, (g->value + 1) & 0xff, (g->value + 1) >> 8, g->end, g->end >> 8 };
|
|
n = att_req(s, fi, sizeof(fi), rsp, sizeof(rsp));
|
|
if (n < 6 || rsp[0] != 0x05 || rsp[1] != 1)
|
|
return -1;
|
|
for (int i = 2; i + 4 <= n; i += 4)
|
|
if (rd16(rsp + i + 2) == 0x2902)
|
|
g->cccd = rd16(rsp + i);
|
|
return g->cccd ? 0 : -1;
|
|
}
|
|
|
|
static int att_read(int s, uint16_t h, char *out, size_t max)
|
|
{
|
|
uint8_t req[] = { 0x0a, h, h >> 8 }, rsp[600];
|
|
int n = att_req(s, req, sizeof(req), rsp, sizeof(rsp));
|
|
|
|
if (n < 1 || rsp[0] != 0x0b)
|
|
return n >= 5 && rsp[0] == 0x01 ? -rsp[4] : -1000;
|
|
n--;
|
|
if ((size_t)n >= max)
|
|
n = max - 1;
|
|
memcpy(out, rsp + 1, n);
|
|
out[n] = 0;
|
|
return n;
|
|
}
|
|
|
|
static int att_write(int s, uint16_t h, const void *v, size_t len, int cmd)
|
|
{
|
|
uint8_t req[600], rsp[64];
|
|
|
|
req[0] = cmd ? 0x52 : 0x12;
|
|
req[1] = h;
|
|
req[2] = h >> 8;
|
|
memcpy(req + 3, v, len);
|
|
if (cmd)
|
|
return send(s, req, 3 + len, 0) == (ssize_t)(3 + len) ? 0 : -1;
|
|
int n = att_req(s, req, 3 + len, rsp, sizeof(rsp));
|
|
return n >= 1 && rsp[0] == 0x13 ? 0 : -1;
|
|
}
|
|
|
|
/* A notification of `want` on handle h within ms. */
|
|
static int wait_notif(int s, uint16_t h, const char *want, int ms)
|
|
{
|
|
uint8_t buf[600];
|
|
int n;
|
|
|
|
if (notif_len < 0) {
|
|
n = att_recv(s, buf, sizeof(buf), ms, 1);
|
|
if (n < 3 || buf[0] != 0x1b)
|
|
return -1;
|
|
memcpy(notif, buf, n);
|
|
notif_len = n;
|
|
}
|
|
n = notif_len;
|
|
notif_len = -1;
|
|
return rd16(notif + 1) == h && n - 3 == (int)strlen(want) && !memcmp(notif + 3, want, n - 3) ? 0 : -1;
|
|
}
|
|
|
|
/* Power on, discover, connect, MTU, GATT discovery: the socket, or -1. */
|
|
static int bring_up(const uint8_t addr[6], const char *addrs, struct gatt *g, const char *tag)
|
|
{
|
|
char name[64];
|
|
int idx, s, n;
|
|
double t;
|
|
|
|
idx = hci_index();
|
|
CHECK("hci", idx >= 0, "no hciN in /sys/class/bluetooth (%s)", tag);
|
|
if (idx < 0 || mgmt_open() < 0)
|
|
return -1;
|
|
n = power(idx, 1);
|
|
CHECK("power on", n == 0, "status %d (%s)", n, tag);
|
|
t = now();
|
|
n = discover(idx, addr, name, sizeof(name));
|
|
CHECK("discovery", n == 0 && !strcmp(name, "unkernel fake"), "%s %s, name '%s' (%s)", addrs, n ? "not found" : "found", name, tag);
|
|
say("# discovered in %.2f s", now() - t);
|
|
t = now();
|
|
s = att_connect(addr);
|
|
CHECK("connect", s >= 0, "%s (%s)", strerror(errno), tag);
|
|
if (s < 0)
|
|
return -1;
|
|
say("# connected in %.2f s", now() - t);
|
|
uint8_t mtu[] = { 0x02, 0x05, 0x02 }, rsp[64];
|
|
n = att_req(s, mtu, sizeof(mtu), rsp, sizeof(rsp));
|
|
CHECK("mtu", n == 3 && rsp[0] == 0x03 && rd16(rsp + 1) == 517, "n %d op 0x%x (%s)", n, n > 0 ? rsp[0] : 0, tag);
|
|
n = discover_gatt(s, g);
|
|
CHECK("gatt", n == 0 && g->services == 5, "%d services, loopback %u-%u value %u cccd %u (%s)", g->services, g->start, g->end, g->value, g->cccd, tag);
|
|
return n ? -1 : s;
|
|
}
|
|
|
|
static int run(const uint8_t addr[6], const char *addrs)
|
|
{
|
|
struct gatt g;
|
|
char v[600];
|
|
int s, n;
|
|
|
|
s = bring_up(addr, addrs, &g, "first");
|
|
if (s < 0)
|
|
goto out;
|
|
n = att_read(s, g.value, v, sizeof(v));
|
|
CHECK("read", n == 5 && !strcmp(v, "hello"), "%d '%s'", n, n > 0 ? v : "");
|
|
n = att_write(s, g.value, "world", 5, 0);
|
|
CHECK("write", n == 0, "write request failed");
|
|
n = att_read(s, g.value, v, sizeof(v));
|
|
CHECK("read back", n == 5 && !strcmp(v, "world"), "%d '%s'", n, n > 0 ? v : "");
|
|
uint8_t on[] = { 1, 0 };
|
|
n = att_write(s, g.cccd, on, 2, 0);
|
|
CHECK("cccd", n == 0, "the CCCD write failed");
|
|
notif_len = -1;
|
|
n = att_write(s, g.value, "ping", 4, 1);
|
|
n = n ? n : wait_notif(s, g.value, "ping", 5000);
|
|
CHECK("loopback notification", n == 0, "no notification of ping");
|
|
step("notify");
|
|
n = wait_notif(s, g.value, "host", 5000);
|
|
CHECK("host notification", n == 0, "no notification of host");
|
|
|
|
step("remote-disconnect");
|
|
n = att_recv(s, (uint8_t *)v, sizeof(v), 10000, 1);
|
|
CHECK("remote disconnect", n <= 0 && (n == 0 || errno), "recv %d (%s)", n, strerror(errno));
|
|
say("# recv after the remote disconnect: %d %s", n, n < 0 ? strerror(errno) : "");
|
|
close(s);
|
|
s = att_connect(addr);
|
|
CHECK("reconnect", s >= 0, "%s", strerror(errno));
|
|
if (s < 0)
|
|
goto out;
|
|
n = att_read(s, g.value, v, sizeof(v));
|
|
CHECK("read after reconnect", n == 4 && !strcmp(v, "host"), "%d '%s'", n, n > 0 ? v : "");
|
|
|
|
step("detach");
|
|
n = att_recv(s, (uint8_t *)v, sizeof(v), 10000, 1);
|
|
CHECK("detached while connected", n <= 0, "recv %d", n);
|
|
say("# recv after the detach: %d %s", n, n < 0 ? strerror(errno) : "");
|
|
close(s);
|
|
n = wait_hci(0, 10);
|
|
CHECK("hci gone", n == 0, "hci%d still there", hci_index());
|
|
|
|
step("attach");
|
|
n = wait_hci(1, 10);
|
|
CHECK("hci back", n == 0, "no hciN after the attach");
|
|
s = bring_up(addr, addrs, &g, "new controller");
|
|
if (s < 0)
|
|
goto out;
|
|
n = att_read(s, g.value, v, sizeof(v));
|
|
CHECK("read on the new controller", n == 5 && !strcmp(v, "hello"), "%d '%s'", n, n > 0 ? v : "");
|
|
close(s);
|
|
out:
|
|
say("done %d failure(s)", failures);
|
|
return failures ? 1 : 0;
|
|
}
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
uint8_t addr[6];
|
|
|
|
if (argc < 3 || parse_addr(argv[2], addr)) {
|
|
fprintf(stderr, "usage: kwbt run ADDR [CPU] | find ADDR | park ADDR OUT\n");
|
|
return 2;
|
|
}
|
|
if (!strcmp(argv[1], "run")) {
|
|
if (argc > 3) {
|
|
cpu_set_t set;
|
|
CPU_ZERO(&set);
|
|
CPU_SET(atoi(argv[3]), &set);
|
|
if (sched_setaffinity(0, sizeof(set), &set))
|
|
say("FAIL affinity: %s", strerror(errno)), failures++;
|
|
}
|
|
return run(addr, argv[2]);
|
|
}
|
|
if (!strcmp(argv[1], "find")) {
|
|
char name[64];
|
|
int idx = hci_index();
|
|
if (idx < 0 || mgmt_open() < 0 || power(idx, 1) || discover(idx, addr, name, sizeof(name)))
|
|
return 1;
|
|
say("found %s %s", argv[2], name);
|
|
return 0;
|
|
}
|
|
if (!strcmp(argv[1], "park") && argc > 3) {
|
|
struct gatt g;
|
|
char v[64];
|
|
int s = bring_up(addr, argv[2], &g, "park");
|
|
if (s < 0)
|
|
return 1;
|
|
say("ready");
|
|
int n = recv(s, v, sizeof(v), 0);
|
|
int e = errno;
|
|
/* Made only now, so that the host sees it only with the result. */
|
|
FILE *f = fopen(argv[3], "w");
|
|
if (!f)
|
|
return 1;
|
|
fprintf(f, "recv %d %s\n", n, n < 0 ? strerror(e) : "-");
|
|
fclose(f);
|
|
return 0;
|
|
}
|
|
return 2;
|
|
}
|