C API reference headers

API.

Public macros, types, ownership rules, return values, and function contracts, organized by the headers exported through cadb/cadb.h.

C11 / C ABIOpaque handlesExplicit errorsMIT License

01 / CONTRACT

Include the API and interpret results

Include <cadb/cadb.h> for the complete public API. Individual headers can also be included when a module boundary is useful. All declarations use C linkage when included from C++.

Return-value convention

Functions returning cadb_err_t report the operation or transport status. CADB_OK means that the library-level operation completed; it does not necessarily mean a remote command succeeded. Check the relevant output field, such as Shell v2 exit_code or task result. Output handles and result structs are caller-owned unless stated otherwise.

CADB_OK (0)

Meaning
Success
Typical context
Operation completed; inspect remote exit/task result where applicable.

CADB_ERR_INVALID_ARGUMENT (1)

Meaning
Invalid input
Typical context
Null output, invalid length, malformed address or path.

CADB_ERR_NO_MEMORY (2)

Meaning
Allocation failed
Typical context
Object or packet allocation.

CADB_ERR_IO (3)

Meaning
Transport I/O failure
Typical context
Socket callback failed or made invalid zero progress.

CADB_ERR_TIMEOUT (4)

Meaning
Deadline elapsed
Typical context
Connect, read, write, handshake, or service operation.

CADB_ERR_CANCELLED (5)

Meaning
Cancellation requested
Typical context
A blocking operation observed its cancellation token.

CADB_ERR_PROTOCOL (6)

Meaning
Invalid ADB/SYNC exchange
Typical context
Bad frame, unexpected packet, or malformed peer response.

CADB_ERR_AUTH (7)

Meaning
Authentication failed
Typical context
AUTH challenge rejected, callback failed, or challenge limit reached.

CADB_ERR_NOT_SUPPORTED (8)

Meaning
Backend capability unavailable
Typical context
Built-in transport absent or TLS hook not implemented.

CADB_ERR_INSTALL (9)

Meaning
APK installation failed
Typical context
Remote package manager reported installation failure.

CADB_ERR_INTERNAL (10)

Meaning
Internal failure
Typical context
Unexpected library invariant failure.

CADB_ERR_COMMAND_FAILED (11)

Meaning
Remote command failed
Typical context
SYNC remove command returned a nonzero exit status.

CADB_ERR_BUSY (12)

Meaning
Object cannot accept this operation now
Typical context
Concurrent task or second active ADB stream.

const char *cadb_err_str(cadb_err_t err)

Returns a static human-readable identifier for an error code. Use the enum value as the stable programmatic result; keep localized UI wording in the host application.

Parameter
err: error code to describe.
Return
Pointer to a static string; the caller does not free it.

Version and export macros

CADB_VERSION_MAJOR, CADB_VERSION_MINOR, CADB_VERSION_PATCH

Definition
0, 2, 0
Use
Compile-time version components from version.h.

CADB_VERSION_STRING

Definition
"0.2.0"
Use
Compile-time version string.

const char *cadb_version_string(void)

Definition
Returns const char *
Use
Runtime version string; static storage.

unsigned int cadb_version_number(void)

Definition
(major << 16) | (minor << 8) | patch
Use
Packed numeric version.

CADB_API

Definition
Visibility/import-export annotation
Use
Defined by the build for shared-library exports; empty for static builds with CADB_STATIC.

CADB_INVALID_SOCKET

Definition
(cadb_socket_t)-1
Use
Invalid socket-handle sentinel.

02 / SHARED TYPES

Enums, value structs, and cancellation

These declarations live in types.h. Endpoint, device, progress, and task records are caller-visible value types. Network, ADB, SYNC, task-runner, and cancellation objects are opaque handles.

Enums

cadb_err_t

Values
CADB_OK, CADB_ERR_* 1–12
Meaning
Operation status; full names and values are listed above.

cadb_device_kind_t

Values
UNKNOWN=0, ANDROID_TV=1, CAST_TARGET=2, GENERIC_LAN=3
Meaning
Classification supplied by a device query or host.

cadb_device_state_t

Values
DISCONNECTED=0, CONNECTING=1, AUTHENTICATING=2, READY=3, BUSY=4, ERROR=5
Meaning
Lifecycle state for device-facing application logic.

cadb_task_kind_t

