32 Commits

Author SHA1 Message Date
cocool97
8c382f0bde feat: add mdns devices discovery (#54)
* feat: add mdns devices discovery

---------

Co-authored-by: Jinke <164604729+JinkeJ@users.noreply.github.com>
2024-12-01 18:39:07 +01:00
cocool97
b933ab083f feat: add benches (#58)
* feat: add benches
2024-11-30 11:34:35 +01:00
cli
2f4d13bd29 feat: create an USBTransport from a rusb::Device (#66)
This allows to be more flexible on USB device we want to connect to,
without making public API to complex
2024-11-30 10:21:21 +01:00
cli
9eeb8f7da8 feat: add direct devices TLS support; refactoring (#64)
* feat: massive internal refactoring

* feat: fix doc + add 'doc' github action

* feat: improve code; add TLS

---------

Co-authored-by: LIAUD Corentin <corentinliaud26@gmail.com>
2024-11-29 13:30:03 +01:00
cocool97
152836fe54 feat: add framebuffer_bytes method (#61)
* feat: add `framebuffer_bytes` method
2024-11-18 17:15:11 +01:00
cocool97
507796887b feat: rework USB auth (#60)
* feat: rework USB auth

* ci: run clippy with `--all-features`
2024-11-18 14:43:40 +01:00
cocool97
2f08e5e16d fix: pub export AdbStatResponse (#59)
* chore: clarify licensing

* fix: pub export AdbStatResponse
2024-11-17 18:16:20 +01:00
LIAUD Corentin
6a2d652f60 chore: version 2.0.3 2024-11-14 20:56:19 +01:00
cocool97
b7ae0b1155 feat: add install command (tcp + usb) (#56) 2024-11-14 20:48:12 +01:00
MahieDev
ec0ae681ac fix: underflow in recv (#53)
* fix: read length
2024-11-10 12:58:28 +01:00
LIAUD Corentin
61ba07ecf0 fix: minor improvments 2024-11-09 14:00:23 +01:00
Himadri Bhattacharjee
c835f20263 feat: add run_activity method and default impl for ADBDeviceExt 2024-11-09 14:00:23 +01:00
Himadri Bhattacharjee
b51965f5af feat: add adb run command with activitymanager
### Changes
- `LocalCommand` and `USBCommand` now have respective variants for "run"
- Both these impls run the shell command `am start INTENT`
2024-11-09 14:00:23 +01:00
LIAUD Corentin
66b0e4c71c license: remove license-file in favor of license 2024-11-09 13:40:59 +01:00
LIAUD Corentin
cb23fd6155 ci: add publish on crates.io 2024-11-05 08:03:33 +01:00
Rohit Sangwan
d932e93d0b Add Forward and Reverse commands 2024-11-04 08:01:54 +01:00
LIAUD Corentin
e60ae7434b ci: deb + rpm + binary upload on new release 2024-11-02 18:06:17 +01:00
LIAUD Corentin
005d864609 chore: add license file 2024-11-02 18:06:17 +01:00
LIAUD Corentin
4d8e5d9367 chore: version 2.0.1 2024-10-31 16:05:19 +01:00
Himadri Bhattacharjee
cff0e68f46 feat: autodetect an ADB device when no vendor or product ID is specified (#44)
* feat: autodetect an ADB device when no vendor or product ID is specified

### Changes

- Added methods `autodetect` to `autodetect_with_custom_private_key` to
`ADBUSBDevice`
- Added private functions to check if a usb device has the signature of
an ADB device
- Made the `vendor_id` and `product_id` USB arguments optional and
default to aforementioned methods

* fix: improve github actions workflows

---------

Co-authored-by: LIAUD Corentin <corentinliaud26@gmail.com>
2024-10-31 16:00:13 +01:00
LIAUD Corentin
266265ca35 feat: v2.0.0 2024-10-25 18:13:11 +02:00
cocool97
479d2d9ade Support devices over usb (#40)
* feat: device interactions over USB (shell, push, pull, reboot for now)

* feat: parse vid and pid from hex as seen in lsusb output (#32)

* usb: Read RSA keypair from user home or generate them (#34)

* feat read keypair from user home or generate ephemeral ones
---------

Co-authored-by: LIAUD Corentin <corentin.liaud@orange.fr>
Co-authored-by: Himadri Bhattacharjee <107522312+lavafroth@users.noreply.github.com>
2024-10-25 18:09:41 +02:00
LIAUD Corentin
c53f5cc11b feat: update workflow 2024-10-24 12:21:29 +02:00
Jinke
95fe89a12c Fix RegexParsingError when parsing device list (#37) 2024-10-11 15:43:51 +02:00
cocool97
e37b6d47cc feat: add github actions (#39) 2024-10-11 15:33:00 +02:00
cocool97
d2d9ede8ab feat: add logo + rework README.md (#38) 2024-10-10 16:41:16 +02:00
cocool97
ed884b0d27 feat: should make crate usable on Windows (#35)
Co-authored-by: LIAUD Corentin <corentin.liaud@orange.fr>
2024-10-01 19:39:25 +02:00
LIAUD Corentin
2f39c13355 feat: v1.0.7 2024-09-28 21:30:44 +02:00
LIAUD Corentin
488af2b9dd feat: improve performances of recv & send 2024-09-28 21:29:09 +02:00
LIAUD Corentin
83d716d685 release: 1.0.6 2024-09-13 13:56:42 +02:00
Samuel Cavalcanti
101fafe4ec Fix pairing (#30)
* fix: pairing code that starts with 0

* feat: add`no_run` end `std::io::stdout` to pass in examples
---------

Co-authored-by: LIAUD Corentin <corentin.liaud@orange.fr>
2024-09-13 13:49:46 +02:00
LIAUD Corentin
251276c766 feat: add logcat + log crate 2024-09-05 16:54:39 +02:00
103 changed files with 4379 additions and 1270 deletions

15
.github/workflows/rust-build.yml vendored Normal file
View File

@@ -0,0 +1,15 @@
name: Rust - Build
on: [push, pull_request]
env:
CARGO_TERM_COLOR: always
jobs:
build-release:
name: "build-release"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build project
run: cargo build --release --all-features

42
.github/workflows/rust-quality.yml vendored Normal file
View File

@@ -0,0 +1,42 @@
name: Rust - Quality
on: [push, pull_request]
env:
CARGO_TERM_COLOR: always
jobs:
clippy:
name: "clippy"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: rustup component add clippy
- name: Run clippy
run: cargo clippy --all-features
fmt:
name: "fmt"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run formatter
run: cargo fmt --all --check
doc:
name: "doc"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run doc
run: cargo doc --all-features --no-deps
env:
RUSTDOCFLAGS: "-D warnings"
tests:
name: "tests"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
run: cargo test --verbose --all-features

50
.github/workflows/rust-release.yml vendored Normal file
View File

@@ -0,0 +1,50 @@
name: Rust - Release creation
on:
release:
types: [created]
jobs:
create-release:
runs-on: ubuntu-latest
steps:
- name: "Checkout repository"
uses: actions/checkout@v4
- name: "Set up Rust"
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: "Install dependencies"
run: |
sudo apt update
sudo apt install -y rpm
cargo install cargo-deb
cargo install cargo-generate-rpm
- name: "build-release"
run: cargo build --all-features --release
- name: "Build DEB package"
run: cargo deb -p adb_cli
- name: "Build RPM package"
run: cargo generate-rpm -p adb_cli
- name: "Publish GitHub artefacts"
uses: softprops/action-gh-release@v2
with:
files: |
target/debian/*.deb
target/generate-rpm/*.rpm
target/release/adb_cli
- name: "Publish crates"
run: |
cargo publish -p adb_client --token ${CRATES_IO_TOKEN}
cargo publish -p adb_cli --token ${CRATES_IO_TOKEN}
env:
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}

View File

@@ -3,11 +3,21 @@ members = ["adb_cli", "adb_client"]
resolver = "2"
[workspace.package]
authors = ["Corentin LIAUD"]
edition = "2021"
license = "GPL-3.0"
homepage = "https://github.com/cocool97/adb_client"
keywords = ["adb", "android", "tcp", "usb"]
license = "MIT"
repository = "https://github.com/cocool97/adb_client"
version = "1.0.4"
version = "2.0.6"
# To build locally when working on a new version
# To build locally when working on a new release
[patch.crates-io]
adb_client = { path = "./adb_client" }
adb_client = { path = "./adb_client" }
[profile.release]
codegen-units = 1
debug-assertions = false
lto = "thin"
opt-level = 'z'
strip = true

695
LICENSE
View File

@@ -1,674 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
MIT License
Copyright (c) 2023-2024 Corentin LIAUD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

100
README.md
View File

@@ -1,76 +1,52 @@
# adb_client
<p align="center" style="text-align: center">
<img src="assets/logo.png" width="33%">
</p>
[![Latest version](https://img.shields.io/crates/v/adb_client.svg)](https://crates.io/crates/adb_client)
[![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT)
[![dependency status](https://deps.rs/repo/github/cocool97/adb_client/status.svg)](https://deps.rs/repo/github/cocool97/adb_client)
[![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client)
<p align="center">
<p align="center">Android Debug Bridge (ADB) client implementation in pure Rust !</p>
<p align="center">
<a href="https://crates.io/crates/adb_client">
<img alt="crates.io" src="https://img.shields.io/crates/v/adb_client.svg"/>
</a>
<a href="https://github.com/cocool97/adb_client/actions">
<img alt="ci status" src="https://github.com/cocool97/adb_client/actions/workflows/rust-build.yml/badge.svg"/>
</a>
<a href="https://deps.rs/repo/github/cocool97/adb_client">
<img alt="dependency status" src="https://deps.rs/repo/github/cocool97/adb_client/status.svg"/>
</a>
<a href="https://opensource.org/licenses/MIT">
<img alt="dependency status" src="https://img.shields.io/badge/License-MIT-yellow.svg"/>
</a>
</p>
</p>
Android Debug Bridge (ADB) client implementation in pure Rust !
Main features of this library:
Main features :
- Full Rust, no need to use `adb *` shell commands
- Currently only support server TCP/IP protocol
- Full Rust, don't use `adb *` shell commands to interact with devices
- Supports
- Using ADB server as a proxy (standard behavior when using `adb` CLI)
- Connecting directly to end devices (without using adb-server)
- Over **USB**
- Over **TCP/IP**
- Implements hidden `adb` features, like `framebuffer`
- Highly configurable
- Easy to use !
## Examples
## adb_client
First declare `adb_client` as a dependency by simply adding it to your `Cargo.toml`:
Rust library implementing both ADB protocols (server and end-devices) and providing a high-level abstraction over the many supported commands.
```toml
[dependencies]
adb_client = "*"
```
Improved documentation available [here](./adb_client/README.md).
### Launch a command on device via ADB server
## adb_cli
```rust
use adb_client::ADBServer;
Rust binary providing an improved version of Google's official `adb` CLI, by using `adb_client` library.
Provides an usage example of the library.
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
device.shell_command(["df", "-h"]);
```
Improved documentation available [here](./adb_cli/README.md).
### Get available ADB devices
## Related publications
```rust
use adb_client::ADBServer;
use std::net::{SocketAddrV4, Ipv4Addr};
- [Diving into ADB protocol internals (1/2)](https://www.synacktiv.com/publications/diving-into-adb-protocol-internals-12)
// A custom server address can be provided
let server_ip = Ipv4Addr::new(127, 0, 0, 1);
let server_port = 5037;
let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
server.devices();
```
### Push a file to the device
```rust
use adb_client::ADBServer;
use std::net::Ipv4Addr;
use std::fs::File;
use std::path::Path;
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
let mut input = File::open(Path::new("/tmp")).unwrap();
device.send(&mut input, "/data/local/tmp");
```
## Rust binary
This crate also provides a lightweight binary based on the `adb_client` crate. You can install it by running the following command :
```shell
cargo install adb_cli
```
## Missing features
- USB protocol
All pull requests are welcome !
Some features may still be missing, all pull requests are welcome !

View File

@@ -1,14 +1,39 @@
[package]
authors.workspace = true
description = "Rust ADB (Android Debug Bridge) CLI"
edition.workspace = true
keywords = ["adb", "android"]
keywords.workspace = true
license.workspace = true
name = "adb_cli"
readme = "../README.md"
readme = "README.md"
repository.workspace = true
version.workspace = true
[dependencies]
adb_client = { version = "1.0.4" }
anyhow = { version = "1.0.86" }
clap = { version = "4.5.9", features = ["derive"] }
adb_client = { version = "2.0.5" }
anyhow = { version = "1.0.89" }
clap = { version = "4.5.18", features = ["derive"] }
env_logger = { version = "0.11.5" }
log = { version = "0.4.22" }
[target.'cfg(unix)'.dependencies]
termios = { version = "0.3.3" }
#####################################
# Debian package build instructions #
#####################################
[package.metadata.deb]
assets = [
{ source = "target/release/adb_cli", dest = "usr/bin/", mode = "755" },
]
priority = "optional"
section = "utility"
##################################
# RPM package build instructions #
##################################
[package.metadata.generate-rpm]
assets = [
{ source = "target/release/adb_cli", dest = "/usr/bin/adb_cli", mode = "755" },
]
license = "MIT"

76
adb_cli/README.md Normal file
View File

@@ -0,0 +1,76 @@
# adb_cli
[![MIT licensed](https://img.shields.io/crates/l/adb_cli.svg)](./LICENSE-MIT)
![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_cli)
Rust binary providing an improved version of `adb` CLI.
## Rust binary
This crate provides a lightweight binary based on the `adb_client` crate. You can install it by running the following command :
```shell
cargo install adb_cli
```
Usage is quite simple, and tends to look like `adb`:
- To use ADB server as a proxy:
```bash
user@laptop ~/adb_client (main)> adb_cli --help
Rust ADB (Android Debug Bridge) CLI
Usage: adb_cli [OPTIONS] <COMMAND>
Commands:
host-features List available server features
push Push a file on device
pull Pull a file from device
list List a directory on device
stat Stat a file specified on device
shell Spawn an interactive shell or run a list of commands on the device
reboot Reboot the device
framebuffer Dump framebuffer of device
logcat Get logs of device
version Print current ADB version
kill Ask ADB server to quit immediately
devices List connected devices
track-devices Track new devices showing up
pair Pair device with a given code
connect Connect device over WI-FI
disconnect Disconnect device over WI-FI
sms Send a SMS with given phone number and given content
rotate Rotate device screen from 90°
help Print this message or the help of the given subcommand(s)
Options:
-d, --debug
-a, --address <ADDRESS> [default: 127.0.0.1:5037]
-s, --serial <SERIAL> Serial id of a specific device. Every request will be sent to this device
-h, --help Print help
-V, --version Print version
```
- To interact directly with end devices
```bash
user@laptop ~/adb_client (main)> adb_cli usb --help
Device commands via USB, no server needed
Usage: adb_cli usb [OPTIONS] --vendor-id <VID> --product-id <PID> <COMMAND>
Commands:
shell Spawn an interactive shell or run a list of commands on the device
pull Pull a file from device
push Push a file on device
stat Stat a file on device
reboot Reboot the device
help Print this message or the help of the given subcommand(s)
Options:
-v, --vendor-id <VID> Hexadecimal vendor id of this USB device
-p, --product-id <PID> Hexadecimal product id of this USB device
-k, --private-key <PATH_TO_PRIVATE_KEY> Path to a custom private key to use for authentication
-h, --help Print help
```

View File

@@ -1,3 +1,5 @@
#![cfg(any(target_os = "linux", target_os = "macos"))]
use std::os::unix::prelude::{AsRawFd, RawFd};
use termios::{tcsetattr, Termios, TCSANOW, VMIN, VTIME};
@@ -33,6 +35,8 @@ impl ADBTermios {
impl Drop for ADBTermios {
fn drop(&mut self) {
// Custom drop implementation, restores previous termios structure.
tcsetattr(self.fd, TCSANOW, &self.old_termios).unwrap();
if let Err(e) = tcsetattr(self.fd, TCSANOW, &self.old_termios) {
log::error!("Error while droping ADBTermios: {e}")
}
}
}

View File

@@ -16,9 +16,24 @@ pub enum HostCommand {
/// Track new devices showing up.
TrackDevices,
/// Pair device with a given code
Pair { address: SocketAddrV4, code: u32 },
Pair { address: SocketAddrV4, code: String },
/// Connect device over WI-FI
Connect { address: SocketAddrV4 },
/// Disconnect device over WI-FI
Disconnect { address: SocketAddrV4 },
/// MDNS services
Mdns {
#[clap(subcommand)]
subcommand: MdnsCommand,
},
/// Display server status
ServerStatus,
}
#[derive(Parser, Debug)]
pub enum MdnsCommand {
/// Check mdns status
Check,
/// List mdns services available
Services,
}

View File

@@ -1,4 +1,5 @@
use clap::Parser;
use std::path::PathBuf;
use crate::models::RebootTypeCommand;
@@ -15,12 +16,31 @@ pub enum LocalCommand {
/// Stat a file specified on device
Stat { path: String },
/// Spawn an interactive shell or run a list of commands on the device
Shell { command: Vec<String> },
Shell { commands: Vec<String> },
/// Run an activity on device specified by the intent
Run {
/// The package whose activity is to be invoked
#[clap(short = 'p', long = "package")]
package: String,
/// The activity to be invoked itself, Usually it is MainActivity
#[clap(short = 'a', long = "activity")]
activity: String,
},
/// Reboot the device
Reboot {
#[clap(subcommand)]
sub_command: RebootTypeCommand,
reboot_type: RebootTypeCommand,
},
/// Dump framebuffer of device
Framebuffer { path: String },
/// Get logs of device
Logcat {
/// Path to output file (created if not exists)
path: Option<String>,
},
/// Install an APK on device
Install {
/// Path to APK file. Extension must be ".apk"
path: PathBuf,
},
}

View File

@@ -1,7 +1,11 @@
mod emu;
mod host;
mod local;
mod tcp;
mod usb;
pub use emu::EmuCommand;
pub use host::HostCommand;
pub use host::{HostCommand, MdnsCommand};
pub use local::LocalCommand;
pub use tcp::{TcpCommand, TcpCommands};
pub use usb::{UsbCommand, UsbCommands};

View File

@@ -0,0 +1,44 @@
use std::net::SocketAddr;
use std::path::PathBuf;
use clap::Parser;
use crate::models::RebootTypeCommand;
#[derive(Parser, Debug)]
pub struct TcpCommand {
pub address: SocketAddr,
#[clap(subcommand)]
pub commands: TcpCommands,
}
#[derive(Parser, Debug)]
pub enum TcpCommands {
/// Spawn an interactive shell or run a list of commands on the device
Shell { commands: Vec<String> },
/// Pull a file from device
Pull { source: String, destination: String },
/// Push a file on device
Push { filename: String, path: String },
/// Stat a file on device
Stat { path: String },
/// Run an activity on device specified by the intent
Run {
/// The package whose activity is to be invoked
#[clap(short = 'p', long = "package")]
package: String,
/// The activity to be invoked itself, Usually it is MainActivity
#[clap(short = 'a', long = "activity")]
activity: String,
},
/// Reboot the device
Reboot {
#[clap(subcommand)]
reboot_type: RebootTypeCommand,
},
/// Install an APK on device
Install {
/// Path to APK file. Extension must be ".apk"
path: PathBuf,
},
}

View File

@@ -0,0 +1,56 @@
use std::num::ParseIntError;
use std::path::PathBuf;
use clap::Parser;
use crate::models::RebootTypeCommand;
fn parse_hex_id(id: &str) -> Result<u16, ParseIntError> {
u16::from_str_radix(id, 16)
}
#[derive(Parser, Debug)]
pub struct UsbCommand {
/// Hexadecimal vendor id of this USB device
#[clap(short = 'v', long = "vendor-id", value_parser=parse_hex_id, value_name="VID")]
pub vendor_id: Option<u16>,
/// Hexadecimal product id of this USB device
#[clap(short = 'p', long = "product-id", value_parser=parse_hex_id, value_name="PID")]
pub product_id: Option<u16>,
/// Path to a custom private key to use for authentication
#[clap(short = 'k', long = "private-key")]
pub path_to_private_key: Option<PathBuf>,
#[clap(subcommand)]
pub commands: UsbCommands,
}
#[derive(Parser, Debug)]
pub enum UsbCommands {
/// Spawn an interactive shell or run a list of commands on the device
Shell { commands: Vec<String> },
/// Pull a file from device
Pull { source: String, destination: String },
/// Push a file on device
Push { filename: String, path: String },
/// Stat a file on device
Stat { path: String },
/// Run an activity on device specified by the intent
Run {
/// The package whose activity is to be invoked
#[clap(short = 'p', long = "package")]
package: String,
/// The activity to be invoked itself, Usually it is MainActivity
#[clap(short = 'a', long = "activity")]
activity: String,
},
/// Reboot the device
Reboot {
#[clap(subcommand)]
reboot_type: RebootTypeCommand,
},
/// Install an APK on device
Install {
/// Path to APK file. Extension must be ".apk"
path: PathBuf,
},
}

View File

@@ -1,23 +1,47 @@
#![doc = include_str!("../README.md")]
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod adb_termios;
mod commands;
mod models;
use adb_client::{ADBEmulatorDevice, ADBServer, DeviceShort};
use adb_client::{
ADBDeviceExt, ADBEmulatorDevice, ADBServer, ADBTcpDevice, ADBUSBDevice, DeviceShort,
MDNSBackend, MDNSDiscoveryService,
};
use anyhow::{anyhow, Result};
use clap::Parser;
use commands::{EmuCommand, HostCommand, LocalCommand};
use commands::{EmuCommand, HostCommand, LocalCommand, MdnsCommand, TcpCommands, UsbCommands};
use models::{Command, Opts};
use std::fs::File;
use std::io::{self, Write};
use std::io::Write;
use std::path::Path;
fn main() -> Result<()> {
let opt = Opts::parse();
let opts = Opts::parse();
match opt.command {
// RUST_LOG variable has more priority then "--debug" flag
if std::env::var("RUST_LOG").is_err() {
let level = match opts.debug {
true => "trace",
false => "info",
};
std::env::set_var("RUST_LOG", level);
}
// Setting default log level as "info" if not set
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
env_logger::init();
match opts.command {
Command::Local(local) => {
let mut adb_server = ADBServer::new(opt.address);
let mut adb_server = ADBServer::new(opts.address);
let mut device = match opt.serial {
let mut device = match opts.serial {
Some(serial) => adb_server.get_device_by_name(&serial)?,
None => adb_server.get_device()?,
};
@@ -25,13 +49,13 @@ fn main() -> Result<()> {
match local {
LocalCommand::Pull { path, filename } => {
let mut output = File::create(Path::new(&filename))?;
device.recv(&path, &mut output)?;
println!("Downloaded {path} as {filename}");
device.pull(&path, &mut output)?;
log::info!("Downloaded {path} as {filename}");
}
LocalCommand::Push { filename, path } => {
let mut input = File::open(Path::new(&filename))?;
device.send(&mut input, &path)?;
println!("Uploaded {filename} to {path}");
device.push(&mut input, &path)?;
log::info!("Uploaded {filename} to {path}");
}
LocalCommand::List { path } => {
device.list(path)?;
@@ -40,79 +64,135 @@ fn main() -> Result<()> {
let stat_response = device.stat(path)?;
println!("{}", stat_response);
}
LocalCommand::Shell { command } => {
if command.is_empty() {
device.shell()?;
LocalCommand::Shell { commands } => {
if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
// Using a scope here would call drop() too early..
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let mut adb_termios = adb_termios::ADBTermios::new(std::io::stdin())?;
adb_termios.set_adb_termios()?;
device.shell(std::io::stdin(), std::io::stdout())?;
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
device.shell(std::io::stdin(), std::io::stdout())?;
}
} else {
let stdout = device.shell_command(command)?;
io::stdout().write_all(&stdout)?;
device.shell_command(commands, std::io::stdout())?;
}
}
LocalCommand::Run { package, activity } => {
let output = device.run_activity(&package, &activity)?;
std::io::stdout().write_all(&output)?;
}
LocalCommand::HostFeatures => {
println!("Available host features");
for feature in device.host_features()? {
println!("- {}", feature);
}
let features = device
.host_features()?
.iter()
.map(|v| v.to_string())
.reduce(|a, b| format!("{a},{b}"))
.ok_or(anyhow!("cannot list features"))?;
log::info!("Available host features: {features}");
}
LocalCommand::Reboot { sub_command } => {
println!("Reboots device");
device.reboot(sub_command.into())?
LocalCommand::Reboot { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type);
device.reboot(reboot_type.into())?
}
LocalCommand::Framebuffer { path } => {
device.framebuffer(&path)?;
println!("Framebuffer dropped: {path}");
log::info!("Framebuffer dropped: {path}");
}
LocalCommand::Logcat { path } => {
let writer: Box<dyn Write> = if let Some(path) = path {
let f = File::create(path)?;
Box::new(f)
} else {
Box::new(std::io::stdout())
};
device.get_logs(writer)?;
}
LocalCommand::Install { path } => {
log::info!("Starting installation of APK {}...", path.display());
device.install(path)?;
}
}
}
Command::Host(host) => {
let mut adb_server = ADBServer::new(opt.address);
let mut adb_server = ADBServer::new(opts.address);
match host {
HostCommand::Version => {
let version = adb_server.version()?;
println!("Android Debug Bridge version {}", version);
println!("Package version {}-rust", std::env!("CARGO_PKG_VERSION"));
log::info!("Android Debug Bridge version {}", version);
log::info!("Package version {}-rust", std::env!("CARGO_PKG_VERSION"));
}
HostCommand::Kill => {
adb_server.kill()?;
}
HostCommand::Devices { long } => {
if long {
println!("List of devices attached (extended)");
log::info!("List of devices attached (extended)");
for device in adb_server.devices_long()? {
println!("{}", device);
log::info!("{}", device);
}
} else {
println!("List of devices attached");
log::info!("List of devices attached");
for device in adb_server.devices()? {
println!("{}", device);
log::info!("{}", device);
}
}
}
HostCommand::TrackDevices => {
let callback = |device: DeviceShort| {
println!("{}", device);
log::info!("{}", device);
Ok(())
};
println!("Live list of devices attached");
log::info!("Live list of devices attached");
adb_server.track_devices(callback)?;
}
HostCommand::Pair { address, code } => {
adb_server.pair(address, code)?;
println!("paired device {address}");
log::info!("Paired device {address}");
}
HostCommand::Connect { address } => {
adb_server.connect_device(address)?;
println!("connected to {address}");
log::info!("Connected to {address}");
}
HostCommand::Disconnect { address } => {
adb_server.disconnect_device(address)?;
println!("disconnected {address}");
log::info!("Disconnected {address}");
}
HostCommand::Mdns { subcommand } => match subcommand {
MdnsCommand::Check => {
let check = adb_server.mdns_check()?;
let server_status = adb_server.server_status()?;
match server_status.mdns_backend {
MDNSBackend::Unknown => log::info!("unknown mdns backend..."),
MDNSBackend::Bonjour => match check {
true => log::info!("mdns daemon version [Bonjour]"),
false => log::info!("ERROR: mdns daemon unavailable"),
},
MDNSBackend::OpenScreen => {
log::info!("mdns daemon version [Openscreen discovery 0.0.0]")
}
}
}
MdnsCommand::Services => {
log::info!("List of discovered mdns services");
for service in adb_server.mdns_services()? {
log::info!("{}", service);
}
}
},
HostCommand::ServerStatus => {
log::info!("{}", adb_server.server_status()?);
}
}
}
Command::Emu(emu) => {
let mut emulator = match opt.serial {
let mut emulator = match opts.serial {
Some(serial) => ADBEmulatorDevice::new(serial, None)?,
None => return Err(anyhow!("Serial must be set to use emulators !")),
};
@@ -123,11 +203,150 @@ fn main() -> Result<()> {
content,
} => {
emulator.send_sms(&phone_number, &content)?;
println!("sms sent...");
log::info!("SMS sent to {phone_number}");
}
EmuCommand::Rotate => emulator.rotate()?,
}
}
Command::Usb(usb) => {
let mut device = match (usb.vendor_id, usb.product_id) {
(Some(vid), Some(pid)) => match usb.path_to_private_key {
Some(pk) => ADBUSBDevice::new_with_custom_private_key(vid, pid, pk)?,
None => ADBUSBDevice::new(vid, pid)?,
},
(None, None) => match usb.path_to_private_key {
Some(pk) => ADBUSBDevice::autodetect_with_custom_private_key(pk)?,
None => ADBUSBDevice::autodetect()?,
},
_ => {
anyhow::bail!("please either supply values for both the --vendor-id and --product-id flags or none.");
}
};
match usb.commands {
UsbCommands::Shell { commands } => {
if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
// Using a scope here would call drop() too early..
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let mut adb_termios = adb_termios::ADBTermios::new(std::io::stdin())?;
adb_termios.set_adb_termios()?;
device.shell(std::io::stdin(), std::io::stdout())?;
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
device.shell(std::io::stdin(), std::io::stdout())?;
}
} else {
device.shell_command(commands, std::io::stdout())?;
}
}
UsbCommands::Pull {
source,
destination,
} => {
let mut output = File::create(Path::new(&destination))?;
device.pull(&source, &mut output)?;
log::info!("Downloaded {source} as {destination}");
}
UsbCommands::Stat { path } => {
let stat_response = device.stat(&path)?;
println!("{}", stat_response);
}
UsbCommands::Reboot { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type);
device.reboot(reboot_type.into())?
}
UsbCommands::Push { filename, path } => {
let mut input = File::open(Path::new(&filename))?;
device.push(&mut input, &path)?;
log::info!("Uploaded {filename} to {path}");
}
UsbCommands::Run { package, activity } => {
let output = device.run_activity(&package, &activity)?;
std::io::stdout().write_all(&output)?;
}
UsbCommands::Install { path } => {
log::info!("Starting installation of APK {}...", path.display());
device.install(path)?;
}
}
}
Command::Tcp(tcp) => {
let mut device = ADBTcpDevice::new(tcp.address)?;
match tcp.commands {
TcpCommands::Shell { commands } => {
if commands.is_empty() {
// Need to duplicate some code here as ADBTermios [Drop] implementation resets terminal state.
// Using a scope here would call drop() too early..
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let mut adb_termios = adb_termios::ADBTermios::new(std::io::stdin())?;
adb_termios.set_adb_termios()?;
device.shell(std::io::stdin(), std::io::stdout())?;
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
device.shell(std::io::stdin(), std::io::stdout())?;
}
} else {
device.shell_command(commands, std::io::stdout())?;
}
}
TcpCommands::Pull {
source,
destination,
} => {
let mut output = File::create(Path::new(&destination))?;
device.pull(&source, &mut output)?;
log::info!("Downloaded {source} as {destination}");
}
TcpCommands::Stat { path } => {
let stat_response = device.stat(&path)?;
println!("{}", stat_response);
}
TcpCommands::Reboot { reboot_type } => {
log::info!("Reboots device in mode {:?}", reboot_type);
device.reboot(reboot_type.into())?
}
TcpCommands::Push { filename, path } => {
let mut input = File::open(Path::new(&filename))?;
device.push(&mut input, &path)?;
log::info!("Uploaded {filename} to {path}");
}
TcpCommands::Run { package, activity } => {
let output = device.run_activity(&package, &activity)?;
std::io::stdout().write_all(&output)?;
}
TcpCommands::Install { path } => {
log::info!("Starting installation of APK {}...", path.display());
device.install(path)?;
}
}
}
Command::MdnsDiscovery => {
let mut service = MDNSDiscoveryService::new()?;
let (tx, rx) = std::sync::mpsc::channel();
service.start(tx)?;
log::info!("Starting mdns discovery...");
while let Ok(device) = rx.recv() {
log::info!(
"Found device {} with addresses {:?}",
device.fullname,
device.addresses
)
}
service.shutdown()?;
}
}
Ok(())

View File

@@ -2,11 +2,13 @@ use std::net::SocketAddrV4;
use clap::Parser;
use crate::commands::{EmuCommand, HostCommand, LocalCommand};
use crate::commands::{EmuCommand, HostCommand, LocalCommand, TcpCommand, UsbCommand};
#[derive(Parser, Debug)]
#[clap(about, version, author)]
pub struct Opts {
#[clap(long = "debug")]
pub debug: bool,
#[clap(short = 'a', long = "address", default_value = "127.0.0.1:5037")]
pub address: SocketAddrV4,
/// Serial id of a specific device. Every request will be sent to this device.
@@ -22,6 +24,13 @@ pub enum Command {
Local(LocalCommand),
#[clap(flatten)]
Host(HostCommand),
#[clap(flatten)]
/// Emulator specific commands
#[clap(subcommand)]
Emu(EmuCommand),
/// Device commands via USB, no server needed
Usb(UsbCommand),
/// Device commands via TCP, no server needed
Tcp(TcpCommand),
/// Discover devices over MDNS without using adb-server
MdnsDiscovery,
}

View File

@@ -1,21 +1,44 @@
[package]
authors.workspace = true
description = "Rust ADB (Android Debug Bridge) client library"
edition.workspace = true
keywords = ["adb", "android"]
keywords.workspace = true
license.workspace = true
name = "adb_client"
readme = "../README.md"
readme = "README.md"
repository.workspace = true
version.workspace = true
[dependencies]
base64 = { version = "0.22.1" }
bincode = { version = "1.3.3" }
byteorder = { version = "1.5.0" }
chrono = { version = "0.4.38" }
homedir = "0.3.3"
image = { version = "0.25.2" }
homedir = { version = "0.3.4" }
image = { version = "0.25.5" }
lazy_static = { version = "1.5.0" }
log = { version = "0.4.22" }
mio = { version = "1.0.1", features = ["os-ext", "os-poll"] }
regex = { version = "1.10.5", features = ["perf", "std", "unicode"] }
termios = { version = "0.3.3" }
thiserror = { version = "1.0.63" }
mdns-sd = { version = "0.12.0" }
num-bigint = { version = "0.8.4", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" }
rand = { version = "0.8.5" }
rcgen = { version = "0.13.1" }
regex = { version = "1.11.0", features = ["perf", "std", "unicode"] }
rsa = { version = "0.9.7" }
rusb = { version = "0.9.4", features = ["vendored"] }
rustls = { version = "0.23.18" }
rustls-pki-types = "1.10.0"
serde = { version = "1.0.210", features = ["derive"] }
serde_repr = { version = "0.1.19" }
sha1 = { version = "0.10.6", features = ["oid"] }
thiserror = { version = "2.0.1" }
[dev-dependencies]
anyhow = { version = "1.0.93" }
criterion = { version = "0.5.1" } # Used for benchmarks
[[bench]]
harness = false
name = "benchmark_adb_push"
path = "../benches/benchmark_adb_push.rs"

97
adb_client/README.md Normal file
View File

@@ -0,0 +1,97 @@
# adb_client
[![MIT licensed](https://img.shields.io/crates/l/adb_client.svg)](./LICENSE-MIT)
[![Documentation](https://docs.rs/adb_client/badge.svg)](https://docs.rs/adb_client)
![Crates.io Total Downloads](https://img.shields.io/crates/d/adb_client)
Rust library implementing ADB protocol.
## Installation
Add `adb_client` crate as a dependency by simply adding it to your `Cargo.toml`:
```toml
[dependencies]
adb_client = "*"
```
## Examples
### Get available ADB devices
```rust no_run
use adb_client::ADBServer;
use std::net::{SocketAddrV4, Ipv4Addr};
// A custom server address can be provided
let server_ip = Ipv4Addr::new(127, 0, 0, 1);
let server_port = 5037;
let mut server = ADBServer::new(SocketAddrV4::new(server_ip, server_port));
server.devices();
```
### Using ADB server as bridge
#### Launch a command on device
```rust no_run
use adb_client::{ADBServer, ADBDeviceExt};
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
device.shell_command(["df", "-h"],std::io::stdout());
```
#### Push a file to the device
```rust no_run
use adb_client::ADBServer;
use std::net::Ipv4Addr;
use std::fs::File;
use std::path::Path;
let mut server = ADBServer::default();
let mut device = server.get_device().expect("cannot get device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, "/data/local/tmp");
```
### Interact directly with end devices
#### (USB) Launch a command on device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
device.shell_command(["df", "-h"],std::io::stdout());
```
#### (USB) Push a file to the device
```rust no_run
use adb_client::{ADBUSBDevice, ADBDeviceExt};
use std::fs::File;
use std::path::Path;
let vendor_id = 0x04e8;
let product_id = 0x6860;
let mut device = ADBUSBDevice::new(vendor_id, product_id).expect("cannot find device");
let mut input = File::open(Path::new("/tmp/f")).expect("Cannot open file");
device.push(&mut input, "/data/local/tmp");
```
### (TCP) Get a shell from device
```rust no_run
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use adb_client::{ADBTcpDevice, ADBDeviceExt};
let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 10));
let device_port = 43210;
let mut device = ADBTcpDevice::new(SocketAddr::new(device_ip, device_port)).expect("cannot find device");
device.shell(std::io::stdin(), std::io::stdout());
```

View File

@@ -0,0 +1,46 @@
use std::io::{Read, Write};
use std::path::Path;
use crate::models::AdbStatResponse;
use crate::{RebootType, Result};
/// Trait representing all features available on both [`crate::ADBServerDevice`] and [`crate::ADBUSBDevice`]
pub trait ADBDeviceExt {
/// Runs command in a shell on the device, and write its output and error streams into output.
fn shell_command<S: ToString, W: Write>(
&mut self,
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()>;
/// Starts an interactive shell session on the device.
/// Input data is read from reader and write to writer.
/// W has a 'static bound as it is internally used in a thread.
fn shell<R: Read, W: Write + Send + 'static>(&mut self, reader: R, writer: W) -> Result<()>;
/// Display the stat information for a remote file
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse>;
/// Pull the remote file pointed to by `source` and write its contents into `output`
fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()>;
/// Push `stream` to `path` on the device.
fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()>;
/// Reboot the device using given reboot type
fn reboot(&mut self, reboot_type: RebootType) -> Result<()>;
/// Run `activity` from `package` on device. Return the command output.
fn run_activity(&mut self, package: &str, activity: &str) -> Result<Vec<u8>> {
let mut output = Vec::new();
self.shell_command(
["am", "start", &format!("{package}/{package}.{activity}")],
&mut output,
)?;
Ok(output)
}
/// Install an APK pointed to by `apk_path` on device.
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()>;
}

View File

@@ -0,0 +1 @@
pub const BUFFER_SIZE: usize = 65536;

View File

@@ -0,0 +1,236 @@
use byteorder::{LittleEndian, ReadBytesExt};
use rand::Rng;
use std::io::{Cursor, Read, Seek};
use crate::{constants::BUFFER_SIZE, ADBMessageTransport, AdbStatResponse, Result, RustADBError};
use super::{models::MessageSubcommand, ADBTransportMessage, MessageCommand};
/// Generic structure representing an ADB device reachable over an [`ADBMessageTransport`].
/// Structure is totally agnostic over which transport is truly used.
#[derive(Debug)]
pub struct ADBMessageDevice<T: ADBMessageTransport> {
transport: T,
}
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// Instantiate a new [`ADBMessageTransport`]
pub fn new(transport: T) -> Self {
Self { transport }
}
pub(crate) fn get_transport(&mut self) -> &T {
&self.transport
}
pub(crate) fn get_transport_mut(&mut self) -> &mut T {
&mut self.transport
}
/// Receive a message and acknowledge it by replying with an `OKAY` command
pub(crate) fn recv_and_reply_okay(
&mut self,
local_id: u32,
remote_id: u32,
) -> Result<ADBTransportMessage> {
let message = self.transport.read_message()?;
self.transport.write_message(ADBTransportMessage::new(
MessageCommand::Okay,
local_id,
remote_id,
"".into(),
))?;
Ok(message)
}
/// Expect a message with an `OKAY` command after sending a message.
pub(crate) fn send_and_expect_okay(
&mut self,
message: ADBTransportMessage,
) -> Result<ADBTransportMessage> {
self.transport.write_message(message)?;
let message = self.transport.read_message()?;
let received_command = message.header().command();
if received_command != MessageCommand::Okay {
return Err(RustADBError::ADBRequestFailed(format!(
"expected command OKAY after message, got {}",
received_command
)));
}
Ok(message)
}
pub(crate) fn recv_file<W: std::io::Write>(
&mut self,
local_id: u32,
remote_id: u32,
mut output: W,
) -> std::result::Result<(), RustADBError> {
let mut len: Option<u64> = None;
loop {
let payload = self
.recv_and_reply_okay(local_id, remote_id)?
.into_payload();
let mut rdr = Cursor::new(&payload);
while rdr.position() != payload.len() as u64 {
match len.take() {
Some(0) | None => {
rdr.seek_relative(4)?;
len.replace(rdr.read_u32::<LittleEndian>()? as u64);
}
Some(length) => {
let remaining_bytes = payload.len() as u64 - rdr.position();
if length < remaining_bytes {
std::io::copy(&mut rdr.by_ref().take(length), &mut output)?;
} else {
std::io::copy(&mut rdr.take(remaining_bytes), &mut output)?;
len.replace(length - remaining_bytes);
// this payload is now exhausted
break;
}
}
}
}
if Cursor::new(&payload[(payload.len() - 8)..(payload.len() - 4)])
.read_u32::<LittleEndian>()?
== MessageSubcommand::Done as u32
{
break;
}
}
Ok(())
}
pub(crate) fn push_file<R: std::io::Read>(
&mut self,
local_id: u32,
remote_id: u32,
mut reader: R,
) -> std::result::Result<(), RustADBError> {
let mut buffer = [0; BUFFER_SIZE];
let amount_read = reader.read(&mut buffer)?;
let subcommand_data = MessageSubcommand::Data.with_arg(amount_read as u32);
let mut serialized_message =
bincode::serialize(&subcommand_data).map_err(|_e| RustADBError::ConversionError)?;
serialized_message.append(&mut buffer[..amount_read].to_vec());
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
serialized_message,
);
self.send_and_expect_okay(message)?;
loop {
let mut buffer = [0; BUFFER_SIZE];
match reader.read(&mut buffer) {
Ok(0) => {
// Currently file mtime is not forwarded
let subcommand_data = MessageSubcommand::Done.with_arg(0);
let serialized_message = bincode::serialize(&subcommand_data)
.map_err(|_e| RustADBError::ConversionError)?;
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
serialized_message,
);
self.send_and_expect_okay(message)?;
// Command should end with a Write => Okay
let received = self.transport.read_message()?;
match received.header().command() {
MessageCommand::Write => return Ok(()),
c => {
return Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}",
c
)))
}
}
}
Ok(size) => {
let subcommand_data = MessageSubcommand::Data.with_arg(size as u32);
let mut serialized_message = bincode::serialize(&subcommand_data)
.map_err(|_e| RustADBError::ConversionError)?;
serialized_message.append(&mut buffer[..size].to_vec());
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
serialized_message,
);
self.send_and_expect_okay(message)?;
}
Err(e) => {
return Err(RustADBError::IOError(e));
}
}
}
}
pub(crate) fn begin_synchronization(&mut self) -> Result<(u32, u32)> {
let sync_directive = "sync:\0";
let mut rng = rand::thread_rng();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rng.gen(), /* Our 'local-id' */
0,
sync_directive.into(),
);
let message = self.send_and_expect_okay(message)?;
let local_id = message.header().arg1();
let remote_id = message.header().arg0();
Ok((local_id, remote_id))
}
pub(crate) fn stat_with_explicit_ids(
&mut self,
remote_path: &str,
local_id: u32,
remote_id: u32,
) -> Result<AdbStatResponse> {
let stat_buffer = MessageSubcommand::Stat.with_arg(remote_path.len() as u32);
let message = ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
bincode::serialize(&stat_buffer).map_err(|_e| RustADBError::ConversionError)?,
);
self.send_and_expect_okay(message)?;
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
remote_path.into(),
))?;
let response = self.transport.read_message()?;
// Skip first 4 bytes as this is the literal "STAT".
// Interesting part starts right after
bincode::deserialize(&response.into_payload()[4..])
.map_err(|_e| RustADBError::ConversionError)
}
pub(crate) fn end_transaction(&mut self, local_id: u32, remote_id: u32) -> Result<()> {
let quit_buffer = MessageSubcommand::Quit.with_arg(0u32);
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
bincode::serialize(&quit_buffer).map_err(|_e| RustADBError::ConversionError)?,
))?;
let _discard_close = self.transport.read_message()?;
Ok(())
}
}

View File

@@ -0,0 +1,38 @@
use crate::{models::AdbStatResponse, ADBDeviceExt, ADBMessageTransport, RebootType, Result};
use std::io::{Read, Write};
use super::ADBMessageDevice;
impl<T: ADBMessageTransport> ADBDeviceExt for ADBMessageDevice<T> {
fn shell_command<S: ToString, W: Write>(
&mut self,
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()> {
self.shell_command(command, output)
}
fn shell<R: Read, W: Write + Send + 'static>(&mut self, reader: R, writer: W) -> Result<()> {
self.shell(reader, writer)
}
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
self.stat(remote_path)
}
fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> {
self.pull(source, output)
}
fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
self.push(stream, path)
}
fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
self.reboot(reboot_type)
}
fn install<P: AsRef<std::path::Path>>(&mut self, apk_path: P) -> Result<()> {
self.install(apk_path)
}
}

View File

@@ -0,0 +1,112 @@
use std::net::SocketAddr;
use std::path::Path;
use super::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand;
use super::ADBTransportMessage;
use crate::{ADBDeviceExt, ADBMessageTransport, ADBTransport, Result, RustADBError, TcpTransport};
/// Represent a device reached and available over USB.
#[derive(Debug)]
pub struct ADBTcpDevice {
inner: ADBMessageDevice<TcpTransport>,
}
impl ADBTcpDevice {
/// Instantiate a new [`ADBTcpDevice`]
pub fn new(address: SocketAddr) -> Result<Self> {
let mut device = Self {
inner: ADBMessageDevice::new(TcpTransport::new(address)?),
};
device.connect()?;
Ok(device)
}
/// Send initial connect
pub fn connect(&mut self) -> Result<()> {
self.get_transport_mut().connect()?;
let message = ADBTransportMessage::new(
MessageCommand::Cnxn,
0x01000000,
1048576,
format!("host::{}\0", env!("CARGO_PKG_NAME"))
.as_bytes()
.to_vec(),
);
self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?;
// At this point, we should have received a STLS message
if message.header().command() != MessageCommand::Stls {
return Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}",
message.header().command()
)));
};
let message = ADBTransportMessage::new(MessageCommand::Stls, 1, 0, vec![]);
self.get_transport_mut().write_message(message)?;
// Upgrade TCP connection to TLS
self.get_transport_mut().upgrade_connection()?;
log::debug!("Connection successfully upgraded from TCP to TLS");
Ok(())
}
fn get_transport_mut(&mut self) -> &mut TcpTransport {
self.inner.get_transport_mut()
}
}
impl ADBDeviceExt for ADBTcpDevice {
fn shell_command<S: ToString, W: std::io::Write>(
&mut self,
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()> {
self.inner.shell_command(command, output)
}
fn shell<R: std::io::Read, W: std::io::Write + Send + 'static>(
&mut self,
reader: R,
writer: W,
) -> Result<()> {
self.inner.shell(reader, writer)
}
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path)
}
fn pull<A: AsRef<str>, W: std::io::Write>(&mut self, source: A, output: W) -> Result<()> {
self.inner.pull(source, output)
}
fn push<R: std::io::Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
self.inner.push(stream, path)
}
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type)
}
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()> {
self.inner.install(apk_path)
}
}
impl Drop for ADBTcpDevice {
fn drop(&mut self) {
// Best effort here
let _ = self.get_transport_mut().disconnect();
}
}

