libadb-ffi 0.9.0

C ABI for libadb
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*
 * libadb — C API for the ADB wire-protocol library.
 *
 * All functions are synchronous and block the calling thread until the
 * underlying async operation completes. A const char * is a
 * null-terminated string.
 *
 * Handles may be passed between threads and used from several at once.
 * The calls that wait on the device for an answer — adb_open_channel(),
 * adb_read_channel(), adb_accept_channel(), the reverse calls,
 * adb_shell_open() and adb_shell_read_frame() — hold the connection's
 * read lock, so they run one at a time. The exception is a read that
 * finds the lock taken: it takes the data the holder dispatches for its
 * channel, and the lock once it comes free. Writes and closes never wait
 * for the lock: a thread blocked in a read does not keep another from
 * writing. The metadata queries — adb_connection_max_payload(),
 * adb_connection_delayed_ack(), adb_connection_device_banner(),
 * adb_connection_has_feature() and adb_connection_features() — take no
 * lock at all, so they are safe to call while another thread is blocked
 * in adb_read_channel().
 *
 * A write, adb_write_channel() or a shell frame, needs no read call
 * running. Nothing reads the connection in the background: only a call
 * holding the read lock takes packets off it, and that includes the
 * OKAY a write waits for. Without delayed ACK a channel has room for
 * one WRTE at a time, so a second write in a row waits for the OKAY to
 * the first; with delayed ACK a write waits once the credit runs out.
 * While it waits for the device and no read call is running, the write
 * reads the connection itself, holding the read lock, so a call that
 * needs the lock waits its turn and data for other channels is kept for
 * their reads.
 *
 * On error, functions return a non-zero adb_status_t and set a
 * thread-local error string retrievable via adb_last_error().
 */

#ifndef LIBADB_H
#define LIBADB_H

#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct adb_connection adb_connection_t;
/* 64-bit: the implementation packs the protocol id and a table slot
 * into one value and writes all eight bytes through out-pointers. */
typedef uint64_t adb_channel_id_t;

typedef enum {
    ADB_OK                  = 0,
    ADB_ERR_INVALID_ARG     = 1,
    ADB_ERR_INVALID_URI     = 2,
    ADB_ERR_CONNECT         = 3,
    ADB_ERR_IO              = 4,
    ADB_ERR_AUTH            = 5,
    ADB_ERR_PROTOCOL        = 6,
    ADB_ERR_CHANNEL_CLOSED  = 7,
    ADB_ERR_NO_FREE_CHANNELS = 8,
    ADB_ERR_DESYNCHRONIZED  = 9,
    /* The device's reverse rule service refused the request; the
     * device's own message is in adb_last_error(). */
    ADB_ERR_REVERSE         = 10,
    /* The device answered the handshake with STLS (Android 11+ wireless
     * debugging) and this call cannot start TLS: the library was built
     * without the `tls` feature, or the key sits behind an
     * adb_authenticator_t. adb_last_error() says which. */
    ADB_ERR_TLS_REQUIRED    = 11,
    /* adb_pair(): the device did not take the key. The code did not
     * match, or the device ended the exchange itself (dialog dismissed,
     * attempts used up); adb_last_error() says which. */
    ADB_ERR_PAIRING         = 12,
    /* The connection has ended and nothing more will arrive from the
     * device: the device or the transport went away, or what came in
     * does not parse. The call that saw this returned ADB_ERR_IO or
     * ADB_ERR_PROTOCOL. Every later call that waits on the device gets
     * ADB_ERR_DISCONNECTED; a read gets it only after handing over what
     * had already arrived. A read timeout does not end the connection
     * and never leads here. Open a new connection. */
    ADB_ERR_DISCONNECTED    = 13,
    ADB_ERR_INTERNAL        = 255
} adb_status_t;

