diff options
| author | Lena <lena@omega> | 2026-01-01 00:00:00 +0000 |
|---|---|---|
| committer | Lena <lena@omega> | 2026-01-01 00:00:00 +0000 |
| commit | 7e04941bccb2683f8a6e3ee38a99c50129234dd1 (patch) | |
| tree | 471227fa437291e7a6b499e3de6c106c54eaf311 | |
| download | rsend-7e04941bccb2683f8a6e3ee38a99c50129234dd1.tar.gz | |
rsend: push phone folders to a home SSH host over rsync
A small Android app for one-way folder backup, a KISS alternative to
Syncthing. It bundles rsync (built from pinned source via the NDK) and
a pure-Go SSH transport, both shipped in the APK as lib*.so and run from
the native library directory.
rsend pins the host key, stores the ed25519 identity Keystore-encrypted,
pushes each folder additively or as a mirror, and runs on demand or on a
WiFi-only schedule. The build is self-contained and reproducible: make
setup provisions the toolchain, make builds rsync, rsh, and the APK.
85 files changed, 4772 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a281502 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# Build output and native-lib artifacts (rebuilt from source). +/out/ +/app/build/ +/app/src/main/jniLibs/ +/rsync/work/ +/rsync/*.tar.gz +/rsh/rsh + +# Gradle and Android local config. +.gradle/ +/.kotlin/ +/local.properties + +# Secrets: .gitignore is the secret manager. +*.keystore +*.jks +/keystore.properties + +# Editor and OS noise. +*.swp +*~ +.DS_Store @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c41c7e4 --- /dev/null +++ b/Makefile @@ -0,0 +1,41 @@ +# rsend build orchestration. Heavy lifting lives in the shell scripts so the +# project builds with one `make` on any Debian box with the pinned toolchain. + +.POSIX: + +all: native app + +# Provision the pinned toolchain (JDK, Go, Android SDK+NDK, Gradle) into +# $HOME/toolchains. One-time; then `. $HOME/toolchains/env.sh` before building. +setup: + sh ci/setup-toolchain.sh + +# Native executables, shipped inside the APK as lib*.so. +native: rsync rsh + +# Real rsync, cross-compiled from pinned source via the Android NDK. +rsync: + sh rsync/build.sh + +# Go SSH transport, cross-compiled to Bionic PIE via the NDK (needs the NDK, +# like rsync). rsh logic is verified host-side by `make test`. +rsh: + sh rsh/build.sh + +# Android app. Consumes the native libs from app/src/main/jniLibs. Uses the +# pinned system gradle; run from the repo root where settings.gradle lives. No +# wrapper jar is committed; gradle/wrapper/gradle-wrapper.properties only pins +# the version for F-Droid's gradlew, which refuses to build without it. +app: native + gradle :app:assembleRelease + +test: + sh ci/test.sh + +verify-repro: + sh ci/verify-repro.sh + +clean: + rm -rf out app/build app/src/main/jniLibs rsync/work rsh/rsh + +.PHONY: all setup native rsync rsh app test verify-repro clean @@ -0,0 +1,122 @@ +rsend +===== +Push configured phone folders to a home SSH host using real rsync. + +rsend backs up folders such as DCIM, WhatsApp media, and call recordings to a +remote host over SSH. One-way push only, on WiFi by default, periodic or +manual. Small, boring, self-contained: real rsync and a pure-Go SSH transport, +both built from source and shipped inside the APK. No foreign prebuilt +binaries. + + +What it does +------------ +- Pushes one or more local folders to remote paths over rsync-over-SSH. +- Incremental: only changed files move; large videos resume (rsync --partial). +- Per-folder deletion policy: additive backup (default) or mirror (--delete). +- Runs on unmetered WiFi, periodically (WorkManager) or on demand. +- ed25519 key auth with strict, pinned host-key verification. + + +Layout +------ +- rsh/ pure-Go SSH transport used as rsync's remote shell (-e). +- rsync/ build script that compiles pinned rsync from source via the NDK. +- app/ Android app (Kotlin, classic Views); bundles both as lib*.so. +- ci/ CI-agnostic build and test scripts; the Makefile drives them. +- metadata/ reproducibility and F-Droid build notes. +- versions pinned toolchain and source versions; the single source of truth. + + +Build +----- +The repository is self-contained: clone it and the build fetches and pins +everything else from source. The only host prerequisites are a POSIX shell, +curl, python3, tar, and git. The toolchain (JDK, Go, Android SDK and NDK, +Gradle) and the rsync source are downloaded and version-pinned by the build +(see versions for every pin). + + make setup # provision the toolchain into $HOME/toolchains + . "$HOME/toolchains/env.sh" # put it on PATH (do this in each shell) + make # rsync (NDK) -> rsh (Go) -> APK + make test # Go tests plus the host-side end-to-end push + make verify-repro # build twice, diff the artifacts + +The APK lands under app/build/outputs/apk/. It is unsigned by default; signing +config is local and gitignored. Continuous integration runs the same scripts: +ci/setup-toolchain.sh then ci/build.sh and ci/test.sh. + + +Run +--- +1. Install the APK and grant all-files access and notifications. +2. Generate a key in the app and add the shown public key to the home host's + ~/.ssh/authorized_keys. +3. Set the remote host, user, and port; run Test connection and accept the + pinned host-key fingerprint. +4. Add folders, choose each folder's deletion policy, set the schedule. +5. Tap Sync now, or wait for the periodic WiFi sync. + +For scheduled backup to run reliably, tap Battery and allow rsend to ignore +battery optimization. Phones with aggressive power management (Samsung, Xiaomi, +and others) otherwise delay or skip background jobs; see dontkillmyapp.com. + + +Server +------ +Any host with sshd and rsync works; rsend pushes over rsync-over-SSH, not SFTP. +The account is confined to "rsync into one folder and nothing else" by a forced +rrsync command, not by its shell. sshd runs that command through the account's +login shell, so the shell must be real: /bin/sh works, while /bin/false or +/sbin/nologin would break rsync. The confinement comes from key-only auth, the +forced command, and rrsync's write-only root. As root on the server: + + useradd -m -d /srv/backup -s /bin/sh rsendbackup + passwd -l rsendbackup + mkdir -p /srv/backup/phone && chown -R rsendbackup:rsendbackup /srv/backup + +This assumes UsePAM yes in sshd_config (the default on most distros; set it if +your build has it off). With UsePAM yes a password-locked account still accepts +key logins. With UsePAM no, sshd refuses any locked account even for keys +("account is locked"); there, skip passwd -l, set PasswordAuthentication no, and +leave the account with a non-locked password field. + +Put the app's public key in /srv/backup/.ssh/authorized_keys as one restricted +line that forces rrsync, write-only, into that directory: + + command="/usr/bin/rrsync -wo /srv/backup/phone",restrict ssh-ed25519 AAAA... rsend + +To apply the same limit account-wide, so it holds even if another key is added +later and not only on this key, force the command in sshd_config and reload +sshd: + + Match User rsendbackup + ForceCommand /usr/bin/rrsync -wo /srv/backup/phone + PasswordAuthentication no + PermitTTY no + AllowTcpForwarding no + AllowAgentForwarding no + AllowStreamLocalForwarding no + X11Forwarding no + +The account can then do nothing but receive rsync into that folder: every +session, with any key, is forced through rrsync, which rejects anything but a +plain rsync transfer into its root. Remote paths are relative to that root, so +set a folder's remote path to DCIM, not an absolute path. rrsync may instead +live at /usr/share/rsync/scripts/rrsync; check command -v rrsync. Verify the +host key from Test connection against +ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub on the server. + + +Debug +----- +- The in-app log viewer tails the plain-text rsync log. +- Reproduce a sync from a shell using the same rsync invocation rsend logs at + the top of each run. +- rsh transport: RSH_KEY, RSH_KNOWN_HOSTS, and RSH_PORT select the key, + known_hosts file, and port. Run rsh by hand to isolate SSH from rsync. + + +License +------- +GPLv3. Bundling rsync makes the whole app GPLv3; see LICENSE. diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..56036ab --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,88 @@ +plugins { + id 'com.android.application' + id 'org.jetbrains.kotlin.android' +} + +// Release signing is configured only if a local keystore.properties exists +// (gitignored). Otherwise the release build is unsigned, which is what F-Droid +// and reproducible-build verification want. +def keystoreProps = rootProject.file('keystore.properties') + +android { + namespace 'invalid.lena.rsend' + compileSdk 35 + + defaultConfig { + applicationId 'invalid.lena.rsend' + minSdk 30 + targetSdk 35 + versionCode 1 + versionName '0.1.0' + // Ship only the ABIs we build native libs for. + ndk { abiFilters 'arm64-v8a', 'x86_64' } + } + + signingConfigs { + if (keystoreProps.exists()) { + def props = new Properties() + keystoreProps.withInputStream { props.load(it) } + release { + storeFile rootProject.file(props['storeFile']) + storePassword props['storePassword'] + keyAlias props['keyAlias'] + keyPassword props['keyPassword'] + // Include v1 (JAR) signing too; some sideload installers + // (Samsung One UI on Android 11/12) reject v2-only APKs with + // "problem parsing the package". + enableV1Signing true + enableV2Signing true + enableV3Signing true + } + } + } + + buildTypes { + release { + minifyEnabled false + if (keystoreProps.exists()) { + signingConfig signingConfigs.release + } + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = '17' + } + + buildFeatures { + buildConfig true + } + + // Native executables ship as lib*.so and must be extracted so we can exec + // them from nativeLibraryDir (useLegacyPackaging => extractNativeLibs=true). + packaging { + jniLibs { + useLegacyPackaging true + } + } + + // Reproducible / F-Droid: do not embed the Google dependency metadata block. + dependenciesInfo { + includeInApk false + includeInBundle false + } +} + +dependencies { + implementation 'androidx.core:core-ktx:1.13.1' + implementation 'androidx.appcompat:appcompat:1.7.0' + implementation 'androidx.work:work-runtime-ktx:2.10.0' + + // The real org.json shadows the android.jar stub so JSON tests run on the JVM. + testImplementation 'junit:junit:4.13.2' + testImplementation 'org.json:json:20240303' +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..31c8b72 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,62 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools"> + + <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> + <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> + <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> + <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> + <uses-permission android:name="android.permission.WAKE_LOCK" /> + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> + + <application + android:name=".App" + android:allowBackup="false" + android:icon="@mipmap/ic_launcher" + android:label="@string/app_name" + android:supportsRtl="true" + android:theme="@style/Theme.Rsend"> + + <activity + android:name=".MainActivity" + android:exported="true"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + + <activity + android:name=".RemoteActivity" + android:exported="false" /> + + <activity + android:name=".FolderEditActivity" + android:exported="false" /> + + <activity + android:name=".ScheduleActivity" + android:exported="false" /> + + <activity + android:name=".LogActivity" + android:exported="false" /> + + <receiver + android:name=".BootReceiver" + android:exported="true"> + <intent-filter> + <action android:name="android.intent.action.BOOT_COMPLETED" /> + </intent-filter> + </receiver> + + <!-- WorkManager runs the sync as a dataSync foreground service. --> + <service + android:name="androidx.work.impl.foreground.SystemForegroundService" + android:foregroundServiceType="dataSync" + tools:node="merge" /> + </application> +</manifest> diff --git a/app/src/main/java/invalid/lena/rsend/App.kt b/app/src/main/java/invalid/lena/rsend/App.kt new file mode 100644 index 0000000..55ed66e --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/App.kt @@ -0,0 +1,22 @@ +package invalid.lena.rsend + +import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager +import android.os.Build + +// App creates the notification channel used by the foreground sync service. +class App : Application() { + + override fun onCreate() { + super.onCreate() + if (Build.VERSION.SDK_INT >= 26) { + val ch = NotificationChannel(CHANNEL, "Sync", NotificationManager.IMPORTANCE_LOW) + getSystemService(NotificationManager::class.java).createNotificationChannel(ch) + } + } + + companion object { + const val CHANNEL = "sync" + } +} diff --git a/app/src/main/java/invalid/lena/rsend/BootReceiver.kt b/app/src/main/java/invalid/lena/rsend/BootReceiver.kt new file mode 100644 index 0000000..3e135f3 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/BootReceiver.kt @@ -0,0 +1,15 @@ +package invalid.lena.rsend + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +// BootReceiver re-applies the schedule after the device restarts, so periodic +// sync survives reboots even if WorkManager's own state was cleared. +class BootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == Intent.ACTION_BOOT_COMPLETED) { + Scheduler.apply(context) + } + } +} diff --git a/app/src/main/java/invalid/lena/rsend/Config.kt b/app/src/main/java/invalid/lena/rsend/Config.kt new file mode 100644 index 0000000..8c9c22c --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/Config.kt @@ -0,0 +1,107 @@ +package invalid.lena.rsend + +import android.content.Context +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +// Config is rsend's whole state: the remote target, the schedule, and the +// folders to push. It is stored as plain JSON in app-private storage. + +data class Remote(val host: String = "", val port: Int = 22, val user: String = "") + +data class Schedule( + val enabled: Boolean = false, + val intervalMinutes: Int = 120, + val wifiOnly: Boolean = true, + val requireCharging: Boolean = false, +) + +data class Folder( + val name: String = "", + val local: String = "", + val remote: String = "", + val delete: Boolean = false, + val excludes: List<String> = emptyList(), +) + +data class Config( + val remote: Remote = Remote(), + val schedule: Schedule = Schedule(), + val folders: List<Folder> = emptyList(), +) { + fun toJson(): JSONObject = JSONObject().apply { + put("remote", JSONObject().apply { + put("host", remote.host) + put("port", remote.port) + put("user", remote.user) + }) + put("schedule", JSONObject().apply { + put("enabled", schedule.enabled) + put("intervalMinutes", schedule.intervalMinutes) + put("wifiOnly", schedule.wifiOnly) + put("requireCharging", schedule.requireCharging) + }) + put("folders", JSONArray().apply { + folders.forEach { f -> + put(JSONObject().apply { + put("name", f.name) + put("local", f.local) + put("remote", f.remote) + put("delete", f.delete) + put("excludes", JSONArray(f.excludes)) + }) + } + }) + } + + companion object { + fun file(ctx: Context): File = File(ctx.filesDir, "config.json") + + fun load(ctx: Context): Config { + val f = file(ctx) + if (!f.exists()) return Config() + return fromJson(JSONObject(f.readText())) + } + + fun save(ctx: Context, c: Config) { + file(ctx).writeText(c.toJson().toString(2)) + } + + fun fromJson(o: JSONObject): Config { + val r = o.optJSONObject("remote") ?: JSONObject() + val s = o.optJSONObject("schedule") ?: JSONObject() + val fa = o.optJSONArray("folders") ?: JSONArray() + val folders = ArrayList<Folder>(fa.length()) + for (i in 0 until fa.length()) { + val fo = fa.getJSONObject(i) + val ex = fo.optJSONArray("excludes") ?: JSONArray() + val excludes = ArrayList<String>(ex.length()) + for (j in 0 until ex.length()) excludes.add(ex.getString(j)) + folders.add( + Folder( + name = fo.optString("name"), + local = fo.optString("local"), + remote = fo.optString("remote"), + delete = fo.optBoolean("delete", false), + excludes = excludes, + ) + ) + } + return Config( + remote = Remote( + host = r.optString("host"), + port = r.optInt("port", 22), + user = r.optString("user"), + ), + schedule = Schedule( + enabled = s.optBoolean("enabled", false), + intervalMinutes = s.optInt("intervalMinutes", 120), + wifiOnly = s.optBoolean("wifiOnly", true), + requireCharging = s.optBoolean("requireCharging", false), + ), + folders = folders, + ) + } + } +} diff --git a/app/src/main/java/invalid/lena/rsend/FolderEditActivity.kt b/app/src/main/java/invalid/lena/rsend/FolderEditActivity.kt new file mode 100644 index 0000000..2fe2b1b --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/FolderEditActivity.kt @@ -0,0 +1,77 @@ +package invalid.lena.rsend + +import android.os.Bundle +import android.view.View +import android.widget.Button +import android.widget.EditText +import android.widget.Switch +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import java.io.File + +// FolderEditActivity adds or edits one folder mapping. index < 0 means a new +// folder. +class FolderEditActivity : AppCompatActivity() { + + private var index: Int = -1 + private lateinit var name: EditText + private lateinit var local: EditText + private lateinit var remote: EditText + private lateinit var excludes: EditText + private lateinit var delete: Switch + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_folder) + setSupportActionBar(findViewById(R.id.toolbar)) + title = "Folder" + fitSystemBars() + name = findViewById(R.id.name) + local = findViewById(R.id.local) + remote = findViewById(R.id.remote) + excludes = findViewById(R.id.excludes) + delete = findViewById(R.id.delete) + + index = intent.getIntExtra("index", -1) + val cfg = Config.load(this) + if (index in cfg.folders.indices) { + val f = cfg.folders[index] + name.setText(f.name) + local.setText(f.local) + remote.setText(f.remote) + excludes.setText(f.excludes.joinToString(", ")) + delete.isChecked = f.delete + } + + findViewById<Button>(R.id.save).setOnClickListener { saveFolder(); finish() } + val del = findViewById<Button>(R.id.removeFolder) + del.visibility = if (index < 0) View.GONE else View.VISIBLE + del.setOnClickListener { removeFolder(); finish() } + } + + private fun saveFolder() { + val f = Folder( + name = name.text.toString().trim(), + local = local.text.toString().trim(), + remote = remote.text.toString().trim(), + delete = delete.isChecked, + excludes = excludes.text.toString().split(",").map { it.trim() }.filter { it.isNotEmpty() }, + ) + if (f.local.isNotEmpty() && !File(f.local).exists()) { + Toast.makeText(this, "Warning: local path does not exist yet.", Toast.LENGTH_LONG).show() + } + val cfg = Config.load(this) + val list = cfg.folders.toMutableList() + if (index in list.indices) list[index] = f else list.add(f) + Config.save(this, cfg.copy(folders = list)) + } + + private fun removeFolder() { + val cfg = Config.load(this) + val list = cfg.folders.toMutableList() + if (index in list.indices) { + list.removeAt(index) + Config.save(this, cfg.copy(folders = list)) + } + } +} diff --git a/app/src/main/java/invalid/lena/rsend/Insets.kt b/app/src/main/java/invalid/lena/rsend/Insets.kt new file mode 100644 index 0000000..e72b5a7 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/Insets.kt @@ -0,0 +1,34 @@ +package invalid.lena.rsend + +import android.content.res.Configuration +import android.os.Build +import android.view.View +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat + +// Android 15 (target SDK 35) forces the window edge-to-edge: content otherwise +// draws behind the status and navigation bars. Pad the screen root (the toolbar +// plus the scroll content) by the system-bar insets so the toolbar sits below +// the status bar and the content stays clear of the navigation bar and keyboard. +// If the decor already insets the content the listener simply sees zero insets, +// so this is a no-op rather than double padding. Call once after setContentView. +fun AppCompatActivity.fitSystemBars() { + val root = findViewById<View>(R.id.appRoot) + ViewCompat.setOnApplyWindowInsetsListener(root) { v, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) + val ime = insets.getInsets(WindowInsetsCompat.Type.ime()) + v.setPadding(bars.left, bars.top, bars.right, maxOf(bars.bottom, ime.bottom)) + WindowInsetsCompat.CONSUMED + } + // The bars are now transparent and show the window background instead of the + // old solid bar colour, so match the icon contrast to day/night. + if (Build.VERSION.SDK_INT >= 35) { + val night = resources.configuration.uiMode and + Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES + val controller = WindowCompat.getInsetsController(window, window.decorView) + controller.isAppearanceLightStatusBars = !night + controller.isAppearanceLightNavigationBars = !night + } +} diff --git a/app/src/main/java/invalid/lena/rsend/KeyVault.kt b/app/src/main/java/invalid/lena/rsend/KeyVault.kt new file mode 100644 index 0000000..ae3e8d4 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/KeyVault.kt @@ -0,0 +1,48 @@ +package invalid.lena.rsend + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +// KeyVault encrypts the SSH private key at rest with a hardware-backed AES-GCM +// key in the Android Keystore. The Keystore key cannot be exported, so the blob +// on disk is useless off this device. Blob layout is IV || ciphertext+tag. +object KeyVault { + + private const val ALIAS = "rsend-key" + private const val TRANSFORM = "AES/GCM/NoPadding" + private const val IV_LEN = 12 + private const val TAG_BITS = 128 + + private fun secret(): SecretKey { + val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (ks.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey } + val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + gen.init( + KeyGenParameterSpec.Builder( + ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .build(), + ) + return gen.generateKey() + } + + fun encrypt(plain: ByteArray): ByteArray { + val c = Cipher.getInstance(TRANSFORM) + c.init(Cipher.ENCRYPT_MODE, secret()) + return c.iv + c.doFinal(plain) + } + + fun decrypt(blob: ByteArray): ByteArray { + val c = Cipher.getInstance(TRANSFORM) + c.init(Cipher.DECRYPT_MODE, secret(), GCMParameterSpec(TAG_BITS, blob, 0, IV_LEN)) + return c.doFinal(blob, IV_LEN, blob.size - IV_LEN) + } +} diff --git a/app/src/main/java/invalid/lena/rsend/Keys.kt b/app/src/main/java/invalid/lena/rsend/Keys.kt new file mode 100644 index 0000000..0a5384d --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/Keys.kt @@ -0,0 +1,75 @@ +package invalid.lena.rsend + +import android.content.Context +import java.io.File + +// Keys manages the on-device ed25519 identity and the pinned host keys. The +// private key is stored Keystore-encrypted (KeyVault) and only ever exists in +// plaintext in memory, passed to rsh through RSH_KEY_DATA. +object Keys { + + private fun keyEnc(ctx: Context): File = File(ctx.filesDir, "id_ed25519.enc") + private fun publicKey(ctx: Context): File = File(ctx.filesDir, "id_ed25519.pub") + + fun knownHosts(ctx: Context): File = File(ctx.filesDir, "known_hosts") + + fun exists(ctx: Context): Boolean = keyEnc(ctx).exists() + + // generate creates the key pair, stores the private key encrypted, and + // returns the public key in authorized_keys format. + fun generate(ctx: Context): String { + val tmp = File(ctx.cacheDir, "keygen").apply { mkdirs() } + Native.run(Native.rsh(ctx), listOf("-keygen", tmp.absolutePath)) + keyEnc(ctx).writeBytes(KeyVault.encrypt(File(tmp, "id_ed25519").readBytes())) + File(tmp, "id_ed25519.pub").copyTo(publicKey(ctx), overwrite = true) + tmp.deleteRecursively() + return publicKeyText(ctx) + } + + // importKey stores a user-supplied private key, replacing any current one. + // The bundled rsh derives and validates the public key (-pubkey uses the + // same parser as the transport), so a key that imports here will also sync. + // Throws IllegalArgumentException with rsh's message if the key is unusable + // (wrong type, or passphrase-protected: rsend needs an unencrypted key). + fun importKey(ctx: Context, pem: ByteArray) { + val r = Native.run(Native.rsh(ctx), listOf("-pubkey"), mapOf("RSH_KEY_DATA" to String(pem))) + if (r.code != 0) throw IllegalArgumentException(r.output.trim().ifEmpty { "invalid private key" }) + val pub = r.output.trim() + keyEnc(ctx).writeBytes(KeyVault.encrypt(pem)) + publicKey(ctx).writeText(pub + "\n") + } + + fun publicKeyText(ctx: Context): String = + if (publicKey(ctx).exists()) publicKey(ctx).readText().trim() else "" + + // env returns the RSH_* environment rsh needs. The decrypted key is passed + // by value so it never touches the filesystem. + fun env(ctx: Context, port: Int): Map<String, String> = mapOf( + "RSH_KEY_DATA" to String(KeyVault.decrypt(keyEnc(ctx).readBytes())), + "RSH_KNOWN_HOSTS" to knownHosts(ctx).absolutePath, + "RSH_PORT" to port.toString(), + ) + + data class Scan(val ok: Boolean, val fingerprint: String, val line: String, val error: String) + + // scan connects (proving the key is installed), captures the host key, and + // returns its fingerprint and the known_hosts line to pin. pin() writes it + // once the user accepts. + fun scan(ctx: Context, remote: Remote): Scan { + val r = Native.run( + Native.rsh(ctx), + listOf("-scan", "${remote.user}@${remote.host}"), + env(ctx, remote.port), + ) + if (r.code != 0) return Scan(false, "", "", r.output.trim()) + val lines = r.output.trim().lines() + if (lines.size < 2) return Scan(false, "", "", "unexpected scan output:\n${r.output}") + return Scan(true, lines[0], lines[1], "") + } + + fun pin(ctx: Context, line: String) { + knownHosts(ctx).writeText(line + "\n") + } + + fun pinned(ctx: Context): Boolean = knownHosts(ctx).let { it.exists() && it.length() > 0 } +} diff --git a/app/src/main/java/invalid/lena/rsend/LastSync.kt b/app/src/main/java/invalid/lena/rsend/LastSync.kt new file mode 100644 index 0000000..3f1d518 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/LastSync.kt @@ -0,0 +1,21 @@ +package invalid.lena.rsend + +import android.content.Context +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +// LastSync records the outcome of the most recent run so the dashboard can show +// it without opening the log. +object LastSync { + + private fun file(ctx: Context): File = File(ctx.filesDir, "last-sync") + private val fmt = SimpleDateFormat("MM-dd HH:mm", Locale.US) + + fun set(ctx: Context, ok: Boolean) { + file(ctx).writeText("${fmt.format(Date())} ${if (ok) "ok" else "FAILED"}") + } + + fun get(ctx: Context): String = if (file(ctx).exists()) file(ctx).readText() else "never" +} diff --git a/app/src/main/java/invalid/lena/rsend/LogActivity.kt b/app/src/main/java/invalid/lena/rsend/LogActivity.kt new file mode 100644 index 0000000..c9cce94 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/LogActivity.kt @@ -0,0 +1,35 @@ +package invalid.lena.rsend + +import android.os.Bundle +import android.widget.Button +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity + +// LogActivity shows the plain-text sync log with refresh and clear. +class LogActivity : AppCompatActivity() { + + private lateinit var log: TextView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_log) + setSupportActionBar(findViewById(R.id.toolbar)) + title = "Log" + fitSystemBars() + log = findViewById(R.id.log) + findViewById<Button>(R.id.refresh).setOnClickListener { load() } + findViewById<Button>(R.id.clear).setOnClickListener { + SyncLog(this).file.writeText("") + load() + } + } + + override fun onResume() { + super.onResume() + load() + } + + private fun load() { + log.text = SyncLog(this).text().ifEmpty { "No log yet." } + } +} diff --git a/app/src/main/java/invalid/lena/rsend/MainActivity.kt b/app/src/main/java/invalid/lena/rsend/MainActivity.kt new file mode 100644 index 0000000..6b51252 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/MainActivity.kt @@ -0,0 +1,338 @@ +package invalid.lena.rsend + +import android.Manifest +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Environment +import android.os.PowerManager +import android.provider.Settings +import android.view.View +import android.widget.Button +import android.widget.LinearLayout +import android.widget.ProgressBar +import android.widget.TextView +import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.work.ExistingWorkPolicy +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkInfo +import androidx.work.WorkManager +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread + +// MainActivity is the dashboard: a status hero, a primary Sync action, grouped +// Setup and Permissions rows, and the list of folders. Editing happens in +// RemoteActivity, ScheduleActivity, and FolderEditActivity. +class MainActivity : AppCompatActivity() { + + private lateinit var lastSync: TextView + private lateinit var remoteValue: TextView + private lateinit var keyValue: TextView + private lateinit var scheduleValue: TextView + private lateinit var dotAllFiles: View + private lateinit var valAllFiles: TextView + private lateinit var dotNotif: View + private lateinit var valNotif: TextView + private lateinit var dotBattery: View + private lateinit var valBattery: TextView + private lateinit var folders: LinearLayout + private lateinit var btnSync: Button + private lateinit var syncBar: ProgressBar + private lateinit var syncStatus: TextView + + private val notifPerm = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { refresh() } + + private val openKeyDoc = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) importKeyFrom(uri) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + setSupportActionBar(findViewById(R.id.toolbar)) + fitSystemBars() + lastSync = findViewById(R.id.lastSync) + remoteValue = findViewById(R.id.remoteValue) + keyValue = findViewById(R.id.keyValue) + scheduleValue = findViewById(R.id.scheduleValue) + dotAllFiles = findViewById(R.id.dotAllFiles) + valAllFiles = findViewById(R.id.valAllFiles) + dotNotif = findViewById(R.id.dotNotif) + valNotif = findViewById(R.id.valNotif) + dotBattery = findViewById(R.id.dotBattery) + valBattery = findViewById(R.id.valBattery) + folders = findViewById(R.id.folders) + btnSync = findViewById(R.id.btnSync) + syncBar = findViewById(R.id.syncBar) + syncStatus = findViewById(R.id.syncStatus) + + findViewById<TextView>(R.id.appVersion).text = "v${BuildConfig.VERSION_NAME}" + + btnSync.setOnClickListener { syncNow() } + observeSync() + findViewById<LinearLayout>(R.id.rowRemote).setOnClickListener { + startActivity(Intent(this, RemoteActivity::class.java)) + } + findViewById<LinearLayout>(R.id.rowKey).setOnClickListener { showKey() } + findViewById<LinearLayout>(R.id.rowSchedule).setOnClickListener { + startActivity(Intent(this, ScheduleActivity::class.java)) + } + findViewById<LinearLayout>(R.id.rowAllFiles).setOnClickListener { + startActivity( + Intent( + Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, + Uri.parse("package:$packageName"), + ) + ) + } + findViewById<LinearLayout>(R.id.rowNotif).setOnClickListener { + if (Build.VERSION.SDK_INT >= 33 && !notif()) { + notifPerm.launch(Manifest.permission.POST_NOTIFICATIONS) + } else { + // No runtime permission to request (pre-13) or already granted: + // open the app's notification settings so the row still acts. + startActivity( + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, packageName), + ) + } + } + findViewById<LinearLayout>(R.id.rowBattery).setOnClickListener { + if (batteryUnrestricted()) { + startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) + } else { + startActivity( + Intent( + Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, + Uri.parse("package:$packageName"), + ), + ) + } + } + findViewById<Button>(R.id.btnAddFolder).setOnClickListener { + startActivity(Intent(this, FolderEditActivity::class.java).putExtra("index", -1)) + } + findViewById<Button>(R.id.btnLog).setOnClickListener { + startActivity(Intent(this, LogActivity::class.java)) + } + } + + private fun syncNow() { + if (!Keys.pinned(this)) { + Toast.makeText(this, "Set the remote and pin its host key first.", Toast.LENGTH_LONG).show() + return + } + val req = OneTimeWorkRequestBuilder<SyncWorker>().build() + WorkManager.getInstance(this).enqueueUniqueWork("sync-now", ExistingWorkPolicy.KEEP, req) + Toast.makeText(this, "Sync started.", Toast.LENGTH_SHORT).show() + } + + // observeSync follows the manual sync's WorkInfo so the dashboard updates + // live: an indeterminate bar and the current folder while it runs, and a + // fresh status (last sync) the moment it ends, without leaving the screen. + private fun observeSync() { + WorkManager.getInstance(this) + .getWorkInfosForUniqueWorkLiveData("sync-now") + .observe(this) { infos -> + val info = infos.lastOrNull() + val running = info != null && + (info.state == WorkInfo.State.RUNNING || info.state == WorkInfo.State.ENQUEUED) + if (running) { + syncBar.visibility = View.VISIBLE + syncStatus.visibility = View.VISIBLE + btnSync.isEnabled = false + btnSync.text = "Syncing..." + val p = info!!.progress + val folder = p.getString(SyncWorker.KEY_FOLDER) + val i = p.getInt(SyncWorker.KEY_INDEX, 0) + val n = p.getInt(SyncWorker.KEY_TOTAL, 0) + syncStatus.text = + if (folder != null && n > 0) "Syncing $folder ($i/$n)" else "Starting sync..." + } else { + syncBar.visibility = View.GONE + syncStatus.visibility = View.GONE + btnSync.isEnabled = true + btnSync.text = "Sync now" + refresh() + } + } + } + + override fun onResume() { + super.onResume() + Scheduler.apply(this) + refresh() + } + + private fun allFiles() = Environment.isExternalStorageManager() + + private fun notif() = Build.VERSION.SDK_INT < 33 || + checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED + + private fun batteryUnrestricted(): Boolean = + getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(packageName) + + // jobState reports the WorkManager state of the scheduled sync (ENQUEUED, + // RUNNING, none, ...) so the dashboard shows whether the scheduler is armed. + private fun jobState(): String = try { + WorkManager.getInstance(this) + .getWorkInfosForUniqueWork(Scheduler.NAME) + .get(500, TimeUnit.MILLISECONDS) + .firstOrNull()?.state?.name ?: "none" + } catch (e: Exception) { + "?" + } + + private fun refresh() { + val cfg = Config.load(this) + + lastSync.text = "Last sync: ${LastSync.get(this)}" + + val r = cfg.remote + remoteValue.text = if (r.host.isEmpty()) { + "Not set" + } else { + "${r.user}@${r.host}:${r.port}, ${if (Keys.pinned(this)) "pinned" else "not pinned"}" + } + + keyValue.text = if (Keys.exists(this)) "Generated, tap to view" else "Not created, tap to create" + + val s = cfg.schedule + val sched = if (s.enabled) { + "Every ${s.intervalMinutes}m" + + (if (s.wifiOnly) ", wifi" else "") + + (if (s.requireCharging) ", charging" else "") + } else { + "Off" + } + scheduleValue.text = "$sched, job ${jobState()}" + + setPerm(dotAllFiles, valAllFiles, allFiles(), "Granted", "Tap to grant") + setPerm(dotNotif, valNotif, notif(), "Granted", "Tap to grant") + setPerm(dotBattery, valBattery, batteryUnrestricted(), "Unrestricted", "Optimized, tap to fix") + + folders.removeAllViews() + if (cfg.folders.isEmpty()) { + folders.addView(TextView(this).apply { + text = "No folders yet. Tap Add folder below." + setTextAppearance(R.style.TextAppearance_Rsend_Caption) + setPadding(0, 0, 0, resources.getDimensionPixelSize(R.dimen.space_m)) + }) + } else { + cfg.folders.forEachIndexed { i, f -> + val row = layoutInflater.inflate(R.layout.item_folder, folders, false) + row.findViewById<TextView>(R.id.folderName).text = f.name.ifEmpty { f.local } + row.findViewById<TextView>(R.id.folderPath).text = "${f.local} -> ${f.remote}" + row.findViewById<TextView>(R.id.folderChip).text = if (f.delete) "mirror" else "add" + row.setOnClickListener { + startActivity( + Intent(this@MainActivity, FolderEditActivity::class.java) + .putExtra("index", i) + ) + } + folders.addView(row) + } + } + } + + private fun setPerm(dot: View, value: TextView, ok: Boolean, okText: String, badText: String) { + dot.setBackgroundResource(if (ok) R.drawable.dot_on else R.drawable.dot_off) + value.text = if (ok) okText else badText + } + + // showKey displays the public key (only the key) and offers to copy it, + // generate a fresh key, or import the user's own private key. + private fun showKey() { + val view = layoutInflater.inflate(R.layout.dialog_key, null) + val keyText = view.findViewById<TextView>(R.id.keyText) + val pub = Keys.publicKeyText(this) + keyText.text = pub.ifEmpty { "No key yet. Generate or import one below." } + + val dialog = AlertDialog.Builder(this) + .setTitle("Identity key") + .setView(view) + .setNegativeButton("Close", null) + .create() + + val copy = view.findViewById<Button>(R.id.btnCopyKey) + copy.isEnabled = pub.isNotEmpty() + copy.setOnClickListener { + val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + cm.setPrimaryClip(ClipData.newPlainText("rsend pubkey", pub)) + Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show() + } + view.findViewById<Button>(R.id.btnGenKey).setOnClickListener { + dialog.dismiss() + confirmGenerate() + } + view.findViewById<Button>(R.id.btnImportKey).setOnClickListener { + dialog.dismiss() + openKeyDoc.launch(arrayOf("*/*")) + } + dialog.show() + } + + // confirmGenerate warns before replacing an existing key, then generates a + // new one off the main thread and shows it so the user can copy it. + private fun confirmGenerate() { + val msg = if (Keys.exists(this)) { + "Replace the current key with a new one? You must add the new public key to the server's authorized_keys." + } else { + "Generate a new identity key?" + } + AlertDialog.Builder(this) + .setTitle("Generate new key") + .setMessage(msg) + .setPositiveButton("Generate") { _, _ -> + thread { + Keys.generate(this) + runOnUiThread { + refresh() + Toast.makeText(this, "New key generated.", Toast.LENGTH_SHORT).show() + showKey() + } + } + } + .setNegativeButton("Cancel", null) + .show() + } + + // importKeyFrom reads the chosen private-key file and stores it, replacing + // the current key. rsh validates the key first; an unusable key (wrong type + // or passphrase-protected) is reported rather than saved. + private fun importKeyFrom(uri: Uri) { + thread { + val error = try { + val data = contentResolver.openInputStream(uri)?.use { it.readBytes() } + ?: throw IllegalArgumentException("could not read the file") + Keys.importKey(this, data) + null + } catch (e: Exception) { + e.message ?: "import failed" + } + runOnUiThread { + if (error == null) { + refresh() + Toast.makeText(this, "Key imported.", Toast.LENGTH_SHORT).show() + showKey() + } else { + AlertDialog.Builder(this) + .setTitle("Import failed") + .setMessage(error) + .setPositiveButton("OK", null) + .show() + } + } + } + } +} diff --git a/app/src/main/java/invalid/lena/rsend/Native.kt b/app/src/main/java/invalid/lena/rsend/Native.kt new file mode 100644 index 0000000..ec02cfe --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/Native.kt @@ -0,0 +1,26 @@ +package invalid.lena.rsend + +import android.content.Context +import java.io.File + +// Native locates and runs the executables shipped inside the APK as lib*.so. +// Android only allows exec of native code from the app's native library dir, +// so the rsync and rsh binaries are packaged there and run from there. +object Native { + + fun rsync(ctx: Context): File = File(ctx.applicationInfo.nativeLibraryDir, "libxrsync.so") + + fun rsh(ctx: Context): File = File(ctx.applicationInfo.nativeLibraryDir, "libxrsh.so") + + data class Result(val code: Int, val output: String) + + // Blocking; call off the main thread. stderr is merged into stdout. + fun run(bin: File, args: List<String>, env: Map<String, String> = emptyMap()): Result { + val pb = ProcessBuilder(listOf(bin.absolutePath) + args).redirectErrorStream(true) + pb.environment().putAll(env) + val p = pb.start() + val out = p.inputStream.bufferedReader().use { it.readText() } + val code = p.waitFor() + return Result(code, out) + } +} diff --git a/app/src/main/java/invalid/lena/rsend/RemoteActivity.kt b/app/src/main/java/invalid/lena/rsend/RemoteActivity.kt new file mode 100644 index 0000000..a587667 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/RemoteActivity.kt @@ -0,0 +1,82 @@ +package invalid.lena.rsend + +import android.os.Bundle +import android.widget.Button +import android.widget.EditText +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import kotlin.concurrent.thread + +// RemoteActivity edits the SSH target and runs Test connection, which scans the +// host key and pins it on the user's confirmation. +class RemoteActivity : AppCompatActivity() { + + private lateinit var host: EditText + private lateinit var port: EditText + private lateinit var user: EditText + private lateinit var status: TextView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_remote) + setSupportActionBar(findViewById(R.id.toolbar)) + title = "Remote" + fitSystemBars() + host = findViewById(R.id.host) + port = findViewById(R.id.port) + user = findViewById(R.id.user) + status = findViewById(R.id.status) + + val cfg = Config.load(this) + host.setText(cfg.remote.host) + port.setText(cfg.remote.port.toString()) + user.setText(cfg.remote.user) + + findViewById<Button>(R.id.save).setOnClickListener { save(); finish() } + findViewById<Button>(R.id.test).setOnClickListener { test() } + } + + private fun current(): Remote = Remote( + host = host.text.toString().trim(), + port = port.text.toString().toIntOrNull() ?: 22, + user = user.text.toString().trim(), + ) + + private fun save() { + val cfg = Config.load(this) + Config.save(this, cfg.copy(remote = current())) + } + + private fun test() { + save() + val r = current() + when { + !Keys.exists(this) -> + status.text = "No key yet. Generate one on the main screen and add it to the server first." + r.host.isEmpty() || r.user.isEmpty() -> + status.text = "Set host and user first." + else -> { + status.text = "Connecting to ${r.user}@${r.host}:${r.port} ..." + thread { + val scan = Keys.scan(this, r) + runOnUiThread { + if (!scan.ok) { + status.text = "Connection failed:\n${scan.error}" + } else { + AlertDialog.Builder(this) + .setTitle("Verify host key") + .setMessage("Fingerprint:\n${scan.fingerprint}\n\nPin this host?") + .setPositiveButton("Pin") { _, _ -> + Keys.pin(this, scan.line) + status.text = "Host key pinned. Connection OK." + } + .setNegativeButton("Cancel", null) + .show() + } + } + } + } + } + } +} diff --git a/app/src/main/java/invalid/lena/rsend/RsyncRunner.kt b/app/src/main/java/invalid/lena/rsend/RsyncRunner.kt new file mode 100644 index 0000000..d8f8b93 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/RsyncRunner.kt @@ -0,0 +1,47 @@ +package invalid.lena.rsend + +import android.content.Context + +// RsyncRunner builds and runs the rsync invocation for one folder, streaming +// rsync's output into the log. It uses the bundled rsync and rsh binaries and +// passes key, known_hosts, and port to rsh through the environment. +object RsyncRunner { + + // args builds the rsync argument vector for one folder. Flags are tuned for + // media backup: recursive, preserve mtimes, resume partial files, create + // the remote path, and skip the ownership and permission bits that mean + // nothing across Android and a server. + fun args(rsh: String, remote: Remote, f: Folder): List<String> { + val a = ArrayList<String>() + a.add("-rt") + a.add("--partial") + // Abort rather than hang if the network stalls for 5 minutes. + a.add("--timeout=300") + a.add("--mkpath") + a.add("--no-perms") + a.add("--no-owner") + a.add("--no-group") + a.add("--omit-dir-times") + a.add("-e") + a.add(rsh) + for (e in f.excludes) a.add("--exclude=$e") + if (f.delete) a.add("--delete") + a.add(withSlash(f.local)) + a.add("${remote.user}@${remote.host}:${withSlash(f.remote)}") + return a + } + + private fun withSlash(p: String): String = if (p.endsWith("/")) p else "$p/" + + // runFolder execs rsync for one folder, appending every output line to the + // log, and returns rsync's exit code. + fun runFolder(ctx: Context, remote: Remote, f: Folder, log: SyncLog): Int { + val cmd = listOf(Native.rsync(ctx).absolutePath) + args(Native.rsh(ctx).absolutePath, remote, f) + log.line("rsync ${cmd.drop(1).joinToString(" ")}") + val pb = ProcessBuilder(cmd).redirectErrorStream(true) + pb.environment().putAll(Keys.env(ctx, remote.port)) + val p = pb.start() + p.inputStream.bufferedReader().forEachLine { log.line(it) } + return p.waitFor() + } +} diff --git a/app/src/main/java/invalid/lena/rsend/ScheduleActivity.kt b/app/src/main/java/invalid/lena/rsend/ScheduleActivity.kt new file mode 100644 index 0000000..b917bff --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/ScheduleActivity.kt @@ -0,0 +1,51 @@ +package invalid.lena.rsend + +import android.os.Bundle +import android.widget.Button +import android.widget.EditText +import android.widget.Switch +import androidx.appcompat.app.AppCompatActivity + +// ScheduleActivity edits the periodic sync settings and (re)applies them to +// WorkManager on save. +class ScheduleActivity : AppCompatActivity() { + + private lateinit var enabled: Switch + private lateinit var interval: EditText + private lateinit var wifiOnly: Switch + private lateinit var charging: Switch + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_schedule) + setSupportActionBar(findViewById(R.id.toolbar)) + title = "Schedule" + fitSystemBars() + enabled = findViewById(R.id.enabled) + interval = findViewById(R.id.interval) + wifiOnly = findViewById(R.id.wifiOnly) + charging = findViewById(R.id.charging) + + val s = Config.load(this).schedule + enabled.isChecked = s.enabled + interval.setText(s.intervalMinutes.toString()) + wifiOnly.isChecked = s.wifiOnly + charging.isChecked = s.requireCharging + + findViewById<Button>(R.id.save).setOnClickListener { save(); finish() } + } + + private fun save() { + val cfg = Config.load(this) + val s = Schedule( + enabled = enabled.isChecked, + intervalMinutes = interval.text.toString().toIntOrNull()?.coerceAtLeast(1) ?: 120, + wifiOnly = wifiOnly.isChecked, + requireCharging = charging.isChecked, + ) + Config.save(this, cfg.copy(schedule = s)) + // Config changed: force a re-arm so the new interval/constraints take + // effect now instead of after the current countdown. + Scheduler.apply(this, force = true) + } +} diff --git a/app/src/main/java/invalid/lena/rsend/Scheduler.kt b/app/src/main/java/invalid/lena/rsend/Scheduler.kt new file mode 100644 index 0000000..af713e0 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/Scheduler.kt @@ -0,0 +1,71 @@ +package invalid.lena.rsend + +import android.content.Context +import androidx.work.Constraints +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import java.util.concurrent.TimeUnit + +// Scheduler runs the sync on a self-perpetuating chain of one-time jobs: each +// run re-arms the next from SyncWorker. This sidesteps WorkManager's 15-minute +// periodic floor (so the interval can be as low as 1 minute) and tends to be +// more reliable across OEMs. +object Scheduler { + + const val NAME = "periodic-sync" + + // Floor on the chained delay so a sync that runs longer than the interval + // cannot turn the chain into a hot loop. + private val MIN_DELAY_MS = TimeUnit.SECONDS.toMillis(15) + + // apply (re)arms or cancels the chain to match the schedule config. force + // decides what to do when a job is already pending under NAME: + // force=false (KEEP) leave a pending countdown running; only arm when + // nothing is pending. Used on app open and boot, so + // returning to the app does not reset the timer. + // force=true (REPLACE) cancel and re-arm now. Used when the schedule + // config changes. + fun apply(ctx: Context, force: Boolean = false) { + val cfg = Config.load(ctx) + val intervalMs = TimeUnit.MINUTES.toMillis(intervalMinutes(cfg)) + arm(ctx, cfg, force, intervalMs) + } + + // armAfterRun schedules the next run so the cadence is measured from when + // this run STARTED, not when it finished: delay = interval - runtime. That + // keeps "every N minutes" close to N minutes instead of N plus the sync + // duration. Always replaces, since the finishing run holds the unique name. + fun armAfterRun(ctx: Context, runMillis: Long) { + val cfg = Config.load(ctx) + val intervalMs = TimeUnit.MINUTES.toMillis(intervalMinutes(cfg)) + arm(ctx, cfg, force = true, delayMs = (intervalMs - runMillis).coerceAtLeast(MIN_DELAY_MS)) + } + + private fun intervalMinutes(cfg: Config): Long = + cfg.schedule.intervalMinutes.toLong().coerceAtLeast(1) + + private fun arm(ctx: Context, cfg: Config, force: Boolean, delayMs: Long) { + val s = cfg.schedule + val wm = WorkManager.getInstance(ctx) + + val ready = cfg.remote.host.isNotEmpty() && cfg.folders.isNotEmpty() && + Keys.exists(ctx) && Keys.pinned(ctx) + if (!s.enabled || !ready) { + wm.cancelUniqueWork(NAME) + return + } + + val constraints = Constraints.Builder() + .setRequiredNetworkType(if (s.wifiOnly) NetworkType.UNMETERED else NetworkType.CONNECTED) + .setRequiresCharging(s.requireCharging) + .build() + val req = OneTimeWorkRequestBuilder<SyncWorker>() + .setInitialDelay(delayMs, TimeUnit.MILLISECONDS) + .setConstraints(constraints) + .build() + val policy = if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP + wm.enqueueUniqueWork(NAME, policy, req) + } +} diff --git a/app/src/main/java/invalid/lena/rsend/SyncLog.kt b/app/src/main/java/invalid/lena/rsend/SyncLog.kt new file mode 100644 index 0000000..44c4d46 --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/SyncLog.kt @@ -0,0 +1,26 @@ +package invalid.lena.rsend + +import android.content.Context +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +// SyncLog is a plain-text, append-only log of sync runs, capped in size. It is +// what the user reads to see what rsend did and to debug failures. +class SyncLog(ctx: Context) { + + val file: File = File(ctx.filesDir, "sync.log") + private val fmt = SimpleDateFormat("MM-dd HH:mm:ss", Locale.US) + + fun line(s: String) { + file.appendText("${fmt.format(Date())} $s\n") + } + + // Truncate once the log grows past the cap so it cannot fill storage. + fun rotateIfBig() { + if (file.exists() && file.length() > 512 * 1024) file.writeText("") + } + + fun text(): String = if (file.exists()) file.readText() else "" +} diff --git a/app/src/main/java/invalid/lena/rsend/SyncWorker.kt b/app/src/main/java/invalid/lena/rsend/SyncWorker.kt new file mode 100644 index 0000000..f4607ea --- /dev/null +++ b/app/src/main/java/invalid/lena/rsend/SyncWorker.kt @@ -0,0 +1,103 @@ +package invalid.lena.rsend + +import android.app.Notification +import android.content.Context +import android.content.pm.ServiceInfo +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.work.CoroutineWorker +import androidx.work.ForegroundInfo +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +// SyncWorker runs one full sync as a foreground job: it pushes every configured +// folder with rsync and records the outcome in the log. It is used for both the +// manual "Sync now" action and the periodic schedule. +class SyncWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) { + + companion object { + const val KEY_FOLDER = "folder" + const val KEY_INDEX = "i" + const val KEY_TOTAL = "n" + } + + override suspend fun doWork(): Result = withContext(Dispatchers.IO) { + val ctx = applicationContext + val startedAt = System.currentTimeMillis() + val cfg = Config.load(ctx) + if (cfg.remote.host.isEmpty() || cfg.folders.isEmpty() || !Keys.exists(ctx) || !Keys.pinned(ctx)) { + return@withContext Result.success() + } + + val log = SyncLog(ctx) + log.rotateIfBig() + log.line("sync started (${cfg.folders.size} folders)") + // A foreground service lets long syncs survive, but Android 12+ forbids + // starting one when the periodic job fires in the background. Try it, and + // fall back to a plain background job when it is not allowed. + try { + setForeground(foregroundInfo()) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.line("foreground unavailable, running in background") + } + + var ok = true + val total = cfg.folders.size + cfg.folders.forEachIndexed { i, f -> + val label = f.name.ifEmpty { f.local } + // Publish progress the dashboard observes (current folder, i of n). + setProgress(workDataOf(KEY_FOLDER to label, KEY_INDEX to i + 1, KEY_TOTAL to total)) + log.line("=== $label ===") + val code = try { + RsyncRunner.runFolder(ctx, cfg.remote, f, log) + } catch (e: Exception) { + log.line("error: ${e.message}") + 1 + } + log.line("exit=$code") + if (code != 0) ok = false + } + log.line("sync finished ok=$ok") + LastSync.set(ctx, ok) + if (!ok) notifyError(ctx) + // Re-arm the next scheduled run (the chain), measuring the interval from + // when this run started so the cadence stays close to the configured + // interval. Always succeed so a failed run does not break the chain. + Scheduler.armAfterRun(ctx, System.currentTimeMillis() - startedAt) + Result.success() + } + + private fun notifyError(ctx: Context) { + val n = NotificationCompat.Builder(ctx, App.CHANNEL) + .setContentTitle("rsend") + .setContentText("Sync failed. Open the app and check the log.") + .setSmallIcon(R.drawable.ic_notification) + .setAutoCancel(true) + .build() + try { + NotificationManagerCompat.from(ctx).notify(2, n) + } catch (_: SecurityException) { + // POST_NOTIFICATIONS not granted; the log still records the failure. + } + } + + private fun foregroundInfo(): ForegroundInfo { + val n: Notification = NotificationCompat.Builder(applicationContext, App.CHANNEL) + .setContentTitle("rsend") + .setContentText("Syncing") + .setSmallIcon(R.drawable.ic_notification) + .setOngoing(true) + .build() + return if (Build.VERSION.SDK_INT >= 29) { + ForegroundInfo(1, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) + } else { + ForegroundInfo(1, n) + } + } +} diff --git a/app/src/main/res/drawable/bg_button_primary.xml b/app/src/main/res/drawable/bg_button_primary.xml new file mode 100644 index 0000000..c2a22f5 --- /dev/null +++ b/app/src/main/res/drawable/bg_button_primary.xml @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8"?> +<ripple xmlns:android="http://schemas.android.com/apk/res/android" + android:color="#33FFFFFF"> + <item> + <shape android:shape="rectangle"> + <solid android:color="@color/button_primary_bg" /> + <corners android:radius="@dimen/radius" /> + </shape> + </item> +</ripple> diff --git a/app/src/main/res/drawable/bg_button_secondary.xml b/app/src/main/res/drawable/bg_button_secondary.xml new file mode 100644 index 0000000..93c7ccd --- /dev/null +++ b/app/src/main/res/drawable/bg_button_secondary.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?> +<ripple xmlns:android="http://schemas.android.com/apk/res/android" + android:color="@color/surface_variant"> + <item> + <shape android:shape="rectangle"> + <solid android:color="@color/surface" /> + <corners android:radius="@dimen/radius" /> + <stroke + android:width="@dimen/stroke" + android:color="@color/outline" /> + </shape> + </item> +</ripple> diff --git a/app/src/main/res/drawable/bg_card.xml b/app/src/main/res/drawable/bg_card.xml new file mode 100644 index 0000000..0971d54 --- /dev/null +++ b/app/src/main/res/drawable/bg_card.xml @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="utf-8"?> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <solid android:color="@color/surface" /> + <corners android:radius="@dimen/radius" /> + <stroke + android:width="@dimen/stroke" + android:color="@color/outline" /> +</shape> diff --git a/app/src/main/res/drawable/bg_chip.xml b/app/src/main/res/drawable/bg_chip.xml new file mode 100644 index 0000000..aecffef --- /dev/null +++ b/app/src/main/res/drawable/bg_chip.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <solid android:color="@color/surface_variant" /> + <corners android:radius="@dimen/radius_pill" /> +</shape> diff --git a/app/src/main/res/drawable/bg_input.xml b/app/src/main/res/drawable/bg_input.xml new file mode 100644 index 0000000..b87f6b3 --- /dev/null +++ b/app/src/main/res/drawable/bg_input.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<selector xmlns:android="http://schemas.android.com/apk/res/android"> + <item android:state_focused="true"> + <shape android:shape="rectangle"> + <solid android:color="@color/surface" /> + <corners android:radius="@dimen/radius" /> + <stroke + android:width="2dp" + android:color="@color/accent" /> + </shape> + </item> + <item> + <shape android:shape="rectangle"> + <solid android:color="@color/surface" /> + <corners android:radius="@dimen/radius" /> + <stroke + android:width="@dimen/stroke" + android:color="@color/outline" /> + </shape> + </item> +</selector> diff --git a/app/src/main/res/drawable/dot_off.xml b/app/src/main/res/drawable/dot_off.xml new file mode 100644 index 0000000..3115ccc --- /dev/null +++ b/app/src/main/res/drawable/dot_off.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="oval"> + <solid android:color="@android:color/transparent" /> + <stroke + android:width="2dp" + android:color="@color/text_secondary" /> + <size + android:width="10dp" + android:height="10dp" /> +</shape> diff --git a/app/src/main/res/drawable/dot_on.xml b/app/src/main/res/drawable/dot_on.xml new file mode 100644 index 0000000..396b841 --- /dev/null +++ b/app/src/main/res/drawable/dot_on.xml @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="utf-8"?> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="oval"> + <solid android:color="@color/accent" /> + <size + android:width="10dp" + android:height="10dp" /> +</shape> diff --git a/app/src/main/res/drawable/ic_chevron.xml b/app/src/main/res/drawable/ic_chevron.xml new file mode 100644 index 0000000..4c416de --- /dev/null +++ b/app/src/main/res/drawable/ic_chevron.xml @@ -0,0 +1,9 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="@color/text_secondary" + android:pathData="M10,6L8.59,7.41 13.17,12l-4.58,4.59L10,18l6,-6z" /> +</vector> diff --git a/app/src/main/res/drawable/ic_folder.xml b/app/src/main/res/drawable/ic_folder.xml new file mode 100644 index 0000000..b5b85f9 --- /dev/null +++ b/app/src/main/res/drawable/ic_folder.xml @@ -0,0 +1,9 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="@color/text_secondary" + android:pathData="M10,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2h-8l-2,-2z" /> +</vector> diff --git a/app/src/main/res/drawable/ic_key.xml b/app/src/main/res/drawable/ic_key.xml new file mode 100644 index 0000000..1d905df --- /dev/null +++ b/app/src/main/res/drawable/ic_key.xml @@ -0,0 +1,9 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="@color/text_secondary" + android:pathData="M12.65,10C11.83,7.67 9.61,6 7,6c-3.31,0 -6,2.69 -6,6s2.69,6 6,6c2.61,0 4.83,-1.67 5.65,-4H17v4h4v-4h2v-4H12.65zM7,14c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2 -0.9,2 -2,2z" /> +</vector> diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..c468735 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,9 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="108dp" + android:height="108dp" + android:viewportWidth="108" + android:viewportHeight="108"> + <path + android:fillColor="#23252B" + android:pathData="M0,0h108v108h-108z" /> +</vector> diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..ff1dc35 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,14 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="108dp" + android:height="108dp" + android:viewportWidth="108" + android:viewportHeight="108"> + <!-- Checkmark inside the 72dp adaptive-icon safe zone. --> + <path + android:strokeColor="#FFFFFF" + android:strokeWidth="9" + android:strokeLineCap="round" + android:strokeLineJoin="round" + android:fillColor="#00000000" + android:pathData="M38,55 L49,67 L72,40" /> +</vector> diff --git a/app/src/main/res/drawable/ic_notification.xml b/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 0000000..b4309dd --- /dev/null +++ b/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,10 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <!-- White silhouette; the system tints status-bar icons by alpha. --> + <path + android:fillColor="#FFFFFF" + android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z" /> +</vector> diff --git a/app/src/main/res/drawable/ic_remote.xml b/app/src/main/res/drawable/ic_remote.xml new file mode 100644 index 0000000..c81a049 --- /dev/null +++ b/app/src/main/res/drawable/ic_remote.xml @@ -0,0 +1,9 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="@color/text_secondary" + android:pathData="M19,15H5c-1.1,0 -2,0.9 -2,2v2c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2v-2c0,-1.1 -0.9,-2 -2,-2zM7,19c-0.55,0 -1,-0.45 -1,-1s0.45,-1 1,-1 1,0.45 1,1 -0.45,1 -1,1zM19,3H5c-1.1,0 -2,0.9 -2,2v2c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2V5c0,-1.1 -0.9,-2 -2,-2zM7,7C6.45,7 6,6.55 6,6s0.45,-1 1,-1 1,0.45 1,1 -0.45,1 -1,1z" /> +</vector> diff --git a/app/src/main/res/drawable/ic_schedule.xml b/app/src/main/res/drawable/ic_schedule.xml new file mode 100644 index 0000000..e125104 --- /dev/null +++ b/app/src/main/res/drawable/ic_schedule.xml @@ -0,0 +1,12 @@ +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="@color/text_secondary" + android:pathData="M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8z" /> + <path + android:fillColor="@color/text_secondary" + android:pathData="M12.5,7H11v6l5.25,3.15 0.75,-1.23 -4.5,-2.67z" /> +</vector> diff --git a/app/src/main/res/layout/activity_folder.xml b/app/src/main/res/layout/activity_folder.xml new file mode 100644 index 0000000..1a15f00 --- /dev/null +++ b/app/src/main/res/layout/activity_folder.xml @@ -0,0 +1,123 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/appRoot" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + + <include layout="@layout/app_toolbar" /> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:padding="@dimen/space_m"> + + <LinearLayout + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="Name" /> + + <EditText + android:id="@+id/name" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="text" + android:hint="DCIM" /> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="Local path" /> + + <EditText + android:id="@+id/local" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="textUri" + android:hint="/storage/emulated/0/DCIM" /> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="Remote path" /> + + <EditText + android:id="@+id/remote" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="textUri" + android:hint="/backup/phone/DCIM" /> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="Excludes (comma-separated)" /> + + <EditText + android:id="@+id/excludes" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="text" + android:hint=".thumbnails/, .trashed/" /> + + <Switch + android:id="@+id/delete" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Mirror (delete on server when deleted locally)" /> + </LinearLayout> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal"> + + <Button + android:id="@+id/save" + style="@style/Widget.Rsend.Button.Primary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:layout_marginEnd="@dimen/space_s" + android:text="Save" /> + + <Button + android:id="@+id/removeFolder" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:text="Remove" /> + </LinearLayout> + </LinearLayout> + </ScrollView> +</LinearLayout> diff --git a/app/src/main/res/layout/activity_log.xml b/app/src/main/res/layout/activity_log.xml new file mode 100644 index 0000000..af15ec2 --- /dev/null +++ b/app/src/main/res/layout/activity_log.xml @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/appRoot" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + + <include layout="@layout/app_toolbar" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:orientation="vertical" + android:padding="@dimen/space_m"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal" + android:layout_marginBottom="@dimen/space_m"> + + <Button + android:id="@+id/refresh" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:layout_marginEnd="@dimen/space_s" + android:text="Refresh" /> + + <Button + android:id="@+id/clear" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:text="Clear" /> + </LinearLayout> + + <ScrollView + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1"> + + <TextView + android:id="@+id/log" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Mono" + android:textSize="11sp" + android:textIsSelectable="true" /> + </ScrollView> + </LinearLayout> +</LinearLayout> diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..d58f907 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,413 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/appRoot" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + + <include layout="@layout/app_toolbar" /> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:padding="@dimen/space_m"> + + <!-- Status hero --> + <LinearLayout + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal" + android:gravity="center_vertical"> + + <TextView + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:textAppearance="@style/TextAppearance.Rsend.SectionHeader" + android:text="Status" /> + + <TextView + android:id="@+id/appVersion" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <TextView + android:id="@+id/lastSync" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_s" + android:textAppearance="@style/TextAppearance.Rsend.Title" + android:textIsSelectable="true" + android:text="Last sync: never" /> + </LinearLayout> + + <!-- Primary action --> + <Button + android:id="@+id/btnSync" + style="@style/Widget.Rsend.Button.Primary" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="@dimen/space_m" + android:text="Sync now" /> + + <ProgressBar + android:id="@+id/syncBar" + style="?android:attr/progressBarStyleHorizontal" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:indeterminate="true" + android:visibility="gone" /> + + <TextView + android:id="@+id/syncStatus" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:visibility="gone" /> + + <!-- Setup --> + <LinearLayout + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="@dimen/space_s" + android:textAppearance="@style/TextAppearance.Rsend.SectionHeader" + android:text="Setup" /> + + <LinearLayout + android:id="@+id/rowRemote" + style="@style/Widget.Rsend.Row" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <ImageView + android:layout_width="24dp" + android:layout_height="24dp" + android:layout_marginEnd="@dimen/space_m" + android:src="@drawable/ic_remote" + android:contentDescription="@null" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Remote" /> + + <TextView + android:id="@+id/remoteValue" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <ImageView + android:layout_width="20dp" + android:layout_height="20dp" + android:src="@drawable/ic_chevron" + android:contentDescription="@null" /> + </LinearLayout> + + <View + android:layout_width="match_parent" + android:layout_height="@dimen/stroke" + android:layout_marginStart="40dp" + android:background="@color/outline" /> + + <LinearLayout + android:id="@+id/rowKey" + style="@style/Widget.Rsend.Row" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <ImageView + android:layout_width="24dp" + android:layout_height="24dp" + android:layout_marginEnd="@dimen/space_m" + android:src="@drawable/ic_key" + android:contentDescription="@null" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Identity key" /> + + <TextView + android:id="@+id/keyValue" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <ImageView + android:layout_width="20dp" + android:layout_height="20dp" + android:src="@drawable/ic_chevron" + android:contentDescription="@null" /> + </LinearLayout> + + <View + android:layout_width="match_parent" + android:layout_height="@dimen/stroke" + android:layout_marginStart="40dp" + android:background="@color/outline" /> + + <LinearLayout + android:id="@+id/rowSchedule" + style="@style/Widget.Rsend.Row" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <ImageView + android:layout_width="24dp" + android:layout_height="24dp" + android:layout_marginEnd="@dimen/space_m" + android:src="@drawable/ic_schedule" + android:contentDescription="@null" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Schedule" /> + + <TextView + android:id="@+id/scheduleValue" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <ImageView + android:layout_width="20dp" + android:layout_height="20dp" + android:src="@drawable/ic_chevron" + android:contentDescription="@null" /> + </LinearLayout> + </LinearLayout> + + <!-- Permissions --> + <LinearLayout + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="@dimen/space_s" + android:textAppearance="@style/TextAppearance.Rsend.SectionHeader" + android:text="Permissions" /> + + <LinearLayout + android:id="@+id/rowAllFiles" + style="@style/Widget.Rsend.Row" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <View + android:id="@+id/dotAllFiles" + android:layout_width="10dp" + android:layout_height="10dp" + android:layout_marginStart="7dp" + android:layout_marginEnd="@dimen/space_l" + android:background="@drawable/dot_off" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="All-files access" /> + + <TextView + android:id="@+id/valAllFiles" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <ImageView + android:layout_width="20dp" + android:layout_height="20dp" + android:src="@drawable/ic_chevron" + android:contentDescription="@null" /> + </LinearLayout> + + <View + android:layout_width="match_parent" + android:layout_height="@dimen/stroke" + android:layout_marginStart="40dp" + android:background="@color/outline" /> + + <LinearLayout + android:id="@+id/rowNotif" + style="@style/Widget.Rsend.Row" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <View + android:id="@+id/dotNotif" + android:layout_width="10dp" + android:layout_height="10dp" + android:layout_marginStart="7dp" + android:layout_marginEnd="@dimen/space_l" + android:background="@drawable/dot_off" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Notifications" /> + + <TextView + android:id="@+id/valNotif" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <ImageView + android:layout_width="20dp" + android:layout_height="20dp" + android:src="@drawable/ic_chevron" + android:contentDescription="@null" /> + </LinearLayout> + + <View + android:layout_width="match_parent" + android:layout_height="@dimen/stroke" + android:layout_marginStart="40dp" + android:background="@color/outline" /> + + <LinearLayout + android:id="@+id/rowBattery" + style="@style/Widget.Rsend.Row" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <View + android:id="@+id/dotBattery" + android:layout_width="10dp" + android:layout_height="10dp" + android:layout_marginStart="7dp" + android:layout_marginEnd="@dimen/space_l" + android:background="@drawable/dot_off" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Battery" /> + + <TextView + android:id="@+id/valBattery" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <ImageView + android:layout_width="20dp" + android:layout_height="20dp" + android:src="@drawable/ic_chevron" + android:contentDescription="@null" /> + </LinearLayout> + </LinearLayout> + + <!-- Folders --> + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginStart="@dimen/space_s" + android:layout_marginBottom="@dimen/space_s" + android:textAppearance="@style/TextAppearance.Rsend.SectionHeader" + android:text="Folders" /> + + <LinearLayout + android:id="@+id/folders" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal"> + + <Button + android:id="@+id/btnAddFolder" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:layout_marginEnd="@dimen/space_s" + android:text="+ Add folder" /> + + <Button + android:id="@+id/btnLog" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:text="View log" /> + </LinearLayout> + </LinearLayout> + </ScrollView> +</LinearLayout> diff --git a/app/src/main/res/layout/activity_remote.xml b/app/src/main/res/layout/activity_remote.xml new file mode 100644 index 0000000..2c3ba4b --- /dev/null +++ b/app/src/main/res/layout/activity_remote.xml @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/appRoot" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + + <include layout="@layout/app_toolbar" /> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:padding="@dimen/space_m"> + + <LinearLayout + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="Host" /> + + <EditText + android:id="@+id/host" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="textUri" + android:hint="home.example.org" /> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="Port" /> + + <EditText + android:id="@+id/port" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="number" + android:hint="22" /> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="User" /> + + <EditText + android:id="@+id/user" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="text" + android:hint="backup" /> + </LinearLayout> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal"> + + <Button + android:id="@+id/test" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:layout_marginEnd="@dimen/space_s" + android:text="Test connection" /> + + <Button + android:id="@+id/save" + style="@style/Widget.Rsend.Button.Primary" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:text="Save" /> + </LinearLayout> + + <TextView + android:id="@+id/status" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Mono" + android:textIsSelectable="true" /> + </LinearLayout> + </ScrollView> +</LinearLayout> diff --git a/app/src/main/res/layout/activity_schedule.xml b/app/src/main/res/layout/activity_schedule.xml new file mode 100644 index 0000000..981d6a9 --- /dev/null +++ b/app/src/main/res/layout/activity_schedule.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/appRoot" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical"> + + <include layout="@layout/app_toolbar" /> + + <ScrollView + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:padding="@dimen/space_m"> + + <LinearLayout + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <Switch + android:id="@+id/enabled" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Auto-sync on a schedule" /> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Caption" + android:text="Interval (minutes, minimum 1)" /> + + <EditText + android:id="@+id/interval" + style="@style/Widget.Rsend.EditText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:inputType="number" + android:hint="120" /> + + <Switch + android:id="@+id/wifiOnly" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="WiFi only (unmetered networks)" /> + + <Switch + android:id="@+id/charging" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/space_m" + android:textAppearance="@style/TextAppearance.Rsend.Body" + android:text="Only while charging" /> + </LinearLayout> + + <Button + android:id="@+id/save" + style="@style/Widget.Rsend.Button.Primary" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="Save" /> + </LinearLayout> + </ScrollView> +</LinearLayout> diff --git a/app/src/main/res/layout/app_toolbar.xml b/app/src/main/res/layout/app_toolbar.xml new file mode 100644 index 0000000..12eeb47 --- /dev/null +++ b/app/src/main/res/layout/app_toolbar.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Shared title bar. The theme is NoActionBar so each screen hosts its own + Toolbar; the dark overlay gives the title light text on the dark bar. --> +<androidx.appcompat.widget.Toolbar + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/toolbar" + android:layout_width="match_parent" + android:layout_height="?attr/actionBarSize" + android:background="@color/bar" + android:elevation="4dp" + android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" /> diff --git a/app/src/main/res/layout/dialog_key.xml b/app/src/main/res/layout/dialog_key.xml new file mode 100644 index 0000000..c2a0ed6 --- /dev/null +++ b/app/src/main/res/layout/dialog_key.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical" + android:padding="@dimen/space_m"> + + <TextView + android:id="@+id/keyText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="@dimen/space_m" + android:background="@drawable/bg_input" + android:padding="12dp" + android:textAppearance="@style/TextAppearance.Rsend.Mono" + android:textIsSelectable="true" /> + + <Button + android:id="@+id/btnCopyKey" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="@dimen/space_s" + android:text="Copy public key" /> + + <Button + android:id="@+id/btnGenKey" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="@dimen/space_s" + android:text="Generate new key" /> + + <Button + android:id="@+id/btnImportKey" + style="@style/Widget.Rsend.Button.Secondary" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="Import private key" /> +</LinearLayout> diff --git a/app/src/main/res/layout/item_folder.xml b/app/src/main/res/layout/item_folder.xml new file mode 100644 index 0000000..bb5a2bf --- /dev/null +++ b/app/src/main/res/layout/item_folder.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + style="@style/Widget.Rsend.Card" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal" + android:gravity="center_vertical" + android:clickable="true" + android:focusable="true" + android:foreground="?attr/selectableItemBackground"> + + <ImageView + android:layout_width="24dp" + android:layout_height="24dp" + android:layout_marginEnd="@dimen/space_m" + android:src="@drawable/ic_folder" + android:contentDescription="@null" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:id="@+id/folderName" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:maxLines="1" + android:ellipsize="end" + android:textAppearance="@style/TextAppearance.Rsend.Title" /> + + <TextView + android:id="@+id/folderPath" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:maxLines="1" + android:ellipsize="end" + android:textAppearance="@style/TextAppearance.Rsend.Caption" /> + </LinearLayout> + + <TextView + android:id="@+id/folderChip" + style="@style/Widget.Rsend.Chip" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginStart="@dimen/space_s" /> +</LinearLayout> diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..b3e26b4 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> + <background android:drawable="@drawable/ic_launcher_background" /> + <foreground android:drawable="@drawable/ic_launcher_foreground" /> + <monochrome android:drawable="@drawable/ic_launcher_foreground" /> +</adaptive-icon> diff --git a/app/src/main/res/values-night/colors.xml b/app/src/main/res/values-night/colors.xml new file mode 100644 index 0000000..e3d2e06 --- /dev/null +++ b/app/src/main/res/values-night/colors.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <!-- Neutral / monochrome palette, dark mode. --> + <color name="background">#121315</color> + <color name="surface">#1C1D20</color> + <color name="surface_variant">#2A2B2F</color> + <color name="outline">#34363B</color> + <color name="text_primary">#ECECEE</color> + <color name="text_secondary">#A0A2A8</color> + + <color name="accent">#AEB6C7</color> + + <!-- Light fill + near-black text reads well on a dark surface. --> + <color name="button_primary_bg">#E6E7EA</color> + <color name="button_primary_text">#16171A</color> + + <color name="bar">#1C1D20</color> +</resources> diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..bfcdd4e --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <!-- Neutral / monochrome palette. Light mode; values-night overrides. --> + <color name="background">#F4F4F5</color> + <color name="surface">#FFFFFF</color> + <color name="surface_variant">#ECECEE</color> + <color name="outline">#DCDCE0</color> + <color name="text_primary">#17181A</color> + <color name="text_secondary">#6A6C70</color> + + <!-- Single restrained accent: a quiet slate. Drives switches and focus. --> + <color name="accent">#3B4252</color> + + <!-- Primary button flips so it always has contrast against the surface. --> + <color name="button_primary_bg">#23252B</color> + <color name="button_primary_text">#FFFFFF</color> + + <!-- Action bar / status bar. --> + <color name="bar">#23252B</color> +</resources> diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml new file mode 100644 index 0000000..abcba37 --- /dev/null +++ b/app/src/main/res/values/dimens.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <dimen name="space_s">8dp</dimen> + <dimen name="space_m">16dp</dimen> + <dimen name="space_l">24dp</dimen> + + <dimen name="radius">14dp</dimen> + <dimen name="radius_pill">999dp</dimen> + + <dimen name="card_padding">16dp</dimen> + <dimen name="row_min_height">56dp</dimen> + <dimen name="stroke">1dp</dimen> +</resources> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..1f1e4bb --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ +<resources> + <string name="app_name">rsend</string> +</resources> diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..c31d4d8 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,103 @@ +<resources> + + <style name="Theme.Rsend" parent="Theme.AppCompat.DayNight.NoActionBar"> + <item name="colorPrimary">@color/bar</item> + <item name="colorPrimaryDark">@color/bar</item> + <item name="colorAccent">@color/accent</item> + <item name="colorControlActivated">@color/accent</item> + <item name="android:windowBackground">@color/background</item> + <item name="android:colorBackground">@color/background</item> + <item name="android:textColorPrimary">@color/text_primary</item> + <item name="android:textColorSecondary">@color/text_secondary</item> + <item name="android:textColorHint">@color/text_secondary</item> + </style> + + <!-- Text --> + <style name="TextAppearance.Rsend.Title" parent="TextAppearance.AppCompat"> + <item name="android:textColor">@color/text_primary</item> + <item name="android:textSize">17sp</item> + <item name="android:textStyle">bold</item> + </style> + + <style name="TextAppearance.Rsend.SectionHeader" parent="TextAppearance.AppCompat"> + <item name="android:textColor">@color/text_secondary</item> + <item name="android:textSize">12sp</item> + <item name="android:textStyle">bold</item> + <item name="android:textAllCaps">true</item> + <item name="android:letterSpacing">0.08</item> + </style> + + <style name="TextAppearance.Rsend.Body" parent="TextAppearance.AppCompat"> + <item name="android:textColor">@color/text_primary</item> + <item name="android:textSize">15sp</item> + </style> + + <style name="TextAppearance.Rsend.Caption" parent="TextAppearance.AppCompat"> + <item name="android:textColor">@color/text_secondary</item> + <item name="android:textSize">13sp</item> + </style> + + <style name="TextAppearance.Rsend.Mono" parent="TextAppearance.AppCompat"> + <item name="android:textColor">@color/text_primary</item> + <item name="android:fontFamily">monospace</item> + <item name="android:textSize">12sp</item> + </style> + + <!-- Containers --> + <style name="Widget.Rsend.Card" parent=""> + <item name="android:background">@drawable/bg_card</item> + <item name="android:padding">@dimen/card_padding</item> + <item name="android:layout_marginBottom">@dimen/space_m</item> + </style> + + <style name="Widget.Rsend.Row" parent=""> + <item name="android:orientation">horizontal</item> + <item name="android:gravity">center_vertical</item> + <item name="android:minHeight">@dimen/row_min_height</item> + <item name="android:background">?attr/selectableItemBackground</item> + <item name="android:paddingTop">@dimen/space_s</item> + <item name="android:paddingBottom">@dimen/space_s</item> + </style> + + <!-- Buttons --> + <style name="Widget.Rsend.Button.Primary" parent="Widget.AppCompat.Button"> + <item name="android:background">@drawable/bg_button_primary</item> + <item name="android:textColor">@color/button_primary_text</item> + <item name="android:textAllCaps">false</item> + <item name="android:textStyle">bold</item> + <item name="android:textSize">15sp</item> + <item name="android:minHeight">52dp</item> + <item name="android:stateListAnimator">@null</item> + </style> + + <style name="Widget.Rsend.Button.Secondary" parent="Widget.AppCompat.Button"> + <item name="android:background">@drawable/bg_button_secondary</item> + <item name="android:textColor">@color/text_primary</item> + <item name="android:textAllCaps">false</item> + <item name="android:textSize">15sp</item> + <item name="android:minHeight">48dp</item> + <item name="android:stateListAnimator">@null</item> + </style> + + <!-- Inputs --> + <style name="Widget.Rsend.EditText" parent="Widget.AppCompat.EditText"> + <item name="android:background">@drawable/bg_input</item> + <item name="android:textColor">@color/text_primary</item> + <item name="android:textColorHint">@color/text_secondary</item> + <item name="android:padding">12dp</item> + <item name="android:textSize">15sp</item> + </style> + + <!-- Chip (per-folder add/mirror tag) --> + <style name="Widget.Rsend.Chip" parent=""> + <item name="android:background">@drawable/bg_chip</item> + <item name="android:textColor">@color/text_secondary</item> + <item name="android:textSize">11sp</item> + <item name="android:textAllCaps">true</item> + <item name="android:paddingLeft">10dp</item> + <item name="android:paddingRight">10dp</item> + <item name="android:paddingTop">3dp</item> + <item name="android:paddingBottom">3dp</item> + </style> + +</resources> diff --git a/app/src/test/java/invalid/lena/rsend/ConfigTest.kt b/app/src/test/java/invalid/lena/rsend/ConfigTest.kt new file mode 100644 index 0000000..51796ba --- /dev/null +++ b/app/src/test/java/invalid/lena/rsend/ConfigTest.kt @@ -0,0 +1,26 @@ +package invalid.lena.rsend + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Test + +class ConfigTest { + + @Test + fun roundTrip() { + val c = Config( + remote = Remote("home", 2222, "backup"), + schedule = Schedule(enabled = true, intervalMinutes = 30, wifiOnly = false, requireCharging = true), + folders = listOf( + Folder("DCIM", "/storage/emulated/0/DCIM", "/b/DCIM", false, listOf(".thumbnails/")), + Folder("W", "/w", "/b/w", true, emptyList()), + ), + ) + assertEquals(c, Config.fromJson(c.toJson())) + } + + @Test + fun defaultsForEmptyObject() { + assertEquals(Config(), Config.fromJson(JSONObject("{}"))) + } +} diff --git a/app/src/test/java/invalid/lena/rsend/RsyncRunnerTest.kt b/app/src/test/java/invalid/lena/rsend/RsyncRunnerTest.kt new file mode 100644 index 0000000..ef7958f --- /dev/null +++ b/app/src/test/java/invalid/lena/rsend/RsyncRunnerTest.kt @@ -0,0 +1,49 @@ +package invalid.lena.rsend + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RsyncRunnerTest { + + private val remote = Remote("host", 22, "user") + + @Test + fun basicArgs() { + val a = RsyncRunner.args("RSH", remote, Folder(name = "n", local = "/a", remote = "/b")) + assertEquals( + listOf( + "-rt", "--partial", "--timeout=300", "--mkpath", + "--no-perms", "--no-owner", "--no-group", "--omit-dir-times", + "-e", "RSH", "/a/", "user@host:/b/", + ), + a, + ) + } + + @Test + fun mirrorAddsDelete() { + val a = RsyncRunner.args("RSH", remote, Folder(local = "/a", remote = "/b", delete = true)) + assertTrue(a.contains("--delete")) + } + + @Test + fun additiveOmitsDelete() { + val a = RsyncRunner.args("RSH", remote, Folder(local = "/a", remote = "/b", delete = false)) + assertTrue(!a.contains("--delete")) + } + + @Test + fun excludesBecomeFlags() { + val a = RsyncRunner.args("RSH", remote, Folder(local = "/a", remote = "/b", excludes = listOf(".x/", ".y"))) + assertTrue(a.contains("--exclude=.x/")) + assertTrue(a.contains("--exclude=.y")) + } + + @Test + fun trailingSlashIdempotent() { + val a = RsyncRunner.args("RSH", remote, Folder(local = "/a/", remote = "/b/")) + assertTrue(a.contains("/a/")) + assertTrue(a.contains("user@host:/b/")) + } +} diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..96d7c9c --- /dev/null +++ b/build.gradle @@ -0,0 +1,5 @@ +// Plugin versions are pinned here; see also the `versions` file. +plugins { + id 'com.android.application' version '8.7.3' apply false + id 'org.jetbrains.kotlin.android' version '2.0.21' apply false +} diff --git a/ci/build.sh b/ci/build.sh new file mode 100755 index 0000000..5afbfd4 --- /dev/null +++ b/ci/build.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Full build: native executables (rsync + rsh via the NDK), then the APK. +# Requires the pinned toolchain (see versions): Android SDK + NDK, a JDK, Go. +set -eu + +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) + +make -C "$root" native +make -C "$root" app + +echo "ci: APK at app/build/outputs/apk/release/" +ls -l "$root"/app/build/outputs/apk/release/*.apk 2>/dev/null || true diff --git a/ci/release.sh b/ci/release.sh new file mode 100755 index 0000000..cec2b42 --- /dev/null +++ b/ci/release.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Publish a signed release APK to a Codeberg (Forgejo) release. Run on a tag, +# after ci/build.sh has produced a signed app-release.apk (signing happens when +# keystore.properties is present). +# +# Environment: +# CODEBERG_TOKEN Forgejo API token (secret) +# CODEBERG_REPO owner/name, e.g. lena/rsend +# TAG release tag (defaults to CI_COMMIT_TAG) +# CODEBERG_URL base URL (defaults to https://codeberg.org) +set -eu + +: "${CODEBERG_TOKEN:?set CODEBERG_TOKEN}" +: "${CODEBERG_REPO:?set CODEBERG_REPO as owner/name}" +tag=${TAG:-${CI_COMMIT_TAG:?set TAG or CI_COMMIT_TAG}} +base=${CODEBERG_URL:-https://codeberg.org} +apk=app/build/outputs/apk/release/app-release.apk + +[ -f "$apk" ] || { echo "release: $apk not found; run ci/build.sh first" >&2; exit 1; } + +api="$base/api/v1/repos/$CODEBERG_REPO" + +# Create the release for the tag and capture its id. +id=$(curl -fsS -X POST "$api/releases" \ + -H "Authorization: token $CODEBERG_TOKEN" \ + -H "Content-Type: application/json" \ + -d "{\"tag_name\":\"$tag\",\"name\":\"$tag\"}" \ + | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p' | head -1) +[ -n "$id" ] || { echo "release: could not create release for $tag" >&2; exit 1; } + +# Upload the APK as a release asset. +curl -fsS -X POST "$api/releases/$id/assets?name=rsend-$tag.apk" \ + -H "Authorization: token $CODEBERG_TOKEN" \ + -F "attachment=@$apk" >/dev/null + +echo "release: uploaded rsend-$tag.apk to $CODEBERG_REPO ($tag)" diff --git a/ci/setup-toolchain.sh b/ci/setup-toolchain.sh new file mode 100755 index 0000000..c832708 --- /dev/null +++ b/ci/setup-toolchain.sh @@ -0,0 +1,73 @@ +#!/bin/sh +# Provision the pinned Android build toolchain into TOOLCHAIN_DIR (default +# $HOME/toolchains): JDK 17, Android cmdline-tools, SDK platform, build-tools, +# NDK, and Gradle. Idempotent: re-running only fills what is missing. Writes an +# env.sh to source before building. This is what CI runs to get a build host. +set -eu + +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +. "$root/versions" + +dir=${TOOLCHAIN_DIR:-$HOME/toolchains} +sdk="$dir/android-sdk" +mkdir -p "$dir/dl" + +# JDK 17 (Temurin). +if [ ! -x "$dir/jdk17/bin/java" ]; then + echo "setup: JDK $JDK_VERSION" + curl -fsSL "https://api.adoptium.net/v3/binary/latest/${JDK_VERSION}/ga/linux/x64/jdk/hotspot/normal/eclipse" -o "$dir/dl/jdk.tar.gz" + mkdir -p "$dir/jdk17" + tar xzf "$dir/dl/jdk.tar.gz" -C "$dir/jdk17" --strip-components=1 +fi +export JAVA_HOME="$dir/jdk17" +export PATH="$JAVA_HOME/bin:$PATH" + +# Android cmdline-tools. +if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then + echo "setup: cmdline-tools $ANDROID_CMDLINE_TOOLS" + curl -fsSL "https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_CMDLINE_TOOLS}_latest.zip" -o "$dir/dl/clt.zip" + rm -rf "$dir/dl/clt" + python3 -m zipfile -e "$dir/dl/clt.zip" "$dir/dl/clt" + mkdir -p "$sdk/cmdline-tools" + rm -rf "$sdk/cmdline-tools/latest" + mv "$dir/dl/clt/cmdline-tools" "$sdk/cmdline-tools/latest" + chmod +x "$sdk/cmdline-tools/latest/bin/"* +fi + +# SDK packages. +echo "setup: sdk packages" +yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null 2>&1 || true +"$sdk/cmdline-tools/latest/bin/sdkmanager" \ + "platform-tools" \ + "platforms;android-${ANDROID_PLATFORM}" \ + "build-tools;${ANDROID_BUILD_TOOLS}" \ + "ndk;${ANDROID_NDK}" >/dev/null + +# Gradle. +if [ ! -x "$dir/gradle-${GRADLE_VERSION}/bin/gradle" ]; then + echo "setup: Gradle $GRADLE_VERSION" + curl -fsSL "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" -o "$dir/dl/gradle.zip" + python3 -m zipfile -e "$dir/dl/gradle.zip" "$dir" + chmod +x "$dir/gradle-${GRADLE_VERSION}/bin/gradle" +fi + +# Go (pinned; builds rsh). +if [ ! -x "$dir/go/bin/go" ]; then + echo "setup: Go $GO_VERSION" + curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o "$dir/dl/go.tar.gz" + rm -rf "$dir/go" + tar xzf "$dir/dl/go.tar.gz" -C "$dir" +fi + +# Emit the env to source before building. +cat > "$dir/env.sh" <<EOF +export JAVA_HOME="$dir/jdk17" +export GOROOT="$dir/go" +export ANDROID_HOME="$sdk" +export ANDROID_SDK_ROOT="$sdk" +export ANDROID_NDK_HOME="$sdk/ndk/${ANDROID_NDK}" +export GRADLE_HOME="$dir/gradle-${GRADLE_VERSION}" +export PATH="\$JAVA_HOME/bin:$dir/go/bin:\$GRADLE_HOME/bin:$sdk/cmdline-tools/latest/bin:$sdk/platform-tools:\$PATH" +EOF + +echo "setup: done; source $dir/env.sh" diff --git a/ci/test.sh b/ci/test.sh new file mode 100755 index 0000000..8e8a3a4 --- /dev/null +++ b/ci/test.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Host-verifiable checks: pinned source checksum, Go formatting, vet, and tests +# (including the real-rsync-through-rsh end-to-end). Needs Go and rsync; no +# Android toolchain. This is what runs on every push. +set -eu + +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +. "$root/versions" + +if [ -f "$root/rsync/rsync-${RSYNC_VERSION}.tar.gz" ]; then + echo "ci: verifying pinned rsync checksum" + ( cd "$root/rsync" && sha256sum -c "rsync-${RSYNC_VERSION}.tar.gz.sha256" ) +fi + +echo "ci: gofmt" +unformatted=$(gofmt -l "$root/rsh") +if [ -n "$unformatted" ]; then + echo "ci: gofmt needed for:" >&2 + echo "$unformatted" >&2 + exit 1 +fi + +echo "ci: go vet" +( cd "$root/rsh" && go vet ./... ) + +echo "ci: go test" +( cd "$root/rsh" && go test ./... ) + +echo "ci: ok" diff --git a/ci/testsshd/go.mod b/ci/testsshd/go.mod new file mode 100644 index 0000000..88ccdc7 --- /dev/null +++ b/ci/testsshd/go.mod @@ -0,0 +1,7 @@ +module rsend/ci/testsshd + +go 1.25.0 + +require golang.org/x/crypto v0.53.0 + +require golang.org/x/sys v0.46.0 // indirect diff --git a/ci/testsshd/go.sum b/ci/testsshd/go.sum new file mode 100644 index 0000000..68cadc1 --- /dev/null +++ b/ci/testsshd/go.sum @@ -0,0 +1,6 @@ +golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= +golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= diff --git a/ci/testsshd/main.go b/ci/testsshd/main.go new file mode 100644 index 0000000..19a53ac --- /dev/null +++ b/ci/testsshd/main.go @@ -0,0 +1,149 @@ +// testsshd is a minimal SSH server for rsend integration tests: one host key, +// an authorized_keys allowlist, and command execution via /bin/sh (so it runs +// the remote rsync). It is not a product component; it stands in for a real +// sshd so the full push path can be exercised on a device or in CI. +package main + +import ( + "flag" + "io" + "log" + "net" + "os" + "os/exec" + + "golang.org/x/crypto/ssh" +) + +func main() { + addr := flag.String("addr", "127.0.0.1:2222", "listen address") + hostKeyPath := flag.String("hostkey", "", "OpenSSH private host key (required)") + authPath := flag.String("authorized", "", "authorized_keys file (required)") + flag.Parse() + + if *hostKeyPath == "" || *authPath == "" { + log.Fatal("testsshd: -hostkey and -authorized are required") + } + + hostKey := mustSigner(*hostKeyPath) + allowed := mustAuthorized(*authPath) + + cfg := &ssh.ServerConfig{ + PublicKeyCallback: func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + if allowed[string(key.Marshal())] { + return &ssh.Permissions{}, nil + } + return nil, io.EOF + }, + } + cfg.AddHostKey(hostKey) + + ln, err := net.Listen("tcp", *addr) + if err != nil { + log.Fatalf("testsshd: listen: %v", err) + } + log.Printf("testsshd: listening on %s", ln.Addr()) + for { + c, err := ln.Accept() + if err != nil { + log.Fatalf("testsshd: accept: %v", err) + } + go handle(c, cfg) + } +} + +func mustSigner(path string) ssh.Signer { + b, err := os.ReadFile(path) + if err != nil { + log.Fatalf("testsshd: read host key: %v", err) + } + s, err := ssh.ParsePrivateKey(b) + if err != nil { + log.Fatalf("testsshd: parse host key: %v", err) + } + return s +} + +func mustAuthorized(path string) map[string]bool { + b, err := os.ReadFile(path) + if err != nil { + log.Fatalf("testsshd: read authorized_keys: %v", err) + } + m := map[string]bool{} + for len(b) > 0 { + key, _, _, rest, err := ssh.ParseAuthorizedKey(b) + if err != nil { + break + } + m[string(key.Marshal())] = true + b = rest + } + if len(m) == 0 { + log.Fatal("testsshd: no authorized keys") + } + return m +} + +func handle(nConn net.Conn, cfg *ssh.ServerConfig) { + conn, chans, reqs, err := ssh.NewServerConn(nConn, cfg) + if err != nil { + return + } + defer conn.Close() + go ssh.DiscardRequests(reqs) + for nc := range chans { + if nc.ChannelType() != "session" { + nc.Reject(ssh.UnknownChannelType, "only session") + continue + } + ch, requests, err := nc.Accept() + if err != nil { + return + } + go session(ch, requests) + } +} + +func session(ch ssh.Channel, requests <-chan *ssh.Request) { + for req := range requests { + if req.Type != "exec" { + if req.WantReply { + req.Reply(false, nil) + } + continue + } + var payload struct{ Command string } + ssh.Unmarshal(req.Payload, &payload) + if req.WantReply { + req.Reply(true, nil) + } + code := run(payload.Command, ch) + ch.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{uint32(code)})) + ch.Close() + return + } +} + +func run(cmd string, ch ssh.Channel) int { + c := exec.Command("/bin/sh", "-c", cmd) + c.Stdout = ch + c.Stderr = ch.Stderr() + in, err := c.StdinPipe() + if err != nil { + return 1 + } + if err := c.Start(); err != nil { + return 1 + } + go func() { + io.Copy(in, ch) + in.Close() + }() + if err := c.Wait(); err != nil { + if ee, ok := err.(*exec.ExitError); ok { + return ee.ExitCode() + } + return 1 + } + return 0 +} diff --git a/ci/verify-repro.sh b/ci/verify-repro.sh new file mode 100755 index 0000000..d412713 --- /dev/null +++ b/ci/verify-repro.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Build the native libs twice and diff them, catching nondeterminism early. +# Requires the Android NDK and Go. +set -eu + +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +a=$(mktemp -d) +b=$(mktemp -d) +trap 'rm -rf "$a" "$b"' EXIT + +make -C "$root" native +cp -r "$root/app/src/main/jniLibs" "$a/jniLibs" + +rm -rf "$root/app/src/main/jniLibs" "$root/rsync/work" "$root/out" +make -C "$root" native +cp -r "$root/app/src/main/jniLibs" "$b/jniLibs" + +if diff -r "$a/jniLibs" "$b/jniLibs"; then + echo "verify-repro: native libs are bit-identical" +else + echo "verify-repro: NONDETERMINISM detected" >&2 + exit 1 +fi diff --git a/fastlane/metadata/android/en-US/changelogs/1.txt b/fastlane/metadata/android/en-US/changelogs/1.txt new file mode 100644 index 0000000..c0feef1 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/1.txt @@ -0,0 +1,4 @@ +First release. rsync-over-SSH push of phone folders to a home host, with +rsync and the SSH transport built from source and bundled in the APK. One-way +push, WiFi-only by default, periodic or manual, ed25519 key auth with pinned +host-key verification. diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt new file mode 100644 index 0000000..0806b2b --- /dev/null +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -0,0 +1,14 @@ +Pushes configured phone folders (DCIM, WhatsApp media, call recordings, and +so on) to a home SSH host using rsync over SSH. One-way push only, on WiFi +by default, periodic or on demand. + +rsync and the SSH transport are built from source and shipped inside the +APK; nothing prebuilt is bundled. The app needs all-files access to read +arbitrary backup folders such as OEM call-recording directories. + +Features: + +* Incremental transfers; large videos resume (rsync --partial). +* Per-folder deletion policy: additive backup or mirror. +* Runs on unmetered WiFi, periodically or on demand. +* ed25519 key auth with strict, pinned host-key verification. diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png Binary files differnew file mode 100644 index 0000000..8a42552 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png Binary files differnew file mode 100644 index 0000000..a882b86 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.png diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png Binary files differnew file mode 100644 index 0000000..d9aafd8 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.png diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png Binary files differnew file mode 100644 index 0000000..d77c244 --- /dev/null +++ b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.png diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt new file mode 100644 index 0000000..b18f43a --- /dev/null +++ b/fastlane/metadata/android/en-US/short_description.txt @@ -0,0 +1 @@ +Push phone folders to a home SSH host with rsync over SSH diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt new file mode 100644 index 0000000..e0645d9 --- /dev/null +++ b/fastlane/metadata/android/en-US/title.txt @@ -0,0 +1 @@ +rsend diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..f389bf5 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx2048m +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..09523c0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/metadata/reproducible-builds.md b/metadata/reproducible-builds.md new file mode 100644 index 0000000..9830957 --- /dev/null +++ b/metadata/reproducible-builds.md @@ -0,0 +1,46 @@ +rsend reproducible builds +========================= +How rsend stays reproducible and what F-Droid needs to build it. + + +Pinning +------- +Every tool and source version lives in ./versions: the rsync source and its +sha256, the Go version, the Android NDK, SDK platform, build-tools, Gradle, the +Android Gradle Plugin, and Kotlin. The build never floats a version. + + +Determinism +----------- +- rsh (Go): built with the NDK clang, -trimpath, -ldflags "-s -w -buildid=", + and CGO_CFLAGS=-ffile-prefix-map to drop build paths. +- rsync (C): cross-compiled with -ffile-prefix-map and stripped; optional + dependencies are disabled and zlib and popt come from rsync's bundled copies, + so the binary needs nothing outside Bionic. +- APK: no code shrinking (minifyEnabled false), the Google dependency-metadata + block is dropped (dependenciesInfo off), and native libs use legacy packaging. + +Verify locally by building twice and diffing the native libs: + + make verify-repro + + +F-Droid +------- +The build recipe lives in fdroiddata, not in this repo. F-Droid supplies the +NDK named by the recipe's ndk field and exports ANDROID_NDK_HOME. It pins Go +through the go srclib (the official Go source) and builds it with make.bash, +and installs make and g++ for rsync. The native lib*.so are then built in the +recipe's build step, which runs after F-Droid's source scanner and calls +rsync/build.sh and rsh/build.sh; Gradle then assembles the APK. The release +build is unsigned unless a local keystore.properties is present, so F-Droid +signs the published APK with its own key. + + +All-files access +---------------- +rsend requests MANAGE_EXTERNAL_STORAGE. It is required: backup targets such as +OEM call-recording directories and app-specific media folders live outside the +scoped-media buckets, and rsync needs real filesystem paths rather than SAF +content URIs. The app makes no network access other than the SSH connection to +the host the user configures. diff --git a/rsh/build.sh b/rsh/build.sh new file mode 100755 index 0000000..88cdf9c --- /dev/null +++ b/rsh/build.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# Build the rsh SSH transport for each Android ABI as a Bionic PIE executable +# named lib*.so (packaged inside the APK and exec'd from nativeLibraryDir), +# using the Android NDK. Also build a plain host binary for tests and manual +# debugging. +# +# Android needs PIE and the Bionic dynamic linker (/system/bin/linker64), so +# the on-device build is GOOS=android with cgo and the NDK clang. A GOOS=linux +# build targets glibc's linker and will not exec on a phone. +set -eu + +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +. "$root/versions" + +# Locate the NDK toolchain. +ndk=${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}} +if [ -z "$ndk" ] && [ -n "${ANDROID_HOME:-}" ]; then + ndk="$ANDROID_HOME/ndk/$ANDROID_NDK" +fi +if [ -z "$ndk" ] || [ ! -d "$ndk" ]; then + echo "rsh: Android NDK not found; set ANDROID_NDK_HOME" >&2 + exit 1 +fi +tc="$ndk/toolchains/llvm/prebuilt/linux-x86_64/bin" + +ldflags="-s -w -buildid=" + +cd "$root/rsh" + +for abi in $ABIS; do + case "$abi" in + arm64-v8a) goarch=arm64 goarm= cc="aarch64-linux-android${ANDROID_MIN_SDK}-clang" ;; + armeabi-v7a) goarch=arm goarm=7 cc="armv7a-linux-androideabi${ANDROID_MIN_SDK}-clang" ;; + x86_64) goarch=amd64 goarm= cc="x86_64-linux-android${ANDROID_MIN_SDK}-clang" ;; + x86) goarch=386 goarm= cc="i686-linux-android${ANDROID_MIN_SDK}-clang" ;; + *) echo "rsh: unknown ABI $abi" >&2; exit 1 ;; + esac + dest="$root/app/src/main/jniLibs/$abi" + mkdir -p "$dest" + echo "rsh: building $abi (android/$goarch)" + CGO_ENABLED=1 GOOS=android GOARCH="$goarch" GOARM="$goarm" \ + CC="$tc/$cc" GOFLAGS=-trimpath CGO_CFLAGS="-ffile-prefix-map=$root=." \ + go build -buildmode=pie -ldflags "$ldflags" -o "$dest/libxrsh.so" . +done + +# Host binary (no NDK, cgo off) for tests and manual debugging. +mkdir -p "$root/out" +echo "rsh: building host binary -> out/rsh" +CGO_ENABLED=0 GOFLAGS=-trimpath go build -ldflags "$ldflags" -o "$root/out/rsh" . diff --git a/rsh/e2e_test.go b/rsh/e2e_test.go new file mode 100644 index 0000000..1fa80c7 --- /dev/null +++ b/rsh/e2e_test.go @@ -0,0 +1,84 @@ +package main + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strconv" + "testing" +) + +// TestEndToEndRealRsync drives the actual rsync binary through the actual rsh +// transport binary into the in-process SSH server, which runs the remote rsync +// via /bin/sh. It proves real rsync + the Go transport move files intact. +func TestEndToEndRealRsync(t *testing.T) { + if testing.Short() { + t.Skip("short mode") + } + rsyncBin, err := exec.LookPath("rsync") + if err != nil { + t.Skip("rsync not installed") + } + + // Build the rsh binary so rsync can exec it as its remote shell. + rshBin := filepath.Join(t.TempDir(), "rsh") + if out, err := exec.Command("go", "build", "-o", rshBin, ".").CombinedOutput(); err != nil { + t.Fatalf("build rsh: %v\n%s", err, out) + } + + keyPath, pub := genClientKey(t) + srv := newTestServer(t, pub, shellExec) + kh := writeKnownHosts(t, "127.0.0.1", srv.port(), srv.hostKey.PublicKey()) + + src := t.TempDir() + dst := t.TempDir() + mustWrite(t, filepath.Join(src, "a.txt"), "alpha") + mustWrite(t, filepath.Join(src, "sub", "b.bin"), "\x00\x01\x02\x03beta") + mustWrite(t, filepath.Join(src, "sub", "c.txt"), "gamma gamma gamma") + + cmd := exec.Command(rsyncBin, "-a", "-e", rshBin, src+"/", "u@127.0.0.1:"+dst+"/") + cmd.Env = append(os.Environ(), + "RSH_KEY="+keyPath, + "RSH_KNOWN_HOSTS="+kh, + "RSH_PORT="+strconv.Itoa(srv.port()), + ) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("rsync: %v\n%s", err, out) + } + + checkSame(t, src, dst) +} + +func mustWrite(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func checkSame(t *testing.T, src, dst string) { + t.Helper() + err := filepath.Walk(src, func(p string, info os.FileInfo, err error) error { + if err != nil || info.IsDir() { + return err + } + rel, _ := filepath.Rel(src, p) + want, _ := os.ReadFile(p) + got, err := os.ReadFile(filepath.Join(dst, rel)) + if err != nil { + t.Errorf("missing on dest: %s (%v)", rel, err) + return nil + } + if !bytes.Equal(got, want) { + t.Errorf("content mismatch for %s", rel) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/rsh/go.mod b/rsh/go.mod new file mode 100644 index 0000000..661c774 --- /dev/null +++ b/rsh/go.mod @@ -0,0 +1,7 @@ +module rsend/rsh + +go 1.25.0 + +require golang.org/x/crypto v0.53.0 + +require golang.org/x/sys v0.46.0 // indirect diff --git a/rsh/go.sum b/rsh/go.sum new file mode 100644 index 0000000..68cadc1 --- /dev/null +++ b/rsh/go.sum @@ -0,0 +1,6 @@ +golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= +golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= diff --git a/rsh/main.go b/rsh/main.go new file mode 100644 index 0000000..31029cb --- /dev/null +++ b/rsh/main.go @@ -0,0 +1,273 @@ +// rsh is rsend's SSH transport. It is invoked three ways: +// +// rsh [-l USER] [USER@]HOST CMD... rsync remote shell (rsync -e), strict +// rsh -keygen DIR generate an ed25519 key, print the pubkey +// rsh -pubkey print the pubkey for RSH_KEY_DATA/RSH_KEY +// rsh -scan USER@HOST connect, print host-key fingerprint + line +// +// Transport mode mirrors what ssh does for rsync: it dials the host, runs the +// remote command, and bridges stdin/stdout/stderr. Host keys are verified +// strictly against RSH_KNOWN_HOSTS; an unknown or changed key fails loud. +// Key, known_hosts path, and port come from the environment because rsync owns +// the argument vector: +// +// RSH_KEY path to the ed25519 private key +// RSH_KEY_DATA the private key itself (PEM), preferred over RSH_KEY so the +// app need never write the plaintext key to disk +// RSH_KNOWN_HOSTS path to the known_hosts file (required in transport mode) +// RSH_PORT TCP port (optional, default 22) +// +// Pure Go, no cgo. +package main + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" +) + +const dialTimeout = 30 * time.Second + +func main() { + if err := run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr); err != nil { + var ee *ssh.ExitError + if errors.As(err, &ee) { + os.Exit(ee.ExitStatus()) + } + fmt.Fprintf(os.Stderr, "rsh: %v\n", err) + os.Exit(1) + } +} + +func run(args []string, in io.Reader, out, errw io.Writer) error { + if len(args) >= 1 { + switch args[0] { + case "-keygen": + if len(args) != 2 { + return errors.New("usage: rsh -keygen DIR") + } + return keygen(args[1], out) + case "-pubkey": + if len(args) != 1 { + return errors.New("usage: rsh -pubkey") + } + return pubkey(out) + case "-scan": + if len(args) != 2 { + return errors.New("usage: rsh -scan USER@HOST") + } + return scan(args[1], out) + } + } + return transport(args, in, out, errw) +} + +// transport runs the remote command and bridges I/O, verifying the host key +// strictly against RSH_KNOWN_HOSTS. +func transport(args []string, in io.Reader, out, errw io.Writer) error { + user, host, cmd, err := parseTransport(args) + if err != nil { + return err + } + if user == "" { + return errors.New("no remote user (expected -l USER or USER@HOST)") + } + if len(cmd) == 0 { + return errors.New("no remote command") + } + kh := os.Getenv("RSH_KNOWN_HOSTS") + if kh == "" { + return errors.New("RSH_KNOWN_HOSTS not set") + } + cb, err := knownhosts.New(kh) + if err != nil { + return fmt.Errorf("known_hosts: %w (run Test connection first)", err) + } + client, err := dial(user, host, cb) + if err != nil { + return err + } + defer client.Close() + go keepAlive(client) + + session, err := client.NewSession() + if err != nil { + return err + } + defer session.Close() + session.Stdin = in + session.Stdout = out + session.Stderr = errw + return session.Run(strings.Join(cmd, " ")) +} + +// scan connects (authenticating, so it also proves the key is installed), +// captures the presented host key, and prints its SHA256 fingerprint and a +// known_hosts line for the caller to pin. +func scan(target string, out io.Writer) error { + user, host := splitUserHost(target) + if user == "" { + return errors.New("scan target must be USER@HOST") + } + var hostKey ssh.PublicKey + capture := func(_ string, _ net.Addr, key ssh.PublicKey) error { + hostKey = key + return nil + } + client, err := dial(user, host, capture) + if err != nil { + return err + } + client.Close() + + addr := knownhosts.Normalize(net.JoinHostPort(host, strconv.Itoa(sshPort()))) + line := knownhosts.Line([]string{addr}, hostKey) + fmt.Fprintf(out, "%s\n%s\n", ssh.FingerprintSHA256(hostKey), line) + return nil +} + +// keygen writes an ed25519 key pair into dir and prints the public key in +// authorized_keys format to out. +func keygen(dir string, out io.Writer) error { + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return err + } + block, err := ssh.MarshalPrivateKey(priv, "rsend") + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(dir, "id_ed25519"), pem.EncodeToMemory(block), 0o600); err != nil { + return err + } + sshPub, err := ssh.NewPublicKey(pub) + if err != nil { + return err + } + authLine := ssh.MarshalAuthorizedKey(sshPub) + if err := os.WriteFile(filepath.Join(dir, "id_ed25519.pub"), authLine, 0o644); err != nil { + return err + } + _, err = out.Write(authLine) + return err +} + +// pubkey loads the private key (RSH_KEY_DATA or RSH_KEY) and prints its public +// key in authorized_keys format. The app uses it to validate and display a key +// the user imported: if loadSigner accepts it here, the transport will too. +func pubkey(out io.Writer) error { + signer, err := loadSigner() + if err != nil { + return err + } + _, err = out.Write(ssh.MarshalAuthorizedKey(signer.PublicKey())) + return err +} + +// loadSigner reads the private key from RSH_KEY_DATA (the key itself) or, if +// that is unset, the file named by RSH_KEY. +func loadSigner() (ssh.Signer, error) { + if data := os.Getenv("RSH_KEY_DATA"); data != "" { + return ssh.ParsePrivateKey([]byte(data)) + } + keyPath := os.Getenv("RSH_KEY") + if keyPath == "" { + return nil, errors.New("RSH_KEY or RSH_KEY_DATA not set") + } + pemBytes, err := os.ReadFile(keyPath) + if err != nil { + return nil, fmt.Errorf("read key: %w", err) + } + return ssh.ParsePrivateKey(pemBytes) +} + +// dial opens an SSH connection authenticated with the configured key, verifying +// the host key with hostKey. +func dial(user, host string, hostKey ssh.HostKeyCallback) (*ssh.Client, error) { + signer, err := loadSigner() + if err != nil { + return nil, err + } + cfg := &ssh.ClientConfig{ + User: user, + Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, + HostKeyCallback: hostKey, + Timeout: dialTimeout, + } + addr := net.JoinHostPort(host, strconv.Itoa(sshPort())) + return ssh.Dial("tcp", addr, cfg) +} + +// parseTransport extracts the user, host, and remote command from the argument +// vector rsync hands to its remote shell: an optional "-l USER", the host +// (possibly USER@HOST), then the remote command. +func parseTransport(args []string) (user, host string, cmd []string, err error) { + i := 0 + for i < len(args) { + a := args[i] + if a == "-l" { + if i+1 >= len(args) { + return "", "", nil, errors.New("-l requires an argument") + } + user = args[i+1] + i += 2 + continue + } + if strings.HasPrefix(a, "-") { + return "", "", nil, fmt.Errorf("unexpected option %q", a) + } + break + } + if i >= len(args) { + return "", "", nil, errors.New("missing host") + } + host = args[i] + cmd = args[i+1:] + if u, h := splitUserHost(host); u != "" { + host = h + if user == "" { + user = u + } + } + return user, host, cmd, nil +} + +func splitUserHost(s string) (user, host string) { + if i := strings.Index(s, "@"); i >= 0 { + return s[:i], s[i+1:] + } + return "", s +} + +func sshPort() int { + if s := os.Getenv("RSH_PORT"); s != "" { + if p, err := strconv.Atoi(s); err == nil && p > 0 { + return p + } + } + return 22 +} + +// keepAlive pings the server so a long transfer is not dropped by an idle NAT. +// It returns once the connection is closed. +func keepAlive(client *ssh.Client) { + t := time.NewTicker(60 * time.Second) + defer t.Stop() + for range t.C { + if _, _, err := client.SendRequest("keepalive@openssh.com", true, nil); err != nil { + return + } + } +} diff --git a/rsh/sshserver_test.go b/rsh/sshserver_test.go new file mode 100644 index 0000000..087bff4 --- /dev/null +++ b/rsh/sshserver_test.go @@ -0,0 +1,141 @@ +package main + +import ( + "crypto/ed25519" + "crypto/rand" + "errors" + "fmt" + "io" + "net" + "os/exec" + "testing" + + "golang.org/x/crypto/ssh" +) + +// execHandler runs the remote command for one session and returns its exit +// code. +type execHandler func(cmd string, stdin io.Reader, stdout, stderr io.Writer) int + +// testServer is a minimal in-process SSH server for tests: one host key, one +// accepted client public key, and a pluggable exec handler. No sshd needed. +type testServer struct { + ln net.Listener + hostKey ssh.Signer + authPub ssh.PublicKey + handle execHandler +} + +func newTestServer(t *testing.T, clientPub ssh.PublicKey, handle execHandler) *testServer { + t.Helper() + _, hpriv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + signer, err := ssh.NewSignerFromKey(hpriv) + if err != nil { + t.Fatal(err) + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s := &testServer{ln: ln, hostKey: signer, authPub: clientPub, handle: handle} + go s.serve() + t.Cleanup(func() { ln.Close() }) + return s +} + +func (s *testServer) port() int { return s.ln.Addr().(*net.TCPAddr).Port } + +func (s *testServer) serve() { + cfg := &ssh.ServerConfig{ + PublicKeyCallback: func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + if s.authPub != nil && string(key.Marshal()) == string(s.authPub.Marshal()) { + return &ssh.Permissions{}, nil + } + return nil, fmt.Errorf("unknown public key") + }, + } + cfg.AddHostKey(s.hostKey) + for { + nConn, err := s.ln.Accept() + if err != nil { + return + } + go s.handleConn(nConn, cfg) + } +} + +func (s *testServer) handleConn(nConn net.Conn, cfg *ssh.ServerConfig) { + conn, chans, reqs, err := ssh.NewServerConn(nConn, cfg) + if err != nil { + return + } + defer conn.Close() + go ssh.DiscardRequests(reqs) + for newCh := range chans { + if newCh.ChannelType() != "session" { + newCh.Reject(ssh.UnknownChannelType, "only session") + continue + } + ch, requests, err := newCh.Accept() + if err != nil { + return + } + go s.handleSession(ch, requests) + } +} + +func (s *testServer) handleSession(ch ssh.Channel, requests <-chan *ssh.Request) { + for req := range requests { + if req.Type != "exec" { + if req.WantReply { + req.Reply(false, nil) + } + continue + } + var payload struct{ Command string } + ssh.Unmarshal(req.Payload, &payload) + if req.WantReply { + req.Reply(true, nil) + } + code := s.handle(payload.Command, ch, ch, ch.Stderr()) + ch.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{uint32(code)})) + ch.Close() + return + } +} + +// shellExec runs cmd via /bin/sh -c, exactly as sshd would, wiring the channel +// to the process. Used by the real-rsync end-to-end test. +// +// stdin is fed through a detached goroutine rather than c.Stdin so that Wait +// does not block on the stdin copy: rsync's remote receiver exits while the +// client still holds the channel open, and a c.Run with a non-file Stdin would +// deadlock waiting for that copy to finish. +func shellExec(cmd string, stdin io.Reader, stdout, stderr io.Writer) int { + c := exec.Command("/bin/sh", "-c", cmd) + c.Stdout = stdout + c.Stderr = stderr + inPipe, err := c.StdinPipe() + if err != nil { + return 1 + } + if err := c.Start(); err != nil { + return 1 + } + go func() { + io.Copy(inPipe, stdin) + inPipe.Close() + }() + err = c.Wait() + var ee *exec.ExitError + if errors.As(err, &ee) { + return ee.ExitCode() + } + if err != nil { + return 1 + } + return 0 +} diff --git a/rsh/transport_test.go b/rsh/transport_test.go new file mode 100644 index 0000000..562c4d2 --- /dev/null +++ b/rsh/transport_test.go @@ -0,0 +1,224 @@ +package main + +import ( + "bytes" + "errors" + "io" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" +) + +// genClientKey makes a client key via keygen and returns the private key path +// and the parsed public key. +func genClientKey(t *testing.T) (keyPath string, pub ssh.PublicKey) { + t.Helper() + dir := t.TempDir() + if err := keygen(dir, io.Discard); err != nil { + t.Fatal(err) + } + keyPath = filepath.Join(dir, "id_ed25519") + pb, err := os.ReadFile(filepath.Join(dir, "id_ed25519.pub")) + if err != nil { + t.Fatal(err) + } + pub, _, _, _, err = ssh.ParseAuthorizedKey(pb) + if err != nil { + t.Fatal(err) + } + return keyPath, pub +} + +func writeKnownHosts(t *testing.T, host string, port int, hostKey ssh.PublicKey) string { + t.Helper() + addr := knownhosts.Normalize(net.JoinHostPort(host, strconv.Itoa(port))) + line := knownhosts.Line([]string{addr}, hostKey) + p := filepath.Join(t.TempDir(), "known_hosts") + if err := os.WriteFile(p, []byte(line+"\n"), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +func setEnv(t *testing.T, key, kh string, port int) { + t.Setenv("RSH_KEY", key) + t.Setenv("RSH_KNOWN_HOSTS", kh) + t.Setenv("RSH_PORT", strconv.Itoa(port)) +} + +func TestTransportBridgesStdio(t *testing.T) { + keyPath, pub := genClientKey(t) + echo := func(_ string, stdin io.Reader, stdout, _ io.Writer) int { + io.Copy(stdout, stdin) + return 0 + } + srv := newTestServer(t, pub, echo) + kh := writeKnownHosts(t, "127.0.0.1", srv.port(), srv.hostKey.PublicKey()) + setEnv(t, keyPath, kh, srv.port()) + + want := []byte("the quick brown fox\x00\x01\x02 binary tail") + var out bytes.Buffer + if err := transport([]string{"-l", "u", "127.0.0.1", "cat"}, bytes.NewReader(want), &out, io.Discard); err != nil { + t.Fatalf("transport: %v", err) + } + if !bytes.Equal(out.Bytes(), want) { + t.Fatalf("bridged data mismatch:\n got %q\nwant %q", out.Bytes(), want) + } +} + +func TestTransportKeyFromData(t *testing.T) { + keyPath, pub := genClientKey(t) + echo := func(_ string, stdin io.Reader, stdout, _ io.Writer) int { + io.Copy(stdout, stdin) + return 0 + } + srv := newTestServer(t, pub, echo) + kh := writeKnownHosts(t, "127.0.0.1", srv.port(), srv.hostKey.PublicKey()) + keyData, err := os.ReadFile(keyPath) + if err != nil { + t.Fatal(err) + } + // RSH_KEY points nowhere; RSH_KEY_DATA must take precedence and work. + t.Setenv("RSH_KEY", "/does/not/exist") + t.Setenv("RSH_KEY_DATA", string(keyData)) + t.Setenv("RSH_KNOWN_HOSTS", kh) + t.Setenv("RSH_PORT", strconv.Itoa(srv.port())) + + want := []byte("via key data") + var out bytes.Buffer + if err := transport([]string{"-l", "u", "127.0.0.1", "cat"}, bytes.NewReader(want), &out, io.Discard); err != nil { + t.Fatalf("transport: %v", err) + } + if !bytes.Equal(out.Bytes(), want) { + t.Fatalf("bridged data mismatch: %q", out.Bytes()) + } +} + +func TestTransportRejectsUnknownHostKey(t *testing.T) { + keyPath, pub := genClientKey(t) + srv := newTestServer(t, pub, func(_ string, _ io.Reader, _, _ io.Writer) int { return 0 }) + + // Pin a DIFFERENT key, so the server's real host key must be rejected. + _, wrong := genClientKey(t) + kh := writeKnownHosts(t, "127.0.0.1", srv.port(), wrong) + setEnv(t, keyPath, kh, srv.port()) + + if err := transport([]string{"-l", "u", "127.0.0.1", "true"}, bytes.NewReader(nil), io.Discard, io.Discard); err == nil { + t.Fatal("expected host-key mismatch error, got nil") + } +} + +func TestTransportPropagatesExitCode(t *testing.T) { + keyPath, pub := genClientKey(t) + srv := newTestServer(t, pub, func(_ string, _ io.Reader, _, _ io.Writer) int { return 7 }) + kh := writeKnownHosts(t, "127.0.0.1", srv.port(), srv.hostKey.PublicKey()) + setEnv(t, keyPath, kh, srv.port()) + + err := transport([]string{"-l", "u", "127.0.0.1", "false"}, bytes.NewReader(nil), io.Discard, io.Discard) + var ee *ssh.ExitError + if !errors.As(err, &ee) || ee.ExitStatus() != 7 { + t.Fatalf("expected exit status 7, got %v", err) + } +} + +func TestPubkeyMatchesKeygen(t *testing.T) { + keyPath, pub := genClientKey(t) + keyData, err := os.ReadFile(keyPath) + if err != nil { + t.Fatal(err) + } + t.Setenv("RSH_KEY", "") + t.Setenv("RSH_KEY_DATA", string(keyData)) + + var out bytes.Buffer + if err := pubkey(&out); err != nil { + t.Fatalf("pubkey: %v", err) + } + got, _, _, _, err := ssh.ParseAuthorizedKey(out.Bytes()) + if err != nil { + t.Fatalf("parse pubkey output: %v", err) + } + if !bytes.Equal(got.Marshal(), pub.Marshal()) { + t.Fatal("pubkey output does not match the keygen public key") + } +} + +func TestPubkeyRejectsMissingKey(t *testing.T) { + t.Setenv("RSH_KEY", "") + t.Setenv("RSH_KEY_DATA", "") + if err := pubkey(io.Discard); err == nil { + t.Fatal("expected error when no key is configured") + } +} + +func TestScanPrintsFingerprintAndLine(t *testing.T) { + keyPath, pub := genClientKey(t) + srv := newTestServer(t, pub, func(_ string, _ io.Reader, _, _ io.Writer) int { return 0 }) + t.Setenv("RSH_KEY", keyPath) + t.Setenv("RSH_PORT", strconv.Itoa(srv.port())) + + var out bytes.Buffer + if err := scan("u@127.0.0.1", &out); err != nil { + t.Fatalf("scan: %v", err) + } + lines := strings.SplitN(strings.TrimSpace(out.String()), "\n", 2) + if len(lines) != 2 { + t.Fatalf("want fingerprint + known_hosts line, got %q", out.String()) + } + if !strings.HasPrefix(lines[0], "SHA256:") { + t.Errorf("fingerprint: %q", lines[0]) + } + // The printed known_hosts line must validate the real host key. + khPath := filepath.Join(t.TempDir(), "kh") + if err := os.WriteFile(khPath, []byte(lines[1]+"\n"), 0o600); err != nil { + t.Fatal(err) + } + cb, err := knownhosts.New(khPath) + if err != nil { + t.Fatal(err) + } + addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(srv.port())) + remote := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: srv.port()} + if err := cb(addr, remote, srv.hostKey.PublicKey()); err != nil { + t.Errorf("pinned line did not validate the host key: %v", err) + } +} + +func TestParseTransport(t *testing.T) { + cases := []struct { + args []string + user, host string + cmd string + wantErr bool + }{ + {[]string{"-l", "alice", "host", "rsync", "--server"}, "alice", "host", "rsync --server", false}, + {[]string{"bob@host", "echo", "hi"}, "bob", "host", "echo hi", false}, + {[]string{"-l", "alice", "carol@host", "x"}, "alice", "host", "x", false}, + {[]string{"host"}, "", "host", "", false}, + {[]string{"-l"}, "", "", "", true}, + {[]string{"-p", "22", "host", "x"}, "", "", "", true}, + } + for _, c := range cases { + u, h, cmd, err := parseTransport(c.args) + if c.wantErr { + if err == nil { + t.Errorf("%v: expected error", c.args) + } + continue + } + if err != nil { + t.Errorf("%v: %v", c.args, err) + continue + } + if u != c.user || h != c.host || strings.Join(cmd, " ") != c.cmd { + t.Errorf("%v: got (%q,%q,%q) want (%q,%q,%q)", + c.args, u, h, strings.Join(cmd, " "), c.user, c.host, c.cmd) + } + } +} diff --git a/rsync/build.sh b/rsync/build.sh new file mode 100755 index 0000000..1160e74 --- /dev/null +++ b/rsync/build.sh @@ -0,0 +1,67 @@ +#!/bin/sh +# Build rsync for each Android ABI from pinned source via the NDK. Output is a +# stripped PIE executable named lib*.so, packaged inside the APK and exec'd from +# nativeLibraryDir. Optional dependencies are disabled so the binary needs +# nothing outside Bionic; zlib and popt come from rsync's bundled copies. +set -eu + +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +. "$root/versions" + +# Locate the NDK toolchain. +ndk=${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}} +if [ -z "$ndk" ] && [ -n "${ANDROID_HOME:-}" ]; then + ndk="$ANDROID_HOME/ndk/$ANDROID_NDK" +fi +if [ -z "$ndk" ] || [ ! -d "$ndk" ]; then + echo "rsync: Android NDK not found; set ANDROID_NDK_HOME" >&2 + exit 1 +fi +tc="$ndk/toolchains/llvm/prebuilt/linux-x86_64/bin" + +work="$root/rsync/work" +tarball="$root/rsync/rsync-${RSYNC_VERSION}.tar.gz" +src="$work/rsync-${RSYNC_VERSION}" + +# Fetch and verify the pinned source tarball. +mkdir -p "$work" +if [ ! -f "$tarball" ]; then + echo "rsync: fetching $RSYNC_URL" + curl -fsSL "$RSYNC_URL" -o "$tarball" +fi +echo "rsync: verifying sha256" +( cd "$root/rsync" && sha256sum -c "rsync-${RSYNC_VERSION}.tar.gz.sha256" ) + +# No system libraries, no docs (md2man needs python3), no iconv. +flags="--disable-md2man --disable-openssl --disable-xxhash --disable-zstd \ +--disable-lz4 --disable-iconv --disable-acl-support --disable-xattr-support \ +--with-included-popt --with-included-zlib" + +for abi in $ABIS; do + case "$abi" in + arm64-v8a) host=aarch64-linux-android cc="aarch64-linux-android${ANDROID_MIN_SDK}-clang" ;; + armeabi-v7a) host=arm-linux-androideabi cc="armv7a-linux-androideabi${ANDROID_MIN_SDK}-clang" ;; + x86_64) host=x86_64-linux-android cc="x86_64-linux-android${ANDROID_MIN_SDK}-clang" ;; + x86) host=i686-linux-android cc="i686-linux-android${ANDROID_MIN_SDK}-clang" ;; + *) echo "rsync: unknown ABI $abi" >&2; exit 1 ;; + esac + + # Fresh build tree per ABI. + rm -rf "$src" + tar xzf "$tarball" -C "$work" + + echo "rsync: configuring $abi" + ( cd "$src" && \ + CC="$tc/$cc" AR="$tc/llvm-ar" RANLIB="$tc/llvm-ranlib" \ + CFLAGS="-O2 -fPIE -ffile-prefix-map=$src=." LDFLAGS="-pie" \ + ./configure --host="$host" $flags >/dev/null ) + + echo "rsync: building $abi" + ( cd "$src" && make -s rsync ) + + dest="$root/app/src/main/jniLibs/$abi" + mkdir -p "$dest" + cp "$src/rsync" "$dest/libxrsync.so" + "$tc/llvm-strip" "$dest/libxrsync.so" + echo "rsync: $abi -> jniLibs/$abi/libxrsync.so" +done diff --git a/rsync/rsync-3.4.1.tar.gz.sha256 b/rsync/rsync-3.4.1.tar.gz.sha256 new file mode 100644 index 0000000..1c230fd --- /dev/null +++ b/rsync/rsync-3.4.1.tar.gz.sha256 @@ -0,0 +1 @@ +2924bcb3a1ed8b551fc101f740b9f0fe0a202b115027647cf69850d65fd88c52 rsync-3.4.1.tar.gz diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..3bc9510 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "rsend" +include ":app" diff --git a/versions b/versions new file mode 100644 index 0000000..bb4987a --- /dev/null +++ b/versions @@ -0,0 +1,28 @@ +# rsend pinned versions. Single source of truth. +# +# Sourced by the build scripts (POSIX sh: . ./versions) and mirrored by the +# F-Droid recipe. Keep builds reproducible: bump deliberately, never float. + +# Native rsync, built from source via the Android NDK. The tarball sha256 lives +# in rsync/rsync-${RSYNC_VERSION}.tar.gz.sha256, which the build verifies. +RSYNC_VERSION=3.4.1 +RSYNC_URL=https://download.samba.org/pub/rsync/src/rsync-${RSYNC_VERSION}.tar.gz + +# Go SSH transport (rsh). Matches the go.mod go directive; x/crypto needs 1.25+. +GO_VERSION=1.25.0 + +# Android toolchain. ANDROID_NDK is the sdkmanager package revision. +ANDROID_NDK=27.2.12479018 +ANDROID_CMDLINE_TOOLS=11076708 +ANDROID_BUILD_TOOLS=35.0.0 +ANDROID_PLATFORM=35 +ANDROID_MIN_SDK=30 +ANDROID_TARGET_SDK=35 +AGP_VERSION=8.7.3 +GRADLE_VERSION=8.9 +KOTLIN_VERSION=2.0.21 +JDK_VERSION=17 + +# Native ABIs to build. arm64-v8a ships on the phone; x86_64 is for host and +# emulator tests. Add armeabi-v7a to support 32-bit phones. +ABIS="arm64-v8a x86_64" |