View File

@@ -0,0 +1,110 @@
use serde::{Deserialize, Serialize};
use crate::RustADBError;
use super::models::MessageCommand;
pub const AUTH_TOKEN: u32 = 1;
pub const AUTH_SIGNATURE: u32 = 2;
pub const AUTH_RSAPUBLICKEY: u32 = 3;
#[derive(Debug)]
pub struct ADBTransportMessage {
header: ADBTransportMessageHeader,
payload: Vec<u8>,
}
#[derive(Debug, Serialize, Deserialize)]
#[repr(C)]
pub struct ADBTransportMessageHeader {
command: MessageCommand, /* command identifier constant */
arg0: u32, /* first argument */
arg1: u32, /* second argument */
data_length: u32, /* length of payload (0 is allowed) */
data_crc32: u32, /* crc32 of data payload */
magic: u32, /* command ^ 0xffffffff */
}
impl ADBTransportMessageHeader {
pub fn new(command: MessageCommand, arg0: u32, arg1: u32, data: &[u8]) -> Self {
Self {
command,
arg0,
arg1,
data_length: data.len() as u32,
data_crc32: Self::compute_crc32(data),
magic: Self::compute_magic(command),
}
}
pub fn command(&self) -> MessageCommand {
self.command
}
pub fn arg0(&self) -> u32 {
self.arg0
}
pub fn arg1(&self) -> u32 {
self.arg1
}
pub fn data_length(&self) -> u32 {
self.data_length
}
pub fn data_crc32(&self) -> u32 {
self.data_crc32
}
pub(crate) fn compute_crc32(data: &[u8]) -> u32 {
data.iter().map(|&x| x as u32).sum()
}
fn compute_magic(command: MessageCommand) -> u32 {
let command_u32 = command as u32;
command_u32 ^ 0xFFFFFFFF
}
pub fn as_bytes(&self) -> Result<Vec<u8>, RustADBError> {
bincode::serialize(&self).map_err(|_e| RustADBError::ConversionError)
}
}
impl ADBTransportMessage {
pub fn new(command: MessageCommand, arg0: u32, arg1: u32, data: Vec<u8>) -> Self {
Self {
header: ADBTransportMessageHeader::new(command, arg0, arg1, &data),
payload: data,
}
}
pub fn from_header_and_payload(header: ADBTransportMessageHeader, payload: Vec<u8>) -> Self {
Self { header, payload }
}
pub fn check_message_integrity(&self) -> bool {
ADBTransportMessageHeader::compute_magic(self.header.command) == self.header.magic
&& ADBTransportMessageHeader::compute_crc32(&self.payload) == self.header.data_crc32
}
pub fn header(&self) -> &ADBTransportMessageHeader {
&self.header
}
pub fn payload(&self) -> &Vec<u8> {
&self.payload
}
pub fn into_payload(self) -> Vec<u8> {
self.payload
}
}
impl TryFrom<[u8; 24]> for ADBTransportMessageHeader {
type Error = RustADBError;
fn try_from(value: [u8; 24]) -> Result<Self, Self::Error> {
bincode::deserialize(&value).map_err(|_e| RustADBError::ConversionError)
}
}