/*
 * Connect and perform the CNXN/AUTH handshake.
 *
 *   uri            "tcp://HOST:PORT" or "usb://[VID:PID|serial/SERIAL]"
 *   priv_key_pem   PKCS#8 PEM RSA private key (contents of ~/.android/adbkey)
 *   pub_key        ADB-format public key blob (contents of ~/.android/adbkey.pub)
 *   banner         identity banner, e.g. "host::features=shell_v2,delayed_ack"
 *   out            receives a handle; release with adb_connection_free().
 *
 * Wireless debugging (Android 11+): the port the "Wireless debugging"
 * screen shows answers the handshake with STLS and speaks TLS 1.3 from
 * then on. Built with the `tls` feature, adb_connect() starts TLS and
 * presents a certificate carrying the key in priv_key_pem. A key the
 * device already trusts, confirmed at a USB prompt or paired, needs
 * nothing more; a key it does not trust is ADB_ERR_AUTH. Without the
 * feature the call returns ADB_ERR_TLS_REQUIRED. The port changes every
 * time the setting is switched on and the library does no DNS-SD, so
 * the caller supplies it. USB and the legacy port `adb tcpip` opens
 * stay in the clear either way. If no certificate can be built for the
 * key, for example because the system clock is outside what a
 * certificate can carry, the call returns ADB_ERR_INTERNAL.
 *
 * Security, as with `adb`: the device is not authenticated. Its
 * certificate is self-signed and taken on trust, and TLS starts only
 * when the device asks for it with STLS: a peer that answers CNXN or
 * AUTH instead is served in the clear. On a network you do not trust,
 * an attacker in the middle can therefore take the device's place,
 * inside TLS or, by answering without STLS, outside it. TLS keeps a
 * passive eavesdropper out, but this API has no way to pin the
 * device's certificate or to insist on TLS.
 */
adb_status_t adb_connect(
    const char        *uri,
    const char        *priv_key_pem,
    const char        *pub_key,
    const char        *banner,
    adb_connection_t **out);

/*
 * Caller-supplied signing callback for adb_connect_with_authenticator().
 * It runs synchronously during the handshake.
 *
 * The implementation must produce a PKCS#1 v1.5 signature of the SHA-1
 * prehash supplied in `token` (always 20 bytes), write up to
 * `out_capacity` bytes into `out_signature`, and store the actual
 * signature length through `*out_length`. Returning anything other
 * than ADB_OK aborts the handshake; the caller observes ADB_ERR_AUTH.
 *
 * `user_data` is forwarded verbatim from adb_authenticator_t to every
 * call and is otherwise opaque to libadb.
 */
typedef adb_status_t (*adb_sign_fn)(
    void          *user_data,
    const uint8_t *token,
    size_t         token_len,
    uint8_t       *out_signature,
    size_t         out_capacity,
    size_t        *out_length);

/*
 * Caller-supplied authenticator. `public_key` and `public_key_len`
 * describe the ADB-format public key blob (contents of
 * ~/.android/adbkey.pub); a trailing NUL is appended if it is not
 * already there. The bytes are copied on connect, so the buffer only
 * needs to stay valid for the duration of the call. The `sign` callback
 * must stay valid for the duration of the call too.
 */
typedef struct {
    const uint8_t *public_key;
    size_t         public_key_len;
    adb_sign_fn    sign;
    void          *user_data;
} adb_authenticator_t;

/*
 * Like adb_connect(), but uses a caller-supplied authenticator instead
 * of the built-in RSA/PEM signer. Use this when the private key lives
 * outside the host process (HSM, remote signer, non-PKCS#8 store).
 *
 * Plaintext only: the callback signs the 20-byte AUTH token, while TLS
 * 1.3 client authentication needs an RSA-PSS signature over the
 * handshake transcript and a certificate, neither of which it can
 * produce. Against a wireless-debugging port this is
 * ADB_ERR_TLS_REQUIRED whatever the build; use adb_connect with the
 * private key there.
 */
adb_status_t adb_connect_with_authenticator(
    const char                *uri,
    const adb_authenticator_t *authenticator,
    const char                *banner,
    adb_connection_t         **out);

/* Release a handle from adb_connect() or adb_connect_with_authenticator().
 * NULL is a no-op. Any other value, or a handle already freed, is
 * undefined behaviour. */
void adb_connection_free(adb_connection_t *conn);

/* ---- host key store -------------------------------------------------
 *
 * An RSA host key read from, or written into, a key directory. The
 * strings the accessors return are owned by the handle and stay valid
 * until adb_key_free(); feed them straight to adb_connect().
 */
