Skip to content
weenasPublic

About

Lightweight C11 client library for talking directly to adbd over TCP.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

cadb

cadb — C11 ADB client library

Embed ADB directly into your app.

A lightweight, dependency-free C11 library that connects directly to Android devices over ADB TCP — without bundling the adb executable or running a host ADB Server.

Pure C11 · Small native core · C ABI for many languages · Caller-managed keys and TLS · Cancellable device tasks

The native library itself needs no virtual machine, garbage collector, interpreter, or C++ runtime. In a representative macOS arm64 Release build, the static archive was 34 KB and the shared library 53 KB; actual size varies by platform, toolchain, and build options.

flowchart LR
    App["Your app<br/>C · Swift · Kotlin/JNI · Flutter · React Native · Rust · Python · C++"]
    Core["cadb<br/>native C11 library"]
    Transport["POSIX TCP<br/>or custom transport / TLS"]
    Device["Android / TV<br/>adbd"]
    App -->|"C ABI / FFI / bridge"| Core
    Core --> Transport --> Device
Loading

Why embed cadb?

  • No host ADB stack to ship or supervise — link the C library into your app and connect directly to the device's ADB TCP endpoint.
  • Keep security in your app — ADB signing is provided through callbacks; TLS can use a platform transport. Private keys and trust policy stay with the host application.
  • Build complete device workflows — Shell v2, progress-reporting SYNC push, APK install, installed-app queries, app uninstall/enable/disable, device queries, key events, and text input are available through one C ABI.
  • Own timeouts and cancellation — network operations accept timeouts and a thread-safe cancellation token; transports are injectable for platform integration and tests.

Use cadb from C/C++, Swift/Objective-C, Android JNI, Flutter/Dart FFI, React Native native modules, Rust, or Python. The language examples include the required bridge/FFI layer; they are integration starting points, not zero-setup bindings.

Project website · Browse language samples · Quickstart · Build and test

AI coding tools: Read AGENTS.md for contribution guidance before making changes. This file points to the project documentation for API and integration details rather than duplicating it.

Core capabilities

  • Direct ADB/TCP client: 24-byte packet framing, CNXN negotiation, callback-based AUTH (at most CADB_MAX_AUTH_ROUNDS token challenges), optional STLS upgrade, and serialized streams.
  • Application-ready shell: Shell v2 captures stdout/stderr separately and returns the device command's exit status.
  • File and APK workflows: SYNC pushes files in chunks up to 65536 bytes, reports progress, supports cancellation, and best-effort cleans up failed remote transfers; APK tasks report task-ID-scoped transfer progress, install/cleanup stage updates, and cleanup errors.
  • Portable C API: Opaque handles and a C ABI designed for C++, Swift/Objective-C, JNI, and FFI callers.
  • Pluggable networking: Built-in POSIX TCP or a caller-provided transport for platform sockets, TLS, and deterministic tests.

What cadb Does NOT Do

To keep the library small, auditable, and MIT-pure, cadb intentionally excludes:

  • No host-side adb server / daemon: Does not implement the localhost:5037 smart-socket server, USB device tracking, or adb start-server management.
  • No USB transport: Only TCP (or caller-supplied cadb_net_ops_t stream transports) is supported; no libusb / WinUSB / IOKit USB code.
  • No built-in RSA crypto, key storage, or TLS/SPAKE2 pairing: Private key storage and signing are delegated to cadb_auth_provider_t callbacks; pairing and identity storage belong to the caller (e.g., iOS Keychain/SecKey or Android Keystore). A custom transport can provide an already-TLS-connected handle for wireless debugging, or implement the optional STLS upgrade hook; that hook is responsible for TLS handshake and peer validation.
  • No mDNS / Bonjour / NSD: Service discovery via _adb-tls-connect._tcp or _adb-tls-pairing._tcp should be handled by platform APIs (NWBrowser, NsdManager, Avahi, etc.).
  • No SYNC pull / stat / list yet: Current cadb_sync focuses on pushing files (SEND/DATA/DONE) and removing temporary remote files.
  • No built-in Winsock2 backend yet: Built-in networking targets POSIX (macOS, Linux, Android, iOS); Windows consumers can plug in a cadb_net_ops_t implementation.

Unsupported behavior and error codes

