diff --git a/main.go b/main.go index 44056cf..fc9b1f4 100644 --- a/main.go +++ b/main.go @@ -72,7 +72,9 @@ func main() { var attach func(*bluetooth.Ble) (bluetooth.Radio, error) switch *transport { case "ble": - attach = func(b *bluetooth.Ble) (bluetooth.Radio, error) { return bluetooth.NewGattRadio(b, state.Id, *hci) } + attach = func(b *bluetooth.Ble) (bluetooth.Radio, error) { + return bluetooth.NewGattRadio(b, state.Id, *hci, state.BleAddress) + } case "impossible": attach = func(b *bluetooth.Ble) (bluetooth.Radio, error) { return bluetooth.NewSimRadio(b, *socket, state.PeripheralID, state.Id) diff --git a/pkg/bluetooth/address.go b/pkg/bluetooth/address.go new file mode 100644 index 0000000..71c6597 --- /dev/null +++ b/pkg/bluetooth/address.go @@ -0,0 +1,46 @@ +package bluetooth + +import ( + "crypto/rand" + "fmt" +) + +// RandomStaticAddress makes a random static Bluetooth address, written most +// significant byte first, as in "C4:1F:22:9A:07:5E". Each fresh pod gets its +// own, as every real pod has its own address. A phone then treats a new pod as +// a new device, with nothing cached from the pod before it, which may have +// been the other kind with a different data characteristic. +func RandomStaticAddress() string { + var a [6]byte + for { + rand.Read(a[:]) + // The two most significant bits of a static address are both 1. + a[0] |= 0xC0 + // The rest of the address can be neither all 0s nor all 1s. + rest := a + rest[0] &^= 0xC0 + if rest != [6]byte{} && rest != [6]byte{0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} { + break + } + } + return formatAddress(a) +} + +func formatAddress(a [6]byte) string { + return fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", a[0], a[1], a[2], a[3], a[4], a[5]) +} + +// ParseStaticAddress reads an address written by RandomStaticAddress. +func ParseStaticAddress(s string) ([6]byte, error) { + var a [6]byte + if _, err := fmt.Sscanf(s, "%02X:%02X:%02X:%02X:%02X:%02X", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]); err != nil { + return a, fmt.Errorf("Bluetooth address %q: %w", s, err) + } + if formatAddress(a) != s { + return a, fmt.Errorf("Bluetooth address %q: want six hex bytes such as C4:1F:22:9A:07:5E", s) + } + if a[0]&0xC0 != 0xC0 { + return a, fmt.Errorf("Bluetooth address %q is not a static random address: its first byte must be C0 or above", s) + } + return a, nil +} diff --git a/pkg/bluetooth/address_test.go b/pkg/bluetooth/address_test.go new file mode 100644 index 0000000..cebbbdd --- /dev/null +++ b/pkg/bluetooth/address_test.go @@ -0,0 +1,43 @@ +package bluetooth + +import "testing" + +func TestRandomStaticAddressesAreStaticAndDiffer(t *testing.T) { + seen := map[string]bool{} + for i := 0; i < 100; i++ { + s := RandomStaticAddress() + a, err := ParseStaticAddress(s) + if err != nil { + t.Fatalf("RandomStaticAddress made %q, which doesn't parse: %s", s, err) + } + if a[0]&0xC0 != 0xC0 { + t.Fatalf("%s is not a static random address: the top two bits must be 1", s) + } + if seen[s] { + t.Fatalf("%s came up twice in 100 addresses", s) + } + seen[s] = true + } +} + +func TestParseStaticAddress(t *testing.T) { + a, err := ParseStaticAddress("C4:1F:22:9A:07:5E") + if err != nil { + t.Fatalf("a good address didn't parse: %s", err) + } + if a != [6]byte{0xC4, 0x1F, 0x22, 0x9A, 0x07, 0x5E} { + t.Fatalf("parsed as % X, want C4 1F 22 9A 07 5E", a) + } + + for _, bad := range []string{ + "", + "C4:1F:22:9A:07", // too short + "C4:1F:22:9A:07:5E:00", // too long + "c4:1f:22:9a:07:5e", // not as RandomStaticAddress writes it + "44:1F:22:9A:07:5E", // not a static random address + } { + if _, err := ParseStaticAddress(bad); err == nil { + t.Errorf("%q parsed, want an error", bad) + } + } +} diff --git a/pkg/bluetooth/gatt_linux.go b/pkg/bluetooth/gatt_linux.go index fa663ab..d9105a7 100644 --- a/pkg/bluetooth/gatt_linux.go +++ b/pkg/bluetooth/gatt_linux.go @@ -1,6 +1,7 @@ package bluetooth import ( + "bytes" "encoding/hex" "fmt" "sync" @@ -33,29 +34,66 @@ type gattRadio struct { } // ServerOptions is how the pod serves itself from adapter hci, or from -// the first one with LE support when n is negative. -func ServerOptions(hci int) []gatt.Option { +// the first one with LE support when n is negative. With randomAddress, it +// advertises from the random address set after the device is opened instead +// of the adapter's own address. +func ServerOptions(hci int, randomAddress bool) []gatt.Option { + var ownAddressType uint8 // 0x00: public + if randomAddress { + ownAddressType = 0x01 // random + } return []gatt.Option{ gatt.LnxMaxConnections(1), gatt.LnxDeviceID(hci, true), gatt.LnxSetAdvertisingParameters(&cmd.LESetAdvertisingParameters{ AdvertisingIntervalMin: 0x00f4, AdvertisingIntervalMax: 0x00f4, + OwnAddressType: ownAddressType, AdvertisingChannelMap: 0x7, }), } } +// setRandomAddress gives the adapter the pod's own address. Opening the device +// resets the adapter, which clears any random address, and the advertising +// parameters only go to the adapter when the pod first advertises. So this +// goes after gatt.NewDevice and before the first advertisement. +func setRandomAddress(d gatt.Device, address string) error { + a, err := ParseStaticAddress(address) + if err != nil { + return err + } + var rsp bytes.Buffer + if err := d.Option(gatt.LnxSendHCIRawCommand(cmd.LESetRandomAddress{RandomAddress: a}, &rsp)); err != nil { + return fmt.Errorf("could not set the Bluetooth address to %s: %w", address, err) + } + if rsp.Len() == 0 || rsp.Bytes()[0] != 0x00 { + return fmt.Errorf("the adapter refused Bluetooth address %s: response [% X]", address, rsp.Bytes()) + } + return nil +} + // NewGattRadio serves the pod from Bluetooth adapter hci, or from the // first one with LE support when hci is negative. Which adapter matters: // an Omnipod 5 needs a 247-byte ATT MTU, which a phone asks for only of a // Bluetooth 4.2 or later radio, so a Pi 3B's own 4.1 radio will not do and // a dongle has to be named here rather than left to chance. -func NewGattRadio(b *Ble, podId []byte, hci int) (Radio, error) { - d, err := gatt.NewDevice(ServerOptions(hci)...) +// +// address is the pod's own random static address, or empty to use the +// adapter's address, as a pod from an older state file does. +func NewGattRadio(b *Ble, podId []byte, hci int, address string) (Radio, error) { + d, err := gatt.NewDevice(ServerOptions(hci, address != "")...) if err != nil { log.Fatalf("pkg bluetooth; failed to open device, err: %s", err) } + if address != "" { + if err := setRandomAddress(d, address); err != nil { + log.Fatalf("pkg bluetooth; %s", err) + } + log.Infof("pkg bluetooth; serving the pod from its own address %s", address) + } else { + log.Infof("pkg bluetooth; serving the pod from the adapter's address; use -fresh to give a new pod its own") + } r := &gattRadio{device: d, profile: b.profile, podId: podId} d.Handle( diff --git a/pkg/bluetooth/gatt_other.go b/pkg/bluetooth/gatt_other.go index d70131e..395ff5a 100644 --- a/pkg/bluetooth/gatt_other.go +++ b/pkg/bluetooth/gatt_other.go @@ -5,6 +5,6 @@ package bluetooth import "errors" -func NewGattRadio(b *Ble, podId []byte, hci int) (Radio, error) { +func NewGattRadio(b *Ble, podId []byte, hci int, address string) (Radio, error) { return nil, errors.New("the Bluetooth transport needs Linux; use -transport impossible for the iOS Simulator") } diff --git a/pkg/pod/state.go b/pkg/pod/state.go index 1dc5f1a..d0a596d 100644 --- a/pkg/pod/state.go +++ b/pkg/pod/state.go @@ -52,6 +52,12 @@ type PODState struct { // PeripheralID is the identifier the iOS Simulator transport gives the pod. PeripheralID string `toml:"peripheral_id"` + // BleAddress is the random static address the pod serves itself from over + // a Bluetooth adapter, so that each fresh pod is a new device to the phone. + // It is empty in a state file written before pods had their own address, + // and that pod keeps the adapter's address so the phone still finds it. + BleAddress string `toml:"ble_address"` + // Mode is the kind of pod being simulated, "dash" or "o5". It is kept // with the state so that restarting the simulator does not change the // pod the phone paired with. @@ -81,6 +87,7 @@ func NewFreshState(filename string, mode bluetooth.Mode) *PODState { ActivationTime: time.Now(), Filename: filename, Mode: string(mode), + BleAddress: bluetooth.RandomStaticAddress(), } }