typedef struct adb_key adb_key_t;

/*
 * Load <android_dir>/adbkey, generating and persisting a 2048-bit key
 * (adbkey, owner-only, plus a matching adbkey.pub) when there is none;
 * the device then asks the user to confirm the new key once.
 *
 *   android_dir  key directory — required. Point it at ~/.android to
 *                reuse the identity the standard adb client already
 *                had the device trust, or at any directory of your own;
 *                the library resolves no paths and reads no environment
 *                of its own. Taken as bytes on Unix, so a path that is
 *                not valid UTF-8 is fine; on Windows it must be UTF-8.
 *   name         "user@host" comment shown in the device's dialog,
 *                or NULL for a default
 *   out          receives the handle; release with adb_key_free()
 *
 * An existing key is reused untouched, in either PKCS#8 or the PKCS#1
 * older adb releases wrote. An existing adbkey that will not parse is
 * ADB_ERR_AUTH and is left on disk: it may still be trusted by a
 * device, so it is never overwritten.
 */
adb_status_t adb_key_load_or_generate(
    const char  *android_dir,
    const char  *name,
    adb_key_t  **out);

/* PKCS#8 PEM private key; pass to adb_connect(). NULL if key is NULL. */
const char *adb_key_private_key_pem(const adb_key_t *key);

/* ADB-format public key line; pass to adb_connect(). NULL if key is NULL. */
const char *adb_key_public_key(const adb_key_t *key);

/* Release a handle from adb_key_load_or_generate(). NULL is a no-op. */
void adb_key_free(adb_key_t *key);

/* ---- pairing (Android 11+ wireless debugging) ---------------------
 *
 * Present only when libadb-ffi is built with --features pairing: the
 * symbol does not exist otherwise, and a program calling it fails to
 * link rather than at run time.
 */

/*
 * Pair with a device: put the caller's key into its trusted store
 * through "Pair device with pairing code" on the device's Wireless
 * debugging screen (SPAKE2 inside TLS, as `adb pair` does). A key the
 * device already trusts — one confirmed at a USB prompt — needs none
 * of this; adbd checks both against the same store.
 *
 *   uri            "tcp://HOST:PORT": the *pairing* port shown beside
 *                  the code. It is not the port the device connects
 *                  on, it changes each time the dialog opens, and it
 *                  stops listening once one pairing succeeds. usb://
 *                  is refused with ADB_ERR_INVALID_URI.
 *   priv_key_pem   PKCS#8 PEM RSA private key, as adb_connect() takes it
 *   pub_key        the matching ADB-format public key line. The text
 *                  after the base64 blob ("user@host") is the name the
 *                  device lists this host under, unchanged; a line
 *                  ending after it, which reading a file leaves behind,
 *                  is dropped. A blob that does not belong to the
 *                  private key is ADB_ERR_INVALID_ARG.
 *   code           the code on the dialog: six digits when typed, or
 *                  the password a QR code carried. Only emptiness is
 *                  checked here — validate a typed code yourself, since
 *                  a wrong one costs the device one of its attempts,
 *                  and it stops serving after twenty.
 *   guid, guid_cap, out_guid_len
 *                  receive the device's GUID — the name it announces
 *                  its connect port under over DNS-SD
 *                  (_adb-tls-connect._tcp) — not NUL-terminated, with
 *                  the truncate-and-report convention of
 *                  adb_connection_features(); either pointer may be
 *                  NULL.
 *
 * Returns ADB_OK once the device has stored the key, even if the GUID
 * copy was cut short: by then the pairing is done and the port is gone,
 * so a short buffer is no reason to fail. From then on the same
 * priv_key_pem / pub_key connect over TLS through adb_connect().
 *
 * ADB_ERR_PAIRING is the device saying no (wrong code, or it ended the
 * exchange); ADB_ERR_CONNECT means nothing answered at that address,
 * typically a pairing port that has already closed; ADB_ERR_IO is a
 * connection that broke part way. Blocks until the exchange ends;
 * there is no timeout.
 */