Condition Stable behavior
Built-in backend was not compiled and cadb_net_create() receives ops == NULL Returns CADB_ERR_NOT_SUPPORTED; sets *out_net to NULL. Provide a custom cadb_net_ops_t to use the library without the POSIX backend.
An ADB peer requests the STLS upgrade but the transport has no start_tls callback Returns CADB_ERR_NOT_SUPPORTED; the caller must provide a TLS-capable transport or use an already-TLS-connected handle.
A second stream is opened while one is active Returns CADB_ERR_BUSY; close the active stream before opening another. Session calls must be serialized by the caller.
USB, host-side ADB server, SYNC pull/stat/list, or a built-in Windows socket backend These operations have no public entry point in this version, so cannot be invoked and do not return a runtime error. If a later API exposes one while its backend remains unavailable, it will return CADB_ERR_NOT_SUPPORTED.

Remote Android App Management

include/cadb/apps.h adds task-based APIs for listing apps installed for Android's primary user (user 0), uninstalling a package for that user, and enabling or disabling a package. These commands use ADB shell through cadb; they do not implement a second ADB protocol. The task runner can be created with only an ADB handle for these shell-only operations. Existing APK install still requires a SYNC handle and keeps its existing API and behavior.

cadb_task_config_t task_config = {0};
cadb_task_runner_t *runner = NULL;
cadb_app_info_t apps[128];
cadb_app_query_t query = {0};
size_t count = 0;
bool truncated = false;

task_config.adb = adb;
if (cadb_task_runner_create(&task_config, &runner) != CADB_OK) {
    /* handle error */
}
query.system_filter = CADB_APP_FILTER_USER_ONLY;
query.keyword = "stream"; /* optional package-name substring */
if (cadb_task_query_apps(runner, &query, apps, 128, &count, &truncated,
                         cancel, &task) == CADB_OK) {
    /* inspect count records; check available_fields before using optional data */
}
cadb_task_runner_destroy(runner);

The query is bounded: max_results == 0 uses the default limit of 256, CADB_APP_QUERY_MAX_LIMIT is 4096, and out_truncated signals that either the caller's array, requested result limit, or internal listing capture omitted matches. Each operation returns a task ID, stage, final state and standard cadb_err_t; command operations also retain separate device stdout/stderr and the shell exit code in caller-provided buffers. The existing ADB I/O timeout and cancellation token apply to each operation.

The package label and version name are intentionally reported as unavailable: Android does not expose a stable, locale-independent app-label query through the ordinary ADB shell interface. versionCode is returned only when the device's pm list packages --show-versioncode output contains a parseable value; older package-manager implementations fall back to a plain package listing. The system-app and enabled flags come from Package Manager's -s and -e filters. Fields are valid only when their CADB_APP_FIELD_* bit is set.

For device-localized application labels and PNG icons, use the additive, versioned cadb_task_query_app_metadata_v1 task after obtaining package names. It leaves cadb_task_query_apps and its ABI unchanged, returns fields through a callback with explicit availability flags, and uses bounded temporary helper deployment. Its ownership, limits, compatibility caveats, and example are documented in Installed app display names and icons.

By default, uninstall/enable/disable first check the system-package listing and refuse a package identified as a system app with CADB_ERR_PERMISSION_DENIED. If this check fails or its output is incomplete, the operation fails closed. allow_system_apps is an explicit opt-in to issue the command for system packages; ordinary ADB shell access still cannot bypass device policy, protected-package restrictions, or OEM limitations. Android does not provide a reliable generic distinction between “critical” and “non-critical” system packages, so CADB protects all packages classified as system apps by default. These operations target user 0 only; they do not manage secondary users or work profiles. Android TV / Google TV builds differ by API level and vendor: package-manager flags and mutability can vary, and a command may return a device-side failure even after successful ADB authentication.

The optional OpenSSL CLI sample exposes the operations for manual testing:

./build/examples/cadb_cli 192.168.1.80 5555 apps user stream
./build/examples/cadb_cli 192.168.1.80 5555 disable com.example.tv
./build/examples/cadb_cli 192.168.1.80 5555 enable com.example.tv
./build/examples/cadb_cli 192.168.1.80 5555 uninstall com.example.tv
# Explicit opt-in for a system package:
./build/examples/cadb_cli 192.168.1.80 5555 disable com.android.tv --allow-system

