Full Code of MuntashirAkon/libadb-android for AI

master c849886ebc6d cached
58 files
300.2 KB
75.0k tokens
271 symbols
1 requests
Download .txt
Showing preview only (320K chars total). Download the full file or copy to clipboard to get everything.
Repository: MuntashirAkon/libadb-android
Branch: master
Commit: c849886ebc6d
Files: 58
Total size: 300.2 KB

Directory structure:
gitextract_bnja9n_o/

├── .gitignore
├── COPYING
├── LICENSES/
│   ├── Apache-2.0
│   ├── BSD-3-Clause
│   ├── GPL-3.0-or-later
│   └── MIT
├── README.md
├── SERVICES.md
├── app/
│   ├── .gitignore
│   ├── build.gradle
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── io/
│           │       └── github/
│           │           └── muntashirakon/
│           │               └── adb/
│           │                   └── testapp/
│           │                       ├── AdbConnectionManager.java
│           │                       ├── App.java
│           │                       ├── MainActivity.java
│           │                       └── MainViewModel.java
│           └── res/
│               ├── drawable/
│               │   ├── ic_add_link.xml
│               │   ├── ic_launcher_background.xml
│               │   ├── ic_link.xml
│               │   └── ic_link_off.xml
│               ├── drawable-v24/
│               │   └── ic_launcher_foreground.xml
│               ├── layout/
│               │   ├── activity_main.xml
│               │   └── dialog_input.xml
│               ├── menu/
│               │   └── actions_main.xml
│               ├── mipmap-anydpi-v26/
│               │   ├── ic_launcher.xml
│               │   └── ic_launcher_round.xml
│               └── values/
│                   └── strings.xml
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── libadb/
│   ├── .gitignore
│   ├── build.gradle
│   └── src/
│       ├── main/
│       │   ├── AndroidManifest.xml
│       │   └── java/
│       │       └── io/
│       │           └── github/
│       │               └── muntashirakon/
│       │                   └── adb/
│       │                       ├── AbsAdbConnectionManager.java
│       │                       ├── AdbAuthenticationFailedException.java
│       │                       ├── AdbConnection.java
│       │                       ├── AdbInputStream.java
│       │                       ├── AdbOutputStream.java
│       │                       ├── AdbPairingRequiredException.java
│       │                       ├── AdbProtocol.java
│       │                       ├── AdbStream.java
│       │                       ├── AndroidPubkey.java
│       │                       ├── ByteArrayNoThrowOutputStream.java
│       │                       ├── KeyPair.java
│       │                       ├── LocalServices.java
│       │                       ├── PRNGFixes.java
│       │                       ├── PairingAuthCtx.java
│       │                       ├── PairingConnectionCtx.java
│       │                       ├── SslUtils.java
│       │                       ├── StringCompat.java
│       │                       └── android/
│       │                           ├── AdbMdns.java
│       │                           ├── AndroidUtils.java
│       │                           └── package.html
│       └── test/
│           └── java/
│               └── io/
│                   └── github/
│                       └── muntashirakon/
│                           └── adb/
│                               └── AndroidPubkeyTest.java
└── settings.gradle

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
.idea
.gradle
.DS_Store
/build
local.properties

================================================
FILE: COPYING
================================================
LibADB Android is provided under:

	SPDX-License-Identifier: GPL-3.0-or-later or Apache-2.0

Being under the terms of the GNU General Public License version 3 or
later, according with:

	LICENSES/GPL-3.0-or-later

or Apache License, Version 2.0, according with:

	LICENSES/Apache-2.0

In addition, other licenses may also apply. Please navigate to:

	LICENSES/

to see all the licenses used in this project.

All contributions to the LibADB Android are subject to this COPYING
file.


================================================
FILE: LICENSES/Apache-2.0
================================================
Valid-License-Identifier: Apache-2.0
SPDX-URL: https://spdx.org/licenses/Apache-2.0.html
Usage-Guide:
  To use the Apache License version 2.0 put the following SPDX tag/value
  pair into a comment according to the placement guidelines in the
  licensing rules documentation:
    SPDX-License-Identifier: Apache-2.0
  Do NOT use this license unless the files are copied from another work
  under the same license. In such cases, use "AND GPL-3.0-or-later" so
  that your contributions are under GPL-3.0+ license.
License-Text:

Apache License

Version 2.0, January 2004

http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the
copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other
entities that control, are controlled by, or are under common control with
that entity. For the purposes of this definition, "control" means (i) the
power, direct or indirect, to cause the direction or management of such
entity, whether by contract or otherwise, or (ii) ownership of fifty
percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation source,
and configuration files.

"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled
object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that
is included in or attached to the work (an example is provided in the
Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial
revisions, annotations, elaborations, or other modifications represent, as
a whole, an original work of authorship. For the purposes of this License,
Derivative Works shall not include works that remain separable from, or
merely link (or bind by name) to the interfaces of, the Work and Derivative
Works thereof.

"Contribution" shall mean any work of authorship, including the original
version of the Work and any modifications or additions to that Work or
Derivative Works thereof, that is intentionally submitted to Licensor for
inclusion in the Work by the copyright owner or by an individual or Legal
Entity authorized to submit on behalf of the copyright owner. For the
purposes of this definition, "submitted" means any form of electronic,
verbal, or written communication sent to the Licensor or its
representatives, including but not limited to communication on electronic
mailing lists, source code control systems, and issue tracking systems that
are managed by, or on behalf of, the Licensor for the purpose of discussing
and improving the Work, but excluding communication that is conspicuously
marked or otherwise designated in writing by the copyright owner as "Not a
Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on
behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of this
   License, each Contributor hereby grants to You a perpetual, worldwide,
   non-exclusive, no-charge, royalty-free, irrevocable copyright license to
   reproduce, prepare Derivative Works of, publicly display, publicly
   perform, sublicense, and distribute the Work and such Derivative Works
   in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of this
   License, each Contributor hereby grants to You a perpetual, worldwide,
   non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
   this section) patent license to make, have made, use, offer to sell,
   sell, import, and otherwise transfer the Work, where such license
   applies only to those patent claims licensable by such Contributor that
   are necessarily infringed by their Contribution(s) alone or by
   combination of their Contribution(s) with the Work to which such
   Contribution(s) was submitted. If You institute patent litigation
   against any entity (including a cross-claim or counterclaim in a
   lawsuit) alleging that the Work or a Contribution incorporated within
   the Work constitutes direct or contributory patent infringement, then
   any patent licenses granted to You under this License for that Work
   shall terminate as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the Work or
   Derivative Works thereof in any medium, with or without modifications,
   and in Source or Object form, provided that You meet the following
   conditions:

   a. You must give any other recipients of the Work or Derivative Works a
      copy of this License; and

   b. You must cause any modified files to carry prominent notices stating
      that You changed the files; and

   c. You must retain, in the Source form of any Derivative Works that You
      distribute, all copyright, patent, trademark, and attribution notices
      from the Source form of the Work, excluding those notices that do not
      pertain to any part of the Derivative Works; and

   d. If the Work includes a "NOTICE" text file as part of its
      distribution, then any Derivative Works that You distribute must
      include a readable copy of the attribution notices contained within
      such NOTICE file, excluding those notices that do not pertain to any
      part of the Derivative Works, in at least one of the following
      places: within a NOTICE text file distributed as part of the
      Derivative Works; within the Source form or documentation, if
      provided along with the Derivative Works; or, within a display
      generated by the Derivative Works, if and wherever such third-party
      notices normally appear. The contents of the NOTICE file are for
      informational purposes only and do not modify the License. You may
      add Your own attribution notices within Derivative Works that You
      distribute, alongside or as an addendum to the NOTICE text from the
      Work, provided that such additional attribution notices cannot be
      construed as modifying the License.

    You may add Your own copyright statement to Your modifications and may
    provide additional or different license terms and conditions for use,
    reproduction, or distribution of Your modifications, or for any such
    Derivative Works as a whole, provided Your use, reproduction, and
    distribution of the Work otherwise complies with the conditions stated
    in this License.

5. Submission of Contributions. Unless You explicitly state otherwise, any
   Contribution intentionally submitted for inclusion in the Work by You to
   the Licensor shall be under the terms and conditions of this License,
   without any additional terms or conditions. Notwithstanding the above,
   nothing herein shall supersede or modify the terms of any separate
   license agreement you may have executed with Licensor regarding such
   Contributions.

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor,
   except as required for reasonable and customary use in describing the
   origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or agreed to
   in writing, Licensor provides the Work (and each Contributor provides
   its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
   OF ANY KIND, either express or implied, including, without limitation,
   any warranties or conditions of TITLE, NON-INFRINGEMENT,
   MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely
   responsible for determining the appropriateness of using or
   redistributing the Work and assume any risks associated with Your
   exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory, whether
   in tort (including negligence), contract, or otherwise, unless required
   by applicable law (such as deliberate and grossly negligent acts) or
   agreed to in writing, shall any Contributor be liable to You for
   damages, including any direct, indirect, special, incidental, or
   consequential damages of any character arising as a result of this
   License or out of the use or inability to use the Work (including but
   not limited to damages for loss of goodwill, work stoppage, computer
   failure or malfunction, or any and all other commercial damages or
   losses), even if such Contributor has been advised of the possibility of
   such damages.

9. Accepting Warranty or Additional Liability. While redistributing the
   Work or Derivative Works thereof, You may choose to offer, and charge a
   fee for, acceptance of support, warranty, indemnity, or other liability
   obligations and/or rights consistent with this License. However, in
   accepting such obligations, You may act only on Your own behalf and on
   Your sole responsibility, not on behalf of any other Contributor, and
   only if You agree to indemnify, defend, and hold each Contributor
   harmless for any liability incurred by, or claims asserted against, such
   Contributor by reason of your accepting any such warranty or additional
   liability.

END OF TERMS AND CONDITIONS

================================================
FILE: LICENSES/BSD-3-Clause
================================================
Valid-License-Identifier: BSD-3-Clause
SPDX-URL: https://spdx.org/licenses/BSD-3-Clause.html
Usage-Guide:
  To use the BSD 3-clause "New" or "Revised" License put the following SPDX
  tag/value pair into a comment according to the placement guidelines in
  the licensing rules documentation:
    SPDX-License-Identifier: BSD-3-Clause
License-Text:

Copyright (c) <year> <owner> . All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

================================================
FILE: LICENSES/GPL-3.0-or-later
================================================
Valid-License-Identifier: GPL-3.0+
Valid-License-Identifier: GPL-3.0-or-later
SPDX-URL: https://spdx.org/licenses/GPL-3.0-or-later.html
Usage-Guide:
  To use this license in source code, put one of the following SPDX
  tag/value pairs into a comment according to the placement
  guidelines in the licensing rules documentation.
  For 'GNU General Public License (GPL) version 3 or any later version' use:
    SPDX-License-Identifier: GPL-3.0+
  or
    SPDX-License-Identifier: GPL-3.0-or-later
License-Text:

                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

================================================
FILE: LICENSES/MIT
================================================
Valid-License-Identifier: MIT
SPDX-URL: https://spdx.org/licenses/MIT.html
Usage-Guide:
  To use the MIT License put the following SPDX tag/value pair into a
  comment according to the placement guidelines in the licensing rules
  documentation:
    SPDX-License-Identifier: MIT
  Do NOT use this license unless the files are copied from another work
  under the same license. In such cases, use "AND GPL-3.0-or-later" so
  that your contributions are under GPL-3.0+ license.
License-Text:

MIT License

Copyright (c) <year> <copyright holders>

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.

================================================
FILE: README.md
================================================
# LibADB Android

ADB library for Android. It enables an app to connect to the ADB daemon (`adbd` process) belonging to the same or a
different device and execute arbitrary services or commands (via `shell:` service).

**Disclaimer:** This library has never gone through a security audit. Please, proceed with caution if security is
crucial for your app. Avoid using the APIs for reasons other than connecting or using ADB. For the safety of your app
and its users, open a remote service instead of using ADB and ask the user to disconnect Wireless debugging.

## Getting Started
### Adding Dependencies
LibADB Android is available via JitPack.

```groovy
// Top level build file
repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
}

// Add to dependencies section
dependencies {
    // Add this library
    implementation 'com.github.MuntashirAkon:libadb-android:3.1.1'
    
    // Library to generate X509Certificate. You can also use BouncyCastle for
    // this. See example for use-case.
    // implementation 'com.github.MuntashirAkon:sun-security-android:1.1'

    // Bypass hidden API if you want to use the Android default Conscrypt in
    // Android 9 (Pie) or later. It also requires additional steps. See
    // https://github.com/LSPosed/AndroidHiddenApiBypass to find out more about
    // this.
    // implementation 'org.lsposed.hiddenapibypass:hiddenapibypass:6.1'

    // Use custom Conscrypt library. If you want to connect to a remote ADB
    // daemon instead of the device the app is currently running or do not want
    // to bypass hidden API, this is the recommended choice.
    implementation 'org.conscrypt:conscrypt-android:2.5.3'
}
```

If you're using the custom Conscrypt library in order to connect to a remote ADB daemon and the app targets Android
version below 4.4, you have to extend `android.app.Application` to apply fixes for the random number generation:
```java
public class MyAwesomeApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // Fix random number generation in Android versions below 4.4.
        PRNGFixes.apply();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // Uncomment the following line if you want to bypass hidden API as
        // described above.
        // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        //     HiddenApiBypass.addHiddenApiExemptions("L");
        // }
    }
}
```

**Notice:** Conscrypt supports only API 9 (Gingerbread) or later, meaning you cannot use ADB pairing or any TLSv1.3
features in API less than 9. The corresponding methods are already annotated properly. So, you don't have to worry about
compatibility issues that may arise when your app's minimum SDK is set to one of the unsupported versions.

### Configuring ADB
Instead of doing everything manually, you can create a concrete implementation of the `AbsAdbConnectionManager` class. 
Example:

```java
public class AdbConnectionManager extends AbsAdbConnectionManager {
    private static AbsAdbConnectionManager INSTANCE;

    public static AbsAdbConnectionManager getInstance() throws Exception {
        if (INSTANCE == null) {
            INSTANCE = new AdbConnectionManager();
        }
        return INSTANCE;
    }

    private PrivateKey mPrivateKey;
    private Certificate mCertificate;

    private AdbConnectionManager() throws Exception {
        // Set the API version whose `adbd` is running
        setApi(Build.VERSION.SDK_INT);
        // TODO: Load private key and certificate (along with public key) from
        //  some place such as KeyStore or file system.
        mPrivateKey = ...;
        mCertificate = ...;
        if (mPrivateKey == null) {
            // Generate a new key pair
            int keySize = 2048;
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(keySize, SecureRandom.getInstance("SHA1PRNG"));
            KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = generateKeyPair.getPublic();
            mPrivateKey = generateKeyPair.getPrivate();
            // Generate a certificate
            // On Android, it requires sun.security-android library as mentioned
            // above.
            String subject = "CN=My Awesome App";
            String algorithmName = "SHA512withRSA";
            long expiryDate = System.currentTimeMillis() + 86400000;
            CertificateExtensions certificateExtensions = new CertificateExtensions();
            certificateExtensions.set("SubjectKeyIdentifier", new SubjectKeyIdentifierExtension(
                    new KeyIdentifier(publicKey).getIdentifier()));
            X500Name x500Name = new X500Name(subject);
            Date notBefore = new Date();
            Date notAfter = new Date(expiryDate);
            certificateExtensions.set("PrivateKeyUsage", new PrivateKeyUsageExtension(notBefore, notAfter));
            CertificateValidity certificateValidity = new CertificateValidity(notBefore, notAfter);
            X509CertInfo x509CertInfo = new X509CertInfo();
            x509CertInfo.set("version", new CertificateVersion(2));
            x509CertInfo.set("serialNumber", new CertificateSerialNumber(new Random().nextInt() & Integer.MAX_VALUE));
            x509CertInfo.set("algorithmID", new CertificateAlgorithmId(AlgorithmId.get(algorithmName)));
            x509CertInfo.set("subject", new CertificateSubjectName(x500Name));
            x509CertInfo.set("key", new CertificateX509Key(publicKey));
            x509CertInfo.set("validity", certificateValidity);
            x509CertInfo.set("issuer", new CertificateIssuerName(x500Name));
            x509CertInfo.set("extensions", certificateExtensions);
            X509CertImpl x509CertImpl = new X509CertImpl(x509CertInfo);
            x509CertImpl.sign(mPrivateKey, algorithmName);
            mCertificate = x509CertImpl;
            // TODO: Store the key pair to some place else.
        }
    }

    @NonNull
    @Override
    protected PrivateKey getPrivateKey() {
        return mPrivateKey;
    }

    @NonNull
    @Override
    protected Certificate getCertificate() {
        return mCertificate;
    }

    @NonNull
    @Override
    protected String getDeviceName() {
        return "MyAwesomeApp";
    }
}
```

### Connecting to ADB

You can connect to ADB in several ways from the `AbsAdbConnectionManager`:

| Method                          | Description                                                                                                   |
|---------------------------------|---------------------------------------------------------------------------------------------------------------|
| `connect(host, port)`           | Connect using a host address and a port number                                                                |
| `connect(port)`                 | Connect using a host address set by `setHostAddress()` and a port number                                      |
| `connectTcp(Context, timeout)`  | (SDK 16+) Discover host address and port number automatically for ADB over TCP and connect to it              | 
| `connectTls(Context, timeout)`  | (SDK 16+) Discover host address and port number automatically for TLS (from Android 9) and connect to it      |
| `autoConnect(Context, timeout)` | (SDK 16+) Discover host address and port number automatically for both ADB over TCP and TLS and connect to it |

### Wireless Debugging
Internally, ADB over TCP and Wireless Debugging are very similar except Wireless Debugging requires an extra step of
_pairing_ the device. In order to pair a new device, you can simply invoke `AdbConnectionManager.getInstance().pair(host, port, pairingCode)`.
After the pairing, you can connect to ADB via the usual `connect()` methods without any additional steps.

### Opening ADB Shell for Executing Arbitrary Commands
Simply use `AdbConnectionManager.getInstance().openStream("shell:")`. This will return an `AdbStream` which can be used
to read/write to the ADB shell via `AdbStream#openInputStream()` and `AdbStream#openOutputStream()` methods
respectively like a normal Java `Process`. While it is possible to read/write in the same thread (first write and then
read), this is not recommended because the shell might be stuck indefinitely for commands such as `top`.

**NOTE:** If you want to create a full-featured terminal emulator, this approach isn't recommended. Instead, you should
create a remote service via `app_process` or start an SSH server and connect to it.

### Other services
You can also use other services via the `AdbConnectionManager#openStream()` methods. See [SERVICES.md](./SERVICES.md)
for more information.

## For Java (non-Android) Projects
It is possible to modify this library to work on non-Android project. But it isn't supported because Spake2-Java only
provides stable releases for Android. However, you can incorporate this library in your project by manually compiling
Spake2 library for your platforms.

## Contributing
By contributing to this project, you permit your work to be released under the terms of GNU General Public License, 
Version 3 or later **or** Apache License, Version 2.0.

## License
Copyright 2021 &copy; Muntashir Al-Islam

Dual licensed under the terms of [GPL-3.0-or-later](https://www.gnu.org/licenses/gpl-3.0.html) or
[Apache-2.0 license](https://www.apache.org/licenses/LICENSE-2.0.html). Use whatever license you need for your project.

_Note regarding the Apache-2.0 license, this library has an LGPL dependency which may go against the policy of some
organizations such as ASF._


================================================
FILE: SERVICES.md
================================================
# Services

LibADB only supports local services which can be requested through `AbsAdbConnectionManager#openStream(String)` or
`AdbConnection#open(String)`.

- `shell:command arg1 arg2 ...`

  Run `command arg1 arg2 ...` in a shell on the device, and return its output and error streams. Note that arguments
  must be separated by spaces. If an argument contains a space, it must be quoted with double-quotes. Arguments cannot
  contain double quotes or things will go very wrong.

- `shell:`

  Start an interactive shell session on the device. Redirect stdin/stdout/stderr as appropriate.

- `dev:<path>`

  Opens a device file and connects the client directly to it for read/write purposes. Useful for debugging, but may 
  require special privileges and thus may not run on all devices. `<path>` is a full path from the root of the
  filesystem.

- `tcp:<port>`

  Tries to connect to tcp port `<port>` on localhost.

- `tcp:<port>:<server-name>`

  Tries to connect to tcp port `<port>` on machine `<server-name>` from the device. This can be useful to debug some
  networking/proxy issues that can only be revealed on the device itself.

- `local:<path>`

  Tries to connect to a Unix domain socket `<path>` on the device.

- `localreserved:<path>`/
  `localabstract:<path>`/
  `localfilesystem:<path>`

  Variants of `local:<path>` that are used to access other Android socket namespaces.

- `sync:`

  This starts the file synchronization service, used to implement "adb push" and "adb pull". Since this service is
  pretty complex, it will be detailed in a companion document named SYNC.TXT

- `reverse:<forward-command>`

  This implements the 'adb reverse' feature, i.e. the ability to reverse socket connections from a device to the host.
  `<forward-command>` is one of the forwarding commands that are described above, as in:

      list-forward
      forward:<local>;<remote>
      forward:norebind:<local>;<remote>
      killforward-all
      killforward:<local>

  Note that in this case, <local> corresponds to the socket on the device
  and <remote> corresponds to the socket on the host.

  The output of reverse:list-forward is the same as host:list-forward
  except that <serial> will be just 'host'.

## Reference
- [SERVICES.TXT](https://android.googlesource.com/platform/packages/modules/adb/+/6a85258511fb13ebbbedba4e36616db4c6e970fb/SERVICES.TXT)


================================================
FILE: app/.gitignore
================================================
/build

================================================
FILE: app/build.gradle
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

plugins {
    id 'com.android.application'
}

android {
    compileSdk 35
    namespace "io.github.muntashirakon.adb.testapp"

    defaultConfig {
        applicationId "io.github.muntashirakon.adb.testapp"
        minSdk 21
        targetSdk 35
        versionCode 8
        versionName "3.1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation project(path: ':libadb')
    implementation 'androidx.appcompat:appcompat:1.7.1'
    implementation 'com.google.android.material:material:1.12.0'

    // Library to generate X509Certificate. You can also use BouncyCastle for this.
    implementation 'com.github.MuntashirAkon:sun-security-android:1.1'

    // Bypass hidden API if you want to use Android default conscrypt. It also requires additional steps.
    // See https://github.com/LSPosed/AndroidHiddenApiBypass to find out more about this.
    // Comment out the line below if you do not need this.
    implementation 'org.lsposed.hiddenapibypass:hiddenapibypass:6.1'

    // Uncomment the line below if you want to use the custom conscrypt.
    // implementation 'org.conscrypt:conscrypt-android:2.5.3'
}


================================================
FILE: app/src/main/AndroidManifest.xml
================================================
<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:name=".App"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Material3.DayNight.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

================================================
FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/AdbConnectionManager.java
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

package io.github.muntashirakon.adb.testapp;

import android.content.Context;
import android.os.Build;
import android.sun.misc.BASE64Encoder;
import android.sun.security.provider.X509Factory;
import android.sun.security.x509.AlgorithmId;
import android.sun.security.x509.CertificateAlgorithmId;
import android.sun.security.x509.CertificateExtensions;
import android.sun.security.x509.CertificateIssuerName;
import android.sun.security.x509.CertificateSerialNumber;
import android.sun.security.x509.CertificateSubjectName;
import android.sun.security.x509.CertificateValidity;
import android.sun.security.x509.CertificateVersion;
import android.sun.security.x509.CertificateX509Key;
import android.sun.security.x509.KeyIdentifier;
import android.sun.security.x509.PrivateKeyUsageExtension;
import android.sun.security.x509.SubjectKeyIdentifierExtension;
import android.sun.security.x509.X500Name;
import android.sun.security.x509.X509CertImpl;
import android.sun.security.x509.X509CertInfo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;
import java.util.Random;

import io.github.muntashirakon.adb.AbsAdbConnectionManager;

public class AdbConnectionManager extends AbsAdbConnectionManager {
    private static AbsAdbConnectionManager INSTANCE;

    public static AbsAdbConnectionManager getInstance(@NonNull Context context) throws Exception {
        if (INSTANCE == null) {
            INSTANCE = new AdbConnectionManager(context);
        }
        return INSTANCE;
    }

    private PrivateKey mPrivateKey;
    private Certificate mCertificate;

    private AdbConnectionManager(@NonNull Context context) throws Exception {
        setApi(Build.VERSION.SDK_INT);
        mPrivateKey = readPrivateKeyFromFile(context);
        mCertificate = readCertificateFromFile(context);
        if (mPrivateKey == null) {
            // Generate a new key pair
            int keySize = 2048;
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(keySize, SecureRandom.getInstance("SHA1PRNG"));
            KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = generateKeyPair.getPublic();
            mPrivateKey = generateKeyPair.getPrivate();
            // Generate a new certificate
            String subject = "CN=My Awesome App";
            String algorithmName = "SHA512withRSA";
            long expiryDate = System.currentTimeMillis() + 86400000;
            CertificateExtensions certificateExtensions = new CertificateExtensions();
            certificateExtensions.set("SubjectKeyIdentifier", new SubjectKeyIdentifierExtension(
                    new KeyIdentifier(publicKey).getIdentifier()));
            X500Name x500Name = new X500Name(subject);
            Date notBefore = new Date();
            Date notAfter = new Date(expiryDate);
            certificateExtensions.set("PrivateKeyUsage", new PrivateKeyUsageExtension(notBefore, notAfter));
            CertificateValidity certificateValidity = new CertificateValidity(notBefore, notAfter);
            X509CertInfo x509CertInfo = new X509CertInfo();
            x509CertInfo.set("version", new CertificateVersion(2));
            x509CertInfo.set("serialNumber", new CertificateSerialNumber(new Random().nextInt() & Integer.MAX_VALUE));
            x509CertInfo.set("algorithmID", new CertificateAlgorithmId(AlgorithmId.get(algorithmName)));
            x509CertInfo.set("subject", new CertificateSubjectName(x500Name));
            x509CertInfo.set("key", new CertificateX509Key(publicKey));
            x509CertInfo.set("validity", certificateValidity);
            x509CertInfo.set("issuer", new CertificateIssuerName(x500Name));
            x509CertInfo.set("extensions", certificateExtensions);
            X509CertImpl x509CertImpl = new X509CertImpl(x509CertInfo);
            x509CertImpl.sign(mPrivateKey, algorithmName);
            mCertificate = x509CertImpl;
            // Write files
            writePrivateKeyToFile(context, mPrivateKey);
            writeCertificateToFile(context, mCertificate);
        }
    }

    @NonNull
    @Override
    protected PrivateKey getPrivateKey() {
        return mPrivateKey;
    }

    @NonNull
    @Override
    protected Certificate getCertificate() {
        return mCertificate;
    }

    @NonNull
    @Override
    protected String getDeviceName() {
        return "MyAwesomeApp";
    }

    @Nullable
    private static Certificate readCertificateFromFile(@NonNull Context context)
            throws IOException, CertificateException {
        File certFile = new File(context.getFilesDir(), "cert.pem");
        if (!certFile.exists()) return null;
        try (InputStream cert = new FileInputStream(certFile)) {
            return CertificateFactory.getInstance("X.509").generateCertificate(cert);
        }
    }

    private static void writeCertificateToFile(@NonNull Context context, @NonNull Certificate certificate)
            throws CertificateEncodingException, IOException {
        File certFile = new File(context.getFilesDir(), "cert.pem");
        BASE64Encoder encoder = new BASE64Encoder();
        try (OutputStream os = new FileOutputStream(certFile)) {
            os.write(X509Factory.BEGIN_CERT.getBytes(StandardCharsets.UTF_8));
            os.write('\n');
            encoder.encode(certificate.getEncoded(), os);
            os.write('\n');
            os.write(X509Factory.END_CERT.getBytes(StandardCharsets.UTF_8));
        }
    }

    @Nullable
    private static PrivateKey readPrivateKeyFromFile(@NonNull Context context)
            throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        File privateKeyFile = new File(context.getFilesDir(), "private.key");
        if (!privateKeyFile.exists()) return null;
        byte[] privKeyBytes = new byte[(int) privateKeyFile.length()];
        try (InputStream is = new FileInputStream(privateKeyFile)) {
            is.read(privKeyBytes);
        }
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
        return keyFactory.generatePrivate(privateKeySpec);
    }

    private static void writePrivateKeyToFile(@NonNull Context context, @NonNull PrivateKey privateKey)
            throws IOException {
        File privateKeyFile = new File(context.getFilesDir(), "private.key");
        try (OutputStream os = new FileOutputStream(privateKeyFile)) {
           os.write(privateKey.getEncoded());
        }
    }
}


================================================
FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/App.java
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

package io.github.muntashirakon.adb.testapp;

import android.app.Application;
import android.content.Context;
import android.os.Build;

import org.lsposed.hiddenapibypass.HiddenApiBypass;

import io.github.muntashirakon.adb.PRNGFixes;

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        PRNGFixes.apply();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            HiddenApiBypass.addHiddenApiExemptions("L");
        }
    }
}


================================================
FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/MainActivity.java
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

package io.github.muntashirakon.adb.testapp;

import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ScrollView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;

import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    private static final int DEFAULT_PORT_ADDRESS = 5555;

    private MenuItem connectAdbMenu;
    private MenuItem disconnectAdbMenu;
    private MenuItem pairAdbMenu;
    private ScrollView scrollView;

    private AppCompatEditText commandInput;
    private AppCompatTextView commandOutput;
    private MainViewModel viewModel;
    private boolean connected = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setSupportActionBar(findViewById(R.id.toolbar));
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);
        scrollView = findViewById(R.id.scrollView);
        commandInput = findViewById(R.id.command_input);
        commandOutput = findViewById(R.id.command_output);
        init();
    }

    private void init() {
        commandInput.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE && connected) {
                String command = Objects.requireNonNull(commandInput.getText()).toString();
                viewModel.execute(command);
                return true;
            }
            return false;
        });

        // Observers
        viewModel.watchConnectAdb().observe(this, isConnected -> {
            connected = isConnected;
            checkMenus();
            if (isConnected) {
                Toast.makeText(this, getString(R.string.connected_to_adb), Toast.LENGTH_SHORT).show();
                openIme();
            } else {
                Toast.makeText(this, getString(R.string.disconnected_from_adb), Toast.LENGTH_SHORT).show();
            }
        });
        viewModel.watchPairAdb().observe(this, isPaired -> {
            if (isPaired) {
                Toast.makeText(this, getString(R.string.pairing_successful), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, getString(R.string.pairing_failed), Toast.LENGTH_SHORT).show();
            }
        });
        viewModel.watchAskPairAdb().observe(this, displayDialog -> {
            if (displayDialog) {
                pairAdb();
            }
        });
        viewModel.watchCommandOutput().observe(this, output -> {
            commandOutput.setText(output == null ? "" : output);
            commandOutput.post(() -> scrollView.scrollTo(0, commandOutput.getHeight()));
        });

        // Try auto-connecting
        viewModel.autoConnect();
    }

    @Override
    protected void onResume() {
        super.onResume();
        openIme();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (connected && commandInput != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(commandInput.getWindowToken(), 0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.actions_main, menu);
        connectAdbMenu = menu.findItem(R.id.action_connect);
        disconnectAdbMenu = menu.findItem(R.id.action_disconnect);
        pairAdbMenu = menu.findItem(R.id.action_pair);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (pairAdbMenu != null) {
            pairAdbMenu.setEnabled(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R);
            pairAdbMenu.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R);
        }
        checkMenus();
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_connect) {
            connectAdb();
            return true;
        }
        if (id == R.id.action_disconnect) {
            connectAdb();
            return true;
        }
        if (id == R.id.action_pair) {
            pairAdb();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void openIme() {
        if (connected && commandInput != null && !commandInput.isFocused()) {
            commandInput.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.showSoftInput(commandInput, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    private void checkMenus() {
        if (connectAdbMenu != null) {
            connectAdbMenu.setEnabled(!connected);
            connectAdbMenu.setVisible(!connected);
        }
        if (disconnectAdbMenu != null) {
            disconnectAdbMenu.setEnabled(connected);
            disconnectAdbMenu.setVisible(connected);
        }
    }

    private void connectAdb() {
        if (connected) {
            viewModel.disconnect();
            return;
        }
        AppCompatEditText editText = new AppCompatEditText(this);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setText(String.valueOf(DEFAULT_PORT_ADDRESS));
        new MaterialAlertDialogBuilder(this)
                .setTitle(R.string.connect_adb)
                .setView(editText)
                .setPositiveButton(R.string.connect_adb, (dialog, which) -> {
                    CharSequence portString = editText.getText();
                    if (portString != null && TextUtils.isDigitsOnly(portString)) {
                        int port = Integer.parseInt(portString.toString());
                        viewModel.connect(port);
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    private void pairAdb() {
        View view = getLayoutInflater().inflate(R.layout.dialog_input, null);
        TextInputEditText pairingCodeEditText = view.findViewById(R.id.pairing_code);
        TextInputEditText portNumberEditText = view.findViewById(R.id.port_number);
        viewModel.watchPairingPort().observe(this, port -> {
            if (port != -1) {
                portNumberEditText.setText(String.valueOf(port));
            } else {
                portNumberEditText.setText(null);
            }
        });
        viewModel.getPairingPort();
        new MaterialAlertDialogBuilder(this)
                .setTitle(R.string.pair_adb)
                .setView(view)
                .setPositiveButton(R.string.pair_adb, (dialog, which) -> {
                    CharSequence pairingCode = pairingCodeEditText.getText();
                    CharSequence portNumberString = portNumberEditText.getText();
                    if (pairingCode != null && pairingCode.length() == 6 && portNumberString != null
                            && TextUtils.isDigitsOnly(portNumberString)) {
                        int port = Integer.parseInt(portNumberString.toString());
                        viewModel.pair(port, pairingCode.toString());
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .setOnDismissListener(dialog -> viewModel.watchPairingPort().removeObservers(this))
                .show();
    }
}


================================================
FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/MainViewModel.java
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

package io.github.muntashirakon.adb.testapp;

import android.app.Application;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.github.muntashirakon.adb.AbsAdbConnectionManager;
import io.github.muntashirakon.adb.AdbPairingRequiredException;
import io.github.muntashirakon.adb.AdbStream;
import io.github.muntashirakon.adb.LocalServices;
import io.github.muntashirakon.adb.android.AdbMdns;
import io.github.muntashirakon.adb.android.AndroidUtils;

public class MainViewModel extends AndroidViewModel {
    private final ExecutorService executor = Executors.newFixedThreadPool(3);
    private final MutableLiveData<Boolean> connectAdb = new MutableLiveData<>();
    private final MutableLiveData<Boolean> pairAdb = new MutableLiveData<>();
    private final MutableLiveData<Boolean> askPairAdb = new MutableLiveData<>();
    private final MutableLiveData<CharSequence> commandOutput = new MutableLiveData<>();
    private final MutableLiveData<Integer> pairingPort = new MutableLiveData<>();

    @Nullable
    private AdbStream adbShellStream;

    public MainViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<Boolean> watchConnectAdb() {
        return connectAdb;
    }

    public LiveData<Boolean> watchPairAdb() {
        return pairAdb;
    }

    public LiveData<Boolean> watchAskPairAdb() {
        return askPairAdb;
    }

    public LiveData<CharSequence> watchCommandOutput() {
        return commandOutput;
    }

    public LiveData<Integer> watchPairingPort() {
        return pairingPort;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        executor.submit(() -> {
            try {
                if (adbShellStream != null) {
                    adbShellStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                AdbConnectionManager.getInstance(getApplication()).close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        executor.shutdown();
    }

    public void connect(int port) {
        executor.submit(() -> {
            try {
                AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());
                boolean connectionStatus;
                try {
                    connectionStatus = manager.connect(AndroidUtils.getHostIpAddress(getApplication()), port);
                } catch (Throwable th) {
                    th.printStackTrace();
                    connectionStatus = false;
                }
                connectAdb.postValue(connectionStatus);
            } catch (Throwable th) {
                th.printStackTrace();
                connectAdb.postValue(false);
            }
        });
    }

    public void autoConnect() {
        executor.submit(this::autoConnectInternal);
    }

    public void disconnect() {
        executor.submit(() -> {
            try {
                AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());
                manager.disconnect();
                connectAdb.postValue(false);
            } catch (Throwable th) {
                th.printStackTrace();
                connectAdb.postValue(true);
            }
        });
    }

    public void getPairingPort() {
        executor.submit(() -> {
            AtomicInteger atomicPort = new AtomicInteger(-1);
            CountDownLatch resolveHostAndPort = new CountDownLatch(1);

            AdbMdns adbMdns = new AdbMdns(getApplication(), AdbMdns.SERVICE_TYPE_TLS_PAIRING, (hostAddress, port) -> {
                atomicPort.set(port);
                resolveHostAndPort.countDown();
            });
            adbMdns.start();

            try {
                if (!resolveHostAndPort.await(1, TimeUnit.MINUTES)) {
                    return;
                }
            } catch (InterruptedException ignore) {
            } finally {
                adbMdns.stop();
            }

            pairingPort.postValue(atomicPort.get());
        });
    }

    public void pair(int port, String pairingCode) {
        executor.submit(() -> {
            try {
                boolean pairingStatus;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());
                    pairingStatus = manager.pair(AndroidUtils.getHostIpAddress(getApplication()), port, pairingCode);
                } else pairingStatus = false;
                pairAdb.postValue(pairingStatus);
                autoConnectInternal();
            } catch (Throwable th) {
                th.printStackTrace();
                pairAdb.postValue(false);
            }
        });
    }

    @WorkerThread
    private void autoConnectInternal() {
        try {
            AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());
            boolean connected = false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                try {
                    connected = manager.autoConnect(getApplication(), 5000);
                } catch (AdbPairingRequiredException e) {
                    askPairAdb.postValue(true);
                    return;
                } catch (Throwable th) {
                    th.printStackTrace();
                }
            }
            if (!connected) {
                connected = manager.connect(5555);
            }
            if (connected) {
                connectAdb.postValue(true);
            }
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

    private volatile boolean clearEnabled;
    private final Runnable outputGenerator = () -> {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(adbShellStream.openInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = reader.readLine()) != null) {
                if (clearEnabled) {
                    sb.delete(0, sb.length());
                    clearEnabled = false;
                }
                sb.append(s).append("\n");
                commandOutput.postValue(sb);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    public void execute(String command) {
        executor.submit(() -> {
            try {
                if (adbShellStream == null || adbShellStream.isClosed()) {
                    AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());
                    adbShellStream = manager.openStream(LocalServices.SHELL);
                    new Thread(outputGenerator).start();
                }
                if (command.equals("clear")) {
                    clearEnabled = true;
                }
                try (OutputStream os = adbShellStream.openOutputStream()) {
                    os.write(String.format("%1$s\n", command).getBytes(StandardCharsets.UTF_8));
                    os.flush();
                    os.write("\n".getBytes(StandardCharsets.UTF_8));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}


================================================
FILE: app/src/main/res/drawable/ic_add_link.xml
================================================
<!-- SPDX-License-Identifier: Apache-2.0 -->
<vector android:height="24dp"
    android:tint="#000000"
    android:viewportHeight="24"
    android:viewportWidth="24"
    android:width="24dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M8,11h8v2L8,13zM20.1,12L22,12c0,-2.76 -2.24,-5 -5,-5h-4v1.9h4c1.71,0 3.1,1.39 3.1,3.1zM3.9,12c0,-1.71 1.39,-3.1 3.1,-3.1h4L11,7L7,7c-2.76,0 -5,2.24 -5,5s2.24,5 5,5h4v-1.9L7,15.1c-1.71,0 -3.1,-1.39 -3.1,-3.1zM19,12h-2v3h-3v2h3v3h2v-3h3v-2h-3z" />
</vector>


================================================
FILE: app/src/main/res/drawable/ic_launcher_background.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108"
    android:viewportHeight="108">
    <path android:fillColor="#3DDC84" android:pathData="M0,0h108v108h-108z" />
    <path android:fillColor="#00000000" android:pathData="M9,0L9,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M19,0L19,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M29,0L29,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M39,0L39,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M49,0L49,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M59,0L59,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M69,0L69,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M79,0L79,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M89,0L89,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M99,0L99,108" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,9L108,9" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,19L108,19" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,29L108,29" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,39L108,39" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,49L108,49" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,59L108,59" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,69L108,69" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,79L108,79" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,89L108,89" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M0,99L108,99" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M19,29L89,29" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M19,39L89,39" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M19,49L89,49" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M19,59L89,59" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M19,69L89,69" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M19,79L89,79" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M29,19L29,89" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M39,19L39,89" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M49,19L49,89" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M59,19L59,89" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M69,19L69,89" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
    <path android:fillColor="#00000000" android:pathData="M79,19L79,89" android:strokeWidth="0.8"
        android:strokeColor="#33FFFFFF" />
</vector>


================================================
FILE: app/src/main/res/drawable/ic_link.xml
================================================
<!-- SPDX-License-Identifier: Apache-2.0 -->
<vector android:height="24dp"
    android:tint="#000000"
    android:viewportHeight="24"
    android:viewportWidth="24"
    android:width="24dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M3.9,12c0,-1.71 1.39,-3.1 3.1,-3.1h4L11,7L7,7c-2.76,0 -5,2.24 -5,5s2.24,5 5,5h4v-1.9L7,15.1c-1.71,0 -3.1,-1.39 -3.1,-3.1zM8,13h8v-2L8,11v2zM17,7h-4v1.9h4c1.71,0 3.1,1.39 3.1,3.1s-1.39,3.1 -3.1,3.1h-4L13,17h4c2.76,0 5,-2.24 5,-5s-2.24,-5 -5,-5z" />
</vector>


================================================
FILE: app/src/main/res/drawable/ic_link_off.xml
================================================
<!-- SPDX-License-Identifier: Apache-2.0 -->
<vector android:height="24dp"
    android:tint="#000000"
    android:viewportHeight="24"
    android:viewportWidth="24"
    android:width="24dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M17,7h-4v1.9h4c1.71,0 3.1,1.39 3.1,3.1 0,1.43 -0.98,2.63 -2.31,2.98l1.46,1.46C20.88,15.61 22,13.95 22,12c0,-2.76 -2.24,-5 -5,-5zM16,11h-2.19l2,2L16,13zM2,4.27l3.11,3.11C3.29,8.12 2,9.91 2,12c0,2.76 2.24,5 5,5h4v-1.9L7,15.1c-1.71,0 -3.1,-1.39 -3.1,-3.1 0,-1.59 1.21,-2.9 2.76,-3.07L8.73,11L8,11v2h2.73L13,15.27L13,17h1.73l4.01,4L20,19.74 3.27,3 2,4.27z" />
</vector>


================================================
FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml
================================================
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt"
    android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
    <path
        android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
        <aapt:attr name="android:fillColor">
            <gradient android:endX="85.84757" android:endY="92.4963" android:startX="42.9492" android:startY="49.59793"
                android:type="linear">
                <item android:color="#44000000" android:offset="0.0" />
                <item android:color="#00000000" android:offset="1.0" />
            </gradient>
        </aapt:attr>
    </path>
    <path
        android:fillColor="#FFFFFF"
        android:fillType="nonZero" android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z" android:strokeWidth="1"
        android:strokeColor="#00000000" />
</vector>

================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:menu="@menu/actions_main" />

    </com.google.android.material.appbar.AppBarLayout>

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="?actionBarSize"
        app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/command_output"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingVertical="8dp"
            android:paddingHorizontal="16dp"
            android:textIsSelectable="true"
            android:fontFamily="monospace"
            android:textSize="12sp"
            tools:text="Command output" />
    </ScrollView>

    <com.google.android.material.bottomappbar.BottomAppBar
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:layout_gravity="bottom"
        app:navigationIcon="@null">

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingEnd="8dp"
            android:hint="@string/enter_command"
            app:endIconMode="clear_text"
            tools:ignore="RtlSymmetry">

            <androidx.appcompat.widget.AppCompatEditText
                android:id="@+id/command_input"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textNoSuggestions"
                android:fontFamily="monospace"
                android:maxLines="1"
                android:imeOptions="actionDone" />

        </com.google.android.material.textfield.TextInputLayout>

    </com.google.android.material.bottomappbar.BottomAppBar>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

================================================
FILE: app/src/main/res/layout/dialog_input.xml
================================================
<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingHorizontal="16dp"
    android:paddingVertical="8dp">

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/pairing_code">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/pairing_code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:hint="@string/port_number">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/port_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

</androidx.appcompat.widget.LinearLayoutCompat>

================================================
FILE: app/src/main/res/menu/actions_main.xml
================================================
<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_connect"
        android:title="@string/connect_adb"
        android:icon="@drawable/ic_link"
        app:showAsAction="always" />
    <item
        android:id="@+id/action_disconnect"
        android:title="@string/disconnect_adb"
        android:icon="@drawable/ic_link_off"
        app:showAsAction="always" />
    <item
        android:id="@+id/action_pair"
        android:title="@string/pair_adb"
        android:icon="@drawable/ic_add_link"
        app:showAsAction="always" />
</menu>

================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@drawable/ic_launcher_background" />
    <foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@drawable/ic_launcher_background" />
    <foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

================================================
FILE: app/src/main/res/values/strings.xml
================================================
<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->
<resources>
    <string name="app_name">ADB Shell</string>
    <string name="connect_adb">Connect</string>
    <string name="pair_adb">Pair</string>
    <string name="enter_command">Enter command</string>
    <string name="run_command">Run</string>
    <string name="pairing_successful">Pairing successful!</string>
    <string name="pairing_failed">Pairing failed!</string>
    <string name="connected_to_adb">Connected to ADB!</string>
    <string name="disconnected_from_adb">Disconnected from ADB!</string>
    <string name="disconnect_adb">Disconnect</string>
    <string name="pairing_code">Pairing Code</string>
    <string name="port_number">Port Number</string>
</resources>


================================================
FILE: build.gradle
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:8.9.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

wrapper {
    distributionType = Wrapper.DistributionType.BIN
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url "https://jitpack.io" }
    }
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile).tap {
            configureEach {
                options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
            }
        }
    }
}


================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=8fad3d78296ca518113f3d29016617c7f9367dc005f932bd9d93bf45ba46072b
distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists


================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
android.useAndroidX=true
android.enableJetifier=true
android.jetifier.ignorelist=bcprov-jdk15to18
android.nonTransitiveRClass=true
android.nonFinalResIds=false


================================================
FILE: gradlew
================================================
#!/bin/sh

#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#

##############################################################################
#
#   Gradle start up script for POSIX generated by Gradle.
#
#   Important for running:
#
#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
#       noncompliant, but you have some other compliant shell such as ksh or
#       bash, then to run this script, type that shell name before the whole
#       command line, like:
#
#           ksh Gradle
#
#       Busybox and similar reduced shells will NOT work, because this script
#       requires all of these POSIX shell features:
#         * functions;
#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
#         * compound commands having a testable exit status, especially «case»;
#         * various built-in commands including «command», «set», and «ulimit».
#
#   Important for patching:
#
#   (2) This script targets any POSIX shell, so it avoids extensions provided
#       by Bash, Ksh, etc; in particular arrays are avoided.
#
#       The "traditional" practice of packing multiple parameters into a
#       space-separated string is a well documented source of bugs and security
#       problems, so this is (mostly) avoided, by progressively accumulating
#       options in "$@", and eventually passing that to Java.
#
#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
#       see the in-line comments for details.
#
#       There are tweaks for specific operating systems such as AIX, CygWin,
#       Darwin, MinGW, and NonStop.
#
#   (3) This script is generated from the Groovy template
#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
#       within the Gradle project.
#
#       You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################

# Attempt to set APP_HOME

# Resolve links: $0 may be a link
app_path=$0

# Need this for daisy-chained symlinks.
while
    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
    [ -h "$app_path" ]
do
    ls=$( ls -ld "$app_path" )
    link=${ls#*' -> '}
    case $link in             #(
      /*)   app_path=$link ;; #(
      *)    app_path=$APP_HOME$link ;;
    esac
done

# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum

warn () {
    echo "$*"
} >&2

die () {
    echo
    echo "$*"
    echo
    exit 1
} >&2

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in                #(
  CYGWIN* )         cygwin=true  ;; #(
  Darwin* )         darwin=true  ;; #(
  MSYS* | MINGW* )  msys=true    ;; #(
  NONSTOP* )        nonstop=true ;;
esac

CLASSPATH="\\\"\\\""


# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD=$JAVA_HOME/jre/sh/java
    else
        JAVACMD=$JAVA_HOME/bin/java
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD=java
    if ! command -v java >/dev/null 2>&1
    then
        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
    case $MAX_FD in #(
      max*)
        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        MAX_FD=$( ulimit -H -n ) ||
            warn "Could not query maximum file descriptor limit"
    esac
    case $MAX_FD in  #(
      '' | soft) :;; #(
      *)
        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        ulimit -n "$MAX_FD" ||
            warn "Could not set maximum file descriptor limit to $MAX_FD"
    esac
fi

# Collect all arguments for the java command, stacking in reverse order:
#   * args from the command line
#   * the main class name
#   * -classpath
#   * -D...appname settings
#   * --module-path (only if needed)
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.

# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
    CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )

    JAVACMD=$( cygpath --unix "$JAVACMD" )

    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    for arg do
        if
            case $arg in                                #(
              -*)   false ;;                            # don't mess with options #(
              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
                    [ -e "$t" ] ;;                      #(
              *)    false ;;
            esac
        then
            arg=$( cygpath --path --ignore --mixed "$arg" )
        fi
        # Roll the args list around exactly as many times as the number of
        # args, so each arg winds up back in the position where it started, but
        # possibly modified.
        #
        # NB: a `for` loop captures its iteration list before it begins, so
        # changing the positional parameters here affects neither the number of
        # iterations, nor the values presented in `arg`.
        shift                   # remove old arg
        set -- "$@" "$arg"      # push replacement arg
    done
fi


# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
#     and any embedded shellness will be escaped.
#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
#     treated as '${Hostname}' itself on the command line.

set -- \
        "-Dorg.gradle.appname=$APP_BASE_NAME" \
        -classpath "$CLASSPATH" \
        -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
        "$@"

# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
    die "xargs is not available"
fi

# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
#   set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#

eval "set -- $(
        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
        xargs -n1 |
        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
        tr '\n' ' '
    )" '"$@"'

exec "$JAVACMD" "$@"


================================================
FILE: gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem      https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem

@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:execute
@rem Setup the command line

set CLASSPATH=


@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*

:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega


================================================
FILE: jitpack.yml
================================================
jdk:
  - openjdk21
before_install:
  - sdk install java 21.0.4-tem
  - sdk use java 21.0.4-tem
  - sdk install maven
  - mvn -v

================================================
FILE: libadb/.gitignore
================================================
/build


================================================
FILE: libadb/build.gradle
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

plugins {
    id 'com.android.library'
    id 'maven-publish'
}

group = 'io.github.muntashirakon'
version = '3.1.1'

android {
    compileSdk 35
    namespace "io.github.muntashirakon.adb"

    defaultConfig {
        minSdk 1
        targetSdk 35
        aarMetadata {
            minCompileSdk = 1
        }
    }

    buildTypes {
        release {
            minifyEnabled false
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    publishing {
        singleVariant("release") {
            withSourcesJar()
            withJavadocJar()
        }
    }
}

publishing {
    publications {
        release(MavenPublication) {
            artifactId = 'libadb'
            afterEvaluate {
                from components.release
            }
        }
    }
}

dependencies {
    implementation "androidx.annotation:annotation:1.9.1"
    implementation 'org.bouncycastle:bcprov-jdk15to18:1.81'
    implementation 'com.github.MuntashirAkon.spake2-java:spake2-android:2.2.1'

    testImplementation 'junit:junit:4.13.2'
}


================================================
FILE: libadb/src/main/AndroidManifest.xml
================================================
<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AbsAdbConnectionManager.java
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

package io.github.muntashirakon.adb;

import android.content.Context;
import android.os.Build;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.WorkerThread;

import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import javax.security.auth.DestroyFailedException;

import io.github.muntashirakon.adb.android.AdbMdns;

@SuppressWarnings("unused")
public abstract class AbsAdbConnectionManager implements Closeable {
    private final Object mLock = new Object();
    @Nullable
    private AdbConnection mAdbConnection;
    private String mHostAddress = "127.0.0.1";
    private int mApi = Build.VERSION_CODES.BASE;
    private long mTimeout = Long.MAX_VALUE;
    private TimeUnit mTimeoutUnit = TimeUnit.MILLISECONDS;
    private boolean mThrowOnUnauthorised = false;

    /**
     * Return generated/stored private key.
     */
    @NonNull
    protected abstract PrivateKey getPrivateKey();

    /**
     * Return public key wrapped around a certificate.
     */
    @NonNull
    protected abstract Certificate getCertificate();

    /**
     * Return a name for the device. This can be the app label, hostname or user@hostname.
     */
    @NonNull
    protected abstract String getDeviceName();

    /**
     * Set host address for this connection. On the same device, this should be {@code 127.0.0.1}.
     */
    @CallSuper
    public void setHostAddress(@NonNull String hostAddress) {
        mHostAddress = Objects.requireNonNull(hostAddress);
    }

    /**
     * Get host address for this connection. Default value is {@code 127.0.0.1}.
     */
    @NonNull
    public String getHostAddress() {
        return mHostAddress;
    }

    /**
     * Set Android API (i.e. SDK) version for this connection. If the daemon and the client are located in the same
     * directory, the value should be {@link Build.VERSION#SDK_INT} in order to improve performance as well as security.
     *
     * @param api The API version, default is {@link Build.VERSION_CODES#BASE}.
     */
    public void setApi(int api) {
        this.mApi = api;
    }

    /**
     * Get Android API (i.e. SDK) version for this connection. Default value is {@link Build.VERSION_CODES#BASE}.
     */
    public int getApi() {
        return mApi;
    }

    /**
     * Set time to wait for the connection to be made.
     *
     * @param timeout Timeout value
     * @param unit    Timeout unit
     */
    @CallSuper
    public void setTimeout(long timeout, TimeUnit unit) {
        mTimeout = timeout;
        mTimeoutUnit = unit;
    }

    /**
     * Get time to wait for the connection to be made. If not set using {@link #setTimeout(long, TimeUnit)}, the default
     * timeout is {@link Long#MAX_VALUE} milliseconds.
     *
     * @return Timeout in milliseconds
     */
    public long getTimeout() {
        return mTimeoutUnit.toMillis(mTimeout);
    }

    /**
     * Get the unit for the timeout. If not set using {@link #setTimeout(long, TimeUnit)}, the default timeout unit is
     * {@link TimeUnit#MILLISECONDS}.
     */
    @NonNull
    public TimeUnit getTimeoutUnit() {
        return mTimeoutUnit;
    }

    /**
     * Set whether to throw {@link AdbAuthenticationFailedException} if the daemon rejects the first authentication
     * attempt.
     *
     * @param throwOnUnauthorised {@code true} to throw {@link AdbAuthenticationFailedException} or {@code false}
     *                            otherwise.
     */
    @CallSuper
    public void setThrowOnUnauthorised(boolean throwOnUnauthorised) {
        mThrowOnUnauthorised = throwOnUnauthorised;
    }

    /**
     * Get whether to throw {@link AdbAuthenticationFailedException} if the daemon rejects the first authentication
     * attempt.
     *
     * @return {@code true} if the system is configured to throw {@link AdbAuthenticationFailedException} or
     * {@code false} otherwise. The default value is {@code false}.
     */
    public boolean isThrowOnUnauthorised() {
        return mThrowOnUnauthorised;
    }

    /**
     * Get the {@link AdbConnection} backed by this object.
     *
     * @return Underlying {@link AdbConnection}, or {@code null} if the connection hasn't been made yet.
     */
    @CallSuper
    @Nullable
    public AdbConnection getAdbConnection() {
        synchronized (mLock) {
            return mAdbConnection;
        }
    }

    /**
     * Check if it is connected to an ADB daemon.
     *
     * @return {@code true} if connected, {@code false} otherwise.
     */
    public boolean isConnected() {
        synchronized (mLock) {
            return mAdbConnection != null && mAdbConnection.isConnected() && mAdbConnection.isConnectionEstablished();
        }
    }

    /**
     * Attempt to connect to ADB by performing an automatic network discovery of TLS host and port. Host address set by
     * {@link #setHostAddress(String)} is ignored.
     *
     * @param context       Application context
     * @param timeoutMillis Amount of time spent in searching for a host and a port.
     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection
     * attempt is unsuccessful, or it has already been made.
     * @throws IOException                      If the socket connection could not be made.
     * @throws InterruptedException             If timeout has reached.
     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB
     *                                          daemon has rejected the first authentication attempt, which indicates
     *                                          that the daemon has not saved the public key from a previous connection.
     * @throws AdbPairingRequiredException      If ADB lacks pairing
     */
    @WorkerThread
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    public boolean connectTls(@NonNull Context context, long timeoutMillis)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        return autoConnect(context, AdbMdns.SERVICE_TYPE_TLS_CONNECT, timeoutMillis);
    }

    /**
     * Attempt to connect to ADB by performing an automatic network discovery of TCP host and port. Host address set by
     * {@link #setHostAddress(String)} is ignored.
     *
     * @param context       Application context
     * @param timeoutMillis Amount of time spent in searching for a host and a port.
     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection
     * attempt is unsuccessful, or it has already been made.
     * @throws IOException                      If the socket connection could not be made.
     * @throws InterruptedException             If timeout has reached.
     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB
     *                                          daemon has rejected the first authentication attempt, which indicates
     *                                          that the daemon has not saved the public key from a previous connection.
     * @throws AdbPairingRequiredException      If ADB lacks pairing
     */
    @WorkerThread
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    public boolean connectTcp(@NonNull Context context, long timeoutMillis)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        return autoConnect(context, AdbMdns.SERVICE_TYPE_ADB, timeoutMillis);
    }

    /**
     * Attempt to connect to ADB by performing an automatic network discovery of host and port. Host address set by
     * {@link #setHostAddress(String)} is ignored.
     *
     * @param context       Application context
     * @param timeoutMillis Amount of time spent in searching for a host and a port.
     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection
     * attempt is unsuccessful, or it has already been made.
     * @throws IOException                      If the socket connection could not be made.
     * @throws InterruptedException             If timeout has reached.
     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB
     *                                          daemon has rejected the first authentication attempt, which indicates
     *                                          that the daemon has not saved the public key from a previous connection.
     * @throws AdbPairingRequiredException      If ADB lacks pairing
     */
    @WorkerThread
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    public boolean autoConnect(@NonNull Context context, long timeoutMillis)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        synchronized (mLock) {
            AtomicInteger atomicPort = new AtomicInteger(-1);
            AtomicReference<String> atomicHostAddress = new AtomicReference<>(null);
            CountDownLatch resolveHostAndPort = new CountDownLatch(1);

            AdbMdns adbMdnsTcp = new AdbMdns(context, AdbMdns.SERVICE_TYPE_ADB, (hostAddress, port) -> {
                if (hostAddress != null) {
                    atomicHostAddress.set(hostAddress.getHostAddress());
                    atomicPort.set(port);
                }
                resolveHostAndPort.countDown();
            });
            adbMdnsTcp.start();

            AdbMdns adbMdnsTls = new AdbMdns(context, AdbMdns.SERVICE_TYPE_TLS_CONNECT, (hostAddress, port) -> {
                if (hostAddress != null) {
                    atomicHostAddress.set(hostAddress.getHostAddress());
                    atomicPort.set(port);
                }
                resolveHostAndPort.countDown();
            });
            adbMdnsTls.start();

            try {
                if (!resolveHostAndPort.await(timeoutMillis, TimeUnit.MILLISECONDS)) {
                    throw new InterruptedException("Timed out while trying to find a valid host address and port");
                }
            } finally {
                adbMdnsTcp.stop();
                adbMdnsTls.stop();
            }

            String host = atomicHostAddress.get();
            int port = atomicPort.get();

            if (host == null || port == -1) {
                throw new IOException("Could not find any valid host address or port");
            }

            mHostAddress = host;
            mAdbConnection = new AdbConnection.Builder(host, port)
                    .setApi(mApi)
                    .setKeyPair(getAdbKeyPair())
                    .setDeviceName(Objects.requireNonNull(getDeviceName()))
                    .build();
            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);
        }
    }

    @WorkerThread
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    private boolean autoConnect(@NonNull Context context, @AdbMdns.ServiceType @NonNull String serviceType, long timeoutMillis)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        synchronized (mLock) {
            AtomicInteger atomicPort = new AtomicInteger(-1);
            AtomicReference<String> atomicHostAddress = new AtomicReference<>(null);
            CountDownLatch resolveHostAndPort = new CountDownLatch(1);

            AdbMdns adbMdns = new AdbMdns(context, serviceType, (hostAddress, port) -> {
                if (hostAddress != null) {
                    atomicHostAddress.set(hostAddress.getHostAddress());
                    atomicPort.set(port);
                }
                resolveHostAndPort.countDown();
            });
            adbMdns.start();

            try {
                if (!resolveHostAndPort.await(timeoutMillis, TimeUnit.MILLISECONDS)) {
                    throw new InterruptedException("Timed out while trying to find a valid host address and port");
                }
            } finally {
                adbMdns.stop();
            }

            String host = atomicHostAddress.get();
            int port = atomicPort.get();

            if (host == null || port == -1) {
                throw new IOException("Could not find any valid host address or port");
            }

            mHostAddress = host;
            mAdbConnection = new AdbConnection.Builder(host, port)
                    .setApi(mApi)
                    .setKeyPair(getAdbKeyPair())
                    .setDeviceName(Objects.requireNonNull(getDeviceName()))
                    .build();
            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);
        }
    }

    /**
     * Attempt to connect to ADB given a port number. Host address is set via {@link #setHostAddress(String)}.
     *
     * @param port Port number
     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection
     * attempt is unsuccessful, or it has already been made.
     * @throws IOException                      If the socket connection could not be made.
     * @throws InterruptedException             If timeout has reached.
     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB
     *                                          daemon has rejected the first authentication attempt, which indicates
     *                                          that the daemon has not saved the public key from a previous connection.
     * @throws AdbPairingRequiredException      If ADB lacks pairing
     */
    @WorkerThread
    public boolean connect(int port) throws IOException, InterruptedException, AdbPairingRequiredException {
        synchronized (mLock) {
            if (isConnected()) {
                return false;
            }
            mAdbConnection = new AdbConnection.Builder(mHostAddress, port)
                    .setApi(mApi)
                    .setKeyPair(getAdbKeyPair())
                    .setDeviceName(Objects.requireNonNull(getDeviceName()))
                    .build();
            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);
        }
    }

    /**
     * Attempt to connect to ADB via a host address and a port number.
     *
     * @param host Host address to use instead of taking it from the {@link #getHostAddress()}
     * @param port Port number
     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection
     * attempt is unsuccessful, or it has already been made.
     * @throws IOException                      If the socket connection could not be made.
     * @throws InterruptedException             If timeout has reached.
     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the
     *                                          ADB daemon has rejected the first authentication attempt, which
     *                                          indicates that the daemon has not saved the public key from a previous
     *                                          connection.
     * @throws AdbPairingRequiredException      If ADB lacks pairing
     */
    @WorkerThread
    public boolean connect(@NonNull String host, int port)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        synchronized (mLock) {
            if (isConnected()) {
                return false;
            }
            mHostAddress = host;
            mAdbConnection = new AdbConnection.Builder(host, port)
                    .setApi(mApi)
                    .setKeyPair(getAdbKeyPair())
                    .setDeviceName(Objects.requireNonNull(getDeviceName()))
                    .build();
            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);
        }
    }

    /**
     * Disconnect the underlying {@link AdbConnection}.
     *
     * @throws IOException If the underlying socket fails to close
     */
    public void disconnect() throws IOException {
        synchronized (mLock) {
            if (mAdbConnection != null) {
                mAdbConnection.close();
                mAdbConnection = null;
            }
        }
    }

    /**
     * Opens an {@link AdbStream} object corresponding to the specified destination.
     * This routine will block until the connection completes.
     *
     * @param destination The destination to open on the target
     * @return {@link AdbStream} object corresponding to the specified destination
     * @throws IOException                  If the steam fails or no connection has been made
     * @throws InterruptedException         If the stream fails while sending the packet
     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8.
     */
    @WorkerThread
    @NonNull
    public AdbStream openStream(String destination) throws IOException, InterruptedException {
        synchronized (mLock) {
            if (mAdbConnection != null && mAdbConnection.isConnected()) {
                try {
                    return mAdbConnection.open(destination);
                } catch (AdbPairingRequiredException e) {
                    throw new IllegalStateException(e);
                }
            }
            throw new IOException("Not connected to ADB.");
        }
    }

    /**
     * Opens an {@link AdbStream} object corresponding to the specified destination.
     * This routine will block until the connection completes.
     *
     * @param service The service to open. One of the services under {@link LocalServices.Services}.
     * @param args    Additional arguments supported by the service (see the corresponding constant to learn more).
     * @return AdbStream object corresponding to the specified destination
     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8
     * @throws IOException                  If the stream fails while sending the packet
     * @throws InterruptedException         If we are unable to wait for the connection to finish
     */
    @NonNull
    public AdbStream openStream(@LocalServices.Services int service, @NonNull String... args)
            throws IOException, InterruptedException {
        synchronized (mLock) {
            if (mAdbConnection != null && mAdbConnection.isConnected()) {
                try {
                    return mAdbConnection.open(service, args);
                } catch (AdbPairingRequiredException e) {
                    throw new IllegalStateException(e);
                }
            }
            throw new IOException("Not connected to ADB.");
        }
    }

    /**
     * Pair with an ADB daemon given port number and pairing code.
     *
     * @param port        Port number
     * @param pairingCode The six-digit pairing code as string
     * @return {@code true} if the pairing is successful and {@code false} otherwise.
     * @throws Exception If pairing failed for some reason.
     */
    @WorkerThread
    @RequiresApi(Build.VERSION_CODES.GINGERBREAD)
    public boolean pair(int port, @NonNull String pairingCode) throws Exception {
        return pair(mHostAddress, port, pairingCode);
    }

    /**
     * Pair with an ADB daemon given host address, port number and pairing code.
     *
     * @param host        Host address to use instead of taking it from the {@link #getHostAddress()}
     * @param port        Port number
     * @param pairingCode The six-digit pairing code as string
     * @return {@code true} if the pairing is successful and {@code false} otherwise.
     * @throws Exception If pairing failed for some reason.
     */
    @WorkerThread
    @RequiresApi(Build.VERSION_CODES.GINGERBREAD)
    public boolean pair(@NonNull String host, int port, @NonNull String pairingCode) throws Exception {
        synchronized (mLock) {
            KeyPair keyPair = getAdbKeyPair();
            try (PairingConnectionCtx pairingClient = new PairingConnectionCtx(Objects.requireNonNull(host), port,
                    StringCompat.getBytes(Objects.requireNonNull(pairingCode), "UTF-8"), keyPair, getDeviceName())) {
                // TODO: 5/12/21 Return true/false instead of only exceptions
                pairingClient.start();
            }
            return true;
        }
    }

    /**
     * Close the underlying {@link AdbConnection} and destroy the private key.
     *
     * @throws IOException If socket fails to close.
     */
    @Override
    public void close() throws IOException {
        try {
            getPrivateKey().destroy();
        } catch (DestroyFailedException | NoSuchMethodError e) {
            e.printStackTrace();
        }
        if (mAdbConnection != null) {
            mAdbConnection.close();
            mAdbConnection = null;
        }
    }

    @NonNull
    private KeyPair getAdbKeyPair() {
        return new KeyPair(Objects.requireNonNull(getPrivateKey()), Objects.requireNonNull(getCertificate()));
    }
}


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbAuthenticationFailedException.java
================================================
// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)

package io.github.muntashirakon.adb;

/**
 * Thrown when the ADB daemon rejects our initial authentication attempt, which typically means that the peer has not
 * previously saved our public key.
 */
// Copyright 2020 Sam Palmer
public class AdbAuthenticationFailedException extends RuntimeException {
    public AdbAuthenticationFailedException() {
        super("Initial authentication attempt rejected by peer.");
    }
}


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbConnection.java
================================================
// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)

package io.github.muntashirakon.adb;

import android.os.Build;
import android.util.Log;

import androidx.annotation.GuardedBy;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.Socket;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.security.auth.DestroyFailedException;

/**
 * This class represents an ADB connection.
 */
// Copyright 2013 Cameron Gutman
public class AdbConnection implements Closeable {
    public static final String TAG = AdbConnection.class.getSimpleName();

    /**
     * The underlying socket that this class uses to communicate with the target device.
     */
    @NonNull
    private final Socket mSocket;

    @NonNull
    private final String mHost;

    private final int mPort;

    private final int mApi;

    /**
     * The last allocated local stream ID. The ID chosen for the next stream will be this value + 1.
     */
    private int mLastLocalId;

    /**
     * The input stream that this class uses to read from the socket.
     */
    @GuardedBy("lock")
    @NonNull
    private final InputStream mPlainInputStream;

    /**
     * The output stream that this class uses to read from the socket.
     */
    @GuardedBy("lock")
    @NonNull
    private final OutputStream mPlainOutputStream;

    /**
     * The input stream that this class uses to read from the TLS socket.
     */
    @GuardedBy("lock")
    @Nullable
    private volatile InputStream mTlsInputStream;

    /**
     * The output stream that this class uses to read from the TLS socket.
     */
    @GuardedBy("lock")
    @Nullable
    private volatile OutputStream mTlsOutputStream;

    /**
     * The backend thread that handles responding to ADB packets.
     */
    @NonNull
    private final Thread mConnectionThread;

    /**
     * Specifies whether a CNXN has been attempted.
     */
    private volatile boolean mConnectAttempted;

    /**
     * Whether the connection thread should give up if the first authentication attempt fails.
     */
    private volatile boolean mAbortOnUnauthorised;

    /**
     * Whether the first authentication attempt failed and {@link #mAbortOnUnauthorised} was {@code true}.
     */
    private volatile boolean mAuthorisationFailed;

    /**
     * Specifies whether a CNXN packet has been received from the peer.
     */
    private volatile boolean mConnectionEstablished;

    /**
     * Exceptions that occur in {@link #createConnectionThread()}.
     */
    @Nullable
    private volatile Exception mConnectionException;

    /**
     * Specifies the maximum amount data that can be sent to the remote peer.
     * This is only valid after connect() returns successfully.
     */
    private volatile int mMaxData;

    private volatile int mProtocolVersion;

    @NonNull
    private final KeyPair mKeyPair;

    @NonNull
    private volatile String mDeviceName = "Unknown Device";

    /**
     * Specifies whether this connection has already sent a signed token.
     */
    private volatile boolean mSentSignature;

    /**
     * A hash map of our opened streams indexed by local ID.
     */
    @NonNull
    private final ConcurrentHashMap<Integer, AdbStream> mOpenedStreams;

    private volatile boolean mIsTls = false;

    @GuardedBy("lock")
    @NonNull
    private final Object mLock = new Object();

    /**
     * Creates a AdbConnection object associated with the socket and crypto object specified.
     *
     * @return A new AdbConnection object.
     * @throws IOException If there is a socket error
     */
    @WorkerThread
    @NonNull
    public static AdbConnection create(@NonNull String host, int port, @NonNull PrivateKey privateKey,
                                       @NonNull Certificate certificate)
            throws IOException {
        return create(host, port, privateKey, certificate, Build.VERSION_CODES.BASE);
    }

    /**
     * Creates a AdbConnection object associated with the socket and crypto object specified.
     *
     * @return A new AdbConnection object.
     * @throws IOException If there is a socket error
     */
    @WorkerThread
    @NonNull
    public static AdbConnection create(@NonNull String host, int port, @NonNull PrivateKey privateKey,
                                       @NonNull Certificate certificate, int api)
            throws IOException {
        return create(host, port, new KeyPair(Objects.requireNonNull(privateKey), Objects.requireNonNull(certificate)),
                api);
    }

    /**
     * Creates a AdbConnection object associated with the socket and crypto object specified.
     *
     * @return A new AdbConnection object.
     * @throws IOException If there is a socket error
     */
    @WorkerThread
    @NonNull
    static AdbConnection create(@NonNull String host, int port, @NonNull KeyPair keyPair, int api) throws IOException {
        return new AdbConnection(host, port, keyPair, api);
    }

    /**
     * Internal constructor to initialize some internal state
     */
    @WorkerThread
    private AdbConnection(@NonNull String host, int port, @NonNull KeyPair keyPair, int api) throws IOException {
        this.mHost = Objects.requireNonNull(host);
        this.mPort = port;
        this.mApi = api;
        this.mProtocolVersion = AdbProtocol.getProtocolVersion(mApi);
        this.mMaxData = AdbProtocol.getMaxData(api);
        this.mKeyPair = Objects.requireNonNull(keyPair);
        try {
            this.mSocket = new Socket(host, port);
        } catch (Throwable th) {
            //noinspection UnnecessaryInitCause
            throw (IOException) new IOException().initCause(th);
        }
        this.mPlainInputStream = mSocket.getInputStream();
        this.mPlainOutputStream = mSocket.getOutputStream();

        // Disable Nagle because we're sending tiny packets
        mSocket.setTcpNoDelay(true);

        this.mOpenedStreams = new ConcurrentHashMap<>();
        this.mLastLocalId = 0;
        this.mConnectionThread = createConnectionThread();
    }

    @GuardedBy("lock")
    @NonNull
    private InputStream getInputStream() {
        return mIsTls ? Objects.requireNonNull(mTlsInputStream) : mPlainInputStream;
    }

    @GuardedBy("lock")
    @NonNull
    private OutputStream getOutputStream() {
        return mIsTls ? Objects.requireNonNull(mTlsOutputStream) : mPlainOutputStream;
    }

    /**
     * Creates a new connection thread.
     *
     * @return A new connection thread.
     */
    @NonNull
    private Thread createConnectionThread() {
        return new Thread(() -> {
            loop:
            while (!mConnectionThread.isInterrupted()) {
                try {
                    // Read and parse a message off the socket's input stream
                    AdbProtocol.Message msg = AdbProtocol.Message.parse(getInputStream(), mProtocolVersion, mMaxData);

                    switch (msg.command) {
                        // Stream-oriented commands
                        case AdbProtocol.A_OKAY:
                        case AdbProtocol.A_WRTE:
                        case AdbProtocol.A_CLSE: {
                            // Ignore all packets when not connected
                            if (!mConnectionEstablished) {
                                continue;
                            }

                            // Get the stream object corresponding to the packet
                            AdbStream waitingStream = mOpenedStreams.get(msg.arg1);
                            if (waitingStream == null) {
                                continue;
                            }

                            synchronized (waitingStream) {
                                if (msg.command == AdbProtocol.A_OKAY) {
                                    // We're ready for writes
                                    waitingStream.updateRemoteId(msg.arg0);
                                    waitingStream.readyForWrite();

                                    // Notify an open/write
                                    waitingStream.notify();
                                } else if (msg.command == AdbProtocol.A_WRTE) {
                                    // Got some data from our partner
                                    waitingStream.addPayload(msg.payload);

                                    // Tell it we're ready for more
                                    waitingStream.sendReady();
                                } else { // if (msg.command == AdbProtocol.A_CLSE) {
                                    mOpenedStreams.remove(msg.arg1);
                                    // Notify readers and writers
                                    waitingStream.notifyClose(true);
                                }
                            }
                            break;
                        }
                        case AdbProtocol.A_STLS: {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                                sendPacket(AdbProtocol.generateStls());

                                SSLContext sslContext = SslUtils.getSslContext(mKeyPair);
                                SSLSocket tlsSocket = (SSLSocket) sslContext.getSocketFactory()
                                        .createSocket(mSocket, mHost, mPort, true);
                                tlsSocket.startHandshake();
                                Log.d(TAG, "Handshake succeeded.");

                                synchronized (AdbConnection.this) {
                                    mTlsInputStream = tlsSocket.getInputStream();
                                    mTlsOutputStream = tlsSocket.getOutputStream();
                                    mIsTls = true;
                                }
                            }
                            break;
                        }
                        case AdbProtocol.A_AUTH: {
                            if (mIsTls) {
                                break;
                            }
                            if (msg.arg0 != AdbProtocol.ADB_AUTH_TOKEN) {
                                break;
                            }
                            byte[] packet;
                            // This is an authentication challenge
                            if (mSentSignature) {
                                if (mAbortOnUnauthorised) {
                                    mAuthorisationFailed = true;
                                    break loop;
                                }

                                // We've already tried our signature, so send our public key
                                packet = AdbProtocol.generateAuth(AdbProtocol.ADB_AUTH_RSAPUBLICKEY, AndroidPubkey
                                        .encodeWithName((RSAPublicKey) mKeyPair.getPublicKey(), mDeviceName));
                            } else {
                                // Sign the token
                                packet = AdbProtocol.generateAuth(AdbProtocol.ADB_AUTH_SIGNATURE, AndroidPubkey
                                        .adbAuthSign(mKeyPair.getPrivateKey(), msg.payload));
                                mSentSignature = true;
                            }

                            // Write the AUTH reply
                            sendPacket(packet);
                            break;
                        }
                        case AdbProtocol.A_CNXN: {
                            synchronized (AdbConnection.this) {
                                mProtocolVersion = msg.arg0;
                                mMaxData = msg.arg1;
                                mConnectionEstablished = true;
                                AdbConnection.this.notifyAll();
                            }
                            break;
                        }
                        case AdbProtocol.A_OPEN:
                        case AdbProtocol.A_SYNC:
                        default:
                            Log.e(TAG, String.format("Unrecognized command = 0x%x", msg.command));
                            // Unrecognized packet, just drop it
                            break;
                    }
                } catch (Exception e) {
                    mConnectionException = e;
                    e.printStackTrace();
                    // The cleanup is taken care of by a combination of this thread and close()
                    break;
                }
            }

            // This thread takes care of cleaning up pending streams
            synchronized (AdbConnection.this) {
                cleanupStreams();
                AdbConnection.this.notifyAll();
                mConnectionEstablished = false;
                mConnectAttempted = false;
            }
        });
    }

    /**
     * Set a name for the device. Default is “Unknown Device”.
     *
     * @param deviceName Name of the device, could be the app label, hostname or user@hostname.
     */
    public void setDeviceName(@NonNull String deviceName) {
        this.mDeviceName = Objects.requireNonNull(deviceName);
    }

    /**
     * Get the version of the ADB protocol supported by the ADB daemon. The result may depend on the API version
     * specified and whether the connection has been established. In API 29 (Android 9) or later, the daemon returns
     * {@link AdbProtocol#A_VERSION_SKIP_CHECKSUM} regardless of the protocol used to create the connection. So, if
     * {@link #mApi} is set to API 28 or earlier but the OS version is Android 9 or later, before establishing the
     * connection, it returns {@link AdbProtocol#A_VERSION_MIN}, and after establishing the connection, it returns
     * {@link AdbProtocol#A_VERSION_SKIP_CHECKSUM}. In other cases, it always returns {@link AdbProtocol#A_VERSION_MIN}.
     *
     * @see #isConnectionEstablished()
     */
    public int getProtocolVersion() {
        return mProtocolVersion;
    }

    /**
     * Get the max data size supported by the ADB daemon. A connection have to be attempted before calling this method
     * and shall be blocked if the connection is in progress.
     *
     * @return The maximum data size indicated in the CONNECT packet.
     * @throws InterruptedException        If a connection cannot be waited on.
     * @throws IOException                 if the connection fails.
     * @throws AdbPairingRequiredException If ADB lacks pairing
     */
    public int getMaxData() throws InterruptedException, IOException, AdbPairingRequiredException {
        if (!mConnectAttempted) {
            throw new IllegalStateException("connect() must be called first");
        }

        waitForConnection(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

        return mMaxData;
    }

    /**
     * Whether a connection has been established. A connection has been established if a CONNECT request has been
     * received from the ADB daemon.
     */
    public boolean isConnectionEstablished() {
        return mConnectionEstablished;
    }

    /**
     * Whether the underlying socket is connected to an ADB daemon and is not in a closed state.
     */
    public boolean isConnected() {
        return !mSocket.isClosed() && mSocket.isConnected();
    }

    /**
     * Same as {@link #connect(long, TimeUnit, boolean)} without throwing anything if the first authentication attempt
     * fails.
     *
     * @return {@code true} if the connection was established, or {@code false} if the connection timed out
     * @throws IOException                 If the socket fails while connecting
     * @throws InterruptedException        If timeout has reached
     * @throws AdbPairingRequiredException If ADB lacks pairing
     */
    public boolean connect() throws IOException, InterruptedException, AdbPairingRequiredException {
        return connect(Long.MAX_VALUE, TimeUnit.MILLISECONDS, false);
    }

    /**
     * Connects to the remote device. This routine will block until the connection completes or the timeout elapses.
     *
     * @param timeout             the time to wait for the lock
     * @param unit                the time unit of the timeout argument
     * @param throwOnUnauthorised Whether to throw an {@link AdbAuthenticationFailedException}
     *                            if the peer rejects out first authentication attempt
     * @return {@code true} if the connection was established, or {@code false} if the connection timed out
     * @throws IOException                      If the socket fails while connecting
     * @throws InterruptedException             If timeout has reached
     * @throws AdbAuthenticationFailedException If {@code throwOnUnauthorised} is {@code true} and the peer rejects the
     *                                          first authentication attempt, which indicates that the peer has not
     *                                          saved the public key from a previous connection
     * @throws AdbPairingRequiredException      If ADB lacks pairing
     */
    public boolean connect(long timeout, @NonNull TimeUnit unit, boolean throwOnUnauthorised)
            throws IOException, InterruptedException, AdbAuthenticationFailedException, AdbPairingRequiredException {
        if (mConnectionEstablished) {
            throw new IllegalStateException("Already connected");
        }

        // Send CONNECT
        sendPacket(AdbProtocol.generateConnect(mApi));

        // Start the connection thread to respond to the peer
        mConnectAttempted = true;
        mAbortOnUnauthorised = throwOnUnauthorised;
        mAuthorisationFailed = false;
        mConnectionThread.start();

        return waitForConnection(timeout, Objects.requireNonNull(unit));
    }

    /**
     * Opens an {@link AdbStream} object corresponding to the specified destination.
     * This routine will block until the connection completes.
     *
     * @param service The service to open. One of the services under {@link LocalServices.Services}.
     * @param args    Additional arguments supported by the service (see the corresponding constant to learn more).
     * @return AdbStream object corresponding to the specified destination
     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8
     * @throws IOException                  If the stream fails while sending the packet
     * @throws InterruptedException         If we are unable to wait for the connection to finish
     * @throws AdbPairingRequiredException  If ADB lacks pairing
     */
    @NonNull
    public AdbStream open(@LocalServices.Services int service, @NonNull String... args)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        if (service < LocalServices.SERVICE_FIRST || service > LocalServices.SERVICE_LAST) {
            throw new IllegalArgumentException("Invalid service: " + service);
        }
        return open(LocalServices.getDestination(service, args));
    }

    /**
     * Opens an AdbStream object corresponding to the specified destination.
     * This routine will block until the connection completes.
     *
     * @param destination The destination to open on the target
     * @return AdbStream object corresponding to the specified destination
     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8
     * @throws IOException                  If the stream fails while sending the packet
     * @throws InterruptedException         If we are unable to wait for the connection to finish
     * @throws AdbPairingRequiredException  If ADB lacks pairing
     */
    @NonNull
    public AdbStream open(@NonNull String destination)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        int localId = ++mLastLocalId;

        if (!mConnectAttempted) {
            throw new IllegalStateException("connect() must be called first");
        }

        waitForConnection(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

        // Add this stream to this list of half-open streams
        AdbStream stream = new AdbStream(this, localId);
        mOpenedStreams.put(localId, stream);

        // Send OPEN
        sendPacket(AdbProtocol.generateOpen(localId, Objects.requireNonNull(destination)));

        // Wait for the connection thread to receive the OKAY
        synchronized (stream) {
            stream.wait();
        }

        // Check if the OPEN request was rejected
        if (stream.isClosed()) {
            mOpenedStreams.remove(localId);
            throw new ConnectException("Stream open actively rejected by remote peer.");
        }

        return stream;
    }

    private boolean waitForConnection(long timeout, @NonNull TimeUnit unit)
            throws InterruptedException, IOException, AdbPairingRequiredException {
        synchronized (this) {
            // Block if a connection is pending, but not yet complete
            long timeoutEndMillis = System.currentTimeMillis() + Objects.requireNonNull(unit).toMillis(timeout);
            while (!mConnectionEstablished && mConnectAttempted && timeoutEndMillis - System.currentTimeMillis() > 0) {
                wait(timeoutEndMillis - System.currentTimeMillis());
            }

            if (!mConnectionEstablished) {
                if (mConnectAttempted) {
                    return false;
                } else if (mAuthorisationFailed) {
                    // The peer may not have saved the public key in the past connections, or they've been removed.
                    throw new AdbAuthenticationFailedException();
                } else {
                    Exception connectionException = mConnectionException;
                    if (connectionException != null) {
                        if (connectionException instanceof javax.net.ssl.SSLProtocolException) {
                            String message = connectionException.getMessage();
                            if (message != null && message.contains("protocol error")) {
                                throw (AdbPairingRequiredException) (new AdbPairingRequiredException("ADB pairing is required.").initCause(connectionException));
                            }
                        }
                    }
                    throw new IOException("Connection failed");
                }
            }
        }

        return true;
    }

    /**
     * This function terminates all I/O on streams associated with this ADB connection
     */
    private void cleanupStreams() {
        // Close all streams on this connection
        for (AdbStream s : mOpenedStreams.values()) {
            try {
                s.close();
            } catch (IOException ignored) {
            }
        }
        mOpenedStreams.clear();
    }

    /**
     * This routine closes the Adb connection and underlying socket
     *
     * @throws IOException if the socket fails to close
     */
    @Override
    public void close() throws IOException {
        // Closing the socket will kick the connection thread
        mSocket.close();

        // Wait for the connection thread to die
        mConnectionThread.interrupt();
        try {
            mConnectionThread.join();
        } catch (InterruptedException ignored) {
        }

        // Destroy keypair
        try {
            mKeyPair.destroy();
        } catch (DestroyFailedException ignore) {
        }
    }

    void sendPacket(byte[] packet) throws IOException {
        synchronized (mLock) {
            OutputStream os = getOutputStream();
            os.write(packet);
            os.flush();
        }
    }

    void flushPacket() throws IOException {
        synchronized (mLock) {
            getOutputStream().flush();
        }
    }

    public static class Builder {
        private String mHost = "127.0.0.1";
        private int mPort = 5555;
        private int mApi = Build.VERSION_CODES.BASE;
        private PrivateKey mPrivateKey;
        private Certificate mCertificate;
        private KeyPair mKeyPair;
        private String mDeviceName;

        public Builder() {
        }

        public Builder(String host, int port) {
            mHost = host;
            mPort = port;
        }

        /**
         * Set host address. Default is 127.0.0.1
         */
        public Builder setHost(String host) {
            this.mHost = host;
            return this;
        }

        /**
         * Set port number. Default is 5555.
         */
        public Builder setPort(int port) {
            this.mPort = port;
            return this;
        }

        /**
         * Set a name for the device. Default is “Unknown Device”.
         *
         * @param deviceName Name of the device, could be the app label, hostname or user@hostname.
         */
        public Builder setDeviceName(String deviceName) {
            this.mDeviceName = deviceName;
            return this;
        }

        /**
         * Set Android API (i.e. SDK) version for this connection. If the ADB daemon and the client are located in the
         * same device, the value should be {@link Build.VERSION#SDK_INT} in order to improve performance as well as
         * security.
         *
         * @param api The API version, default is {@link Build.VERSION_CODES#BASE}.
         */
        public Builder setApi(int api) {
            this.mApi = api;
            return this;
        }

        /**
         * Set generated/stored private key.
         */
        public Builder setPrivateKey(PrivateKey privateKey) {
            this.mPrivateKey = privateKey;
            return this;
        }

        /**
         * Set public key wrapped around a certificate
         */
        public Builder setCertificate(Certificate certificate) {
            this.mCertificate = certificate;
            return this;
        }

        Builder setKeyPair(KeyPair keyPair) {
            this.mKeyPair = keyPair;
            return this;
        }

        /**
         * Creates a new {@link AdbConnection} associated with the socket and crypto object specified.
         *
         * @throws IOException If there was an error while establishing a socket connection
         */
        public AdbConnection build() throws IOException {
            if (mKeyPair == null) {
                if (mPrivateKey == null || mCertificate == null) {
                    throw new UnsupportedOperationException("Private key and certificate must be set.");
                }
                mKeyPair = new KeyPair(mPrivateKey, mCertificate);
            }
            AdbConnection adbConnection = create(mHost, mPort, mKeyPair, mApi);
            if (mDeviceName != null) {
                adbConnection.setDeviceName(mDeviceName);
            }
            return adbConnection;
        }

        /**
         * Same as {@link #connect(long, TimeUnit, boolean)} without throwing anything if the first authentication
         * attempt fails.
         *
         * @return The underlying {@link AdbConnection}
         * @throws IOException                 If the socket fails while connecting
         * @throws InterruptedException        If timeout has reached
         * @throws AdbPairingRequiredException If ADB lacks pairing
         */
        public AdbConnection connect() throws IOException, InterruptedException, AdbPairingRequiredException {
            AdbConnection adbConnection = build();
            if (adbConnection.connect()) {
                throw new IOException("Unable to establish a new connection.");
            }
            return adbConnection;
        }

        /**
         * Connects to the remote device. This routine will block until the connection completes or the timeout elapses.
         *
         * @param timeout             the time to wait for the lock
         * @param unit                the time unit of the timeout argument
         * @param throwOnUnauthorised Whether to throw an {@link AdbAuthenticationFailedException}
         *                            if the peer rejects out first authentication attempt
         * @return {@code true} if the connection was established, or {@code false} if the connection timed out
         * @throws IOException                      If the socket fails while connecting
         * @throws InterruptedException             If timeout has reached
         * @throws AdbAuthenticationFailedException If {@code throwOnUnauthorised} is {@code true} and the peer rejects
         *                                          the first authentication attempt, which indicates that the peer has
         *                                          not saved the public key from a previous connection
         * @throws AdbPairingRequiredException      If ADB lacks pairing
         */
        public AdbConnection connect(long timeout, @NonNull TimeUnit unit, boolean throwOnUnauthorised)
                throws IOException, InterruptedException, AdbPairingRequiredException {
            AdbConnection adbConnection = build();
            if (adbConnection.connect(timeout, unit, throwOnUnauthorised)) {
                throw new IOException("Unable to establish a new connection.");
            }
            return adbConnection;
        }
    }
}


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbInputStream.java
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

package io.github.muntashirakon.adb;

import java.io.IOException;
import java.io.InputStream;

public class AdbInputStream extends InputStream {
    public AdbStream mAdbStream;

    public AdbInputStream(AdbStream adbStream) {
        this.mAdbStream = adbStream;
    }

    @Override
    public int read() throws IOException {
        byte[] bytes = new byte[1];
        if (read(bytes) == -1) {
            return -1;
        }
        return bytes[0];
    }

    @Override
    public int read(byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (mAdbStream.isClosed()) return -1;
        return mAdbStream.read(b, off, len);
    }

    @Override
    public void close() {
    }

    @Override
    public int available() throws IOException {
        return mAdbStream.available();
    }
}


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbOutputStream.java
================================================
// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0

package io.github.muntashirakon.adb;

import java.io.IOException;
import java.io.OutputStream;

public class AdbOutputStream extends OutputStream {
    private final AdbStream mAdbStream;

    public AdbOutputStream(AdbStream adbStream) {
        this.mAdbStream = adbStream;
    }

    @Override
    public void write(int b) throws IOException {
        write(new byte[]{(byte) (b & 0xFF)});
    }

    @Override
    public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        mAdbStream.write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        mAdbStream.flush();
    }

    @Override
    public void close() throws IOException {
        flush();
    }
}


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbPairingRequiredException.java
================================================
package io.github.muntashirakon.adb;