Values
INSTALL_APK=1, QUERY_DEVICE=2, SEND_KEY=3, SEND_TEXT=4, EXEC_COMMAND=5
Meaning
Kind of synchronous task.

cadb_task_state_t

Values
IDLE=0, RUNNING=1, SUCCEEDED=2, FAILED=3, CANCELLED=4
Meaning
Task result state.

cadb_task_stage_t

Values
NONE=0, FILE_TRANSFER=1, INSTALL_COMMAND=2, CLEANUP=3, COMPLETE=4
Meaning
Progress stage delivered to task observers.

Public structs

cadb_endpoint_t

Fields
host[256], port
Contract
Numeric IPv4/IPv6 accepted by built-in POSIX transport; port is 16-bit.

cadb_device_info_t

Fields
kind, state, endpoint, serial, name, model, brand, manufacturer, android_version, api_level, architecture, device
Contract
Fixed-size, NUL-terminated text buffers filled by device query or discovery.

cadb_progress_t

Fields
completed_bytes, total_bytes, percent
Contract
Transfer progress snapshot; callback data is valid for the callback duration.

cadb_task_info_t

Fields
task_id, kind, state, result, stage, cleanup_result
Contract
Cleanup status is reported independently from the primary task result.

cadb_shell_v2_result_t

Fields
exit_code, stdout_length, stderr_length, stdout_total_bytes, stderr_total_bytes, stdout_truncated, stderr_truncated
Contract
exit_code=-1 means no exit record arrived; totals include drained bytes beyond caller capacity.

cadb_packet_t

Fields
command, arg0, arg1, borrowed payload, payload_length, checksum
Contract
Packet header uses ADB's 24-byte little-endian framing. Decode sets payload to NULL.

cadb_auth_provider_t, cadb_sign_fn, cadb_public_key_fn

Fields
Opaque callback context, a signature callback receiving challenge/capacity and returning signature length, and a key callback returning encoded key bytes/length.
Contract
Callbacks keep key storage and signing in the host; cadb never stores private keys. Callback return status is propagated.

cadb_net_ops_t

Fields
connect, send, receive, close, optional start_tls
Contract
Partial I/O is allowed; every callback honors timeout/cancel. The TLS hook upgrades in place and validates the peer.

cadb_net_config_t

Fields
ops, context, default_timeout_ms
Contract
Custom vtable/context are borrowed and must outlive the network object.

cadb_config_t

Fields
net, socket_handle, protocol/payload limits, timeouts, banner, auth
Contract
Network and socket are borrowed. Zero values select documented defaults.

cadb_progress_fn, cadb_task_progress_fn, cadb_task_update_fn

Fields
Progress callbacks receive byte counts (task progress also receives task ID); task update receives a stage/result snapshot.
Contract
SYNC/task progress callbacks can cancel by returning non-OK; task update is observational and returns void.

cadb_sync_config_t

Fields
adb, chunk_size, progress callback and context
Contract
Chunk size defaults to 65536; callback errors abort the transfer.

cadb_task_config_t

Fields
adb, sync, progress/update callbacks and context
Contract
Dependencies are borrowed; task operations execute synchronously.

cadb_install_apk_request_t

Fields
local/remote paths, optional package, install output buffer, length and truncation outputs
Contract
Strings are borrowed for the call; remote temp cleanup result is reported separately.

cadb_device_found_fn

Fields
Context plus a const pointer to one device-info record for the reachable endpoint.
Contract
Callback error stops the scan and is returned.

cadb_discovery_options_t

Fields
IPv4 subnet prefix, host range, port, timeout
Contract
Prefix is exactly three decimal octets; host range is 1–254.

Cancellation API

cadb_err_t cadb_cancel_create(cadb_cancel_t **out_cancel)

Creates an opaque, thread-safe cancellation token backed by C11 atomics.

Parameter
out_cancel: receives the new token on success.
Return
CADB_OK or an error code.

void cadb_cancel_trigger(cadb_cancel_t *cancel)

Requests cancellation. Blocking operations poll this token.

Parameter
cancel: token to trigger.
Return
None.

void cadb_cancel_reset(cadb_cancel_t *cancel)

Clears a cancellation request so the token can be reused.

Parameter
cancel: token to reset.
Return
None.

bool cadb_cancel_is_triggered(const cadb_cancel_t *cancel)

Checks whether cancellation has been requested.

Parameter
cancel: token to inspect.
Return
true when triggered; otherwise false.