adb_status_t adb_pair(
    const char *uri,
    const char *priv_key_pem,
    const char *pub_key,
    const char *code,
    uint8_t    *guid,
    size_t      guid_cap,
    size_t     *out_guid_len);

/*
 * Set the receive and send timeouts of a tcp:// connection, in
 * milliseconds; 0 disables that timeout. USB transports have no such
 * knob and return ADB_ERR_INVALID_ARG.
 *
 * A read that hits the timeout fails with ADB_ERR_IO and the connection
 * stays usable: bytes of a partially received packet are kept, so the
 * next read continues where this one stopped. That guarantee holds on
 * Unix, where SO_RCVTIMEO leaves the socket intact. On Windows, Winsock
 * documents a blocking receive that expires under SO_RCVTIMEO as
 * leaving the connection in an indeterminate state and advises closing
 * it, so there a timed-out read means close the connection, not read
 * again. Until this path uses a readiness-based deadline on Windows,
 * treat the read timeout as recoverable on Unix only.
 *
 * A write waiting for the device reads for itself (see the top of this
 * file), so the timeout ends that read too: the write fails with
 * ADB_ERR_IO, and what it had sent by then stays sent. While a read
 * call on another thread holds the read lock, the timeout ends that
 * call and the write goes on waiting until it finds the lock free.
 *
 * A signal handled during a wait does not fail the call: it goes on
 * waiting, and the timeout starts over.
 *
 * A write timeout is a harder stop even on Unix: firing mid-packet
 * abandons a write the device has partially seen, so the connection is
 * marked desynchronized and every later channel operation fails with
 * ADB_ERR_DESYNCHRONIZED. Reads first hand over what had already
 * arrived; metadata queries and this setter still answer. Set a write
 * timeout only where tearing the connection down beats blocking; for a
 * recoverable bound, use the read timeout.
 *
 * Both hold on a TLS (wireless-debugging) connection too: the timeouts
 * sit on the socket underneath, a timed-out read leaves the session and
 * the partial packet intact, and a timed-out write is the same
 * abandoned packet.
 */
adb_status_t adb_connection_set_io_timeout_ms(
    adb_connection_t *conn,
    uint32_t          read_ms,
    uint32_t          write_ms);

/* Negotiated max payload in bytes; 0 if conn is NULL. */
uint32_t adb_connection_max_payload(const adb_connection_t *conn);

/* Whether delayed-ACK (credit-based flow control) was negotiated; false
 * if conn is NULL. */
bool adb_connection_delayed_ack(const adb_connection_t *conn);

/*
 * Copy up to buf_len bytes of the device banner into buf and write the
 * full banner length through *out_len, so a caller whose buffer was too
 * short can retry with a larger one. Either pointer may be NULL.
 */
adb_status_t adb_connection_device_banner(
    const adb_connection_t *conn,
    uint8_t                *buf,
    size_t                  buf_len,
    size_t                 *out_len);

/*
 * Feature identifiers used with adb_connection_has_feature() and
 * adb_connection_features(). Values are stable across library versions;
 * new features are appended at the end.
 */
typedef uint32_t adb_feature_t;
#define ADB_FEATURE_ABB                            0
#define ADB_FEATURE_ABB_EXEC                       1
#define ADB_FEATURE_APEX                           2
#define ADB_FEATURE_APP_INFO                       3
#define ADB_FEATURE_CMD                            4
#define ADB_FEATURE_DELAYED_ACK                    5
#define ADB_FEATURE_DEVICETRACKER_PROTO_FORMAT     6
#define ADB_FEATURE_DEVRAW                         7
#define ADB_FEATURE_FIXED_PUSH_MKDIR               8
#define ADB_FEATURE_FIXED_PUSH_SYMLINK_TIMESTAMP   9
#define ADB_FEATURE_LS_V2                         10
#define ADB_FEATURE_OPENSCREEN_MDNS               11
#define ADB_FEATURE_REMOUNT_SHELL                 12
#define ADB_FEATURE_SENDRECV_V2                   13
#define ADB_FEATURE_SENDRECV_V2_BROTLI            14
#define ADB_FEATURE_SENDRECV_V2_DRY_RUN_SEND      15
#define ADB_FEATURE_SENDRECV_V2_LZ4               16
#define ADB_FEATURE_SENDRECV_V2_ZSTD              17
#define ADB_FEATURE_SHELL_V2                      18
#define ADB_FEATURE_STAT_V2                       19
#define ADB_FEATURE_TRACK_APP                     20