public class AdbPairingRequiredException extends Exception {
    public AdbPairingRequiredException(String message) {
        super(message);
    }
}


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbProtocol.java
================================================
// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)

package io.github.muntashirakon.adb;

import android.os.Build;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

/**
 * This class provides useful functions and fields for ADB protocol details.
 */
// Copyright 2013 Cameron Gutman
final class AdbProtocol {
    /**
     * The length of the ADB message header
     */
    public static final int ADB_HEADER_LENGTH = 24;

    /**
     * SYNC(online, sequence, "")
     *
     * @deprecated Obsolete, no longer used. Never used on the client side.
     */
    public static final int A_SYNC = 0x434e5953;

    /**
     * CNXN is the connect message. No messages (except AUTH) are valid before this message is received.
     */
    public static final int A_CNXN = 0x4e584e43;

    /**
     * The payload sent with the CONNECT message.
     */
    public static final byte[] SYSTEM_IDENTITY_STRING_HOST = StringCompat.getBytes("host::\0", "UTF-8");

    /**
     * AUTH is the authentication message. It is part of the RSA public key authentication added in Android 4.2.2
     * ({@link Build.VERSION_CODES#JELLY_BEAN_MR1}).
     */
    public static final int A_AUTH = 0x48545541;

    /**
     * OPEN is the open stream message. It is sent to open a new stream on the target device.
     */
    public static final int A_OPEN = 0x4e45504f;

