Skip to content

Latest commit

 

History

History
256 lines (199 loc) · 14.9 KB

protocol.md

File metadata and controls

256 lines (199 loc) · 14.9 KB

Duet protocol, version 1

Duet for Windows (the PC) and Duet for Android (the phone) talk over Wi-Fi or over Bluetooth. The phone listens; the PC finds it and connects. Every message is one UTF-8 JSON object on one line, ended by \n, at most 1 MiB. Every object has a t field naming its type. Unknown types are ignored and unknown fields are ignored, so either side can add messages later without breaking the other.

Transports

Where Transport Side that listens
UDP port 47820 Discovery on Wi-Fi phone
TCP port 47821 TLS: sessions and file transfers (another port if 47821 is taken; the announce says which) phone
Bluetooth RFCOMM service 6104c8e9-42e7-47b0-a275-6fc77d30f7b7 ("Duet") TLS: sessions and discovery phone
Bluetooth RFCOMM service e9d451b0-46f1-4b20-a9a5-316f9f554f27 ("Duet transfer") TLS: file transfers phone

A Bluetooth connection carries exactly the bytes a TCP connection would: the TLS handshake first, then JSON lines. The phone pipes every RFCOMM connection it accepts into its own TLS server on 127.0.0.1, so the certificate, the pairing and the token are the same on both transports, and a phone paired over one works over the other. The phone accepts a loopback peer only when it is one of its own Bluetooth pipes, and treats that session as a Bluetooth session. When the phone's side of a pipe ends first, the phone keeps the Bluetooth connection open until the PC closes it, for up to 10 seconds, so the last bytes are not lost.

The RFCOMM services are registered with listenUsingRfcommWithServiceRecord, so the phone has to be paired with the PC in the operating system's Bluetooth settings and the radio link is encrypted underneath TLS. Bluetooth allows one connection per service between two devices, which is why transfers have their own service and run one at a time.

The phone ignores TCP and UDP peers whose address is not private IPv4 or link-local. It takes at most eight connections that have not identified themselves yet, two per network address, and pipes at most four Bluetooth connections per service.

Discovery

On Wi-Fi the PC sends discover to the broadcast address of every IPv4 interface that is up, every 3 seconds, from an ephemeral port. It does so while it has no session, while its pairing view is open, and while its session runs over Bluetooth and it is allowed to move to Wi-Fi; never when it is set to connect over Bluetooth only:

{"t":"discover","v":1,"pcId":"7f3c…","pcName":"DESKTOP-AMR"}

The phone answers by unicast to the sender's address and port:

{"t":"announce","v":1,"id":"b41e…","name":"Galaxy S24","model":"SM-S921B","manufacturer":"samsung","port":47821}

id is a random UUID created on first launch and kept for the life of the install. Two optional flags appear only when true: "disconnected": true while the phone's user has disconnected, and "resume": true from when the phone's user chose Connect until its next session starts or the user disconnects again (see Disconnecting). The PC also connects straight to the last address it saw for a paired phone, so a sleeping phone that misses a broadcast is still found.

Over Bluetooth there is no broadcast. The PC opens a connection to the Duet service of a phone that Windows has paired, sends the same discover line as its first line inside TLS, and the phone answers with one announce line and closes. The phone answers a discover first line the same way on a TCP connection. The PC does this every 10 seconds for the phones Windows has paired while its pairing view is open, and for its paired phone while disconnected: every 15 seconds while the phone answers, backing off to 2 minutes while it does not.

Announces are not authenticated, so the PC never acts on their flags alone (see Disconnecting).

TLS

The phone's certificate is a self-signed EC P-256 certificate whose private key lives in AndroidKeyStore under the alias duet-tls. TLS 1.2 or later. The PC does not check the certificate chain; it compares the SHA-256 of the certificate's DER encoding (the fingerprint) with the one pinned at pairing. While pairing there is nothing pinned yet, and the pairing code is what proves both sides see the same certificate.

Pairing

The PC opens a connection, picks 16 random bytes (pcNonce) and sends only their hash:

{"t":"pair","v":1,"pcId":"7f3c…","pcName":"DESKTOP-AMR","commit":"<base64 of SHA-256(pcNonce)>"}

The phone answers with 16 random bytes of its own, and the PC then reveals its nonce:

{"t":"pairNonce","nonce":"<base64 of 16 random bytes>"}
{"t":"pairReveal","nonce":"<base64 of pcNonce>"}