/*
 * Whether the device advertises `feature`. Returns false if `conn` is
 * NULL or `feature` is not one of the ADB_FEATURE_* constants above.
 */
bool adb_connection_has_feature(
    const adb_connection_t *conn,
    adb_feature_t           feature);

/*
 * Wire-format name of `feature` (e.g. "shell_v2") as a static
 * null-terminated string, or NULL for unknown values.
 */
const char *adb_feature_name(adb_feature_t feature);

/*
 * Copy up to buf_cap features advertised by the device into buf (in
 * handshake order) and write the full count through *out_len. Either
 * pointer may be NULL: pass (NULL, 0, &n) to query the count, then call
 * again with a larger buffer.
 *
 * Features the library does not recognise are skipped when the
 * handshake is parsed, so the returned count covers only known
 * ADB_FEATURE_* values.
 */
adb_status_t adb_connection_features(
    const adb_connection_t *conn,
    adb_feature_t          *buf,
    size_t                  buf_cap,
    size_t                 *out_len);

/*
 * Open a channel to `destination` (e.g. "shell:ls", "tcp:8080", "sync:").
 * `destination` need not be null-terminated; `destination_len` bytes are
 * sent verbatim. *out_id receives the channel ID on success, usable
 * with the other adb_*_channel functions until the channel is closed.
 *
 * The ID of a closed channel is stale: calls with it fail with
 * ADB_ERR_CHANNEL_CLOSED, even if the slot has since been reused for a
 * new channel. An ID whose table slot no call could have returned makes
 * the channel calls fail with ADB_ERR_INVALID_ARG.
 */
adb_status_t adb_open_channel(
    adb_connection_t *conn,
    const uint8_t    *destination,
    size_t            destination_len,
    adb_channel_id_t *out_id);

/*
 * Read up to buf_len bytes from a channel into buf. *out_read receives
 * the number of bytes read. Channel closure is reported as
 * ADB_ERR_CHANNEL_CLOSED; ADB_OK with *out_read == 0 never happens,
 * which is what makes
 *
 *     while (adb_read_channel(...) == ADB_OK) { ... }
 *
 * a correct loop. buf_len == 0 is rejected with ADB_ERR_INVALID_ARG
 * rather than answering with a zero such a loop would spin on, and a
 * zero-length WRTE from the device, which is legal and delivers
 * nothing, is read past for the same reason.
 *
 * Everything that arrived comes back before any error does, however
 * the connection failed: a device that hangs up leaves what it sent
 * readable. The call that meets the end of the connection returns that
 * failure, ADB_ERR_IO or ADB_ERR_PROTOCOL, and the next call returns
 * ADB_ERR_DISCONNECTED. A read timeout is ADB_ERR_IO too, but the next
 * call simply reads on.
 */
adb_status_t adb_read_channel(
    adb_connection_t *conn,
    adb_channel_id_t  id,
    uint8_t          *buf,
    size_t            buf_len,
    size_t           *out_read);

/*
 * Write buf_len bytes. Returns once all of them are framed and handed
 * to the transport. They go out as WRTEs of at most
 * adb_connection_max_payload() bytes, and each can first wait for the
 * device's OKAY to the one before it, or for credit under delayed ACK.
 * No read call has to be running for that: with none, this call reads
 * the connection itself, and can then fail as a read does, with part of
 * buf already sent. See the top of this file.
 */
adb_status_t adb_write_channel(
    adb_connection_t *conn,
    adb_channel_id_t  id,
    const uint8_t    *buf,
    size_t            buf_len);

/* Close a channel. Subsequent ops on this id return ADB_ERR_CHANNEL_CLOSED.
 *
 * The slot is freed even if sending the CLSE fails. If the device is
 * gone or the connection has ended, no CLSE is sent and the call
 * returns ADB_OK. */