    /**
     * OKAY is a success message. It is sent when a write is processed successfully.
     */
    public static final int A_OKAY = 0x59414b4f;

    /**
     * CLSE is the close stream message. It is sent to close an existing stream on the target device.
     */
    public static final int A_CLSE = 0x45534c43;

    /**
     * WRTE is the write stream message. It is sent with a payload that is the data to write to the stream.
     */
    public static final int A_WRTE = 0x45545257;

    /**
     * STLS is the Stream-based TLS1.3 authentication method, added in Android 9 ({@link Build.VERSION_CODES#P}).
     */
    public static final int A_STLS = 0x534c5453;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({A_SYNC, A_CNXN, A_OPEN, A_OKAY, A_CLSE, A_WRTE, A_AUTH, A_STLS})
    private @interface Command {
    }

    /**
     * Original payload size
     */
    public static final int MAX_PAYLOAD_V1 = 4 * 1024;
    /**
     * Supported payload size since Android 7 (N)
     */
    public static final int MAX_PAYLOAD_V2 = 256 * 1024;
    /**
     * Supported payload size since Android 9 (P)
     */
    public static final int MAX_PAYLOAD_V3 = 1024 * 1024;
    /**
     * Maximum supported payload size is set to the original to support all APIs
     */
    public static final int MAX_PAYLOAD = MAX_PAYLOAD_V1;