void cadb_cancel_destroy(cadb_cancel_t *cancel)

Releases the cancellation token.

Parameter
cancel: token to destroy.
Return
None.

Pass NULL to a cancellable operation to disable cancellation. Keep the token alive until every operation using it has returned.

03 / NETWORK

Transport handles and callback contracts

Declared in net.h. A network object provides connect/send/receive/close and an optional in-place TLS upgrade. The built-in POSIX backend can be selected with ops = NULL when compiled in.

Functions

cadb_err_t cadb_net_create(const cadb_net_config_t *config, cadb_net_t **out_net)

Purpose and contract
Creates backend state. On failure, output is NULL. A zero default timeout selects 10000 ms.
Return
CADB_OK, invalid argument, memory, or not supported.

void cadb_net_destroy(cadb_net_t *net)

Purpose and contract
Releases the network object; it does not close outstanding socket handles.
Return
void

cadb_err_t cadb_net_connect(cadb_net_t *net, const cadb_endpoint_t *endpoint, uint32_t timeout_ms, const cadb_cancel_t *cancel, cadb_socket_t *out_handle)

Purpose and contract
Opens a connection. Successful handles belong to the caller. Per-call timeout 0 selects the configured default.
Return
cadb_err_t

cadb_err_t cadb_net_send_all(cadb_net_t *net, cadb_socket_t handle, const uint8_t *data, size_t length, uint32_t timeout_ms, const cadb_cancel_t *cancel)

Purpose and contract
Loops across partial callback writes until all bytes are sent.
Return
cadb_err_t

cadb_err_t cadb_net_receive_exact(cadb_net_t *net, cadb_socket_t handle, uint8_t *buffer, size_t length, uint32_t timeout_ms, const cadb_cancel_t *cancel)

Purpose and contract
Loops until the requested byte count is received.
Return
cadb_err_t

void cadb_net_close(cadb_net_t *net, cadb_socket_t handle)

Purpose and contract
Closes a caller-owned handle through the configured backend.
Return
void

cadb_err_t cadb_net_start_tls(cadb_net_t *net, cadb_socket_t handle, uint32_t timeout_ms, const cadb_cancel_t *cancel)

Purpose and contract
Invokes the optional TLS hook on an existing socket. TLS handshake and peer validation are the backend's responsibility.
Return
CADB_ERR_NOT_SUPPORTED if no hook exists.

Custom cadb_net_ops_t requires connect, send, receive, and close callbacks. Each must honor timeout and cancellation; send/receive may make partial progress, but zero progress with CADB_OK is treated as I/O failure. Serialize operations on each socket handle.

04 / ADB SESSION

Protocol constants, authentication, streams

Declared in adb.h. cadb_t and cadb_stream_t are opaque. A session borrows its network object and socket handle; it permits one handshake attempt and one active service stream at a time.

ADB macros and enums

CADB_HEADER_SIZE

Value / meaning
24 bytes per ADB packet header.

CADB_MAX_PAYLOAD

Value / meaning
1 MiB default packet payload cap.

CADB_DEFAULT_PORT

Value / meaning
5555.

CADB_PROTOCOL_MIN_VERSION, CADB_PROTOCOL_VERSION

Value / meaning
Minimum 0x01000000; default 0x01000001.

CADB_STLS_VERSION

Value / meaning
ADB STLS protocol version constant.

CADB_MAX_AUTH_ROUNDS

Value / meaning
2: one signature challenge and one public-key challenge.

cadb_cmd_t

Value / meaning
CNXN=0x4e584e43, AUTH=0x48545541, OPEN=0x4e45504f, OKAY=0x59414b4f, CLSE=0x45534c43, WRTE=0x45545257, STLS=0x534c5453.

cadb_auth_type_t

Value / meaning
AUTH_TOKEN=1, AUTH_SIGNATURE=2, AUTH_RSAPUBLICKEY=3.

CADB_AUTH_TOKEN_SIZE

Value / meaning
20-byte challenge digest.

CADB_SHELL_V2_*

Value / meaning
Subpacket IDs: stdin 0, stdout 1, stderr 2, exit 3.

Session and packet functions

cadb_err_t cadb_create(const cadb_config_t *config, cadb_t **out_adb)

Contract
Creates a session using borrowed network/socket. Zero protocol, payload, timeout, and auth timeout select defaults.
Return / output
Error code; output handle on success.