adb_status_t adb_close_channel(
    adb_connection_t *conn,
    adb_channel_id_t  id);

/* ---- reverse forwards ---------------------------------------------- */

/*
 * Establish a reverse forward: the device listens on device_spec and
 * opens a channel toward the host per connection, with host_spec as the
 * destination. Receive those channels with adb_accept_channel().
 *
 * The port adbd reports is written to (data, data_cap, out_data_len)
 * in unsigned decimal, with the same truncate-and-report-full-length
 * convention as adb_connection_features(), and *out_data_len is 0 when
 * it reports none. A newly bound "tcp:0" reports the port adbd picked;
 * a fixed "tcp:<port>" reports it from Android 10 on, not on Android 9;
 * a "vsock:" listener reports its port; a rule that already exists, and
 * any other device_spec, answer a bare OKAY and report none. A reported
 * port is 32 bits wide because vsock ports are; a "tcp:" port always
 * fits 16 bits. Either data-side pointer may be NULL.
 */
adb_status_t adb_reverse_forward(
    adb_connection_t *conn,
    const char       *device_spec,
    const char       *host_spec,
    uint8_t          *data,
    size_t            data_cap,
    size_t           *out_data_len);

/*
 * Remove the reverse rule listening on device_spec, whichever connection
 * established it.
 */
adb_status_t adb_reverse_remove(
    adb_connection_t *conn,
    const char       *device_spec);

/*
 * Remove every reverse rule on the device, whichever connection
 * established it.
 */
adb_status_t adb_reverse_remove_all(adb_connection_t *conn);

/*
 * List the device's reverse rules, whichever connection established
 * them, as "<serial> <remote> <local>\n" lines into (buf, buf_len,
 * out_len), same convention as adb_connection_features(). The lines are
 * the device's own bytes, passed on unparsed.
 */
adb_status_t adb_reverse_list(
    adb_connection_t *conn,
    uint8_t          *buf,
    size_t            buf_len,
    size_t           *out_len);

/*
 * Report the staged device-initiated channel (reverse traffic), waiting
 * for one to arrive if none is staged, and copy its destination into
 * (dest, dest_cap, out_dest_len), same convention as
 * adb_connection_features(). The request stays staged on the handle
 * until adb_incoming_accept() or adb_incoming_reject() takes it, so
 * repeated calls report the same request again. That makes the
 * truncate-and-report convention work here: probe with (NULL, 0, &len),
 * allocate, call again for the bytes.
 *
 * With nothing staged this blocks until a channel arrives, as
 * adb_read_channel() blocks for data, and holds the read lock while
 * waiting, so a device that never opens one blocks this call for good.
 * The staged request stays locked for the whole call, so concurrent
 * calls to this function, adb_incoming_accept() and
 * adb_incoming_reject() run one at a time rather than racing for the
 * queue. There is no way to interrupt the call yet, and the handle must
 * stay alive until it returns: adb_connection_free() from another
 * thread while a call is blocked is undefined behaviour, not an
 * interruption mechanism.
 */
adb_status_t adb_accept_channel(
    adb_connection_t *conn,
    uint8_t          *dest,
    size_t            dest_cap,
    size_t           *out_dest_len);

/*
 * Accept the channel staged by adb_accept_channel(), returning its id
 * through out_id.
 */
adb_status_t adb_incoming_accept(
    adb_connection_t *conn,
    adb_channel_id_t *out_id);

/* Reject the channel staged by adb_accept_channel(). */
adb_status_t adb_incoming_reject(adb_connection_t *conn);

/*
 * Thread-local description of the last error, or NULL if none.
 * Valid until the next libadb call on this thread.
 */
const char *adb_last_error(void);

/* ---- shell_v2 ------------------------------------------------------ */

/*
 * Frame ids in the shell_v2 framing protocol; adb_shell_read_frame()
 * returns one of these through *out_id.
 */
#define ADB_SHELL_V2_STDIN                0
#define ADB_SHELL_V2_STDOUT               1
#define ADB_SHELL_V2_STDERR               2
#define ADB_SHELL_V2_EXIT                 3
#define ADB_SHELL_V2_CLOSE_STDIN          4
#define ADB_SHELL_V2_WINDOW_SIZE_CHANGE   5