    /**
     * The original version of the ADB protocol
     */
    public static final int A_VERSION_MIN = 0x01000000;
    /**
     * The new version of the ADB protocol introduced in Android 9 (P) with the introduction of TLS
     */
    public static final int A_VERSION_SKIP_CHECKSUM = 0x01000001;
    public static final int A_VERSION = A_VERSION_MIN;

    /**
     * The current version of the Stream-based TLS
     */
    public static final int A_STLS_VERSION_MIN = 0x01000000;
    public static final int A_STLS_VERSION = A_STLS_VERSION_MIN;

    /**
     * This authentication type represents a SHA1 hash to sign.
     */
    public static final int ADB_AUTH_TOKEN = 1;

    /**
     * This authentication type represents the signed SHA1 hash.
     */
    public static final int ADB_AUTH_SIGNATURE = 2;

    /**
     * This authentication type represents an RSA public key.
     */
    public static final int ADB_AUTH_RSAPUBLICKEY = 3;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({ADB_AUTH_TOKEN, ADB_AUTH_SIGNATURE, ADB_AUTH_RSAPUBLICKEY})
    private @interface AuthType {
    }

    public static int getMaxData(int api) {
        if (api >= Build.VERSION_CODES.P) {
            return MAX_PAYLOAD_V3;
        }
        if (api >= Build.VERSION_CODES.N) {
            return MAX_PAYLOAD_V2;
        }
        return MAX_PAYLOAD_V1;
    }

    public static int getProtocolVersion(int api) {
        if (api >= Build.VERSION_CODES.P) {
            return A_VERSION_SKIP_CHECKSUM;
        }
        return A_VERSION_MIN;
    }

    /**
     * This function performs a checksum on the ADB payload data.
     *
     * @param data The data
     * @return The checksum of the data
     */
    private static int getPayloadChecksum(@NonNull byte[] data) {
        return getPayloadChecksum(data, 0, data.length);
    }

    /**
     * This function performs a checksum on the ADB payload data.
     *
     * @param data   The data
     * @param offset The start offset in the data
     * @param length The number of bytes to take from the data
     * @return The checksum of the data
     */
    private static int getPayloadChecksum(@NonNull byte[] data, int offset, int length) {
        int checksum = 0;
        for (int i = offset; i < offset + length; ++i) {
            checksum += data[i] & 0xFF;
        }
        return checksum;
    }

    /**
     * This function generates an ADB message given the fields.
     *
     * @param command Command identifier constant
     * @param arg0    First argument
     * @param arg1    Second argument
     * @param data    The data
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateMessage(@Command int command, int arg0, int arg1, @Nullable byte[] data) {
        return generateMessage(command, arg0, arg1, data, 0, data == null ? 0 : data.length);
    }

    /**
     * This function generates an ADB message given the fields.
     *
     * @param command Command identifier constant
     * @param arg0    First argument
     * @param arg1    Second argument
     * @param data    The data
     * @param offset  The start offset in the data
     * @param length  The number of bytes to take from the data
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateMessage(@Command int command, int arg0, int arg1, @Nullable byte[] data, int offset, int length) {
        // Protocol as defined at https://github.com/aosp-mirror/platform_system_core/blob/6072de17cd812daf238092695f26a552d3122f8c/adb/protocol.txt
        // struct message {
        //     unsigned command;       // command identifier constant
        //     unsigned arg0;          // first argument
        //     unsigned arg1;          // second argument
        //     unsigned data_length;   // length of payload (0 is allowed)
        //     unsigned data_check;    // checksum of data payload
        //     unsigned magic;         // command ^ 0xffffffff
        // };

        ByteBuffer message;

        if (data != null) {
            message = ByteBuffer.allocate(ADB_HEADER_LENGTH + length).order(ByteOrder.LITTLE_ENDIAN);
        } else {
            message = ByteBuffer.allocate(ADB_HEADER_LENGTH).order(ByteOrder.LITTLE_ENDIAN);
        }

        message.putInt(command);
        message.putInt(arg0);
        message.putInt(arg1);

        if (data != null) {
            message.putInt(length);
            message.putInt(getPayloadChecksum(data, offset, length));
        } else {
            message.putInt(0);
            message.putInt(0);
        }

        message.putInt(~command);

        if (data != null) {
            message.put(data, offset, length);
        }

        return message.array();
    }

    /**
     * Generates a CONNECT message for a given API.
     * <p>
     * CONNECT(version, maxdata, "system-identity-string")
     *
     * @param api API version
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateConnect(int api) {
        return generateMessage(A_CNXN, getProtocolVersion(api), getMaxData(api), SYSTEM_IDENTITY_STRING_HOST);
    }

    /**
     * Generates an AUTH message with the specified type and payload.
     * <p>
     * AUTH(type, 0, "data")
     *
     * @param type Authentication type (see ADB_AUTH_* constants)
     * @param data The data
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateAuth(@AuthType int type, byte[] data) {
        return generateMessage(A_AUTH, type, 0, data);
    }

    /**
     * Generates an STLS message with default parameters.
     * <p>
     * STLS(version, 0, "")
     *
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateStls() {
        return generateMessage(A_STLS, A_STLS_VERSION, 0, null);
    }

    /**
     * Generates an OPEN stream message with the specified local ID and destination.
     * <p>
     * OPEN(local-id, 0, "destination")
     *
     * @param localId     A unique local ID identifying the stream
     * @param destination The destination of the stream on the target
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateOpen(int localId, @NonNull String destination) {
        ByteBuffer bbuf = ByteBuffer.allocate(destination.length() + 1);
        bbuf.put(StringCompat.getBytes(destination, "UTF-8"));
        bbuf.put((byte) 0);
        return generateMessage(A_OPEN, localId, 0, bbuf.array());
    }

    /**
     * Generates a WRITE stream message with the specified IDs and payload.
     * <p>
     * WRITE(local-id, remote-id, "data")
     *
     * @param localId  The unique local ID of the stream
     * @param remoteId The unique remote ID of the stream
     * @param data     The data
     * @param offset   The start offset in the data
     * @param length   The number of bytes to take from the data
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateWrite(int localId, int remoteId, byte[] data, int offset, int length) {
        return generateMessage(A_WRTE, localId, remoteId, data, offset, length);
    }

    /**
     * Generates a CLOSE stream message with the specified IDs.
     * <p>
     * CLOSE(local-id, remote-id, "")
     *
     * @param localId  The unique local ID of the stream
     * @param remoteId The unique remote ID of the stream
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateClose(int localId, int remoteId) {
        return generateMessage(A_CLSE, localId, remoteId, null);
    }

    /**
     * Generates an OKAY/READY message with the specified IDs.
     * <p>
     * READY(local-id, remote-id, "")
     *
     * @param localId  The unique local ID of the stream
     * @param remoteId The unique remote ID of the stream
     * @return Byte array containing the message
     */
    @NonNull
    public static byte[] generateReady(int localId, int remoteId) {
        return generateMessage(A_OKAY, localId, remoteId, null);
    }

    /**
     * This class provides an abstraction for the ADB message format.
     */
    static final class Message {
        /**
         * The command field of the message
         */
        @Command
        public final int command;
        /**
         * The arg0 field of the message
         */
        public final int arg0;
        /**
         * The arg1 field of the message
         */
        public final int arg1;
        /**
         * The payload length field of the message
         */
        public final int dataLength;
        /**
         * The checksum field of the message
         */
        public final int dataCheck;
        /**
         * The magic field of the message
         */
        public final int magic;
        /**
         * The payload of the message
         */
        public byte[] payload;

        /**
         * Read and parse an ADB message from the supplied input stream.
         * <p>
         * <b>Note:</b> If data is corrupted, the connection has to be closed immediately to avoid inconsistencies.
         *
         * @param in InputStream object to read data from
         * @return An AdbMessage object represented the message read
         * @throws IOException              If the stream fails while reading.
         * @throws StreamCorruptedException If data is corrupted.
         */
        @NonNull
        public static Message parse(@NonNull InputStream in, int protocolVersion, int maxData) throws IOException {
            ByteBuffer header = ByteBuffer.allocate(ADB_HEADER_LENGTH).order(ByteOrder.LITTLE_ENDIAN);

            // Read header
            int dataRead = 0;
            do {
                int bytesRead = in.read(header.array(), dataRead, ADB_HEADER_LENGTH - dataRead);
                if (bytesRead < 0) {
                    throw new IOException("Stream closed");
                } else dataRead += bytesRead;
            } while (dataRead < ADB_HEADER_LENGTH);

            Message msg = new Message(header);

            // Validate header
            if (msg.command != (~msg.magic)) { // magic = cmd ^ 0xFFFFFFFF
                throw new StreamCorruptedException(String.format("Invalid header: Invalid magic 0x%x.", msg.magic));
            }
            if (msg.command != A_SYNC && msg.command != A_CNXN && msg.command != A_OPEN && msg.command != A_OKAY
                    && msg.command != A_CLSE && msg.command != A_WRTE && msg.command != A_AUTH
                    && msg.command != A_STLS) {
                throw new StreamCorruptedException(String.format("Invalid header: Invalid command 0x%x.", msg.command));
            }
            if (msg.dataLength < 0 || msg.dataLength > maxData) {
                throw new StreamCorruptedException(String.format("Invalid header: Invalid data length %d", msg.dataLength));
            }

            if (msg.dataLength == 0) {
                // No payload supplied, return immediately
                return msg;
            }

            // Read payload
            msg.payload = new byte[msg.dataLength];
            dataRead = 0;
            do {
                int bytesRead = in.read(msg.payload, dataRead, msg.dataLength - dataRead);
                if (bytesRead < 0) {
                    throw new IOException("Stream closed");
                } else dataRead += bytesRead;
            } while (dataRead < msg.dataLength);

            // Verify payload
            if ((protocolVersion <= A_VERSION_MIN || (msg.command == A_CNXN && msg.arg0 <= A_VERSION_MIN))
                    && getPayloadChecksum(msg.payload) != msg.dataCheck) {
                // Checksum verification failed
                throw new StreamCorruptedException("Invalid header: Checksum mismatched.");
            }

            return msg;
        }

        private Message(@NonNull ByteBuffer header) {
            command = header.getInt();
            arg0 = header.getInt();
            arg1 = header.getInt();
            dataLength = header.getInt();
            dataCheck = header.getInt();
            magic = header.getInt();
        }

        @NonNull
        @Override
        public String toString() {
            String tag;
            switch (command) {
                case A_SYNC:
                    tag = "SYNC";
                    break;
                case A_CNXN:
                    tag = "CNXN";
                    break;
                case A_OPEN:
                    tag = "OPEN";
                    break;
                case A_OKAY:
                    tag = "OKAY";
                    break;
                case A_CLSE:
                    tag = "CLSE";
                    break;
                case A_WRTE:
                    tag = "WRTE";
                    break;
                case A_AUTH:
                    tag = "AUTH";
                    break;
                case A_STLS:
                    tag = "STLS";
                    break;
                default:
                    tag = "????";
                    break;
            }
            return "Message{" +
                    "command=" + tag +
                    ", arg0=0x" + Integer.toHexString(arg0) +
                    ", arg1=0x" + Integer.toHexString(arg1) +
                    ", payloadLength=" + dataLength +
                    ", checksum=" + dataCheck +
                    ", magic=0x" + Integer.toHexString(magic) +
                    ", payload=" + Arrays.toString(payload) +
                    '}';
        }
    }

}