View File

@@ -0,0 +1,294 @@
use rusb::Device;
use rusb::DeviceDescriptor;
use rusb::UsbContext;
use std::fs::read_to_string;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use super::adb_message_device::ADBMessageDevice;
use super::models::MessageCommand;
use super::{ADBRsaKey, ADBTransportMessage};
use crate::device::adb_transport_message::{AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
use crate::ADBDeviceExt;
use crate::ADBMessageTransport;
use crate::ADBTransport;
use crate::{Result, RustADBError, USBTransport};
pub fn read_adb_private_key<P: AsRef<Path>>(private_key_path: P) -> Result<Option<ADBRsaKey>> {
Ok(read_to_string(private_key_path.as_ref()).map(|pk| {
match ADBRsaKey::new_from_pkcs8(&pk) {
Ok(pk) => Some(pk),
Err(e) => {
log::error!("Error while create RSA private key: {e}");
None
}
}
})?)
}
/// Search for adb devices with known interface class and subclass values
fn search_adb_devices() -> Result<Option<(u16, u16)>> {
let mut found_devices = vec![];
for device in rusb::devices()?.iter() {
let Ok(des) = device.device_descriptor() else {
continue;
};
if is_adb_device(&device, &des) {
log::debug!(
"Autodetect device {:04x}:{:04x}",
des.vendor_id(),
des.product_id()
);
found_devices.push((des.vendor_id(), des.product_id()));
}
}
match (found_devices.first(), found_devices.get(1)) {
(None, _) => Ok(None),
(Some(identifiers), None) => Ok(Some(*identifiers)),
(Some((vid1, pid1)), Some((vid2, pid2))) => Err(RustADBError::DeviceNotFound(format!(
"Found two Android devices {:04x}:{:04x} and {:04x}:{:04x}",
vid1, pid1, vid2, pid2
))),
}
}
fn is_adb_device<T: UsbContext>(device: &Device<T>, des: &DeviceDescriptor) -> bool {
const ADB_CLASS: u8 = 0xff;
const ADB_SUBCLASS: u8 = 0x42;
const ADB_PROTOCOL: u8 = 0x1;
// Some devices require choosing the file transfer mode
// for usb debugging to take effect.
const BULK_CLASS: u8 = 0xdc;
const BULK_ADB_SUBCLASS: u8 = 2;
for n in 0..des.num_configurations() {
let Ok(config_des) = device.config_descriptor(n) else {
continue;
};
for interface in config_des.interfaces() {
for interface_des in interface.descriptors() {
let proto = interface_des.protocol_code();
let class = interface_des.class_code();
let subcl = interface_des.sub_class_code();
if proto == ADB_PROTOCOL
&& ((class == ADB_CLASS && subcl == ADB_SUBCLASS)
|| (class == BULK_CLASS && subcl == BULK_ADB_SUBCLASS))
{
return true;
}
}
}
}
false
}
pub fn get_default_adb_key_path() -> Result<PathBuf> {
homedir::my_home()
.ok()
.flatten()
.map(|home| home.join(".android").join("adbkey"))
.ok_or(RustADBError::NoHomeDirectory)
}
/// Represent a device reached and available over USB.
#[derive(Debug)]
pub struct ADBUSBDevice {
private_key: ADBRsaKey,
inner: ADBMessageDevice<USBTransport>,
}
impl ADBUSBDevice {
/// Instantiate a new [`ADBUSBDevice`]
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
Self::new_with_custom_private_key(vendor_id, product_id, get_default_adb_key_path()?)
}
/// Instantiate a new [`ADBUSBDevice`] using a custom private key path
pub fn new_with_custom_private_key(
vendor_id: u16,
product_id: u16,
private_key_path: PathBuf,
) -> Result<Self> {
Self::new_from_transport_inner(USBTransport::new(vendor_id, product_id)?, private_key_path)
}
/// Instantiate a new [`ADBUSBDevice`] from a [`USBTransport`] and an optional private key path.
pub fn new_from_transport(
transport: USBTransport,
private_key_path: Option<PathBuf>,
) -> Result<Self> {
let private_key_path = match private_key_path {
Some(private_key_path) => private_key_path,
None => get_default_adb_key_path()?,
};
Self::new_from_transport_inner(transport, private_key_path)
}
fn new_from_transport_inner(
transport: USBTransport,
private_key_path: PathBuf,
) -> Result<Self> {
let private_key = match read_adb_private_key(private_key_path)? {
Some(pk) => pk,
None => ADBRsaKey::new_random()?,
};
let mut s = Self {
private_key,
inner: ADBMessageDevice::new(transport),
};
s.connect()?;
Ok(s)
}
/// autodetect connected ADB devices and establish a connection with the first device found
pub fn autodetect() -> Result<Self> {
Self::autodetect_with_custom_private_key(get_default_adb_key_path()?)
}
/// autodetect connected ADB devices and establish a connection with the first device found using a custom private key path
pub fn autodetect_with_custom_private_key(private_key_path: PathBuf) -> Result<Self> {
match search_adb_devices()? {
Some((vendor_id, product_id)) => {
ADBUSBDevice::new_with_custom_private_key(vendor_id, product_id, private_key_path)
}
_ => Err(RustADBError::DeviceNotFound(
"cannot find USB devices matching the signature of an ADB device".into(),
)),
}
}
/// Send initial connect
pub fn connect(&mut self) -> Result<()> {
self.get_transport_mut().connect()?;
let message = ADBTransportMessage::new(
MessageCommand::Cnxn,
0x01000000,
1048576,
format!("host::{}\0", env!("CARGO_PKG_NAME"))
.as_bytes()
.to_vec(),
);
self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?;
// At this point, we should have received either:
// - an AUTH message with arg0 == 1
// - a CNXN message
let auth_message = match message.header().command() {
MessageCommand::Auth if message.header().arg0() == AUTH_TOKEN => message,
MessageCommand::Auth if message.header().arg0() != AUTH_TOKEN => {
return Err(RustADBError::ADBRequestFailed(
"Received AUTH message with type != 1".into(),
))
}
c => {
return Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}",
c
)))
}
};
let sign = self.private_key.sign(auth_message.into_payload())?;
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_SIGNATURE, 0, sign);
self.get_transport_mut().write_message(message)?;
let received_response = self.get_transport_mut().read_message()?;
if received_response.header().command() == MessageCommand::Cnxn {
log::info!(
"Authentication OK, device info {}",
String::from_utf8(received_response.into_payload())?
);
return Ok(());
}
let mut pubkey = self.private_key.android_pubkey_encode()?.into_bytes();
pubkey.push(b'\0');
let message = ADBTransportMessage::new(MessageCommand::Auth, AUTH_RSAPUBLICKEY, 0, pubkey);
self.get_transport_mut().write_message(message)?;
let response = self
.get_transport_mut()
.read_message_with_timeout(Duration::from_secs(10))?;
match response.header().command() {
MessageCommand::Cnxn => log::info!(
"Authentication OK, device info {}",
String::from_utf8(response.into_payload())?
),
_ => {
return Err(RustADBError::ADBRequestFailed(format!(
"wrong response {}",
response.header().command()
)))
}
}
Ok(())
}
fn get_transport_mut(&mut self) -> &mut USBTransport {
self.inner.get_transport_mut()
}
}
impl ADBDeviceExt for ADBUSBDevice {
fn shell_command<S: ToString, W: std::io::Write>(
&mut self,
command: impl IntoIterator<Item = S>,
output: W,
) -> Result<()> {
self.inner.shell_command(command, output)
}
fn shell<R: std::io::Read, W: std::io::Write + Send + 'static>(
&mut self,
reader: R,
writer: W,
) -> Result<()> {
self.inner.shell(reader, writer)
}
fn stat(&mut self, remote_path: &str) -> Result<crate::AdbStatResponse> {
self.inner.stat(remote_path)
}
fn pull<A: AsRef<str>, W: std::io::Write>(&mut self, source: A, output: W) -> Result<()> {
self.inner.pull(source, output)
}
fn push<R: std::io::Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
self.inner.push(stream, path)
}
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.inner.reboot(reboot_type)
}
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()> {
self.inner.install(apk_path)
}
}
impl Drop for ADBUSBDevice {
fn drop(&mut self) {
// Best effort here
let _ = self.get_transport_mut().disconnect();
}
}

View File

@@ -0,0 +1,59 @@
use std::fs::File;
use rand::Rng;
use crate::{
device::{
adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand, MessageWriter,
},
utils::check_extension_is_apk,
ADBMessageTransport, Result,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn install<P: AsRef<std::path::Path>>(&mut self, apk_path: P) -> Result<()> {
let mut apk_file = File::open(&apk_path)?;
check_extension_is_apk(&apk_path)?;
let file_size = apk_file.metadata()?.len();
let mut rng = rand::thread_rng();
let local_id = rng.gen();
let message = ADBTransportMessage::new(
MessageCommand::Open,
local_id,
0,
format!("exec:cmd package 'install' -S {}\0", file_size)
.as_bytes()
.to_vec(),
);
self.get_transport_mut().write_message(message)?;
let response = self.get_transport_mut().read_message()?;
let remote_id = response.header().arg0();
let transport = self.get_transport().clone();
let mut writer = MessageWriter::new(transport, local_id, remote_id);
std::io::copy(&mut apk_file, &mut writer)?;
let final_status = self.get_transport_mut().read_message()?;
match final_status.into_payload().as_slice() {
b"Success\n" => {
log::info!(
"APK file {} successfully installed",
apk_path.as_ref().display()
);
Ok(())
}
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(
d.to_vec(),
)?)),
}
}
}

View File

@@ -0,0 +1,6 @@
mod install;
mod pull;
mod push;
mod reboot;
mod shell;
mod stat;

View File

@@ -0,0 +1,49 @@
use std::io::Write;
use crate::{
device::{
adb_message_device::ADBMessageDevice, models::MessageSubcommand, ADBTransportMessage,
MessageCommand,
},
ADBMessageTransport, Result, RustADBError,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, output: W) -> Result<()> {
let (local_id, remote_id) = self.begin_synchronization()?;
let source = source.as_ref();
let adb_stat_response = self.stat_with_explicit_ids(source, local_id, remote_id)?;
if adb_stat_response.file_perm == 0 {
return Err(RustADBError::UnknownResponseType(
"mode is 0: source file does not exist".to_string(),
));
}
self.get_transport_mut().write_message_with_timeout(
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, "".into()),
std::time::Duration::from_secs(4),
)?;
let recv_buffer = MessageSubcommand::Recv.with_arg(source.len() as u32);
let recv_buffer =
bincode::serialize(&recv_buffer).map_err(|_e| RustADBError::ConversionError)?;
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
recv_buffer,
))?;
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
source.into(),
))?;
self.recv_file(local_id, remote_id, output)?;
self.end_transaction(local_id, remote_id)?;
Ok(())
}
}

View File

@@ -0,0 +1,35 @@
use std::io::Read;
use crate::{
device::{
adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand,
MessageSubcommand,
},
ADBMessageTransport, Result, RustADBError,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
let (local_id, remote_id) = self.begin_synchronization()?;
let path_header = format!("{},0777", path.as_ref());
let send_buffer = MessageSubcommand::Send.with_arg(path_header.len() as u32);
let mut send_buffer =
bincode::serialize(&send_buffer).map_err(|_e| RustADBError::ConversionError)?;
send_buffer.append(&mut path_header.as_bytes().to_vec());
self.send_and_expect_okay(ADBTransportMessage::new(
MessageCommand::Write,
local_id,
remote_id,
send_buffer,
))?;
self.push_file(local_id, remote_id, stream)?;
self.end_transaction(local_id, remote_id)?;
Ok(())
}
}

View File

@@ -0,0 +1,28 @@
use rand::Rng;
use crate::{
device::{adb_message_device::ADBMessageDevice, ADBTransportMessage, MessageCommand},
ADBMessageTransport, RebootType, Result, RustADBError,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn reboot(&mut self, reboot_type: RebootType) -> Result<()> {
let mut rng = rand::thread_rng();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rng.gen(), // Our 'local-id'
0,
format!("reboot:{}\0", reboot_type).as_bytes().to_vec(),
);
self.get_transport_mut().write_message(message)?;
let message = self.get_transport_mut().read_message()?;
if message.header().command() != MessageCommand::Okay {
return Err(RustADBError::ADBShellNotSupported);
}
Ok(())
}
}

View File

@@ -0,0 +1,112 @@
use rand::Rng;
use std::io::{Read, Write};
use crate::device::ShellMessageWriter;
use crate::Result;
use crate::{
device::{ADBMessageDevice, ADBTransportMessage, MessageCommand},
ADBMessageTransport, RustADBError,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// Runs 'command' in a shell on the device, and write its output and error streams into [`output`].
pub(crate) fn shell_command<S: ToString, W: Write>(
&mut self,
command: impl IntoIterator<Item = S>,
mut output: W,
) -> Result<()> {
let message = ADBTransportMessage::new(
MessageCommand::Open,
1,
0,
format!(
"shell:{}\0",
command
.into_iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" "),
)
.as_bytes()
.to_vec(),
);
self.get_transport_mut().write_message(message)?;
let response = self.get_transport_mut().read_message()?;
if response.header().command() != MessageCommand::Okay {
return Err(RustADBError::ADBRequestFailed(format!(
"wrong command {}",
response.header().command()
)));
}
loop {
let response = self.get_transport_mut().read_message()?;
if response.header().command() != MessageCommand::Write {
break;
}
output.write_all(&response.into_payload())?;
}
Ok(())
}
/// Starts an interactive shell session on the device.
/// Input data is read from [reader] and write to [writer].
/// [W] has a 'static bound as it is internally used in a thread.
pub(crate) fn shell<R: Read, W: Write + Send + 'static>(
&mut self,
mut reader: R,
mut writer: W,
) -> Result<()> {
let sync_directive = "shell:\0";
let mut rng = rand::thread_rng();
let message = ADBTransportMessage::new(
MessageCommand::Open,
rng.gen(), /* Our 'local-id' */
0,
sync_directive.into(),
);
let message = self.send_and_expect_okay(message)?;
let local_id = message.header().arg1();
let remote_id = message.header().arg0();
let mut transport = self.get_transport().clone();
// Reading thread, reads response from adbd
std::thread::spawn(move || -> Result<()> {
loop {
let message = transport.read_message()?;
// Acknowledge for more data
let response =
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, vec![]);
transport.write_message(response)?;
match message.header().command() {
MessageCommand::Write => {}
MessageCommand::Okay => continue,
_ => return Err(RustADBError::ADBShellNotSupported),
}
writer.write_all(&message.into_payload())?;
writer.flush()?;
}
});
let transport = self.get_transport().clone();
let mut shell_writer = ShellMessageWriter::new(transport, local_id, remote_id);
// Read from given reader (that could be stdin e.g), and write content to device adbd
if let Err(e) = std::io::copy(&mut reader, &mut shell_writer) {
match e.kind() {
std::io::ErrorKind::BrokenPipe => return Ok(()),
_ => return Err(RustADBError::IOError(e)),
}
}
Ok(())
}
}

View File

@@ -0,0 +1,12 @@
use crate::{
device::adb_message_device::ADBMessageDevice, ADBMessageTransport, AdbStatResponse, Result,
};
impl<T: ADBMessageTransport> ADBMessageDevice<T> {
pub(crate) fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
let (local_id, remote_id) = self.begin_synchronization()?;
let adb_stat_response = self.stat_with_explicit_ids(remote_path, local_id, remote_id)?;
self.end_transaction(local_id, remote_id)?;
Ok(adb_stat_response)
}
}

View File

@@ -0,0 +1,53 @@
use std::io::{ErrorKind, Write};
use crate::ADBMessageTransport;
use super::{ADBTransportMessage, MessageCommand};
/// [`Write`] trait implementation to hide underlying ADB protocol write logic.
///
/// Read received responses to check that message has been correctly received.
pub struct MessageWriter<T: ADBMessageTransport> {
transport: T,
local_id: u32,
remote_id: u32,
}
impl<T: ADBMessageTransport> MessageWriter<T> {
pub fn new(transport: T, local_id: u32, remote_id: u32) -> Self {
Self {
transport,
local_id,
remote_id,
}
}
}
impl<T: ADBMessageTransport> Write for MessageWriter<T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let message = ADBTransportMessage::new(
MessageCommand::Write,
self.local_id,
self.remote_id,
buf.to_vec(),
);
self.transport
.write_message(message)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
match self.transport.read_message() {
Ok(response) => match response.header().command() {
MessageCommand::Okay => Ok(buf.len()),
c => Err(std::io::Error::new(
ErrorKind::Other,
format!("wrong response received: {c}"),
)),
},
Err(e) => Err(std::io::Error::new(ErrorKind::Other, e)),
}
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

View File

@@ -0,0 +1,17 @@
mod adb_message_device;
mod adb_message_device_commands;
mod adb_tcp_device;
mod adb_transport_message;
mod adb_usb_device;
mod commands;
mod message_writer;
mod models;
mod shell_message_writer;
use adb_message_device::ADBMessageDevice;
pub use adb_tcp_device::ADBTcpDevice;
pub use adb_transport_message::{ADBTransportMessage, ADBTransportMessageHeader};
pub use adb_usb_device::{get_default_adb_key_path, ADBUSBDevice};
pub use message_writer::MessageWriter;
pub use models::{ADBRsaKey, MessageCommand, MessageSubcommand};
pub use shell_message_writer::ShellMessageWriter;

View File

@@ -0,0 +1,175 @@
use crate::{Result, RustADBError};
use base64::{engine::general_purpose::STANDARD, Engine};
use num_bigint::{BigUint, ModInverse};
use num_traits::cast::ToPrimitive;
use num_traits::FromPrimitive;
use rand::rngs::OsRng;
use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PublicKeyParts;
use rsa::{Pkcs1v15Sign, RsaPrivateKey};
const ADB_PRIVATE_KEY_SIZE: usize = 2048;
const ANDROID_PUBKEY_MODULUS_SIZE_WORDS: u32 = 64;
#[repr(C)]
#[derive(Debug, Default)]
/// Internal ADB representation of a public key
struct ADBRsaInternalPublicKey {
pub modulus_size_words: u32,
pub n0inv: u32,
pub modulus: BigUint,
pub rr: Vec<u8>,
pub exponent: u32,
}
impl ADBRsaInternalPublicKey {
pub fn new(exponent: &BigUint, modulus: &BigUint) -> Result<Self> {
Ok(Self {
modulus_size_words: ANDROID_PUBKEY_MODULUS_SIZE_WORDS,
exponent: exponent.to_u32().ok_or(RustADBError::ConversionError)?,
modulus: modulus.clone(),
..Default::default()
})
}
pub fn into_bytes(mut self) -> Vec<u8> {
let mut bytes: Vec<u8> = Vec::new();
bytes.append(&mut self.modulus_size_words.to_le_bytes().to_vec());
bytes.append(&mut self.n0inv.to_le_bytes().to_vec());
bytes.append(&mut self.modulus.to_bytes_le());
bytes.append(&mut self.rr);
bytes.append(&mut self.exponent.to_le_bytes().to_vec());
bytes
}
}
#[derive(Debug, Clone)]
pub struct ADBRsaKey {
private_key: RsaPrivateKey,
}
impl ADBRsaKey {
pub fn new_random() -> Result<Self> {
Ok(Self {
private_key: RsaPrivateKey::new(&mut OsRng, ADB_PRIVATE_KEY_SIZE)?,
})
}
pub fn new_from_pkcs8(pkcs8_content: &str) -> Result<Self> {
Ok(ADBRsaKey {
private_key: RsaPrivateKey::from_pkcs8_pem(pkcs8_content)?,
})
}
pub fn android_pubkey_encode(&self) -> Result<String> {
// Helped from project: https://github.com/hajifkd/webadb
// Source code: https://android.googlesource.com/platform/system/core/+/refs/heads/main/libcrypto_utils/android_pubkey.cpp
// Useful function `android_pubkey_encode()`
let mut adb_rsa_pubkey =
ADBRsaInternalPublicKey::new(self.private_key.e(), self.private_key.n())?;
// r32 = 2 ^ 32
let r32 = BigUint::from_u64(1 << 32).ok_or(RustADBError::ConversionError)?;
// r = 2 ^ rsa_size = 2 ^ 2048
let r = set_bit(ADB_PRIVATE_KEY_SIZE)?;
// rr = r ^ 2 mod N
let rr = r.modpow(&BigUint::from(2u32), &adb_rsa_pubkey.modulus);
adb_rsa_pubkey.rr = rr.to_bytes_le();
// rem = N[0]
let rem = &adb_rsa_pubkey.modulus % &r32;
// n0inv = -1 / rem mod r32
let n0inv = rem
.mod_inverse(&r32)
.and_then(|v| v.to_biguint())
.ok_or(RustADBError::ConversionError)?;
// BN_sub(n0inv, r32, n0inv)
adb_rsa_pubkey.n0inv = (r32 - n0inv)
.to_u32()
.ok_or(RustADBError::ConversionError)?;
Ok(self.encode_public_key(adb_rsa_pubkey.into_bytes()))
}
fn encode_public_key(&self, pub_key: Vec<u8>) -> String {
let mut encoded = STANDARD.encode(pub_key);
encoded.push(' ');
encoded.push_str(&format!("adb_client@{}", env!("CARGO_PKG_VERSION")));
encoded
}
pub fn sign(&self, msg: impl AsRef<[u8]>) -> Result<Vec<u8>> {
Ok(self
.private_key
.sign(Pkcs1v15Sign::new::<sha1::Sha1>(), msg.as_ref())?)
}
}
fn set_bit(n: usize) -> Result<BigUint> {
BigUint::parse_bytes(
&{
let mut bits = vec![b'1'];
bits.append(&mut vec![b'0'; n]);
bits
}[..],
2,
)
.ok_or(RustADBError::ConversionError)
}
#[test]
fn test_pubkey_gen() {
const DEFAULT_PRIV_KEY: &'static str = r"-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4Dyn85cxDJnjM
uYXQl/w469MDKdlGdviLfmFMWeYLVfL2Mz1AVyvKqscrtlhbbgMQ/M+3lDvEdHS0
14RIGAwWRtrlTTmhLvM2/IO+eSKSYeCrCVc4KLG3E3WRryUXbs2ynA29xjTJVw+Z
xYxDyn/tAYPEyMm4v+HIJHcOtRzxtO2vjMJ2vBT/ywYxjhncXbFSO09q2E4XrHli
SIPyO82hZgCkpzTZRp+nyA17TYuV9++mvUr9lWH9RbC+o8EF3yitlBsE2uXr97EV
i2Qy8CE7FIxsihXlukppwKRuz+1rJrvmZPTn49ZS+sIS99WE9GoCpsyQvTpvehrM
SIDRsVZPAgMBAAECggEAWNXAzzXeS36zCSR1yILCknqHotw86Pyc4z7BGUe+dzQp
itiaNIaeNTgN3zQoGyDSzA0o+BLMcfo/JdVrHBy3IL1cAxYtvXTaoGxp7bGrlPk2
pXZhqVJCy/jRYtokzdWF5DHbk/+pFJA3kGE/XKzM54g2n/DFI61A/QdUiz2w1ZtI
vc5cM08EM8B/TSI3SeWB8zkh5SlIuLsFO2J2+tCak6PdFfKOVIrFv9dKJYLxx+59
+edZamw2EvNlnl/sewgUk0gaZvQKVf4ivHyM+KSHuV4RFfiLvGuVcyA6XhSjztsG
EA++jDHP5ib/Izes7UK09v9y7kow+z6vUtnDDQOvgQKBgQD8WWAn7FQt9aziCw19
gZynzHG1bXI7uuEVSneuA3UwJImmDu8W+Qb9YL9Dc2nV0M5pGGdXKi2jzq8gPar6
GPAmy7TOlov6Nm0pbMXTAfuovG+gIXxelp3US3FvyRupi0/7UQRRwvetFYbDFwJX
ydF5uEtZdGSHAjPeU5FLq6tBwQKBgQC6uN0JwwZn+eaxguyKOXvp0KykhFI0HI1A
MBDZ1uuKt6OW5+r9NeQtTLctGlNKVQ8wz+Wr0C/nLGIIv4lySS9WFyc5/FnFhDdy
LsEi6whcca4vq3jsMOukvQGFnERsou4LqBEI1Es7jjeeEq+/8WnNTi6Y1flZ6UAp
YAOeFI98DwKBgQDvyfHgHeajwZalOQF5qGb24AOQ9c4dyefGNnvhA/IgbCfMftZc
iwhETuGQM6R3A7KQFRtlrXOu+2BYD6Ffg8D37IwD3vRmL7+tJGoapwC/B0g+7nLi
4tZY+9Nv+LbrdbDry8GB+/UkKJdk3IFicCk4M5KOD1bTH5mwAtLHB/p1QQKBgDHi
k8M45GxA+p4wMUvYgb987bLiWyfq/N3KOaZJYhJkb4MwoLpXfIeRuFqHbvsr8GwF
DwIxE6s6U1KtAWaUIN5qPyOhxMYdRcbusNDIZCp2gKfhsuO/SiVwDYkJr8oqWVip
5SsrtJHLtBY6PdQVBkRAf/h7KiwYQfkL2suQCKmHAoGBAJAkYImBYPHuRcnSXikn
xGDK/moPvzs0CjdPlRcEN+Myy/G0FUrOaC0FcpNoJOdQSYz3F6URA4nX+zj6Ie7G
CNkECiepaGyquQaffwR1CAi8dH6biJjlTQWQPFcCLA0hvernWo3eaSfiL7fHyym+
ile69MHFENUePSpuRSiF3Z02
-----END PRIVATE KEY-----";
let priv_key =
ADBRsaKey::new_from_pkcs8(DEFAULT_PRIV_KEY).expect("cannot create rsa key from data");
let pub_key = priv_key
.android_pubkey_encode()
.expect("cannot encode public key");
let pub_key_adb = "\
QAAAAFH/pU9PVrHRgEjMGnpvOr2QzKYCavSE1fcSwvpS1uPn9GTmuyZr7c9up\
MBpSrrlFYpsjBQ7IfAyZIsVsffr5doEG5StKN8FwaO+sEX9YZX9Sr2m7/eVi0\
17Dcinn0bZNKekAGahzTvyg0hieawXTthqTztSsV3cGY4xBsv/FLx2woyv7bT\
xHLUOdyTI4b+4ycjEgwHtf8pDjMWZD1fJNMa9DZyyzW4XJa+RdRO3sSg4Vwmr\
4GGSInm+g/w28y6hOU3l2kYWDBhIhNe0dHTEO5S3z/wQA25bWLYrx6rKK1dAP\
TP28lUL5llMYX6L+HZG2SkD0+s4/JfQhbnMeCZDzOX8KQ+4ThLy/gDTqCSTjj\
ic8BykdUIqYPwAjBMgQwLOLY5WNJMpjGlFINRcCGhvFFZ73sJTLerECuV/Oae\
nFRcORwnGIRgMrYXj4tjmxJC7sq3cfNX96YIcSCDE9SZFdlKXVK8Jc4YMLGF3\
MI8k1KoTby34uaIyxPJvwM1WR4Rdj60fwMyikFXNaOR2fPteZ3UMBA7CMrOEm\
9iYjntyEppA4hQXIO1TWTzkA/Kfl1i67k5NuLIQdhPFEc5ox5IYVHusauPQ7d\
Awu6BlgK37TUn0JdK0Z6Z4RaEIaNiEI0d5CoP6zQKV2QQnlscYpdsaUW5t9/F\
LioVXPwrz0tx35JyIUZPPYwEAAQA= ";
assert_eq!(&pub_key[..pub_key_adb.len()], pub_key_adb);
}

View File

@@ -0,0 +1,65 @@
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::fmt::Display;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize_repr, Deserialize_repr)]
#[repr(u32)]
pub enum MessageCommand {
/// Connect to a device
Cnxn = 0x4e584e43,
/// Close connection to a device
Clse = 0x45534c43,
/// Device ask for authentication
Auth = 0x48545541,
/// Open a data connection
Open = 0x4e45504f,
/// Write data to connection
Write = 0x45545257,
/// Server understood the message
Okay = 0x59414b4f,
// Sync 0x434e5953
/// Start a connection using TLS
Stls = 0x534C5453,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize_repr, Deserialize_repr)]
#[repr(u32)]
pub enum MessageSubcommand {
Stat = 0x54415453,
Send = 0x444E4553,
Recv = 0x56434552,
Quit = 0x54495551,
Fail = 0x4c494146,
Done = 0x454e4f44,
Data = 0x41544144,
List = 0x5453494c,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SubcommandWithArg {
subcommand: MessageSubcommand,
arg: u32,
}
impl MessageSubcommand {
pub fn with_arg(self, arg: u32) -> SubcommandWithArg {
SubcommandWithArg {
subcommand: self,
arg,
}
}
}
impl Display for MessageCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MessageCommand::Cnxn => write!(f, "CNXN"),
MessageCommand::Clse => write!(f, "CLSE"),
MessageCommand::Auth => write!(f, "AUTH"),
MessageCommand::Open => write!(f, "OPEN"),
MessageCommand::Write => write!(f, "WRTE"),
MessageCommand::Okay => write!(f, "OKAY"),
MessageCommand::Stls => write!(f, "STLS"),
}
}
}

View File

@@ -0,0 +1,5 @@
mod adb_rsa_key;
mod message_commands;
pub use adb_rsa_key::ADBRsaKey;
pub use message_commands::{MessageCommand, MessageSubcommand};

View File

@@ -0,0 +1,41 @@
use std::io::Write;
use crate::ADBMessageTransport;
use super::{models::MessageCommand, ADBTransportMessage};
/// [`Write`] trait implementation to hide underlying ADB protocol write logic for shell commands.
pub struct ShellMessageWriter<T: ADBMessageTransport> {
transport: T,
local_id: u32,
remote_id: u32,
}
impl<T: ADBMessageTransport> ShellMessageWriter<T> {
pub fn new(transport: T, local_id: u32, remote_id: u32) -> Self {
Self {
transport,
local_id,
remote_id,
}
}
}
impl<T: ADBMessageTransport> Write for ShellMessageWriter<T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let message = ADBTransportMessage::new(
MessageCommand::Write,
self.local_id,
self.remote_id,
buf.to_vec(),
);
self.transport
.write_message(message)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

View File

@@ -1,15 +1,14 @@
use std::net::{Ipv4Addr, SocketAddrV4};
use std::{
net::{Ipv4Addr, SocketAddrV4},
sync::LazyLock,
};
use crate::{ADBTransport, Result, RustADBError, TCPEmulatorTransport};
use lazy_static::lazy_static;
use crate::{ADBServerDevice, ADBTransport, Result, RustADBError, TCPEmulatorTransport};
use regex::Regex;
use super::ADBServerDevice;
lazy_static! {
pub static ref EMULATOR_REGEX: Regex =
Regex::new("^emulator-(?P<port>\\d+)$").expect("wrong syntax for emulator regex");
}
static EMULATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("^emulator-(?P<port>\\d+)$").expect("wrong syntax for emulator regex")
});
/// Represents an emulator connected to the ADB server.
#[derive(Debug)]

View File

@@ -0,0 +1,3 @@
mod adb_emulator_device;
mod commands;
pub use adb_emulator_device::ADBEmulatorDevice;

View File

@@ -54,7 +54,70 @@ pub enum RustADBError {
/// An error occurred when converting framebuffer content
#[error("Cannot convert framebuffer into image")]
FramebufferConversionError,
/// Unimplemented framebuffer image version
#[error("Unimplemented framebuffer image version: {0}")]
UnimplementedFramebufferImageVersion(u32),
/// An error occurred while getting user's home directory
#[error(transparent)]
HomeError(#[from] homedir::GetHomeError),
/// Cannot get home directory
#[error("Cannot get home directory")]
NoHomeDirectory,
/// Generic USB error
#[error(transparent)]
UsbError(#[from] rusb::Error),
/// USB device not found
#[error("USB Device not found: {0} {1}")]
USBDeviceNotFound(u16, u16),
/// No descriptor found
#[error("No USB descriptor found")]
USBNoDescriptorFound,
/// Integrity of the received message cannot be validated
#[error("Invalid integrity. Expected CRC32 {0}, got {1}")]
InvalidIntegrity(u32, u32),
/// Error while decoding base64 data
#[error(transparent)]
Base64DecodeError(#[from] base64::DecodeError),
/// Error while encoding base64 data
#[error(transparent)]
Base64EncodeError(#[from] base64::EncodeSliceError),
/// An error occurred with RSA engine
#[error(transparent)]
RSAError(#[from] rsa::errors::Error),
/// Cannot convert given data from slice
#[error(transparent)]
TryFromSliceError(#[from] std::array::TryFromSliceError),
/// Given path does not represent an APK
#[error("wrong file extension: {0}")]
WrongFileExtension(String),
/// An error occurred with PKCS8 data
#[error("error with pkcs8: {0}")]
RsaPkcs8Error(#[from] rsa::pkcs8::Error),
/// Error during certificate generation
#[error(transparent)]
CertificateGenerationError(#[from] rcgen::Error),
/// TLS Error
#[error(transparent)]
TLSError(#[from] rustls::Error),
/// PEM certificate error
#[error(transparent)]
PemCertError(#[from] rustls_pki_types::pem::Error),
/// Error while locking mutex
#[error("error while locking data")]
PoisonError,
/// Cannot upgrade connection from TCP to TLS
#[error("upgrade error: {0}")]
UpgradeError(String),
/// An error occurred while getting mdns devices
#[error(transparent)]
MDNSError(#[from] mdns_sd::Error),
/// An error occurred while sending data to channel
#[error(transparent)]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>),
}
impl<T> From<std::sync::PoisonError<T>> for RustADBError {
fn from(_err: std::sync::PoisonError<T>) -> Self {
Self::PoisonError
}
}

View File

@@ -4,15 +4,26 @@
#![forbid(missing_docs)]
#![doc = include_str!("../README.md")]
mod adb_termios;
mod emulator;
mod adb_device_ext;
mod constants;
mod device;
mod emulator_device;
mod error;
mod mdns;
mod models;
mod server;
mod server_device;
mod transports;
mod utils;
pub use adb_device_ext::ADBDeviceExt;
pub use device::{ADBTcpDevice, ADBUSBDevice};
pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError};
pub use models::{AdbVersion, DeviceLong, DeviceShort, DeviceState, RebootType};
pub use mdns::*;
pub use models::{
AdbStatResponse, AdbVersion, DeviceLong, DeviceShort, DeviceState, MDNSBackend, RebootType,
};
pub use server::*;
pub use server_device::ADBServerDevice;
pub use transports::*;

View File

@@ -0,0 +1,19 @@
use std::{collections::HashSet, net::IpAddr};
/// Represent a device found from mdns search
#[derive(Debug)]
pub struct MDNSDevice {
/// Full device address when resolved
pub fullname: String,
/// Device IP addresses
pub addresses: HashSet<IpAddr>,
}
impl From<mdns_sd::ServiceInfo> for MDNSDevice {
fn from(value: mdns_sd::ServiceInfo) -> Self {
Self {
fullname: value.get_fullname().to_string(),
addresses: value.get_addresses().to_owned(),
}
}
}

View File

@@ -0,0 +1,73 @@
use mdns_sd::{ServiceDaemon, ServiceEvent};
use std::{sync::mpsc::Sender, thread::JoinHandle};
use crate::{MDNSDevice, Result, RustADBError};
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
/// Structure holding responsibility over mdns discovery
pub struct MDNSDiscoveryService {
daemon: ServiceDaemon,
thread_handle: Option<JoinHandle<Result<()>>>,
}
impl std::fmt::Debug for MDNSDiscoveryService {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MDNSDiscoveryService")
.field("daemon", &self.daemon.get_metrics())
.field("handle", &self.thread_handle)
.finish()
}
}
impl MDNSDiscoveryService {
/// Instantiate a new discovery service to find devices over mdns
pub fn new() -> Result<Self> {
Ok(MDNSDiscoveryService {
daemon: ServiceDaemon::new()?,
thread_handle: None,
})
}
/// Start discovery by spawning a new thread responsible of getting events.
pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> {
let receiver = self.daemon.browse(ADB_SERVICE_NAME)?;
let handle: JoinHandle<Result<()>> = std::thread::spawn(move || loop {
while let Ok(event) = receiver.recv() {
match event {
ServiceEvent::SearchStarted(_)
| ServiceEvent::ServiceRemoved(_, _)
| ServiceEvent::ServiceFound(_, _)
| ServiceEvent::SearchStopped(_) => {
// Ignoring these events. We are only interesting in found devices
continue;
}
ServiceEvent::ServiceResolved(service_info) => {
if let Err(e) = sender.send(MDNSDevice::from(service_info)) {
return Err(e.into());
}
}
}
}
});
self.thread_handle = Some(handle);
Ok(())
}
/// Shutdown discovery engines.
pub fn shutdown(&mut self) -> Result<()> {
match self.daemon.shutdown() {
Ok(_) => Ok(()),
Err(e) => match e {
mdns_sd::Error::Again => {
self.daemon.shutdown()?;
Ok(())
}
e => Err(RustADBError::MDNSError(e)),
},
}
}
}

View File

@@ -0,0 +1,5 @@
mod mdns_device;
mod mdns_discovery;
pub use mdns_device::MDNSDevice;
pub use mdns_discovery::MDNSDiscoveryService;

View File

@@ -13,15 +13,27 @@ pub(crate) enum AdbServerCommand {
HostFeatures,
Connect(SocketAddrV4),
Disconnect(SocketAddrV4),
Pair(SocketAddrV4, u32),
Pair(SocketAddrV4, String),
TransportAny,
TransportSerial(String),
MDNSCheck,
MDNSServices,
ServerStatus,
ReconnectOffline,
Install(u64),
// Local commands
ShellCommand(String),
Shell,
FrameBuffer,
Sync,
Reboot(RebootType),
Forward(String, String),
ForwardRemoveAll,
Reverse(String, String),
ReverseRemoveAll,
Reconnect,
TcpIp(u16),
Usb,
}
impl Display for AdbServerCommand {
@@ -50,9 +62,38 @@ impl Display for AdbServerCommand {
AdbServerCommand::Connect(addr) => write!(f, "host:connect:{}", addr),
AdbServerCommand::Disconnect(addr) => write!(f, "host:disconnect:{}", addr),
AdbServerCommand::Pair(addr, code) => {
write!(f, "host:pair:{code}:{}", addr)
write!(f, "host:pair:{code}:{addr}")
}
AdbServerCommand::FrameBuffer => write!(f, "framebuffer:"),
AdbServerCommand::Forward(remote, local) => {
write!(f, "host:forward:{local};{remote}")
}
AdbServerCommand::ForwardRemoveAll => write!(f, "host:killforward-all"),
AdbServerCommand::Reverse(remote, local) => {
write!(f, "reverse:forward:{remote};{local}")
}
AdbServerCommand::ReverseRemoveAll => write!(f, "reverse:killforward-all"),
AdbServerCommand::MDNSCheck => write!(f, "host:mdns:check"),
AdbServerCommand::MDNSServices => write!(f, "host:mdns:services"),
AdbServerCommand::ServerStatus => write!(f, "host:server-status"),
AdbServerCommand::Reconnect => write!(f, "reconnect"),
AdbServerCommand::ReconnectOffline => write!(f, "host:reconnect-offline"),
AdbServerCommand::TcpIp(port) => {
write!(f, "tcpip:{port}")
}
AdbServerCommand::Usb => write!(f, "usb:"),
AdbServerCommand::Install(size) => write!(f, "exec:cmd package 'install' -S {size}"),
}
}
}
#[test]
fn test_pair_command() {
let host = "192.168.0.197:34783";
let code = "091102";
let code_u32 = code.parse::<u32>().expect("cannot parse u32");
let pair = AdbServerCommand::Pair(host.parse().expect("cannot parse host"), code.into());
assert_eq!(pair.to_string(), format!("host:pair:{code}:{host}"));
assert_ne!(pair.to_string(), format!("host:pair:{code_u32}:{host}"))
}

View File

@@ -0,0 +1,47 @@
use byteorder::ByteOrder;
use chrono::{DateTime, Utc};
use std::{
fmt::Display,
time::{Duration, UNIX_EPOCH},
};
use byteorder::LittleEndian;
use serde::{Deserialize, Serialize};
/// Represents a `stat` response
#[derive(Debug, Deserialize, Serialize)]
pub struct AdbStatResponse {
/// File permissions
pub file_perm: u32,
/// File size, in bytes
pub file_size: u32,
/// File modification time
pub mod_time: u32,
}
impl From<[u8; 12]> for AdbStatResponse {
fn from(value: [u8; 12]) -> Self {
Self {
file_perm: LittleEndian::read_u32(&value[0..4]),
file_size: LittleEndian::read_u32(&value[4..8]),
mod_time: LittleEndian::read_u32(&value[8..]),
}
}
}
impl Display for AdbStatResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let d = UNIX_EPOCH + Duration::from_secs(self.mod_time.into());
// Create DateTime from SystemTime
let datetime = DateTime::<Utc>::from(d);
writeln!(f, "File permissions: {}", self.file_perm)?;
writeln!(f, "File size: {} bytes", self.file_size)?;
write!(
f,
"Modification time: {}",
datetime.format("%Y-%m-%d %H:%M:%S.%f %Z")
)?;
Ok(())
}
}

View File

@@ -1,16 +1,15 @@
use lazy_static::lazy_static;
use std::str::FromStr;
use std::sync::LazyLock;
use std::{fmt::Display, str};
use crate::{DeviceState, RustADBError};
use regex::bytes::Regex;
lazy_static! {
static ref DEVICES_LONG_REGEX: Regex = Regex::new("^(?P<identifier>\\S+)\\s+(?P<state>\\w+) ((usb:(?P<usb1>.*)|(?P<usb2>\\d-\\d)) )?(product:(?P<product>\\w+) model:(?P<model>\\w+) device:(?P<device>\\w+) )?transport_id:(?P<transport_id>\\d+)$").expect("cannot build devices long regex");
static DEVICES_LONG_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("^(?P<identifier>\\S+)\\s+(?P<state>\\w+) ((usb:(?P<usb1>.*)|(?P<usb2>\\d-\\d)) )?(product:(?P<product>\\w+) model:(?P<model>\\w+) device:(?P<device>\\w+) )?transport_id:(?P<transport_id>\\d+)$").expect("cannot build devices long regex")
});
}
/// Represents a new device with more informations helded.
/// Represents a new device with more informations.
#[derive(Debug)]
pub struct DeviceLong {
/// Unique device identifier.
@@ -68,14 +67,13 @@ impl TryFrom<Vec<u8>> for DeviceLong {
.as_bytes()
.to_vec(),
)?)?,
usb: String::from_utf8(
groups
.name("usb1")
.or_else(|| groups.name("usb2"))
.ok_or(RustADBError::RegexParsingError)?
.as_bytes()
.to_vec(),
)?,
usb: match groups.name("usb1") {
None => match groups.name("usb2") {
None => "Unk".to_string(),
Some(usb) => String::from_utf8(usb.as_bytes().to_vec())?,
},
Some(usb) => String::from_utf8(usb.as_bytes().to_vec())?,
},
product: match groups.name("product") {
None => "Unk".to_string(),
Some(product) => String::from_utf8(product.as_bytes().to_vec())?,

View File

@@ -1,12 +1,10 @@
use lazy_static::lazy_static;
use regex::bytes::Regex;
use std::{fmt::Display, str::FromStr};
use std::{fmt::Display, str::FromStr, sync::LazyLock};
use crate::{DeviceState, RustADBError};
lazy_static! {
static ref DEVICES_REGEX: Regex = Regex::new("^(\\S+)\t(\\w+)\n?$").unwrap();
}
static DEVICES_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new("^(\\S+)\t(\\w+)\n?$").expect("Cannot build devices regex"));
/// Represents a device connected to the ADB server.
#[derive(Debug, Clone)]
@@ -28,7 +26,9 @@ impl TryFrom<Vec<u8>> for DeviceShort {
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
// Optional final '\n' is used to match TrackDevices inputs
let groups = DEVICES_REGEX.captures(&value).unwrap();
let groups = DEVICES_REGEX
.captures(&value)
.ok_or(RustADBError::RegexParsingError)?;
Ok(DeviceShort {
identifier: String::from_utf8(
groups

View File

@@ -15,6 +15,22 @@ pub enum DeviceState {
Authorizing,
/// The device is unauthorized.
Unauthorized,
/// Haven't received a response from the device yet.
Connecting,
/// Insufficient permissions to communicate with the device.
NoPerm,
/// USB device detached from the adb server (known but not opened/claimed).
Detached,
/// Device running fastboot OS (fastboot) or userspace fastboot (fastbootd).
Bootloader,
/// What a device sees from its end of a Transport (adb host).
Host,
/// Device with bootloader loaded but no ROM OS loaded (adbd).
Recovery,
/// Device running Android OS Sideload mode (minadbd sideload mode).
Sideload,
/// Device running Android OS Rescue mode (minadbd rescue mode).
Rescue,
}
impl Display for DeviceState {
@@ -25,6 +41,14 @@ impl Display for DeviceState {
DeviceState::NoDevice => write!(f, "no device"),
DeviceState::Authorizing => write!(f, "authorizing"),
DeviceState::Unauthorized => write!(f, "unauthorized"),
DeviceState::Connecting => write!(f, "connecting"),
DeviceState::NoPerm => write!(f, "noperm"),
DeviceState::Detached => write!(f, "detached"),
DeviceState::Bootloader => write!(f, "bootloader"),
DeviceState::Host => write!(f, "host"),
DeviceState::Recovery => write!(f, "recovery"),
DeviceState::Sideload => write!(f, "sideload"),
DeviceState::Rescue => write!(f, "rescue"),
}
}
}
@@ -40,6 +64,14 @@ impl FromStr for DeviceState {
"no device" => Ok(Self::NoDevice),
"authorizing" => Ok(Self::Authorizing),
"unauthorized" => Ok(Self::Unauthorized),
"connecting" => Ok(Self::Connecting),
"noperm" => Ok(Self::NoPerm),
"detached" => Ok(Self::Detached),
"bootloader" => Ok(Self::Bootloader),
"host" => Ok(Self::Host),
"recovery" => Ok(Self::Recovery),
"sideload" => Ok(Self::Sideload),
"rescue" => Ok(Self::Rescue),
_ => Err(RustADBError::UnknownDeviceState(lowercased)),
}
}

View File

@@ -0,0 +1,64 @@
use regex::bytes::Regex;
use std::net::SocketAddrV4;
use std::sync::LazyLock;
use std::{fmt::Display, str::FromStr};
use crate::RustADBError;
static MDNS_SERVICES_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new("^(\\S+)\t(\\S+)\t([\\d\\.]+:\\d+)\n?$").expect("Cannot build mdns services regex")
});
/// Represents MDNS Services
#[derive(Debug, Clone)]
pub struct MDNSServices {
/// Service name
pub service_name: String,
/// Reg type
pub reg_type: String,
/// IP addr with port
pub socket_v4: SocketAddrV4,
}
impl Display for MDNSServices {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}\t{}\t{}",
self.service_name, self.reg_type, self.socket_v4
)
}
}
impl TryFrom<&[u8]> for MDNSServices {
type Error = RustADBError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let groups = MDNS_SERVICES_REGEX
.captures(value)
.ok_or(RustADBError::RegexParsingError)?;
Ok(MDNSServices {
service_name: String::from_utf8(
groups
.get(1)
.ok_or(RustADBError::RegexParsingError)?
.as_bytes()
.to_vec(),
)?,
reg_type: String::from_utf8(
groups
.get(2)
.ok_or(RustADBError::RegexParsingError)?
.as_bytes()
.to_vec(),
)?,
socket_v4: SocketAddrV4::from_str(&String::from_utf8(
groups
.get(3)
.ok_or(RustADBError::RegexParsingError)?
.as_bytes()
.to_vec(),
)?)?,
})
}
}

View File

@@ -1,21 +1,28 @@
mod adb_emulator_command;
mod adb_request_status;
mod adb_server_command;
mod adb_stat_response;
mod adb_version;
mod device_long;
mod device_short;
mod device_state;
mod host_features;
mod mdns_services;
mod reboot_type;
mod server_status;
mod sync_command;
pub(crate) use adb_emulator_command::ADBEmulatorCommand;
pub use adb_request_status::AdbRequestStatus;
pub(crate) use adb_server_command::AdbServerCommand;
pub use adb_stat_response::AdbStatResponse;
pub use adb_version::AdbVersion;
pub use device_long::DeviceLong;
pub use device_short::DeviceShort;
pub use device_state::DeviceState;
pub use host_features::HostFeatures;
pub use mdns_services::MDNSServices;
pub use reboot_type::RebootType;
pub use server_status::MDNSBackend;
pub use server_status::ServerStatus;
pub use sync_command::SyncCommand;

View File

@@ -0,0 +1,158 @@
use quick_protobuf::{BytesReader, MessageRead};
use std::fmt::Display;
use crate::RustADBError;
#[derive(Debug, PartialEq, Default, Eq, Clone, Copy)]
pub enum UsbBackend {
#[default]
Unknown = 0,
Native = 1,
LibUSB = 2,
}
impl From<i32> for UsbBackend {
fn from(i: i32) -> Self {
match i {
0 => UsbBackend::Unknown,
1 => UsbBackend::Native,
2 => UsbBackend::LibUSB,
_ => Self::default(),
}
}
}
impl<'a> From<&'a str> for UsbBackend {
fn from(s: &'a str) -> Self {
match s {
"UNKNOWN_USB" => UsbBackend::Unknown,
"NATIVE" => UsbBackend::Native,
"LIBUSB" => UsbBackend::LibUSB,
_ => Self::default(),
}
}
}
impl Display for UsbBackend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UsbBackend::Unknown => write!(f, "UNKNOWN_USB"),
UsbBackend::Native => write!(f, "NATIVE"),
UsbBackend::LibUSB => write!(f, "LIBUSB"),
}
}
}
/// MDNS Backend Status
#[derive(Debug, Clone, PartialEq, Default)]
pub enum MDNSBackend {
#[default]
/// Unknown
Unknown = 0,
/// Bonjour
Bonjour = 1,
/// OpenScreen
OpenScreen = 2,
}
impl From<i32> for MDNSBackend {
fn from(i: i32) -> Self {
match i {
0 => MDNSBackend::Unknown,
1 => MDNSBackend::Bonjour,
2 => MDNSBackend::OpenScreen,
_ => Self::default(),
}
}
}
impl<'a> From<&'a str> for MDNSBackend {
fn from(s: &'a str) -> Self {
match s {
"UNKNOWN_MDNS" => MDNSBackend::Unknown,
"BONJOUR" => MDNSBackend::Bonjour,
"OPENSCREEN" => MDNSBackend::OpenScreen,
_ => Self::default(),
}
}
}
impl Display for MDNSBackend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MDNSBackend::Unknown => write!(f, "UNKNOWN_MDNS"),
MDNSBackend::Bonjour => write!(f, "BONJOUR"),
MDNSBackend::OpenScreen => write!(f, "OPENSCREEN"),
}
}
}
/// Structure representing current server status
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ServerStatus {
pub usb_backend: UsbBackend,
pub usb_backend_forced: bool,
pub mdns_backend: MDNSBackend,
pub mdns_backend_forced: bool,
pub version: String,
pub build: String,
pub executable_absolute_path: String,
pub log_absolute_path: String,
pub os: String,
}
impl<'a> MessageRead<'a> for ServerStatus {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> quick_protobuf::Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(8) => msg.usb_backend = r.read_enum(bytes)?,
Ok(16) => msg.usb_backend_forced = r.read_bool(bytes)?,
Ok(24) => msg.mdns_backend = r.read_enum(bytes)?,
Ok(32) => msg.mdns_backend_forced = r.read_bool(bytes)?,
Ok(42) => msg.version = r.read_string(bytes)?.to_string(),
Ok(50) => msg.build = r.read_string(bytes)?.to_string(),
Ok(58) => msg.executable_absolute_path = r.read_string(bytes)?.to_string(),
Ok(66) => msg.log_absolute_path = r.read_string(bytes)?.to_string(),
Ok(74) => msg.os = r.read_string(bytes)?.to_string(),
Ok(t) => {
r.read_unknown(bytes, t)?;
}
Err(e) => return Err(e),
}
}
Ok(msg)
}
}
impl Display for ServerStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "usb_backend: {}", self.usb_backend)?;
if self.usb_backend_forced {
writeln!(f, "usb_backend_forced: {}", self.usb_backend_forced)?;
}
writeln!(f, "mdns_backend: {}", self.mdns_backend)?;
if self.mdns_backend_forced {
writeln!(f, "mdns_backend_forced: {}", self.mdns_backend_forced)?;
}
writeln!(f, "version: \"{}\"", self.version)?;
writeln!(f, "build: \"{}\"", self.build)?;
writeln!(
f,
"executable_absolute_path: \"{}\"",
self.executable_absolute_path
)?;
writeln!(f, "log_absolute_path: \"{}\"", self.log_absolute_path)?;
writeln!(f, "os: \"{}\"", self.os)
}
}
impl TryFrom<Vec<u8>> for ServerStatus {
type Error = RustADBError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
let mut reader = BytesReader::from_bytes(&value);
ServerStatus::from_reader(&mut reader, &value).map_err(|_| RustADBError::ConversionError)
}
}

View File

@@ -2,6 +2,7 @@ use crate::ADBTransport;
use crate::Result;
use crate::RustADBError;
use crate::TCPServerTransport;
use std::collections::HashMap;
use std::net::SocketAddrV4;
use std::process::Command;
@@ -12,6 +13,8 @@ pub struct ADBServer {
pub(crate) transport: Option<TCPServerTransport>,
/// Address to connect to
pub(crate) socket_addr: Option<SocketAddrV4>,
/// adb-server start envs
pub(crate) envs: HashMap<String, String>,
}
impl ADBServer {
@@ -20,6 +23,7 @@ impl ADBServer {
Self {
transport: None,
socket_addr: Some(address),
envs: HashMap::new(),
}
}
@@ -49,7 +53,13 @@ impl ADBServer {
if is_local_ip {
// ADB Server is local, we start it if not already running
let child = Command::new("adb").arg("start-server").spawn();
let mut command = Command::new("adb");
command.arg("start-server");
for (env_k, env_v) in self.envs.iter() {
command.env(env_k, env_v);
}
let child = command.spawn();
match child {
Ok(mut child) => {
if let Err(e) = child.wait() {

View File

@@ -8,9 +8,10 @@ impl ADBServer {
.connect()?
.proxy_connection(AdbServerCommand::Connect(address), true)?;
match String::from_utf8(response).unwrap() {
s if s.starts_with("connected to") => Ok(()),
s => Err(RustADBError::ADBRequestFailed(s)),
match String::from_utf8(response) {
Ok(s) if s.starts_with("connected to") => Ok(()),
Ok(s) => Err(RustADBError::ADBRequestFailed(s)),
Err(e) => Err(e.into()),
}
}
}

View File

@@ -79,7 +79,6 @@ impl ADBServer {
}
/// Tracks new devices showing up.
// TODO: Change with Generator when feature stabilizes
pub fn track_devices(&mut self, callback: impl Fn(DeviceShort) -> Result<()>) -> Result<()> {
self.connect()?
.send_adb_request(AdbServerCommand::TrackDevices)?;

View File

@@ -8,9 +8,10 @@ impl ADBServer {
.connect()?
.proxy_connection(AdbServerCommand::Disconnect(address), true)?;
match String::from_utf8(response).unwrap() {
s if s.starts_with("disconnected") => Ok(()),
s => Err(RustADBError::ADBRequestFailed(s)),
match String::from_utf8(response) {
Ok(s) if s.starts_with("disconnected") => Ok(()),
Ok(s) => Err(RustADBError::ADBRequestFailed(s)),
Err(e) => Err(e.into()),
}
}
}

View File

@@ -0,0 +1,62 @@
use std::io::BufRead;
use crate::{
models::{AdbServerCommand, MDNSBackend, MDNSServices},
ADBServer, Result,
};
const OPENSCREEN_MDNS_BACKEND: &str = "ADB_MDNS_OPENSCREEN";
impl ADBServer {
/// Check if mdns discovery is available
pub fn mdns_check(&mut self) -> Result<bool> {
let response = self
.connect()?
.proxy_connection(AdbServerCommand::MDNSCheck, true)?;
match String::from_utf8(response) {
Ok(s) if s.starts_with("mdns daemon version") => Ok(true),
Ok(_) => Ok(false),
Err(e) => Err(e.into()),
}
}
/// List all discovered mdns services
pub fn mdns_services(&mut self) -> Result<Vec<MDNSServices>> {
let services = self
.connect()?
.proxy_connection(AdbServerCommand::MDNSServices, true)?;
let mut vec_services: Vec<MDNSServices> = vec![];
for service in services.lines() {
match service {
Ok(service) => {
vec_services.push(MDNSServices::try_from(service.as_bytes())?);
}
Err(e) => log::error!("{}", e),
}
}
Ok(vec_services)
}
/// Check if specified backend mdns service is used, otherwise restart adb server with envs
pub fn mdns_force_backend(&mut self, backend: MDNSBackend) -> Result<()> {
let server_status = self.server_status()?;
if server_status.mdns_backend != backend {
self.kill()?;
self.envs.insert(
OPENSCREEN_MDNS_BACKEND.to_string(),
(if backend == MDNSBackend::OpenScreen {
"1"
} else {
"0"
})
.to_string(),
);
self.connect()?;
}
Ok(())
}
}

View File

@@ -2,5 +2,8 @@ mod connect;
mod devices;
mod disconnect;
mod kill;
mod mdns;
mod pair;
mod reconnect;
mod server_status;
mod version;

View File

@@ -4,14 +4,15 @@ use std::net::SocketAddrV4;
impl ADBServer {
/// Pair device on a specific port with a generated 'code'
pub fn pair(&mut self, address: SocketAddrV4, code: u32) -> Result<()> {
pub fn pair(&mut self, address: SocketAddrV4, code: String) -> Result<()> {
let response = self
.connect()?
.proxy_connection(AdbServerCommand::Pair(address, code), true)?;
match String::from_utf8(response).unwrap() {
s if s.starts_with("Successfully paired to") => Ok(()),
s => Err(RustADBError::ADBRequestFailed(s)),
match String::from_utf8(response) {
Ok(s) if s.starts_with("Successfully paired to") => Ok(()),
Ok(s) => Err(RustADBError::ADBRequestFailed(s)),
Err(e) => Err(e.into()),
}
}
}

View File

@@ -0,0 +1,10 @@
use crate::{models::AdbServerCommand, ADBServer, Result};
impl ADBServer {
/// Reconnect the device
pub fn reconnect_offline(&mut self) -> Result<()> {
self.connect()?
.proxy_connection(AdbServerCommand::ReconnectOffline, false)
.map(|_| ())
}
}

View File

@@ -0,0 +1,15 @@
use crate::{
models::{AdbServerCommand, ServerStatus},
ADBServer, Result,
};
impl ADBServer {
/// Check ADB server status
pub fn server_status(&mut self) -> Result<ServerStatus> {
let status = self
.connect()?
.proxy_connection(AdbServerCommand::ServerStatus, true)?;
ServerStatus::try_from(status)
}
}

View File

@@ -1,85 +0,0 @@
use crate::{
models::{AdbServerCommand, SyncCommand},
ADBServerDevice, Result, RustADBError,
};
use byteorder::{ByteOrder, LittleEndian};
use std::io::{Read, Write};
impl ADBServerDevice {
/// Receives [path] to [stream] from the device.
pub fn recv<A: AsRef<str>>(&mut self, path: A, stream: &mut dyn Write) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
// Set device in SYNC mode
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Sync)?;
// Send a recv command
self.get_transport_mut()
.send_sync_request(SyncCommand::Recv)?;
self.handle_recv_command(path, stream)
}
fn handle_recv_command<S: AsRef<str>>(
&mut self,
from: S,
output: &mut dyn Write,
) -> Result<()> {
// First send 8 byte common header
let mut len_buf = [0_u8; 4];
LittleEndian::write_u32(&mut len_buf, from.as_ref().len() as u32);
self.get_transport_mut()
.get_raw_connection()?
.write_all(&len_buf)?;
self.get_transport_mut()
.get_raw_connection()?
.write_all(from.as_ref().as_bytes())?;
// Then we receive the byte data in chunks of up to 64k
// Chunk looks like 'DATA' <length> <data>
let mut buffer = [0_u8; 64 * 1024]; // Should this be Boxed?
let mut data_header = [0_u8; 4]; // DATA
loop {
self.get_transport_mut()
.get_raw_connection()?
.read_exact(&mut data_header)?;
// Check if data_header is DATA or DONE or FAIL
match &data_header {
b"DATA" => {
// Handle received data
let length: usize = self
.get_transport_mut()
.get_body_length()?
.try_into()
.unwrap();
self.get_transport_mut()
.get_raw_connection()?
.read_exact(&mut buffer[..length])?;
output.write_all(&buffer[..length])?;
}
b"DONE" => break, // We're done here
b"FAIL" => {
// Handle fail
let length: usize = self
.get_transport_mut()
.get_body_length()?
.try_into()
.unwrap();
self.get_transport_mut()
.get_raw_connection()?
.read_exact(&mut buffer[..length])?;
Err(RustADBError::ADBRequestFailed(String::from_utf8(
buffer[..length].to_vec(),
)?))?;
}
_ => panic!("Unknown response from device {:#?}", data_header),
}
}
// Connection should've left SYNC by now
Ok(())
}
}

View File

@@ -1,110 +0,0 @@
use crate::{
models::{AdbRequestStatus, AdbServerCommand, SyncCommand},
ADBServerDevice, Result, RustADBError,
};
use byteorder::{ByteOrder, LittleEndian};
use std::{
convert::TryInto,
io::{Read, Write},
str::{self, FromStr},
time::SystemTime,
};
impl ADBServerDevice {
/// Send [stream] to [path] on the device.
pub fn send<A: AsRef<str>>(&mut self, stream: &mut dyn Read, path: A) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
// Set device in SYNC mode
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Sync)?;
// Send a send command
self.get_transport_mut()
.send_sync_request(SyncCommand::Send)?;
self.handle_send_command(stream, path)
}
fn handle_send_command<S: AsRef<str>>(&mut self, input: &mut dyn Read, to: S) -> Result<()> {
// Append the permission flags to the filename
let to = to.as_ref().to_string() + ",0777";
// The name of command is already sent by get_transport()?.send_sync_request
let mut len_buf = [0_u8; 4];
LittleEndian::write_u32(&mut len_buf, to.len() as u32);
self.get_transport_mut()
.get_raw_connection()?
.write_all(&len_buf)?;
// Send appends the filemode to the string sent
self.get_transport_mut()
.get_raw_connection()?
.write_all(to.as_bytes())?;
// Then we send the byte data in chunks of up to 64k
// Chunk looks like 'DATA' <length> <data>
let mut buffer = [0_u8; 64 * 1024];
loop {
let bytes_read = input.read(&mut buffer)?;
if bytes_read == 0 {
break;
}
let mut chunk_len_buf = [0_u8; 4];
LittleEndian::write_u32(&mut chunk_len_buf, bytes_read as u32);
self.get_transport_mut()
.get_raw_connection()?
.write_all(b"DATA")?;
self.get_transport_mut()
.get_raw_connection()?
.write_all(&chunk_len_buf)?;
self.get_transport_mut()
.get_raw_connection()?
.write_all(&buffer[..bytes_read])?;
}
// When we are done sending, we send 'DONE' <last modified time>
// Re-use len_buf to send the last modified time
let last_modified = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n,
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
};
LittleEndian::write_u32(&mut len_buf, last_modified.as_secs() as u32);
self.get_transport_mut()
.get_raw_connection()?
.write_all(b"DONE")?;
self.get_transport_mut()
.get_raw_connection()?
.write_all(&len_buf)?;
// We expect 'OKAY' response from this
let mut request_status = [0; 4];
self.get_transport_mut()
.get_raw_connection()?
.read_exact(&mut request_status)?;
match AdbRequestStatus::from_str(str::from_utf8(request_status.as_ref())?)? {
AdbRequestStatus::Fail => {
// We can keep reading to get further details
let length = self.get_transport_mut().get_body_length()?;
let mut body = vec![
0;
length
.try_into()
.map_err(|_| RustADBError::ConversionError)?
];
if length > 0 {
self.get_transport_mut()
.get_raw_connection()?
.read_exact(&mut body)?;
}
Err(RustADBError::ADBRequestFailed(String::from_utf8(body)?))
}
AdbRequestStatus::Okay => Ok(()),
}
}
}

View File

@@ -1,155 +0,0 @@
use std::{
io::{self, Read, Write},
sync::mpsc,
time::Duration,
};
use mio::{unix::SourceFd, Events, Interest, Poll, Token};
use crate::{
adb_termios::ADBTermios,
models::{AdbServerCommand, HostFeatures},
ADBServerDevice, Result, RustADBError,
};
const STDIN: Token = Token(0);
const BUFFER_SIZE: usize = 512;
const POLL_DURATION: Duration = Duration::from_millis(100);
fn setup_poll_stdin() -> std::result::Result<Poll, io::Error> {
let poll = Poll::new()?;
let stdin_fd = 0;
poll.registry()
.register(&mut SourceFd(&stdin_fd), STDIN, Interest::READABLE)?;
Ok(poll)
}
impl ADBServerDevice {
/// Runs 'command' in a shell on the device, and return its output and error streams.
pub fn shell_command<S: ToString>(
&mut self,
command: impl IntoIterator<Item = S>,
) -> Result<Vec<u8>> {
let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2)
&& !supported_features.contains(&HostFeatures::Cmd)
{
return Err(RustADBError::ADBShellNotSupported);
}
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.send_adb_request(AdbServerCommand::ShellCommand(
command
.into_iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" "),
))?;
const BUFFER_SIZE: usize = 512;
let mut result = Vec::new();
loop {
let mut buffer = [0; BUFFER_SIZE];
match self
.get_transport_mut()
.get_raw_connection()?
.read(&mut buffer)
{
Ok(size) => {
if size == 0 {
return Ok(result);
} else {
result.extend_from_slice(&buffer[..size]);
}
}
Err(e) => {
return Err(RustADBError::IOError(e));
}
}
}
}
/// Starts an interactive shell session on the device. Redirects stdin/stdout/stderr as appropriate.
pub fn shell(&mut self) -> Result<()> {
let mut adb_termios = ADBTermios::new(std::io::stdin())?;
adb_termios.set_adb_termios()?;
self.connect()?.get_raw_connection()?.set_nodelay(true)?;
// TODO: FORWARD CTRL+C !!
let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2)
&& !supported_features.contains(&HostFeatures::Cmd)
{
return Err(RustADBError::ADBShellNotSupported);
}
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Shell)?;
// let read_stream = Arc::new(self.tcp_stream);
let mut read_stream = self.get_transport_mut().get_raw_connection()?.try_clone()?;
let (tx, rx) = mpsc::channel::<bool>();
let mut write_stream = read_stream.try_clone()?;
// Reading thread
std::thread::spawn(move || -> Result<()> {
loop {
let mut buffer = [0; BUFFER_SIZE];
match read_stream.read(&mut buffer) {
Ok(0) => {
let _ = tx.send(true);
read_stream.shutdown(std::net::Shutdown::Both)?;
return Ok(());
}
Ok(size) => {
std::io::stdout().write_all(&buffer[..size])?;
std::io::stdout().flush()?;
}
Err(e) => {
return Err(RustADBError::IOError(e));
}
}
}
});
let mut buf = [0; BUFFER_SIZE];
let mut events = Events::with_capacity(1);
let mut poll = setup_poll_stdin()?;
// Polling either by checking that reading socket hasn't been closed, and if is there is something to read on stdin.
loop {
poll.poll(&mut events, Some(POLL_DURATION))?;
match rx.try_recv() {
Ok(_) | Err(mpsc::TryRecvError::Disconnected) => return Ok(()),
Err(mpsc::TryRecvError::Empty) => (),
}
for event in events.iter() {
match event.token() {
STDIN => {
let size = match std::io::stdin().read(&mut buf) {
Ok(0) => return Ok(()),
Ok(size) => size,
Err(_) => return Ok(()),
};
write_stream.write_all(&buf[0..size])?;
}
_ => unreachable!(),
}
}
}
}
}