typedef struct adb_shell adb_shell_t;

/*
 * Open a shell_v2 session.
 *
 * `command` must be valid UTF-8 and need not be null-terminated; pass
 * an empty buffer (NULL, 0) for a login shell (only sensible with a pty).
 *
 * `pty` selects shell,v2,pty,... (true) or shell,v2,raw: (false).
 * `term` is the value for the device's TERM env var (e.g.
 *   "xterm-256color"); may be NULL or empty to omit it; ignored when
 *   `pty` is false. A term holding ',' or ':' would rewrite the request
 *   on the device, so it is refused with ADB_ERR_PROTOCOL before
 *   anything is sent, as a NUL in `command` is.
 * `rows`, `cols` — if `pty` and at least one is non-zero, an initial
 *   WINDOW_SIZE_CHANGE frame is sent right after the channel opens, a
 *   write like any other (see the top of this file).
 *
 * On success *out_sh receives the handle. `conn` must remain alive for
 * as long as any shell handle opened against it. Release the handle
 * with adb_shell_free() (call adb_shell_close() first to tear down the
 * channel gracefully).
 */
adb_status_t adb_shell_open(
    adb_connection_t  *conn,
    const uint8_t     *command,
    size_t             command_len,
    bool               pty,
    const char        *term,
    uint16_t           rows,
    uint16_t           cols,
    adb_shell_t      **out_sh);

/* Release a handle from adb_shell_open(). NULL is a no-op. The channel
 * is not closed automatically: call adb_shell_close() first to avoid
 * leaking it on the device. */
void adb_shell_free(adb_shell_t *sh);

/*
 * Read one decoded frame.
 *
 * *out_id receives the frame id (ADB_SHELL_V2_*). Up to `buf_cap` bytes
 * of payload are copied into `buf`; *out_len (may be NULL) receives
 * the full payload length — a value larger than `buf_cap` means the
 * excess was discarded.
 *
 * Frames whose payload exceeds the internal 64 KiB rx buffer are
 * delivered across multiple calls with the same id; concatenate the
 * chunks to reconstruct the payload.
 *
 * Channel closure is reported as ADB_ERR_CHANNEL_CLOSED. As with
 * adb_read_channel(), everything that arrived comes back before any
 * error does, however the connection failed. After adb_shell_close()
 * the call returns ADB_ERR_CHANNEL_CLOSED at once.
 */
adb_status_t adb_shell_read_frame(
    adb_shell_t *sh,
    uint8_t     *out_id,
    uint8_t     *buf,
    size_t       buf_cap,
    size_t      *out_len);

/* Send a STDIN frame.
 *
 * Safe to call from several threads on one session: each frame is
 * written whole, never interleaved with another sender's.
 *
 * The frame header and a payload go out as two WRTEs, and the second
 * can wait for the device: see the top of this file. A failure can
 * leave the header sent and the payload not, and the device then reads
 * whatever comes next as that payload. After a failure the session's
 * frame stream cannot be trusted: close it. */
adb_status_t adb_shell_write_stdin(
    adb_shell_t   *sh,
    const uint8_t *data,
    size_t         len);

/* Signal that no more stdin will be sent.
 *
 * A channel the device has already closed is not a failure: there is no
 * stdin left to close, and what the device wrote before closing stays
 * readable, so the output of a command that finished first is not lost.
 * After adb_shell_close() this returns ADB_ERR_CHANNEL_CLOSED, and on a
 * channel closed by a fault it returns that fault's status. */
adb_status_t adb_shell_close_stdin(adb_shell_t *sh);

/* Notify the device PTY of a terminal resize (a WINDOW_SIZE_CHANGE frame). */
adb_status_t adb_shell_set_window_size(
    adb_shell_t *sh,
    uint16_t     rows,
    uint16_t     cols);

/* Close the underlying channel. Later reads and writes on this handle
 * return ADB_ERR_CHANNEL_CLOSED. Idempotent. */
adb_status_t adb_shell_close(adb_shell_t *sh);

#ifdef __cplusplus
}
#endif

#endif /* LIBADB_H */