================================================
FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbStream.java
================================================
// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)

package io.github.muntashirakon.adb;

import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This class abstracts the underlying ADB streams
 */
// Copyright 2013 Cameron Gutman
public class AdbStream implements Closeable {

    /**
     * The AdbConnection object that the stream communicates over
     */
    private final AdbConnection mAdbConnection;

    /**
     * The local ID of the stream
     */
    private final int mLocalId;

    /**
     * The remote ID of the stream
     */
    private volatile int mRemoteId;

    /**
     * Indicates whether WRTE is currently allowed
     */
    private final AtomicBoolean mWriteReady;

    /**
     * A queue of data from the target's WRTE packets
     */
    private final Queue<byte[]> mReadQueue;

    /**
     * Store data received from the first WRTE packet in order to support buffering.
     */
    private final ByteBuffer mReadBuffer;

    /**
     * Indicates whether the connection is closed already
     */
    private volatile boolean mIsClosed;

    /**
     * Whether the remote peer has closed but we still have unread data in the queue
     */
    private volatile boolean mPendingClose;

    /**
     * Creates a new AdbStream object on the specified AdbConnection
     * with the given local ID.
     *
     * @param adbConnection AdbConnection that this stream is running on
     * @param localId       Local ID of the stream
     */
    AdbStream(AdbConnection adbConnection, int localId)
            throws IOException, InterruptedException, AdbPairingRequiredException {
        this.mAdbConnection = adbConnection;
        this.mLocalId = localId;
        this.mReadQueue = new ConcurrentLinkedQueue<>();
        this.mReadBuffer = (ByteBuffer) ByteBuffer.allocate(adbConnection.getMaxData()).flip();
        this.mWriteReady = new AtomicBoolean(false);
        this.mIsClosed = false;
    }

    public AdbInputStream openInputStream() {
        return new AdbInputStream(this);
    }

    public AdbOutputStream openOutputStream() {
        return new AdbOutputStream(this);
    }

    /**
     * Called by the connection thread to indicate newly received data.
     *
     * @param payload Data inside the WRTE message
     */
    void addPayload(byte[] payload) {
        synchronized (mReadQueue) {
            mReadQueue.add(payload);
            mReadQueue.notifyAll();
        }
    }

    /**
     * Called by the connection thread to send an OKAY packet, allowing the
     * other side to continue transmission.
     *
     * @throws IOException If the connection fails while sending the packet
     */
    void sendReady() throws IOException {
        // Generate and send a OKAY packet
        mAdbConnection.sendPacket(AdbProtocol.generateReady(mLocalId, mRemoteId));
    }

    /**
     * Called by the connection thread to update the remote ID for this stream
     *
     * @param remoteId New remote ID
     */
    void updateRemoteId(int remoteId) {
        this.mRemoteId = remoteId;
    }

    /**
     * Called by the connection thread to indicate the stream is okay to send data.
     */
    void readyForWrite() {
        mWriteReady.set(true);
    }

    /**
     * Called by the connection thread to notify that the stream was closed by the peer.
     */
    void notifyClose(boolean closedByPeer) {
        // We don't call close() because it sends another CLSE
        if (closedByPeer && !mReadQueue.isEmpty()) {
            // The remote peer closed the stream, but we haven't finished reading the remaining data
            mPendingClose = true;
        } else {
            mIsClosed = true;
        }

        // Notify readers and writers
        synchronized (this) {
            notifyAll();
        }
        synchronized (mReadQueue) {
            mReadQueue.notifyAll();
        }
    }

    /**
     * Read bytes from the ADB daemon.
     *
     * @return the next byte of data, or {@code -1} if the end of the stream is reached.
     * @throws IOException If the stream fails while waiting
     */
    public int read(byte[] bytes, int offset, int length) throws IOException {
        if (mReadBuffer.hasRemaining()) {
            return readBuffer(bytes, offset, length);
        }
        // Buffer has no data, grab from the queue
        synchronized (mReadQueue) {
            byte[] data;
            // Wait for the connection to close or data to be received
            while ((data = mReadQueue.poll()) == null && !mIsClosed) {
                try {
                    mReadQueue.wait();
                } catch (InterruptedException e) {
                    //noinspection UnnecessaryInitCause
                    throw (IOException) new IOException().initCause(e);
                }
            }
            // Add data to the buffer
            if (data != null) {
                mReadBuffer.clear();
                mReadBuffer.put(data);
                mReadBuffer.flip();
                if (mReadBuffer.hasRemaining()) {
                    return readBuffer(bytes, offset, length);
                }
            }

            if (mIsClosed) {
                throw new IOException("Stream closed.");
            }

            if (mPendingClose && mReadQueue.isEmpty()) {
                // The peer closed the stream, and we've finished reading the stream data, so this stream is finished
                mIsClosed = true;
            }
        }

        return -1;
    }

    private int readBuffer(byte[] bytes, int offset, int length) {
        int count = 0;
        for (int i = offset; i < offset + length; ++i) {
            if (mReadBuffer.hasRemaining()) {
                bytes[i] = mReadBuffer.get();
                ++count;
            }
        }
        return count;
    }

