[
  {
    "path": ".gitignore",
    "content": ".idea\n.gradle\n.DS_Store\n/build\nlocal.properties"
  },
  {
    "path": "COPYING",
    "content": "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 the GNU General Public License version 3 or\nlater, according with:\n\n\tLICENSES/GPL-3.0-or-later\n\nor Apache License, Version 2.0, according with:\n\n\tLICENSES/Apache-2.0\n\nIn addition, other licenses may also apply. Please navigate to:\n\n\tLICENSES/\n\nto see all the licenses used in this project.\n\nAll contributions to the LibADB Android are subject to this COPYING\nfile.\n"
  },
  {
    "path": "LICENSES/Apache-2.0",
    "content": "Valid-License-Identifier: Apache-2.0\nSPDX-URL: https://spdx.org/licenses/Apache-2.0.html\nUsage-Guide:\n  To use the Apache License version 2.0 put the following SPDX tag/value\n  pair into a comment according to the placement guidelines in the\n  licensing rules documentation:\n    SPDX-License-Identifier: Apache-2.0\n  Do NOT use this license unless the files are copied from another work\n  under the same license. In such cases, use \"AND GPL-3.0-or-later\" so\n  that your contributions are under GPL-3.0+ license.\nLicense-Text:\n\nApache License\n\nVersion 2.0, January 2004\n\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and\ndistribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the\ncopyright owner that is granting the License.\n\n\"Legal Entity\" shall mean the union of the acting entity and all other\nentities that control, are controlled by, or are under common control with\nthat entity. For the purposes of this definition, \"control\" means (i) the\npower, direct or indirect, to cause the direction or management of such\nentity, whether by contract or otherwise, or (ii) ownership of fifty\npercent (50%) or more of the outstanding shares, or (iii) beneficial\nownership of such entity.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising\npermissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications,\nincluding but not limited to software source code, documentation source,\nand configuration files.\n\n\"Object\" form shall mean any form resulting from mechanical transformation\nor translation of a Source form, including but not limited to compiled\nobject code, generated documentation, and conversions to other media types.\n\n\"Work\" shall mean the work of authorship, whether in Source or Object form,\nmade available under the License, as indicated by a copyright notice that\nis included in or attached to the work (an example is provided in the\nAppendix below).\n\n\"Derivative Works\" shall mean any work, whether in Source or Object form,\nthat is based on (or derived from) the Work and for which the editorial\nrevisions, annotations, elaborations, or other modifications represent, as\na whole, an original work of authorship. For the purposes of this License,\nDerivative Works shall not include works that remain separable from, or\nmerely link (or bind by name) to the interfaces of, the Work and Derivative\nWorks thereof.\n\n\"Contribution\" shall mean any work of authorship, including the original\nversion of the Work and any modifications or additions to that Work or\nDerivative Works thereof, that is intentionally submitted to Licensor for\ninclusion in the Work by the copyright owner or by an individual or Legal\nEntity authorized to submit on behalf of the copyright owner. For the\npurposes of this definition, \"submitted\" means any form of electronic,\nverbal, or written communication sent to the Licensor or its\nrepresentatives, including but not limited to communication on electronic\nmailing lists, source code control systems, and issue tracking systems that\nare managed by, or on behalf of, the Licensor for the purpose of discussing\nand improving the Work, but excluding communication that is conspicuously\nmarked or otherwise designated in writing by the copyright owner as \"Not a\nContribution.\"\n\n\"Contributor\" shall mean Licensor and any individual or Legal Entity on\nbehalf of whom a Contribution has been received by Licensor and\nsubsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of this\n   License, each Contributor hereby grants to You a perpetual, worldwide,\n   non-exclusive, no-charge, royalty-free, irrevocable copyright license to\n   reproduce, prepare Derivative Works of, publicly display, publicly\n   perform, sublicense, and distribute the Work and such Derivative Works\n   in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of this\n   License, each Contributor hereby grants to You a perpetual, worldwide,\n   non-exclusive, no-charge, royalty-free, irrevocable (except as stated in\n   this section) patent license to make, have made, use, offer to sell,\n   sell, import, and otherwise transfer the Work, where such license\n   applies only to those patent claims licensable by such Contributor that\n   are necessarily infringed by their Contribution(s) alone or by\n   combination of their Contribution(s) with the Work to which such\n   Contribution(s) was submitted. If You institute patent litigation\n   against any entity (including a cross-claim or counterclaim in a\n   lawsuit) alleging that the Work or a Contribution incorporated within\n   the Work constitutes direct or contributory patent infringement, then\n   any patent licenses granted to You under this License for that Work\n   shall terminate as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the Work or\n   Derivative Works thereof in any medium, with or without modifications,\n   and in Source or Object form, provided that You meet the following\n   conditions:\n\n   a. You must give any other recipients of the Work or Derivative Works a\n      copy of this License; and\n\n   b. You must cause any modified files to carry prominent notices stating\n      that You changed the files; and\n\n   c. You must retain, in the Source form of any Derivative Works that You\n      distribute, all copyright, patent, trademark, and attribution notices\n      from the Source form of the Work, excluding those notices that do not\n      pertain to any part of the Derivative Works; and\n\n   d. If the Work includes a \"NOTICE\" text file as part of its\n      distribution, then any Derivative Works that You distribute must\n      include a readable copy of the attribution notices contained within\n      such NOTICE file, excluding those notices that do not pertain to any\n      part of the Derivative Works, in at least one of the following\n      places: within a NOTICE text file distributed as part of the\n      Derivative Works; within the Source form or documentation, if\n      provided along with the Derivative Works; or, within a display\n      generated by the Derivative Works, if and wherever such third-party\n      notices normally appear. The contents of the NOTICE file are for\n      informational purposes only and do not modify the License. You may\n      add Your own attribution notices within Derivative Works that You\n      distribute, alongside or as an addendum to the NOTICE text from the\n      Work, provided that such additional attribution notices cannot be\n      construed as modifying the License.\n\n    You may add Your own copyright statement to Your modifications and may\n    provide additional or different license terms and conditions for use,\n    reproduction, or distribution of Your modifications, or for any such\n    Derivative Works as a whole, provided Your use, reproduction, and\n    distribution of the Work otherwise complies with the conditions stated\n    in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise, any\n   Contribution intentionally submitted for inclusion in the Work by You to\n   the Licensor shall be under the terms and conditions of this License,\n   without any additional terms or conditions. Notwithstanding the above,\n   nothing herein shall supersede or modify the terms of any separate\n   license agreement you may have executed with Licensor regarding such\n   Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or agreed to\n   in writing, Licensor provides the Work (and each Contributor provides\n   its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS\n   OF ANY KIND, either express or implied, including, without limitation,\n   any warranties or conditions of TITLE, NON-INFRINGEMENT,\n   MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely\n   responsible for determining the appropriateness of using or\n   redistributing the Work and assume any risks associated with Your\n   exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory, whether\n   in tort (including negligence), contract, or otherwise, unless required\n   by applicable law (such as deliberate and grossly negligent acts) or\n   agreed to in writing, shall any Contributor be liable to You for\n   damages, including any direct, indirect, special, incidental, or\n   consequential damages of any character arising as a result of this\n   License or out of the use or inability to use the Work (including but\n   not limited to damages for loss of goodwill, work stoppage, computer\n   failure or malfunction, or any and all other commercial damages or\n   losses), even if such Contributor has been advised of the possibility of\n   such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing the\n   Work or Derivative Works thereof, You may choose to offer, and charge a\n   fee for, acceptance of support, warranty, indemnity, or other liability\n   obligations and/or rights consistent with this License. However, in\n   accepting such obligations, You may act only on Your own behalf and on\n   Your sole responsibility, not on behalf of any other Contributor, and\n   only if You agree to indemnify, defend, and hold each Contributor\n   harmless for any liability incurred by, or claims asserted against, such\n   Contributor by reason of your accepting any such warranty or additional\n   liability.\n\nEND OF TERMS AND CONDITIONS"
  },
  {
    "path": "LICENSES/BSD-3-Clause",
    "content": "Valid-License-Identifier: BSD-3-Clause\nSPDX-URL: https://spdx.org/licenses/BSD-3-Clause.html\nUsage-Guide:\n  To use the BSD 3-clause \"New\" or \"Revised\" License put the following SPDX\n  tag/value pair into a comment according to the placement guidelines in\n  the licensing rules documentation:\n    SPDX-License-Identifier: BSD-3-Clause\nLicense-Text:\n\nCopyright (c) <year> <owner> . All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE."
  },
  {
    "path": "LICENSES/GPL-3.0-or-later",
    "content": "Valid-License-Identifier: GPL-3.0+\nValid-License-Identifier: GPL-3.0-or-later\nSPDX-URL: https://spdx.org/licenses/GPL-3.0-or-later.html\nUsage-Guide:\n  To use this license in source code, put one of the following SPDX\n  tag/value pairs into a comment according to the placement\n  guidelines in the licensing rules documentation.\n  For 'GNU General Public License (GPL) version 3 or any later version' use:\n    SPDX-License-Identifier: GPL-3.0+\n  or\n    SPDX-License-Identifier: GPL-3.0-or-later\nLicense-Text:\n\n                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>."
  },
  {
    "path": "LICENSES/MIT",
    "content": "Valid-License-Identifier: MIT\nSPDX-URL: https://spdx.org/licenses/MIT.html\nUsage-Guide:\n  To use the MIT License put the following SPDX tag/value pair into a\n  comment according to the placement guidelines in the licensing rules\n  documentation:\n    SPDX-License-Identifier: MIT\n  Do NOT use this license unless the files are copied from another work\n  under the same license. In such cases, use \"AND GPL-3.0-or-later\" so\n  that your contributions are under GPL-3.0+ license.\nLicense-Text:\n\nMIT License\n\nCopyright (c) <year> <copyright holders>\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE."
  },
  {
    "path": "README.md",
    "content": "# LibADB Android\n\nADB library for Android. It enables an app to connect to the ADB daemon (`adbd` process) belonging to the same or a\ndifferent device and execute arbitrary services or commands (via `shell:` service).\n\n**Disclaimer:** This library has never gone through a security audit. Please, proceed with caution if security is\ncrucial for your app. Avoid using the APIs for reasons other than connecting or using ADB. For the safety of your app\nand its users, open a remote service instead of using ADB and ask the user to disconnect Wireless debugging.\n\n## Getting Started\n### Adding Dependencies\nLibADB Android is available via JitPack.\n\n```groovy\n// Top level build file\nrepositories {\n    mavenCentral()\n    maven { url \"https://jitpack.io\" }\n}\n\n// Add to dependencies section\ndependencies {\n    // Add this library\n    implementation 'com.github.MuntashirAkon:libadb-android:3.1.1'\n    \n    // Library to generate X509Certificate. You can also use BouncyCastle for\n    // this. See example for use-case.\n    // implementation 'com.github.MuntashirAkon:sun-security-android:1.1'\n\n    // Bypass hidden API if you want to use the Android default Conscrypt in\n    // Android 9 (Pie) or later. It also requires additional steps. See\n    // https://github.com/LSPosed/AndroidHiddenApiBypass to find out more about\n    // this.\n    // implementation 'org.lsposed.hiddenapibypass:hiddenapibypass:6.1'\n\n    // Use custom Conscrypt library. If you want to connect to a remote ADB\n    // daemon instead of the device the app is currently running or do not want\n    // to bypass hidden API, this is the recommended choice.\n    implementation 'org.conscrypt:conscrypt-android:2.5.3'\n}\n```\n\nIf you're using the custom Conscrypt library in order to connect to a remote ADB daemon and the app targets Android\nversion below 4.4, you have to extend `android.app.Application` to apply fixes for the random number generation:\n```java\npublic class MyAwesomeApp extends Application {\n    @Override\n    public void onCreate() {\n        super.onCreate();\n        // Fix random number generation in Android versions below 4.4.\n        PRNGFixes.apply();\n    }\n\n    @Override\n    protected void attachBaseContext(Context base) {\n        super.attachBaseContext(base);\n        // Uncomment the following line if you want to bypass hidden API as\n        // described above.\n        // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n        //     HiddenApiBypass.addHiddenApiExemptions(\"L\");\n        // }\n    }\n}\n```\n\n**Notice:** Conscrypt supports only API 9 (Gingerbread) or later, meaning you cannot use ADB pairing or any TLSv1.3\nfeatures in API less than 9. The corresponding methods are already annotated properly. So, you don't have to worry about\ncompatibility issues that may arise when your app's minimum SDK is set to one of the unsupported versions.\n\n### Configuring ADB\nInstead of doing everything manually, you can create a concrete implementation of the `AbsAdbConnectionManager` class. \nExample:\n\n```java\npublic class AdbConnectionManager extends AbsAdbConnectionManager {\n    private static AbsAdbConnectionManager INSTANCE;\n\n    public static AbsAdbConnectionManager getInstance() throws Exception {\n        if (INSTANCE == null) {\n            INSTANCE = new AdbConnectionManager();\n        }\n        return INSTANCE;\n    }\n\n    private PrivateKey mPrivateKey;\n    private Certificate mCertificate;\n\n    private AdbConnectionManager() throws Exception {\n        // Set the API version whose `adbd` is running\n        setApi(Build.VERSION.SDK_INT);\n        // TODO: Load private key and certificate (along with public key) from\n        //  some place such as KeyStore or file system.\n        mPrivateKey = ...;\n        mCertificate = ...;\n        if (mPrivateKey == null) {\n            // Generate a new key pair\n            int keySize = 2048;\n            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"RSA\");\n            keyPairGenerator.initialize(keySize, SecureRandom.getInstance(\"SHA1PRNG\"));\n            KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();\n            PublicKey publicKey = generateKeyPair.getPublic();\n            mPrivateKey = generateKeyPair.getPrivate();\n            // Generate a certificate\n            // On Android, it requires sun.security-android library as mentioned\n            // above.\n            String subject = \"CN=My Awesome App\";\n            String algorithmName = \"SHA512withRSA\";\n            long expiryDate = System.currentTimeMillis() + 86400000;\n            CertificateExtensions certificateExtensions = new CertificateExtensions();\n            certificateExtensions.set(\"SubjectKeyIdentifier\", new SubjectKeyIdentifierExtension(\n                    new KeyIdentifier(publicKey).getIdentifier()));\n            X500Name x500Name = new X500Name(subject);\n            Date notBefore = new Date();\n            Date notAfter = new Date(expiryDate);\n            certificateExtensions.set(\"PrivateKeyUsage\", new PrivateKeyUsageExtension(notBefore, notAfter));\n            CertificateValidity certificateValidity = new CertificateValidity(notBefore, notAfter);\n            X509CertInfo x509CertInfo = new X509CertInfo();\n            x509CertInfo.set(\"version\", new CertificateVersion(2));\n            x509CertInfo.set(\"serialNumber\", new CertificateSerialNumber(new Random().nextInt() & Integer.MAX_VALUE));\n            x509CertInfo.set(\"algorithmID\", new CertificateAlgorithmId(AlgorithmId.get(algorithmName)));\n            x509CertInfo.set(\"subject\", new CertificateSubjectName(x500Name));\n            x509CertInfo.set(\"key\", new CertificateX509Key(publicKey));\n            x509CertInfo.set(\"validity\", certificateValidity);\n            x509CertInfo.set(\"issuer\", new CertificateIssuerName(x500Name));\n            x509CertInfo.set(\"extensions\", certificateExtensions);\n            X509CertImpl x509CertImpl = new X509CertImpl(x509CertInfo);\n            x509CertImpl.sign(mPrivateKey, algorithmName);\n            mCertificate = x509CertImpl;\n            // TODO: Store the key pair to some place else.\n        }\n    }\n\n    @NonNull\n    @Override\n    protected PrivateKey getPrivateKey() {\n        return mPrivateKey;\n    }\n\n    @NonNull\n    @Override\n    protected Certificate getCertificate() {\n        return mCertificate;\n    }\n\n    @NonNull\n    @Override\n    protected String getDeviceName() {\n        return \"MyAwesomeApp\";\n    }\n}\n```\n\n### Connecting to ADB\n\nYou can connect to ADB in several ways from the `AbsAdbConnectionManager`:\n\n| Method                          | Description                                                                                                   |\n|---------------------------------|---------------------------------------------------------------------------------------------------------------|\n| `connect(host, port)`           | Connect using a host address and a port number                                                                |\n| `connect(port)`                 | Connect using a host address set by `setHostAddress()` and a port number                                      |\n| `connectTcp(Context, timeout)`  | (SDK 16+) Discover host address and port number automatically for ADB over TCP and connect to it              | \n| `connectTls(Context, timeout)`  | (SDK 16+) Discover host address and port number automatically for TLS (from Android 9) and connect to it      |\n| `autoConnect(Context, timeout)` | (SDK 16+) Discover host address and port number automatically for both ADB over TCP and TLS and connect to it |\n\n### Wireless Debugging\nInternally, ADB over TCP and Wireless Debugging are very similar except Wireless Debugging requires an extra step of\n_pairing_ the device. In order to pair a new device, you can simply invoke `AdbConnectionManager.getInstance().pair(host, port, pairingCode)`.\nAfter the pairing, you can connect to ADB via the usual `connect()` methods without any additional steps.\n\n### Opening ADB Shell for Executing Arbitrary Commands\nSimply use `AdbConnectionManager.getInstance().openStream(\"shell:\")`. This will return an `AdbStream` which can be used\nto read/write to the ADB shell via `AdbStream#openInputStream()` and `AdbStream#openOutputStream()` methods\nrespectively like a normal Java `Process`. While it is possible to read/write in the same thread (first write and then\nread), this is not recommended because the shell might be stuck indefinitely for commands such as `top`.\n\n**NOTE:** If you want to create a full-featured terminal emulator, this approach isn't recommended. Instead, you should\ncreate a remote service via `app_process` or start an SSH server and connect to it.\n\n### Other services\nYou can also use other services via the `AdbConnectionManager#openStream()` methods. See [SERVICES.md](./SERVICES.md)\nfor more information.\n\n## For Java (non-Android) Projects\nIt is possible to modify this library to work on non-Android project. But it isn't supported because Spake2-Java only\nprovides stable releases for Android. However, you can incorporate this library in your project by manually compiling\nSpake2 library for your platforms.\n\n## Contributing\nBy contributing to this project, you permit your work to be released under the terms of GNU General Public License, \nVersion 3 or later **or** Apache License, Version 2.0.\n\n## License\nCopyright 2021 &copy; Muntashir Al-Islam\n\nDual licensed under the terms of [GPL-3.0-or-later](https://www.gnu.org/licenses/gpl-3.0.html) or\n[Apache-2.0 license](https://www.apache.org/licenses/LICENSE-2.0.html). Use whatever license you need for your project.\n\n_Note regarding the Apache-2.0 license, this library has an LGPL dependency which may go against the policy of some\norganizations such as ASF._\n"
  },
  {
    "path": "SERVICES.md",
    "content": "# Services\n\nLibADB only supports local services which can be requested through `AbsAdbConnectionManager#openStream(String)` or\n`AdbConnection#open(String)`.\n\n- `shell:command arg1 arg2 ...`\n\n  Run `command arg1 arg2 ...` in a shell on the device, and return its output and error streams. Note that arguments\n  must be separated by spaces. If an argument contains a space, it must be quoted with double-quotes. Arguments cannot\n  contain double quotes or things will go very wrong.\n\n- `shell:`\n\n  Start an interactive shell session on the device. Redirect stdin/stdout/stderr as appropriate.\n\n- `dev:<path>`\n\n  Opens a device file and connects the client directly to it for read/write purposes. Useful for debugging, but may \n  require special privileges and thus may not run on all devices. `<path>` is a full path from the root of the\n  filesystem.\n\n- `tcp:<port>`\n\n  Tries to connect to tcp port `<port>` on localhost.\n\n- `tcp:<port>:<server-name>`\n\n  Tries to connect to tcp port `<port>` on machine `<server-name>` from the device. This can be useful to debug some\n  networking/proxy issues that can only be revealed on the device itself.\n\n- `local:<path>`\n\n  Tries to connect to a Unix domain socket `<path>` on the device.\n\n- `localreserved:<path>`/\n  `localabstract:<path>`/\n  `localfilesystem:<path>`\n\n  Variants of `local:<path>` that are used to access other Android socket namespaces.\n\n- `sync:`\n\n  This starts the file synchronization service, used to implement \"adb push\" and \"adb pull\". Since this service is\n  pretty complex, it will be detailed in a companion document named SYNC.TXT\n\n- `reverse:<forward-command>`\n\n  This implements the 'adb reverse' feature, i.e. the ability to reverse socket connections from a device to the host.\n  `<forward-command>` is one of the forwarding commands that are described above, as in:\n\n      list-forward\n      forward:<local>;<remote>\n      forward:norebind:<local>;<remote>\n      killforward-all\n      killforward:<local>\n\n  Note that in this case, <local> corresponds to the socket on the device\n  and <remote> corresponds to the socket on the host.\n\n  The output of reverse:list-forward is the same as host:list-forward\n  except that <serial> will be just 'host'.\n\n## Reference\n- [SERVICES.TXT](https://android.googlesource.com/platform/packages/modules/adb/+/6a85258511fb13ebbbedba4e36616db4c6e970fb/SERVICES.TXT)\n"
  },
  {
    "path": "app/.gitignore",
    "content": "/build"
  },
  {
    "path": "app/build.gradle",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\nplugins {\n    id 'com.android.application'\n}\n\nandroid {\n    compileSdk 35\n    namespace \"io.github.muntashirakon.adb.testapp\"\n\n    defaultConfig {\n        applicationId \"io.github.muntashirakon.adb.testapp\"\n        minSdk 21\n        targetSdk 35\n        versionCode 8\n        versionName \"3.1.0\"\n    }\n\n    buildTypes {\n        release {\n            minifyEnabled false\n        }\n    }\n    compileOptions {\n        sourceCompatibility JavaVersion.VERSION_1_8\n        targetCompatibility JavaVersion.VERSION_1_8\n    }\n}\n\ndependencies {\n    implementation project(path: ':libadb')\n    implementation 'androidx.appcompat:appcompat:1.7.1'\n    implementation 'com.google.android.material:material:1.12.0'\n\n    // Library to generate X509Certificate. You can also use BouncyCastle for this.\n    implementation 'com.github.MuntashirAkon:sun-security-android:1.1'\n\n    // Bypass hidden API if you want to use Android default conscrypt. It also requires additional steps.\n    // See https://github.com/LSPosed/AndroidHiddenApiBypass to find out more about this.\n    // Comment out the line below if you do not need this.\n    implementation 'org.lsposed.hiddenapibypass:hiddenapibypass:6.1'\n\n    // Uncomment the line below if you want to use the custom conscrypt.\n    // implementation 'org.conscrypt:conscrypt-android:2.5.3'\n}\n"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "content": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <application\n        android:name=\".App\"\n        android:allowBackup=\"false\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:roundIcon=\"@mipmap/ic_launcher_round\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/Theme.Material3.DayNight.NoActionBar\">\n        <activity\n            android:name=\".MainActivity\"\n            android:exported=\"true\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/AdbConnectionManager.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android.content.Context;\nimport android.os.Build;\nimport android.sun.misc.BASE64Encoder;\nimport android.sun.security.provider.X509Factory;\nimport android.sun.security.x509.AlgorithmId;\nimport android.sun.security.x509.CertificateAlgorithmId;\nimport android.sun.security.x509.CertificateExtensions;\nimport android.sun.security.x509.CertificateIssuerName;\nimport android.sun.security.x509.CertificateSerialNumber;\nimport android.sun.security.x509.CertificateSubjectName;\nimport android.sun.security.x509.CertificateValidity;\nimport android.sun.security.x509.CertificateVersion;\nimport android.sun.security.x509.CertificateX509Key;\nimport android.sun.security.x509.KeyIdentifier;\nimport android.sun.security.x509.PrivateKeyUsageExtension;\nimport android.sun.security.x509.SubjectKeyIdentifierExtension;\nimport android.sun.security.x509.X500Name;\nimport android.sun.security.x509.X509CertImpl;\nimport android.sun.security.x509.X509CertInfo;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.nio.charset.StandardCharsets;\nimport java.security.KeyFactory;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.SecureRandom;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.CertificateFactory;\nimport java.security.spec.EncodedKeySpec;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.PKCS8EncodedKeySpec;\nimport java.util.Date;\nimport java.util.Random;\n\nimport io.github.muntashirakon.adb.AbsAdbConnectionManager;\n\npublic class AdbConnectionManager extends AbsAdbConnectionManager {\n    private static AbsAdbConnectionManager INSTANCE;\n\n    public static AbsAdbConnectionManager getInstance(@NonNull Context context) throws Exception {\n        if (INSTANCE == null) {\n            INSTANCE = new AdbConnectionManager(context);\n        }\n        return INSTANCE;\n    }\n\n    private PrivateKey mPrivateKey;\n    private Certificate mCertificate;\n\n    private AdbConnectionManager(@NonNull Context context) throws Exception {\n        setApi(Build.VERSION.SDK_INT);\n        mPrivateKey = readPrivateKeyFromFile(context);\n        mCertificate = readCertificateFromFile(context);\n        if (mPrivateKey == null) {\n            // Generate a new key pair\n            int keySize = 2048;\n            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"RSA\");\n            keyPairGenerator.initialize(keySize, SecureRandom.getInstance(\"SHA1PRNG\"));\n            KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();\n            PublicKey publicKey = generateKeyPair.getPublic();\n            mPrivateKey = generateKeyPair.getPrivate();\n            // Generate a new certificate\n            String subject = \"CN=My Awesome App\";\n            String algorithmName = \"SHA512withRSA\";\n            long expiryDate = System.currentTimeMillis() + 86400000;\n            CertificateExtensions certificateExtensions = new CertificateExtensions();\n            certificateExtensions.set(\"SubjectKeyIdentifier\", new SubjectKeyIdentifierExtension(\n                    new KeyIdentifier(publicKey).getIdentifier()));\n            X500Name x500Name = new X500Name(subject);\n            Date notBefore = new Date();\n            Date notAfter = new Date(expiryDate);\n            certificateExtensions.set(\"PrivateKeyUsage\", new PrivateKeyUsageExtension(notBefore, notAfter));\n            CertificateValidity certificateValidity = new CertificateValidity(notBefore, notAfter);\n            X509CertInfo x509CertInfo = new X509CertInfo();\n            x509CertInfo.set(\"version\", new CertificateVersion(2));\n            x509CertInfo.set(\"serialNumber\", new CertificateSerialNumber(new Random().nextInt() & Integer.MAX_VALUE));\n            x509CertInfo.set(\"algorithmID\", new CertificateAlgorithmId(AlgorithmId.get(algorithmName)));\n            x509CertInfo.set(\"subject\", new CertificateSubjectName(x500Name));\n            x509CertInfo.set(\"key\", new CertificateX509Key(publicKey));\n            x509CertInfo.set(\"validity\", certificateValidity);\n            x509CertInfo.set(\"issuer\", new CertificateIssuerName(x500Name));\n            x509CertInfo.set(\"extensions\", certificateExtensions);\n            X509CertImpl x509CertImpl = new X509CertImpl(x509CertInfo);\n            x509CertImpl.sign(mPrivateKey, algorithmName);\n            mCertificate = x509CertImpl;\n            // Write files\n            writePrivateKeyToFile(context, mPrivateKey);\n            writeCertificateToFile(context, mCertificate);\n        }\n    }\n\n    @NonNull\n    @Override\n    protected PrivateKey getPrivateKey() {\n        return mPrivateKey;\n    }\n\n    @NonNull\n    @Override\n    protected Certificate getCertificate() {\n        return mCertificate;\n    }\n\n    @NonNull\n    @Override\n    protected String getDeviceName() {\n        return \"MyAwesomeApp\";\n    }\n\n    @Nullable\n    private static Certificate readCertificateFromFile(@NonNull Context context)\n            throws IOException, CertificateException {\n        File certFile = new File(context.getFilesDir(), \"cert.pem\");\n        if (!certFile.exists()) return null;\n        try (InputStream cert = new FileInputStream(certFile)) {\n            return CertificateFactory.getInstance(\"X.509\").generateCertificate(cert);\n        }\n    }\n\n    private static void writeCertificateToFile(@NonNull Context context, @NonNull Certificate certificate)\n            throws CertificateEncodingException, IOException {\n        File certFile = new File(context.getFilesDir(), \"cert.pem\");\n        BASE64Encoder encoder = new BASE64Encoder();\n        try (OutputStream os = new FileOutputStream(certFile)) {\n            os.write(X509Factory.BEGIN_CERT.getBytes(StandardCharsets.UTF_8));\n            os.write('\\n');\n            encoder.encode(certificate.getEncoded(), os);\n            os.write('\\n');\n            os.write(X509Factory.END_CERT.getBytes(StandardCharsets.UTF_8));\n        }\n    }\n\n    @Nullable\n    private static PrivateKey readPrivateKeyFromFile(@NonNull Context context)\n            throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {\n        File privateKeyFile = new File(context.getFilesDir(), \"private.key\");\n        if (!privateKeyFile.exists()) return null;\n        byte[] privKeyBytes = new byte[(int) privateKeyFile.length()];\n        try (InputStream is = new FileInputStream(privateKeyFile)) {\n            is.read(privKeyBytes);\n        }\n        KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);\n        return keyFactory.generatePrivate(privateKeySpec);\n    }\n\n    private static void writePrivateKeyToFile(@NonNull Context context, @NonNull PrivateKey privateKey)\n            throws IOException {\n        File privateKeyFile = new File(context.getFilesDir(), \"private.key\");\n        try (OutputStream os = new FileOutputStream(privateKeyFile)) {\n           os.write(privateKey.getEncoded());\n        }\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/App.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.os.Build;\n\nimport org.lsposed.hiddenapibypass.HiddenApiBypass;\n\nimport io.github.muntashirakon.adb.PRNGFixes;\n\npublic class App extends Application {\n    @Override\n    public void onCreate() {\n        super.onCreate();\n        PRNGFixes.apply();\n    }\n\n    @Override\n    protected void attachBaseContext(Context base) {\n        super.attachBaseContext(base);\n        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n            HiddenApiBypass.addHiddenApiExemptions(\"L\");\n        }\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/MainActivity.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.text.InputType;\nimport android.text.TextUtils;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.ScrollView;\nimport android.widget.Toast;\n\nimport androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.appcompat.widget.AppCompatEditText;\nimport androidx.appcompat.widget.AppCompatTextView;\nimport androidx.lifecycle.ViewModelProvider;\n\nimport com.google.android.material.dialog.MaterialAlertDialogBuilder;\nimport com.google.android.material.textfield.TextInputEditText;\n\nimport java.util.Objects;\n\npublic class MainActivity extends AppCompatActivity {\n    private static final int DEFAULT_PORT_ADDRESS = 5555;\n\n    private MenuItem connectAdbMenu;\n    private MenuItem disconnectAdbMenu;\n    private MenuItem pairAdbMenu;\n    private ScrollView scrollView;\n\n    private AppCompatEditText commandInput;\n    private AppCompatTextView commandOutput;\n    private MainViewModel viewModel;\n    private boolean connected = false;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n        setSupportActionBar(findViewById(R.id.toolbar));\n        viewModel = new ViewModelProvider(this).get(MainViewModel.class);\n        scrollView = findViewById(R.id.scrollView);\n        commandInput = findViewById(R.id.command_input);\n        commandOutput = findViewById(R.id.command_output);\n        init();\n    }\n\n    private void init() {\n        commandInput.setOnEditorActionListener((v, actionId, event) -> {\n            if (actionId == EditorInfo.IME_ACTION_DONE && connected) {\n                String command = Objects.requireNonNull(commandInput.getText()).toString();\n                viewModel.execute(command);\n                return true;\n            }\n            return false;\n        });\n\n        // Observers\n        viewModel.watchConnectAdb().observe(this, isConnected -> {\n            connected = isConnected;\n            checkMenus();\n            if (isConnected) {\n                Toast.makeText(this, getString(R.string.connected_to_adb), Toast.LENGTH_SHORT).show();\n                openIme();\n            } else {\n                Toast.makeText(this, getString(R.string.disconnected_from_adb), Toast.LENGTH_SHORT).show();\n            }\n        });\n        viewModel.watchPairAdb().observe(this, isPaired -> {\n            if (isPaired) {\n                Toast.makeText(this, getString(R.string.pairing_successful), Toast.LENGTH_SHORT).show();\n            } else {\n                Toast.makeText(this, getString(R.string.pairing_failed), Toast.LENGTH_SHORT).show();\n            }\n        });\n        viewModel.watchAskPairAdb().observe(this, displayDialog -> {\n            if (displayDialog) {\n                pairAdb();\n            }\n        });\n        viewModel.watchCommandOutput().observe(this, output -> {\n            commandOutput.setText(output == null ? \"\" : output);\n            commandOutput.post(() -> scrollView.scrollTo(0, commandOutput.getHeight()));\n        });\n\n        // Try auto-connecting\n        viewModel.autoConnect();\n    }\n\n    @Override\n    protected void onResume() {\n        super.onResume();\n        openIme();\n    }\n\n    @Override\n    protected void onPause() {\n        super.onPause();\n        if (connected && commandInput != null) {\n            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n            imm.hideSoftInputFromWindow(commandInput.getWindowToken(), 0);\n        }\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.actions_main, menu);\n        connectAdbMenu = menu.findItem(R.id.action_connect);\n        disconnectAdbMenu = menu.findItem(R.id.action_disconnect);\n        pairAdbMenu = menu.findItem(R.id.action_pair);\n        return super.onCreateOptionsMenu(menu);\n    }\n\n    @Override\n    public boolean onPrepareOptionsMenu(Menu menu) {\n        if (pairAdbMenu != null) {\n            pairAdbMenu.setEnabled(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R);\n            pairAdbMenu.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R);\n        }\n        checkMenus();\n        return super.onPrepareOptionsMenu(menu);\n    }\n\n    @Override\n    public boolean onOptionsItemSelected(@NonNull MenuItem item) {\n        int id = item.getItemId();\n        if (id == R.id.action_connect) {\n            connectAdb();\n            return true;\n        }\n        if (id == R.id.action_disconnect) {\n            connectAdb();\n            return true;\n        }\n        if (id == R.id.action_pair) {\n            pairAdb();\n            return true;\n        }\n        return super.onOptionsItemSelected(item);\n    }\n\n    private void openIme() {\n        if (connected && commandInput != null && !commandInput.isFocused()) {\n            commandInput.requestFocus();\n            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n            imm.showSoftInput(commandInput, InputMethodManager.SHOW_IMPLICIT);\n        }\n    }\n\n    private void checkMenus() {\n        if (connectAdbMenu != null) {\n            connectAdbMenu.setEnabled(!connected);\n            connectAdbMenu.setVisible(!connected);\n        }\n        if (disconnectAdbMenu != null) {\n            disconnectAdbMenu.setEnabled(connected);\n            disconnectAdbMenu.setVisible(connected);\n        }\n    }\n\n    private void connectAdb() {\n        if (connected) {\n            viewModel.disconnect();\n            return;\n        }\n        AppCompatEditText editText = new AppCompatEditText(this);\n        editText.setInputType(InputType.TYPE_CLASS_NUMBER);\n        editText.setText(String.valueOf(DEFAULT_PORT_ADDRESS));\n        new MaterialAlertDialogBuilder(this)\n                .setTitle(R.string.connect_adb)\n                .setView(editText)\n                .setPositiveButton(R.string.connect_adb, (dialog, which) -> {\n                    CharSequence portString = editText.getText();\n                    if (portString != null && TextUtils.isDigitsOnly(portString)) {\n                        int port = Integer.parseInt(portString.toString());\n                        viewModel.connect(port);\n                    }\n                })\n                .setNegativeButton(android.R.string.cancel, null)\n                .show();\n    }\n\n    private void pairAdb() {\n        View view = getLayoutInflater().inflate(R.layout.dialog_input, null);\n        TextInputEditText pairingCodeEditText = view.findViewById(R.id.pairing_code);\n        TextInputEditText portNumberEditText = view.findViewById(R.id.port_number);\n        viewModel.watchPairingPort().observe(this, port -> {\n            if (port != -1) {\n                portNumberEditText.setText(String.valueOf(port));\n            } else {\n                portNumberEditText.setText(null);\n            }\n        });\n        viewModel.getPairingPort();\n        new MaterialAlertDialogBuilder(this)\n                .setTitle(R.string.pair_adb)\n                .setView(view)\n                .setPositiveButton(R.string.pair_adb, (dialog, which) -> {\n                    CharSequence pairingCode = pairingCodeEditText.getText();\n                    CharSequence portNumberString = portNumberEditText.getText();\n                    if (pairingCode != null && pairingCode.length() == 6 && portNumberString != null\n                            && TextUtils.isDigitsOnly(portNumberString)) {\n                        int port = Integer.parseInt(portNumberString.toString());\n                        viewModel.pair(port, pairingCode.toString());\n                    }\n                })\n                .setNegativeButton(android.R.string.cancel, null)\n                .setOnDismissListener(dialog -> viewModel.watchPairingPort().removeObservers(this))\n                .show();\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/io/github/muntashirakon/adb/testapp/MainViewModel.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.testapp;\n\nimport android.app.Application;\nimport android.os.Build;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.WorkerThread;\nimport androidx.lifecycle.AndroidViewModel;\nimport androidx.lifecycle.LiveData;\nimport androidx.lifecycle.MutableLiveData;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.nio.charset.StandardCharsets;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport io.github.muntashirakon.adb.AbsAdbConnectionManager;\nimport io.github.muntashirakon.adb.AdbPairingRequiredException;\nimport io.github.muntashirakon.adb.AdbStream;\nimport io.github.muntashirakon.adb.LocalServices;\nimport io.github.muntashirakon.adb.android.AdbMdns;\nimport io.github.muntashirakon.adb.android.AndroidUtils;\n\npublic class MainViewModel extends AndroidViewModel {\n    private final ExecutorService executor = Executors.newFixedThreadPool(3);\n    private final MutableLiveData<Boolean> connectAdb = new MutableLiveData<>();\n    private final MutableLiveData<Boolean> pairAdb = new MutableLiveData<>();\n    private final MutableLiveData<Boolean> askPairAdb = new MutableLiveData<>();\n    private final MutableLiveData<CharSequence> commandOutput = new MutableLiveData<>();\n    private final MutableLiveData<Integer> pairingPort = new MutableLiveData<>();\n\n    @Nullable\n    private AdbStream adbShellStream;\n\n    public MainViewModel(@NonNull Application application) {\n        super(application);\n    }\n\n    public LiveData<Boolean> watchConnectAdb() {\n        return connectAdb;\n    }\n\n    public LiveData<Boolean> watchPairAdb() {\n        return pairAdb;\n    }\n\n    public LiveData<Boolean> watchAskPairAdb() {\n        return askPairAdb;\n    }\n\n    public LiveData<CharSequence> watchCommandOutput() {\n        return commandOutput;\n    }\n\n    public LiveData<Integer> watchPairingPort() {\n        return pairingPort;\n    }\n\n    @Override\n    protected void onCleared() {\n        super.onCleared();\n        executor.submit(() -> {\n            try {\n                if (adbShellStream != null) {\n                    adbShellStream.close();\n                }\n            } catch (Exception e) {\n                e.printStackTrace();\n            }\n            try {\n                AdbConnectionManager.getInstance(getApplication()).close();\n            } catch (Exception e) {\n                e.printStackTrace();\n            }\n        });\n        executor.shutdown();\n    }\n\n    public void connect(int port) {\n        executor.submit(() -> {\n            try {\n                AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());\n                boolean connectionStatus;\n                try {\n                    connectionStatus = manager.connect(AndroidUtils.getHostIpAddress(getApplication()), port);\n                } catch (Throwable th) {\n                    th.printStackTrace();\n                    connectionStatus = false;\n                }\n                connectAdb.postValue(connectionStatus);\n            } catch (Throwable th) {\n                th.printStackTrace();\n                connectAdb.postValue(false);\n            }\n        });\n    }\n\n    public void autoConnect() {\n        executor.submit(this::autoConnectInternal);\n    }\n\n    public void disconnect() {\n        executor.submit(() -> {\n            try {\n                AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());\n                manager.disconnect();\n                connectAdb.postValue(false);\n            } catch (Throwable th) {\n                th.printStackTrace();\n                connectAdb.postValue(true);\n            }\n        });\n    }\n\n    public void getPairingPort() {\n        executor.submit(() -> {\n            AtomicInteger atomicPort = new AtomicInteger(-1);\n            CountDownLatch resolveHostAndPort = new CountDownLatch(1);\n\n            AdbMdns adbMdns = new AdbMdns(getApplication(), AdbMdns.SERVICE_TYPE_TLS_PAIRING, (hostAddress, port) -> {\n                atomicPort.set(port);\n                resolveHostAndPort.countDown();\n            });\n            adbMdns.start();\n\n            try {\n                if (!resolveHostAndPort.await(1, TimeUnit.MINUTES)) {\n                    return;\n                }\n            } catch (InterruptedException ignore) {\n            } finally {\n                adbMdns.stop();\n            }\n\n            pairingPort.postValue(atomicPort.get());\n        });\n    }\n\n    public void pair(int port, String pairingCode) {\n        executor.submit(() -> {\n            try {\n                boolean pairingStatus;\n                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n                    AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());\n                    pairingStatus = manager.pair(AndroidUtils.getHostIpAddress(getApplication()), port, pairingCode);\n                } else pairingStatus = false;\n                pairAdb.postValue(pairingStatus);\n                autoConnectInternal();\n            } catch (Throwable th) {\n                th.printStackTrace();\n                pairAdb.postValue(false);\n            }\n        });\n    }\n\n    @WorkerThread\n    private void autoConnectInternal() {\n        try {\n            AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());\n            boolean connected = false;\n            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n                try {\n                    connected = manager.autoConnect(getApplication(), 5000);\n                } catch (AdbPairingRequiredException e) {\n                    askPairAdb.postValue(true);\n                    return;\n                } catch (Throwable th) {\n                    th.printStackTrace();\n                }\n            }\n            if (!connected) {\n                connected = manager.connect(5555);\n            }\n            if (connected) {\n                connectAdb.postValue(true);\n            }\n        } catch (Throwable th) {\n            th.printStackTrace();\n        }\n    }\n\n    private volatile boolean clearEnabled;\n    private final Runnable outputGenerator = () -> {\n        try (BufferedReader reader = new BufferedReader(new InputStreamReader(adbShellStream.openInputStream()))) {\n            StringBuilder sb = new StringBuilder();\n            String s;\n            while ((s = reader.readLine()) != null) {\n                if (clearEnabled) {\n                    sb.delete(0, sb.length());\n                    clearEnabled = false;\n                }\n                sb.append(s).append(\"\\n\");\n                commandOutput.postValue(sb);\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    };\n\n    public void execute(String command) {\n        executor.submit(() -> {\n            try {\n                if (adbShellStream == null || adbShellStream.isClosed()) {\n                    AbsAdbConnectionManager manager = AdbConnectionManager.getInstance(getApplication());\n                    adbShellStream = manager.openStream(LocalServices.SHELL);\n                    new Thread(outputGenerator).start();\n                }\n                if (command.equals(\"clear\")) {\n                    clearEnabled = true;\n                }\n                try (OutputStream os = adbShellStream.openOutputStream()) {\n                    os.write(String.format(\"%1$s\\n\", command).getBytes(StandardCharsets.UTF_8));\n                    os.flush();\n                    os.write(\"\\n\".getBytes(StandardCharsets.UTF_8));\n                }\n            } catch (Exception e) {\n                e.printStackTrace();\n            }\n        });\n    }\n}\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_add_link.xml",
    "content": "<!-- SPDX-License-Identifier: Apache-2.0 -->\n<vector android:height=\"24dp\"\n    android:tint=\"#000000\"\n    android:viewportHeight=\"24\"\n    android:viewportWidth=\"24\"\n    android:width=\"24dp\"\n    xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <path\n        android:fillColor=\"@android:color/white\"\n        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\" />\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_launcher_background.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"108dp\" android:height=\"108dp\" android:viewportWidth=\"108\"\n    android:viewportHeight=\"108\">\n    <path android:fillColor=\"#3DDC84\" android:pathData=\"M0,0h108v108h-108z\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M9,0L9,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M19,0L19,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M29,0L29,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M39,0L39,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M49,0L49,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M59,0L59,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M69,0L69,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M79,0L79,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M89,0L89,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M99,0L99,108\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,9L108,9\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,19L108,19\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,29L108,29\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,39L108,39\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,49L108,49\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,59L108,59\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,69L108,69\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,79L108,79\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,89L108,89\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M0,99L108,99\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M19,29L89,29\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M19,39L89,39\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M19,49L89,49\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M19,59L89,59\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M19,69L89,69\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M19,79L89,79\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M29,19L29,89\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M39,19L39,89\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M49,19L49,89\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M59,19L59,89\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M69,19L69,89\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path android:fillColor=\"#00000000\" android:pathData=\"M79,19L79,89\" android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_link.xml",
    "content": "<!-- SPDX-License-Identifier: Apache-2.0 -->\n<vector android:height=\"24dp\"\n    android:tint=\"#000000\"\n    android:viewportHeight=\"24\"\n    android:viewportWidth=\"24\"\n    android:width=\"24dp\"\n    xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <path\n        android:fillColor=\"@android:color/white\"\n        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\" />\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable/ic_link_off.xml",
    "content": "<!-- SPDX-License-Identifier: Apache-2.0 -->\n<vector android:height=\"24dp\"\n    android:tint=\"#000000\"\n    android:viewportHeight=\"24\"\n    android:viewportWidth=\"24\"\n    android:width=\"24dp\"\n    xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <path\n        android:fillColor=\"@android:color/white\"\n        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\" />\n</vector>\n"
  },
  {
    "path": "app/src/main/res/drawable-v24/ic_launcher_foreground.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:aapt=\"http://schemas.android.com/aapt\"\n    android:width=\"108dp\" android:height=\"108dp\" android:viewportWidth=\"108\" android:viewportHeight=\"108\">\n    <path\n        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\">\n        <aapt:attr name=\"android:fillColor\">\n            <gradient android:endX=\"85.84757\" android:endY=\"92.4963\" android:startX=\"42.9492\" android:startY=\"49.59793\"\n                android:type=\"linear\">\n                <item android:color=\"#44000000\" android:offset=\"0.0\" />\n                <item android:color=\"#00000000\" android:offset=\"1.0\" />\n            </gradient>\n        </aapt:attr>\n    </path>\n    <path\n        android:fillColor=\"#FFFFFF\"\n        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\"\n        android:strokeColor=\"#00000000\" />\n</vector>"
  },
  {
    "path": "app/src/main/res/layout/activity_main.xml",
    "content": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    tools:context=\".MainActivity\">\n\n    <com.google.android.material.appbar.AppBarLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\">\n\n        <com.google.android.material.appbar.MaterialToolbar\n            android:id=\"@+id/toolbar\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            tools:menu=\"@menu/actions_main\" />\n\n    </com.google.android.material.appbar.AppBarLayout>\n\n    <ScrollView\n        android:id=\"@+id/scrollView\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:layout_marginBottom=\"?actionBarSize\"\n        app:layout_behavior=\"com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior\">\n\n        <androidx.appcompat.widget.AppCompatTextView\n            android:id=\"@+id/command_output\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:paddingVertical=\"8dp\"\n            android:paddingHorizontal=\"16dp\"\n            android:textIsSelectable=\"true\"\n            android:fontFamily=\"monospace\"\n            android:textSize=\"12sp\"\n            tools:text=\"Command output\" />\n    </ScrollView>\n\n    <com.google.android.material.bottomappbar.BottomAppBar\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"?actionBarSize\"\n        android:layout_gravity=\"bottom\"\n        app:navigationIcon=\"@null\">\n\n        <com.google.android.material.textfield.TextInputLayout\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\"\n            android:paddingEnd=\"8dp\"\n            android:hint=\"@string/enter_command\"\n            app:endIconMode=\"clear_text\"\n            tools:ignore=\"RtlSymmetry\">\n\n            <androidx.appcompat.widget.AppCompatEditText\n                android:id=\"@+id/command_input\"\n                android:layout_width=\"match_parent\"\n                android:layout_height=\"wrap_content\"\n                android:inputType=\"textNoSuggestions\"\n                android:fontFamily=\"monospace\"\n                android:maxLines=\"1\"\n                android:imeOptions=\"actionDone\" />\n\n        </com.google.android.material.textfield.TextInputLayout>\n\n    </com.google.android.material.bottomappbar.BottomAppBar>\n\n</androidx.coordinatorlayout.widget.CoordinatorLayout>"
  },
  {
    "path": "app/src/main/res/layout/dialog_input.xml",
    "content": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<androidx.appcompat.widget.LinearLayoutCompat xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    android:orientation=\"vertical\"\n    android:paddingHorizontal=\"16dp\"\n    android:paddingVertical=\"8dp\">\n\n    <com.google.android.material.textfield.TextInputLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:hint=\"@string/pairing_code\">\n\n        <com.google.android.material.textfield.TextInputEditText\n            android:id=\"@+id/pairing_code\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\" />\n\n    </com.google.android.material.textfield.TextInputLayout>\n\n    <com.google.android.material.textfield.TextInputLayout\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:layout_marginTop=\"8dp\"\n        android:hint=\"@string/port_number\">\n\n        <com.google.android.material.textfield.TextInputEditText\n            android:id=\"@+id/port_number\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"wrap_content\" />\n\n    </com.google.android.material.textfield.TextInputLayout>\n\n</androidx.appcompat.widget.LinearLayoutCompat>"
  },
  {
    "path": "app/src/main/res/menu/actions_main.xml",
    "content": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n    <item\n        android:id=\"@+id/action_connect\"\n        android:title=\"@string/connect_adb\"\n        android:icon=\"@drawable/ic_link\"\n        app:showAsAction=\"always\" />\n    <item\n        android:id=\"@+id/action_disconnect\"\n        android:title=\"@string/disconnect_adb\"\n        android:icon=\"@drawable/ic_link_off\"\n        app:showAsAction=\"always\" />\n    <item\n        android:id=\"@+id/action_pair\"\n        android:title=\"@string/pair_adb\"\n        android:icon=\"@drawable/ic_add_link\"\n        app:showAsAction=\"always\" />\n</menu>"
  },
  {
    "path": "app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "content": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<resources>\n    <string name=\"app_name\">ADB Shell</string>\n    <string name=\"connect_adb\">Connect</string>\n    <string name=\"pair_adb\">Pair</string>\n    <string name=\"enter_command\">Enter command</string>\n    <string name=\"run_command\">Run</string>\n    <string name=\"pairing_successful\">Pairing successful!</string>\n    <string name=\"pairing_failed\">Pairing failed!</string>\n    <string name=\"connected_to_adb\">Connected to ADB!</string>\n    <string name=\"disconnected_from_adb\">Disconnected from ADB!</string>\n    <string name=\"disconnect_adb\">Disconnect</string>\n    <string name=\"pairing_code\">Pairing Code</string>\n    <string name=\"port_number\">Port Number</string>\n</resources>\n"
  },
  {
    "path": "build.gradle",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\nbuildscript {\n    repositories {\n        google()\n        mavenCentral()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:8.9.2'\n        // NOTE: Do not place your application dependencies here; they belong\n        // in the individual module build.gradle files\n    }\n}\n\nwrapper {\n    distributionType = Wrapper.DistributionType.BIN\n}\n\nallprojects {\n    repositories {\n        google()\n        mavenCentral()\n        maven { url \"https://jitpack.io\" }\n    }\n    gradle.projectsEvaluated {\n        tasks.withType(JavaCompile).tap {\n            configureEach {\n                options.compilerArgs << \"-Xlint:unchecked\" << \"-Xlint:deprecation\"\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionSha256Sum=8fad3d78296ca518113f3d29016617c7f9367dc005f932bd9d93bf45ba46072b\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-9.0.0-bin.zip\nnetworkTimeout=10000\nvalidateDistributionUrl=true\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\nandroid.useAndroidX=true\nandroid.enableJetifier=true\nandroid.jetifier.ignorelist=bcprov-jdk15to18\nandroid.nonTransitiveRClass=true\nandroid.nonFinalResIds=false\n"
  },
  {
    "path": "gradlew",
    "content": "#!/bin/sh\n\n#\n# Copyright © 2015 the original authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n#\n\n##############################################################################\n#\n#   Gradle start up script for POSIX generated by Gradle.\n#\n#   Important for running:\n#\n#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is\n#       noncompliant, but you have some other compliant shell such as ksh or\n#       bash, then to run this script, type that shell name before the whole\n#       command line, like:\n#\n#           ksh Gradle\n#\n#       Busybox and similar reduced shells will NOT work, because this script\n#       requires all of these POSIX shell features:\n#         * functions;\n#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,\n#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;\n#         * compound commands having a testable exit status, especially «case»;\n#         * various built-in commands including «command», «set», and «ulimit».\n#\n#   Important for patching:\n#\n#   (2) This script targets any POSIX shell, so it avoids extensions provided\n#       by Bash, Ksh, etc; in particular arrays are avoided.\n#\n#       The \"traditional\" practice of packing multiple parameters into a\n#       space-separated string is a well documented source of bugs and security\n#       problems, so this is (mostly) avoided, by progressively accumulating\n#       options in \"$@\", and eventually passing that to Java.\n#\n#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,\n#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;\n#       see the in-line comments for details.\n#\n#       There are tweaks for specific operating systems such as AIX, CygWin,\n#       Darwin, MinGW, and NonStop.\n#\n#   (3) This script is generated from the Groovy template\n#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt\n#       within the Gradle project.\n#\n#       You can find Gradle at https://github.com/gradle/gradle/.\n#\n##############################################################################\n\n# Attempt to set APP_HOME\n\n# Resolve links: $0 may be a link\napp_path=$0\n\n# Need this for daisy-chained symlinks.\nwhile\n    APP_HOME=${app_path%\"${app_path##*/}\"}  # leaves a trailing /; empty if no leading path\n    [ -h \"$app_path\" ]\ndo\n    ls=$( ls -ld \"$app_path\" )\n    link=${ls#*' -> '}\n    case $link in             #(\n      /*)   app_path=$link ;; #(\n      *)    app_path=$APP_HOME$link ;;\n    esac\ndone\n\n# This is normally unused\n# shellcheck disable=SC2034\nAPP_BASE_NAME=${0##*/}\n# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)\nAPP_HOME=$( cd -P \"${APP_HOME:-./}\" > /dev/null && printf '%s\\n' \"$PWD\" ) || exit\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=maximum\n\nwarn () {\n    echo \"$*\"\n} >&2\n\ndie () {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n} >&2\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"$( uname )\" in                #(\n  CYGWIN* )         cygwin=true  ;; #(\n  Darwin* )         darwin=true  ;; #(\n  MSYS* | MINGW* )  msys=true    ;; #(\n  NONSTOP* )        nonstop=true ;;\nesac\n\nCLASSPATH=\"\\\\\\\"\\\\\\\"\"\n\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=$JAVA_HOME/jre/sh/java\n    else\n        JAVACMD=$JAVA_HOME/bin/java\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=java\n    if ! command -v java >/dev/null 2>&1\n    then\n        die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nfi\n\n# Increase the maximum file descriptors if we can.\nif ! \"$cygwin\" && ! \"$darwin\" && ! \"$nonstop\" ; then\n    case $MAX_FD in #(\n      max*)\n        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.\n        # shellcheck disable=SC2039,SC3045\n        MAX_FD=$( ulimit -H -n ) ||\n            warn \"Could not query maximum file descriptor limit\"\n    esac\n    case $MAX_FD in  #(\n      '' | soft) :;; #(\n      *)\n        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.\n        # shellcheck disable=SC2039,SC3045\n        ulimit -n \"$MAX_FD\" ||\n            warn \"Could not set maximum file descriptor limit to $MAX_FD\"\n    esac\nfi\n\n# Collect all arguments for the java command, stacking in reverse order:\n#   * args from the command line\n#   * the main class name\n#   * -classpath\n#   * -D...appname settings\n#   * --module-path (only if needed)\n#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.\n\n# For Cygwin or MSYS, switch paths to Windows format before running java\nif \"$cygwin\" || \"$msys\" ; then\n    APP_HOME=$( cygpath --path --mixed \"$APP_HOME\" )\n    CLASSPATH=$( cygpath --path --mixed \"$CLASSPATH\" )\n\n    JAVACMD=$( cygpath --unix \"$JAVACMD\" )\n\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    for arg do\n        if\n            case $arg in                                #(\n              -*)   false ;;                            # don't mess with options #(\n              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath\n                    [ -e \"$t\" ] ;;                      #(\n              *)    false ;;\n            esac\n        then\n            arg=$( cygpath --path --ignore --mixed \"$arg\" )\n        fi\n        # Roll the args list around exactly as many times as the number of\n        # args, so each arg winds up back in the position where it started, but\n        # possibly modified.\n        #\n        # NB: a `for` loop captures its iteration list before it begins, so\n        # changing the positional parameters here affects neither the number of\n        # iterations, nor the values presented in `arg`.\n        shift                   # remove old arg\n        set -- \"$@\" \"$arg\"      # push replacement arg\n    done\nfi\n\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS='\"-Xmx64m\" \"-Xms64m\"'\n\n# Collect all arguments for the java command:\n#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,\n#     and any embedded shellness will be escaped.\n#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be\n#     treated as '${Hostname}' itself on the command line.\n\nset -- \\\n        \"-Dorg.gradle.appname=$APP_BASE_NAME\" \\\n        -classpath \"$CLASSPATH\" \\\n        -jar \"$APP_HOME/gradle/wrapper/gradle-wrapper.jar\" \\\n        \"$@\"\n\n# Stop when \"xargs\" is not available.\nif ! command -v xargs >/dev/null 2>&1\nthen\n    die \"xargs is not available\"\nfi\n\n# Use \"xargs\" to parse quoted args.\n#\n# With -n1 it outputs one arg per line, with the quotes and backslashes removed.\n#\n# In Bash we could simply go:\n#\n#   readarray ARGS < <( xargs -n1 <<<\"$var\" ) &&\n#   set -- \"${ARGS[@]}\" \"$@\"\n#\n# but POSIX shell has neither arrays nor command substitution, so instead we\n# post-process each arg (as a line of input to sed) to backslash-escape any\n# character that might be a shell metacharacter, then use eval to reverse\n# that process (while maintaining the separation between arguments), and wrap\n# the whole thing up as a single \"set\" statement.\n#\n# This will of course break if any of these variables contains a newline or\n# an unmatched quote.\n#\n\neval \"set -- $(\n        printf '%s\\n' \"$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\" |\n        xargs -n1 |\n        sed ' s~[^-[:alnum:]+,./:=@_]~\\\\&~g; ' |\n        tr '\\n' ' '\n    )\" '\"$@\"'\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@rem\n@rem Copyright 2015 the original author or authors.\n@rem\n@rem Licensed under the Apache License, Version 2.0 (the \"License\");\n@rem you may not use this file except in compliance with the License.\n@rem You may obtain a copy of the License at\n@rem\n@rem      https://www.apache.org/licenses/LICENSE-2.0\n@rem\n@rem Unless required by applicable law or agreed to in writing, software\n@rem distributed under the License is distributed on an \"AS IS\" BASIS,\n@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n@rem See the License for the specific language governing permissions and\n@rem limitations under the License.\n@rem\n@rem SPDX-License-Identifier: Apache-2.0\n@rem\n\n@if \"%DEBUG%\"==\"\" @echo off\n@rem ##########################################################################\n@rem\n@rem  Gradle startup script for Windows\n@rem\n@rem ##########################################################################\n\n@rem Set local scope for the variables with windows NT shell\nif \"%OS%\"==\"Windows_NT\" setlocal\n\nset DIRNAME=%~dp0\nif \"%DIRNAME%\"==\"\" set DIRNAME=.\n@rem This is normally unused\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n\n@rem Resolve any \".\" and \"..\" in APP_HOME to make it shorter.\nfor %%i in (\"%APP_HOME%\") do set APP_HOME=%%~fi\n\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nset DEFAULT_JVM_OPTS=\"-Xmx64m\" \"-Xms64m\"\n\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\n\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\nif %ERRORLEVEL% equ 0 goto execute\n\necho. 1>&2\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2\necho. 1>&2\necho Please set the JAVA_HOME variable in your environment to match the 1>&2\necho location of your Java installation. 1>&2\n\ngoto fail\n\n:findJavaFromJavaHome\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n\nif exist \"%JAVA_EXE%\" goto execute\n\necho. 1>&2\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2\necho. 1>&2\necho Please set the JAVA_HOME variable in your environment to match the 1>&2\necho location of your Java installation. 1>&2\n\ngoto fail\n\n:execute\n@rem Setup the command line\n\nset CLASSPATH=\n\n\n@rem Execute Gradle\n\"%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\" %*\n\n:end\n@rem End local scope for the variables with windows NT shell\nif %ERRORLEVEL% equ 0 goto mainEnd\n\n:fail\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\nrem the _cmd.exe /c_ return code!\nset EXIT_CODE=%ERRORLEVEL%\nif %EXIT_CODE% equ 0 set EXIT_CODE=1\nif not \"\"==\"%GRADLE_EXIT_CONSOLE%\" exit %EXIT_CODE%\nexit /b %EXIT_CODE%\n\n:mainEnd\nif \"%OS%\"==\"Windows_NT\" endlocal\n\n:omega\n"
  },
  {
    "path": "jitpack.yml",
    "content": "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  - mvn -v"
  },
  {
    "path": "libadb/.gitignore",
    "content": "/build\n"
  },
  {
    "path": "libadb/build.gradle",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\nplugins {\n    id 'com.android.library'\n    id 'maven-publish'\n}\n\ngroup = 'io.github.muntashirakon'\nversion = '3.1.1'\n\nandroid {\n    compileSdk 35\n    namespace \"io.github.muntashirakon.adb\"\n\n    defaultConfig {\n        minSdk 1\n        targetSdk 35\n        aarMetadata {\n            minCompileSdk = 1\n        }\n    }\n\n    buildTypes {\n        release {\n            minifyEnabled false\n        }\n    }\n\n    compileOptions {\n        sourceCompatibility JavaVersion.VERSION_1_8\n        targetCompatibility JavaVersion.VERSION_1_8\n    }\n\n    publishing {\n        singleVariant(\"release\") {\n            withSourcesJar()\n            withJavadocJar()\n        }\n    }\n}\n\npublishing {\n    publications {\n        release(MavenPublication) {\n            artifactId = 'libadb'\n            afterEvaluate {\n                from components.release\n            }\n        }\n    }\n}\n\ndependencies {\n    implementation \"androidx.annotation:annotation:1.9.1\"\n    implementation 'org.bouncycastle:bcprov-jdk15to18:1.81'\n    implementation 'com.github.MuntashirAkon.spake2-java:spake2-android:2.2.1'\n\n    testImplementation 'junit:junit:4.13.2'\n}\n"
  },
  {
    "path": "libadb/src/main/AndroidManifest.xml",
    "content": "<!-- SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0 -->\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <uses-permission android:name=\"android.permission.INTERNET\" />\n</manifest>\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AbsAdbConnectionManager.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.content.Context;\nimport android.os.Build;\n\nimport androidx.annotation.CallSuper;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.WorkerThread;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.security.PrivateKey;\nimport java.security.cert.Certificate;\nimport java.util.Objects;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport javax.security.auth.DestroyFailedException;\n\nimport io.github.muntashirakon.adb.android.AdbMdns;\n\n@SuppressWarnings(\"unused\")\npublic abstract class AbsAdbConnectionManager implements Closeable {\n    private final Object mLock = new Object();\n    @Nullable\n    private AdbConnection mAdbConnection;\n    private String mHostAddress = \"127.0.0.1\";\n    private int mApi = Build.VERSION_CODES.BASE;\n    private long mTimeout = Long.MAX_VALUE;\n    private TimeUnit mTimeoutUnit = TimeUnit.MILLISECONDS;\n    private boolean mThrowOnUnauthorised = false;\n\n    /**\n     * Return generated/stored private key.\n     */\n    @NonNull\n    protected abstract PrivateKey getPrivateKey();\n\n    /**\n     * Return public key wrapped around a certificate.\n     */\n    @NonNull\n    protected abstract Certificate getCertificate();\n\n    /**\n     * Return a name for the device. This can be the app label, hostname or user@hostname.\n     */\n    @NonNull\n    protected abstract String getDeviceName();\n\n    /**\n     * Set host address for this connection. On the same device, this should be {@code 127.0.0.1}.\n     */\n    @CallSuper\n    public void setHostAddress(@NonNull String hostAddress) {\n        mHostAddress = Objects.requireNonNull(hostAddress);\n    }\n\n    /**\n     * Get host address for this connection. Default value is {@code 127.0.0.1}.\n     */\n    @NonNull\n    public String getHostAddress() {\n        return mHostAddress;\n    }\n\n    /**\n     * Set Android API (i.e. SDK) version for this connection. If the daemon and the client are located in the same\n     * directory, the value should be {@link Build.VERSION#SDK_INT} in order to improve performance as well as security.\n     *\n     * @param api The API version, default is {@link Build.VERSION_CODES#BASE}.\n     */\n    public void setApi(int api) {\n        this.mApi = api;\n    }\n\n    /**\n     * Get Android API (i.e. SDK) version for this connection. Default value is {@link Build.VERSION_CODES#BASE}.\n     */\n    public int getApi() {\n        return mApi;\n    }\n\n    /**\n     * Set time to wait for the connection to be made.\n     *\n     * @param timeout Timeout value\n     * @param unit    Timeout unit\n     */\n    @CallSuper\n    public void setTimeout(long timeout, TimeUnit unit) {\n        mTimeout = timeout;\n        mTimeoutUnit = unit;\n    }\n\n    /**\n     * Get time to wait for the connection to be made. If not set using {@link #setTimeout(long, TimeUnit)}, the default\n     * timeout is {@link Long#MAX_VALUE} milliseconds.\n     *\n     * @return Timeout in milliseconds\n     */\n    public long getTimeout() {\n        return mTimeoutUnit.toMillis(mTimeout);\n    }\n\n    /**\n     * Get the unit for the timeout. If not set using {@link #setTimeout(long, TimeUnit)}, the default timeout unit is\n     * {@link TimeUnit#MILLISECONDS}.\n     */\n    @NonNull\n    public TimeUnit getTimeoutUnit() {\n        return mTimeoutUnit;\n    }\n\n    /**\n     * Set whether to throw {@link AdbAuthenticationFailedException} if the daemon rejects the first authentication\n     * attempt.\n     *\n     * @param throwOnUnauthorised {@code true} to throw {@link AdbAuthenticationFailedException} or {@code false}\n     *                            otherwise.\n     */\n    @CallSuper\n    public void setThrowOnUnauthorised(boolean throwOnUnauthorised) {\n        mThrowOnUnauthorised = throwOnUnauthorised;\n    }\n\n    /**\n     * Get whether to throw {@link AdbAuthenticationFailedException} if the daemon rejects the first authentication\n     * attempt.\n     *\n     * @return {@code true} if the system is configured to throw {@link AdbAuthenticationFailedException} or\n     * {@code false} otherwise. The default value is {@code false}.\n     */\n    public boolean isThrowOnUnauthorised() {\n        return mThrowOnUnauthorised;\n    }\n\n    /**\n     * Get the {@link AdbConnection} backed by this object.\n     *\n     * @return Underlying {@link AdbConnection}, or {@code null} if the connection hasn't been made yet.\n     */\n    @CallSuper\n    @Nullable\n    public AdbConnection getAdbConnection() {\n        synchronized (mLock) {\n            return mAdbConnection;\n        }\n    }\n\n    /**\n     * Check if it is connected to an ADB daemon.\n     *\n     * @return {@code true} if connected, {@code false} otherwise.\n     */\n    public boolean isConnected() {\n        synchronized (mLock) {\n            return mAdbConnection != null && mAdbConnection.isConnected() && mAdbConnection.isConnectionEstablished();\n        }\n    }\n\n    /**\n     * Attempt to connect to ADB by performing an automatic network discovery of TLS host and port. Host address set by\n     * {@link #setHostAddress(String)} is ignored.\n     *\n     * @param context       Application context\n     * @param timeoutMillis Amount of time spent in searching for a host and a port.\n     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection\n     * attempt is unsuccessful, or it has already been made.\n     * @throws IOException                      If the socket connection could not be made.\n     * @throws InterruptedException             If timeout has reached.\n     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB\n     *                                          daemon has rejected the first authentication attempt, which indicates\n     *                                          that the daemon has not saved the public key from a previous connection.\n     * @throws AdbPairingRequiredException      If ADB lacks pairing\n     */\n    @WorkerThread\n    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)\n    public boolean connectTls(@NonNull Context context, long timeoutMillis)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        return autoConnect(context, AdbMdns.SERVICE_TYPE_TLS_CONNECT, timeoutMillis);\n    }\n\n    /**\n     * Attempt to connect to ADB by performing an automatic network discovery of TCP host and port. Host address set by\n     * {@link #setHostAddress(String)} is ignored.\n     *\n     * @param context       Application context\n     * @param timeoutMillis Amount of time spent in searching for a host and a port.\n     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection\n     * attempt is unsuccessful, or it has already been made.\n     * @throws IOException                      If the socket connection could not be made.\n     * @throws InterruptedException             If timeout has reached.\n     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB\n     *                                          daemon has rejected the first authentication attempt, which indicates\n     *                                          that the daemon has not saved the public key from a previous connection.\n     * @throws AdbPairingRequiredException      If ADB lacks pairing\n     */\n    @WorkerThread\n    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)\n    public boolean connectTcp(@NonNull Context context, long timeoutMillis)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        return autoConnect(context, AdbMdns.SERVICE_TYPE_ADB, timeoutMillis);\n    }\n\n    /**\n     * Attempt to connect to ADB by performing an automatic network discovery of host and port. Host address set by\n     * {@link #setHostAddress(String)} is ignored.\n     *\n     * @param context       Application context\n     * @param timeoutMillis Amount of time spent in searching for a host and a port.\n     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection\n     * attempt is unsuccessful, or it has already been made.\n     * @throws IOException                      If the socket connection could not be made.\n     * @throws InterruptedException             If timeout has reached.\n     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB\n     *                                          daemon has rejected the first authentication attempt, which indicates\n     *                                          that the daemon has not saved the public key from a previous connection.\n     * @throws AdbPairingRequiredException      If ADB lacks pairing\n     */\n    @WorkerThread\n    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)\n    public boolean autoConnect(@NonNull Context context, long timeoutMillis)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        synchronized (mLock) {\n            AtomicInteger atomicPort = new AtomicInteger(-1);\n            AtomicReference<String> atomicHostAddress = new AtomicReference<>(null);\n            CountDownLatch resolveHostAndPort = new CountDownLatch(1);\n\n            AdbMdns adbMdnsTcp = new AdbMdns(context, AdbMdns.SERVICE_TYPE_ADB, (hostAddress, port) -> {\n                if (hostAddress != null) {\n                    atomicHostAddress.set(hostAddress.getHostAddress());\n                    atomicPort.set(port);\n                }\n                resolveHostAndPort.countDown();\n            });\n            adbMdnsTcp.start();\n\n            AdbMdns adbMdnsTls = new AdbMdns(context, AdbMdns.SERVICE_TYPE_TLS_CONNECT, (hostAddress, port) -> {\n                if (hostAddress != null) {\n                    atomicHostAddress.set(hostAddress.getHostAddress());\n                    atomicPort.set(port);\n                }\n                resolveHostAndPort.countDown();\n            });\n            adbMdnsTls.start();\n\n            try {\n                if (!resolveHostAndPort.await(timeoutMillis, TimeUnit.MILLISECONDS)) {\n                    throw new InterruptedException(\"Timed out while trying to find a valid host address and port\");\n                }\n            } finally {\n                adbMdnsTcp.stop();\n                adbMdnsTls.stop();\n            }\n\n            String host = atomicHostAddress.get();\n            int port = atomicPort.get();\n\n            if (host == null || port == -1) {\n                throw new IOException(\"Could not find any valid host address or port\");\n            }\n\n            mHostAddress = host;\n            mAdbConnection = new AdbConnection.Builder(host, port)\n                    .setApi(mApi)\n                    .setKeyPair(getAdbKeyPair())\n                    .setDeviceName(Objects.requireNonNull(getDeviceName()))\n                    .build();\n            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);\n        }\n    }\n\n    @WorkerThread\n    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)\n    private boolean autoConnect(@NonNull Context context, @AdbMdns.ServiceType @NonNull String serviceType, long timeoutMillis)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        synchronized (mLock) {\n            AtomicInteger atomicPort = new AtomicInteger(-1);\n            AtomicReference<String> atomicHostAddress = new AtomicReference<>(null);\n            CountDownLatch resolveHostAndPort = new CountDownLatch(1);\n\n            AdbMdns adbMdns = new AdbMdns(context, serviceType, (hostAddress, port) -> {\n                if (hostAddress != null) {\n                    atomicHostAddress.set(hostAddress.getHostAddress());\n                    atomicPort.set(port);\n                }\n                resolveHostAndPort.countDown();\n            });\n            adbMdns.start();\n\n            try {\n                if (!resolveHostAndPort.await(timeoutMillis, TimeUnit.MILLISECONDS)) {\n                    throw new InterruptedException(\"Timed out while trying to find a valid host address and port\");\n                }\n            } finally {\n                adbMdns.stop();\n            }\n\n            String host = atomicHostAddress.get();\n            int port = atomicPort.get();\n\n            if (host == null || port == -1) {\n                throw new IOException(\"Could not find any valid host address or port\");\n            }\n\n            mHostAddress = host;\n            mAdbConnection = new AdbConnection.Builder(host, port)\n                    .setApi(mApi)\n                    .setKeyPair(getAdbKeyPair())\n                    .setDeviceName(Objects.requireNonNull(getDeviceName()))\n                    .build();\n            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);\n        }\n    }\n\n    /**\n     * Attempt to connect to ADB given a port number. Host address is set via {@link #setHostAddress(String)}.\n     *\n     * @param port Port number\n     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection\n     * attempt is unsuccessful, or it has already been made.\n     * @throws IOException                      If the socket connection could not be made.\n     * @throws InterruptedException             If timeout has reached.\n     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the ADB\n     *                                          daemon has rejected the first authentication attempt, which indicates\n     *                                          that the daemon has not saved the public key from a previous connection.\n     * @throws AdbPairingRequiredException      If ADB lacks pairing\n     */\n    @WorkerThread\n    public boolean connect(int port) throws IOException, InterruptedException, AdbPairingRequiredException {\n        synchronized (mLock) {\n            if (isConnected()) {\n                return false;\n            }\n            mAdbConnection = new AdbConnection.Builder(mHostAddress, port)\n                    .setApi(mApi)\n                    .setKeyPair(getAdbKeyPair())\n                    .setDeviceName(Objects.requireNonNull(getDeviceName()))\n                    .build();\n            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);\n        }\n    }\n\n    /**\n     * Attempt to connect to ADB via a host address and a port number.\n     *\n     * @param host Host address to use instead of taking it from the {@link #getHostAddress()}\n     * @param port Port number\n     * @return {@code true} if and only if the connection is successful. It returns {@code false} if the connection\n     * attempt is unsuccessful, or it has already been made.\n     * @throws IOException                      If the socket connection could not be made.\n     * @throws InterruptedException             If timeout has reached.\n     * @throws AdbAuthenticationFailedException If {@link #isThrowOnUnauthorised()} is set to {@code true}, and the\n     *                                          ADB daemon has rejected the first authentication attempt, which\n     *                                          indicates that the daemon has not saved the public key from a previous\n     *                                          connection.\n     * @throws AdbPairingRequiredException      If ADB lacks pairing\n     */\n    @WorkerThread\n    public boolean connect(@NonNull String host, int port)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        synchronized (mLock) {\n            if (isConnected()) {\n                return false;\n            }\n            mHostAddress = host;\n            mAdbConnection = new AdbConnection.Builder(host, port)\n                    .setApi(mApi)\n                    .setKeyPair(getAdbKeyPair())\n                    .setDeviceName(Objects.requireNonNull(getDeviceName()))\n                    .build();\n            return mAdbConnection.connect(mTimeout, mTimeoutUnit, mThrowOnUnauthorised);\n        }\n    }\n\n    /**\n     * Disconnect the underlying {@link AdbConnection}.\n     *\n     * @throws IOException If the underlying socket fails to close\n     */\n    public void disconnect() throws IOException {\n        synchronized (mLock) {\n            if (mAdbConnection != null) {\n                mAdbConnection.close();\n                mAdbConnection = null;\n            }\n        }\n    }\n\n    /**\n     * Opens an {@link AdbStream} object corresponding to the specified destination.\n     * This routine will block until the connection completes.\n     *\n     * @param destination The destination to open on the target\n     * @return {@link AdbStream} object corresponding to the specified destination\n     * @throws IOException                  If the steam fails or no connection has been made\n     * @throws InterruptedException         If the stream fails while sending the packet\n     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8.\n     */\n    @WorkerThread\n    @NonNull\n    public AdbStream openStream(String destination) throws IOException, InterruptedException {\n        synchronized (mLock) {\n            if (mAdbConnection != null && mAdbConnection.isConnected()) {\n                try {\n                    return mAdbConnection.open(destination);\n                } catch (AdbPairingRequiredException e) {\n                    throw new IllegalStateException(e);\n                }\n            }\n            throw new IOException(\"Not connected to ADB.\");\n        }\n    }\n\n    /**\n     * Opens an {@link AdbStream} object corresponding to the specified destination.\n     * This routine will block until the connection completes.\n     *\n     * @param service The service to open. One of the services under {@link LocalServices.Services}.\n     * @param args    Additional arguments supported by the service (see the corresponding constant to learn more).\n     * @return AdbStream object corresponding to the specified destination\n     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8\n     * @throws IOException                  If the stream fails while sending the packet\n     * @throws InterruptedException         If we are unable to wait for the connection to finish\n     */\n    @NonNull\n    public AdbStream openStream(@LocalServices.Services int service, @NonNull String... args)\n            throws IOException, InterruptedException {\n        synchronized (mLock) {\n            if (mAdbConnection != null && mAdbConnection.isConnected()) {\n                try {\n                    return mAdbConnection.open(service, args);\n                } catch (AdbPairingRequiredException e) {\n                    throw new IllegalStateException(e);\n                }\n            }\n            throw new IOException(\"Not connected to ADB.\");\n        }\n    }\n\n    /**\n     * Pair with an ADB daemon given port number and pairing code.\n     *\n     * @param port        Port number\n     * @param pairingCode The six-digit pairing code as string\n     * @return {@code true} if the pairing is successful and {@code false} otherwise.\n     * @throws Exception If pairing failed for some reason.\n     */\n    @WorkerThread\n    @RequiresApi(Build.VERSION_CODES.GINGERBREAD)\n    public boolean pair(int port, @NonNull String pairingCode) throws Exception {\n        return pair(mHostAddress, port, pairingCode);\n    }\n\n    /**\n     * Pair with an ADB daemon given host address, port number and pairing code.\n     *\n     * @param host        Host address to use instead of taking it from the {@link #getHostAddress()}\n     * @param port        Port number\n     * @param pairingCode The six-digit pairing code as string\n     * @return {@code true} if the pairing is successful and {@code false} otherwise.\n     * @throws Exception If pairing failed for some reason.\n     */\n    @WorkerThread\n    @RequiresApi(Build.VERSION_CODES.GINGERBREAD)\n    public boolean pair(@NonNull String host, int port, @NonNull String pairingCode) throws Exception {\n        synchronized (mLock) {\n            KeyPair keyPair = getAdbKeyPair();\n            try (PairingConnectionCtx pairingClient = new PairingConnectionCtx(Objects.requireNonNull(host), port,\n                    StringCompat.getBytes(Objects.requireNonNull(pairingCode), \"UTF-8\"), keyPair, getDeviceName())) {\n                // TODO: 5/12/21 Return true/false instead of only exceptions\n                pairingClient.start();\n            }\n            return true;\n        }\n    }\n\n    /**\n     * Close the underlying {@link AdbConnection} and destroy the private key.\n     *\n     * @throws IOException If socket fails to close.\n     */\n    @Override\n    public void close() throws IOException {\n        try {\n            getPrivateKey().destroy();\n        } catch (DestroyFailedException | NoSuchMethodError e) {\n            e.printStackTrace();\n        }\n        if (mAdbConnection != null) {\n            mAdbConnection.close();\n            mAdbConnection = null;\n        }\n    }\n\n    @NonNull\n    private KeyPair getAdbKeyPair() {\n        return new KeyPair(Objects.requireNonNull(getPrivateKey()), Objects.requireNonNull(getCertificate()));\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbAuthenticationFailedException.java",
    "content": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\n/**\n * Thrown when the ADB daemon rejects our initial authentication attempt, which typically means that the peer has not\n * previously saved our public key.\n */\n// Copyright 2020 Sam Palmer\npublic class AdbAuthenticationFailedException extends RuntimeException {\n    public AdbAuthenticationFailedException() {\n        super(\"Initial authentication attempt rejected by peer.\");\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbConnection.java",
    "content": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimport android.os.Build;\nimport android.util.Log;\n\nimport androidx.annotation.GuardedBy;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.WorkerThread;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.ConnectException;\nimport java.net.Socket;\nimport java.security.PrivateKey;\nimport java.security.cert.Certificate;\nimport java.security.interfaces.RSAPublicKey;\nimport java.util.Objects;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.TimeUnit;\n\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocket;\nimport javax.security.auth.DestroyFailedException;\n\n/**\n * This class represents an ADB connection.\n */\n// Copyright 2013 Cameron Gutman\npublic class AdbConnection implements Closeable {\n    public static final String TAG = AdbConnection.class.getSimpleName();\n\n    /**\n     * The underlying socket that this class uses to communicate with the target device.\n     */\n    @NonNull\n    private final Socket mSocket;\n\n    @NonNull\n    private final String mHost;\n\n    private final int mPort;\n\n    private final int mApi;\n\n    /**\n     * The last allocated local stream ID. The ID chosen for the next stream will be this value + 1.\n     */\n    private int mLastLocalId;\n\n    /**\n     * The input stream that this class uses to read from the socket.\n     */\n    @GuardedBy(\"lock\")\n    @NonNull\n    private final InputStream mPlainInputStream;\n\n    /**\n     * The output stream that this class uses to read from the socket.\n     */\n    @GuardedBy(\"lock\")\n    @NonNull\n    private final OutputStream mPlainOutputStream;\n\n    /**\n     * The input stream that this class uses to read from the TLS socket.\n     */\n    @GuardedBy(\"lock\")\n    @Nullable\n    private volatile InputStream mTlsInputStream;\n\n    /**\n     * The output stream that this class uses to read from the TLS socket.\n     */\n    @GuardedBy(\"lock\")\n    @Nullable\n    private volatile OutputStream mTlsOutputStream;\n\n    /**\n     * The backend thread that handles responding to ADB packets.\n     */\n    @NonNull\n    private final Thread mConnectionThread;\n\n    /**\n     * Specifies whether a CNXN has been attempted.\n     */\n    private volatile boolean mConnectAttempted;\n\n    /**\n     * Whether the connection thread should give up if the first authentication attempt fails.\n     */\n    private volatile boolean mAbortOnUnauthorised;\n\n    /**\n     * Whether the first authentication attempt failed and {@link #mAbortOnUnauthorised} was {@code true}.\n     */\n    private volatile boolean mAuthorisationFailed;\n\n    /**\n     * Specifies whether a CNXN packet has been received from the peer.\n     */\n    private volatile boolean mConnectionEstablished;\n\n    /**\n     * Exceptions that occur in {@link #createConnectionThread()}.\n     */\n    @Nullable\n    private volatile Exception mConnectionException;\n\n    /**\n     * Specifies the maximum amount data that can be sent to the remote peer.\n     * This is only valid after connect() returns successfully.\n     */\n    private volatile int mMaxData;\n\n    private volatile int mProtocolVersion;\n\n    @NonNull\n    private final KeyPair mKeyPair;\n\n    @NonNull\n    private volatile String mDeviceName = \"Unknown Device\";\n\n    /**\n     * Specifies whether this connection has already sent a signed token.\n     */\n    private volatile boolean mSentSignature;\n\n    /**\n     * A hash map of our opened streams indexed by local ID.\n     */\n    @NonNull\n    private final ConcurrentHashMap<Integer, AdbStream> mOpenedStreams;\n\n    private volatile boolean mIsTls = false;\n\n    @GuardedBy(\"lock\")\n    @NonNull\n    private final Object mLock = new Object();\n\n    /**\n     * Creates a AdbConnection object associated with the socket and crypto object specified.\n     *\n     * @return A new AdbConnection object.\n     * @throws IOException If there is a socket error\n     */\n    @WorkerThread\n    @NonNull\n    public static AdbConnection create(@NonNull String host, int port, @NonNull PrivateKey privateKey,\n                                       @NonNull Certificate certificate)\n            throws IOException {\n        return create(host, port, privateKey, certificate, Build.VERSION_CODES.BASE);\n    }\n\n    /**\n     * Creates a AdbConnection object associated with the socket and crypto object specified.\n     *\n     * @return A new AdbConnection object.\n     * @throws IOException If there is a socket error\n     */\n    @WorkerThread\n    @NonNull\n    public static AdbConnection create(@NonNull String host, int port, @NonNull PrivateKey privateKey,\n                                       @NonNull Certificate certificate, int api)\n            throws IOException {\n        return create(host, port, new KeyPair(Objects.requireNonNull(privateKey), Objects.requireNonNull(certificate)),\n                api);\n    }\n\n    /**\n     * Creates a AdbConnection object associated with the socket and crypto object specified.\n     *\n     * @return A new AdbConnection object.\n     * @throws IOException If there is a socket error\n     */\n    @WorkerThread\n    @NonNull\n    static AdbConnection create(@NonNull String host, int port, @NonNull KeyPair keyPair, int api) throws IOException {\n        return new AdbConnection(host, port, keyPair, api);\n    }\n\n    /**\n     * Internal constructor to initialize some internal state\n     */\n    @WorkerThread\n    private AdbConnection(@NonNull String host, int port, @NonNull KeyPair keyPair, int api) throws IOException {\n        this.mHost = Objects.requireNonNull(host);\n        this.mPort = port;\n        this.mApi = api;\n        this.mProtocolVersion = AdbProtocol.getProtocolVersion(mApi);\n        this.mMaxData = AdbProtocol.getMaxData(api);\n        this.mKeyPair = Objects.requireNonNull(keyPair);\n        try {\n            this.mSocket = new Socket(host, port);\n        } catch (Throwable th) {\n            //noinspection UnnecessaryInitCause\n            throw (IOException) new IOException().initCause(th);\n        }\n        this.mPlainInputStream = mSocket.getInputStream();\n        this.mPlainOutputStream = mSocket.getOutputStream();\n\n        // Disable Nagle because we're sending tiny packets\n        mSocket.setTcpNoDelay(true);\n\n        this.mOpenedStreams = new ConcurrentHashMap<>();\n        this.mLastLocalId = 0;\n        this.mConnectionThread = createConnectionThread();\n    }\n\n    @GuardedBy(\"lock\")\n    @NonNull\n    private InputStream getInputStream() {\n        return mIsTls ? Objects.requireNonNull(mTlsInputStream) : mPlainInputStream;\n    }\n\n    @GuardedBy(\"lock\")\n    @NonNull\n    private OutputStream getOutputStream() {\n        return mIsTls ? Objects.requireNonNull(mTlsOutputStream) : mPlainOutputStream;\n    }\n\n    /**\n     * Creates a new connection thread.\n     *\n     * @return A new connection thread.\n     */\n    @NonNull\n    private Thread createConnectionThread() {\n        return new Thread(() -> {\n            loop:\n            while (!mConnectionThread.isInterrupted()) {\n                try {\n                    // Read and parse a message off the socket's input stream\n                    AdbProtocol.Message msg = AdbProtocol.Message.parse(getInputStream(), mProtocolVersion, mMaxData);\n\n                    switch (msg.command) {\n                        // Stream-oriented commands\n                        case AdbProtocol.A_OKAY:\n                        case AdbProtocol.A_WRTE:\n                        case AdbProtocol.A_CLSE: {\n                            // Ignore all packets when not connected\n                            if (!mConnectionEstablished) {\n                                continue;\n                            }\n\n                            // Get the stream object corresponding to the packet\n                            AdbStream waitingStream = mOpenedStreams.get(msg.arg1);\n                            if (waitingStream == null) {\n                                continue;\n                            }\n\n                            synchronized (waitingStream) {\n                                if (msg.command == AdbProtocol.A_OKAY) {\n                                    // We're ready for writes\n                                    waitingStream.updateRemoteId(msg.arg0);\n                                    waitingStream.readyForWrite();\n\n                                    // Notify an open/write\n                                    waitingStream.notify();\n                                } else if (msg.command == AdbProtocol.A_WRTE) {\n                                    // Got some data from our partner\n                                    waitingStream.addPayload(msg.payload);\n\n                                    // Tell it we're ready for more\n                                    waitingStream.sendReady();\n                                } else { // if (msg.command == AdbProtocol.A_CLSE) {\n                                    mOpenedStreams.remove(msg.arg1);\n                                    // Notify readers and writers\n                                    waitingStream.notifyClose(true);\n                                }\n                            }\n                            break;\n                        }\n                        case AdbProtocol.A_STLS: {\n                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {\n                                sendPacket(AdbProtocol.generateStls());\n\n                                SSLContext sslContext = SslUtils.getSslContext(mKeyPair);\n                                SSLSocket tlsSocket = (SSLSocket) sslContext.getSocketFactory()\n                                        .createSocket(mSocket, mHost, mPort, true);\n                                tlsSocket.startHandshake();\n                                Log.d(TAG, \"Handshake succeeded.\");\n\n                                synchronized (AdbConnection.this) {\n                                    mTlsInputStream = tlsSocket.getInputStream();\n                                    mTlsOutputStream = tlsSocket.getOutputStream();\n                                    mIsTls = true;\n                                }\n                            }\n                            break;\n                        }\n                        case AdbProtocol.A_AUTH: {\n                            if (mIsTls) {\n                                break;\n                            }\n                            if (msg.arg0 != AdbProtocol.ADB_AUTH_TOKEN) {\n                                break;\n                            }\n                            byte[] packet;\n                            // This is an authentication challenge\n                            if (mSentSignature) {\n                                if (mAbortOnUnauthorised) {\n                                    mAuthorisationFailed = true;\n                                    break loop;\n                                }\n\n                                // We've already tried our signature, so send our public key\n                                packet = AdbProtocol.generateAuth(AdbProtocol.ADB_AUTH_RSAPUBLICKEY, AndroidPubkey\n                                        .encodeWithName((RSAPublicKey) mKeyPair.getPublicKey(), mDeviceName));\n                            } else {\n                                // Sign the token\n                                packet = AdbProtocol.generateAuth(AdbProtocol.ADB_AUTH_SIGNATURE, AndroidPubkey\n                                        .adbAuthSign(mKeyPair.getPrivateKey(), msg.payload));\n                                mSentSignature = true;\n                            }\n\n                            // Write the AUTH reply\n                            sendPacket(packet);\n                            break;\n                        }\n                        case AdbProtocol.A_CNXN: {\n                            synchronized (AdbConnection.this) {\n                                mProtocolVersion = msg.arg0;\n                                mMaxData = msg.arg1;\n                                mConnectionEstablished = true;\n                                AdbConnection.this.notifyAll();\n                            }\n                            break;\n                        }\n                        case AdbProtocol.A_OPEN:\n                        case AdbProtocol.A_SYNC:\n                        default:\n                            Log.e(TAG, String.format(\"Unrecognized command = 0x%x\", msg.command));\n                            // Unrecognized packet, just drop it\n                            break;\n                    }\n                } catch (Exception e) {\n                    mConnectionException = e;\n                    e.printStackTrace();\n                    // The cleanup is taken care of by a combination of this thread and close()\n                    break;\n                }\n            }\n\n            // This thread takes care of cleaning up pending streams\n            synchronized (AdbConnection.this) {\n                cleanupStreams();\n                AdbConnection.this.notifyAll();\n                mConnectionEstablished = false;\n                mConnectAttempted = false;\n            }\n        });\n    }\n\n    /**\n     * Set a name for the device. Default is “Unknown Device”.\n     *\n     * @param deviceName Name of the device, could be the app label, hostname or user@hostname.\n     */\n    public void setDeviceName(@NonNull String deviceName) {\n        this.mDeviceName = Objects.requireNonNull(deviceName);\n    }\n\n    /**\n     * Get the version of the ADB protocol supported by the ADB daemon. The result may depend on the API version\n     * specified and whether the connection has been established. In API 29 (Android 9) or later, the daemon returns\n     * {@link AdbProtocol#A_VERSION_SKIP_CHECKSUM} regardless of the protocol used to create the connection. So, if\n     * {@link #mApi} is set to API 28 or earlier but the OS version is Android 9 or later, before establishing the\n     * connection, it returns {@link AdbProtocol#A_VERSION_MIN}, and after establishing the connection, it returns\n     * {@link AdbProtocol#A_VERSION_SKIP_CHECKSUM}. In other cases, it always returns {@link AdbProtocol#A_VERSION_MIN}.\n     *\n     * @see #isConnectionEstablished()\n     */\n    public int getProtocolVersion() {\n        return mProtocolVersion;\n    }\n\n    /**\n     * Get the max data size supported by the ADB daemon. A connection have to be attempted before calling this method\n     * and shall be blocked if the connection is in progress.\n     *\n     * @return The maximum data size indicated in the CONNECT packet.\n     * @throws InterruptedException        If a connection cannot be waited on.\n     * @throws IOException                 if the connection fails.\n     * @throws AdbPairingRequiredException If ADB lacks pairing\n     */\n    public int getMaxData() throws InterruptedException, IOException, AdbPairingRequiredException {\n        if (!mConnectAttempted) {\n            throw new IllegalStateException(\"connect() must be called first\");\n        }\n\n        waitForConnection(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n\n        return mMaxData;\n    }\n\n    /**\n     * Whether a connection has been established. A connection has been established if a CONNECT request has been\n     * received from the ADB daemon.\n     */\n    public boolean isConnectionEstablished() {\n        return mConnectionEstablished;\n    }\n\n    /**\n     * Whether the underlying socket is connected to an ADB daemon and is not in a closed state.\n     */\n    public boolean isConnected() {\n        return !mSocket.isClosed() && mSocket.isConnected();\n    }\n\n    /**\n     * Same as {@link #connect(long, TimeUnit, boolean)} without throwing anything if the first authentication attempt\n     * fails.\n     *\n     * @return {@code true} if the connection was established, or {@code false} if the connection timed out\n     * @throws IOException                 If the socket fails while connecting\n     * @throws InterruptedException        If timeout has reached\n     * @throws AdbPairingRequiredException If ADB lacks pairing\n     */\n    public boolean connect() throws IOException, InterruptedException, AdbPairingRequiredException {\n        return connect(Long.MAX_VALUE, TimeUnit.MILLISECONDS, false);\n    }\n\n    /**\n     * Connects to the remote device. This routine will block until the connection completes or the timeout elapses.\n     *\n     * @param timeout             the time to wait for the lock\n     * @param unit                the time unit of the timeout argument\n     * @param throwOnUnauthorised Whether to throw an {@link AdbAuthenticationFailedException}\n     *                            if the peer rejects out first authentication attempt\n     * @return {@code true} if the connection was established, or {@code false} if the connection timed out\n     * @throws IOException                      If the socket fails while connecting\n     * @throws InterruptedException             If timeout has reached\n     * @throws AdbAuthenticationFailedException If {@code throwOnUnauthorised} is {@code true} and the peer rejects the\n     *                                          first authentication attempt, which indicates that the peer has not\n     *                                          saved the public key from a previous connection\n     * @throws AdbPairingRequiredException      If ADB lacks pairing\n     */\n    public boolean connect(long timeout, @NonNull TimeUnit unit, boolean throwOnUnauthorised)\n            throws IOException, InterruptedException, AdbAuthenticationFailedException, AdbPairingRequiredException {\n        if (mConnectionEstablished) {\n            throw new IllegalStateException(\"Already connected\");\n        }\n\n        // Send CONNECT\n        sendPacket(AdbProtocol.generateConnect(mApi));\n\n        // Start the connection thread to respond to the peer\n        mConnectAttempted = true;\n        mAbortOnUnauthorised = throwOnUnauthorised;\n        mAuthorisationFailed = false;\n        mConnectionThread.start();\n\n        return waitForConnection(timeout, Objects.requireNonNull(unit));\n    }\n\n    /**\n     * Opens an {@link AdbStream} object corresponding to the specified destination.\n     * This routine will block until the connection completes.\n     *\n     * @param service The service to open. One of the services under {@link LocalServices.Services}.\n     * @param args    Additional arguments supported by the service (see the corresponding constant to learn more).\n     * @return AdbStream object corresponding to the specified destination\n     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8\n     * @throws IOException                  If the stream fails while sending the packet\n     * @throws InterruptedException         If we are unable to wait for the connection to finish\n     * @throws AdbPairingRequiredException  If ADB lacks pairing\n     */\n    @NonNull\n    public AdbStream open(@LocalServices.Services int service, @NonNull String... args)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        if (service < LocalServices.SERVICE_FIRST || service > LocalServices.SERVICE_LAST) {\n            throw new IllegalArgumentException(\"Invalid service: \" + service);\n        }\n        return open(LocalServices.getDestination(service, args));\n    }\n\n    /**\n     * Opens an AdbStream object corresponding to the specified destination.\n     * This routine will block until the connection completes.\n     *\n     * @param destination The destination to open on the target\n     * @return AdbStream object corresponding to the specified destination\n     * @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8\n     * @throws IOException                  If the stream fails while sending the packet\n     * @throws InterruptedException         If we are unable to wait for the connection to finish\n     * @throws AdbPairingRequiredException  If ADB lacks pairing\n     */\n    @NonNull\n    public AdbStream open(@NonNull String destination)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        int localId = ++mLastLocalId;\n\n        if (!mConnectAttempted) {\n            throw new IllegalStateException(\"connect() must be called first\");\n        }\n\n        waitForConnection(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n\n        // Add this stream to this list of half-open streams\n        AdbStream stream = new AdbStream(this, localId);\n        mOpenedStreams.put(localId, stream);\n\n        // Send OPEN\n        sendPacket(AdbProtocol.generateOpen(localId, Objects.requireNonNull(destination)));\n\n        // Wait for the connection thread to receive the OKAY\n        synchronized (stream) {\n            stream.wait();\n        }\n\n        // Check if the OPEN request was rejected\n        if (stream.isClosed()) {\n            mOpenedStreams.remove(localId);\n            throw new ConnectException(\"Stream open actively rejected by remote peer.\");\n        }\n\n        return stream;\n    }\n\n    private boolean waitForConnection(long timeout, @NonNull TimeUnit unit)\n            throws InterruptedException, IOException, AdbPairingRequiredException {\n        synchronized (this) {\n            // Block if a connection is pending, but not yet complete\n            long timeoutEndMillis = System.currentTimeMillis() + Objects.requireNonNull(unit).toMillis(timeout);\n            while (!mConnectionEstablished && mConnectAttempted && timeoutEndMillis - System.currentTimeMillis() > 0) {\n                wait(timeoutEndMillis - System.currentTimeMillis());\n            }\n\n            if (!mConnectionEstablished) {\n                if (mConnectAttempted) {\n                    return false;\n                } else if (mAuthorisationFailed) {\n                    // The peer may not have saved the public key in the past connections, or they've been removed.\n                    throw new AdbAuthenticationFailedException();\n                } else {\n                    Exception connectionException = mConnectionException;\n                    if (connectionException != null) {\n                        if (connectionException instanceof javax.net.ssl.SSLProtocolException) {\n                            String message = connectionException.getMessage();\n                            if (message != null && message.contains(\"protocol error\")) {\n                                throw (AdbPairingRequiredException) (new AdbPairingRequiredException(\"ADB pairing is required.\").initCause(connectionException));\n                            }\n                        }\n                    }\n                    throw new IOException(\"Connection failed\");\n                }\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * This function terminates all I/O on streams associated with this ADB connection\n     */\n    private void cleanupStreams() {\n        // Close all streams on this connection\n        for (AdbStream s : mOpenedStreams.values()) {\n            try {\n                s.close();\n            } catch (IOException ignored) {\n            }\n        }\n        mOpenedStreams.clear();\n    }\n\n    /**\n     * This routine closes the Adb connection and underlying socket\n     *\n     * @throws IOException if the socket fails to close\n     */\n    @Override\n    public void close() throws IOException {\n        // Closing the socket will kick the connection thread\n        mSocket.close();\n\n        // Wait for the connection thread to die\n        mConnectionThread.interrupt();\n        try {\n            mConnectionThread.join();\n        } catch (InterruptedException ignored) {\n        }\n\n        // Destroy keypair\n        try {\n            mKeyPair.destroy();\n        } catch (DestroyFailedException ignore) {\n        }\n    }\n\n    void sendPacket(byte[] packet) throws IOException {\n        synchronized (mLock) {\n            OutputStream os = getOutputStream();\n            os.write(packet);\n            os.flush();\n        }\n    }\n\n    void flushPacket() throws IOException {\n        synchronized (mLock) {\n            getOutputStream().flush();\n        }\n    }\n\n    public static class Builder {\n        private String mHost = \"127.0.0.1\";\n        private int mPort = 5555;\n        private int mApi = Build.VERSION_CODES.BASE;\n        private PrivateKey mPrivateKey;\n        private Certificate mCertificate;\n        private KeyPair mKeyPair;\n        private String mDeviceName;\n\n        public Builder() {\n        }\n\n        public Builder(String host, int port) {\n            mHost = host;\n            mPort = port;\n        }\n\n        /**\n         * Set host address. Default is 127.0.0.1\n         */\n        public Builder setHost(String host) {\n            this.mHost = host;\n            return this;\n        }\n\n        /**\n         * Set port number. Default is 5555.\n         */\n        public Builder setPort(int port) {\n            this.mPort = port;\n            return this;\n        }\n\n        /**\n         * Set a name for the device. Default is “Unknown Device”.\n         *\n         * @param deviceName Name of the device, could be the app label, hostname or user@hostname.\n         */\n        public Builder setDeviceName(String deviceName) {\n            this.mDeviceName = deviceName;\n            return this;\n        }\n\n        /**\n         * Set Android API (i.e. SDK) version for this connection. If the ADB daemon and the client are located in the\n         * same device, the value should be {@link Build.VERSION#SDK_INT} in order to improve performance as well as\n         * security.\n         *\n         * @param api The API version, default is {@link Build.VERSION_CODES#BASE}.\n         */\n        public Builder setApi(int api) {\n            this.mApi = api;\n            return this;\n        }\n\n        /**\n         * Set generated/stored private key.\n         */\n        public Builder setPrivateKey(PrivateKey privateKey) {\n            this.mPrivateKey = privateKey;\n            return this;\n        }\n\n        /**\n         * Set public key wrapped around a certificate\n         */\n        public Builder setCertificate(Certificate certificate) {\n            this.mCertificate = certificate;\n            return this;\n        }\n\n        Builder setKeyPair(KeyPair keyPair) {\n            this.mKeyPair = keyPair;\n            return this;\n        }\n\n        /**\n         * Creates a new {@link AdbConnection} associated with the socket and crypto object specified.\n         *\n         * @throws IOException If there was an error while establishing a socket connection\n         */\n        public AdbConnection build() throws IOException {\n            if (mKeyPair == null) {\n                if (mPrivateKey == null || mCertificate == null) {\n                    throw new UnsupportedOperationException(\"Private key and certificate must be set.\");\n                }\n                mKeyPair = new KeyPair(mPrivateKey, mCertificate);\n            }\n            AdbConnection adbConnection = create(mHost, mPort, mKeyPair, mApi);\n            if (mDeviceName != null) {\n                adbConnection.setDeviceName(mDeviceName);\n            }\n            return adbConnection;\n        }\n\n        /**\n         * Same as {@link #connect(long, TimeUnit, boolean)} without throwing anything if the first authentication\n         * attempt fails.\n         *\n         * @return The underlying {@link AdbConnection}\n         * @throws IOException                 If the socket fails while connecting\n         * @throws InterruptedException        If timeout has reached\n         * @throws AdbPairingRequiredException If ADB lacks pairing\n         */\n        public AdbConnection connect() throws IOException, InterruptedException, AdbPairingRequiredException {\n            AdbConnection adbConnection = build();\n            if (adbConnection.connect()) {\n                throw new IOException(\"Unable to establish a new connection.\");\n            }\n            return adbConnection;\n        }\n\n        /**\n         * Connects to the remote device. This routine will block until the connection completes or the timeout elapses.\n         *\n         * @param timeout             the time to wait for the lock\n         * @param unit                the time unit of the timeout argument\n         * @param throwOnUnauthorised Whether to throw an {@link AdbAuthenticationFailedException}\n         *                            if the peer rejects out first authentication attempt\n         * @return {@code true} if the connection was established, or {@code false} if the connection timed out\n         * @throws IOException                      If the socket fails while connecting\n         * @throws InterruptedException             If timeout has reached\n         * @throws AdbAuthenticationFailedException If {@code throwOnUnauthorised} is {@code true} and the peer rejects\n         *                                          the first authentication attempt, which indicates that the peer has\n         *                                          not saved the public key from a previous connection\n         * @throws AdbPairingRequiredException      If ADB lacks pairing\n         */\n        public AdbConnection connect(long timeout, @NonNull TimeUnit unit, boolean throwOnUnauthorised)\n                throws IOException, InterruptedException, AdbPairingRequiredException {\n            AdbConnection adbConnection = build();\n            if (adbConnection.connect(timeout, unit, throwOnUnauthorised)) {\n                throw new IOException(\"Unable to establish a new connection.\");\n            }\n            return adbConnection;\n        }\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbInputStream.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\npublic class AdbInputStream extends InputStream {\n    public AdbStream mAdbStream;\n\n    public AdbInputStream(AdbStream adbStream) {\n        this.mAdbStream = adbStream;\n    }\n\n    @Override\n    public int read() throws IOException {\n        byte[] bytes = new byte[1];\n        if (read(bytes) == -1) {\n            return -1;\n        }\n        return bytes[0];\n    }\n\n    @Override\n    public int read(byte[] b) throws IOException {\n        return read(b, 0, b.length);\n    }\n\n    @Override\n    public int read(byte[] b, int off, int len) throws IOException {\n        if (mAdbStream.isClosed()) return -1;\n        return mAdbStream.read(b, off, len);\n    }\n\n    @Override\n    public void close() {\n    }\n\n    @Override\n    public int available() throws IOException {\n        return mAdbStream.available();\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbOutputStream.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.io.IOException;\nimport java.io.OutputStream;\n\npublic class AdbOutputStream extends OutputStream {\n    private final AdbStream mAdbStream;\n\n    public AdbOutputStream(AdbStream adbStream) {\n        this.mAdbStream = adbStream;\n    }\n\n    @Override\n    public void write(int b) throws IOException {\n        write(new byte[]{(byte) (b & 0xFF)});\n    }\n\n    @Override\n    public void write(byte[] b) throws IOException {\n        write(b, 0, b.length);\n    }\n\n    @Override\n    public void write(byte[] b, int off, int len) throws IOException {\n        mAdbStream.write(b, off, len);\n    }\n\n    @Override\n    public void flush() throws IOException {\n        mAdbStream.flush();\n    }\n\n    @Override\n    public void close() throws IOException {\n        flush();\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbPairingRequiredException.java",
    "content": "package io.github.muntashirakon.adb;\n\npublic class AdbPairingRequiredException extends Exception {\n    public AdbPairingRequiredException(String message) {\n        super(message);\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbProtocol.java",
    "content": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimport android.os.Build;\n\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.StreamCorruptedException;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.util.Arrays;\n\n/**\n * This class provides useful functions and fields for ADB protocol details.\n */\n// Copyright 2013 Cameron Gutman\nfinal class AdbProtocol {\n    /**\n     * The length of the ADB message header\n     */\n    public static final int ADB_HEADER_LENGTH = 24;\n\n    /**\n     * SYNC(online, sequence, \"\")\n     *\n     * @deprecated Obsolete, no longer used. Never used on the client side.\n     */\n    public static final int A_SYNC = 0x434e5953;\n\n    /**\n     * CNXN is the connect message. No messages (except AUTH) are valid before this message is received.\n     */\n    public static final int A_CNXN = 0x4e584e43;\n\n    /**\n     * The payload sent with the CONNECT message.\n     */\n    public static final byte[] SYSTEM_IDENTITY_STRING_HOST = StringCompat.getBytes(\"host::\\0\", \"UTF-8\");\n\n    /**\n     * AUTH is the authentication message. It is part of the RSA public key authentication added in Android 4.2.2\n     * ({@link Build.VERSION_CODES#JELLY_BEAN_MR1}).\n     */\n    public static final int A_AUTH = 0x48545541;\n\n    /**\n     * OPEN is the open stream message. It is sent to open a new stream on the target device.\n     */\n    public static final int A_OPEN = 0x4e45504f;\n\n    /**\n     * OKAY is a success message. It is sent when a write is processed successfully.\n     */\n    public static final int A_OKAY = 0x59414b4f;\n\n    /**\n     * CLSE is the close stream message. It is sent to close an existing stream on the target device.\n     */\n    public static final int A_CLSE = 0x45534c43;\n\n    /**\n     * WRTE is the write stream message. It is sent with a payload that is the data to write to the stream.\n     */\n    public static final int A_WRTE = 0x45545257;\n\n    /**\n     * STLS is the Stream-based TLS1.3 authentication method, added in Android 9 ({@link Build.VERSION_CODES#P}).\n     */\n    public static final int A_STLS = 0x534c5453;\n\n    @Retention(RetentionPolicy.SOURCE)\n    @IntDef({A_SYNC, A_CNXN, A_OPEN, A_OKAY, A_CLSE, A_WRTE, A_AUTH, A_STLS})\n    private @interface Command {\n    }\n\n    /**\n     * Original payload size\n     */\n    public static final int MAX_PAYLOAD_V1 = 4 * 1024;\n    /**\n     * Supported payload size since Android 7 (N)\n     */\n    public static final int MAX_PAYLOAD_V2 = 256 * 1024;\n    /**\n     * Supported payload size since Android 9 (P)\n     */\n    public static final int MAX_PAYLOAD_V3 = 1024 * 1024;\n    /**\n     * Maximum supported payload size is set to the original to support all APIs\n     */\n    public static final int MAX_PAYLOAD = MAX_PAYLOAD_V1;\n\n    /**\n     * The original version of the ADB protocol\n     */\n    public static final int A_VERSION_MIN = 0x01000000;\n    /**\n     * The new version of the ADB protocol introduced in Android 9 (P) with the introduction of TLS\n     */\n    public static final int A_VERSION_SKIP_CHECKSUM = 0x01000001;\n    public static final int A_VERSION = A_VERSION_MIN;\n\n    /**\n     * The current version of the Stream-based TLS\n     */\n    public static final int A_STLS_VERSION_MIN = 0x01000000;\n    public static final int A_STLS_VERSION = A_STLS_VERSION_MIN;\n\n    /**\n     * This authentication type represents a SHA1 hash to sign.\n     */\n    public static final int ADB_AUTH_TOKEN = 1;\n\n    /**\n     * This authentication type represents the signed SHA1 hash.\n     */\n    public static final int ADB_AUTH_SIGNATURE = 2;\n\n    /**\n     * This authentication type represents an RSA public key.\n     */\n    public static final int ADB_AUTH_RSAPUBLICKEY = 3;\n\n    @Retention(RetentionPolicy.SOURCE)\n    @IntDef({ADB_AUTH_TOKEN, ADB_AUTH_SIGNATURE, ADB_AUTH_RSAPUBLICKEY})\n    private @interface AuthType {\n    }\n\n    public static int getMaxData(int api) {\n        if (api >= Build.VERSION_CODES.P) {\n            return MAX_PAYLOAD_V3;\n        }\n        if (api >= Build.VERSION_CODES.N) {\n            return MAX_PAYLOAD_V2;\n        }\n        return MAX_PAYLOAD_V1;\n    }\n\n    public static int getProtocolVersion(int api) {\n        if (api >= Build.VERSION_CODES.P) {\n            return A_VERSION_SKIP_CHECKSUM;\n        }\n        return A_VERSION_MIN;\n    }\n\n    /**\n     * This function performs a checksum on the ADB payload data.\n     *\n     * @param data The data\n     * @return The checksum of the data\n     */\n    private static int getPayloadChecksum(@NonNull byte[] data) {\n        return getPayloadChecksum(data, 0, data.length);\n    }\n\n    /**\n     * This function performs a checksum on the ADB payload data.\n     *\n     * @param data   The data\n     * @param offset The start offset in the data\n     * @param length The number of bytes to take from the data\n     * @return The checksum of the data\n     */\n    private static int getPayloadChecksum(@NonNull byte[] data, int offset, int length) {\n        int checksum = 0;\n        for (int i = offset; i < offset + length; ++i) {\n            checksum += data[i] & 0xFF;\n        }\n        return checksum;\n    }\n\n    /**\n     * This function generates an ADB message given the fields.\n     *\n     * @param command Command identifier constant\n     * @param arg0    First argument\n     * @param arg1    Second argument\n     * @param data    The data\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateMessage(@Command int command, int arg0, int arg1, @Nullable byte[] data) {\n        return generateMessage(command, arg0, arg1, data, 0, data == null ? 0 : data.length);\n    }\n\n    /**\n     * This function generates an ADB message given the fields.\n     *\n     * @param command Command identifier constant\n     * @param arg0    First argument\n     * @param arg1    Second argument\n     * @param data    The data\n     * @param offset  The start offset in the data\n     * @param length  The number of bytes to take from the data\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateMessage(@Command int command, int arg0, int arg1, @Nullable byte[] data, int offset, int length) {\n        // Protocol as defined at https://github.com/aosp-mirror/platform_system_core/blob/6072de17cd812daf238092695f26a552d3122f8c/adb/protocol.txt\n        // struct message {\n        //     unsigned command;       // command identifier constant\n        //     unsigned arg0;          // first argument\n        //     unsigned arg1;          // second argument\n        //     unsigned data_length;   // length of payload (0 is allowed)\n        //     unsigned data_check;    // checksum of data payload\n        //     unsigned magic;         // command ^ 0xffffffff\n        // };\n\n        ByteBuffer message;\n\n        if (data != null) {\n            message = ByteBuffer.allocate(ADB_HEADER_LENGTH + length).order(ByteOrder.LITTLE_ENDIAN);\n        } else {\n            message = ByteBuffer.allocate(ADB_HEADER_LENGTH).order(ByteOrder.LITTLE_ENDIAN);\n        }\n\n        message.putInt(command);\n        message.putInt(arg0);\n        message.putInt(arg1);\n\n        if (data != null) {\n            message.putInt(length);\n            message.putInt(getPayloadChecksum(data, offset, length));\n        } else {\n            message.putInt(0);\n            message.putInt(0);\n        }\n\n        message.putInt(~command);\n\n        if (data != null) {\n            message.put(data, offset, length);\n        }\n\n        return message.array();\n    }\n\n    /**\n     * Generates a CONNECT message for a given API.\n     * <p>\n     * CONNECT(version, maxdata, \"system-identity-string\")\n     *\n     * @param api API version\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateConnect(int api) {\n        return generateMessage(A_CNXN, getProtocolVersion(api), getMaxData(api), SYSTEM_IDENTITY_STRING_HOST);\n    }\n\n    /**\n     * Generates an AUTH message with the specified type and payload.\n     * <p>\n     * AUTH(type, 0, \"data\")\n     *\n     * @param type Authentication type (see ADB_AUTH_* constants)\n     * @param data The data\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateAuth(@AuthType int type, byte[] data) {\n        return generateMessage(A_AUTH, type, 0, data);\n    }\n\n    /**\n     * Generates an STLS message with default parameters.\n     * <p>\n     * STLS(version, 0, \"\")\n     *\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateStls() {\n        return generateMessage(A_STLS, A_STLS_VERSION, 0, null);\n    }\n\n    /**\n     * Generates an OPEN stream message with the specified local ID and destination.\n     * <p>\n     * OPEN(local-id, 0, \"destination\")\n     *\n     * @param localId     A unique local ID identifying the stream\n     * @param destination The destination of the stream on the target\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateOpen(int localId, @NonNull String destination) {\n        ByteBuffer bbuf = ByteBuffer.allocate(destination.length() + 1);\n        bbuf.put(StringCompat.getBytes(destination, \"UTF-8\"));\n        bbuf.put((byte) 0);\n        return generateMessage(A_OPEN, localId, 0, bbuf.array());\n    }\n\n    /**\n     * Generates a WRITE stream message with the specified IDs and payload.\n     * <p>\n     * WRITE(local-id, remote-id, \"data\")\n     *\n     * @param localId  The unique local ID of the stream\n     * @param remoteId The unique remote ID of the stream\n     * @param data     The data\n     * @param offset   The start offset in the data\n     * @param length   The number of bytes to take from the data\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateWrite(int localId, int remoteId, byte[] data, int offset, int length) {\n        return generateMessage(A_WRTE, localId, remoteId, data, offset, length);\n    }\n\n    /**\n     * Generates a CLOSE stream message with the specified IDs.\n     * <p>\n     * CLOSE(local-id, remote-id, \"\")\n     *\n     * @param localId  The unique local ID of the stream\n     * @param remoteId The unique remote ID of the stream\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateClose(int localId, int remoteId) {\n        return generateMessage(A_CLSE, localId, remoteId, null);\n    }\n\n    /**\n     * Generates an OKAY/READY message with the specified IDs.\n     * <p>\n     * READY(local-id, remote-id, \"\")\n     *\n     * @param localId  The unique local ID of the stream\n     * @param remoteId The unique remote ID of the stream\n     * @return Byte array containing the message\n     */\n    @NonNull\n    public static byte[] generateReady(int localId, int remoteId) {\n        return generateMessage(A_OKAY, localId, remoteId, null);\n    }\n\n    /**\n     * This class provides an abstraction for the ADB message format.\n     */\n    static final class Message {\n        /**\n         * The command field of the message\n         */\n        @Command\n        public final int command;\n        /**\n         * The arg0 field of the message\n         */\n        public final int arg0;\n        /**\n         * The arg1 field of the message\n         */\n        public final int arg1;\n        /**\n         * The payload length field of the message\n         */\n        public final int dataLength;\n        /**\n         * The checksum field of the message\n         */\n        public final int dataCheck;\n        /**\n         * The magic field of the message\n         */\n        public final int magic;\n        /**\n         * The payload of the message\n         */\n        public byte[] payload;\n\n        /**\n         * Read and parse an ADB message from the supplied input stream.\n         * <p>\n         * <b>Note:</b> If data is corrupted, the connection has to be closed immediately to avoid inconsistencies.\n         *\n         * @param in InputStream object to read data from\n         * @return An AdbMessage object represented the message read\n         * @throws IOException              If the stream fails while reading.\n         * @throws StreamCorruptedException If data is corrupted.\n         */\n        @NonNull\n        public static Message parse(@NonNull InputStream in, int protocolVersion, int maxData) throws IOException {\n            ByteBuffer header = ByteBuffer.allocate(ADB_HEADER_LENGTH).order(ByteOrder.LITTLE_ENDIAN);\n\n            // Read header\n            int dataRead = 0;\n            do {\n                int bytesRead = in.read(header.array(), dataRead, ADB_HEADER_LENGTH - dataRead);\n                if (bytesRead < 0) {\n                    throw new IOException(\"Stream closed\");\n                } else dataRead += bytesRead;\n            } while (dataRead < ADB_HEADER_LENGTH);\n\n            Message msg = new Message(header);\n\n            // Validate header\n            if (msg.command != (~msg.magic)) { // magic = cmd ^ 0xFFFFFFFF\n                throw new StreamCorruptedException(String.format(\"Invalid header: Invalid magic 0x%x.\", msg.magic));\n            }\n            if (msg.command != A_SYNC && msg.command != A_CNXN && msg.command != A_OPEN && msg.command != A_OKAY\n                    && msg.command != A_CLSE && msg.command != A_WRTE && msg.command != A_AUTH\n                    && msg.command != A_STLS) {\n                throw new StreamCorruptedException(String.format(\"Invalid header: Invalid command 0x%x.\", msg.command));\n            }\n            if (msg.dataLength < 0 || msg.dataLength > maxData) {\n                throw new StreamCorruptedException(String.format(\"Invalid header: Invalid data length %d\", msg.dataLength));\n            }\n\n            if (msg.dataLength == 0) {\n                // No payload supplied, return immediately\n                return msg;\n            }\n\n            // Read payload\n            msg.payload = new byte[msg.dataLength];\n            dataRead = 0;\n            do {\n                int bytesRead = in.read(msg.payload, dataRead, msg.dataLength - dataRead);\n                if (bytesRead < 0) {\n                    throw new IOException(\"Stream closed\");\n                } else dataRead += bytesRead;\n            } while (dataRead < msg.dataLength);\n\n            // Verify payload\n            if ((protocolVersion <= A_VERSION_MIN || (msg.command == A_CNXN && msg.arg0 <= A_VERSION_MIN))\n                    && getPayloadChecksum(msg.payload) != msg.dataCheck) {\n                // Checksum verification failed\n                throw new StreamCorruptedException(\"Invalid header: Checksum mismatched.\");\n            }\n\n            return msg;\n        }\n\n        private Message(@NonNull ByteBuffer header) {\n            command = header.getInt();\n            arg0 = header.getInt();\n            arg1 = header.getInt();\n            dataLength = header.getInt();\n            dataCheck = header.getInt();\n            magic = header.getInt();\n        }\n\n        @NonNull\n        @Override\n        public String toString() {\n            String tag;\n            switch (command) {\n                case A_SYNC:\n                    tag = \"SYNC\";\n                    break;\n                case A_CNXN:\n                    tag = \"CNXN\";\n                    break;\n                case A_OPEN:\n                    tag = \"OPEN\";\n                    break;\n                case A_OKAY:\n                    tag = \"OKAY\";\n                    break;\n                case A_CLSE:\n                    tag = \"CLSE\";\n                    break;\n                case A_WRTE:\n                    tag = \"WRTE\";\n                    break;\n                case A_AUTH:\n                    tag = \"AUTH\";\n                    break;\n                case A_STLS:\n                    tag = \"STLS\";\n                    break;\n                default:\n                    tag = \"????\";\n                    break;\n            }\n            return \"Message{\" +\n                    \"command=\" + tag +\n                    \", arg0=0x\" + Integer.toHexString(arg0) +\n                    \", arg1=0x\" + Integer.toHexString(arg1) +\n                    \", payloadLength=\" + dataLength +\n                    \", checksum=\" + dataCheck +\n                    \", magic=0x\" + Integer.toHexString(magic) +\n                    \", payload=\" + Arrays.toString(payload) +\n                    '}';\n        }\n    }\n\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AdbStream.java",
    "content": "// SPDX-License-Identifier: BSD-3-Clause AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.Queue;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n/**\n * This class abstracts the underlying ADB streams\n */\n// Copyright 2013 Cameron Gutman\npublic class AdbStream implements Closeable {\n\n    /**\n     * The AdbConnection object that the stream communicates over\n     */\n    private final AdbConnection mAdbConnection;\n\n    /**\n     * The local ID of the stream\n     */\n    private final int mLocalId;\n\n    /**\n     * The remote ID of the stream\n     */\n    private volatile int mRemoteId;\n\n    /**\n     * Indicates whether WRTE is currently allowed\n     */\n    private final AtomicBoolean mWriteReady;\n\n    /**\n     * A queue of data from the target's WRTE packets\n     */\n    private final Queue<byte[]> mReadQueue;\n\n    /**\n     * Store data received from the first WRTE packet in order to support buffering.\n     */\n    private final ByteBuffer mReadBuffer;\n\n    /**\n     * Indicates whether the connection is closed already\n     */\n    private volatile boolean mIsClosed;\n\n    /**\n     * Whether the remote peer has closed but we still have unread data in the queue\n     */\n    private volatile boolean mPendingClose;\n\n    /**\n     * Creates a new AdbStream object on the specified AdbConnection\n     * with the given local ID.\n     *\n     * @param adbConnection AdbConnection that this stream is running on\n     * @param localId       Local ID of the stream\n     */\n    AdbStream(AdbConnection adbConnection, int localId)\n            throws IOException, InterruptedException, AdbPairingRequiredException {\n        this.mAdbConnection = adbConnection;\n        this.mLocalId = localId;\n        this.mReadQueue = new ConcurrentLinkedQueue<>();\n        this.mReadBuffer = (ByteBuffer) ByteBuffer.allocate(adbConnection.getMaxData()).flip();\n        this.mWriteReady = new AtomicBoolean(false);\n        this.mIsClosed = false;\n    }\n\n    public AdbInputStream openInputStream() {\n        return new AdbInputStream(this);\n    }\n\n    public AdbOutputStream openOutputStream() {\n        return new AdbOutputStream(this);\n    }\n\n    /**\n     * Called by the connection thread to indicate newly received data.\n     *\n     * @param payload Data inside the WRTE message\n     */\n    void addPayload(byte[] payload) {\n        synchronized (mReadQueue) {\n            mReadQueue.add(payload);\n            mReadQueue.notifyAll();\n        }\n    }\n\n    /**\n     * Called by the connection thread to send an OKAY packet, allowing the\n     * other side to continue transmission.\n     *\n     * @throws IOException If the connection fails while sending the packet\n     */\n    void sendReady() throws IOException {\n        // Generate and send a OKAY packet\n        mAdbConnection.sendPacket(AdbProtocol.generateReady(mLocalId, mRemoteId));\n    }\n\n    /**\n     * Called by the connection thread to update the remote ID for this stream\n     *\n     * @param remoteId New remote ID\n     */\n    void updateRemoteId(int remoteId) {\n        this.mRemoteId = remoteId;\n    }\n\n    /**\n     * Called by the connection thread to indicate the stream is okay to send data.\n     */\n    void readyForWrite() {\n        mWriteReady.set(true);\n    }\n\n    /**\n     * Called by the connection thread to notify that the stream was closed by the peer.\n     */\n    void notifyClose(boolean closedByPeer) {\n        // We don't call close() because it sends another CLSE\n        if (closedByPeer && !mReadQueue.isEmpty()) {\n            // The remote peer closed the stream, but we haven't finished reading the remaining data\n            mPendingClose = true;\n        } else {\n            mIsClosed = true;\n        }\n\n        // Notify readers and writers\n        synchronized (this) {\n            notifyAll();\n        }\n        synchronized (mReadQueue) {\n            mReadQueue.notifyAll();\n        }\n    }\n\n    /**\n     * Read bytes from the ADB daemon.\n     *\n     * @return the next byte of data, or {@code -1} if the end of the stream is reached.\n     * @throws IOException If the stream fails while waiting\n     */\n    public int read(byte[] bytes, int offset, int length) throws IOException {\n        if (mReadBuffer.hasRemaining()) {\n            return readBuffer(bytes, offset, length);\n        }\n        // Buffer has no data, grab from the queue\n        synchronized (mReadQueue) {\n            byte[] data;\n            // Wait for the connection to close or data to be received\n            while ((data = mReadQueue.poll()) == null && !mIsClosed) {\n                try {\n                    mReadQueue.wait();\n                } catch (InterruptedException e) {\n                    //noinspection UnnecessaryInitCause\n                    throw (IOException) new IOException().initCause(e);\n                }\n            }\n            // Add data to the buffer\n            if (data != null) {\n                mReadBuffer.clear();\n                mReadBuffer.put(data);\n                mReadBuffer.flip();\n                if (mReadBuffer.hasRemaining()) {\n                    return readBuffer(bytes, offset, length);\n                }\n            }\n\n            if (mIsClosed) {\n                throw new IOException(\"Stream closed.\");\n            }\n\n            if (mPendingClose && mReadQueue.isEmpty()) {\n                // The peer closed the stream, and we've finished reading the stream data, so this stream is finished\n                mIsClosed = true;\n            }\n        }\n\n        return -1;\n    }\n\n    private int readBuffer(byte[] bytes, int offset, int length) {\n        int count = 0;\n        for (int i = offset; i < offset + length; ++i) {\n            if (mReadBuffer.hasRemaining()) {\n                bytes[i] = mReadBuffer.get();\n                ++count;\n            }\n        }\n        return count;\n    }\n\n    /**\n     * Sends a WRTE packet with a given byte array payload. It does not flush the stream.\n     *\n     * @param bytes Payload in the form of a byte array\n     * @throws IOException If the stream fails while sending data\n     */\n    public void write(byte[] bytes, int offset, int length) throws IOException {\n        synchronized (this) {\n            // Make sure we're ready for a WRTE\n            while (!mIsClosed && !mWriteReady.compareAndSet(true, false)) {\n                try {\n                    wait();\n                } catch (InterruptedException e) {\n                    //noinspection UnnecessaryInitCause\n                    throw (IOException) new IOException().initCause(e);\n                }\n            }\n\n            if (mIsClosed) {\n                throw new IOException(\"Stream closed\");\n            }\n        }\n        // Split and send data as WRTE packet\n        // TODO: A WRITE message may not be sent until a READY message is received.\n        //  Once a WRITE message is sent, an additional WRITE message may not be\n        //  sent until another READY message has been received.  Recipients of\n        //  a WRITE message that is in violation of this requirement will CLOSE\n        //  the connection.\n        int maxData;\n        try {\n            maxData = mAdbConnection.getMaxData();\n        } catch (InterruptedException | AdbPairingRequiredException e) {\n            //noinspection UnnecessaryInitCause\n            throw (IOException) new IOException().initCause(e);\n        }\n        while (length != 0) {\n            if (length <= maxData) {\n                mAdbConnection.sendPacket(AdbProtocol.generateWrite(mLocalId, mRemoteId, bytes, offset, length));\n                offset = offset + length;\n                length = 0;\n            } else { // if (length > maxData) {\n                mAdbConnection.sendPacket(AdbProtocol.generateWrite(mLocalId, mRemoteId, bytes, offset, maxData));\n                offset = offset + maxData;\n                length = length - maxData;\n            }\n        }\n    }\n\n    public void flush() throws IOException {\n        if (mIsClosed) {\n            throw new IOException(\"Stream closed\");\n        }\n        mAdbConnection.flushPacket();\n    }\n\n    /**\n     * Closes the stream. This sends a close message to the peer.\n     *\n     * @throws IOException If the stream fails while sending the close message.\n     */\n    @Override\n    public void close() throws IOException {\n        synchronized (this) {\n            // This may already be closed by the remote host\n            if (mIsClosed)\n                return;\n\n            // Notify readers/writers that we've closed\n            notifyClose(false);\n        }\n\n        mAdbConnection.sendPacket(AdbProtocol.generateClose(mLocalId, mRemoteId));\n    }\n\n    /**\n     * Returns whether the stream is closed or not\n     *\n     * @return True if the stream is close, false if not\n     */\n    public boolean isClosed() {\n        return mIsClosed;\n    }\n\n    /**\n     * Returns an estimate of available data.\n     *\n     * @return an estimate of the number of bytes that can be read from this stream without blocking.\n     * @throws IOException if the stream is close.\n     */\n    public int available() throws IOException {\n        synchronized (this) {\n            if (mIsClosed) {\n                throw new IOException(\"Stream closed.\");\n            }\n            if (mReadBuffer.hasRemaining()) {\n                return mReadBuffer.remaining();\n            }\n            byte[] data = mReadQueue.peek();\n            return data == null ? 0 : data.length;\n        }\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/AndroidPubkey.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.VisibleForTesting;\n\nimport org.bouncycastle.util.encoders.Base64;\n\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.security.GeneralSecurityException;\nimport java.security.InvalidKeyException;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.util.Objects;\n\nimport javax.crypto.Cipher;\n\nfinal class AndroidPubkey {\n    /**\n     * Size of an RSA modulus such as an encrypted block or a signature.\n     */\n    public static final int ANDROID_PUBKEY_MODULUS_SIZE = 2048 / 8;\n\n    /**\n     * Size of an encoded RSA key.\n     */\n    public static final int ANDROID_PUBKEY_ENCODED_SIZE = 3 * 4 + 2 * ANDROID_PUBKEY_MODULUS_SIZE;\n\n    /**\n     * Size of the RSA modulus in words.\n     */\n    public static final int ANDROID_PUBKEY_MODULUS_SIZE_WORDS = ANDROID_PUBKEY_MODULUS_SIZE / 4;\n\n    /**\n     * The RSA signature padding as an int array.\n     */\n    private static final int[] SIGNATURE_PADDING_AS_INT = new int[]{\n            0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,\n            0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00,\n            0x04, 0x14\n    };\n\n    /**\n     * The RSA signature padding as a byte array\n     */\n    private static final byte[] RSA_SHA_PKCS1_SIGNATURE_PADDING;\n\n    static {\n        RSA_SHA_PKCS1_SIGNATURE_PADDING = new byte[SIGNATURE_PADDING_AS_INT.length];\n\n        for (int i = 0; i < RSA_SHA_PKCS1_SIGNATURE_PADDING.length; i++)\n            RSA_SHA_PKCS1_SIGNATURE_PADDING[i] = (byte) SIGNATURE_PADDING_AS_INT[i];\n    }\n\n    /**\n     * Signs the ADB SHA1 payload with the private key of this object.\n     *\n     * @param privateKey Private key to sign with\n     * @param payload    SHA1 payload to sign\n     * @return Signed SHA1 payload\n     * @throws GeneralSecurityException If signing fails\n     */\n    // Taken from adb_auth_sign\n    @NonNull\n    public static byte[] adbAuthSign(@NonNull PrivateKey privateKey, byte[] payload)\n            throws GeneralSecurityException {\n        Cipher c = Cipher.getInstance(\"RSA/ECB/NoPadding\");\n        c.init(Cipher.ENCRYPT_MODE, privateKey);\n        c.update(RSA_SHA_PKCS1_SIGNATURE_PADDING);\n        return c.doFinal(payload);\n    }\n\n    /**\n     * Converts a standard RSAPublicKey object to the special ADB format. Available since 4.2.2.\n     *\n     * @param publicKey RSAPublicKey object to convert\n     * @param name      Name without null terminator\n     * @return Byte array containing the converted RSAPublicKey object\n     */\n    @NonNull\n    public static byte[] encodeWithName(@NonNull RSAPublicKey publicKey, @NonNull String name)\n            throws InvalidKeyException {\n        int pkeySize = 4 * (int) Math.ceil(ANDROID_PUBKEY_ENCODED_SIZE / 3.0);\n        try (ByteArrayNoThrowOutputStream bos = new ByteArrayNoThrowOutputStream(pkeySize + name.length() + 2)) {\n            bos.write(Base64.encode(encode(publicKey)));\n            bos.write(getUserInfo(name));\n            return bos.toByteArray();\n        }\n    }\n\n    // Taken from get_user_info except that a custom name is used instead of host@user\n    @VisibleForTesting\n    @NonNull\n    static byte[] getUserInfo(@NonNull String name) {\n        return StringCompat.getBytes(String.format(\" %s\\u0000\", name), \"UTF-8\");\n    }\n\n    // https://android.googlesource.com/platform/system/core/+/e797a5c75afc17024d0f0f488c130128fcd704e2/libcrypto_utils/android_pubkey.cpp\n    // typedef struct RSAPublicKey {\n    //     uint32_t modulus_size_words;                     // Modulus length. This must be ANDROID_PUBKEY_MODULUS_SIZE.\n    //     uint32_t n0inv;                                  // Precomputed montgomery parameter: -1 / n[0] mod 2^32\n    //     uint8_t modulus[ANDROID_PUBKEY_MODULUS_SIZE];    // RSA modulus as a little-endian array.\n    //     uint8_t rr[ANDROID_PUBKEY_MODULUS_SIZE];         // Montgomery parameter R^2 as a little-endian array.\n    //     uint32_t exponent;                               // RSA modulus: 3 or 65537\n    // } RSAPublicKey;\n\n    /**\n     * Allocates a new {@link RSAPublicKey} object, decodes a public RSA key stored in Android's custom binary format,\n     * and sets the key parameters. The resulting key can be used with the standard Java cryptography API to perform\n     * public operations.\n     *\n     * @param androidPubkey Public RSA key in Android's custom binary format. The size of the key must be at least\n     *                      {@link #ANDROID_PUBKEY_ENCODED_SIZE}\n     * @return {@link RSAPublicKey} object\n     */\n    @NonNull\n    public static RSAPublicKey decode(@NonNull byte[] androidPubkey)\n            throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {\n        BigInteger n;\n        BigInteger e;\n\n        // Check size is large enough and the modulus size is correct.\n        if (androidPubkey.length < ANDROID_PUBKEY_ENCODED_SIZE) {\n            throw new InvalidKeyException(\"Invalid key length\");\n        }\n        ByteBuffer keyStruct = ByteBuffer.wrap(androidPubkey).order(ByteOrder.LITTLE_ENDIAN);\n        int modulusSize = keyStruct.getInt();\n        if (modulusSize != ANDROID_PUBKEY_MODULUS_SIZE_WORDS) {\n            throw new InvalidKeyException(\"Invalid modulus length.\");\n        }\n\n        // Convert the modulus to big-endian byte order as expected by BN_bin2bn.\n        byte[] modulus = new byte[ANDROID_PUBKEY_MODULUS_SIZE];\n        keyStruct.position(8);\n        keyStruct.get(modulus);\n        n = new BigInteger(1, swapEndianness(modulus));\n\n        // Read the exponent.\n        keyStruct.position(520);\n        e = BigInteger.valueOf(keyStruct.getInt());\n\n        KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(n, e);\n        return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);\n    }\n\n    /**\n     * Encodes the given key in the Android RSA public key binary format.\n     *\n     * @return Public RSA key in Android's custom binary format. The size of the key should be at least\n     * {@link #ANDROID_PUBKEY_ENCODED_SIZE}\n     */\n    @NonNull\n    public static byte[] encode(@NonNull RSAPublicKey publicKey) throws InvalidKeyException {\n        BigInteger r32;\n        BigInteger n0inv;\n        BigInteger rr;\n\n        if (publicKey.getModulus().toByteArray().length < ANDROID_PUBKEY_MODULUS_SIZE) {\n            throw new InvalidKeyException(\"Invalid key length \" + publicKey.getModulus().toByteArray().length);\n        }\n\n        ByteBuffer keyStruct = ByteBuffer.allocate(ANDROID_PUBKEY_ENCODED_SIZE).order(ByteOrder.LITTLE_ENDIAN);\n        // Store the modulus size.\n        keyStruct.putInt(ANDROID_PUBKEY_MODULUS_SIZE_WORDS); // modulus_size_words\n\n        // Compute and store n0inv = -1 / N[0] mod 2^32.\n        r32 = BigInteger.ZERO.setBit(32); // r32 = 2^32\n        n0inv = publicKey.getModulus().mod(r32); // n0inv = N[0] mod 2^32\n        n0inv = n0inv.modInverse(r32); // n0inv = 1/n0inv mod 2^32\n        n0inv = r32.subtract(n0inv);  // n0inv = 2^32 - n0inv\n        keyStruct.putInt(n0inv.intValue()); // n0inv\n\n        // Store the modulus.\n        keyStruct.put(Objects.requireNonNull(BigEndianToLittleEndianPadded(ANDROID_PUBKEY_MODULUS_SIZE, publicKey.getModulus())));\n\n        // Compute and store rr = (2^(rsa_size)) ^ 2 mod N.\n        rr = BigInteger.ZERO.setBit(ANDROID_PUBKEY_MODULUS_SIZE * 8); // rr = 2^(rsa_size)\n        rr = rr.modPow(BigInteger.valueOf(2), publicKey.getModulus()); // rr = rr^2 mod N\n        keyStruct.put(Objects.requireNonNull(BigEndianToLittleEndianPadded(ANDROID_PUBKEY_MODULUS_SIZE, rr)));\n\n        // Store the exponent.\n        keyStruct.putInt(publicKey.getPublicExponent().intValue()); // exponent\n\n        return keyStruct.array();\n    }\n\n    @Nullable\n    private static byte[] BigEndianToLittleEndianPadded(int len, @NonNull BigInteger in) {\n        byte[] out = new byte[len];\n        byte[] bytes = swapEndianness(in.toByteArray());  // Convert big endian -> little endian\n        int num_bytes = bytes.length;\n        if (len < num_bytes) {\n            if (!fitsInBytes(bytes, num_bytes, len)) {\n                return null;\n            }\n            num_bytes = len;\n        }\n        System.arraycopy(bytes, 0, out, 0, num_bytes);\n        return out;\n    }\n\n    static boolean fitsInBytes(@NonNull byte[] bytes, int num_bytes, int len) {\n        byte mask = 0;\n        for (int i = len; i < num_bytes; i++) {\n            mask |= bytes[i];\n        }\n        return mask == 0;\n    }\n\n    @NonNull\n    private static byte[] swapEndianness(@NonNull byte[] bytes) {\n        int len = bytes.length;\n        byte[] out = new byte[len];\n        for (int i = 0; i < len; ++i) {\n            out[i] = bytes[len - i - 1];\n        }\n        return out;\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/ByteArrayNoThrowOutputStream.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.io.ByteArrayOutputStream;\n\nclass ByteArrayNoThrowOutputStream extends ByteArrayOutputStream {\n    public ByteArrayNoThrowOutputStream() {\n        super();\n    }\n\n    public ByteArrayNoThrowOutputStream(int size) {\n        super(size);\n    }\n\n    @Override\n    public void write(byte[] b) {\n        write(b, 0, b.length);\n    }\n\n    @Override\n    public void close() {\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/KeyPair.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.cert.Certificate;\n\nimport javax.security.auth.DestroyFailedException;\n\nfinal class KeyPair {\n    private final PrivateKey mPrivateKey;\n    private final Certificate mCertificate;\n\n    public KeyPair(PrivateKey privateKey, Certificate certificate) {\n        mPrivateKey = privateKey;\n        mCertificate = certificate;\n    }\n\n    public PrivateKey getPrivateKey() {\n        return mPrivateKey;\n    }\n\n    public PublicKey getPublicKey() {\n        return mCertificate.getPublicKey();\n    }\n\n    public Certificate getCertificate() {\n        return mCertificate;\n    }\n\n    public void destroy() throws DestroyFailedException {\n        try {\n            mPrivateKey.destroy();\n        } catch (NoSuchMethodError ignore) {\n        }\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/LocalServices.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.text.TextUtils;\n\nimport androidx.annotation.IntDef;\nimport androidx.annotation.NonNull;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.Objects;\n\n\n/**\n * Local services extracted from the <a href=\"https://cs.android.com/android/platform/superproject/+/master:packages/modules/adb/client/commandline.cpp\">ADB client</a>\n * for easy access.\n */\npublic class LocalServices {\n    static final int SERVICE_FIRST = 1;\n\n    public static final int SHELL = 1;\n    /**\n     * Remount the device's filesystem in read-write mode, instead of read-only. This is usually necessary before\n     * performing an {@link #SYNC} request. This request may not succeed on certain builds which do not allow that.\n     * <p>\n     * This essentially executes {@code /system/bin/remount} command. Additional arguments such as {@code -R} can be\n     * passed too.\n     */\n    public static final int REMOUNT = 2;\n    public static final int FILE = 3;\n    public static final int TCP_CONNECT = 4;\n    public static final int LOCAL_UNIX_SOCKET = 5;\n    public static final int LOCAL_UNIX_SOCKET_RESERVED = 6;\n    public static final int LOCAL_UNIX_SOCKET_ABSTRACT = 7;\n    public static final int LOCAL_UNIX_SOCKET_FILE_SYSTEM = 8;\n    /**\n     * Receive snapshots of the framebuffer. It requires sufficient privileges (or the connection is closed immediately)\n     * but works as follows:\n     * <p>\n     * After an {@link AdbStream} is opened, ADB daemon sends a 16-byte binary structure containing the following fields\n     * (little-endian format):\n     * <pre>\n     * uint32_t depth;     // framebuffer depth = 16\n     * uint32_t size;      // framebuffer size in bytes = 2 * width * height\n     * uint32_t width;     // framebuffer width in pixels\n     * uint32_t height;    // framebuffer height in pixels\n     * </pre>\n     * After that, each time a snapshot is wanted, one byte should be sent through the channel, which will trigger the\n     * daemon to send {@code size} bytes of framebuffer data.\n     */\n    public static final int FRAMEBUFFER = 9;\n    /**\n     * Connects to the JDWP thread running in the VM of process PID (specified as an argument).\n     */\n    public static final int CONNECT_JDWP = 10;\n    /**\n     * Receive the list of JDWP PIDs periodically. The format of the returned data is the following (in order):\n     * <ol>\n     * <li> {@code hex4}: The length of all content as a 4-char hexadecimal string i.e. {@code %04zx}.\n     * <li> {@code content}: A series of ASCII lines of the following format:\n     *  <pre>\n     *  &lt;pid&gt; \"\\n\"\n     *  </pre>\n     * </ol>\n     * This service is used by DDMS to know which debuggable processes are running on the device/emulator.\n     * <p>\n     * Note that there is no single-shot service to retrieve the list only once.\n     */\n    public static final int TRACK_JDWP = 11;\n    public static final int SYNC = 12;\n    /**\n     * Reverse socket connections from the device running ADB daemon to this client. This should not be used if both\n     * the ADB daemon and the client are in the same device.\n     * <p>\n     * It takes an additional argument called {@code forward-command}. It can be one of the following:\n     * <ul>\n     * <li> {@code list-forward}: List all forwarded connections from the device\n     *   This returns something that looks like the following:\n     *   <ol>\n     *   <li> {@code hex4}: The length of the payload, as 4 hexadecimal chars i.e. {@code %04zx}.\n     *   <li> {@code payload}: A series of lines of the following format:\n     *     <pre>\n     *     host \" \" &lt;local&gt; \" \" &lt;remote&gt; \"\\n\"\n     *     </pre>\n     *     Where &lt;local&gt;  is the device-specific endpoint (e.g. {@code tcp:9000}), and &lt;remote&gt; is the\n     *     client-specific endpoint.\n     *   </ol>\n     * <li> forward:<local>;<remote>\n     * <li> forward:norebind:<local>;<remote>\n     * <li> killforward-all\n     * <li> killforward:<local>\n     * </ul>\n     */\n    public static final int REVERSE = 13;\n    /**\n     * Backup some or all packages installed in the device. For this to work, {@code allowBackup=true} must be present\n     * in the application section of the AndroidManifest.xml of the app.\n     * <p>\n     * It takes additional arguments which can be one of the following:\n     * <ul>\n     * <li>List of packages (as array)\n     * <li>{@code -all}\n     * <li>{@code -shared}\n     * </ul>\n     * Output is a stream which is in zlib format with 24 bytes at the front (if unencrypted).\n     */\n    public static final int BACKUP = 14;\n    /**\n     * Restore a backup. Input is a stream which is in zlib format with 24 bytes at the front (if unencrypted).\n     */\n    public static final int RESTORE = 15;\n\n    static final int SERVICE_LAST = 15;\n\n    @IntDef({\n            SHELL,\n            REMOUNT,\n            FILE,\n            TCP_CONNECT,\n            LOCAL_UNIX_SOCKET,\n            LOCAL_UNIX_SOCKET_RESERVED,\n            LOCAL_UNIX_SOCKET_ABSTRACT,\n            LOCAL_UNIX_SOCKET_FILE_SYSTEM,\n            FRAMEBUFFER,\n            CONNECT_JDWP,\n            TRACK_JDWP,\n            SYNC,\n            REVERSE,\n            BACKUP,\n            RESTORE,\n    })\n    @Retention(RetentionPolicy.SOURCE)\n    public @interface Services {\n    }\n\n    @NonNull\n    static String getServiceName(@Services int service) {\n        switch (service) {\n            case SHELL:\n                return \"shell:\";\n            case CONNECT_JDWP:\n                return \"jdwp:\";\n            case FILE:\n                return \"dev:\";\n            case FRAMEBUFFER:\n                return \"framebuffer:\";\n            case LOCAL_UNIX_SOCKET:\n                return \"local:\";\n            case LOCAL_UNIX_SOCKET_ABSTRACT:\n                return \"localabstract:\";\n            case LOCAL_UNIX_SOCKET_FILE_SYSTEM:\n                return \"localfilesystem:\";\n            case LOCAL_UNIX_SOCKET_RESERVED:\n                return \"localreserved:\";\n            case REMOUNT:\n                return \"remount:\";\n            case REVERSE:\n                return \"reverse:\";\n            case SYNC:\n                return \"sync:\";\n            case TCP_CONNECT:\n                return \"tcp:\";\n            case TRACK_JDWP:\n                return \"track-jdwp\";\n            case BACKUP:\n                return \"backup:\";\n            case RESTORE:\n                return \"restore:\";\n            default:\n                throw new IllegalArgumentException(\"Invalid service: \" + service);\n        }\n    }\n\n    @NonNull\n    static String getDestination(@Services int service, @NonNull String... args) {\n        String serviceName = getServiceName(service);\n        StringBuilder destination = new StringBuilder(serviceName);\n        switch (service) {\n            case SHELL:\n                for (String arg : args) {\n                    if (arg.contains(\"\\\"\")) {\n                        throw new IllegalArgumentException(\"Arguments for inline shell cannot contain double\" +\n                                \" quotations.\");\n                    }\n                    if (arg.contains(\" \")) {\n                        destination.append(\"\\\"\").append(Objects.requireNonNull(arg)).append(\"\\\"\");\n                    } else destination.append(Objects.requireNonNull(arg));\n                }\n                break;\n            case FILE:\n                if (args.length == 0) {\n                    throw new IllegalArgumentException(\"File name must be specified.\");\n                } else if (args.length != 1) {\n                    throw new IllegalArgumentException(\"Service expects exactly one argument, \" + args.length\n                            + \" supplied.\");\n                }\n                destination.append(Objects.requireNonNull(args[0]));\n                break;\n            case TCP_CONNECT:\n                if (args.length == 0) {\n                    throw new IllegalArgumentException(\"Port number must be specified.\");\n                } else if (args.length == 1) {\n                    destination.append(args[0]);\n                } else if (args.length == 2) {\n                    destination.append(Objects.requireNonNull(args[0]))\n                            .append(':')\n                            .append(Objects.requireNonNull(args[1]));\n                } else {\n                    throw new IllegalArgumentException(\"Invalid number of arguments supplied.\");\n                }\n                break;\n            case LOCAL_UNIX_SOCKET:\n            case LOCAL_UNIX_SOCKET_ABSTRACT:\n            case LOCAL_UNIX_SOCKET_FILE_SYSTEM:\n            case LOCAL_UNIX_SOCKET_RESERVED:\n                if (args.length == 0) {\n                    throw new IllegalArgumentException(\"Path must be specified.\");\n                } else if (args.length != 1) {\n                    throw new IllegalArgumentException(\"Service expects exactly one argument, \" + args.length\n                            + \" supplied.\");\n                }\n                destination.append(Objects.requireNonNull(args[0]));\n                break;\n            case CONNECT_JDWP:\n                if (args.length == 0) {\n                    throw new IllegalArgumentException(\"PID must be specified.\");\n                } else if (args.length != 1) {\n                    throw new IllegalArgumentException(\"Service expects exactly one argument, \" + args.length\n                            + \" supplied.\");\n                }\n                destination.append(Objects.requireNonNull(args[0]));\n                break;\n            case REVERSE:\n                if (args.length == 0) {\n                    throw new IllegalArgumentException(\"Forward command must be specified.\");\n                } else if (args.length != 1) {\n                    throw new IllegalArgumentException(\"Service expects exactly one argument, \" + args.length\n                            + \" supplied.\");\n                }\n                if (args[0] == null) {\n                    throw new IllegalArgumentException(\"Forward command is empty\");\n                }\n                if (\"list-forward\".equals(args[0]) || \"killforward-all\".equals(args[0])) {\n                    destination.append(args[0]);\n                } else if (args[0].startsWith(\"forward:\") || args[0].startsWith(\"killforward:\")) {\n                    destination.append(args[0]);\n                } else {\n                    throw new IllegalArgumentException(\"Invalid forward command.\");\n                }\n                break;\n            case BACKUP:\n                if (args.length == 0) {\n                    throw new IllegalArgumentException(\"At least one package must be specified or use -shared/-all.\");\n                }\n            case REMOUNT:\n                // Additional arguments for the commands\n                destination.append(TextUtils.join(\" \", args));\n                break;\n            case RESTORE:\n            case FRAMEBUFFER:\n            case SYNC:\n            case TRACK_JDWP:\n                if (args.length != 0) {\n                    throw new IllegalArgumentException(\"Service expects no arguments.\");\n                }\n                break;\n        }\n        return destination.toString();\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/PRNGFixes.java",
    "content": "// SPDX-License-Identifier: MIT AND (GPL-3.0-or-later OR Apache-2.0)\n\npackage io.github.muntashirakon.adb;\n\nimport android.os.Build;\nimport android.os.Process;\nimport android.util.Log;\n\nimport androidx.annotation.GuardedBy;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.Provider;\nimport java.security.SecureRandom;\nimport java.security.SecureRandomSpi;\nimport java.security.Security;\n\n/**\n * Fixes for the output of the default PRNG having low entropy.\n * <p>\n * The fixes need to be applied via {@link #apply()} before any use of Java\n * Cryptography Architecture primitives. A good place to invoke them is in the\n * application's {@code onCreate}.\n */\n// Copyright 2013 Google Inc.\npublic final class PRNGFixes {\n    private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = getBuildFingerprintAndDeviceSerial();\n\n    /**\n     * Hidden constructor to prevent instantiation.\n     */\n    private PRNGFixes() {\n    }\n\n    /**\n     * Applies all fixes.\n     *\n     * @throws SecurityException if a fix is needed but could not be applied.\n     */\n    public static void apply() {\n        applyOpenSSLFix();\n        installLinuxPRNGSecureRandom();\n    }\n\n    /**\n     * Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the\n     * fix is not needed.\n     *\n     * @throws SecurityException if the fix is needed but could not be applied.\n     */\n    private static void applyOpenSSLFix() throws SecurityException {\n        if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)\n                || (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2)) {\n            // No need to apply the fix\n            return;\n        }\n\n        try {\n            // Mix in the device- and invocation-specific seed.\n            Class.forName(\"org.apache.harmony.xnet.provider.jsse.NativeCrypto\")\n                    .getMethod(\"RAND_seed\", byte[].class)\n                    .invoke(null, generateSeed());\n\n            // Mix output of Linux PRNG into OpenSSL's PRNG\n            int bytesRead = (Integer) Class.forName(\"org.apache.harmony.xnet.provider.jsse.NativeCrypto\")\n                    .getMethod(\"RAND_load_file\", String.class, long.class)\n                    .invoke(null, \"/dev/urandom\", 1024);\n            if (bytesRead != 1024) {\n                throw new IOException(\"Unexpected number of bytes read from Linux PRNG: \" + bytesRead);\n            }\n        } catch (Exception e) {\n            throw new SecurityException(\"Failed to seed OpenSSL PRNG\", e);\n        }\n    }\n\n    /**\n     * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the\n     * default. Does nothing if the implementation is already the default or if\n     * there is not need to install the implementation.\n     *\n     * @throws SecurityException if the fix is needed but could not be applied.\n     */\n    private static void installLinuxPRNGSecureRandom()\n            throws SecurityException {\n        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {\n            // No need to apply the fix\n            return;\n        }\n\n        // Install a Linux PRNG-based SecureRandom implementation as the\n        // default, if not yet installed.\n        Provider[] secureRandomProviders = Security.getProviders(\"SecureRandom.SHA1PRNG\");\n        if ((secureRandomProviders == null)\n                || (secureRandomProviders.length < 1)\n                || (!LinuxPRNGSecureRandomProvider.class.equals(secureRandomProviders[0].getClass()))) {\n            Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);\n        }\n\n        // Assert that new SecureRandom() and\n        // SecureRandom.getInstance(\"SHA1PRNG\") return a SecureRandom backed\n        // by the Linux PRNG-based SecureRandom implementation.\n        SecureRandom rng1 = new SecureRandom();\n        if (!LinuxPRNGSecureRandomProvider.class.equals(rng1.getProvider().getClass())) {\n            throw new SecurityException(\"new SecureRandom() backed by wrong Provider: \"\n                    + rng1.getProvider().getClass());\n        }\n\n        SecureRandom rng2;\n        try {\n            rng2 = SecureRandom.getInstance(\"SHA1PRNG\");\n        } catch (NoSuchAlgorithmException e) {\n            throw new SecurityException(\"SHA1PRNG not available\", e);\n        }\n        if (!LinuxPRNGSecureRandomProvider.class.equals(\n                rng2.getProvider().getClass())) {\n            throw new SecurityException(\"SecureRandom.getInstance(\\\"SHA1PRNG\\\") backed by wrong provider: \"\n                    + rng2.getProvider().getClass());\n        }\n    }\n\n    /**\n     * {@code Provider} of {@code SecureRandom} engines which pass through\n     * all requests to the Linux PRNG.\n     */\n    private static class LinuxPRNGSecureRandomProvider extends Provider {\n\n        public LinuxPRNGSecureRandomProvider() {\n            super(\"LinuxPRNG\", 1.0, \"A Linux-specific random number provider that uses /dev/urandom\");\n            // Although /dev/urandom is not a SHA-1 PRNG, some apps\n            // explicitly request a SHA1PRNG SecureRandom and we thus need to\n            // prevent them from getting the default implementation whose output\n            // may have low entropy.\n            put(\"SecureRandom.SHA1PRNG\", LinuxPRNGSecureRandom.class.getName());\n            put(\"SecureRandom.SHA1PRNG ImplementedIn\", \"Software\");\n        }\n    }\n\n    /**\n     * {@link SecureRandomSpi} which passes all requests to the Linux PRNG\n     * ({@code /dev/urandom}).\n     */\n    public static class LinuxPRNGSecureRandom extends SecureRandomSpi {\n\n        /*\n         * IMPLEMENTATION NOTE: Requests to generate bytes and to mix in a seed\n         * are passed through to the Linux PRNG (/dev/urandom). Instances of\n         * this class seed themselves by mixing in the current time, PID, UID,\n         * build fingerprint, and hardware serial number (where available) into\n         * Linux PRNG.\n         *\n         * Concurrency: Read requests to the underlying Linux PRNG are\n         * serialized (on sLock) to ensure that multiple threads do not get\n         * duplicated PRNG output.\n         */\n\n        private static final File URANDOM_FILE = new File(\"/dev/urandom\");\n\n        private static final Object sLock = new Object();\n\n        /**\n         * Input stream for reading from Linux PRNG or {@code null} if not yet\n         * opened.\n         */\n        @GuardedBy(\"sLock\")\n        private static DataInputStream sUrandomIn;\n\n        /**\n         * Output stream for writing to Linux PRNG or {@code null} if not yet\n         * opened.\n         */\n        @GuardedBy(\"sLock\")\n        private static OutputStream sUrandomOut;\n\n        /**\n         * Whether this engine instance has been seeded. This is needed because\n         * each instance needs to seed itself if the client does not explicitly\n         * seed it.\n         */\n        private boolean mSeeded;\n\n        @Override\n        protected void engineSetSeed(byte[] bytes) {\n            try {\n                OutputStream out;\n                synchronized (sLock) {\n                    out = getUrandomOutputStream();\n                }\n                out.write(bytes);\n                out.flush();\n            } catch (IOException e) {\n                // On a small fraction of devices /dev/urandom is not writable.\n                // Log and ignore.\n                Log.w(PRNGFixes.class.getSimpleName(),\n                        \"Failed to mix seed into \" + URANDOM_FILE);\n            } finally {\n                mSeeded = true;\n            }\n        }\n\n        @Override\n        protected void engineNextBytes(byte[] bytes) {\n            if (!mSeeded) {\n                // Mix in the device- and invocation-specific seed.\n                engineSetSeed(generateSeed());\n            }\n\n            try {\n                DataInputStream in;\n                synchronized (sLock) {\n                    in = getUrandomInputStream();\n                }\n                synchronized (in) {\n                    in.readFully(bytes);\n                }\n            } catch (IOException e) {\n                throw new SecurityException(\n                        \"Failed to read from \" + URANDOM_FILE, e);\n            }\n        }\n\n        @Override\n        protected byte[] engineGenerateSeed(int size) {\n            byte[] seed = new byte[size];\n            engineNextBytes(seed);\n            return seed;\n        }\n\n        private DataInputStream getUrandomInputStream() {\n            synchronized (sLock) {\n                if (sUrandomIn == null) {\n                    // NOTE: Consider inserting a BufferedInputStream between\n                    // DataInputStream and FileInputStream if you need higher\n                    // PRNG output performance and can live with future PRNG\n                    // output being pulled into this process prematurely.\n                    try {\n                        sUrandomIn = new DataInputStream(\n                                new FileInputStream(URANDOM_FILE));\n                    } catch (IOException e) {\n                        throw new SecurityException(\"Failed to open \"\n                                + URANDOM_FILE + \" for reading\", e);\n                    }\n                }\n                return sUrandomIn;\n            }\n        }\n\n        private OutputStream getUrandomOutputStream() throws IOException {\n            synchronized (sLock) {\n                if (sUrandomOut == null) {\n                    sUrandomOut = new FileOutputStream(URANDOM_FILE);\n                }\n                return sUrandomOut;\n            }\n        }\n    }\n\n    /**\n     * Generates a device- and invocation-specific seed to be mixed into the\n     * Linux PRNG.\n     */\n    private static byte[] generateSeed() {\n        try {\n            ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();\n            DataOutputStream seedBufferOut =\n                    new DataOutputStream(seedBuffer);\n            seedBufferOut.writeLong(System.currentTimeMillis());\n            seedBufferOut.writeLong(System.nanoTime());\n            seedBufferOut.writeInt(Process.myPid());\n            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE_1_1) {\n                seedBufferOut.writeInt(Process.myUid());\n            }\n            seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);\n            seedBufferOut.close();\n            return seedBuffer.toByteArray();\n        } catch (IOException e) {\n            throw new SecurityException(\"Failed to generate seed\", e);\n        }\n    }\n\n    /**\n     * Gets the hardware serial number of this device.\n     *\n     * @return serial number or {@code null} if not available.\n     */\n    private static String getDeviceSerialNumber() {\n        // We're using the Reflection API because Build.SERIAL is only available\n        // since API Level 9 (Gingerbread, Android 2.3).\n        try {\n            return (String) Build.class.getField(\"SERIAL\").get(null);\n        } catch (Exception ignored) {\n            return null;\n        }\n    }\n\n    private static byte[] getBuildFingerprintAndDeviceSerial() {\n        StringBuilder result = new StringBuilder();\n        String fingerprint = Build.FINGERPRINT;\n        if (fingerprint != null) {\n            result.append(fingerprint);\n        }\n        String serial = getDeviceSerialNumber();\n        if (serial != null) {\n            result.append(serial);\n        }\n        try {\n            return result.toString().getBytes(\"UTF-8\");\n        } catch (UnsupportedEncodingException e) {\n            throw new RuntimeException(\"UTF-8 encoding not supported\");\n        }\n    }\n}"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/PairingAuthCtx.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.os.Build;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.VisibleForTesting;\n\nimport org.bouncycastle.crypto.InvalidCipherTextException;\nimport org.bouncycastle.crypto.digests.SHA256Digest;\nimport org.bouncycastle.crypto.engines.AESEngine;\nimport org.bouncycastle.crypto.generators.HKDFBytesGenerator;\nimport org.bouncycastle.crypto.modes.GCMBlockCipher;\nimport org.bouncycastle.crypto.modes.GCMModeCipher;\nimport org.bouncycastle.crypto.params.AEADParameters;\nimport org.bouncycastle.crypto.params.HKDFParameters;\nimport org.bouncycastle.crypto.params.KeyParameter;\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.util.Arrays;\n\nimport javax.security.auth.Destroyable;\n\nimport io.github.muntashirakon.crypto.spake2.Spake2Context;\nimport io.github.muntashirakon.crypto.spake2.Spake2Role;\n\n@RequiresApi(Build.VERSION_CODES.GINGERBREAD)\nclass PairingAuthCtx implements Destroyable {\n    // The following values are taken from the following source and are subjected to change\n    // https://github.com/aosp-mirror/platform_system_core/blob/android-11.0.0_r1/adb/pairing_auth/pairing_auth.cpp\n    private static final byte[] CLIENT_NAME = StringCompat.getBytes(\"adb pair client\\u0000\", \"UTF-8\");\n    private static final byte[] SERVER_NAME = StringCompat.getBytes(\"adb pair server\\u0000\", \"UTF-8\");\n\n    // The following values are taken from the following source and are subjected to change\n    // https://github.com/aosp-mirror/platform_system_core/blob/android-11.0.0_r1/adb/pairing_auth/aes_128_gcm.cpp\n    private static final byte[] INFO = StringCompat.getBytes(\"adb pairing_auth aes-128-gcm key\", \"UTF-8\");\n    private static final int HKDF_KEY_LENGTH = 128 / 8;\n    public static final int GCM_IV_LENGTH = 12; // in bytes\n\n    private final byte[] mMsg;\n    private final Spake2Context mSpake2Ctx;\n    private final byte[] mSecretKey = new byte[HKDF_KEY_LENGTH];\n    private long mDecIv = 0;\n    private long mEncIv = 0;\n    private boolean mIsDestroyed = false;\n\n    @Nullable\n    public static PairingAuthCtx createAlice(byte[] password) {\n        Spake2Context spake25519 = new Spake2Context(Spake2Role.Alice, CLIENT_NAME, SERVER_NAME);\n        try {\n            return new PairingAuthCtx(spake25519, password);\n        } catch (IllegalArgumentException | IllegalStateException e) {\n            return null;\n        }\n    }\n\n    @VisibleForTesting\n    @Nullable\n    public static PairingAuthCtx createBob(byte[] password) {\n        Spake2Context spake25519 = new Spake2Context(Spake2Role.Bob, SERVER_NAME, CLIENT_NAME);\n        try {\n            return new PairingAuthCtx(spake25519, password);\n        } catch (IllegalArgumentException | IllegalStateException e) {\n            return null;\n        }\n    }\n\n    private PairingAuthCtx(Spake2Context spake25519, byte[] password)\n            throws IllegalArgumentException, IllegalStateException {\n        mSpake2Ctx = spake25519;\n        mMsg = mSpake2Ctx.generateMessage(password);\n    }\n\n    public byte[] getMsg() {\n        return mMsg;\n    }\n\n    public boolean initCipher(byte[] theirMsg) throws IllegalArgumentException, IllegalStateException {\n        if (mIsDestroyed) return false;\n        byte[] keyMaterial = mSpake2Ctx.processMessage(theirMsg);\n        if (keyMaterial == null) return false;\n        HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest());\n        hkdf.init(new HKDFParameters(keyMaterial, null, INFO));\n        hkdf.generateBytes(mSecretKey, 0, mSecretKey.length);\n        return true;\n    }\n\n    @Nullable\n    public byte[] encrypt(@NonNull byte[] in) {\n        return encryptDecrypt(true, in, ByteBuffer.allocate(GCM_IV_LENGTH)\n                .order(ByteOrder.LITTLE_ENDIAN).putLong(mEncIv++).array());\n    }\n\n    @Nullable\n    public byte[] decrypt(@NonNull byte[] in) {\n        return encryptDecrypt(false, in, ByteBuffer.allocate(GCM_IV_LENGTH)\n                .order(ByteOrder.LITTLE_ENDIAN).putLong(mDecIv++).array());\n    }\n\n    @Override\n    public boolean isDestroyed() {\n        return mIsDestroyed;\n    }\n\n    @Override\n    public void destroy() {\n        mIsDestroyed = true;\n        Arrays.fill(mSecretKey, (byte) 0);\n        mSpake2Ctx.destroy();\n    }\n\n    @Nullable\n    private byte[] encryptDecrypt(boolean forEncryption, @NonNull byte[] in, @NonNull byte[] iv) {\n        if (mIsDestroyed) return null;\n        AEADParameters spec = new AEADParameters(new KeyParameter(mSecretKey), mSecretKey.length * 8, iv);\n        GCMModeCipher cipher = GCMBlockCipher.newInstance(AESEngine.newInstance());\n        cipher.init(forEncryption, spec);\n        byte[] out = new byte[cipher.getOutputSize(in.length)];\n        int newOffset = cipher.processBytes(in, 0, in.length, out, 0);\n        try {\n            cipher.doFinal(out, newOffset);\n        } catch (InvalidCipherTextException e) {\n            return null;\n        }\n        return out;\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/PairingConnectionCtx.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.annotation.SuppressLint;\nimport android.os.Build;\nimport android.util.Log;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\n\nimport java.io.Closeable;\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.IOException;\nimport java.lang.reflect.Method;\nimport java.net.Socket;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.security.InvalidKeyException;\nimport java.security.KeyManagementException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.cert.Certificate;\nimport java.security.interfaces.RSAPublicKey;\nimport java.util.Arrays;\nimport java.util.Objects;\n\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLException;\nimport javax.net.ssl.SSLServerSocket;\nimport javax.net.ssl.SSLSocket;\n\n// https://github.com/aosp-mirror/platform_system_core/blob/android-11.0.0_r1/adb/pairing_connection/pairing_connection.cpp\n// Also based on Shizuku's implementation\n@RequiresApi(Build.VERSION_CODES.GINGERBREAD)\npublic final class PairingConnectionCtx implements Closeable {\n    public static final String TAG = PairingConnectionCtx.class.getSimpleName();\n\n    public static final String EXPORTED_KEY_LABEL = \"adb-label\\u0000\";\n    public static final int EXPORT_KEY_SIZE = 64;\n\n    private enum State {\n        Ready,\n        ExchangingMsgs,\n        ExchangingPeerInfo,\n        Stopped\n    }\n\n    enum Role {\n        Client,\n        Server,\n    }\n\n    private final String mHost;\n    private final int mPort;\n    private final byte[] mPswd;\n    private final PeerInfo mPeerInfo;\n    private final SSLContext mSslContext;\n    private final Role mRole = Role.Client;\n\n    private DataInputStream mInputStream;\n    private DataOutputStream mOutputStream;\n    private PairingAuthCtx mPairingAuthCtx;\n    private State mState = State.Ready;\n\n    public PairingConnectionCtx(@NonNull String host, int port, @NonNull byte[] pswd, @NonNull KeyPair keyPair,\n                                @NonNull String deviceName)\n            throws NoSuchAlgorithmException, KeyManagementException, InvalidKeyException {\n        this.mHost = Objects.requireNonNull(host);\n        this.mPort = port;\n        this.mPswd = Objects.requireNonNull(pswd);\n        this.mPeerInfo = new PeerInfo(PeerInfo.ADB_RSA_PUB_KEY, AndroidPubkey.encodeWithName((RSAPublicKey)\n                keyPair.getPublicKey(), Objects.requireNonNull(deviceName)));\n        this.mSslContext = SslUtils.getSslContext(keyPair);\n    }\n\n    public PairingConnectionCtx(@NonNull String host, int port, @NonNull byte[] pswd, @NonNull PrivateKey privateKey,\n                                @NonNull Certificate certificate, @NonNull String deviceName)\n            throws NoSuchAlgorithmException, KeyManagementException, InvalidKeyException {\n        this(host, port, pswd, new KeyPair(Objects.requireNonNull(privateKey), Objects.requireNonNull(certificate)),\n                deviceName);\n    }\n\n    public void start() throws IOException {\n        if (mState != State.Ready) {\n            throw new IOException(\"Connection is not ready yet.\");\n        }\n\n        mState = State.ExchangingMsgs;\n\n        // Start worker\n        setupTlsConnection();\n\n        for (; ; ) {\n            switch (mState) {\n                case ExchangingMsgs:\n                    if (!doExchangeMsgs()) {\n                        notifyResult();\n                        throw new IOException(\"Exchanging message wasn't successful.\");\n                    }\n                    mState = State.ExchangingPeerInfo;\n                    break;\n                case ExchangingPeerInfo:\n                    if (!doExchangePeerInfo()) {\n                        notifyResult();\n                        throw new IOException(\"Could not exchange peer info.\");\n                    }\n                    notifyResult();\n                    return;\n                case Ready:\n                case Stopped:\n                    throw new IOException(\"Connection closed with errors.\");\n            }\n        }\n    }\n\n    private void notifyResult() {\n        mState = State.Stopped;\n    }\n\n    private void setupTlsConnection() throws IOException {\n        Socket socket;\n        if (mRole == Role.Server) {\n            SSLServerSocket sslServerSocket = (SSLServerSocket) mSslContext.getServerSocketFactory().createServerSocket(mPort);\n            socket = sslServerSocket.accept();\n            // TODO: Write automated test scripts after removing Conscrypt dependency.\n        } else { // role == Role.Client\n            socket = new Socket(mHost, mPort);\n        }\n        socket.setTcpNoDelay(true);\n\n        // We use custom SSLContext to allow any SSL certificates\n        SSLSocket sslSocket = (SSLSocket) mSslContext.getSocketFactory().createSocket(socket, mHost, mPort, true);\n        sslSocket.startHandshake();\n        Log.d(TAG, \"Handshake succeeded.\");\n\n        mInputStream = new DataInputStream(sslSocket.getInputStream());\n        mOutputStream = new DataOutputStream(sslSocket.getOutputStream());\n\n        // To ensure the connection is not stolen while we do the PAKE, append the exported key material from the\n        // tls connection to the password.\n        byte[] keyMaterial = exportKeyingMaterial(sslSocket, EXPORT_KEY_SIZE);\n        byte[] passwordBytes = new byte[mPswd.length + keyMaterial.length];\n        System.arraycopy(mPswd, 0, passwordBytes, 0, mPswd.length);\n        System.arraycopy(keyMaterial, 0, passwordBytes, mPswd.length, keyMaterial.length);\n\n        PairingAuthCtx pairingAuthCtx = PairingAuthCtx.createAlice(passwordBytes);\n        if (pairingAuthCtx == null) {\n            throw new IOException(\"Unable to create PairingAuthCtx.\");\n        }\n        this.mPairingAuthCtx = pairingAuthCtx;\n    }\n\n    @SuppressLint(\"PrivateApi\") // Conscrypt is a stable private API\n    private byte[] exportKeyingMaterial(SSLSocket sslSocket, int length) throws SSLException {\n        // Conscrypt#exportKeyingMaterial(SSLSocket socket, String label, byte[] context, int length): byte[]\n        //          throws SSLException\n        try {\n            Class<?> conscryptClass;\n            if (SslUtils.isCustomConscrypt()) {\n                conscryptClass = Class.forName(\"org.conscrypt.Conscrypt\");\n            } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {\n                // Although support for conscrypt has been added in Android 5.0 (Lollipop),\n                // TLS1.3 isn't supported until Android 9 (Pie).\n                throw new SSLException(\"TLSv1.3 isn't supported on your platform. Use custom Conscrypt library instead.\");\n            } else {\n                conscryptClass = Class.forName(\"com.android.org.conscrypt.Conscrypt\");\n            }\n            Method exportKeyingMaterial = conscryptClass.getMethod(\"exportKeyingMaterial\", SSLSocket.class,\n                    String.class, byte[].class, int.class);\n            return (byte[]) exportKeyingMaterial.invoke(null, sslSocket, EXPORTED_KEY_LABEL, null, length);\n        } catch (SSLException e) {\n            throw e;\n        } catch (Throwable th) {\n            throw new SSLException(th);\n        }\n    }\n\n    private void writeHeader(@NonNull PairingPacketHeader header, @NonNull byte[] payload) throws IOException {\n        ByteBuffer buffer = ByteBuffer.allocate(PairingPacketHeader.PAIRING_PACKET_HEADER_SIZE)\n                .order(ByteOrder.BIG_ENDIAN);\n        header.writeTo(buffer);\n\n        mOutputStream.write(buffer.array());\n        mOutputStream.write(payload);\n    }\n\n    @Nullable\n    private PairingPacketHeader readHeader() throws IOException {\n        byte[] bytes = new byte[PairingPacketHeader.PAIRING_PACKET_HEADER_SIZE];\n        mInputStream.readFully(bytes);\n        ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);\n        return PairingPacketHeader.readFrom(buffer);\n    }\n\n    @NonNull\n    private PairingPacketHeader createHeader(byte type, int payloadSize) {\n        return new PairingPacketHeader(PairingPacketHeader.CURRENT_KEY_HEADER_VERSION, type, payloadSize);\n    }\n\n    private boolean checkHeaderType(byte expected, byte actual) {\n        if (expected != actual) {\n            Log.e(TAG, \"Unexpected header type (expected=\" + expected + \" actual=\" + actual + \")\");\n            return false;\n        }\n        return true;\n    }\n\n    private boolean doExchangeMsgs() throws IOException {\n        byte[] msg = mPairingAuthCtx.getMsg();\n\n        PairingPacketHeader ourHeader = createHeader(PairingPacketHeader.SPAKE2_MSG, msg.length);\n        // Write our SPAKE2 msg\n        writeHeader(ourHeader, msg);\n\n        // Read the peer's SPAKE2 msg header\n        PairingPacketHeader theirHeader = readHeader();\n        if (theirHeader == null || !checkHeaderType(PairingPacketHeader.SPAKE2_MSG, theirHeader.type)) return false;\n\n        // Read the SPAKE2 msg payload and initialize the cipher for encrypting the PeerInfo and certificate.\n        byte[] theirMsg = new byte[theirHeader.payloadSize];\n        mInputStream.readFully(theirMsg);\n\n        try {\n            return mPairingAuthCtx.initCipher(theirMsg);\n        } catch (Exception e) {\n            Log.e(TAG, \"Unable to initialize pairing cipher\");\n            //noinspection UnnecessaryInitCause\n            throw (IOException) new IOException().initCause(e);\n        }\n    }\n\n    private boolean doExchangePeerInfo() throws IOException {\n        // Encrypt PeerInfo\n        ByteBuffer buffer = ByteBuffer.allocate(PeerInfo.MAX_PEER_INFO_SIZE).order(ByteOrder.BIG_ENDIAN);\n        mPeerInfo.writeTo(buffer);\n        byte[] outBuffer = mPairingAuthCtx.encrypt(buffer.array());\n        if (outBuffer == null) {\n            Log.e(TAG, \"Failed to encrypt peer info\");\n            return false;\n        }\n\n        // Write out the packet header\n        PairingPacketHeader ourHeader = createHeader(PairingPacketHeader.PEER_INFO, outBuffer.length);\n        // Write out the encrypted payload\n        writeHeader(ourHeader, outBuffer);\n\n        // Read in the peer's packet header\n        PairingPacketHeader theirHeader = readHeader();\n        if (theirHeader == null || !checkHeaderType(PairingPacketHeader.PEER_INFO, theirHeader.type)) return false;\n\n        // Read in the encrypted peer certificate\n        byte[] theirMsg = new byte[theirHeader.payloadSize];\n        mInputStream.readFully(theirMsg);\n\n        // Try to decrypt the certificate\n        byte[] decryptedMsg = mPairingAuthCtx.decrypt(theirMsg);\n        if (decryptedMsg == null) {\n            Log.e(TAG, \"Unsupported payload while decrypting peer info.\");\n            return false;\n        }\n\n        // The decrypted message should contain the PeerInfo.\n        if (decryptedMsg.length != PeerInfo.MAX_PEER_INFO_SIZE) {\n            Log.e(TAG, \"Got size=\" + decryptedMsg.length + \" PeerInfo.size=\" + PeerInfo.MAX_PEER_INFO_SIZE);\n            return false;\n        }\n\n        PeerInfo theirPeerInfo = PeerInfo.readFrom(ByteBuffer.wrap(decryptedMsg));\n        Log.d(TAG, theirPeerInfo.toString());\n        return true;\n    }\n\n    @Override\n    public void close() {\n        Arrays.fill(mPswd, (byte) 0);\n        try {\n            mInputStream.close();\n        } catch (IOException ignore) {\n        }\n        try {\n            mOutputStream.close();\n        } catch (IOException ignore) {\n        }\n        if (mState != State.Ready) {\n            mPairingAuthCtx.destroy();\n        }\n    }\n\n    private static class PeerInfo {\n        public static final int MAX_PEER_INFO_SIZE = 1 << 13;\n\n        public static final byte ADB_RSA_PUB_KEY = 0;\n        public static final byte ADB_DEVICE_GUID = 0;\n\n        @NonNull\n        public static PeerInfo readFrom(@NonNull ByteBuffer buffer) {\n            byte type = buffer.get();\n            byte[] data = new byte[MAX_PEER_INFO_SIZE - 1];\n            buffer.get(data);\n            return new PeerInfo(type, data);\n        }\n\n        private final byte type;\n        private final byte[] data = new byte[MAX_PEER_INFO_SIZE - 1];\n\n        public PeerInfo(byte type, byte[] data) {\n            this.type = type;\n            System.arraycopy(data, 0, this.data, 0, Math.min(data.length, MAX_PEER_INFO_SIZE - 1));\n        }\n\n        public void writeTo(@NonNull ByteBuffer buffer) {\n            buffer.put(type).put(data);\n        }\n\n        @NonNull\n        @Override\n        public String toString() {\n            return \"PeerInfo{\" +\n                    \"type=\" + type +\n                    \", data=\" + Arrays.toString(data) +\n                    '}';\n        }\n    }\n\n    private static class PairingPacketHeader {\n        public static final byte CURRENT_KEY_HEADER_VERSION = 1;\n        public static final byte MIN_SUPPORTED_KEY_HEADER_VERSION = 1;\n        public static final byte MAX_SUPPORTED_KEY_HEADER_VERSION = 1;\n\n        public static final int MAX_PAYLOAD_SIZE = 2 * PeerInfo.MAX_PEER_INFO_SIZE;\n        public static final byte PAIRING_PACKET_HEADER_SIZE = 6;\n\n        public static final byte SPAKE2_MSG = 0;\n        public static final byte PEER_INFO = 1;\n\n        @Nullable\n        public static PairingPacketHeader readFrom(@NonNull ByteBuffer buffer) {\n            byte version = buffer.get();\n            byte type = buffer.get();\n            int payload = buffer.getInt();\n            if (version < MIN_SUPPORTED_KEY_HEADER_VERSION || version > MAX_SUPPORTED_KEY_HEADER_VERSION) {\n                Log.e(TAG, \"PairingPacketHeader version mismatch (us=\" + CURRENT_KEY_HEADER_VERSION\n                        + \" them=\" + version + \")\");\n                return null;\n            }\n            if (type != SPAKE2_MSG && type != PEER_INFO) {\n                Log.e(TAG, \"Unknown PairingPacket type \" + type);\n                return null;\n            }\n            if (payload <= 0 || payload > MAX_PAYLOAD_SIZE) {\n                Log.e(TAG, \"Header payload not within a safe payload size (size=\" + payload + \")\");\n                return null;\n            }\n            return new PairingPacketHeader(version, type, payload);\n        }\n\n        private final byte version;\n        private final byte type;\n        private final int payloadSize;\n\n        public PairingPacketHeader(byte version, byte type, int payloadSize) {\n            this.version = version;\n            this.type = type;\n            this.payloadSize = payloadSize;\n        }\n\n        public void writeTo(@NonNull ByteBuffer buffer) {\n            buffer.put(version).put(type).putInt(payloadSize);\n        }\n\n        @NonNull\n        @Override\n        public String toString() {\n            return \"PairingPacketHeader{\" +\n                    \"version=\" + version +\n                    \", type=\" + type +\n                    \", payloadSize=\" + payloadSize +\n                    '}';\n        }\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/SslUtils.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.annotation.SuppressLint;\nimport android.os.Build;\n\nimport androidx.annotation.NonNull;\n\nimport java.net.Socket;\nimport java.security.KeyManagementException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.Principal;\nimport java.security.PrivateKey;\nimport java.security.Provider;\nimport java.security.SecureRandom;\nimport java.security.cert.X509Certificate;\n\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.X509ExtendedKeyManager;\nimport javax.net.ssl.X509TrustManager;\n\nfinal class SslUtils {\n    private static boolean customConscrypt = false;\n    private static SSLContext sslContext;\n\n    public static boolean isCustomConscrypt() {\n        return customConscrypt;\n    }\n\n    @SuppressLint(\"TrulyRandom\") // The users are already instructed to fix this issue\n    @NonNull\n    public static SSLContext getSslContext(KeyPair keyPair) throws NoSuchAlgorithmException, KeyManagementException {\n        if (sslContext != null) {\n            return sslContext;\n        }\n        try {\n            Class<?> providerClass = Class.forName(\"org.conscrypt.OpenSSLProvider\");\n            Provider openSslProvder = (Provider) providerClass.getDeclaredConstructor().newInstance();\n            sslContext = SSLContext.getInstance(\"TLSv1.3\", openSslProvder);\n            customConscrypt = true;\n        } catch (NoSuchAlgorithmException e) {\n            throw e;\n        } catch (Throwable e) {\n            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {\n                // Custom error message to inform user that they should use custom Conscrypt library.\n                throw new NoSuchAlgorithmException(\"TLSv1.3 isn't supported on your platform. Use custom Conscrypt library instead.\");\n            }\n            sslContext = SSLContext.getInstance(\"TLSv1.3\");\n            customConscrypt = false;\n        }\n        System.out.println(\"Using \" + (customConscrypt ? \"custom\" : \"default\") + \" TLSv1.3 provider...\");\n        sslContext.init(new KeyManager[]{getKeyManager(keyPair)},\n                new X509TrustManager[]{getAllAcceptingTrustManager()},\n                new SecureRandom());\n        return sslContext;\n    }\n\n    @NonNull\n    private static KeyManager getKeyManager(KeyPair keyPair) {\n        return new X509ExtendedKeyManager() {\n            private final String mAlias = \"key\";\n\n            @Override\n            public String[] getClientAliases(String keyType, Principal[] issuers) {\n                return null;\n            }\n\n            @Override\n            public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {\n                for (String keyType : keyTypes) {\n                    if (keyType.equals(\"RSA\")) return mAlias;\n                }\n                return null;\n            }\n\n            @Override\n            public String[] getServerAliases(String keyType, Principal[] issuers) {\n                return null;\n            }\n\n            @Override\n            public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {\n                return null;\n            }\n\n            @Override\n            public X509Certificate[] getCertificateChain(String alias) {\n                if (this.mAlias.equals(alias)) {\n                    return new X509Certificate[]{(X509Certificate) keyPair.getCertificate()};\n                }\n                return null;\n            }\n\n            @Override\n            public PrivateKey getPrivateKey(String alias) {\n                if (this.mAlias.equals(alias)) {\n                    return keyPair.getPrivateKey();\n                }\n                return null;\n            }\n        };\n    }\n\n    @SuppressLint(\"TrustAllX509TrustManager\") // Accept all certificates\n    @NonNull\n    private static X509TrustManager getAllAcceptingTrustManager() {\n        return new X509TrustManager() {\n            @Override\n            public void checkClientTrusted(X509Certificate[] chain, String authType) {\n            }\n\n            @Override\n            public void checkServerTrusted(X509Certificate[] chain, String authType) {\n            }\n\n            @Override\n            public X509Certificate[] getAcceptedIssuers() {\n                return new X509Certificate[0];\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/StringCompat.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport android.os.Build;\n\nimport androidx.annotation.NonNull;\n\nimport java.io.UnsupportedEncodingException;\nimport java.nio.charset.Charset;\nimport java.nio.charset.IllegalCharsetNameException;\n\nfinal class StringCompat {\n    @NonNull\n    public static byte[] getBytes(@NonNull String text, @NonNull String charsetName) {\n        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {\n            return text.getBytes(Charset.forName(charsetName));\n        }\n        try {\n            return text.getBytes(charsetName);\n        } catch (UnsupportedEncodingException e) {\n            throw (IllegalCharsetNameException) new IllegalCharsetNameException(\"Illegal charset \" + charsetName)\n                    .initCause(e);\n        }\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/android/AdbMdns.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.android;\n\nimport android.content.Context;\nimport android.net.nsd.NsdManager;\nimport android.net.nsd.NsdServiceInfo;\nimport android.os.Build;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.RequiresApi;\nimport androidx.annotation.StringDef;\n\nimport java.io.IOException;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.NetworkInterface;\nimport java.net.ServerSocket;\nimport java.net.SocketException;\nimport java.util.Collections;\nimport java.util.Objects;\n\n/**\n * Automatic discovery of ADB daemons.\n */\n// Copyright 2020 南宫雪珊\n// Copyright 2022 Muntashir Al-Islam\n// Based on https://android.googlesource.com/platform/packages/modules/adb/+/eddd2d3a386a83f5d1e14f87a318adef4c2f1a9d/adb_mdns.cpp\n@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)\npublic class AdbMdns {\n    public static final String SERVICE_TYPE_ADB = \"adb\";\n    public static final String SERVICE_TYPE_TLS_PAIRING = \"adb-tls-pairing\";\n    public static final String SERVICE_TYPE_TLS_CONNECT = \"adb-tls-connect\";\n\n    @StringDef({\n            SERVICE_TYPE_ADB,\n            SERVICE_TYPE_TLS_PAIRING,\n            SERVICE_TYPE_TLS_CONNECT,\n    })\n    @Retention(RetentionPolicy.SOURCE)\n    public @interface ServiceType {\n    }\n\n    public interface OnAdbDaemonDiscoveredListener {\n        void onPortChanged(@Nullable InetAddress hostAddress, int port);\n    }\n\n    @NonNull\n    private final Context mContext;\n    @NonNull\n    private final String mServiceType;\n    @NonNull\n    private final OnAdbDaemonDiscoveredListener mAdbDaemonDiscoveredListener;\n    private final NsdManager.DiscoveryListener mDiscoveryListener;\n    private final NsdManager mNsdManager;\n\n    private boolean mRegistered;\n    private boolean mRunning;\n    @Nullable\n    private String mServiceName;\n\n    public AdbMdns(@NonNull Context context, @ServiceType @NonNull String serviceType,\n                   @NonNull OnAdbDaemonDiscoveredListener portChangeListener) {\n        mContext = Objects.requireNonNull(context);\n        mServiceType = String.format(\"_%s._tcp\", Objects.requireNonNull(serviceType));\n        mAdbDaemonDiscoveredListener = Objects.requireNonNull(portChangeListener);\n        mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);\n        mDiscoveryListener = new DiscoveryListener(this);\n    }\n\n    public void start() {\n        if (mRunning) return;\n        mRunning = true;\n        if (!mRegistered) {\n            mNsdManager.discoverServices(mServiceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);\n        }\n    }\n\n    public void stop() {\n        if (!mRunning) return;\n        mRunning = false;\n        if (mRegistered) {\n            mNsdManager.stopServiceDiscovery(mDiscoveryListener);\n        }\n    }\n\n    public boolean isRunning() {\n        return mRunning;\n    }\n\n    private void onDiscoveryStart() {\n        mRegistered = true;\n    }\n\n    private void onDiscoverStop() {\n        mRegistered = false;\n    }\n\n    private void onServiceFound(NsdServiceInfo serviceInfo) {\n        mNsdManager.resolveService(serviceInfo, new ResolveListener(this));\n    }\n\n    private void onServiceLost(NsdServiceInfo serviceInfo) {\n        if (mServiceName != null && mServiceName.equals(serviceInfo.getServiceName())) {\n            mAdbDaemonDiscoveredListener.onPortChanged(serviceInfo.getHost(), -1);\n        }\n    }\n\n    private void onServiceResolved(NsdServiceInfo serviceInfo) {\n        if (!mRunning) return;\n        try {\n            for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {\n                for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {\n                    String inetHost = inetAddress.getHostAddress();\n                    if (Objects.equals(inetHost, serviceInfo.getHost().getHostAddress())\n                            && isPortAvailable(serviceInfo.getPort())) {\n                        mServiceName = serviceInfo.getServiceName();\n                        mAdbDaemonDiscoveredListener.onPortChanged(serviceInfo.getHost(), serviceInfo.getPort());\n                    }\n                }\n            }\n        } catch (SocketException e) {\n            e.printStackTrace();\n        }\n    }\n\n    private boolean isPortAvailable(int port) {\n        try (ServerSocket socket = new ServerSocket()) {\n            socket.bind(new InetSocketAddress(AndroidUtils.getHostIpAddress(mContext), port), 1);\n            return false;\n        } catch (IOException e) {\n            return true;\n        }\n    }\n\n    private static class DiscoveryListener implements NsdManager.DiscoveryListener {\n        @NonNull\n        private final AdbMdns mAdbMdns;\n\n        private DiscoveryListener(@NonNull AdbMdns adbMdns) {\n            mAdbMdns = adbMdns;\n        }\n\n        @Override\n        public void onDiscoveryStarted(String serviceType) {\n            mAdbMdns.onDiscoveryStart();\n        }\n\n        @Override\n        public void onStartDiscoveryFailed(String serviceType, int errorCode) {\n        }\n\n        @Override\n        public void onDiscoveryStopped(String serviceType) {\n            mAdbMdns.onDiscoverStop();\n        }\n\n        @Override\n        public void onStopDiscoveryFailed(String serviceType, int errorCode) {\n        }\n\n        @Override\n        public void onServiceFound(NsdServiceInfo serviceInfo) {\n            mAdbMdns.onServiceFound(serviceInfo);\n        }\n\n        @Override\n        public void onServiceLost(NsdServiceInfo serviceInfo) {\n            mAdbMdns.onServiceLost(serviceInfo);\n        }\n    }\n\n    private static class ResolveListener implements NsdManager.ResolveListener {\n        @NonNull\n        private final AdbMdns mAdbMdns;\n\n        private ResolveListener(@NonNull AdbMdns adbMdns) {\n            mAdbMdns = adbMdns;\n        }\n\n        @Override\n        public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {\n        }\n\n        @Override\n        public void onServiceResolved(NsdServiceInfo serviceInfo) {\n            mAdbMdns.onServiceResolved(serviceInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/android/AndroidUtils.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb.android;\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.os.Build;\nimport android.provider.Settings;\n\nimport androidx.annotation.NonNull;\n\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\n\npublic class AndroidUtils {\n    // https://github.com/firebase/firebase-android-sdk/blob/7d86138304a6573cbe2c61b66b247e930fa05767/firebase-crashlytics/src/main/java/com/google/firebase/crashlytics/internal/common/CommonUtils.java#L402\n    private static final String GOLDFISH = \"goldfish\";\n    private static final String RANCHU = \"ranchu\";\n    private static final String SDK = \"sdk\";\n\n    public static boolean isEmulator(@NonNull Context context) {\n        if (Build.PRODUCT.contains(SDK)) {\n            return true;\n        }\n        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO\n                && (Build.HARDWARE.contains(GOLDFISH) || Build.HARDWARE.contains(RANCHU))) {\n            return true;\n        }\n        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {\n            @SuppressLint(\"HardwareIds\")\n            String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);\n            return androidId == null;\n        }\n        return false;\n    }\n\n\n    @NonNull\n    public static String getHostIpAddress(@NonNull Context context) {\n        if (AndroidUtils.isEmulator(context)) {\n            return \"10.0.2.2\";\n        }\n        String ipAddress;\n        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n            ipAddress = InetAddress.getLoopbackAddress().getHostAddress();\n        } else {\n            try {\n                ipAddress = InetAddress.getLocalHost().getHostAddress();\n            } catch (UnknownHostException e) {\n                ipAddress = null;\n            }\n        }\n        if (ipAddress == null || ipAddress.equals(\"::1\")) {\n            return \"127.0.0.1\";\n        }\n        return ipAddress;\n    }\n}\n"
  },
  {
    "path": "libadb/src/main/java/io/github/muntashirakon/adb/android/package.html",
    "content": "<p>All Android dependencies are kept under this package for easy reference.</p>"
  },
  {
    "path": "libadb/src/test/java/io/github/muntashirakon/adb/AndroidPubkeyTest.java",
    "content": "// SPDX-License-Identifier: GPL-3.0-or-later OR Apache-2.0\n\npackage io.github.muntashirakon.adb;\n\nimport org.bouncycastle.util.encoders.Base64;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.math.BigInteger;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.Signature;\nimport java.security.SignatureException;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.InvalidKeySpecException;\n\nimport static io.github.muntashirakon.adb.AndroidPubkey.ANDROID_PUBKEY_ENCODED_SIZE;\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\npublic class AndroidPubkeyTest {\n    private static final byte[] DIGEST = {\n            0x31, 0x5f, 0x5b, (byte) 0xdb, 0x76, (byte) 0xd0, 0x78, (byte) 0xc4, 0x3b, (byte) 0x8a, (byte) 0xc0,\n            0x06, 0x4e, 0x4a, 0x01, 0x64, 0x61, 0x2b, 0x1f, (byte) 0xce, 0x77, (byte) 0xc8,\n            0x69, 0x34, 0x5b, (byte) 0xfc, (byte) 0x94, (byte) 0xc7, 0x58, (byte) 0x94, (byte) 0xed, (byte) 0xd3,\n    };\n\n    private static final String[] KEYS = new String[] {\n            \"20686253007643618731996444194404343867753606615063450617882673005393433941259733754887313620913867473991126076227684529071148116710971688307399269161393680066708223500416626973582453156074796463551655506880263757530692111705709492670974173865966567229986684076018218836054376260921024258822748029571012424062161309155451659011612585496480130049086533401220131725127467783734498206350584978609270260042864036755332689164701948323567009422782353582299103998793983781904622199786127904484293079447215050401933233201140660611995982950449318766441491470794461010754367235997277784582260919909111021889463573881293340673638258140979906632549357292907467007755298711750754693102503358563113321739768558800007075371722687735888311697725543005911629713945900921982291726988822299885412290333597947505237030964811359845572308590371290828162825800693816284267659154250460946638141531109051703958714241913036543711553816745407369784077289292046547482798618404863636910359464490602947766408857942988353632212055739706153132169632236839182513092231542800002960492871433639429992495815686493836203332828415821398124085709593551180637824827628263278195555177924931666478926276783820224389307415162160245683448074970045831874158357509710640316611667245663639463489328681291088128\",\n            \"20686253017157961681070131581867072824582833493615686581285202812978323130952408474782337908483014193592959801158288937338861941384391935424181886115887706116180211910326203195827988548568848400075560545658694754072288281934799100824960003665469676627306218542649151650279594335310005774745074102233566034401681058875954456976451246992673780060830565203755535989743862421541016487655599803066890290569271073410408457924901854658523004566584730402488976324736395344746149490673499453625232592526755899773745566599094231998380788633185151420348626744906833795805930985207848484533950617753433631247755579325235753032891647748010767177734536686383017861046451119520379951845678816861944386294035286574657104145896837994175074910881605806540878194352563352369751154950231748036893872855863146059482454816118277619882879924798566063675418426269661488345544005535393697052314311247263890598514707311723166476167962362723441242864747039873917888833291982018201334656703016344691467362831812856230943332947764107530472082685276225170871545829843748520918630697076657160036883930216256677113853170428981812392602195530517909206428574912517211805856768824444514391062511206137932417723915871095033856634183547083377240616484404928845477796622124210865489291636384376815872\",\n            \"20686253012016661596297187165295953810124840916410787780259125355974730724901079696472630368937851048257090320232652157100991308376039941481829068380105246658346925724672501337521327139011807932361821638555679532028068537874220234967686261347630150684757119393835764732734869517200772690364990583127671131537583714931243019173197423018607993303448083354399470192423616983206536107095715775647406269008431508946794838483788727203899942491271993309634327951609153908662621681729016801610515674359693917283475097384354342498810325041161909134028476434295385254073752420814778998269287749533881374904934126049438895801381045118590479396113271334390254276279559056023087328573647647215037607856427456918131285395255693120064580259556735556512377323876432429678739578757363573131334912599024688462135510569451655007983978712803921393726583392694890019375462303417604382964474778937531805444153682154861176782819373335110870826625829171651646773939431655533573703527937698849234129612444879578476798107659804571742743573317338460943463599693739087545180845307099319818906850017269705411337110447078163740825844263091960377332261204721538817750302929778362322626050195563553439929517852576974112801805532465084720065825179978157459297137449086759181900619029928059339008\",\n            \"20686253007164298102187579022292645782622950267376457918101697669358007301488761837295142744126519186355305488389221986154518328646591249427359811715893827299671450881507028164629286041250862175310771677831707558127385367785197803483575096787182004608184320944234595728063837868041235349956855438493602107933402900375680275580658634153323631657275297128293064166637994755918951415154912946597772260559048829851194391800720841779417294685741008056484437199267285946970880090812268047882017049497063496655486104722944355404468824860822958344153152666873208144779124031791189998000506056940151806004196000409215856732235270100083588540707679527939391873638758465419555753702157561970233144942307459852882991188472466621152506161477788274973160814417916904823923993324434775898693916605927490225550209649971721585529738473244554435841443463085919856039187050589485138795602302083255665055214846777613999233572727226441658259782563053572457091354281339853515214717324207788284184709742610276702868576013972404040386528578798398612655692848123956484300353770097737367273673338660759524265042605762204830694090505973135478745543215676846804149964034093456987246386704478034104616628251724608616498482846759154973645939865112578396682953063481438609050519636632406065408\",\n            \"20686253013631672077140860925430431681294767795873158523291037328668344494856968639956583809600800609243074268151952075506986744112173705954028708402476984870394191960873402354883924141967550191866699568842907604201375691789447875717904606519911990426542474202257873447575301056799275687300162520647747107269726474224871972583841770132600021392824170364479997596039740110453703092023353509635466916728572484548240377314945387893669640571134322168573530937553272534344026352868086607470719702834083444892288110107409203387500645304783564563250097472203694663921776055854765509655453678476671839476460047809572066383800073578102412448677588127686456580476332728179819886722353651757881477563060082645588924556499391555273484226830089405923826482032061727033691299171028963180078332147031372667760359558227049050997025606644301016548127476540817805335115255877601761512137427173611440130583277311855464175578764391247410560993954608789331880719073041849580910172771756479685430766451208229539612899065008167414362054168182076054905614418672686595489698195205424496943265168367449853961685536803353605862503830213266961051166928463688349071936538327772591282503905358730343548547940428875061176999789174879128250317383032697059739647594262479435287070553934024147200\",\n            \"20686253009137100677580536481772220019834185053674835675104805567705108100012120793382980473459675176967509777404926949610065001902175161695962003614967789069678586166752499518706455413722715678873250863436364658098942388406798677103189295795606470644008251449037179794502035845361840650187691172794383123040477163218916023150334807750836446866590977919532470017535348573419966872388934361829146368421225272657444717715086585757479506344335650280743058062849751597138313964046571213056448713724664410661632559255622391230727347897637119451531510420187884140761879388980580251574156491409434892603700316490405451728370661830847139541500680542314851537865497120978838526245028564455048339534705369938676962653936571813488824888264746297425445127522661324094850525422265769467214262342247384649233154604849204645241734493281272153516726661106475381716751539505876924878328383153759965309983960685978480476384651288642156631803739479287061925347068044278079778523599362177880625669615321469494541417207707795112792614703988712865352607326208856280054996813476487679520479619834119561518751799862129372840860158171276154958342280155058027979175914132253409673754984859885834350221155842157851019202903208837729538330893332631827655821675906374426442436139049029730560\",\n            \"20686253016517652578576226218037280304512998878967782081643030383762252648179296997011341926638803523834137938978407145354361840964277764429298580433833879753046327333287664442011756674514375099551151016760768951640623954608522240638785781825523830834849040469461889966736539399995075932019080426966535734677817177333374424187501199788948653236985818361084089703379091583995023155469499841274582203201561305334645372332402890018547968670807123139871175453983341212876440749594027233646858105401856148507349000386220939016569850622488928617382330345394648656509732599042249901506581310905883901959534984505897371121911753593182717796270161120916944128299041339386928147022131549318082428289605796149115464012497661997457808599992494790605129095762340900378198216634471902525669353909170959057894014738736417606036662468401786737193290238560507341770145447091177773612273526207707414967862580865925752359713241893890750323872352660127060159105979208005350694984418621693785977972962175850201555015110758212910334258690225997862373112062500145196188829278217998167244761059788293227986694796302184050693617864339940026112434075085598165880397454033611127221858601971082649842623914964304450321042940327685124173187185970331014916661615200988009485722532416914981120\",\n            \"20686253011995955629076325009649943801969349915799396834999938713706577453135666219827378331078791305568238767012603523685969479718725348248703275237034007216573140943056580311779171211523596323125369774697691841627573832408640321451759775024971845341190607371902257208390902094844221754727824487661732047560640579666147972731827393052406954025855636608759486135987631984582660021446965995410633211966029298815507401281475655895406689670177716825267171265721675030636564325187593177345954853929509007143136312590872799900706331444637303395615294877562776780224309357978460277807368192971699424316405430599226137562559166681593644350393134128404993203172540565405337112770214130741644001329050834501676799331704650166273747915134031416224513404401863940821611218604578118152404764705070475345051218888969396184751106112136786410948127273335981631264270134095884196287017029694382607779915472082121808328197672918175667411956374486872625493883365083931491511971634291156868483178497893682614629335075497305499292286022408321989969349011048118695523910315223143950295729792988112393289748804875597785632720969020601590483488192942403773245914283442681067607851920760864623779136461182039085569209069946423436337464957827499602113031939666405499335195577103935340800\",\n            \"20686253012905249420753123641394125581338490431246330974155061264735030723090537231131634982701543430151111947340098713400919665484501369074291449678715950324404084971416405468246859755401939519930479946881325066315343108805200689731279192503717023845106229875664749782703938485867918135872531314893451199777947488701264763722901060781624134818284452130770584902522697944415430677834037635796007590708428660357263597678671576847673995935030932886476827700205482688638424266106169588048237006500162050678096674641748475495896688241776715995439349517453160862577278522303148756730047750797909055062592477399585648804967165274624689461786686029846025735530763855449050156214748263389735761523970386426501083016336782069534800132132814441821194458883018197602204145921510758387553720734875367542620886529149295030141428678136073816645318546217907182935719212846985527885268490931042846941843895577575986868990275246964000930910996610476509616118972208655613370459666905798364207165929375677455372211850892032163428761255574831943581170173798962498310302619079810560252634395602186653677496588976269539691991643655645015285991996519815871201426765673211289585535433601874045698363351158020555486412212492888981581014428858434326634365544072244470887968780251830419712\",\n            \"20686253012482713944170510486006503495965426418624979215207888186336584311563125668176618892341461495958989530109497058836208707044168245279695940788984032479278397649608713044920405685548592937000089068732569152566103178304391968262275366634982743672579525342222333315935193825742608586653438687027252465742150192128141744663537027469859051411958033527779975309458836521627355592244019941914250716050720601976679339560457780808022948385738031590113665471354096086486875697653599495164469297979201195396357751415927806268197841979271997133417306549038027016271542831330284708665839765584145061136794149016409901583479427347126229617073748763355410944442711689578134558428523469322867841307165512505150561440558923516413487943512575228004609949233825559134736566257971598139983362643764003946061810478982678081113673133692828469537444314163454166205388851192666274080898281014667651235171324569407150427688362370268502748192144621240298284168580601438138025554803091157078261255439130748192811252524386962992249383432688422311292315445533782932932345446806388697895661377268890467142415746788623768632474596533761037877631922147784592888033960567149861018268485072235834034618474495971824025999049529331906554158125086921199432771280915863695896037886622831739136\",\n            \"20686253017596800673636777315187534270021266420333274774530680374903816600749071306262945801692120725976064051984138994058746162072937121793853747964627815552811045393684927849560459595356986505364881801969476935753890194193700810599429133930398705250755254836009280177917842707354484199908531777573893797187673907712955690758349411755815598103902935655017090298516565740392457105436565547185001255070561133895788176000782782281412093088710504721088727045238362229707513145743387163755472103144359822049806563915934557475036319622688517527471037575232699010534869068383647539493972360025529780544812641848222048512592585298352948703198597172454291713942776468719578698387846171669051363353131159533380505301214164797646016372174811126560901763198906646299690775898549445445030438862050154367175654798908548309949046431701706518418835907611144671153892500148829267345643289528684512615681494813120785604119244868024564867462454807660897301092541915645564379781995052629376347977326432306238090292830317108743463398855319724461757906202501054760315093634564844367373695116166888912389471388175972952318344253589126281155102370809690828946212895190035082791906579557462335096539646297577735157137081490920968937162188359746613039900117481527765337456961996600639744\",\n            \"20686253021670819484641397455235988893189004357659986764689257803151409177614461364649970433006714126825319428176308950177181495096102292376641455488005607469636772210940591752734984815566464618433768320892209283008301650256134897180639126904431683668620836360770522622987413924299753298563911962706925772038987129402614215060442406183258855362002322270760435388491304782642695492897104954057313819686015892539037035024067606433686326406317580126032026561653107203711784714174553258867988922391584823277517348441610017887616725654033103467290522569906901516453939475371008093949281078143911461551090436073001946185740446013553585657161583955882953841177944465026376300855580949947151004864741065528954219420584830087663819106583270144309975996802314686009200802567965571029611087066652726123514794266804514760076981917095632831537957124002094177446121777714425501240501887464206036422959211832442482836841510124546833303416051006026030814775613976153585582885196096288806254708297796542938960077290086802302255719602193211623734787514863004972159363553648873516823809184020531994302661726715338441496144201492168521781315979852201195520642908900413827363866480500192561642524090584879553530477247358859671792789145550860764422409857398848511879706827894470738176\",\n            \"20686253007779418538146435611960103480111665071547886109640735401007273574064776615540701179896428377142052442567006099697162043246765708980976145988576633992791951978052644497415923662944617922884643981724695008383893280530637173581248946990739081903596261263913018197718895124329861431222284653233340024925156526473018621659579602661924631346612848404894851502528305401866261493226279256928046285934986381048052034850172444367408714525087992488005859355731486073285673373650699722735519641713322832229543168311432490222848569998028342925773025050691460124263527225809542829858215777298289860007795297848906118975152353977610454216097635614989263760656961019437297514661609993804271689676470502860376666591936653476564447284287948444996394814992534945211106658510902269472032893555816145339327183535542766040947125922850444024392962311389749647694036921114853739217072675694979896955780825486065012334086560739968331771161859717998929049806691359069902247801751447279973168812586166245092210343145733018596567430818598988422806423359671179738425327829924055793651209866185908863272645671672053161275134558190614726280574493595200071091284480123481958235975875823917688354274132904898857900963754501168982796149653431776796588769427548375743948019813104125739264\",\n            \"20686253007604876142864868042280524165402934179882610914697720762337073476216917389996124773136098970057364791099676488858171958566606397819353213332750920419342798801931043028447913975575839783079948872757605203684602892225855510703027538051098416020818203339920511893350539925823111193247570595010592164929661686244708062422421354240082899804498188803419141823510080225562148441961167143787065210061597742895645200944179873692681009532549500390826790962525777523907581122863044028963918723919775810059776782603566022001398041618219382359180430108215466147420894596600846280899658544993640061836655948799058416531930107797645597300743718230009291894571536654250713613225292199432580280761478601571747214473410393967212703089811962847476443829426705969655282817199293842112005075777464459419904700085996691611909093195963267420749267548377551222829489604133422219862110546274841495019087571956520965526972054781444561101065107965888687457231748284726446965643182772550915093919251096627310403665749159263278352617835127791887411059400056120654704697281677759462412423949563123799300922337337031434011248992699167653294572541741943792138821657961461481276538506021735660790599721725446180641231442745067805783335704101764512016456627263309212202141050291403882752\",\n            \"20686253007021608241689663659963106759118723298198840826493322751986448442693666027764988836450224647331743582291670090917210382327270531482163927227988223092974790331550687752773643667187876554181907548400902488924327949585152208488928230350565913895512207957249179245514039152326127203620938403901730645311641228704710362766137452100607502345181504058992226565546374405238584328644321921093037858527565125084661975400406032983072371091348426803460064043823708388520703550652014817583643133020229845020242944346824617584906011027684828450454972028242671768211013258545366598182329727396593002246615440504964904310838157610000834126195478113929502258505249404659889702740225008795785252745301900749237920017295319107372211580703483426556992675462580169514689033492702354908848878614127325367288349925054680142050382109615731173807465659057525671650993994596156034190434249834629081700288210478883667431390577000482807339023985920513954187158118910393481098591489866417654826052352494975210865965568210016302565250763960252121003586393653990260068738875254130452064019745948999144292814505789232823453267156783611177723108336077508126670001743428554516943943698961609321446420452826416665860184743437533100494614025619487465731926709595422582461864066896099279104\",\n            \"20686253017576328604397757628696916976575522581262455658158084545267679494101813744271361066833895727275999990362314163487589781714736086134535643149499659121815284171966664818069832388563106430729424843320170501399681992962816815405466327181883993596336326588913980995040153015039842498603793624311027080239766082382138185011127721145696561736552179519972972189860686192212873871541534333569298609110022068676249161087325016973188219381193106238748350352370017704856280849939084182123474167745313719296726857149643911426423892259144920430332447233445727394410596908871121943691683251347594543016832133353836309946329620336278195398229250583694331105065483574747460477844028959296763798522682650225035915279057821815082477316716472233093622430236186011224736996806782238285457943841178908716320629716681607442109914452439698030106201073955996654282803838012221802786122722463668921800632723654622027772616422218197375832565654227089919843040086396119306096757556190008760084017430688032081654953292207865443621116020116320243741976393955557450724420382106551748948637361361237424102598662130622446951212397620681130020351934387640468968673784832844072192051121879959906157803839174272822858710610565971349380572855080734703266039110827437002755727257645879394560\",\n            \"20686253015632194446964549752865306095675796992984280836459827244594988985728341929467828908174136317388413601759640625700697567744571888535192920357933899911995149737015137803918541787810386447480938150007979984323709223630514858926018913313903533635089468154621298339064447275675686499058206570127524798025633713627136893628055375633970109073821185460898039856680258335615963791682491988980277498832573429849348764105832237085843498643498195695163785310161310344120423648634988353729865581801558283805742288660458122510719188397548085580202887930607910533534516693933657267260780859925051022338611693920561790642016487656354781128170103744324893680564297782645461578140938361264816397758641997289612268599215669012143301913510494792757326575404821915282598318350394530566425173158364070432671579795603645149354325381596532039075427958043639242360621114659751231872073036120732181043105972973109788769983560711082730917065413254697951492111991932795350395291042777547404358191506284743875086602012076691203993957228415814341341317076567346863011063363884150995846166969589047317632929392743149362575140604429955129918452363340274074095953595228692113309367060073180152866610193934981631436082786314283160713802768267996895973676591655886961137949790395651064064\",\n            \"20686253008280076434063627792976585679258240901117771774848183680897991358808598372294247945349776781930725891159660642772324594460473591428092423907922733507827637130679002417108815594381100952950780741331843640801790721759935458380251498677194095462459535511544103447989319232932465020496572704531324890159727609395394440487675667733293698176844674240132373049476798001543842889891227651621801389443373039936389118507727414268889974019400734622787942381724850321036295849698333470872363731655908573604683885345765197680079122655638597424255830729241057473120238971524652052886581049260033714044170704671920548231649930751117900234527322744641536960791319040850129139290431448454658633022000433479483039128614980515014378005152986215764207972187867609137628051392176711451953239313092106278507175222152806081191880959633861865125667318317791167731714976299042173744637249086661016974783212613211649879521639713884566600223256092655930849081112415596892313717463722708665626233145587935660772625224236074541613317671527221358656944545879413948646453563296121659821042385880073296612404056486812912561838422746761742255638925665021058593318024264673057295116442867443437729038595456425369615349800800527803917805871133175616209136030135179809038417225106990301440\",\n            \"20686253024951658247963784256461033211161677366121981865435929241662537577939141826066423582382620272467025896961525533649529834951928815732696192031254242001310976196395313722735262686979806326419012885189967369774411212706004362512392149609842235706677304433133443952583032520610040362070455319152450494660815670160633796512952042902222316108338953442388922875611033294149441219453308994445197831263244239682760264737410367007220572112879442727200430192143800723337291968248880476611034380579121992553429999072019510264034072224367169076681647830266796198698184376443826044285160611787998026826563875013778342721603031807058331671932037301518976354062079082150728323092697138014541325857426045339923252246197903880065058351701199295574478678901159403090260453086693563410504667697340773698567005624143430980337698805702319491020156284314353992648718466728823214596123324888480179957675142649621354384527020551369805874882218433548180164260225089194029633825464003674135793863996433213944915953458051073341886199898474985986664620533716615542750212008869522238677744797202727258018045172140382145668069884754503189079041670422324774317816739968675502203964561699314302235308312748370659797007514871638586017968916729509284382607208921962626655481606857704866048\",\n            \"20686253015329051263633614301062841926780457793244333362445652976039258394085904409997569212036513569627020122416105184089156035648212037623378445311136404144169674742143343217136229368645245696403751711017904206141255246181738620208604563131352355142398183885029711993169895631312556797474335190203415666424731815815318567886625912492670817003495147968334343459502296653971351530810954197377406607923523701655523747303747572405902504136614192793569878303382172717914572317866962252666818690300625318696007782616025654101394182820792992039050797265658839910245551706198215350312385971886655288470117569599164586651540666084220530837687983855363703457438523945771377188384096611403701921732343378131772105605616111230060395767250296130321274230574922212950953525510434760474902956273375775869424140206127230345610638214846167903417131896656272090379493970136500706006844054279981738876197283239177788834113814444218385342970502089028750415245685729607184037765166339498069290010361131234888359345071611741250271620624165209355771772144843622884733754033577735187746521804131583913214093166309888724137377435858133185966519694264750031605141214041348529307409532348278522558737337691108243193690034235284716283236278857093221201219489501714217369972614111881593088\",\n    };\n    private static final String[] SIGNATURES = new String[] {\n            \"8528503594670204436052357015928862792506358113369106777406225289021120755325204284915095461436534593726527514965930392069276752206673637292335104066658988404928981760593418142871524780306395774215697719603009673950459832507052700686367128506073190142373812763000304886902929199810111204681208295515597746727406521222365667866848729045254159801613868059972975579907523041955922782192361370263034597048555422592874100353115430271270939317456318510451811646267157137577724074073241955677595103004166831493027134464898153615411682508571271524917051485420113620183698439910489332188676948813054298376589190870205376721722\",\n            \"12714752653171379071902223518900086455469254778099176783756546057501252740388760646633111438554988457804110827172122185741643374376377476845818226306550070549540100924375173033053872725592206270543865057909506204686416217217175205975936864769675359443835464932866652953564668335772839380415278907842078521565813907913565738769303530371937587632865012931316702492771417680964122472313546679654313803229834342261250191743408149738051095079442654981806457495648490488615580878652623030639431127849097089635678230782461813874847730298433045763073635235796063186457060470168072867337516295219377274643254214166187741928195\",\n            \"13908999250565370485651189816621604309406838390888107327583648160922258563174890896666525571590573441122409145906761904814530942061844184451657972503856070661891327123507140696829535452282425270195643203742925435202847440053652045520143275171734902378485911971935113470515174453988792439225620093679659059409128896537294846575246782278559049832955440237015381818190544157681329515828756452798679892374749946754033759443639475313334060671371142984239868008118691626803951984815668325843801784709432199331447858105577423245817671538352849819889855177911611607915665983585833151320422174088007859931381348016319265461694\",\n            \"10663928803538142495874798753524371044109713444112476166920999738661408452717517594386747916849812868865845184227592286809206405151706316864404978033443369238163211298053129657897912511475878426734168668138448142684774180483848489762892194047712675443661602073836529221861198253894032646440612405989149292046072809162239075060183622012102135247005904791258725387249405763973030121585327387996523577075440922630211242753391888083653575027601995970547566022378966563679332453413606097684906558136475009659092263370997631008298982911150670427099551097448345541506637646597809408731612314781030427962298783217248914223806\",\n            \"2306715670154317872337078201496706067018016875073166641656805679181208518844313408613041429049277142712575268846333720788389889629069536193483907615434194600534988985015385608627085443890672124721486043133411014103460576453162713180941943637321699804181949641374502608547423908202551134802437475178385172142729079080049166263881079442027408091314096230581266354997604485294706409288693050419576182967429750806152579311940537301588263217818952406077159490924792302551188620989397020490518323111334752644091498632583425115828895844183618266417719447627326662269293970039782216019092059851746977085656284304341508057993\",\n            \"4659358238164596158948789743224240069711265838365302036573085292613329291682190238495190399519475812546652724862729777463345410534406299261146698284440785385833664987236353362536409224868061055771434659441519724477807214986173373107393432602854768393738777892796122503107069552589289874263521713955968508746406485296523435090470754765084421945615052354670619502660960366860227870952975168583254800217898305238191480303688181715819411899720342242163096384819366364486118817498794842558871973328704472113837172120537734616429530518033340109825721160272151409573547421252939751876457633571421692240302001467345028442601\",\n            \"4049477946498817875644423736582614129429104652925293903578491350187944109357140281079215461385310310227699148230226103813511093858314731577806298771933039828435988536582683795573155489962134767330360695808904080698959547160137535666545619466761042007784679323603927971926202759931895569401425552243257170909460081819203771507281795697451004296311404365704082156689073796657538886169509765942854790434677625126588993604623270447590077611239790400219558927531394967281599304514894414627660359455930701315462448554588404533268609540765516347343066315049932609011242206592126920115645749055638930724732121135122116141166\",\n            \"-15821074705595424775489985353461364659530670829708431022534131332700730014024858879661015439321392526031983716218847190089100850526695320564737549648506802838787532008475561270345163817098663400387502475397954072183343244145179711236049401253605959260401466676172293703977395461139502392520912345905534309764600115973777897708515531741002585035454835142666002006897210376288419070871163424306698312361191916347081600355010527694492360779722717717750770230108246572032092508371533877677011198486557314243866055301211143049322569030292978261520962920278653892612567676627225563117772597001334618978059073836056716669225\",\n            \"-3253944899977321876942783783337240903554123129096642235321635334925673112914508303442241100990114967311556077951307727781710343006400897352395067739623245112414217140757020483043902863652615234151122932808390646136142553799710067271445726854624819815642073592109754781288339958163810012173119634614599349819358363736874502076277367766337257137053470157924537552941473944009380652976471624978609651165801832875705879218057300556705292310854083054205343202526672473020368237867322973861758935442876895613369159646304355164238984667221571500917386264593984463607981687284420899772355044207890979293151892151717827509819\",\n            \"9499141240577043451589632252552399646757731315654129758760015349045571672430739028949896539759619921365912271793699639488523910752170974284878504952562109143512853537668435378131893436415070630973505762192641967189753052893201272349296728232365714025670987726850356205941217266924338273790152610590219162996666427392130736201968771225650743588893284231594006554226911151399044815787836234434162548055950690340366254107040568369155820242765188526434944719636880243193487042089094702078107054425645211148742327810444676596010608038011230808463633129576609253919361989917628880939682855954355300546341301909315104641292\",\n            \"2785829464159962785792464154214301170737801888846376572507071703868621757492888529934734721293299181626548638776917276845515937348930186241646686214395195802058604838439131193816292088810714374344194956806787815938869239553710725569223765884297868657637234129941827347968009169909865231403471928705479925843478070964175560548021424092972184851431376822977172730546215170545593072337665216944481311725273881895390870402865177526671062318915225337990250246626982564561668482752340309344623795724163702528068799345034816267947632414651344549931495044609876171529597903856776762161922406306755255424075670945233876468235\",\n            \"9693399573277126168117955145498856804911026370939734084616110928720966781810687706982467213763886301391323622148228097849029578280382356919106089289850794524605638208088414420886934380985144626389853251740087295754111363849778298354982244500232225340060817412736334732343104887783650252691586118114592726131559322014895783483438914376642606356658629244848851203222766693264106049037206515886724418160132270092812177670695280590828717742154134306911500638045109639882998686085462128237114003344000744142984004964727666767343836058943694299268149858387245532882552313792450703351859102940672866025492125862734810702868\",\n            \"2588026480762077299880435211630462130829042494172803139844752929165151314366576349692479708707902818325002447901174618910914735813021836209789642281992964413385413651230009333804422618970344994918374367306597128918353293939655079898804834272495466247472976936750289217893184038643984663442084787174472727556425006629985118671735361758704886890235923409705820370265894413685399080693702003337025366946813158285546498272869112876242928634530360165484359119404508056677189703714418493887546407516490045931543871651300601164453872612008839158278878642833640818155397129455955015836831802614094386547616288007668519396656\",\n            \"-11728748857916220938525563370642851174888323460551443012033711709118634455694860641893644284241538905301760022334170567702665954472646365780973999849934512640749241332019089471035867766088117990425231025030842560049003944730933840471815845647939175446669519176892871100667327144122288934729242175451319185176733723593770503584081246166626636645030357166311144861050296775574567995193508629237812544699293985433002148216129743645932049717574867996068064127541167278296952065930035012382421475825376778590937794554225647092055932998039404832926821724386093261449972691735490787917635072888523885575813644811005358833688\",\n            \"-15229937207665399077858745779056928142076482322535266981438711930746572914030457988461614013826308364893535928521195966837848031188929394769614489759198148009387852082467397161392193074580370561838070595801238055150547001898037272379177792186097373425590642040064504319592980875488946638406365056236476661594999049247103250079448049760186508271091630332833596279458697068078832218087075544964591498372812863039399793891647438843170406180128852474289724184601066049404074247449524559845321683147746932532594721096776453826585995068663187778354136614612407086729935627102933428001169544176494702260120088616177094122596\",\n            \"4423817485097350932424418489755694412699593088843423207118652642017753124828670168023683986663483348010821563740973349339039999652593572489226634061594354003970858509410018682617414793335864951696251946617385611984536476771260728219342233573060916777310319872368264904534560004743365113463062419519791519083814132572592001715626074081892878836026456243524878087931315541387440248693791684485700635565529131429893772243402800191002799200914843481323690852313588145236316661063827783308810378121509659713394573216583671878018935266378492137948180346291679018739284608191825337179228499660670255782455554732811032893595\",\n            \"14060727610797171065873730743344628826300688857981195853338897134682600312555998942680998373000530961057721631672534399458386502204866782136713687245588626842312961478612189645195715241803501047584717823837224418642078891142575255896720379626691373477223808040839453370799715426143237974402342331020941533125564932963228074818891707580296516262584451816695873169230235668081091425131622898726217356123668519420820803676318446901933688924722455581079574809688082011559628335681866023133655136379898615214209349346203435853293689318189116037465645474669519318589567809649024218325830547412938703120625760137723658167545\",\n            \"12143975642996547734993210479666904095397741261764866078090510262645460132290235986630376713004350672851651807054875332939956731775733959997351324143497076406076776154977723396094902338839439098161231984686885314849947129332117197645344151755344324038625202859604817402251985217489847067013287339738384296915967594310421751908244841803407747710371415190598155158739898568686373111717605879278384135851318969079281050507414909011506576169586220120054116056221990949404820925350166961128163192137909212020962545745326872002538950594091355414304183527270036601878504771221000529804769425263948649859429914831451793830447\",\n            \"7681905128991420738358979923777240433337546546660192093231163456029821861424188702648102462301544733499592591906609649350535414419477664467070025593525931603028515171360109575816154776046183332815807349628739221532165348992025144025203444717113795284728750784856862721905401143841702874481392901879089726940312479501647028937736816673686877284445430463537947530572199915087117895344271025474693120828230653492777168767540782277375513209223619007329449471451811372004116502977451480549159579358749540564515729677785198516083957467543681269622455949740687260144765977931043642705413831493101417185777391942989245676973\",\n            \"6324957736802947762698105017681228051594271495029008384509236777170014306498658302206164665097448703570931287007659305566350360036085316522653055137878512074480755437541173568670880476898182300821763522340043814781148109583375526242284492181946863678861291620814183269643728258345959383134128289995080908583694306703558113066837628145217885578776624299254179033312744171665733436458179725336656848290970572987456090589484353899143202322971998318634185334126489034866595781074592194167476225131764951162637607536439161513547138214421713349130949142742184752353531752780426054707814473818221353155710305120310324535073\",\n    };\n\n    private final RSAPublicKey[] mPublicKeys = new RSAPublicKey[20];\n\n    @Before\n    public void setUp() throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {\n        for (int i = 0; i < 20; ++i) {\n            mPublicKeys[i] = AndroidPubkey.decode(new BigInteger(KEYS[i]).toByteArray());\n        }\n    }\n\n    @Test\n    public void decodeTest() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {\n        for (int i = 0; i < 20; ++i) {\n            Signature signature = Signature.getInstance(\"SHA256withRSA\");\n            signature.initVerify(mPublicKeys[i]);\n            signature.update(DIGEST);\n            assertTrue(signature.verify(new BigInteger(SIGNATURES[i]).toByteArray()));\n        }\n    }\n\n    @Test\n    public void encodeTest() throws InvalidKeyException {\n        for (int i = 0; i < 20; ++i) {\n            byte[] pubKey = AndroidPubkey.encode(mPublicKeys[i]);\n            assertEquals(ANDROID_PUBKEY_ENCODED_SIZE, pubKey.length);\n            assertArrayEquals(new BigInteger(KEYS[i]).toByteArray(), pubKey);\n        }\n    }\n\n    @Test\n    public void encodeWithNameTest() throws InvalidKeyException {\n        String name = \"MyAwesomeApp\";\n        byte[] nameEncodedBytes = AndroidPubkey.getUserInfo(name);\n        int pkeyB64Size = 4 * (int) Math.ceil(ANDROID_PUBKEY_ENCODED_SIZE / 3.0);\n        int expectedLength = pkeyB64Size + nameEncodedBytes.length;\n        for (int i = 0; i < 20; ++i) {\n            byte[] expectedEncodedBytes = new byte[expectedLength];\n            System.arraycopy(Base64.encode(new BigInteger(KEYS[i]).toByteArray()), 0, expectedEncodedBytes, 0, pkeyB64Size);\n            System.arraycopy(nameEncodedBytes, 0, expectedEncodedBytes, pkeyB64Size, nameEncodedBytes.length);\n            byte[] actualEncodedBytes = AndroidPubkey.encodeWithName(mPublicKeys[i], name);\n            assertEquals(expectedLength, actualEncodedBytes.length);\n            assertArrayEquals(expectedEncodedBytes, actualEncodedBytes);\n        }\n    }\n\n}\n"
  },
  {
    "path": "settings.gradle",
    "content": "include ':libadb'\ninclude ':app'\nrootProject.name = \"libadb-android\"\nproject(':libadb').name = 'libadb'\n"
  }
]