The phone checks that the revealed nonce hashes to the commit and otherwise answers rejected / malformed; it skips any ping that arrives first, and closes the connection when the handshake, the pair line and the reveal have not all arrived within 15 seconds. Both sides then compute the pairing code: SHA-256(certificate DER || pcNonce || phoneNonce), take the first four bytes as a big-endian unsigned 32-bit integer, reduce it modulo 1 000 000 and print it as six digits with leading zeros. Each side fixes its random bytes before it sees the other's, so nobody in the middle can steer the two screens to the same code.

The PC shows the code; the phone shows the code with Pair and Decline. Until paired, the PC acts on nothing but pairNonce, paired and rejected. It keeps pinging and waits up to 75 seconds; the phone does not answer pings while it waits for its user. The phone waits at most 60 seconds, then answers one of:

{"t":"paired","token":"<base64 of 32 random bytes>"}
{"t":"rejected","reason":"declined"}

reason is declined, timeout (nobody answered), busy (another pairing request is on screen, or one ended without being accepted in the last 10 seconds; the phone answers this to a valid pairReveal, without showing anything) or malformed (which is also what an app from before this exchange answers).

After paired the phone sends welcome and the session continues as if it had started with hello. The PC stores the phone id, name, model, fingerprint, token, last address and port, and the phone's Bluetooth address once it has connected that way. The phone stores the PC id, name and the SHA-256 of the token.

Session start

A paired PC opens every session with:

{"t":"hello","v":1,"pcId":"7f3c…","pcName":"DESKTOP-AMR","token":"<base64>","app":"1.1.0","resume":false}

resume is true from when the PC's user chose Connect until the phone answers welcome or the user disconnects again. The phone answers rejected (reason: unknown-pc, bad-token, disconnected while disconnected and resume is false, or malformed for a first line of a known type that is missing a field) and closes, or:

{"t":"welcome","v":1,"id":"b41e…","name":"Galaxy S24","model":"SM-S921B","manufacturer":"samsung","android":"16","sdk":36,"app":"1.1.0"}

followed by a battery, an adb, a bluetooth and a ringState message. The phone holds one session at a time; a new authenticated session replaces the old one. That is how the PC moves from Bluetooth to Wi-Fi: it opens the Wi-Fi session first and lets go of the Bluetooth one when the phone answers welcome.

Heartbeat

The PC sends {"t":"ping"} every 5 seconds and the phone answers {"t":"pong"}. The PC closes the session after 15 seconds without receiving anything (30 seconds over Bluetooth), and the phone after 30 seconds.

Phone to PC

Message Meaning
{"t":"battery","level":82,"charging":true} Sent at session start and whenever the level or charging state changes
{"t":"adb","wirelessDebugging":true,"canEnable":true,"tlsPort":37411,"pairingPort":null,"developerOptions":true} Wireless debugging state. developerOptions: Developer options are on, sent only when true. canEnable: the app holds WRITE_SECURE_SETTINGS. tlsPort: the phone's own _adb-tls-connect._tcp port, null when not found. pairingPort: the _adb-tls-pairing._tcp port while the system pairing dialog is open, else null. Both ports are always null on a Bluetooth session. Sent at session start and on every change
{"t":"bluetooth","state":"ready"} Whether the PC can reach the phone over Bluetooth. state: ready (both services are listening), off (Bluetooth is off), denied (Duet does not hold Nearby devices) or unsupported. Sent at session start and on every change
{"t":"notification","key":"0|com.whatsapp|…","package":"com.whatsapp","app":"WhatsApp","title":"Sam","text":"On my way","time":1795000000000} A new or updated notification, when mirroring is on. Ongoing notifications, group summaries, notifications with no title and no text, and Duet's own are not sent
{"t":"notificationRemoved","key":"…"} The notification was dismissed on the phone
{"t":"clipboard","text":"…"} Put this text on the PC clipboard. Either side refuses to send text whose line would reach 1 MiB
{"t":"streamRequest","mode":"audio"} The user asked from the phone. mode: audio, screen or stop
{"t":"fileOffer","id":"c2…","name":"IMG_2041.jpg","size":2481152,"mime":"image/jpeg"} The user shared a file to the PC; the PC fetches it
{"t":"ringState","ringing":false} Whether the phone is ringing. Sent at session start and whenever ringing starts or stops, including when the user stopped it on the phone or it ran out after 60 seconds
{"t":"disconnect"} The phone's user disconnected; the phone closes the session (see Disconnecting)

PC to phone