void cadb_destroy(cadb_t *adb)

Contract
Destroys session state, but not the borrowed socket or network object.
Return / output
void

cadb_err_t cadb_connect(cadb_t *adb, const cadb_cancel_t *cancel)

Contract
Negotiates CNXN and optional AUTH. On any failed or cancelled handshake, discard session and socket and start fresh.
Return / output
Error code; one handshake attempt per session.

bool cadb_is_connected(const cadb_t *adb)

uint32_t cadb_get_max_payload(const cadb_t *adb)

const char *cadb_get_peer_banner(const cadb_t *adb)

Contract
Read connection status, negotiated payload cap, and peer banner.
Return / output
Bool, uint32, and borrowed string (or NULL).

cadb_err_t cadb_encode_header(const cadb_packet_t *packet, uint8_t header[CADB_HEADER_SIZE])

cadb_err_t cadb_decode_header(const uint8_t header[CADB_HEADER_SIZE], cadb_packet_t *out_packet)

Contract
Encode/decode 24-byte little-endian frames. Decode checks magic and payload bounds; it does not allocate a payload.
Return / output
Error code; decoded payload is NULL.

cadb_err_t cadb_validate_payload(const cadb_packet_t *packet, const uint8_t *payload, size_t length)

Contract
Checks packet payload length/checksum constraints.
Return / output
Error code.

Streams and command execution

cadb_err_t cadb_open_stream(cadb_t *adb, const char *service, const cadb_cancel_t *cancel, cadb_stream_t **out_stream)

Contract
Opens an ADB service such as shell:... or sync:. Close it before another stream or session destruction.
Return / output
CADB_ERR_BUSY when a stream is already active.

cadb_err_t cadb_stream_write(cadb_stream_t *stream, const uint8_t *data, size_t length, const cadb_cancel_t *cancel)

Contract
Writes bytes to the active service.
Return / output
Error code.

cadb_err_t cadb_stream_read(cadb_stream_t *stream, uint8_t *buffer, size_t capacity, size_t *out_read, const cadb_cancel_t *cancel)

Contract
Reads bytes. Capacity 0 is a no-op; zero bytes with nonzero capacity signals peer closure.
Return / output
Error code and byte count.

void cadb_stream_close(cadb_stream_t *stream)

Contract
Closes and releases the active stream.
Return / output
void

cadb_err_t cadb_exec(cadb_t *adb, const char *service, uint8_t *response, size_t capacity, size_t *out_length, const cadb_cancel_t *cancel)

Contract
Opens a service, drains all output, copies up to capacity, then closes the stream. A NULL buffer with zero capacity discards output.
Return / output
Error code and copied byte count.

cadb_err_t cadb_exec_shell_v2(cadb_t *adb, const char *command, uint8_t *stdout_buf, size_t stdout_capacity, uint8_t *stderr_buf, size_t stderr_capacity, cadb_shell_v2_result_t *out_result, const cadb_cancel_t *cancel)

Contract
Runs Shell v2 and drains excess output. Output buffers may be NULL when capacity is zero.
Return / output
CADB_OK means protocol success; inspect result->exit_code for command success. Truncation and total byte counts are returned separately.

AUTH signing callback receives the 20-byte SHA-1 challenge and must sign it directly as RSA PKCS#1 v1.5 DigestInfo(SHA-1), without hashing it again. Public-key callback returns the ADB-encoded key without a NUL terminator; cadb appends one. Private-key storage remains with the caller.

05 / FILE TRANSFER

SYNC push and remote cleanup

Declared in sync.h. The current API supports file push and remote removal. CADB_SYNC_MAX_CHUNK_SIZE is 65536 bytes.

cadb_err_t cadb_sync_create(const cadb_sync_config_t *config, cadb_sync_t **out_sync)

Contract and return values
Creates a SYNC client around a borrowed ADB session. Chunk size 0 selects the 65536-byte maximum; valid explicit range is 1–65536.

void cadb_sync_destroy(cadb_sync_t *sync)

Contract and return values
Releases the SYNC object; it does not destroy the borrowed ADB session.

cadb_err_t cadb_sync_push_file(cadb_sync_t *sync, const char *local_path, const char *remote_path, uint32_t mode, const cadb_cancel_t *cancel)

Contract and return values
Pushes a file and reports progress. On failure/cancellation, best-effort remote cleanup runs; original transfer error takes precedence.

cadb_err_t cadb_sync_remove_remote(cadb_sync_t *sync, const char *remote_path, const cadb_cancel_t *cancel)

Contract and return values
Removes a remote path using Shell v2; nonzero remote exit returns CADB_ERR_COMMAND_FAILED.

Remote paths must be absolute, use the documented safe ASCII character set, and contain no empty, ., or .. segments. Returning a non-CADB_OK progress callback status aborts the transfer and propagates that status.

06 / TASKS

Synchronous device operations

Declared in task.h. A task runner borrows ADB/SYNC objects and performs each operation synchronously while polling the optional cancellation token.

cadb_err_t cadb_task_runner_create(const cadb_task_config_t *config, cadb_task_runner_t **out_runner)

void cadb_task_runner_destroy(cadb_task_runner_t *runner)

Purpose
Create/release the task coordinator.
Output / special result
Runner borrows configured sessions and callback context.

cadb_err_t cadb_task_install_apk( cadb_task_runner_t *runner, const cadb_install_apk_request_t *request, const cadb_cancel_t *cancel, cadb_task_info_t *out_task)

Purpose
Pushes the APK, invokes installation, then attempts remote temp-file cleanup.
Output / special result
Task ID/stage/result; cleanup error is separate in cleanup_result; install output can be truncated.

cadb_err_t cadb_task_query_device(cadb_task_runner_t *runner, const cadb_cancel_t *cancel, cadb_device_info_t *out_device)

Purpose
Reads device properties.
Output / special result
Fills cadb_device_info_t.

cadb_err_t cadb_task_send_key(cadb_task_runner_t *runner, uint32_t key_code, const cadb_cancel_t *cancel, cadb_task_info_t *out_task)

Purpose
Sends a key event.
Output / special result
Task record.

cadb_err_t cadb_task_send_text(cadb_task_runner_t *runner, const char *utf8_text, const cadb_cancel_t *cancel, cadb_task_info_t *out_task)

Purpose
Sends UTF-8 text.
Output / special result
Task record.

cadb_err_t cadb_task_exec_command(cadb_task_runner_t *runner, const char *command, const cadb_cancel_t *cancel, cadb_task_info_t *out_task)

Purpose
Runs a remote command.
Output / special result
Task result distinguishes library errors from command outcome.

The progress callback runs synchronously during APK transfer; a non-OK status cancels and propagates. The update callback observes transfer/install/cleanup/final stages and cannot alter execution. Never block the callback waiting on work that needs the current task thread.

07 / DISCOVERY

IPv4 subnet probing

Declared in discovery.h. The prefix must contain exactly three decimal IPv4 octets (for example 192.168.1); leading zeroes are rejected. Host bounds are 1–254 with last_host >= first_host.

cadb_err_t cadb_discover_ipv4_range(cadb_net_t *net, const cadb_discovery_options_t *options, cadb_device_found_fn callback, void *context, const cadb_cancel_t *cancel)

Probes each generated host once on the configured port and calls callback for each reachable endpoint. A successful TCP connection only proves that the port is open; it does not identify an Android device or authenticate ADB.

Parameters
net, options, and callback configure the scan; context is passed to the callback; cancel is optional.
Return
CADB_OK or a timeout, cancellation, transport, invalid-argument, or callback error. A non-OK callback status stops the scan and is returned.

08 / COMPATIBILITY

Version compatibility and capability limits

  • Pin the source. Before 1.0, source and binary compatibility are not guaranteed. Depend on a release tag or full commit SHA, not a moving branch.
  • Match the transport to the platform. The built-in backend is POSIX TCP and accepts numeric IPv4/IPv6 addresses. Windows or custom TLS verification policy requires caller-provided cadb_net_ops_t.
  • Provide TLS where required. The library exposes an optional TLS-upgrade callback but does not bundle a TLS implementation or pairing flow.
  • Observe current feature boundaries. SYNC supports push/remove only; host-side adb server, USB transport, SYNC pull/stat/list, and built-in Windows sockets have no public entry point in this version.
  • Keep operations serialized. A session supports one active stream and must not be used concurrently. Only its cancellation token is designed to be shared across threads.
  • Preserve MIT notices. Closed-source redistribution is allowed when the cadb copyright and permission notice are included.

For a runnable setup, continue to Quick Start. For authentication and host-language examples, see Samples.