View File

@@ -1,9 +1,4 @@
mod adb_emulator_device;
mod adb_server;
mod adb_server_device;
mod device_commands;
mod server_commands;
mod commands;
pub use adb_emulator_device::ADBEmulatorDevice;
pub use adb_server::ADBServer;
pub use adb_server_device::ADBServerDevice;

View File

@@ -0,0 +1,133 @@
use std::{
io::{Read, Write},
path::Path,
};
use crate::{
constants::BUFFER_SIZE,
models::{AdbServerCommand, AdbStatResponse, HostFeatures},
ADBDeviceExt, Result, RustADBError,
};
use super::ADBServerDevice;
impl ADBDeviceExt for ADBServerDevice {
fn shell_command<S: ToString, W: Write>(
&mut self,
command: impl IntoIterator<Item = S>,
mut output: W,
) -> Result<()> {
let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2)
&& !supported_features.contains(&HostFeatures::Cmd)
{
return Err(RustADBError::ADBShellNotSupported);
}
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.send_adb_request(AdbServerCommand::ShellCommand(
command
.into_iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" "),
))?;
const BUFFER_SIZE: usize = 4096;
loop {
let mut buffer = [0; BUFFER_SIZE];
match self
.get_transport_mut()
.get_raw_connection()?
.read(&mut buffer)
{
Ok(size) => {
if size == 0 {
return Ok(());
} else {
output.write_all(&buffer[..size])?;
}
}
Err(e) => {
return Err(RustADBError::IOError(e));
}
}
}
}
fn stat(&mut self, remote_path: &str) -> Result<AdbStatResponse> {
self.stat(remote_path)
}
fn shell<R: Read, W: Write + Send + 'static>(
&mut self,
mut reader: R,
mut writer: W,
) -> Result<()> {
let supported_features = self.host_features()?;
if !supported_features.contains(&HostFeatures::ShellV2)
&& !supported_features.contains(&HostFeatures::Cmd)
{
return Err(RustADBError::ADBShellNotSupported);
}
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Shell)?;
let mut read_stream = self.get_transport_mut().get_raw_connection()?.try_clone()?;
let mut write_stream = read_stream.try_clone()?;
// Reading thread, reads response from adb-server
std::thread::spawn(move || -> Result<()> {
loop {
let mut buffer = [0; BUFFER_SIZE];
match read_stream.read(&mut buffer) {
Ok(0) => {
read_stream.shutdown(std::net::Shutdown::Both)?;
return Ok(());
}
Ok(size) => {
writer.write_all(&buffer[..size])?;
writer.flush()?;
}
Err(e) => {
return Err(RustADBError::IOError(e));
}
}
}
});
// Read from given reader (that could be stdin e.g), and write content to server socket
if let Err(e) = std::io::copy(&mut reader, &mut write_stream) {
match e.kind() {
std::io::ErrorKind::BrokenPipe => return Ok(()),
_ => return Err(RustADBError::IOError(e)),
}
}
Ok(())
}
fn pull<A: AsRef<str>, W: Write>(&mut self, source: A, mut output: W) -> Result<()> {
self.pull(source, &mut output)
}
fn reboot(&mut self, reboot_type: crate::RebootType) -> Result<()> {
self.reboot(reboot_type)
}
fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
self.push(stream, path)
}
fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()> {
self.install(apk_path)
}
}

View File

@@ -0,0 +1,25 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Forward socket connection
pub fn forward(&mut self, remote: String, local: String) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial.clone()))?;
self.get_transport_mut()
.proxy_connection(AdbServerCommand::Forward(remote, local), false)
.map(|_| ())
}
/// Remove all previously applied forward rules
pub fn forward_remove_all(&mut self) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial.clone()))?;
self.get_transport_mut()
.proxy_connection(AdbServerCommand::ForwardRemoveAll, false)
.map(|_| ())
}
}

View File

@@ -1,7 +1,12 @@
use std::{io::Read, iter::Map, path::Path, slice::ChunksExact};
use std::{
io::{Read, Seek, Write},
iter::Map,
path::Path,
slice::ChunksExact,
};
use byteorder::{LittleEndian, ReadBytesExt};
use image::{ImageBuffer, Rgba};
use image::{ImageBuffer, ImageFormat, Rgba};
use crate::{models::AdbServerCommand, utils, ADBServerDevice, Result, RustADBError};
@@ -98,13 +103,21 @@ impl TryFrom<[u8; std::mem::size_of::<Self>()]> for FrameBufferInfoV2 {
}
impl ADBServerDevice {
/// Dump framebuffer of this device
/// Big help from source code (https://android.googlesource.com/platform/system/adb/+/refs/heads/main/framebuffer_service.cpp)
/// Dump framebuffer of this device into given ['path']
/// Big help from source code (<https://android.googlesource.com/platform/system/adb/+/refs/heads/main/framebuffer_service.cpp>)
pub fn framebuffer<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
let img = self.framebuffer_inner()?;
Ok(img.save(path.as_ref())?)
}
/// Dump framebuffer of this device and return corresponding bytes.
///
/// Output data format is currently only `PNG`.
pub fn framebuffer_bytes<W: Write + Seek>(&mut self, mut writer: W) -> Result<()> {
let img = self.framebuffer_inner()?;
Ok(img.write_to(&mut writer, ImageFormat::Png)?)
}
/// Inner method requesting framebuffer from Android device
fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>> {
let serial: String = self.identifier.clone();
@@ -170,7 +183,7 @@ impl ADBServerDevice {
.ok_or_else(|| RustADBError::FramebufferConversionError)?,
)
}
v => unimplemented!("Version {} not implemented", v),
v => Err(RustADBError::UnimplementedFramebufferImageVersion(v)),
}
}
}

View File

@@ -0,0 +1,43 @@
use std::{fs::File, io::Read, path::Path};
use crate::{
models::AdbServerCommand, server_device::ADBServerDevice, utils::check_extension_is_apk, Result,
};
impl ADBServerDevice {
/// Install an APK on device
pub fn install<P: AsRef<Path>>(&mut self, apk_path: P) -> Result<()> {
let mut apk_file = File::open(&apk_path)?;
check_extension_is_apk(&apk_path)?;
let file_size = apk_file.metadata()?.len();
let serial: String = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Install(file_size))?;
let mut raw_connection = self.get_transport_mut().get_raw_connection()?;
std::io::copy(&mut apk_file, &mut raw_connection)?;
let mut data = [0; 1024];
let read_amount = self.get_transport().get_raw_connection()?.read(&mut data)?;
match &data[0..read_amount] {
b"Success\n" => {
log::info!(
"APK file {} successfully installed",
apk_path.as_ref().display()
);
Ok(())
}
d => Err(crate::RustADBError::ADBRequestFailed(String::from_utf8(
d.to_vec(),
)?)),
}
}
}

View File

@@ -9,7 +9,7 @@ use std::{
};
impl ADBServerDevice {
/// Lists files in [path] on the device.
/// Lists files in path on the device.
pub fn list<A: AsRef<str>>(&mut self, path: A) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
@@ -70,7 +70,7 @@ impl ADBServerDevice {
"DONE" => {
return Ok(());
}
x => println!("Unknown response {}", x),
x => log::error!("Got an unknown response {}", x),
}
}
}

View File

@@ -0,0 +1,56 @@
use std::io::{self, Write};
use crate::{ADBDeviceExt, ADBServerDevice, Result};
struct LogFilter<W: Write> {
writer: W,
buffer: Vec<u8>,
}
impl<W: Write> LogFilter<W> {
pub fn new(writer: W) -> Self {
LogFilter {
writer,
buffer: Vec::new(),
}
}
fn should_write(&self, _line: &[u8]) -> bool {
// Can implement checks here to ensure if logs have to be written
true
}
}
impl<W: Write> Write for LogFilter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.buffer.extend_from_slice(buf);
let buf_clone = self.buffer.clone();
let mut lines = buf_clone.split_inclusive(|&byte| byte == b'\n').peekable();
while let Some(line) = lines.next() {
if lines.peek().is_some() {
if self.should_write(line) {
self.writer.write_all(line)?;
}
} else {
// This is the last (unfinished) element, we keep it for next round
self.buffer = line.to_vec();
break;
}
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
impl ADBServerDevice {
/// Get logs from device
pub fn get_logs<W: Write>(&mut self, output: W) -> Result<()> {
self.shell_command(["exec logcat"], LogFilter::new(output))
}
}

View File

@@ -1,9 +1,15 @@
mod forward;
mod framebuffer;
mod host_features;
mod install;
mod list;
mod logcat;
mod reboot;
mod reconnect;
mod recv;
mod reverse;
mod send;
mod shell;
mod stat;
mod tcpip;
mod transport;
mod usb;

View File

@@ -0,0 +1,14 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Reconnect device
pub fn reconnect(&mut self) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.proxy_connection(AdbServerCommand::Reconnect, false)
.map(|_| ())
}
}

View File

@@ -0,0 +1,111 @@
use crate::{
constants,
models::{AdbServerCommand, SyncCommand},
ADBServerDevice, Result,
};
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::{BufReader, BufWriter, Read, Write};
/// Internal structure wrapping a [std::io::Read] and hiding underlying protocol logic.
struct ADBRecvCommandReader<R: Read> {
inner: R,
remaining_data_bytes_to_read: usize,
}
impl<R: Read> ADBRecvCommandReader<R> {
pub fn new(inner: R) -> Self {
Self {
inner,
remaining_data_bytes_to_read: 0,
}
}
}
impl<R: Read> Read for ADBRecvCommandReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
// In case of a "DATA" header, we may not have enough space in `buf` to fill it with "length" bytes coming from device.
// `remaining_data_bytes_to_read` represents how many bytes are still left to read before receiving another header.
if self.remaining_data_bytes_to_read == 0 {
let mut header = [0_u8; 4];
self.inner.read_exact(&mut header)?;
match &header[..] {
b"DATA" => {
let length = self.inner.read_u32::<LittleEndian>()? as usize;
let effective_read = self.inner.read(&mut buf[0..length])?;
self.remaining_data_bytes_to_read = length - effective_read;
Ok(effective_read)
}
b"DONE" => Ok(0),
b"FAIL" => {
let length = self.inner.read_u32::<LittleEndian>()? as usize;
let mut error_msg = vec![0; length];
self.inner.read_exact(&mut error_msg)?;
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"ADB request failed: {}",
String::from_utf8_lossy(&error_msg)
),
))
}
_ => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Unknown response from device {:#?}", header),
)),
}
} else {
// Computing minimum to ensure to stop reading before next header...
let data_to_read = std::cmp::min(self.remaining_data_bytes_to_read, buf.len());
self.inner.read_exact(&mut buf[..data_to_read])?;
self.remaining_data_bytes_to_read -= self.remaining_data_bytes_to_read;
Ok(data_to_read)
}
}
}
impl ADBServerDevice {
/// Receives path to stream from the device.
pub fn pull<A: AsRef<str>>(&mut self, path: A, stream: &mut dyn Write) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
// Set device in SYNC mode
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Sync)?;
// Send a recv command
self.get_transport_mut()
.send_sync_request(SyncCommand::Recv)?;
self.handle_recv_command(path, stream)
}
fn handle_recv_command<S: AsRef<str>>(
&mut self,
from: S,
output: &mut dyn Write,
) -> Result<()> {
let mut raw_connection = self.get_transport().get_raw_connection()?;
let from_as_bytes = from.as_ref().as_bytes();
let mut buffer = Vec::with_capacity(4 + from_as_bytes.len());
buffer.extend_from_slice(&(from.as_ref().len() as u32).to_le_bytes());
buffer.extend_from_slice(from_as_bytes);
raw_connection.write_all(&buffer)?;
let reader = ADBRecvCommandReader::new(raw_connection);
std::io::copy(
&mut BufReader::with_capacity(constants::BUFFER_SIZE, reader),
&mut BufWriter::with_capacity(constants::BUFFER_SIZE, output),
)?;
// Connection should've been left in SYNC mode by now
Ok(())
}
}

View File

@@ -0,0 +1,25 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Reverse socket connection
pub fn reverse(&mut self, remote: String, local: String) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.proxy_connection(AdbServerCommand::Reverse(remote, local), false)
.map(|_| ())
}
/// Remove all reverse rules
pub fn reverse_remove_all(&mut self) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial.clone()))?;
self.get_transport_mut()
.proxy_connection(AdbServerCommand::ReverseRemoveAll, false)
.map(|_| ())
}
}

View File

@@ -0,0 +1,121 @@
use crate::{
constants,
models::{AdbRequestStatus, AdbServerCommand, SyncCommand},
ADBServerDevice, Result, RustADBError,
};
use std::{
convert::TryInto,
io::{BufReader, BufWriter, Read, Write},
str::{self, FromStr},
time::SystemTime,
};
/// Internal structure wrapping a [std::io::Write] and hiding underlying protocol logic.
struct ADBSendCommandWriter<W: Write> {
inner: W,
}
impl<W: Write> ADBSendCommandWriter<W> {
pub fn new(inner: W) -> Self {
ADBSendCommandWriter { inner }
}
}
impl<W: Write> Write for ADBSendCommandWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let chunk_len = buf.len() as u32;
// 8 = "DATA".len() + sizeof(u32)
let mut buffer = Vec::with_capacity(8 + buf.len());
buffer.extend_from_slice(b"DATA");
buffer.extend_from_slice(&chunk_len.to_le_bytes());
buffer.extend_from_slice(buf);
self.inner.write_all(&buffer)?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
impl ADBServerDevice {
/// Send stream to path on the device.
pub fn push<R: Read, A: AsRef<str>>(&mut self, stream: R, path: A) -> Result<()> {
log::info!("Sending data to {}", path.as_ref());
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
// Set device in SYNC mode
self.get_transport_mut()
.send_adb_request(AdbServerCommand::Sync)?;
// Send a send command
self.get_transport_mut()
.send_sync_request(SyncCommand::Send)?;
self.handle_send_command(stream, path)
}
fn handle_send_command<R: Read, S: AsRef<str>>(&mut self, input: R, to: S) -> Result<()> {
// Append the permission flags to the filename
let to = to.as_ref().to_string() + ",0777";
let mut raw_connection = self.get_transport_mut().get_raw_connection()?;
// The name of the command is already sent by get_transport()?.send_sync_request
let to_as_bytes = to.as_bytes();
let mut buffer = Vec::with_capacity(4 + to_as_bytes.len());
buffer.extend_from_slice(&(to.len() as u32).to_le_bytes());
buffer.extend_from_slice(to_as_bytes);
raw_connection.write_all(&buffer)?;
let writer = ADBSendCommandWriter::new(raw_connection);
std::io::copy(
&mut BufReader::with_capacity(constants::BUFFER_SIZE, input),
&mut BufWriter::with_capacity(constants::BUFFER_SIZE, writer),
)?;
// Copy is finished, we can now notify as finished
// Have to send DONE + file mtime
let last_modified = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n,
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
};
let mut done_buffer = Vec::with_capacity(8);
done_buffer.extend_from_slice(b"DONE");
done_buffer.extend_from_slice(&last_modified.as_secs().to_le_bytes());
raw_connection.write_all(&done_buffer)?;
// We expect 'OKAY' response from this
let mut request_status = [0; 4];
raw_connection.read_exact(&mut request_status)?;
match AdbRequestStatus::from_str(str::from_utf8(&request_status)?)? {
AdbRequestStatus::Fail => {
// We can keep reading to get further details
let length = self.get_transport_mut().get_body_length()?;
let mut body = vec![
0;
length
.try_into()
.map_err(|_| RustADBError::ConversionError)?
];
if length > 0 {
self.get_transport()
.get_raw_connection()?
.read_exact(&mut body)?;
}
Err(RustADBError::ADBRequestFailed(String::from_utf8(body)?))
}
AdbRequestStatus::Okay => Ok(()),
}
}
}

View File

@@ -1,51 +1,12 @@
use std::{
fmt::Display,
io::{Read, Write},
time::{Duration, UNIX_EPOCH},
};
use std::io::{Read, Write};
use byteorder::{ByteOrder, LittleEndian};
use chrono::{DateTime, Utc};
use crate::{
models::{AdbServerCommand, SyncCommand},
models::{AdbServerCommand, AdbStatResponse, SyncCommand},
ADBServerDevice, Result, RustADBError,
};
#[derive(Debug)]
pub struct AdbStatResponse {
pub file_perm: u32,
pub file_size: u32,
pub mod_time: u32,
}
impl From<[u8; 12]> for AdbStatResponse {
fn from(value: [u8; 12]) -> Self {
Self {
file_perm: LittleEndian::read_u32(&value[0..4]),
file_size: LittleEndian::read_u32(&value[4..8]),
mod_time: LittleEndian::read_u32(&value[8..]),
}
}
}
impl Display for AdbStatResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let d = UNIX_EPOCH + Duration::from_secs(self.mod_time.into());
// Create DateTime from SystemTime
let datetime = DateTime::<Utc>::from(d);
writeln!(f, "File permissions: {}", self.file_perm)?;
writeln!(f, "File size: {} bytes", self.file_size)?;
write!(
f,
"Modification time: {}",
datetime.format("%Y-%m-%d %H:%M:%S.%f %Z")
)?;
Ok(())
}
}
impl ADBServerDevice {
fn handle_stat_command<S: AsRef<str>>(&mut self, path: S) -> Result<AdbStatResponse> {
let mut len_buf = [0_u8; 4];
@@ -80,7 +41,7 @@ impl ADBServerDevice {
}
}
/// Stat file given as [path] on the device.
/// Stat file given as path on the device.
pub fn stat<A: AsRef<str>>(&mut self, path: A) -> Result<AdbStatResponse> {
let serial = self.identifier.clone();
self.connect()?

View File

@@ -0,0 +1,14 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Set adb daemon to tcp/ip mode
pub fn tcpip(&mut self, port: u16) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.proxy_connection(AdbServerCommand::TcpIp(port), false)
.map(|_| ())
}
}

View File

@@ -0,0 +1,14 @@
use crate::{models::AdbServerCommand, ADBServerDevice, Result};
impl ADBServerDevice {
/// Set adb daemon to usb mode
pub fn usb(&mut self) -> Result<()> {
let serial = self.identifier.clone();
self.connect()?
.send_adb_request(AdbServerCommand::TransportSerial(serial))?;
self.get_transport_mut()
.proxy_connection(AdbServerCommand::Usb, false)
.map(|_| ())
}
}

View File

@@ -0,0 +1,5 @@
mod adb_server_device;
mod adb_server_device_commands;
mod commands;
pub use adb_server_device::ADBServerDevice;

View File

@@ -1,6 +1,11 @@
mod tcp_emulator_transport;
mod tcp_server_transport;
mod transport_trait;
mod tcp_transport;
mod traits;
mod usb_transport;
pub use tcp_emulator_transport::TCPEmulatorTransport;
pub use tcp_server_transport::TCPServerTransport;
pub use transport_trait::ADBTransport;
pub use tcp_transport::TcpTransport;
pub use traits::{ADBMessageTransport, ADBTransport};
pub use usb_transport::USBTransport;

View File

@@ -38,7 +38,7 @@ impl TCPEmulatorTransport {
pub fn get_authentication_token(&mut self) -> Result<String> {
let home = match my_home()? {
Some(home) => home,
None => todo!(),
None => return Err(RustADBError::NoHomeDirectory),
};
let mut f = File::open(home.join(".emulator_console_auth_token"))?;
@@ -91,6 +91,7 @@ impl ADBTransport for TCPEmulatorTransport {
fn disconnect(&mut self) -> Result<()> {
if let Some(conn) = &mut self.tcp_stream {
conn.shutdown(std::net::Shutdown::Both)?;
log::trace!("Disconnected from {}", conn.peer_addr()?);
}
Ok(())
@@ -101,6 +102,8 @@ impl ADBTransport for TCPEmulatorTransport {
if self.tcp_stream.is_none() {
let stream = TcpStream::connect(self.socket_addr)?;
log::trace!("Successfully connected to {}", self.socket_addr);
self.tcp_stream = Some(stream.try_clone()?);
let mut reader = BufReader::new(stream);
@@ -115,6 +118,8 @@ impl ADBTransport for TCPEmulatorTransport {
}
self.authenticate()?;
log::trace!("Authentication successful");
}
Ok(())

View File

@@ -143,6 +143,7 @@ impl ADBTransport for TCPServerTransport {
fn disconnect(&mut self) -> Result<()> {
if let Some(conn) = &mut self.tcp_stream {
conn.shutdown(std::net::Shutdown::Both)?;
log::trace!("Disconnected from {}", conn.peer_addr()?);
}
Ok(())
@@ -153,7 +154,10 @@ impl ADBTransport for TCPServerTransport {
// Ignoring underlying error, we will recreate a new connection
let _ = previous.shutdown(std::net::Shutdown::Both);
}
self.tcp_stream = Some(TcpStream::connect(self.socket_addr)?);
let tcp_stream = TcpStream::connect(self.socket_addr)?;
tcp_stream.set_nodelay(true)?;
self.tcp_stream = Some(tcp_stream);
log::trace!("Successfully connected to {}", self.socket_addr);
Ok(())
}

View File

@@ -0,0 +1,344 @@
use rcgen::{CertificateParams, KeyPair, PKCS_RSA_SHA256};
use rustls::{
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
pki_types::{pem::PemObject, CertificateDer, PrivatePkcs8KeyDer},
ClientConfig, ClientConnection, KeyLogFile, SignatureScheme, StreamOwned,
};
use super::{ADBMessageTransport, ADBTransport};
use crate::{
device::{
get_default_adb_key_path, ADBTransportMessage, ADBTransportMessageHeader, MessageCommand,
},
Result, RustADBError,
};
use std::{
fs::read_to_string,
io::{Read, Write},
net::{Shutdown, SocketAddr, TcpStream},
ops::{Deref, DerefMut},
path::PathBuf,
sync::{Arc, Mutex},
time::Duration,
};
#[derive(Debug)]
enum CurrentConnection {
Tcp(TcpStream),
Tls(Box<StreamOwned<ClientConnection, TcpStream>>),
}
impl CurrentConnection {
fn set_read_timeout(&self, read_timeout: Duration) -> Result<()> {
match self {
CurrentConnection::Tcp(tcp_stream) => {
Ok(tcp_stream.set_read_timeout(Some(read_timeout))?)
}
CurrentConnection::Tls(stream_owned) => {
Ok(stream_owned.sock.set_read_timeout(Some(read_timeout))?)
}
}
}
fn set_write_timeout(&self, write_timeout: Duration) -> Result<()> {
match self {
CurrentConnection::Tcp(tcp_stream) => {
Ok(tcp_stream.set_write_timeout(Some(write_timeout))?)
}
CurrentConnection::Tls(stream_owned) => {
Ok(stream_owned.sock.set_write_timeout(Some(write_timeout))?)
}
}
}
}
impl Read for CurrentConnection {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
CurrentConnection::Tcp(tcp_stream) => tcp_stream.read(buf),
CurrentConnection::Tls(tls_conn) => tls_conn.read(buf),
}
}
}
impl Write for CurrentConnection {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match self {
CurrentConnection::Tcp(tcp_stream) => tcp_stream.write(buf),
CurrentConnection::Tls(tls_conn) => tls_conn.write(buf),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match self {
CurrentConnection::Tcp(tcp_stream) => tcp_stream.flush(),
CurrentConnection::Tls(tls_conn) => tls_conn.flush(),
}
}
}
/// Transport running on USB
#[derive(Clone, Debug)]
pub struct TcpTransport {
address: SocketAddr,
current_connection: Option<Arc<Mutex<CurrentConnection>>>,
private_key_path: PathBuf,
}
fn certificate_from_pk(key_pair: &KeyPair) -> Result<Vec<CertificateDer<'static>>> {
let certificate_params = CertificateParams::default();
let certificate = certificate_params.self_signed(key_pair)?;
Ok(vec![certificate.der().to_owned()])
}
impl TcpTransport {
/// Instantiate a new [`TcpTransport`]
pub fn new(address: SocketAddr) -> Result<Self> {
Self::new_with_custom_private_key(address, get_default_adb_key_path()?)
}
/// Instantiate a new [`TcpTransport`] using a given private key
pub fn new_with_custom_private_key(
address: SocketAddr,
private_key_path: PathBuf,
) -> Result<Self> {
Ok(Self {
address,
current_connection: None,
private_key_path,
})
}
fn get_current_connection(&mut self) -> Result<Arc<Mutex<CurrentConnection>>> {
self.current_connection
.as_ref()
.ok_or(RustADBError::IOError(std::io::Error::new(
std::io::ErrorKind::NotConnected,
"not connected",
)))
.cloned()
}
pub(crate) fn upgrade_connection(&mut self) -> Result<()> {
let current_connection = match self.current_connection.clone() {
Some(current_connection) => current_connection,
None => {
return Err(RustADBError::UpgradeError(
"cannot upgrade a non-existing connection...".into(),
))
}
};
{
let mut current_conn_locked = current_connection.lock()?;
match current_conn_locked.deref() {
CurrentConnection::Tcp(tcp_stream) => {
// TODO: Check if we cannot be more precise
let pk_content = read_to_string(&self.private_key_path)?;
let key_pair =
KeyPair::from_pkcs8_pem_and_sign_algo(&pk_content, &PKCS_RSA_SHA256)?;
let certificate = certificate_from_pk(&key_pair)?;
let private_key = PrivatePkcs8KeyDer::from_pem_file(&self.private_key_path)?;
let mut client_config = ClientConfig::builder()
.dangerous()
.with_custom_certificate_verifier(Arc::new(NoCertificateVerification {}))
.with_client_auth_cert(certificate, private_key.into())?;
client_config.key_log = Arc::new(KeyLogFile::new());
let rc_config = Arc::new(client_config);
let example_com = self.address.ip().into();
let conn = ClientConnection::new(rc_config, example_com)?;
let owned = tcp_stream.try_clone()?;
let client = StreamOwned::new(conn, owned);
// Update current connection state to now use TLS protocol
*current_conn_locked = CurrentConnection::Tls(Box::new(client));
}
CurrentConnection::Tls(_) => {
return Err(RustADBError::UpgradeError(
"cannot upgrade a TLS connection...".into(),
))
}
}
}
let message = self.read_message()?;
match message.header().command() {
MessageCommand::Cnxn => {
let device_infos = String::from_utf8(message.into_payload())?;
log::debug!("received device info: {device_infos}");
Ok(())
}
c => Err(RustADBError::ADBRequestFailed(format!(
"Wrong command received {}",
c
))),
}
}
}
impl ADBTransport for TcpTransport {
fn connect(&mut self) -> Result<()> {
let stream = TcpStream::connect(self.address)?;
self.current_connection = Some(Arc::new(Mutex::new(CurrentConnection::Tcp(stream))));
Ok(())
}
fn disconnect(&mut self) -> Result<()> {
log::debug!("disconnecting...");
if let Some(current_connection) = &self.current_connection {
let mut lock = current_connection.lock()?;
match lock.deref_mut() {
CurrentConnection::Tcp(tcp_stream) => {
let _ = tcp_stream.shutdown(Shutdown::Both);
}
CurrentConnection::Tls(tls_conn) => {
tls_conn.conn.send_close_notify();
let _ = tls_conn.sock.shutdown(Shutdown::Both);
}
}
}
Ok(())
}
}
impl ADBMessageTransport for TcpTransport {
fn read_message_with_timeout(
&mut self,
read_timeout: std::time::Duration,
) -> Result<crate::device::ADBTransportMessage> {
let raw_connection_lock = self.get_current_connection()?;
let mut raw_connection = raw_connection_lock.lock()?;
raw_connection.set_read_timeout(read_timeout)?;
let mut data = [0; 24];
let mut total_read = 0;
loop {
total_read += raw_connection.read(&mut data[total_read..])?;
if total_read == data.len() {
break;
}
}
let header = ADBTransportMessageHeader::try_from(data)?;
if header.data_length() != 0 {
let mut msg_data = vec![0_u8; header.data_length() as usize];
let mut total_read = 0;
loop {
total_read += raw_connection.read(&mut msg_data[total_read..])?;
if total_read == msg_data.capacity() {
break;
}
}
let message = ADBTransportMessage::from_header_and_payload(header, msg_data);
// Check message integrity
if !message.check_message_integrity() {
return Err(RustADBError::InvalidIntegrity(
ADBTransportMessageHeader::compute_crc32(message.payload()),
message.header().data_crc32(),
));
}
return Ok(message);
}
Ok(ADBTransportMessage::from_header_and_payload(header, vec![]))
}
fn write_message_with_timeout(
&mut self,
message: ADBTransportMessage,
write_timeout: Duration,
) -> Result<()> {
let message_bytes = message.header().as_bytes()?;
let raw_connection_lock = self.get_current_connection()?;
let mut raw_connection = raw_connection_lock.lock()?;
raw_connection.set_write_timeout(write_timeout)?;
let mut total_written = 0;
loop {
total_written += raw_connection.write(&message_bytes[total_written..])?;
if total_written == message_bytes.len() {
raw_connection.flush()?;
break;
}
}
let payload = message.into_payload();
if !payload.is_empty() {
let mut total_written = 0;
loop {
total_written += raw_connection.write(&payload[total_written..])?;
if total_written == payload.len() {
raw_connection.flush()?;
break;
}
}
}
Ok(())
}
}
#[derive(Debug)]
struct NoCertificateVerification;
impl ServerCertVerifier for NoCertificateVerification {
fn verify_server_cert(
&self,
_end_entity: &rustls::pki_types::CertificateDer<'_>,
_intermediates: &[rustls::pki_types::CertificateDer<'_>],
_server_name: &rustls::pki_types::ServerName<'_>,
_ocsp_response: &[u8],
_now: rustls::pki_types::UnixTime,
) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &rustls::pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &rustls::pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
vec![
SignatureScheme::RSA_PKCS1_SHA1,
SignatureScheme::ECDSA_SHA1_Legacy,
SignatureScheme::RSA_PKCS1_SHA256,
SignatureScheme::ECDSA_NISTP256_SHA256,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::ECDSA_NISTP384_SHA384,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::ECDSA_NISTP521_SHA512,
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA512,
SignatureScheme::ED25519,
SignatureScheme::ED448,
]
}
}

View File

@@ -0,0 +1,30 @@
use std::time::Duration;
use super::ADBTransport;
use crate::{device::ADBTransportMessage, Result};
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(u64::MAX);
const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(2);
/// Trait representing a transport able to read and write messages.
pub trait ADBMessageTransport: ADBTransport + Clone + Send + 'static {
/// Read a message using given timeout on the underlying transport
fn read_message_with_timeout(&mut self, read_timeout: Duration) -> Result<ADBTransportMessage>;
/// Read data to underlying connection, using default timeout
fn read_message(&mut self) -> Result<ADBTransportMessage> {
self.read_message_with_timeout(DEFAULT_READ_TIMEOUT)
}
/// Write a message using given timeout on the underlying transport
fn write_message_with_timeout(
&mut self,
message: ADBTransportMessage,
write_timeout: Duration,
) -> Result<()>;
/// Write data to underlying connection, using default timeout
fn write_message(&mut self, message: ADBTransportMessage) -> Result<()> {
self.write_message_with_timeout(message, DEFAULT_WRITE_TIMEOUT)
}
}

View File

@@ -0,0 +1,10 @@
use crate::Result;
/// Trait representing a transport usable by ADB protocol.
pub trait ADBTransport {
/// Initializes the connection to this transport.
fn connect(&mut self) -> Result<()>;
/// Shuts down the connection to this transport.
fn disconnect(&mut self) -> Result<()>;
}

View File

@@ -0,0 +1,5 @@
mod adb_message_transport;
mod adb_transport;
pub use adb_message_transport::ADBMessageTransport;
pub use adb_transport::ADBTransport;

View File

@@ -1,10 +0,0 @@
use crate::Result;
/// Trait representing a transport
pub trait ADBTransport {
/// Initializes the connection
fn connect(&mut self) -> Result<()>;
/// Shuts down the connection
fn disconnect(&mut self) -> Result<()>;
}

View File

@@ -0,0 +1,232 @@
use std::{sync::Arc, time::Duration};
use rusb::{
constants::LIBUSB_CLASS_VENDOR_SPEC, Device, DeviceHandle, Direction, GlobalContext,
TransferType,
};
use super::{ADBMessageTransport, ADBTransport};
use crate::{
device::{ADBTransportMessage, ADBTransportMessageHeader, MessageCommand},
Result, RustADBError,
};
#[derive(Debug)]
struct Endpoint {
iface: u8,
address: u8,
}
/// Transport running on USB
#[derive(Debug, Clone)]
pub struct USBTransport {
device: Device<GlobalContext>,
handle: Option<Arc<DeviceHandle<GlobalContext>>>,
}
impl USBTransport {
/// Instantiate a new [`USBTransport`].
/// Only the first device with given vendor_id and product_id is returned.
pub fn new(vendor_id: u16, product_id: u16) -> Result<Self> {
for device in rusb::devices()?.iter() {
if let Ok(descriptor) = device.device_descriptor() {
if descriptor.vendor_id() == vendor_id && descriptor.product_id() == product_id {
return Ok(Self::new_from_device(device));
}
}
}
Err(RustADBError::DeviceNotFound(format!(
"cannot find USB device with vendor_id={} and product_id={}",
vendor_id, product_id
)))
}
/// Instantiate a new [`USBTransport`] from a [`rusb::Device`].
///
/// Devices can be enumerated using [`rusb::devices()`] and then filtered out to get desired device.
pub fn new_from_device(rusb_device: rusb::Device<GlobalContext>) -> Self {
Self {
device: rusb_device,
handle: None,
}
}
pub(crate) fn get_raw_connection(&self) -> Result<Arc<DeviceHandle<GlobalContext>>> {
self.handle
.as_ref()
.ok_or(RustADBError::IOError(std::io::Error::new(
std::io::ErrorKind::NotConnected,
"not connected",
)))
.cloned()
}
fn configure_endpoint(handle: &DeviceHandle<GlobalContext>, endpoint: &Endpoint) -> Result<()> {
handle.claim_interface(endpoint.iface)?;
Ok(())
}
fn find_readable_endpoint(&self) -> Result<Endpoint> {
let handle = self.get_raw_connection()?;
for n in 0..handle.device().device_descriptor()?.num_configurations() {
let config_desc = match handle.device().config_descriptor(n) {
Ok(c) => c,
Err(_) => continue,
};
for interface in config_desc.interfaces() {
for interface_desc in interface.descriptors() {
for endpoint_desc in interface_desc.endpoint_descriptors() {
if endpoint_desc.direction() == Direction::In
&& endpoint_desc.transfer_type() == TransferType::Bulk
&& interface_desc.class_code() == LIBUSB_CLASS_VENDOR_SPEC
&& interface_desc.sub_class_code() == 0x42
&& interface_desc.protocol_code() == 0x01
{
return Ok(Endpoint {
iface: interface_desc.interface_number(),
address: endpoint_desc.address(),
});
}
}
}
}
}
Err(RustADBError::USBNoDescriptorFound)
}
fn find_writable_endpoint(&self) -> Result<Endpoint> {
let handle = self.get_raw_connection()?;
for n in 0..handle.device().device_descriptor()?.num_configurations() {
let config_desc = match handle.device().config_descriptor(n) {
Ok(c) => c,
Err(_) => continue,
};
for interface in config_desc.interfaces() {
for interface_desc in interface.descriptors() {
for endpoint_desc in interface_desc.endpoint_descriptors() {
if endpoint_desc.direction() == Direction::Out
&& endpoint_desc.transfer_type() == TransferType::Bulk
&& interface_desc.class_code() == LIBUSB_CLASS_VENDOR_SPEC
&& interface_desc.sub_class_code() == 0x42
&& interface_desc.protocol_code() == 0x01
{
return Ok(Endpoint {
iface: interface_desc.interface_number(),
address: endpoint_desc.address(),
});
}
}
}
}
}
Err(RustADBError::USBNoDescriptorFound)
}
}
impl ADBTransport for USBTransport {
fn connect(&mut self) -> crate::Result<()> {
self.handle = Some(Arc::new(self.device.open()?));
Ok(())
}
fn disconnect(&mut self) -> crate::Result<()> {
let message = ADBTransportMessage::new(MessageCommand::Clse, 0, 0, "".into());
self.write_message(message)
}
}
impl ADBMessageTransport for USBTransport {
fn write_message_with_timeout(
&mut self,
message: ADBTransportMessage,
timeout: Duration,
) -> Result<()> {
let endpoint = self.find_writable_endpoint()?;
let handle = self.get_raw_connection()?;
if let Ok(true) = handle.kernel_driver_active(endpoint.iface) {
handle.detach_kernel_driver(endpoint.iface)?;
}
Self::configure_endpoint(&handle, &endpoint)?;
let message_bytes = message.header().as_bytes()?;
let mut total_written = 0;
loop {
total_written +=
handle.write_bulk(endpoint.address, &message_bytes[total_written..], timeout)?;
if total_written == message_bytes.len() {
break;
}
}
let payload = message.into_payload();
if !payload.is_empty() {
let mut total_written = 0;
loop {
total_written +=
handle.write_bulk(endpoint.address, &payload[total_written..], timeout)?;
if total_written == payload.len() {
break;
}
}
}
Ok(())
}
fn read_message_with_timeout(&mut self, timeout: Duration) -> Result<ADBTransportMessage> {
let endpoint = self.find_readable_endpoint()?;
let handle = self.get_raw_connection()?;
if let Ok(true) = handle.kernel_driver_active(endpoint.iface) {
handle.detach_kernel_driver(endpoint.iface)?;
}
Self::configure_endpoint(&handle, &endpoint)?;
let mut data = [0; 24];
let mut total_read = 0;
loop {
total_read += handle.read_bulk(endpoint.address, &mut data[total_read..], timeout)?;
if total_read == data.len() {
break;
}
}
let header = ADBTransportMessageHeader::try_from(data)?;
log::trace!("received header {header:?}");
if header.data_length() != 0 {
let mut msg_data = vec![0_u8; header.data_length() as usize];
let mut total_read = 0;
loop {
total_read +=
handle.read_bulk(endpoint.address, &mut msg_data[total_read..], timeout)?;
if total_read == msg_data.capacity() {
break;
}
}
let message = ADBTransportMessage::from_header_and_payload(header, msg_data);
// Check message integrity
if !message.check_message_integrity() {
return Err(RustADBError::InvalidIntegrity(
ADBTransportMessageHeader::compute_crc32(message.payload()),
message.header().data_crc32(),
));
}
return Ok(message);
}
Ok(ADBTransportMessage::from_header_and_payload(header, vec![]))
}
}

View File

@@ -1,3 +1,5 @@
use std::{ffi::OsStr, path::Path};
use crate::{Result, RustADBError};
pub fn u32_from_le(value: &[u8]) -> Result<u32> {
@@ -7,3 +9,16 @@ pub fn u32_from_le(value: &[u8]) -> Result<u32> {
.map_err(|_| RustADBError::ConversionError)?,
))
}
pub fn check_extension_is_apk<P: AsRef<Path>>(path: P) -> Result<()> {
if let Some(extension) = path.as_ref().extension() {
if ![OsStr::new("apk")].contains(&extension) {
return Err(RustADBError::WrongFileExtension(format!(
"{} is not an APK file",
extension.to_string_lossy()
)));
}
}
Ok(())
}

Some files were not shown because too many files have changed in this diff Show More