Only use the system override when the target package and device recovery path are understood. The CLI example is not a replacement for OEM provisioning or privileged device-management APIs.

CADB_ERR_NOT_SUPPORTED is reserved for a known operation or backend that the current build/transport cannot provide. It is distinct from CADB_ERR_IO, which reports a failed supported operation. Applications can map the stable enum to their own platform-specific guidance.

Directory Layout

cadb/
├── CMakeLists.txt
├── LICENSE                     # MIT License
├── README.md
├── cmake/
│   ├── cadb.pc.in
│   └── cadbConfig.cmake.in
├── include/cadb/               # Public C11 headers (C++ & FFI compatible)
│   ├── cadb.h                  # Umbrella header
│   ├── adb.h                   # Framing, CNXN/AUTH/STLS handshake, streams, exec
│   ├── discovery.h             # IPv4 range TCP probing
│   ├── export.h                # Shared/static symbol visibility macros
│   ├── net.h                   # Transport abstraction & POSIX backend hook
│   ├── sync.h                  # SYNC file transfer
│   ├── task.h                  # APK install, device query, key/text helpers
│   ├── apps.h                  # Installed-app query and package management
│   ├── types.h                 # Error codes, structs, cadb_cancel_t
│   └── version.h               # Version macros & accessors
├── src/                        # Internal implementation (never installed)
├── examples/
│   ├── minimal_connect.c       # Zero-dependency quickstart sample
│   ├── adb_cli.c               # Optional OpenSSL sample for ~/.android/adbkey
│   └── languages/              # C ABI facade and language bridge examples
│       ├── README.md            # Build notes and language index
│       ├── cadb_sample.c/.h     # Example-only C ABI facade
│       ├── android/             # JNI / Java
│       ├── cpp/                 # C++
│       ├── flutter/             # Dart FFI
│       ├── mobile/              # Native AUTH callback adapter
│       ├── objc/                # Objective-C
│       ├── python/              # ctypes
│       ├── react-native/        # JavaScript native-module call
│       ├── rust/                # Rust FFI
│       └── swift/               # Swift bridging header call
├── tests/                      # CTest unit & protocol mock test suite
└── web/                        # Static website, crawler rules, sitemap, and LLM index

Building & Testing

Requirements: C11 compiler (clang, gcc, or msvc) and CMake >= 3.16. Optional: OpenSSL::Crypto (libcrypto) if you want to build the cadb_cli real-device sample.

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

On macOS with Homebrew OpenSSL 3 (for cadb_cli):

cmake -S . -B build -DCMAKE_PREFIX_PATH="$(brew --prefix openssl@3)"
cmake --build build
ctest --test-dir build --output-on-failure

CMake Options

Option Default (Top-Level / Subproject) Description
BUILD_SHARED_LIBS OFF Build shared library (libcadb.so / .dylib / .dll) instead of static
CADB_BUILD_TESTS ON / OFF Build unit tests under tests/
CADB_BUILD_EXAMPLES ON / OFF Build sample binaries under examples/
CADB_ENABLE_INSTALL ON / OFF Enable cmake --install rules, cadbConfig.cmake, and cadb.pc
CADB_WITH_POSIX_NET ON (non-Windows) / OFF (Windows) Compile the built-in POSIX TCP transport
CADB_STRICT_WARNINGS ON / OFF Enable -Wall -Wextra -Wpedantic -Wshadow -Wconversion (or /W4)
CADB_ENABLE_SANITIZERS OFF Instrument cadb and its tests/examples with AddressSanitizer and UndefinedBehaviorSanitizer (GCC/Clang only)

Address and Undefined Behavior Sanitizer Checks

On GCC or Clang toolchains, enable both sanitizers for the library and test executables:

cmake -S . -B build-sanitize \
  -DCMAKE_BUILD_TYPE=Debug \
  -DCADB_BUILD_TESTS=ON \
  -DCADB_BUILD_EXAMPLES=OFF \
  -DCADB_ENABLE_SANITIZERS=ON
cmake --build build-sanitize --parallel
ctest --test-dir build-sanitize --output-on-failure

Sanitizer instrumentation is opt-in and does not affect normal or downstream builds unless explicitly enabled.

Integrating into Downstream Projects