    /**
     * Sends a WRTE packet with a given byte array payload. It does not flush the stream.
     *
     * @param bytes Payload in the form of a byte array
     * @throws IOException If the stream fails while sending data
     */
    public void write(byte[] bytes, int offset, int length) thro
Download .txt
gitextract_bnja9n_o/

├── .gitignore
├── COPYING
├── LICENSES/
│   ├── Apache-2.0
│   ├── BSD-3-Clause
│   ├── GPL-3.0-or-later
│   └── MIT
├── README.md
├── SERVICES.md
├── app/
│   ├── .gitignore
│   ├── build.gradle
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── io/
│           │       └── github/
│           │           └── muntashirakon/
│           │               └── adb/
│           │                   └── testapp/
│           │                       ├── AdbConnectionManager.java
│           │                       ├── App.java
│           │                       ├── MainActivity.java
│           │                       └── MainViewModel.java
│           └── res/
│               ├── drawable/
│               │   ├── ic_add_link.xml
│               │   ├── ic_launcher_background.xml
│               │   ├── ic_link.xml
│               │   └── ic_link_off.xml
│               ├── drawable-v24/
│               │   └── ic_launcher_foreground.xml
│               ├── layout/
│               │   ├── activity_main.xml
│               │   └── dialog_input.xml
│               ├── menu/
│               │   └── actions_main.xml
│               ├── mipmap-anydpi-v26/
│               │   ├── ic_launcher.xml
│               │   └── ic_launcher_round.xml
│               └── values/
│                   └── strings.xml
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── libadb/
│   ├── .gitignore
│   ├── build.gradle
│   └── src/
│       ├── main/
│       │   ├── AndroidManifest.xml
│       │   └── java/
│       │       └── io/
│       │           └── github/
│       │               └── muntashirakon/
│       │                   └── adb/
│       │                       ├── AbsAdbConnectionManager.java
│       │                       ├── AdbAuthenticationFailedException.java
│       │                       ├── AdbConnection.java
│       │                       ├── AdbInputStream.java
│       │                       ├── AdbOutputStream.java
│       │                       ├── AdbPairingRequiredException.java
│       │                       ├── AdbProtocol.java
│       │                       ├── AdbStream.java
│       │                       ├── AndroidPubkey.java
│       │                       ├── ByteArrayNoThrowOutputStream.java
│       │                       ├── KeyPair.java
│       │                       ├── LocalServices.java
│       │                       ├── PRNGFixes.java
│       │                       ├── PairingAuthCtx.java
│       │                       ├── PairingConnectionCtx.java
│       │                       ├── SslUtils.java
│       │                       ├── StringCompat.java
│       │                       └── android/
│       │                           ├── AdbMdns.java
│       │                           ├── AndroidUtils.java
│       │                           └── package.html
│       └── test/
│           └── java/
│               └── io/
│                   └── github/
│                       └── muntashirakon/
│                           └── adb/
│                               └── AndroidPubkeyTest.java
└── settings.gradle
Download .txt
SYMBOL INDEX (271 symbols across 24 files)

FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/AdbConnectionManager.java
  class AdbConnectionManager (line 54) | public class AdbConnectionManager extends AbsAdbConnectionManager {
    method getInstance (line 57) | public static AbsAdbConnectionManager getInstance(@NonNull Context con...
    method AdbConnectionManager (line 67) | private AdbConnectionManager(@NonNull Context context) throws Exception {
    method getPrivateKey (line 109) | @NonNull
    method getCertificate (line 115) | @NonNull
    method getDeviceName (line 121) | @NonNull
    method readCertificateFromFile (line 127) | @Nullable
    method writeCertificateToFile (line 137) | private static void writeCertificateToFile(@NonNull Context context, @...
    method readPrivateKeyFromFile (line 150) | @Nullable
    method writePrivateKeyToFile (line 164) | private static void writePrivateKeyToFile(@NonNull Context context, @N...

FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/App.java
  class App (line 13) | public class App extends Application {
    method onCreate (line 14) | @Override
    method attachBaseContext (line 20) | @Override

FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/MainActivity.java
  class MainActivity (line 28) | public class MainActivity extends AppCompatActivity {
    method onCreate (line 41) | @Override
    method init (line 53) | private void init() {
    method onResume (line 95) | @Override
    method onPause (line 101) | @Override
    method onCreateOptionsMenu (line 110) | @Override
    method onPrepareOptionsMenu (line 119) | @Override
    method onOptionsItemSelected (line 129) | @Override
    method openIme (line 147) | private void openIme() {
    method checkMenus (line 155) | private void checkMenus() {
    method connectAdb (line 166) | private void connectAdb() {
    method pairAdb (line 188) | private void pairAdb() {

FILE: app/src/main/java/io/github/muntashirakon/adb/testapp/MainViewModel.java
  class MainViewModel (line 33) | public class MainViewModel extends AndroidViewModel {
    method MainViewModel (line 44) | public MainViewModel(@NonNull Application application) {
    method watchConnectAdb (line 48) | public LiveData<Boolean> watchConnectAdb() {
    method watchPairAdb (line 52) | public LiveData<Boolean> watchPairAdb() {
    method watchAskPairAdb (line 56) | public LiveData<Boolean> watchAskPairAdb() {
    method watchCommandOutput (line 60) | public LiveData<CharSequence> watchCommandOutput() {
    method watchPairingPort (line 64) | public LiveData<Integer> watchPairingPort() {
    method onCleared (line 68) | @Override
    method connect (line 88) | public void connect(int port) {
    method autoConnect (line 107) | public void autoConnect() {
    method disconnect (line 111) | public void disconnect() {
    method getPairingPort (line 124) | public void getPairingPort() {
    method pair (line 148) | public void pair(int port, String pairingCode) {
    method autoConnectInternal (line 165) | @WorkerThread
    method execute (line 209) | public void execute(String command) {

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AbsAdbConnectionManager.java
  class AbsAdbConnectionManager (line 29) | @SuppressWarnings("unused")
    method getPrivateKey (line 43) | @NonNull
    method getCertificate (line 49) | @NonNull
    method getDeviceName (line 55) | @NonNull
    method setHostAddress (line 61) | @CallSuper
    method getHostAddress (line 69) | @NonNull
    method setApi (line 80) | public void setApi(int api) {
    method getApi (line 87) | public int getApi() {
    method setTimeout (line 97) | @CallSuper
    method getTimeout (line 109) | public long getTimeout() {
    method getTimeoutUnit (line 117) | @NonNull
    method setThrowOnUnauthorised (line 129) | @CallSuper
    method isThrowOnUnauthorised (line 141) | public boolean isThrowOnUnauthorised() {
    method getAdbConnection (line 150) | @CallSuper
    method isConnected (line 163) | public boolean isConnected() {
    method connectTls (line 184) | @WorkerThread
    method connectTcp (line 206) | @WorkerThread
    method autoConnect (line 228) | @WorkerThread
    method autoConnect (line 281) | @WorkerThread
    method connect (line 337) | @WorkerThread
    method connect (line 367) | @WorkerThread
    method disconnect (line 389) | public void disconnect() throws IOException {
    method openStream (line 408) | @WorkerThread
    method openStream (line 434) | @NonNull
    method pair (line 457) | @WorkerThread
    method pair (line 472) | @WorkerThread
    method close (line 491) | @Override
    method getAdbKeyPair (line 504) | @NonNull

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbAuthenticationFailedException.java
  class AdbAuthenticationFailedException (line 10) | public class AdbAuthenticationFailedException extends RuntimeException {
    method AdbAuthenticationFailedException (line 11) | public AdbAuthenticationFailedException() {

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbConnection.java
  class AdbConnection (line 35) | public class AdbConnection implements Closeable {
    method create (line 153) | @WorkerThread
    method create (line 167) | @WorkerThread
    method create (line 182) | @WorkerThread
    method AdbConnection (line 191) | @WorkerThread
    method getInputStream (line 216) | @GuardedBy("lock")
    method getOutputStream (line 222) | @GuardedBy("lock")
    method createConnectionThread (line 233) | @NonNull
    method setDeviceName (line 366) | public void setDeviceName(@NonNull String deviceName) {
    method getProtocolVersion (line 380) | public int getProtocolVersion() {
    method getMaxData (line 393) | public int getMaxData() throws InterruptedException, IOException, AdbP...
    method isConnectionEstablished (line 407) | public boolean isConnectionEstablished() {
    method isConnected (line 414) | public boolean isConnected() {
    method connect (line 427) | public boolean connect() throws IOException, InterruptedException, Adb...
    method connect (line 446) | public boolean connect(long timeout, @NonNull TimeUnit unit, boolean t...
    method open (line 476) | @NonNull
    method open (line 496) | @NonNull
    method waitForConnection (line 528) | private boolean waitForConnection(long timeout, @NonNull TimeUnit unit)
    method cleanupStreams (line 564) | private void cleanupStreams() {
    method close (line 580) | @Override
    method sendPacket (line 599) | void sendPacket(byte[] packet) throws IOException {
    method flushPacket (line 607) | void flushPacket() throws IOException {
    class Builder (line 613) | public static class Builder {
      method Builder (line 622) | public Builder() {
      method Builder (line 625) | public Builder(String host, int port) {
      method setHost (line 633) | public Builder setHost(String host) {
      method setPort (line 641) | public Builder setPort(int port) {
      method setDeviceName (line 651) | public Builder setDeviceName(String deviceName) {
      method setApi (line 663) | public Builder setApi(int api) {
      method setPrivateKey (line 671) | public Builder setPrivateKey(PrivateKey privateKey) {
      method setCertificate (line 679) | public Builder setCertificate(Certificate certificate) {
      method setKeyPair (line 684) | Builder setKeyPair(KeyPair keyPair) {
      method build (line 694) | public AdbConnection build() throws IOException {
      method connect (line 717) | public AdbConnection connect() throws IOException, InterruptedExcept...
      method connect (line 740) | public AdbConnection connect(long timeout, @NonNull TimeUnit unit, b...

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbInputStream.java
  class AdbInputStream (line 8) | public class AdbInputStream extends InputStream {
    method AdbInputStream (line 11) | public AdbInputStream(AdbStream adbStream) {
    method read (line 15) | @Override
    method read (line 24) | @Override
    method read (line 29) | @Override
    method close (line 35) | @Override
    method available (line 39) | @Override

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbOutputStream.java
  class AdbOutputStream (line 8) | public class AdbOutputStream extends OutputStream {
    method AdbOutputStream (line 11) | public AdbOutputStream(AdbStream adbStream) {
    method write (line 15) | @Override
    method write (line 20) | @Override
    method write (line 25) | @Override
    method flush (line 30) | @Override
    method close (line 35) | @Override

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbPairingRequiredException.java
  class AdbPairingRequiredException (line 3) | public class AdbPairingRequiredException extends Exception {
    method AdbPairingRequiredException (line 4) | public AdbPairingRequiredException(String message) {

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbProtocol.java
  class AdbProtocol (line 24) | final class AdbProtocol {
    method getMaxData (line 136) | public static int getMaxData(int api) {
    method getProtocolVersion (line 146) | public static int getProtocolVersion(int api) {
    method getPayloadChecksum (line 159) | private static int getPayloadChecksum(@NonNull byte[] data) {
    method getPayloadChecksum (line 171) | private static int getPayloadChecksum(@NonNull byte[] data, int offset...
    method generateMessage (line 188) | @NonNull
    method generateMessage (line 204) | @NonNull
    method generateConnect (line 253) | @NonNull
    method generateAuth (line 267) | @NonNull
    method generateStls (line 279) | @NonNull
    method generateOpen (line 293) | @NonNull
    method generateWrite (line 313) | @NonNull
    method generateClose (line 327) | @NonNull
    method generateReady (line 341) | @NonNull
    class Message (line 349) | static final class Message {
      method parse (line 390) | @NonNull
      method Message (line 443) | private Message(@NonNull ByteBuffer header) {
      method toString (line 452) | @NonNull

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AdbStream.java
  class AdbStream (line 16) | public class AdbStream implements Closeable {
    method AdbStream (line 65) | AdbStream(AdbConnection adbConnection, int localId)
    method openInputStream (line 75) | public AdbInputStream openInputStream() {
    method openOutputStream (line 79) | public AdbOutputStream openOutputStream() {
    method addPayload (line 88) | void addPayload(byte[] payload) {
    method sendReady (line 101) | void sendReady() throws IOException {
    method updateRemoteId (line 111) | void updateRemoteId(int remoteId) {
    method readyForWrite (line 118) | void readyForWrite() {
    method notifyClose (line 125) | void notifyClose(boolean closedByPeer) {
    method read (line 149) | public int read(byte[] bytes, int offset, int length) throws IOExcepti...
    method readBuffer (line 188) | private int readBuffer(byte[] bytes, int offset, int length) {
    method write (line 205) | public void write(byte[] bytes, int offset, int length) throws IOExcep...
    method flush (line 247) | public void flush() throws IOException {
    method close (line 259) | @Override
    method isClosed (line 278) | public boolean isClosed() {
    method available (line 288) | public int available() throws IOException {

FILE: libadb/src/main/java/io/github/muntashirakon/adb/AndroidPubkey.java
  class AndroidPubkey (line 26) | final class AndroidPubkey {
    method adbAuthSign (line 88) | @NonNull
    method encodeWithName (line 104) | @NonNull
    method getUserInfo (line 116) | @VisibleForTesting
    method decode (line 140) | @NonNull
    method encode (line 177) | @NonNull
    method BigEndianToLittleEndianPadded (line 212) | @Nullable
    method fitsInBytes (line 227) | static boolean fitsInBytes(@NonNull byte[] bytes, int num_bytes, int l...
    method swapEndianness (line 235) | @NonNull

FILE: libadb/src/main/java/io/github/muntashirakon/adb/ByteArrayNoThrowOutputStream.java
  class ByteArrayNoThrowOutputStream (line 7) | class ByteArrayNoThrowOutputStream extends ByteArrayOutputStream {
    method ByteArrayNoThrowOutputStream (line 8) | public ByteArrayNoThrowOutputStream() {
    method ByteArrayNoThrowOutputStream (line 12) | public ByteArrayNoThrowOutputStream(int size) {
    method write (line 16) | @Override
    method close (line 21) | @Override

FILE: libadb/src/main/java/io/github/muntashirakon/adb/KeyPair.java
  class KeyPair (line 11) | final class KeyPair {
    method KeyPair (line 15) | public KeyPair(PrivateKey privateKey, Certificate certificate) {
    method getPrivateKey (line 20) | public PrivateKey getPrivateKey() {
    method getPublicKey (line 24) | public PublicKey getPublicKey() {
    method getCertificate (line 28) | public Certificate getCertificate() {
    method destroy (line 32) | public void destroy() throws DestroyFailedException {

FILE: libadb/src/main/java/io/github/muntashirakon/adb/LocalServices.java
  class LocalServices (line 19) | public class LocalServices {
    method getServiceName (line 137) | @NonNull
    method getDestination (line 175) | @NonNull

FILE: libadb/src/main/java/io/github/muntashirakon/adb/PRNGFixes.java
  class PRNGFixes (line 34) | public final class PRNGFixes {
    method PRNGFixes (line 40) | private PRNGFixes() {
    method apply (line 48) | public static void apply() {
    method applyOpenSSLFix (line 59) | private static void applyOpenSSLFix() throws SecurityException {
    method installLinuxPRNGSecureRandom (line 91) | private static void installLinuxPRNGSecureRandom()
    class LinuxPRNGSecureRandomProvider (line 133) | private static class LinuxPRNGSecureRandomProvider extends Provider {
      method LinuxPRNGSecureRandomProvider (line 135) | public LinuxPRNGSecureRandomProvider() {
    class LinuxPRNGSecureRandom (line 150) | public static class LinuxPRNGSecureRandom extends SecureRandomSpi {
      method engineSetSeed (line 189) | @Override
      method engineNextBytes (line 208) | @Override
      method engineGenerateSeed (line 229) | @Override
      method getUrandomInputStream (line 236) | private DataInputStream getUrandomInputStream() {
      method getUrandomOutputStream (line 255) | private OutputStream getUrandomOutputStream() throws IOException {
    method generateSeed (line 269) | private static byte[] generateSeed() {
    method getDeviceSerialNumber (line 293) | private static String getDeviceSerialNumber() {
    method getBuildFingerprintAndDeviceSerial (line 303) | private static byte[] getBuildFingerprintAndDeviceSerial() {

FILE: libadb/src/main/java/io/github/muntashirakon/adb/PairingAuthCtx.java
  class PairingAuthCtx (line 31) | @RequiresApi(Build.VERSION_CODES.GINGERBREAD)
    method createAlice (line 51) | @Nullable
    method createBob (line 61) | @VisibleForTesting
    method PairingAuthCtx (line 72) | private PairingAuthCtx(Spake2Context spake25519, byte[] password)
    method getMsg (line 78) | public byte[] getMsg() {
    method initCipher (line 82) | public boolean initCipher(byte[] theirMsg) throws IllegalArgumentExcep...
    method encrypt (line 92) | @Nullable
    method decrypt (line 98) | @Nullable
    method isDestroyed (line 104) | @Override
    method destroy (line 109) | @Override
    method encryptDecrypt (line 116) | @Nullable

FILE: libadb/src/main/java/io/github/muntashirakon/adb/PairingConnectionCtx.java
  class PairingConnectionCtx (line 37) | @RequiresApi(Build.VERSION_CODES.GINGERBREAD)
    type State (line 44) | private enum State {
    type Role (line 51) | enum Role {
    method PairingConnectionCtx (line 68) | public PairingConnectionCtx(@NonNull String host, int port, @NonNull b...
    method PairingConnectionCtx (line 79) | public PairingConnectionCtx(@NonNull String host, int port, @NonNull b...
    method start (line 86) | public void start() throws IOException {
    method notifyResult (line 119) | private void notifyResult() {
    method setupTlsConnection (line 123) | private void setupTlsConnection() throws IOException {
    method exportKeyingMaterial (line 156) | @SuppressLint("PrivateApi") // Conscrypt is a stable private API
    method writeHeader (line 181) | private void writeHeader(@NonNull PairingPacketHeader header, @NonNull...
    method readHeader (line 190) | @Nullable
    method createHeader (line 198) | @NonNull
    method checkHeaderType (line 203) | private boolean checkHeaderType(byte expected, byte actual) {
    method doExchangeMsgs (line 211) | private boolean doExchangeMsgs() throws IOException {
    method doExchangePeerInfo (line 235) | private boolean doExchangePeerInfo() throws IOException {
    method close (line 276) | @Override
    class PeerInfo (line 292) | private static class PeerInfo {
      method readFrom (line 298) | @NonNull
      method PeerInfo (line 309) | public PeerInfo(byte type, byte[] data) {
      method writeTo (line 314) | public void writeTo(@NonNull ByteBuffer buffer) {
      method toString (line 318) | @NonNull
    class PairingPacketHeader (line 328) | private static class PairingPacketHeader {
      method readFrom (line 339) | @Nullable
      method PairingPacketHeader (line 364) | public PairingPacketHeader(byte version, byte type, int payloadSize) {
      method writeTo (line 370) | public void writeTo(@NonNull ByteBuffer buffer) {
      method toString (line 374) | @NonNull

FILE: libadb/src/main/java/io/github/muntashirakon/adb/SslUtils.java
  class SslUtils (line 24) | final class SslUtils {
    method isCustomConscrypt (line 28) | public static boolean isCustomConscrypt() {
    method getSslContext (line 32) | @SuppressLint("TrulyRandom") // The users are already instructed to fi...
    method getKeyManager (line 60) | @NonNull
    method getAllAcceptingTrustManager (line 106) | @SuppressLint("TrustAllX509TrustManager") // Accept all certificates

FILE: libadb/src/main/java/io/github/muntashirakon/adb/StringCompat.java
  class StringCompat (line 13) | final class StringCompat {
    method getBytes (line 14) | @NonNull

FILE: libadb/src/main/java/io/github/muntashirakon/adb/android/AdbMdns.java
  class AdbMdns (line 32) | @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    type OnAdbDaemonDiscoveredListener (line 47) | public interface OnAdbDaemonDiscoveredListener {
      method onPortChanged (line 48) | void onPortChanged(@Nullable InetAddress hostAddress, int port);
    method AdbMdns (line 65) | public AdbMdns(@NonNull Context context, @ServiceType @NonNull String ...
    method start (line 74) | public void start() {
    method stop (line 82) | public void stop() {
    method isRunning (line 90) | public boolean isRunning() {
    method onDiscoveryStart (line 94) | private void onDiscoveryStart() {
    method onDiscoverStop (line 98) | private void onDiscoverStop() {
    method onServiceFound (line 102) | private void onServiceFound(NsdServiceInfo serviceInfo) {
    method onServiceLost (line 106) | private void onServiceLost(NsdServiceInfo serviceInfo) {
    method onServiceResolved (line 112) | private void onServiceResolved(NsdServiceInfo serviceInfo) {
    method isPortAvailable (line 130) | private boolean isPortAvailable(int port) {
    class DiscoveryListener (line 139) | private static class DiscoveryListener implements NsdManager.Discovery...
      method DiscoveryListener (line 143) | private DiscoveryListener(@NonNull AdbMdns adbMdns) {
      method onDiscoveryStarted (line 147) | @Override
      method onStartDiscoveryFailed (line 152) | @Override
      method onDiscoveryStopped (line 156) | @Override
      method onStopDiscoveryFailed (line 161) | @Override
      method onServiceFound (line 165) | @Override
      method onServiceLost (line 170) | @Override
    class ResolveListener (line 176) | private static class ResolveListener implements NsdManager.ResolveList...
      method ResolveListener (line 180) | private ResolveListener(@NonNull AdbMdns adbMdns) {
      method onResolveFailed (line 184) | @Override
      method onServiceResolved (line 188) | @Override

FILE: libadb/src/main/java/io/github/muntashirakon/adb/android/AndroidUtils.java
  class AndroidUtils (line 15) | public class AndroidUtils {
    method isEmulator (line 21) | public static boolean isEmulator(@NonNull Context context) {
    method getHostIpAddress (line 38) | @NonNull

FILE: libadb/src/test/java/io/github/muntashirakon/adb/AndroidPubkeyTest.java
  class AndroidPubkeyTest (line 22) | public class AndroidPubkeyTest {
    method setUp (line 76) | @Before
    method decodeTest (line 83) | @Test
    method encodeTest (line 93) | @Test
    method encodeWithNameTest (line 102) | @Test
Condensed preview — 58 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (320K chars).
[
  {
    "path": ".gitignore",
    "chars": 47,
    "preview": ".idea\n.gradle\n.DS_Store\n/build\nlocal.properties"
  },
  {
    "path": "COPYING",
    "chars": 483,
    "preview": "LibADB Android is provided under:\n\n\tSPDX-License-Identifier: GPL-3.0-or-later or Apache-2.0\n\nBeing under the terms of th"
  },
  {
    "path": "LICENSES/Apache-2.0",
    "chars": 10001,
    "preview": "Valid-License-Identifier: Apache-2.0\nSPDX-URL: https://spdx.org/licenses/Apache-2.0.html\nUsage-Guide:\n  To use the Apach"
  },
  {
    "path": "LICENSES/BSD-3-Clause",
    "chars": 1844,
    "preview": "Valid-License-Identifier: BSD-3-Clause\nSPDX-URL: https://spdx.org/licenses/BSD-3-Clause.html\nUsage-Guide:\n  To use the B"
  },
  {
    "path": "LICENSES/GPL-3.0-or-later",
    "chars": 35657,
    "preview": "Valid-License-Identifier: GPL-3.0+\nValid-License-Identifier: GPL-3.0-or-later\nSPDX-URL: https://spdx.org/licenses/GPL-3."
  },
  {
    "path": "LICENSES/MIT",
    "chars": 1568,
    "preview": "Valid-License-Identifier: MIT\nSPDX-URL: https://spdx.org/licenses/MIT.html\nUsage-Guide:\n  To use the MIT License put the"
  },
  {
    "path": "README.md",
    "chars": 9731,
    "preview": "# LibADB Android\n\nADB library for Android. It enables an app to connect to the ADB daemon (`adbd` process) belonging to "
  },
  {
    "path": "SERVICES.md",
    "chars": 2374,
    "preview": "# Services\n\nLibADB only supports local services which can be requested through `AbsAdbConnectionManager#openStream(Strin"
  },
  {
    "path": "app/.gitignore",
    "chars": 6,
    "preview": "/build"
  },
  {
    "path": "app/build.gradle",
    "chars": 1379,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\nplugins {\n    id 'com.android.application'\n}\n\nandroid {\n    "
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "chars": 810,
    "preview": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<manifest xmlns:android=\"http://schemas.android.com/apk"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/AdbConnectionManager.java",
    "chars": 7459,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/App.java",
    "chars": 681,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/MainActivity.java",
    "chars": 8143,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/MainViewModel.java",
    "chars": 7997,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android"
  },
  {
    "path": "app/src/main/res/drawable/ic_add_link.xml",
    "chars": 595,
    "preview": "<!-- SPDX-License-Identifier: Apache-2.0 -->\n<vector android:height=\"24dp\"\n    android:tint=\"#000000\"\n    android:viewpo"
  },
  {
    "path": "app/src/main/res/drawable/ic_launcher_background.xml",
    "chars": 4810,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width="
  },
  {
    "path": "app/src/main/res/drawable/ic_link.xml",
    "chars": 597,
    "preview": "<!-- SPDX-License-Identifier: Apache-2.0 -->\n<vector android:height=\"24dp\"\n    android:tint=\"#000000\"\n    android:viewpo"
  },
  {
    "path": "app/src/main/res/drawable/ic_link_off.xml",
    "chars": 705,
    "preview": "<!-- SPDX-License-Identifier: Apache-2.0 -->\n<vector android:height=\"24dp\"\n    android:tint=\"#000000\"\n    android:viewpo"
  },
  {
    "path": "app/src/main/res/drawable-v24/ic_launcher_foreground.xml",
    "chars": 1534,
    "preview": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:aapt=\"http://schemas.android.com/aapt\"\n    andr"
  },
  {
    "path": "app/src/main/res/layout/activity_main.xml",
    "chars": 2745,
    "preview": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<androidx.coordinatorlayout.widget.CoordinatorLayout xm"
  },
  {
    "path": "app/src/main/res/layout/dialog_input.xml",
    "chars": 1373,
    "preview": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<androidx.appcompat.widget.LinearLayoutCompat xmlns:and"
  },
  {
    "path": "app/src/main/res/menu/actions_main.xml",
    "chars": 721,
    "preview": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<menu xmlns:android=\"http://schemas.android.com/apk/res"
  },
  {
    "path": "app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml",
    "chars": 272,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <b"
  },
  {
    "path": "app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml",
    "chars": 272,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <b"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "chars": 749,
    "preview": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<resources>\n    <string name=\"app_name\">ADB Shell</stri"
  },
  {
    "path": "build.gradle",
    "chars": 760,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\nbuildscript {\n    repositories {\n        google()\n        ma"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 339,
    "preview": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionSha256Sum=8fad3d78296ca518113f3d29016617c7f"
  },
  {
    "path": "gradle.properties",
    "chars": 192,
    "preview": "# Project-wide Gradle settings.\nandroid.useAndroidX=true\nandroid.enableJetifier=true\nandroid.jetifier.ignorelist=bcprov-"
  },
  {
    "path": "gradlew",
    "chars": 8705,
    "preview": "#!/bin/sh\n\n#\n# Copyright © 2015 the original authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "gradlew.bat",
    "chars": 2843,
    "preview": "@rem\n@rem Copyright 2015 the original author or authors.\n@rem\n@rem Licensed under the Apache License, Version 2.0 (the \""
  },
  {
    "path": "jitpack.yml",
    "chars": 127,
    "preview": "jdk:\n  - openjdk21\nbefore_install:\n  - sdk install java 21.0.4-tem\n  - sdk use java 21.0.4-tem\n  - sdk install maven\n  -"
  },
  {
    "path": "libadb/.gitignore",
    "chars": 7,
    "preview": "/build\n"
  },
  {
    "path": "libadb/build.gradle",
    "chars": 1185,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\nplugins {\n    id 'com.android.library'\n    id 'maven-publish"
  },
  {
    "path": "libadb/src/main/AndroidManifest.xml",
    "chars": 214,
    "preview": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<manifest xmlns:android=\"http://schemas.android.com/apk"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AbsAdbConnectionManager.java",
    "chars": 21556,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.content"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbAuthenticationFailedException.java",
    "chars": 504,
    "preview": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\n/**"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbConnection.java",
    "chars": 29758,
    "preview": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimp"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbInputStream.java",
    "chars": 969,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.io.IOExcep"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbOutputStream.java",
    "chars": 874,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.io.IOExcep"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbPairingRequiredException.java",
    "chars": 188,
    "preview": "package io.github.muntashirakon.adb;\n\npublic class AdbPairingRequiredException extends Exception {\n    public AdbPairing"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbProtocol.java",
    "chars": 16666,
    "preview": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimp"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbStream.java",
    "chars": 9576,
    "preview": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimp"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AndroidPubkey.java",
    "chars": 10620,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport androidx.annota"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/ByteArrayNoThrowOutputStream.java",
    "chars": 486,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.io.ByteArr"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/KeyPair.java",
    "chars": 922,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.security.P"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/LocalServices.java",
    "chars": 11253,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.text.Te"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/PRNGFixes.java",
    "chars": 11877,
    "preview": "// SPDX-License-Identifier: MIT AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimport andro"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/PairingAuthCtx.java",
    "chars": 5085,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.os.Buil"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/PairingConnectionCtx.java",
    "chars": 14902,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.annotat"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/SslUtils.java",
    "chars": 4391,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.annotat"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/StringCompat.java",
    "chars": 845,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.os.Buil"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/android/AdbMdns.java",
    "chars": 6273,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.android;\n\nimport android"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/android/AndroidUtils.java",
    "chars": 2056,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.android;\n\nimport android"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/android/package.html",
    "chars": 79,
    "preview": "<p>All Android dependencies are kept under this package for easy reference.</p>"
  },
  {
    "path": "libadb/src/test/java/io/github/muntashirakon/adb/AndroidPubkeyTest.java",
    "chars": 41470,
    "preview": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport org.bouncycastl"
  },
  {
    "path": "settings.gradle",
    "chars": 104,
    "preview": "include ':libadb'\ninclude ':app'\nrootProject.name = \"libadb-android\"\nproject(':libadb').name = 'libadb'\n"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the MuntashirAkon/libadb-android GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 58 files (300.2 KB), approximately 75.0k tokens, and a symbol index with 271 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!