Message Meaning
{"t":"streamState","mode":"audio"} mode: idle, connecting, audio, screen. Optional via: bluetooth while the audio plays through Bluetooth audio. Optional error: needs-adb-pairing, adb-unavailable, engine-failed, bluetooth-unavailable, needs-wifi. Drives the tile and the streaming notification
{"t":"enableWirelessDebugging"} Switch wireless debugging on when canEnable; the phone answers with adb
{"t":"ring"} / {"t":"stopRing"} Ring the phone at alarm volume until stopped on either side
{"t":"clipboard","text":"…"} Put this text on the phone clipboard
{"t":"unpair"} Forget this PC; the phone closes the session
{"t":"disconnect"} The PC's user disconnected; the phone closes the session (see Disconnecting)

Disconnecting

Either side's user can disconnect. Both sides then keep a persisted disconnected flag: the PC stops reconnecting, the phone answers hello with rejected / disconnected, and any stream stops.

  • The side that disconnects sets its flag, sends {"t":"disconnect"} if a session is open, and closes it. The other side sets its flag when it receives that message.
  • When the phone's user disconnects with no session open, its announce carries "disconnected": true. The PC learns it from the rejected / disconnected answer to its next hello, not from the flag.
  • PC Connect clears the PC's flag. Every hello then carries "resume": true, which clears the phone's flag, until the phone answers welcome or the PC's user disconnects again.
  • Phone Connect clears the phone's flag; its announce carries "resume": true until its next session starts or its user disconnects again. A PC that sees it sends hello with "resume": false and clears its own flag when the phone answers welcome. A forged resume therefore changes nothing: the real phone, still disconnected, answers rejected.

File transfers

A transfer is its own TLS connection: to the session port on Wi-Fi, to the Duet transfer service over Bluetooth. The first line authenticates and says what follows:

{"t":"fileGet","pcId":"7f3c…","token":"<base64>","id":"c2…"}

The phone writes exactly size raw bytes of the offered file and closes. When it cannot serve the file (a wrong token, an offer it no longer holds, a file it can no longer open) it closes without writing anything, and a file that fails part-way ends short of size.

{"t":"filePut","pcId":"7f3c…","token":"<base64>","name":"report.pdf","size":120394,"mime":"application/pdf"}

The PC writes exactly size raw bytes; the phone saves them to Downloads/Duet and answers {"t":"fileSaved","name":"report.pdf"} (the name it was saved under) or {"t":"rejected","reason":"…"}. The answer always comes after the phone has read the bytes: storage-permission (Android 9 and older without the Storage permission) or save-failed. A wrong token closes the connection without an answer.

Both sides give up on a transfer after 30 seconds without progress.

Streaming over adb, end to end

This is the path for screen mirroring, and for audio on a Wi-Fi session unless audio is set to Bluetooth. Mirroring on a Bluetooth session needs a USB cable, which the PC looks for only when asked to mirror.

  1. The PC sends streamState connecting.
  2. If the phone is attached by USB with debugging allowed, the PC uses that device and skips to step 5.
  3. If wirelessDebugging is false and canEnable is true, the PC sends enableWirelessDebugging and waits up to 5 seconds for an adb message with a tlsPort.
  4. The PC runs adb connect against host:tlsPort, then host:5555, then the matching entry of adb mdns services.
  5. Once connected, if canEnable is false, the PC grants it: adb -s <serial> shell pm grant com.projectgraphite.duet android.permission.WRITE_SECURE_SETTINGS, then sends enableWirelessDebugging so the phone reports canEnable: true.
  6. The PC starts scrcpy against that serial and sends streamState audio or screen; it sends idle when scrcpy exits, and idle with error when a step fails.

When adb cannot connect and canEnable is false, the PC opens its one-time streaming setup instead of reporting an error. Setup follows the phone's adb messages step by step, runs adb pair host:pairingPort <code> with the code the user types, then steps 4 and 5 above, and starts the stream the user asked for.

The PC runs its own adb server on port 5038, so it does not disturb an adb server a developer is running on the default port.

On a Bluetooth session without a USB device, a screen request ends with streamState idle and error needs-wifi.

Audio over Bluetooth

When audio is set to Bluetooth, or the session is a Bluetooth session, no adb is involved. The PC opens a Bluetooth audio connection to the phone as an A2DP sink (Windows AudioPlaybackConnection), and the phone routes its media sound to the PC the way it would to a speaker. Nothing in the Duet protocol carries the audio.

  1. The PC sends streamState connecting.
  2. The PC opens the audio connection to the phone Windows has paired. If that fails (no radio, Bluetooth off, the phone not paired with this PC, or the phone refusing media audio) it sends idle with error bluetooth-unavailable.
  3. The PC sends {"t":"streamState","mode":"audio","via":"bluetooth"}, and idle when it closes the connection or the phone drops it.