Option 1: add_subdirectory or FetchContent

When included as a subproject, tests, examples, and install rules default to OFF.

include(FetchContent)
FetchContent_Declare(
    cadb
    GIT_REPOSITORY https://github.com/weenas/cadb.git
    # Replace with a reviewed immutable release tag or full commit SHA.
    GIT_TAG        <reviewed-tag-or-commit-sha>
)
FetchContent_MakeAvailable(cadb)

target_link_libraries(your_target PRIVATE cadb::cadb)

Option 2: System Install + find_package

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build
sudo cmake --install build

Then in your CMakeLists.txt:

find_package(cadb REQUIRED)
target_link_libraries(your_target PRIVATE cadb::cadb)

Before 1.0, source and binary compatibility are not guaranteed. Downstream apps should pin an immutable release tag or full commit SHA and update deliberately; do not track the moving main branch.

Remote paths passed to SYNC push/remove and APK install must be absolute, contain only ASCII letters, digits, /, _, -, and ., and contain no empty, . or .. path segments.

Quickstart Samples

1. Minimal Zero-Dependency Sample (examples/minimal_connect.c)

Connects to an unauthenticated adbd TCP endpoint (for example an emulator or ro.adb.secure=0 target) and runs a shell command:

./build/examples/cadb_minimal_connect 127.0.0.1 5555 "uname -a"

2. Real-Device CLI Sample with RSA AUTH (examples/adb_cli.c)

Uses OpenSSL::Crypto to read $CADB_KEY or ~/.android/adbkey (2048-bit RSA PEM) and talk to real Android / Android TV devices:

# Print SHA-256 fingerprint of your ADB public key
./build/examples/cadb_cli --key-check

# Query device properties
./build/examples/cadb_cli 192.168.1.80 5555 info

# Run a shell command (shell v2: stdout on stdout, stderr on stderr,
# remote exit code printed and returned as the process exit code)
./build/examples/cadb_cli 192.168.1.80 5555 shell "getprop ro.product.model"

# Push a file via SYNC
./build/examples/cadb_cli 192.168.1.80 5555 push ./app.apk /data/local/tmp/app.apk

# Push + install an APK (and clean up the remote temp file)
./build/examples/cadb_cli 192.168.1.80 5555 install ./app.apk

Note on ADB AUTH signing: In the classic ADB protocol, the AUTH_TOKEN payload sent by adbd is already a 20-byte SHA-1 digest. Your cadb_sign_fn callback must sign it directly as PKCS#1 v1.5 DigestInfo(SHA-1) (for example via OpenSSL EVP_PKEY_sign with EVP_sha1(), not EVP_DigestSign, which would hash the challenge a second time).

Minimal Code Snippet

#include <cadb/cadb.h>
#include <stdio.h>

int main(void) {
    cadb_net_t *net = NULL;
    cadb_t *adb = NULL;
    cadb_socket_t sock = CADB_INVALID_SOCKET;

    cadb_net_config_t net_cfg = { .default_timeout_ms = 5000 };
    if (cadb_net_create(&net_cfg, &net) != CADB_OK) return 1;

    cadb_endpoint_t ep = { .host = "127.0.0.1", .port = CADB_DEFAULT_PORT };
    if (cadb_net_connect(net, &ep, 5000, NULL, &sock) != CADB_OK) goto cleanup;

    cadb_config_t cfg = {
        .net = net,
        .socket_handle = sock,
        .timeout_ms = 5000,
        /* .auth = { .context = ctx, .sign = my_sign, .get_public_key = my_pubkey }, */
    };
    if (cadb_create(&cfg, &adb) != CADB_OK || cadb_connect(adb, NULL) != CADB_OK) {
        goto cleanup;
    }

    uint8_t out[4096];
    size_t out_len = 0;
    if (cadb_exec(adb, "shell:getprop ro.product.model", out, sizeof(out) - 1, &out_len, NULL) == CADB_OK) {
        out[out_len] = '\0';
        printf("%s", (const char *)out);
    }

cleanup:
    cadb_destroy(adb);
    if (sock != CADB_INVALID_SOCKET) cadb_net_close(net, sock);
    cadb_net_destroy(net);
    return 0;
}

License

cadb is released under the MIT License.

About

Lightweight C11 client library for talking directly to adbd over TCP.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages