commit 19ccc944533c66ed6281b833de6db8f6b7296b9b Author: Hardcore Sushi Date: Tue Jan 26 19:45:18 2021 +0100 Genesis diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5283209 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +.DS_Store +.Trashes +ehthumbs.db +Thumbs.db +build +.cxx +/app/release +.gradle +local.properties +.idea/ +*.apk +*.ap_ +*.dex +*.class +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e37e32e --- /dev/null +++ b/LICENSE @@ -0,0 +1,613 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The GNU Affero General Public License is a free, copyleft license for software +and other kinds of works, specifically designed to ensure cooperation with +the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free software +are heartened and encouraged by the resulting cooperation. However, in the +case of software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and letting +the public access it on a server without ever releasing its source code to +the public. + +The GNU Affero General Public License is designed specifically to ensure that, +in such cases, the modified source code becomes available to the community. +It requires the operator of a network server to provide the source code of +the modified version running there to the users of that server. Therefore, +public use of a modified version, on a publicly accessible server, gives the +public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different license, +not a version of the Affero GPL, but Affero has released a new version of +the Affero GPL which permits relicensing under this license. + +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 Affero 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 s ue 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. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, +your modified version must prominently offer all users interacting with it +remotely through a computer network (if your version supports such interaction) +an opportunity to receive the Corresponding Source of your version by providing +access to the Corresponding Source from a network server at no charge, through +some standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any work covered +by version 3 of the GNU General Public License that is incorporated pursuant +to the following paragraph. + +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 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 work with which it is combined will remain +governed by version 3 of the GNU General Public License. + + 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero 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 Affero 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 Affero 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 Affero 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. + + + +Copyright (C) + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero 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 Affero General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License along +with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could display +a "Source" link that leads users to an archive of the code. There are many +ways you could offer source, and different solutions will be better for different +programs; see section 13 for the specific requirements. + +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 AGPL, see . diff --git a/README.md b/README.md new file mode 100644 index 0000000..bf56170 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# AIRA Android +AIRA is peer-to-peer encrypted communication tool for local networks built on the [PSEC protocol](https://forge.chapril.org/hardcoresushi/PSEC). It allows to securely send text messages and files without any server or Internet access. + +Here is the Android version. You can find the original AIRA desktop version [here](https://forge.chapril.org/hardcoresushi/AIRA). + +# Disclaimer +AIRA is still under developement and is not ready for production usage yet. Not all features have been implemented and bugs are expected. Neither the code or the PSEC protocol received any security audit and therefore shouldn't be considered fully secure. AIRA is provided "as is", without any warranty of any kind. + +# Features +- End-to-End encryption using the [PSEC protocol](https://forge.chapril.org/hardcoresushi/PSEC) +- Automatic peer discovery using mDNS +- Manual peer connection +- File transferts +- Notifications +- Encrypted database +- Contact verification +- IPv4/v6 compatibility +- Free/Libre and Open Source + +# Build +### Install Rust +AIRA android uses some code from the desktop version which is written in Rust. Therefore, you need to compile this Rust code first. +``` +curl --proto '=https' --tlsv1.3 -sSf https://sh.rustup.rs | sh +rustup target add aarch64-linux-android armv7-linux-androideabi +``` +### Install NDK +The Rust code uses a crate called "rusqlite" to store data in SQLite databases. This crates uses the original SQLite3 library written in C. Therefore, to compile it you need the Android NDK. You can find instructions to install the NDK here: https://developer.android.com/ndk/guides + +Once installed, you need to define the $ANDROID_NDK_HOME environment variable (if not already set): +``` +export ANDROID_NDK_HOME=/home//Android/SDK/ndk/" +``` +### Download AIRA +``` +git clone --depth=1 https://forge.chapril.org/hardcoresushi/AIRA-android.git && cd AIRA-android +``` +### Verify commit +``` +git verify-commit HEAD +``` +### Build AIRA Rust code +``` +cd app/src/main/native +./build.sh +``` +### Build final APK +If you have AndroidStudio installed, you can just open the project directory and then start the build process. Otherwise, you can use Gradle from the command line: + +Generate a signed APK with your keystore: +``` +# From the project root directory: +./gradlew assembleRelease -Pandroid.injected.signing.store.file= -Pandroid.injected.signing.store.password= -Pandroid.injected.signing.key.alias= -Pandroid.injected.signing.key.password= +``` +Generate an unsigned APK: +``` +./gradlew assembleRelease +``` +Once completed, the APKs will be located under `app/build/outputs/apk/release/`. + +If you generate an unsigned APK you won't be able to install it as-is on your device. You will need to force install it with ADB: +``` +adb install app-release-unsigned.apk +``` diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..8de6b18 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,54 @@ +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + defaultConfig { + applicationId "sushi.hardcore.aira" + minSdkVersion 19 + targetSdkVersion 30 + versionCode 1 + versionName "0.1" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildFeatures { + viewBinding true + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation 'androidx.core:core-ktx:1.3.2' + implementation 'androidx.appcompat:appcompat:1.2.0' + implementation "androidx.fragment:fragment-ktx:1.3.2" + implementation "androidx.preference:preference-ktx:1.1.1" + implementation 'com.google.android.material:material:1.3.0' + //implementation 'androidx.constraintlayout:constraintlayout:2.0.4' + //implementation 'androidx.legacy:legacy-support-v4:1.0.0' + //testImplementation 'junit:junit:4.13.1' + + implementation 'net.i2p.crypto:eddsa:0.3.0' + implementation "org.whispersystems:curve25519-android:0.5.0" + implementation 'androidx.constraintlayout:constraintlayout:2.0.4' + implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0" +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/androidTest/java/sushi/hardcore/aira/ExampleInstrumentedTest.kt b/app/src/androidTest/java/sushi/hardcore/aira/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..6f88848 --- /dev/null +++ b/app/src/androidTest/java/sushi/hardcore/aira/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package sushi.hardcore.aira + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("sushi.hardcore.aira", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..24cd1b9 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/sushi/hardcore/aira/AIRADatabase.kt b/app/src/main/java/sushi/hardcore/aira/AIRADatabase.kt new file mode 100644 index 0000000..834d733 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/AIRADatabase.kt @@ -0,0 +1,24 @@ +package sushi.hardcore.aira + +import sushi.hardcore.aira.background_service.Contact + +object AIRADatabase { + external fun isIdentityProtected(databaseFolder: String): Boolean + external fun loadIdentity(databaseFolder: String, password: ByteArray?): Boolean + external fun addContact(name: String, publicKey: ByteArray): Contact? + external fun removeContact(uuid: String): Boolean + external fun loadContacts(): ArrayList? + external fun setVerified(uuid: String): Boolean + external fun setContactSeen(contactUuid: String, seen: Boolean): Boolean + external fun changeContactName(contactUuid: String, newName: String): Boolean + external fun storeMsg(contactUuid: String, outgoing: Boolean, data: ByteArray): Boolean + external fun storeFile(contactUuid: String?, data: ByteArray): ByteArray? + external fun loadMsgs(uuid: String, offset: Int, count: Int): ArrayList? + external fun loadFile(rawUuid: ByteArray): ByteArray? + external fun deleteConversation(contactUuid: String): Boolean + external fun clearTemporaryFiles(): Int + external fun getIdentityPublicKey(): ByteArray + external fun getIdentityFingerprint(): String + external fun changeName(newName: String): Boolean + external fun changePassword(databaseFolder: String, oldPassword: ByteArray?, newPassword: ByteArray?): Boolean +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/ChatActivity.kt b/app/src/main/java/sushi/hardcore/aira/ChatActivity.kt new file mode 100644 index 0000000..e3d228a --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/ChatActivity.kt @@ -0,0 +1,345 @@ +package sushi.hardcore.aira + +import android.content.* +import android.os.Bundle +import android.os.IBinder +import android.provider.OpenableColumns +import android.view.Menu +import android.view.MenuItem +import android.view.View +import android.widget.LinearLayout +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.constraintlayout.widget.ConstraintLayout +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import sushi.hardcore.aira.adapters.ChatAdapter +import sushi.hardcore.aira.background_service.AIRAService +import sushi.hardcore.aira.background_service.Protocol +import sushi.hardcore.aira.background_service.ReceiveFileTransfer +import sushi.hardcore.aira.databinding.ActivityChatBinding +import sushi.hardcore.aira.utils.FileUtils +import sushi.hardcore.aira.utils.StringUtils +import java.util.* + +class ChatActivity : AppCompatActivity() { + private external fun generateFingerprint(publicKey: ByteArray): String + + private lateinit var binding: ActivityChatBinding + private var sessionId = -1 + private lateinit var sessionName: String + private lateinit var airaService: AIRAService + private lateinit var chatAdapter: ChatAdapter + private var lastLoadedMessageOffset = 0 + private var isActivityInForeground = false + private val filePicker = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (::airaService.isInitialized) { + contentResolver.query(uri, null, null, null, null)?.let { cursor -> + if (cursor.moveToFirst()) { + contentResolver.openInputStream(uri)?.let { inputStream -> + val fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) + val fileSize = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE)) + airaService.sendFileTo(sessionId, fileName, fileSize, inputStream)?.let { msg -> + chatAdapter.newMessage(ChatItem(true, msg)) + } + if (airaService.contacts.contains(sessionId)) { + lastLoadedMessageOffset += 1 + } + } + } + cursor.close() + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityChatBinding.inflate(layoutInflater) + setContentView(binding.root) + supportActionBar?.setDisplayHomeAsUpEnabled(true) + + sessionId = intent.getIntExtra("sessionId", -1) + if (sessionId != -1) { + intent.getStringExtra("sessionName")?.let { name -> + sessionName = name + title = name + + chatAdapter = ChatAdapter(this@ChatActivity, ::onClickSaveFile) + binding.recyclerChat.apply { + adapter = chatAdapter + layoutManager = LinearLayoutManager(this@ChatActivity, LinearLayoutManager.VERTICAL, false) + addOnScrollListener(object : RecyclerView.OnScrollListener() { + fun loadMsgsIfNeeded(recyclerView: RecyclerView) { + if (!recyclerView.canScrollVertically(-1) && ::airaService.isInitialized) { + airaService.contacts[sessionId]?.let { contact -> + loadMsgs(contact.uuid) + } + } + } + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + loadMsgsIfNeeded(recyclerView) + } + override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { + loadMsgsIfNeeded(recyclerView) + } + }) + } + Intent(this, AIRAService::class.java).also { serviceIntent -> + bindService(serviceIntent, object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, service: IBinder) { + val binder = service as AIRAService.AIRABinder + airaService = binder.getService() + + airaService.contacts[sessionId]?.let { contact -> + displayIconTrustLevel(true, contact.verified) + loadMsgs(contact.uuid) + } + airaService.receiveFileTransfers[sessionId]?.let { + if (it.shouldAsk) { + it.ask(this@ChatActivity, sessionName) + } + } + airaService.savedMsgs[sessionId]?.let { + for (chatItem in it.asReversed()) { + chatAdapter.newLoadedMessage(chatItem) + } + } + binding.recyclerChat.smoothScrollToPosition(chatAdapter.itemCount) + val onConnected = { + findViewById(R.id.bottom_panel).visibility = View.VISIBLE + binding.buttonSend.setOnClickListener { + val msg = binding.editMessage.text.toString() + airaService.sendTo(sessionId, Protocol.newMessage(msg)) + binding.editMessage.text.clear() + chatAdapter.newMessage(ChatItem(true, Protocol.newMessage(msg))) + if (airaService.contacts.contains(sessionId)) { + lastLoadedMessageOffset += 1 + } + binding.recyclerChat.smoothScrollToPosition(chatAdapter.itemCount) + } + binding.buttonAttach.setOnClickListener { + filePicker.launch("*/*") + } + } + airaService.uiCallbacks = object : AIRAService.UiCallbacks { + override fun onNewSession(sessionId: Int, ip: String) { + if (this@ChatActivity.sessionId == sessionId) { + runOnUiThread { + onConnected() + } + } + } + override fun onSessionDisconnect(sessionId: Int) { + if (this@ChatActivity.sessionId == sessionId) { + runOnUiThread { + findViewById(R.id.bottom_panel).visibility = View.GONE + binding.buttonSend.setOnClickListener(null) + binding.buttonAttach.setOnClickListener(null) + } + } + } + override fun onNameTold(sessionId: Int, name: String) { + if (this@ChatActivity.sessionId == sessionId) { + runOnUiThread { + sessionName = name + title = name + } + } + } + override fun onNewMessage(sessionId: Int, data: ByteArray): Boolean { + return if (this@ChatActivity.sessionId == sessionId) { + runOnUiThread { + chatAdapter.newMessage(ChatItem(false, data)) + binding.recyclerChat.smoothScrollToPosition(chatAdapter.itemCount) + } + if (airaService.contacts.contains(sessionId)) { + lastLoadedMessageOffset += 1 + } + isActivityInForeground + } else { + false + } + } + + override fun onAskLargeFile(sessionId: Int, name: String, receiveFileTransfer: ReceiveFileTransfer): Boolean { + return if (this@ChatActivity.sessionId == sessionId) { + runOnUiThread { + receiveFileTransfer.ask(this@ChatActivity, name) + } + true + } else { + false + } + } + } + airaService.isAppInBackground = false + if (airaService.isOnline(sessionId)) { + onConnected() + } + airaService.setSeen(sessionId, true) + } + override fun onServiceDisconnected(name: ComponentName?) {} + }, Context.BIND_AUTO_CREATE) + } + } + } + } + + fun displayIconTrustLevel(isContact: Boolean, isVerified: Boolean) { + when { + isVerified -> { + binding.imageTrustLevel.setImageResource(R.drawable.ic_verified) + } + isContact -> { + binding.imageTrustLevel.setImageDrawable(null) + } + else -> { + binding.imageTrustLevel.setImageResource(R.drawable.ic_warning) + } + } + } + + fun loadMsgs(contactUuid: String) { + AIRADatabase.loadMsgs(contactUuid, lastLoadedMessageOffset, Constants.MSG_LOADING_COUNT)?.let { + for (chatItem in it.asReversed()) { + chatAdapter.newLoadedMessage(chatItem) + } + lastLoadedMessageOffset += it.size + } + } + + override fun onCreateOptionsMenu(menu: Menu): Boolean { + menuInflater.inflate(R.menu.chat_activity, menu) + val contact = airaService.contacts[sessionId] + if (contact == null){ + menu.findItem(R.id.delete_conversation).isVisible = false + menu.findItem(R.id.set_as_contact).isVisible = true + menu.findItem(R.id.remove_contact).isVisible = false + menu.findItem(R.id.verify).isVisible = false + } else { + menu.findItem(R.id.delete_conversation).isVisible = true + menu.findItem(R.id.set_as_contact).isVisible = false + menu.findItem(R.id.remove_contact).isVisible = true + menu.findItem(R.id.verify).isVisible = !contact.verified + } + return true + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + return when (item.itemId) { + android.R.id.home -> { + finish() + true + } + R.id.session_info -> { + val contact = airaService.contacts[sessionId] + val session = airaService.sessions[sessionId] + val publicKey = contact?.publicKey ?: session?.peerPublicKey + val dialogView = layoutInflater.inflate(R.layout.dialog_info, null) + dialogView.findViewById(R.id.text_fingerprint).text = StringUtils.beautifyFingerprint(generateFingerprint(publicKey!!)) + if (session == null) { + dialogView.findViewById(R.id.online_fields).visibility = View.GONE + } else { + dialogView.findViewById(R.id.text_ip).text = session.ip + dialogView.findViewById(R.id.text_outgoing).text = getString(if (session.outgoing) { + R.string.outgoing + } else { + R.string.incoming + }) + } + AlertDialog.Builder(this) + .setTitle(sessionName) + .setView(dialogView) + .setPositiveButton(R.string.ok, null) + .show() + true + } + R.id.set_as_contact -> { + if (airaService.setAsContact(sessionId, sessionName)) { + invalidateOptionsMenu() + displayIconTrustLevel(true, false) + } + true + } + R.id.remove_contact -> { + AlertDialog.Builder(this) + .setTitle(R.string.warning) + .setMessage(R.string.ask_remove_contact) + .setPositiveButton(R.string.delete) { _, _ -> + if (airaService.removeContact(sessionId)) { + invalidateOptionsMenu() + displayIconTrustLevel(false, false) + } + } + .setNegativeButton(R.string.cancel, null) + .show() + true + } + R.id.verify -> { + airaService.contacts[sessionId]?.let { contact -> + val localFingerprint = StringUtils.beautifyFingerprint(AIRADatabase.getIdentityFingerprint()) + val peerFingerprint = StringUtils.beautifyFingerprint(generateFingerprint(contact.publicKey)) + val dialogView = layoutInflater.inflate(R.layout.dialog_fingerprints, null) + dialogView.findViewById(R.id.text_local_fingerprint).text = localFingerprint + dialogView.findViewById(R.id.text_peer_fingerprint).text = peerFingerprint + AlertDialog.Builder(this) + .setTitle(R.string.verifying_contact) + .setView(dialogView) + .setPositiveButton(R.string.they_match) { _, _ -> + if (airaService.setVerified(sessionId)) { + invalidateOptionsMenu() + displayIconTrustLevel(true, true) + } + } + .setNegativeButton(R.string.cancel, null) + .show() + } + true + } + R.id.delete_conversation -> { + AlertDialog.Builder(this) + .setTitle(R.string.warning) + .setMessage(R.string.ask_delete_conversation) + .setPositiveButton(R.string.delete) { _, _ -> + if (airaService.deleteConversation(sessionId)) { + chatAdapter.clear() + } + } + .setNegativeButton(R.string.cancel, null) + .show() + true + } + else -> super.onOptionsItemSelected(item) + } + } + + override fun onResume() { + super.onResume() + isActivityInForeground = true + if (::airaService.isInitialized) { + airaService.setSeen(sessionId, true) + airaService.isAppInBackground = false + } + } + + override fun onPause() { + super.onPause() + isActivityInForeground = false + if (::airaService.isInitialized) { + airaService.isAppInBackground = true + } + } + + private fun onClickSaveFile(fileName: String, rawUuid: ByteArray) { + FileUtils.openFileForDownload(this, fileName)?.apply { + AIRADatabase.loadFile(rawUuid)?.let { + write(it) + Toast.makeText(this@ChatActivity, R.string.file_saved, Toast.LENGTH_SHORT).show() + } + close() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/ChatItem.kt b/app/src/main/java/sushi/hardcore/aira/ChatItem.kt new file mode 100644 index 0000000..438e7ae --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/ChatItem.kt @@ -0,0 +1,11 @@ +package sushi.hardcore.aira + +import sushi.hardcore.aira.background_service.Protocol + +class ChatItem(val outgoing: Boolean, val data: ByteArray) { + companion object { + const val MESSAGE = 0 + const val FILE = 1 + } + val itemType = if (data[0] == Protocol.MESSAGE) { MESSAGE } else { FILE } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/Constants.kt b/app/src/main/java/sushi/hardcore/aira/Constants.kt new file mode 100644 index 0000000..782402b --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/Constants.kt @@ -0,0 +1,22 @@ +package sushi.hardcore.aira + +import android.content.Context +import java.io.File + +object Constants { + const val port = 7530 + const val mDNSServiceName = "AIRA Node" + const val mDNSServiceType = "_aira._tcp" + const val fileSizeLimit = 32760000 + const val MSG_LOADING_COUNT = 20 + const val FILE_CHUNK_SIZE = 1023996 + private const val databaseName = "AIRA.db" + + fun getDatabaseFolder(context: Context): String { + return getDatabasePath(context).parent!! + } + + fun getDatabasePath(context: Context): File { + return context.getDatabasePath(databaseName) + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/CreateIdentityFragment.kt b/app/src/main/java/sushi/hardcore/aira/CreateIdentityFragment.kt new file mode 100644 index 0000000..1d3f463 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/CreateIdentityFragment.kt @@ -0,0 +1,71 @@ +package sushi.hardcore.aira + +import android.content.Intent +import android.os.Bundle +import androidx.fragment.app.Fragment +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import sushi.hardcore.aira.databinding.FragmentCreateIdentityBinding + +class CreateIdentityFragment : Fragment() { + private external fun createNewIdentity(databaseFolder: String, name: String, password: ByteArray?): Boolean + + companion object { + fun newInstance(): CreateIdentityFragment { + return CreateIdentityFragment() + } + } + + private lateinit var binding: FragmentCreateIdentityBinding + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + binding = FragmentCreateIdentityBinding.inflate(inflater, container, false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + binding.checkboxEnablePassword.setOnCheckedChangeListener { _, isChecked -> + if (isChecked) { + binding.editPassword.visibility = View.VISIBLE + binding.editPasswordConfirm.visibility = View.VISIBLE + } else { + binding.editPassword.visibility = View.GONE + binding.editPasswordConfirm.visibility = View.GONE + } + } + binding.buttonCreate.setOnClickListener { + val identityName = binding.editName.text.toString() + val password = binding.editPassword.text.toString().toByteArray() + if (password.isEmpty()) { + createIdentity(identityName, null) + } else { + val passwordConfirm = binding.editPasswordConfirm.text.toString().toByteArray() + if (password.contentEquals(passwordConfirm)) { + createIdentity(identityName, password) + } else { + Toast.makeText(activity, R.string.password_mismatch, Toast.LENGTH_SHORT).show() + } + passwordConfirm.fill(0) + password.fill(0) + } + } + } + + private fun createIdentity(identityName: String, password: ByteArray?) { + val databaseFolder = Constants.getDatabaseFolder(requireContext()) + if (createNewIdentity( + databaseFolder, + identityName, + password + )) { + val intent = Intent(activity, MainActivity::class.java) + intent.putExtra("identityName", identityName) + startActivity(intent) + activity?.finish() + } else { + Toast.makeText(activity, R.string.identity_create_failed, Toast.LENGTH_SHORT).show() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/LoginActivity.kt b/app/src/main/java/sushi/hardcore/aira/LoginActivity.kt new file mode 100644 index 0000000..5009ae5 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/LoginActivity.kt @@ -0,0 +1,60 @@ +package sushi.hardcore.aira + +import android.content.Intent +import android.os.Bundle +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import sushi.hardcore.aira.background_service.AIRAService +import java.io.File + +class LoginActivity : AppCompatActivity() { + private external fun getIdentityName(databaseFolder: String): String? + + companion object { + init { + System.loadLibrary("aira") + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_login) + val databaseFolder = Constants.getDatabaseFolder(this) + val dbFile = File(databaseFolder) + if (!dbFile.isDirectory) { + if (!dbFile.mkdir()) { + Toast.makeText(this, R.string.db_mkdir_failed, Toast.LENGTH_SHORT).show() + } + } + val isProtected = AIRADatabase.isIdentityProtected(databaseFolder) + val name = getIdentityName(databaseFolder) + if (AIRAService.isServiceRunning) { + startActivity(Intent(this, MainActivity::class.java)) + finish() + } else if (name != null && !isProtected) { + if (AIRADatabase.loadIdentity(databaseFolder, null)) { + AIRADatabase.clearTemporaryFiles() + startMainActivity(name) + } else { + Toast.makeText(this, R.string.identity_load_failed, Toast.LENGTH_SHORT).show() + } + } else { + supportFragmentManager.beginTransaction() + .add( + R.id.fragment_container, if (name == null) { + CreateIdentityFragment.newInstance() + } else { + LoginFragment.newInstance(name) + } + ) + .commit() + } + } + + private fun startMainActivity(identityName: String?) { + val intent = Intent(this, MainActivity::class.java) + intent.putExtra("identityName", identityName) + startActivity(intent) + finish() + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/LoginFragment.kt b/app/src/main/java/sushi/hardcore/aira/LoginFragment.kt new file mode 100644 index 0000000..dccc35d --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/LoginFragment.kt @@ -0,0 +1,50 @@ +package sushi.hardcore.aira + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import android.widget.Toast +import androidx.fragment.app.Fragment +import sushi.hardcore.aira.databinding.FragmentLoginBinding +import sushi.hardcore.aira.widgets.TextAvatar + +class LoginFragment : Fragment() { + companion object { + private const val NAME_ARG = "identityName" + fun newInstance(name: String): LoginFragment { + return LoginFragment().apply { + arguments = Bundle().apply { putString(NAME_ARG, name) } + } + } + } + + private lateinit var binding: FragmentLoginBinding + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + binding = FragmentLoginBinding.inflate(inflater, container, false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + arguments?.let { bundle -> + bundle.getString(NAME_ARG)?.let { name -> + view.findViewById(R.id.text_avatar).setLetterFrom(name) + view.findViewById(R.id.text_identity_name).text = name + binding.buttonLogin.setOnClickListener { + if (AIRADatabase.loadIdentity(Constants.getDatabaseFolder(requireContext()), binding.editPassword.text.toString().toByteArray())) { + AIRADatabase.clearTemporaryFiles() + val intent = Intent(activity, MainActivity::class.java) + intent.putExtra("identityName", name) + startActivity(intent) + activity?.finish() + } else { + Toast.makeText(activity, R.string.identity_load_failed, Toast.LENGTH_SHORT).show() + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/MainActivity.kt b/app/src/main/java/sushi/hardcore/aira/MainActivity.kt new file mode 100644 index 0000000..b89d61c --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/MainActivity.kt @@ -0,0 +1,250 @@ +package sushi.hardcore.aira + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.net.Uri +import android.os.Bundle +import android.os.IBinder +import android.provider.OpenableColumns +import android.view.Menu +import android.view.MenuItem +import android.widget.AdapterView +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import sushi.hardcore.aira.adapters.Session +import sushi.hardcore.aira.adapters.SessionAdapter +import sushi.hardcore.aira.background_service.AIRAService +import sushi.hardcore.aira.background_service.ReceiveFileTransfer +import sushi.hardcore.aira.databinding.ActivityMainBinding +import sushi.hardcore.aira.utils.FileUtils + +class MainActivity : AppCompatActivity() { + private lateinit var binding: ActivityMainBinding + private lateinit var airaService: AIRAService + private lateinit var onlineSessionAdapter: SessionAdapter + private lateinit var offlineSessionAdapter: SessionAdapter + private val uiCallbacks = object : AIRAService.UiCallbacks { + override fun onNewSession(sessionId: Int, ip: String) { + runOnUiThread { + handleNewSession(sessionId, ip) + } + } + override fun onSessionDisconnect(sessionId: Int) { + runOnUiThread { + onlineSessionAdapter.remove(sessionId)?.let { session -> + if (session.isContact) { + offlineSessionAdapter.add(session) + } + } + } + } + override fun onNameTold(sessionId: Int, name: String) { + runOnUiThread { + onlineSessionAdapter.setName(sessionId, name) + } + } + override fun onNewMessage(sessionId: Int, data: ByteArray): Boolean { + runOnUiThread { + onlineSessionAdapter.setSeen(sessionId, false) + } + return false + } + + override fun onAskLargeFile(sessionId: Int, name: String, receiveFileTransfer: ReceiveFileTransfer): Boolean { + runOnUiThread { + receiveFileTransfer.ask(this@MainActivity, name) + } + return true + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + + val identityName = intent.getStringExtra("identityName") + identityName?.let { title = it } + + val openedToShareFile = intent.action == Intent.ACTION_SEND + + onlineSessionAdapter = SessionAdapter(this) + binding.onlineSessions.apply { + adapter = onlineSessionAdapter + onItemClickListener = if (openedToShareFile) { + AdapterView.OnItemClickListener { _, _, position, _ -> + askShareFileTo(onlineSessionAdapter.getItem(position)) + } + } else { + AdapterView.OnItemClickListener { _, _, position, _ -> + launchChatActivity(onlineSessionAdapter.getItem(position)) + } + } + } + offlineSessionAdapter = SessionAdapter(this) + binding.offlineSessions.apply { + adapter = offlineSessionAdapter + onItemClickListener = if (openedToShareFile) { + AdapterView.OnItemClickListener { _, _, position, _ -> + askShareFileTo(offlineSessionAdapter.getItem(position)) + } + } else { + AdapterView.OnItemClickListener { _, _, position, _ -> + launchChatActivity(offlineSessionAdapter.getItem(position)) + } + } + } + Intent(this, AIRAService::class.java).also { serviceIntent -> + bindService(serviceIntent, object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, service: IBinder) { + val binder = service as AIRAService.AIRABinder + airaService = binder.getService() + airaService.uiCallbacks = uiCallbacks + airaService.isAppInBackground = false + loadContacts() + if (AIRAService.isServiceRunning) { + title = airaService.identityName + loadSessions() + } else { + airaService.identityName = identityName + startService(serviceIntent) + } + binding.refresher.setOnRefreshListener { + airaService.restartDiscovery() + binding.refresher.isRefreshing = false + } + } + override fun onServiceDisconnected(name: ComponentName?) {} + }, Context.BIND_AUTO_CREATE) + } + + binding.editPeerIp.setOnEditorActionListener { _, _, _ -> + if (::airaService.isInitialized){ + airaService.connectTo(binding.editPeerIp.text.toString()) + } + binding.editPeerIp.text.clear() + true + } + } + + override fun onCreateOptionsMenu(menu: Menu?): Boolean { + menuInflater.inflate(R.menu.main_activity, menu) + return true + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + return when (item.itemId) { + R.id.settings -> { + startActivity(Intent(this, SettingsActivity::class.java)) + true + } + R.id.close -> { + if (::airaService.isInitialized) { + AlertDialog.Builder(this) + .setTitle(R.string.warning) + .setMessage(R.string.ask_log_out) + .setPositiveButton(R.string.yes) { _, _ -> + airaService.logOut() + if (AIRADatabase.isIdentityProtected(Constants.getDatabaseFolder(this))) { + startActivity(Intent(this, LoginActivity::class.java)) + } + finish() + } + .setNegativeButton(R.string.cancel, null) + .show() + } + true + } + else -> super.onOptionsItemSelected(item) + } + } + + override fun onPause() { + super.onPause() + if (::airaService.isInitialized) { + airaService.isAppInBackground = true + } + } + + override fun onResume() { + super.onResume() + if (::airaService.isInitialized) { + if (AIRAService.isServiceRunning) { + airaService.isAppInBackground = false + airaService.uiCallbacks = uiCallbacks //restoring callbacks + onlineSessionAdapter.reset() + offlineSessionAdapter.reset() + loadContacts() + loadSessions() + title = airaService.identityName + } else { + finish() + } + } + } + + private fun loadContacts() { + for ((sessionId, contact) in airaService.contacts) { + offlineSessionAdapter.add(Session(sessionId, true, contact.verified, contact.seen, null, contact.name)) + } + } + + private fun loadSessions() { + for ((sessionId, session) in airaService.sessions) { + handleNewSession(sessionId, session.ip) + } + } + + private fun handleNewSession(sessionId: Int, ip: String) { + val seen = !airaService.notSeen.contains(sessionId) + val contact = airaService.contacts[sessionId] + if (contact == null) { + onlineSessionAdapter.add(Session(sessionId, false, false, seen, ip, airaService.savedNames[sessionId])) + } else { + onlineSessionAdapter.add(Session(sessionId, true, contact.verified, seen, ip, contact.name)) + offlineSessionAdapter.remove(sessionId) + } + } + + private fun launchChatActivity(session: Session) { + startActivity(Intent(this, ChatActivity::class.java).apply { + putExtra("sessionId", session.sessionId) + putExtra("sessionName", session.name) + }) + } + + private fun askShareFileTo(session: Session) { + val uri = intent.getParcelableExtra(Intent.EXTRA_STREAM) + if (uri == null) { + Toast.makeText(this, R.string.share_uri_null, Toast.LENGTH_SHORT).show() + } else { + val cursor = contentResolver.query(uri, null, null, null, null) + if (cursor == null) { + Toast.makeText(this, R.string.file_open_failed, Toast.LENGTH_SHORT).show() + } else { + if (cursor.moveToFirst()) { + val fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) + val fileSize = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE)) + val inputStream = contentResolver.openInputStream(uri) + if (inputStream == null) { + Toast.makeText(this, R.string.file_open_failed, Toast.LENGTH_SHORT).show() + } else { + AlertDialog.Builder(this) + .setTitle(R.string.warning) + .setMessage(getString(R.string.ask_send_file, fileName, FileUtils.formatSize(fileSize), session.name ?: session.ip)) + .setPositiveButton(R.string.yes) { _, _ -> + airaService.sendFileTo(session.sessionId, fileName, fileSize, inputStream) + finish() + } + .setNegativeButton(R.string.cancel, null) + .show() + } + } + cursor.close() + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/SettingsActivity.kt b/app/src/main/java/sushi/hardcore/aira/SettingsActivity.kt new file mode 100644 index 0000000..b16028f --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/SettingsActivity.kt @@ -0,0 +1,139 @@ +package sushi.hardcore.aira + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.Bundle +import android.os.IBinder +import android.view.MenuItem +import android.view.View +import android.widget.EditText +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.preference.EditTextPreference +import androidx.preference.Preference +import androidx.preference.PreferenceFragmentCompat +import sushi.hardcore.aira.background_service.AIRAService +import sushi.hardcore.aira.databinding.ActivityMainBinding +import sushi.hardcore.aira.databinding.ActivitySettingsBinding +import sushi.hardcore.aira.utils.StringUtils + +class SettingsActivity: AppCompatActivity() { + class MySettingsFragment : PreferenceFragmentCompat() { + private lateinit var airaService: AIRAService + override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + setPreferencesFromResource(R.xml.preferences, rootKey) + val identityName = findPreference("identityName") + Intent(activity, AIRAService::class.java).also { serviceIntent -> + activity?.bindService(serviceIntent, object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, service: IBinder) { + val binder = service as AIRAService.AIRABinder + airaService = binder.getService() + identityName?.text = airaService.identityName + } + override fun onServiceDisconnected(name: ComponentName?) {} + }, Context.BIND_AUTO_CREATE) + } + identityName?.setOnPreferenceChangeListener { _, newValue -> + if (airaService.changeName(newValue as String)) { + identityName.text = newValue + } + false + } + findPreference("deleteIdentity")?.setOnPreferenceClickListener { + activity?.let { activity -> + AlertDialog.Builder(activity) + .setMessage(R.string.confirm_delete) + .setTitle(R.string.warning) + .setPositiveButton(R.string.ok) { _, _ -> + if (Constants.getDatabasePath(activity).delete()) { + airaService.logOut() + startActivity(Intent(activity, LoginActivity::class.java)) + activity.finish() + } + } + .setNegativeButton(R.string.cancel, null) + .show() + } + false + } + findPreference("identityPassword")?.setOnPreferenceClickListener { + activity?.let { activity -> + val dialogView = layoutInflater.inflate(R.layout.dialog_password, null) + val oldPasswordEditText = dialogView.findViewById(R.id.old_password) + val isIdentityProtected = AIRADatabase.isIdentityProtected(Constants.getDatabaseFolder(activity)) + if (!isIdentityProtected) { + oldPasswordEditText.visibility = View.GONE + } + val newPasswordEditText = dialogView.findViewById(R.id.new_password) + val newPasswordConfirmEditText = dialogView.findViewById(R.id.new_password_confirm) + AlertDialog.Builder(activity) + .setView(dialogView) + .setTitle(R.string.change_password) + .setPositiveButton(R.string.ok) { _, _ -> + val newPassword = newPasswordEditText.text.toString().toByteArray() + if (newPassword.isEmpty()) { + if (isIdentityProtected) { //don't change password if identity is not protected and new password is blank + changePassword(activity, isIdentityProtected, oldPasswordEditText, null) + } + } else { + val newPasswordConfirm = newPasswordConfirmEditText.text.toString().toByteArray() + if (newPassword.contentEquals(newPasswordConfirm)) { + changePassword(activity, isIdentityProtected, oldPasswordEditText, newPassword) + } else { + AlertDialog.Builder(activity) + .setMessage(R.string.password_mismatch) + .setTitle(R.string.error) + .setPositiveButton(R.string.ok, null) + .show() + } + newPassword.fill(0) + newPasswordConfirm.fill(0) + } + } + .setNegativeButton(R.string.cancel, null) + .show() + } + false + } + } + + private fun changePassword(context: Context, isIdentityProtected: Boolean, oldPasswordEditText: EditText, newPassword: ByteArray?) { + val oldPassword = if (isIdentityProtected) { + oldPasswordEditText.text.toString().toByteArray() + } else { + null + } + if (!AIRADatabase.changePassword(Constants.getDatabaseFolder(context), oldPassword, newPassword)) { + AlertDialog.Builder(context) + .setMessage(R.string.change_password_failed) + .setTitle(R.string.error) + .setPositiveButton(R.string.ok, null) + .show() + } + oldPassword?.fill(0) + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + return if (item.itemId == android.R.id.home) { + finish() + true + } else { + super.onOptionsItemSelected(item) + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val binding = ActivitySettingsBinding.inflate(layoutInflater) + setContentView(binding.root) + supportFragmentManager + .beginTransaction() + .replace(R.id.settings_container, MySettingsFragment()) + .commit() + supportActionBar?.setDisplayHomeAsUpEnabled(true) + binding.textFingerprint.text = StringUtils.beautifyFingerprint(AIRADatabase.getIdentityFingerprint()) + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/adapters/ChatAdapter.kt b/app/src/main/java/sushi/hardcore/aira/adapters/ChatAdapter.kt new file mode 100644 index 0000000..d65a242 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/adapters/ChatAdapter.kt @@ -0,0 +1,135 @@ +package sushi.hardcore.aira.adapters + +import android.content.Context +import android.graphics.PorterDuff +import android.graphics.PorterDuffColorFilter +import android.view.Gravity +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageButton +import android.widget.LinearLayout +import android.widget.TextView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView +import sushi.hardcore.aira.ChatItem +import sushi.hardcore.aira.R + +class ChatAdapter( + private val context: Context, + private val onSavingFile: (filename: String, rawUuid: ByteArray) -> Unit +): RecyclerView.Adapter() { + + companion object { + const val BUBBLE_MARGIN = 70 + } + + private val inflater: LayoutInflater = LayoutInflater.from(context) + private val chatItems = mutableListOf() + + fun newMessage(chatItem: ChatItem) { + chatItems.add(chatItem) + notifyItemInserted(chatItems.size-1) + } + + fun newLoadedMessage(chatItem: ChatItem) { + chatItems.add(0, chatItem) + notifyItemInserted(0) + } + + fun clear() { + chatItems.clear() + notifyDataSetChanged() + } + + internal open class BubbleViewHolder(private val context: Context, itemView: View): RecyclerView.ViewHolder(itemView) { + fun handleItemView(position: Int) { + if (position == 0) { + itemView.setPadding(itemView.paddingLeft, 50, itemView.paddingRight, itemView.paddingBottom) + } + } + fun setBubbleColor(bubble: View, outgoing: Boolean) { + if (outgoing) { + bubble.background.clearColorFilter() + } else { + bubble.background.colorFilter = PorterDuffColorFilter(ContextCompat.getColor(context, R.color.incomingBubbleBackground), PorterDuff.Mode.SRC) + } + } + } + + internal class MessageViewHolder(context: Context, itemView: View): BubbleViewHolder(context, itemView) { + fun bind(chatItem: ChatItem, position: Int) { + itemView.findViewById(R.id.text_message).apply { + text = chatItem.data.sliceArray(1 until chatItem.data.size).decodeToString() + layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + if (chatItem.outgoing) { + gravity = Gravity.END + marginStart = BUBBLE_MARGIN + } else { + gravity = Gravity.START + marginEnd = BUBBLE_MARGIN + } + } + setBubbleColor(this, chatItem.outgoing) + } + handleItemView(position) + } + } + + internal class FileViewHolder(context: Context, itemView: View): BubbleViewHolder(context, itemView) { + fun bind(chatItem: ChatItem, position: Int, onSavingFile: (filename: String, rawUuid: ByteArray) -> Unit) { + val filename = chatItem.data.sliceArray(17 until chatItem.data.size).decodeToString() + itemView.findViewById(R.id.text_filename).text = filename + itemView.findViewById(R.id.button_save).setOnClickListener { + onSavingFile(filename, chatItem.data.sliceArray(1 until 17)) + } + itemView.findViewById(R.id.bubble_content).apply { + layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + if (chatItem.outgoing) { + gravity = Gravity.END + marginStart = BUBBLE_MARGIN + } else { + gravity = Gravity.START + marginEnd = BUBBLE_MARGIN + } + } + setBubbleColor(this, chatItem.outgoing) + } + handleItemView(position) + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + return when (viewType) { + ChatItem.MESSAGE -> { + val view = inflater.inflate(R.layout.adapter_chat_message, parent, false) + MessageViewHolder(context, view) + } + ChatItem.FILE -> { + val view = inflater.inflate(R.layout.adapter_chat_file, parent, false) + FileViewHolder(context, view) + } + else -> throw RuntimeException("Invalid chat item type") + } + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val chatItem = chatItems[position] + when (chatItem.itemType) { + ChatItem.MESSAGE -> { + (holder as MessageViewHolder).bind(chatItem, position) + } + ChatItem.FILE -> { + (holder as FileViewHolder).bind(chatItem, position, onSavingFile) + } + } + } + + override fun getItemCount(): Int { + return chatItems.size + } + + override fun getItemViewType(position: Int): Int { + return chatItems[position].itemType + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/adapters/Session.kt b/app/src/main/java/sushi/hardcore/aira/adapters/Session.kt new file mode 100644 index 0000000..5f915ed --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/adapters/Session.kt @@ -0,0 +1,10 @@ +package sushi.hardcore.aira.adapters + +class Session( + val sessionId: Int, + val isContact: Boolean, + val isVerified: Boolean, + var seen: Boolean, + val ip: String?, + var name: String? +) \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/adapters/SessionAdapter.kt b/app/src/main/java/sushi/hardcore/aira/adapters/SessionAdapter.kt new file mode 100644 index 0000000..87d5789 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/adapters/SessionAdapter.kt @@ -0,0 +1,101 @@ +package sushi.hardcore.aira.adapters + +import android.content.Context +import android.graphics.Color +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.BaseAdapter +import android.widget.ImageView +import android.widget.TextView +import sushi.hardcore.aira.R +import sushi.hardcore.aira.widgets.TextAvatar + +class SessionAdapter(context: Context): BaseAdapter() { + private val sessions = mutableListOf() + private val inflater: LayoutInflater = LayoutInflater.from(context) + + override fun getCount(): Int { + return sessions.size + } + + override fun getItem(position: Int): Session { + return sessions[position] + } + + override fun getItemId(position: Int): Long { + return 0 + } + + override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { + val view: View = convertView ?: inflater.inflate(R.layout.adapter_session, parent, false) + val currentSession = getItem(position) + view.findViewById(R.id.text_name).apply { + if (currentSession.name == null) { + text = currentSession.ip + setTextColor(Color.RED) + } else { + text = currentSession.name + setTextColor(Color.WHITE) + } + view.findViewById(R.id.text_avatar).setLetterFrom(text.toString()) + } + view.findViewById(R.id.image_trust_level).apply { + if (currentSession.isVerified) { + setImageResource(R.drawable.ic_verified) + } else if (!currentSession.isContact) { + setImageResource(R.drawable.ic_warning) + } else { + setImageDrawable(null) + } + } + view.findViewById(R.id.image_seen).visibility = if (currentSession.seen) { + View.GONE + } else { + View.VISIBLE + } + return view + } + + fun add(session: Session) { + sessions.add(session) + notifyDataSetChanged() + } + + private fun getSessionById(sessionId: Int): Session? { + for (session in sessions){ + if (session.sessionId == sessionId) { + return session + } + } + return null + } + + fun remove(sessionId: Int): Session? { + getSessionById(sessionId)?.let { + sessions.remove(it) + notifyDataSetChanged() + return it + } + return null + } + + fun setName(sessionId: Int, name: String) { + getSessionById(sessionId)?.let { + it.name = name + notifyDataSetChanged() + } + } + + fun setSeen(sessionId: Int, seen: Boolean) { + getSessionById(sessionId)?.let { + it.seen = seen + notifyDataSetChanged() + } + } + + fun reset() { + sessions.clear() + notifyDataSetChanged() + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/AIRAService.kt b/app/src/main/java/sushi/hardcore/aira/background_service/AIRAService.kt new file mode 100644 index 0000000..5266827 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/AIRAService.kt @@ -0,0 +1,810 @@ +package sushi.hardcore.aira.background_service + +import android.app.* +import android.content.Context +import android.content.Intent +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo +import android.os.* +import android.os.Process.THREAD_PRIORITY_BACKGROUND +import android.util.Log +import androidx.annotation.RequiresApi +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.app.RemoteInput +import sushi.hardcore.aira.* +import java.io.IOException +import java.io.InputStream +import java.net.* +import java.nio.ByteBuffer +import java.nio.channels.* + +class AIRAService : Service() { + private external fun releaseIdentity() + + companion object { + const val SERVICE_NOTIFICATION_CHANNEL_ID = "AIRAService" + const val MESSAGES_NOTIFICATION_CHANNEL_ID = "Messages" + const val ASK_FILE_TRANSFER_NOTIFICATION_CHANNEL_ID = "AskFile" + const val FILE_TRANSFER_NOTIFICATION_CHANNEL_ID = "FileTransfer" + const val MESSAGE_CONNECT_TO = 0 + const val MESSAGE_SEND_TO = 1 + const val MESSAGE_LOGOUT = 2 + const val MESSAGE_TELL_NAME = 3 + const val MESSAGE_CANCEL_FILE_TRANSFER = 4 + + var isServiceRunning = false + } + + private val binder = AIRABinder() + val sessions = mutableMapOf() + private var sessionCounter = 0 + private var server: ServerSocketChannel? = null + private lateinit var selector: Selector + private val sessionIdByKey = mutableMapOf() + private val notificationIdManager = NotificationIdManager() + private val sendFileTransfers = mutableMapOf() + val receiveFileTransfers = mutableMapOf() + lateinit var contacts: HashMap + private lateinit var serviceHandler: Handler + private lateinit var notificationManager: NotificationManagerCompat + private lateinit var nsdManager: NsdManager + private val nsdRegistrationListener = object : NsdManager.RegistrationListener { + override fun onRegistrationFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) { + Log.w("mDNS","DNS-SD registration failed: $errorCode") + } + override fun onUnregistrationFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) {} + override fun onServiceRegistered(serviceInfo: NsdServiceInfo?) {} + override fun onServiceUnregistered(serviceInfo: NsdServiceInfo?) {} + } + private var shouldRestartDiscovery = false + private val nsdDiscoveryListener = object : NsdManager.DiscoveryListener { + override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) { + Log.w("mDNS", "Failed to start discovery: $errorCode") + } + override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {} + override fun onDiscoveryStarted(serviceType: String?) {} + override fun onDiscoveryStopped(serviceType: String?) { + if (shouldRestartDiscovery) { + startDiscovery() + shouldRestartDiscovery = false + } + } + override fun onServiceFound(serviceInfo: NsdServiceInfo) { + nsdManager.resolveService(serviceInfo, object : NsdManager.ResolveListener { + override fun onResolveFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) {} + override fun onServiceResolved(serviceInfo: NsdServiceInfo) { + if (isServiceRunning) { + connectTo(serviceInfo.host.hostAddress) + } + } + }) + } + override fun onServiceLost(serviceInfo: NsdServiceInfo?) {} + } + val savedMsgs = mutableMapOf>() + val savedNames = mutableMapOf() + val notSeen = mutableListOf() + var uiCallbacks: UiCallbacks? = null + var isAppInBackground = true + var identityName: String? = null + + inner class AIRABinder : Binder() { + fun getService(): AIRAService = this@AIRAService + } + + override fun onBind(intent: Intent?): IBinder { + return binder + } + + interface UiCallbacks { + fun onNewSession(sessionId: Int, ip: String) + fun onSessionDisconnect(sessionId: Int) + fun onNameTold(sessionId: Int, name: String) + fun onNewMessage(sessionId: Int, data: ByteArray): Boolean + fun onAskLargeFile(sessionId: Int, name: String, receiveFileTransfer: ReceiveFileTransfer): Boolean + } + + fun connectTo(ip: String) { + serviceHandler.obtainMessage().apply { + what = MESSAGE_CONNECT_TO + data = Bundle().apply { putString("ip", ip) } + serviceHandler.sendMessage(this) + } + } + + fun sendTo(sessionId: Int, buffer: ByteArray) { + serviceHandler.obtainMessage().apply { + what = MESSAGE_SEND_TO + data = Bundle().apply { + putInt("sessionId", sessionId) + putByteArray("buff", buffer) + } + serviceHandler.sendMessage(this) + } + } + + fun cancelFileTransfer(sessionId: Int) { + serviceHandler.obtainMessage().apply { + what = MESSAGE_CANCEL_FILE_TRANSFER + data = Bundle().apply { putInt("sessionId", sessionId) } + serviceHandler.sendMessage(this) + } + } + + fun sendFileTo(sessionId: Int, fileName: String, fileSize: Long, inputStream: InputStream): ByteArray? { + if (fileSize <= Constants.fileSizeLimit) { + val buffer = inputStream.readBytes() + inputStream.close() + sendTo(sessionId, Protocol.newFile(fileName, buffer)) + AIRADatabase.storeFile(contacts[sessionId]?.uuid, buffer)?.let { rawFileUuid -> + val msg = byteArrayOf(Protocol.FILE)+rawFileUuid+fileName.toByteArray() + saveMsg(sessionId, msg) + return msg + } + } else { + val fileTransfer = SendFileTransfer(fileName, fileSize, inputStream) + sendFileTransfers[sessionId] = fileTransfer + createFileTransferNotification(sessionId, fileTransfer) + sendTo(sessionId, Protocol.askLargeFile(fileSize, fileName)) + } + return null + } + + fun logOut() { + serviceHandler.sendEmptyMessage(MESSAGE_LOGOUT) + isServiceRunning = false + releaseIdentity() + } + + fun isOnline(sessionId: Int): Boolean { + return sessions.contains(sessionId) + } + + private fun getNameOf(sessionId: Int): String { + return contacts[sessionId]?.name ?: savedNames[sessionId] ?: sessions[sessionId]!!.ip + } + + private fun isContact(sessionId: Int): Boolean { + return contacts.contains(sessionId) + } + + fun setAsContact(sessionId: Int, name: String): Boolean { + sessions[sessionId]?.peerPublicKey?.let { + AIRADatabase.addContact(name, it)?.let { contact -> + contacts[sessionId] = contact + savedMsgs.remove(sessionId)?.let { msgs -> + for (msg in msgs) { + AIRADatabase.storeMsg(contact.uuid, msg.outgoing, msg.data) + } + } + savedNames.remove(sessionId) + return true + } + } + return false + } + + fun setVerified(sessionId: Int): Boolean { + contacts[sessionId]?.let { + if (AIRADatabase.setVerified(it.uuid)) { + it.verified = true + return true + } + } + return false + } + + fun setSeen(sessionId: Int, seen: Boolean) { + if (seen) { + notSeen.remove(sessionId) + notificationManager.cancel(notificationIdManager.getMessageNotificationId(sessionId)) + } else if (!notSeen.contains(sessionId)) { + notSeen.add(sessionId) + } + contacts[sessionId]?.let { contact -> + if (contact.seen != seen) { + if (AIRADatabase.setContactSeen(contact.uuid, seen)) { + contact.seen = seen + } + } + } + } + + fun removeContact(sessionId: Int): Boolean { + contacts.remove(sessionId)?.let { + return if (AIRADatabase.removeContact(it.uuid)) { + savedMsgs[sessionId] = mutableListOf() + savedNames[sessionId] = it.name + true + } else { + false + } + } + return false + } + + fun deleteConversation(sessionId: Int): Boolean { + contacts[sessionId]?.let { + return if (AIRADatabase.deleteConversation(it.uuid)) { + savedMsgs[sessionId] = mutableListOf() + true + } else { + false + } + } + return true + } + + fun changeName(newName: String): Boolean { + return if (AIRADatabase.changeName(newName)) { + identityName = newName + serviceHandler.sendEmptyMessage(MESSAGE_TELL_NAME) + true + } else { + false + } + } + + private fun handleNewSocket(socket: SocketChannel, outgoing: Boolean) { + Thread { + try { + val session = Session(socket, outgoing) + if (session.doHandshake()) { + var isActuallyNewSession = true + for (s in sessions.values) { + if (s.peerPublicKey.contentEquals(session.peerPublicKey)) { + isActuallyNewSession = false + } + } + if (isActuallyNewSession && !session.peerPublicKey.contentEquals(AIRADatabase.getIdentityPublicKey())) { + var sessionId: Int? = null + for ((i, contact) in contacts) { + if (contact.publicKey.contentEquals(session.peerPublicKey)){ + sessions[i] = session + sessionId = i + } + } + if (sessionId == null) { + sessions[sessionCounter] = session + savedMsgs[sessionCounter] = mutableListOf() + sessionId = sessionCounter + sessionCounter++ + } + session.configureBlocking(false) + val key = session.register(selector, SelectionKey.OP_READ) + sessionIdByKey[key] = sessionId + uiCallbacks?.onNewSession(sessionId, session.ip) + if (!isContact(sessionId)) { + session.encryptAndSend(Protocol.askName()) + } + } else { + session.close() + } + } else { + session.close() + } + } catch (e: IOException) { + e.printStackTrace() + } + }.start() + } + + private fun sendNotification(sessionId: Int, msgContent: ByteArray) { + val name = getNameOf(sessionId) + val notificationBuilder = NotificationCompat.Builder(this, MESSAGES_NOTIFICATION_CHANNEL_ID) + .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setSmallIcon(R.drawable.ic_launcher) + .setContentTitle(name) + .setContentText( + if (msgContent[0] == Protocol.MESSAGE) { + msgContent.decodeToString(1) + } else { //file + msgContent.decodeToString(17) + } + ) + .setContentIntent( + PendingIntent.getActivity(this, 0, Intent(this, ChatActivity::class.java).apply { + putExtra("sessionId", sessionId) + putExtra("sessionName", name) + }, 0) + ) + .setAutoCancel(true) + .setDefaults(Notification.DEFAULT_ALL) + .apply { + priority = NotificationCompat.PRIORITY_HIGH + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { + val markReadIntent = PendingIntent.getBroadcast(this, 0, + Intent(this, NotificationBroadcastReceiver::class.java).apply { + val bundle = Bundle() + bundle.putBinder("binder", AIRABinder()) + bundle.putInt("sessionId", sessionId) + putExtra("bundle", bundle) + action = NotificationBroadcastReceiver.ACTION_MARK_READ + }, PendingIntent.FLAG_UPDATE_CURRENT) + notificationBuilder.addAction( + NotificationCompat.Action( + R.drawable.ic_launcher, + getString(R.string.mark_read), + markReadIntent + ) + ) + val replyPendingIntent: PendingIntent = + PendingIntent.getBroadcast(this, 0, + Intent(this, NotificationBroadcastReceiver::class.java).apply { + val bundle = Bundle() + bundle.putBinder("binder", AIRABinder()) + bundle.putInt("sessionId", sessionId) + putExtra("bundle", bundle) + action = NotificationBroadcastReceiver.ACTION_REPLY + }, PendingIntent.FLAG_UPDATE_CURRENT) + notificationBuilder.addAction( + NotificationCompat.Action.Builder(R.drawable.ic_launcher, getString(R.string.reply), replyPendingIntent) + .addRemoteInput( + RemoteInput.Builder(NotificationBroadcastReceiver.KEY_TEXT_REPLY) + .setLabel(getString(R.string.reply)) + .build() + ) + .build() + ) + + } + notificationManager.notify(notificationIdManager.getMessageNotificationId(sessionId), notificationBuilder.build()) + } + + private fun createFileTransferNotification(sessionId: Int, fileTransfer: FileTransfer) { + fileTransfer.notificationBuilder = NotificationCompat.Builder(this, FILE_TRANSFER_NOTIFICATION_CHANNEL_ID) + .setCategory(NotificationCompat.CATEGORY_PROGRESS) + .setSmallIcon(R.drawable.ic_launcher) + .setContentTitle(getNameOf(sessionId)) + .setContentText(fileTransfer.fileName) + .setOngoing(true) + .setProgress(fileTransfer.fileSize.toInt(), fileTransfer.transferred, true) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { + val cancelIntent = PendingIntent.getBroadcast(this, 0, + Intent(this, NotificationBroadcastReceiver::class.java).apply { + val bundle = Bundle() + bundle.putBinder("binder", AIRABinder()) + bundle.putInt("sessionId", sessionId) + putExtra("bundle", bundle) + action = NotificationBroadcastReceiver.ACTION_CANCEL_FILE_TRANSFER + }, PendingIntent.FLAG_UPDATE_CURRENT) + fileTransfer.notificationBuilder.addAction( + NotificationCompat.Action( + R.drawable.ic_launcher, + getString(R.string.cancel), + cancelIntent + ) + ) + } + fileTransfer.notificationId = notificationIdManager.getFileTransferNotificationId(sessionId) + notificationManager.notify(fileTransfer.notificationId, fileTransfer.notificationBuilder.build()) + } + + private fun saveMsg(sessionId: Int, msg: ByteArray) { + var msgSaved = false + contacts[sessionId]?.uuid?.let { uuid -> + msgSaved = AIRADatabase.storeMsg(uuid, true, msg) + } + if (!msgSaved) { + savedMsgs[sessionId]?.add(ChatItem(true, msg)) + } + } + + private fun sendAndSave(sessionId: Int, msg: ByteArray) { + sessions[sessionId]?.encryptAndSend(msg) + if (msg[0] == Protocol.MESSAGE) { + saveMsg(sessionId, msg) + } + } + + override fun onCreate() { + HandlerThread("", THREAD_PRIORITY_BACKGROUND).apply { + start() + serviceHandler = object : Handler(looper){ + override fun handleMessage(msg: Message) { + try { + when (msg.what) { + MESSAGE_SEND_TO -> { + val sessionId = msg.data.getInt("sessionId") + msg.data.getByteArray("buff")?.let { + val fileTransfer = sendFileTransfers[sessionId] + if (fileTransfer?.nextChunk == null) { + sendAndSave(sessionId, it) + } else { + fileTransfer.msgQueue.add(it) + } + } + } + MESSAGE_CONNECT_TO -> { + msg.data.getString("ip")?.let { ip -> + try { + val socket = SocketChannel.open() + if (socket.connect(InetSocketAddress(ip, Constants.port))) { + handleNewSocket(socket, true) + } + } catch (e: ConnectException) { + Log.w("Connect failed", e.message.toString()) + return + } + } + } + MESSAGE_CANCEL_FILE_TRANSFER -> { + val sessionId = msg.data.getInt("sessionId") + sessions[sessionId]?.let { session -> + cancelFileTransfer(sessionId, session, true) + } + } + MESSAGE_TELL_NAME -> { + identityName?.let { + for (session in sessions.values) { + try { + session.encryptAndSend(Protocol.tellName(it)) + } catch (e: SocketException) { + e.printStackTrace() + } + } + } + } + MESSAGE_LOGOUT -> { + nsdManager.unregisterService(nsdRegistrationListener) + stopDiscovery() + quit() + stopSelf() + uiCallbacks = null + for (session in sessions.values) { + session.close() + } + server?.close() + } + } + } catch (e: IOException) { + e.printStackTrace() + } + } + } + val contactList = AIRADatabase.loadContacts() + if (contactList == null) { + contacts = HashMap(0) + } else { + contacts = HashMap(contactList.size) + for (contact in contactList) { + contacts[sessionCounter] = contact + if (!contact.seen) { + notSeen.add(sessionCounter) + } + sessionCounter++ + } + } + } + } + + private fun encryptNextChunk(session: Session, fileTransfer: SendFileTransfer) { + val nextChunk = ByteArray(Constants.FILE_CHUNK_SIZE) + nextChunk[0] = Protocol.LARGE_FILE_CHUNK + val read = fileTransfer.inputStream.read(nextChunk, 1, Constants.FILE_CHUNK_SIZE-1) + fileTransfer.nextChunk = if (read > 0) { + session.encrypt(nextChunk) + } else { + null + } + } + + private fun flushSendFileTransfer(sessionId: Int, session: Session, fileTransfer: SendFileTransfer) { + fileTransfer.nextChunk?.let { + session.writeAll(it) + while (fileTransfer.msgQueue.size > 0) { + val msg = fileTransfer.msgQueue.removeAt(0) + sendAndSave(sessionId, msg) + } + } + } + + private fun cancelFileTransfer(sessionId: Int, session: Session, outgoing: Boolean) { + sendFileTransfers[sessionId]?.let { + it.inputStream.close() + it.onAborted(this, notificationManager, getNameOf(sessionId)) + flushSendFileTransfer(sessionId, session, it) + sendFileTransfers.remove(sessionId) + } + receiveFileTransfers[sessionId]?.let { + it.outputStream?.close() + it.onAborted(this, notificationManager, getNameOf(sessionId)) + receiveFileTransfers.remove(sessionId) + } + if (outgoing) { + session.encryptAndSend(Protocol.abortFileTransfer()) + } + } + + private fun startListening() { + server = try { + ServerSocketChannel.open().apply { + configureBlocking(false) + socket().bind(InetSocketAddress(Constants.port)) + } + } catch (e: SocketException) { + Log.w("Bind failed", e.message.toString()) + null + } + selector = Selector.open() + server?.register(selector, SelectionKey.OP_ACCEPT) + Thread { + while (isServiceRunning) { + selector.select(100) //timeout to stop this thread if we log out + val keys = selector.selectedKeys() + for (key in keys) { + if (key.isValid) { + if (key.isReadable) { + sessionIdByKey[key]?.let { sessionId -> + sessions[sessionId]?.let { session -> + var shouldCloseSession = false + try { + val buffer = session.receiveAndDecrypt() + if (buffer == null) { + shouldCloseSession = true + } else { + when (buffer[0]) { + Protocol.ASK_NAME -> { + identityName?.let { name -> + session.encryptAndSend(Protocol.tellName(name)) + } + } + Protocol.TELL_NAME -> { + val name = buffer.sliceArray(1 until buffer.size).decodeToString() + uiCallbacks?.onNameTold(sessionId, name) + val contact = contacts[sessionId] + if (contact == null) { + savedNames[sessionId] = name + } else { + contact.name = name + AIRADatabase.changeContactName(contact.uuid, name) + } + } + Protocol.LARGE_FILE_CHUNK -> { + receiveFileTransfers[sessionId]?.let { fileTransfer -> + fileTransfer.outputStream?.let { outputStream -> + val chunk = buffer.sliceArray(1 until buffer.size) + try { + outputStream.write(chunk) + session.encryptAndSend(Protocol.ackChunk()) + fileTransfer.transferred += chunk.size + if (fileTransfer.transferred >= fileTransfer.fileSize) { + outputStream.close() + receiveFileTransfers.remove(sessionId) + fileTransfer.onCompleted(this, notificationManager, getNameOf(sessionId)) + } else { + fileTransfer.updateNotificationProgress(notificationManager) + } + } catch (e: IOException) { + cancelFileTransfer(sessionId) + } + } + } + } + Protocol.ACK_CHUNK -> { + sendFileTransfers[sessionId]?.let { fileTransfer -> + flushSendFileTransfer(sessionId, session, fileTransfer) + fileTransfer.transferred += fileTransfer.nextChunk?.size ?: 0 + if (fileTransfer.transferred >= fileTransfer.fileSize) { + fileTransfer.inputStream.close() + sendFileTransfers.remove(sessionId) + fileTransfer.onCompleted(this, notificationManager, getNameOf(sessionId)) + } else { + encryptNextChunk(session, fileTransfer) + fileTransfer.updateNotificationProgress(notificationManager) + } + } + } + Protocol.ABORT_FILE_TRANSFER -> cancelFileTransfer(sessionId, session, false) + Protocol.ACCEPT_LARGE_FILE -> { + sendFileTransfers[sessionId]?.let { fileTransfer -> + encryptNextChunk(session, fileTransfer) + fileTransfer.nextChunk?.let { + session.writeAll(it) + fileTransfer.transferred += fileTransfer.nextChunk?.size ?: 0 + encryptNextChunk(session, fileTransfer) + } + } + } + Protocol.ASK_LARGE_FILE -> { + if (receiveFileTransfers[sessionId] == null) { + val fileSize = ByteBuffer.wrap(buffer.sliceArray(1..8)).long + val fileName = buffer.sliceArray(9 until buffer.size).decodeToString() + val fileTransfer = ReceiveFileTransfer(fileName, fileSize, { fileTransfer -> + createFileTransferNotification(sessionId, fileTransfer) + sendTo(sessionId, Protocol.acceptLargeFile()) + }, { + receiveFileTransfers.remove(sessionId) + sendTo(sessionId, Protocol.abortFileTransfer()) + notificationManager.cancel(notificationIdManager.getFileTransferNotificationId(sessionId)) + }) + receiveFileTransfers[sessionId] = fileTransfer + val name = getNameOf(sessionId) + var shouldSendNotification = true + if (!isAppInBackground) { + if (uiCallbacks?.onAskLargeFile(sessionId, name, fileTransfer) == true) { + shouldSendNotification = false + } + } + if (shouldSendNotification) { + val notificationBuilder = NotificationCompat.Builder(this, ASK_FILE_TRANSFER_NOTIFICATION_CHANNEL_ID) + .setCategory(NotificationCompat.CATEGORY_EVENT) + .setSmallIcon(R.drawable.ic_launcher) + .setContentTitle(getString(R.string.download_file_request)) + .setContentText(getString(R.string.want_to_send_a_file, name, ": $fileName")) + .setOngoing(true) //not cancelable + .setContentIntent( + PendingIntent.getActivity(this, 0, Intent(this, ChatActivity::class.java).apply { + putExtra("sessionId", sessionId) + putExtra("sessionName", name) + }, 0) + ) + .setDefaults(Notification.DEFAULT_ALL) + .apply { + priority = NotificationCompat.PRIORITY_HIGH + } + notificationManager.notify(notificationIdManager.getFileTransferNotificationId(sessionId), notificationBuilder.build()) + } + } + } + else -> { + when (buffer[0]){ + Protocol.MESSAGE -> buffer + Protocol.FILE -> { + val filenameLen = ByteBuffer.wrap(ByteArray(2) +buffer.sliceArray(1..2)).int + val filename = buffer.sliceArray(3 until 3+filenameLen) + val rawFileUuid = AIRADatabase.storeFile(contacts[sessionId]?.uuid, buffer.sliceArray(3+filenameLen until buffer.size)) + if (rawFileUuid == null) { + null + } else { + byteArrayOf(Protocol.FILE)+rawFileUuid+filename + } + } + else -> { + Log.i("Unknown message type", String.format("%02X", buffer[0])) + null + } + }?.let { handledMsg -> + var seen = false + uiCallbacks?.let { uiCallbacks -> + seen = uiCallbacks.onNewMessage(sessionId, handledMsg) + } + setSeen(sessionId, seen) + var msgSaved = false + contacts[sessionId]?.let { contact -> + msgSaved = AIRADatabase.storeMsg(contact.uuid, false, handledMsg) + } + if (!msgSaved){ + savedMsgs[sessionId]?.add(ChatItem(false, handledMsg)) + } + if (isAppInBackground) { + sendNotification(sessionId, handledMsg) + } + } + } + } + } + } catch (e: Exception) { + e.printStackTrace() + shouldCloseSession = true + } + if (shouldCloseSession) { + session.close() + key.cancel() + uiCallbacks?.onSessionDisconnect(sessionId) + sessions.remove(sessionId) + savedMsgs.remove(sessionId) + savedNames.remove(sessionId) + sendFileTransfers.remove(sessionId)?.notificationId?.let { + if (it != -1) { + notificationManager.cancel(it) + } + } + receiveFileTransfers.remove(sessionId)?.notificationId?.let { + if (it != -1) { + notificationManager.cancel(it) + } + } + } + } + } + } else if (key.isAcceptable) { + server?.accept()?.let { + handleNewSocket(it, false) + } + } + } + } + } + }.start() + } + + fun restartDiscovery() { + shouldRestartDiscovery = true + stopDiscovery() + } + + private fun stopDiscovery() { + nsdManager.stopServiceDiscovery(nsdDiscoveryListener) + } + + private fun startDiscovery() { + nsdManager.discoverServices(Constants.mDNSServiceType, NsdManager.PROTOCOL_DNS_SD, nsdDiscoveryListener) + } + + @RequiresApi(Build.VERSION_CODES.O) + private fun createNotificationChannels() { + notificationManager.createNotificationChannel( + NotificationChannel( + SERVICE_NOTIFICATION_CHANNEL_ID, + getString(R.string.service_name), + NotificationManager.IMPORTANCE_LOW + ) + ) + notificationManager.createNotificationChannel( + NotificationChannel( + MESSAGES_NOTIFICATION_CHANNEL_ID, + getString(R.string.msg_notification_channel_name), + NotificationManager.IMPORTANCE_HIGH + ) + ) + notificationManager.createNotificationChannel( + NotificationChannel( + ASK_FILE_TRANSFER_NOTIFICATION_CHANNEL_ID, + getString(R.string.ask_file_notification_channel), + NotificationManager.IMPORTANCE_HIGH + ) + ) + notificationManager.createNotificationChannel( + NotificationChannel( + FILE_TRANSFER_NOTIFICATION_CHANNEL_ID, + getString(R.string.file_transfers), + NotificationManager.IMPORTANCE_LOW + ) + ) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + notificationManager = NotificationManagerCompat.from(this) + val notificationBuilder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + createNotificationChannels() + Notification.Builder(this, SERVICE_NOTIFICATION_CHANNEL_ID) + } else { + @Suppress("Deprecation") + Notification.Builder(this) + } + val notification: Notification = notificationBuilder + .setContentTitle(getString(R.string.background_service)) + .setSmallIcon(R.drawable.ic_launcher) + .setContentIntent( + PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), 0) + ) + .build() + startForeground(1, notification) + + val serviceInfo = NsdServiceInfo().apply { + serviceName = Constants.mDNSServiceName + serviceType = Constants.mDNSServiceType + port = Constants.port + } + nsdManager = getSystemService(Context.NSD_SERVICE) as NsdManager + try { + nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, nsdRegistrationListener) + startDiscovery() + } catch (e: IllegalArgumentException) { + //can happen if service is restarted too quickly + } + + startListening() + + isServiceRunning = true + + return START_STICKY + } + + override fun onDestroy() { + isServiceRunning = false + } +} diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/ApplicationKeys.kt b/app/src/main/java/sushi/hardcore/aira/background_service/ApplicationKeys.kt new file mode 100644 index 0000000..1ee0d16 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/ApplicationKeys.kt @@ -0,0 +1,8 @@ +package sushi.hardcore.aira.background_service + +class ApplicationKeys( + val localKey: ByteArray, + val localIv: ByteArray, + val peerKey: ByteArray, + val peerIv: ByteArray, +) \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/Contact.kt b/app/src/main/java/sushi/hardcore/aira/background_service/Contact.kt new file mode 100644 index 0000000..d27f37b --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/Contact.kt @@ -0,0 +1,3 @@ +package sushi.hardcore.aira.background_service + +class Contact(val uuid: String, val publicKey: ByteArray, var name: String, var verified: Boolean, var seen: Boolean) \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/FileTransfer.kt b/app/src/main/java/sushi/hardcore/aira/background_service/FileTransfer.kt new file mode 100644 index 0000000..e32f9d1 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/FileTransfer.kt @@ -0,0 +1,39 @@ +package sushi.hardcore.aira.background_service + +import android.content.Context +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import sushi.hardcore.aira.R + +open class FileTransfer(val fileName: String, val fileSize: Long) { + var transferred = 0 + lateinit var notificationBuilder: NotificationCompat.Builder + var notificationId = -1 + + fun updateNotificationProgress(notificationManager: NotificationManagerCompat) { + notificationBuilder.setProgress(fileSize.toInt(), transferred, false) + notificationManager.notify(notificationId, notificationBuilder.build()) + } + + private fun endNotification(context: Context, notificationManager: NotificationManagerCompat, sessionName: String, string: Int) { + notificationManager.notify( + notificationId, + NotificationCompat.Builder(context, AIRAService.FILE_TRANSFER_NOTIFICATION_CHANNEL_ID) + .setCategory(NotificationCompat.CATEGORY_EVENT) + .setSmallIcon(R.drawable.ic_launcher) + .setContentTitle(sessionName) + .setContentText(context.getString(string)) + .build() + ) + } + + fun onAborted(context: Context, notificationManager: NotificationManagerCompat, sessionName: String) { + if (::notificationBuilder.isInitialized) { + endNotification(context, notificationManager, sessionName, R.string.transfer_aborted) + } + } + + fun onCompleted(context: Context, notificationManager: NotificationManagerCompat, sessionName: String) { + endNotification(context, notificationManager, sessionName, R.string.transfer_completed) + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/HandshakeKeys.kt b/app/src/main/java/sushi/hardcore/aira/background_service/HandshakeKeys.kt new file mode 100644 index 0000000..58b507f --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/HandshakeKeys.kt @@ -0,0 +1,11 @@ +package sushi.hardcore.aira.background_service + +class HandshakeKeys( + val localKey: ByteArray, + val localIv: ByteArray, + val localHandshakeTrafficSecret: ByteArray, + val peerKey: ByteArray, + val peerIv: ByteArray, + val peerHandshakeTrafficSecret: ByteArray, + val handshakeSecret: ByteArray +) \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/NotificationBroadcastReceiver.kt b/app/src/main/java/sushi/hardcore/aira/background_service/NotificationBroadcastReceiver.kt new file mode 100644 index 0000000..0352076 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/NotificationBroadcastReceiver.kt @@ -0,0 +1,33 @@ +package sushi.hardcore.aira.background_service + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import androidx.core.app.RemoteInput + +class NotificationBroadcastReceiver: BroadcastReceiver() { + companion object { + const val ACTION_MARK_READ = "mark_read" + const val ACTION_CANCEL_FILE_TRANSFER = "cancel" + const val ACTION_REPLY = "reply" + const val KEY_TEXT_REPLY = "key_text_reply" + } + + override fun onReceive(context: Context?, intent: Intent) { + intent.getBundleExtra("bundle")?.let { bundle -> + (bundle.getBinder("binder") as AIRAService.AIRABinder?)?.let { binder -> + val sessionId = bundle.getInt("sessionId") + val airaService = binder.getService() + when (intent.action) { + ACTION_MARK_READ -> airaService.setSeen(sessionId, true) + ACTION_CANCEL_FILE_TRANSFER -> airaService.cancelFileTransfer(sessionId) + ACTION_REPLY -> RemoteInput.getResultsFromIntent(intent)?.getString(KEY_TEXT_REPLY)?.let { reply -> + airaService.sendTo(sessionId, Protocol.newMessage(reply)) + airaService.setSeen(sessionId, true) + } + else -> {} + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/NotificationIdManager.kt b/app/src/main/java/sushi/hardcore/aira/background_service/NotificationIdManager.kt new file mode 100644 index 0000000..e51b349 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/NotificationIdManager.kt @@ -0,0 +1,46 @@ +package sushi.hardcore.aira.background_service + +class NotificationIdManager { + + private enum class NotificationType { + MESSAGE, + FILE_TRANSFER + } + + private inner class Notification( + val sessionId: Int, + val type: NotificationType + ) + + + private val notificationIds = mutableMapOf() + private var lastNotificationId = 1 //got some bugs when starting before 1 + + private fun registerNewId(sessionId: Int, type: NotificationType): Int { + lastNotificationId++ + notificationIds[lastNotificationId] = Notification(sessionId, type) + return lastNotificationId + } + + fun getMessageNotificationId(sessionId: Int): Int { + for ((id, notification) in notificationIds) { + if (notification.sessionId == sessionId) { + if (notification.type == NotificationType.MESSAGE) { + return id + } + } + } + return registerNewId(sessionId, NotificationType.MESSAGE) + } + + fun getFileTransferNotificationId(sessionId: Int): Int { + for ((id, notification) in notificationIds) { + if (notification.sessionId == sessionId) { + if (notification.type == NotificationType.FILE_TRANSFER) { + return id + } + } + } + return registerNewId(sessionId, NotificationType.FILE_TRANSFER) + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/Protocol.kt b/app/src/main/java/sushi/hardcore/aira/background_service/Protocol.kt new file mode 100644 index 0000000..97c2f30 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/Protocol.kt @@ -0,0 +1,49 @@ +package sushi.hardcore.aira.background_service + +import java.nio.ByteBuffer + +class Protocol { + companion object { + const val MESSAGE: Byte = 0x00 + const val ASK_NAME: Byte = 0x01 + const val TELL_NAME: Byte = 0x02 + const val FILE: Byte = 0x03 + const val ASK_LARGE_FILE: Byte = 0x04 + const val ACCEPT_LARGE_FILE: Byte = 0x05 + const val LARGE_FILE_CHUNK: Byte = 0x06 + const val ACK_CHUNK: Byte = 0x07 + const val ABORT_FILE_TRANSFER: Byte = 0x08 + + fun askName(): ByteArray { + return byteArrayOf(ASK_NAME) + } + + fun tellName(name: String): ByteArray { + return byteArrayOf(TELL_NAME)+name.toByteArray() + } + + fun newMessage(msg: String): ByteArray { + return byteArrayOf(MESSAGE)+msg.toByteArray() + } + + fun newFile(fileName: String, buffer: ByteArray): ByteArray { + return byteArrayOf(FILE)+ByteBuffer.allocate(2).putShort(fileName.length.toShort()).array()+fileName.toByteArray()+buffer + } + + fun askLargeFile(fileSize: Long, fileName: String): ByteArray { + return byteArrayOf(ASK_LARGE_FILE)+ByteBuffer.allocate(8).putLong(fileSize).array()+fileName.toByteArray() + } + + fun acceptLargeFile(): ByteArray { + return byteArrayOf(ACCEPT_LARGE_FILE) + } + + fun abortFileTransfer(): ByteArray { + return byteArrayOf(ABORT_FILE_TRANSFER) + } + + fun ackChunk(): ByteArray { + return byteArrayOf(ACK_CHUNK) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/ReceiveFileTransfer.kt b/app/src/main/java/sushi/hardcore/aira/background_service/ReceiveFileTransfer.kt new file mode 100644 index 0000000..5650f3c --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/ReceiveFileTransfer.kt @@ -0,0 +1,44 @@ +package sushi.hardcore.aira.background_service + +import android.annotation.SuppressLint +import android.app.AlertDialog +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import sushi.hardcore.aira.R +import sushi.hardcore.aira.utils.FileUtils +import java.io.OutputStream + +class ReceiveFileTransfer( + fileName: String, + fileSize: Long, + private val onAccepted: (fileTransfer: ReceiveFileTransfer) -> Unit, + private val onAborted: () -> Unit, +): FileTransfer(fileName, fileSize) { + var shouldAsk = true + var outputStream: OutputStream? = null + + @SuppressLint("SetTextI18n") + fun ask(activity: AppCompatActivity, senderName: String) { + val dialogView = activity.layoutInflater.inflate(R.layout.dialog_ask_file, null) + dialogView.findViewById(R.id.text_title).text = activity.getString(R.string.want_to_send_a_file, senderName, ":") + dialogView.findViewById(R.id.text_file_info).text = fileName+" ("+FileUtils.formatSize(fileSize)+")" + AlertDialog.Builder(activity) + .setTitle(R.string.download_file_request) + .setView(dialogView) + .setCancelable(false) + .setPositiveButton(R.string.download) { _, _ -> + outputStream = FileUtils.openFileForDownload(activity, fileName) + if (outputStream == null) { + onAborted() + } else { + onAccepted(this) + } + shouldAsk = false + } + .setNegativeButton(R.string.refuse) { _, _ -> + onAborted() + shouldAsk = false + } + .show() + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/SendFileTransfer.kt b/app/src/main/java/sushi/hardcore/aira/background_service/SendFileTransfer.kt new file mode 100644 index 0000000..5e8f4cd --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/SendFileTransfer.kt @@ -0,0 +1,12 @@ +package sushi.hardcore.aira.background_service + +import java.io.InputStream + +class SendFileTransfer( + fileName: String, + fileSize: Long, + val inputStream: InputStream +): FileTransfer(fileName, fileSize) { + var nextChunk: ByteArray? = null + val msgQueue = mutableListOf() +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/background_service/Session.kt b/app/src/main/java/sushi/hardcore/aira/background_service/Session.kt new file mode 100644 index 0000000..bd21452 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/background_service/Session.kt @@ -0,0 +1,275 @@ +package sushi.hardcore.aira.background_service + +import android.util.Log +import net.i2p.crypto.eddsa.EdDSAEngine +import net.i2p.crypto.eddsa.EdDSAPublicKey +import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable +import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec +import org.whispersystems.curve25519.Curve25519 +import sushi.hardcore.aira.AIRADatabase +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.nio.channels.* +import java.nio.channels.spi.SelectorProvider +import java.security.MessageDigest +import java.security.SecureRandom +import javax.crypto.AEADBadTagException +import javax.crypto.BadPaddingException +import javax.crypto.Cipher +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec +import kotlin.experimental.xor + +class Session(private val socket: SocketChannel, val outgoing: Boolean): SelectableChannel() { + private external fun deriveHandshakeKeys(sharedSecret: ByteArray, handshakeHash: ByteArray, iAmBob: Boolean): HandshakeKeys + private external fun sign(input: ByteArray): ByteArray + private external fun computeHandshakeFinished(localHandshakeTrafficSecret: ByteArray, handshakeHash: ByteArray): ByteArray + private external fun verifyHandshakeFinished(peerHandshakeFinished: ByteArray, peerHandshakeTrafficSecret: ByteArray, handshakeHash: ByteArray): Boolean + private external fun deriveApplicationKeys(handshakeSecret: ByteArray, handshakeHash: ByteArray, iAmBob: Boolean): ApplicationKeys + + companion object { + private const val RANDOM_LEN = 64 + private const val PUBLIC_KEY_LEN = 32 + private const val SIGNATURE_LEN = 64 + private const val AES_TAG_LEN = 16 + private const val IV_LEN = 12 + private const val HASH_OUTPUT_LEN = 48 + private const val handshakeBufferLen = (2*(RANDOM_LEN+PUBLIC_KEY_LEN))+SIGNATURE_LEN+AES_TAG_LEN + private const val CIPHER_TYPE = "AES/GCM/NoPadding" + private const val MESSAGE_LEN_LEN = 4 + private const val PADDED_MAX_SIZE = 32768000 + private const val MAX_RECV_SIZE = MESSAGE_LEN_LEN + PADDED_MAX_SIZE + AES_TAG_LEN + } + + private val prng = SecureRandom() + private val handshakeSentBuff = ByteArrayOutputStream(handshakeBufferLen) + private val handshakeRecvBuff = ByteArrayOutputStream(handshakeBufferLen) + private val peerCipher = Cipher.getInstance(CIPHER_TYPE) + private val localCipher = Cipher.getInstance(CIPHER_TYPE) + private var peerCounter = 0L + private var localCounter = 0L + private lateinit var applicationKeys: ApplicationKeys + lateinit var peerPublicKey: ByteArray + val ip: String = socket.socket().inetAddress.hostAddress + + private fun handshakeWrite(buffer: ByteArray) { + writeAll(buffer) + handshakeSentBuff.write(buffer) + } + + private fun handshakeRead(buffer: ByteBuffer): Boolean { + return if (socket.read(buffer) == buffer.position()) { + handshakeRecvBuff.write(buffer.array()) + true + } else { + false + } + } + private fun handshakeRead(buffer: ByteArray): Boolean { + return handshakeRead(ByteBuffer.wrap(buffer)) + } + + private fun hashHandshake(iAmBob: Boolean): ByteArray { + MessageDigest.getInstance("SHA-384").apply { + if (iAmBob) { + update(handshakeSentBuff.toByteArray()) + update(handshakeRecvBuff.toByteArray()) + } else { + update(handshakeRecvBuff.toByteArray()) + update(handshakeSentBuff.toByteArray()) + } + return digest() + } + } + + private fun amIBob(): Boolean { + val s = handshakeSentBuff.toByteArray() + val r = handshakeRecvBuff.toByteArray() + for (i in s.indices) { + if (s[i] != r[i]) { + return s[i].toInt() and 0xff < r[i].toInt() and 0xff + } + } + throw SecurityException("Handshake buffers are identical") + } + + private fun ivToNonce(iv: ByteArray, counter: Long): ByteArray { + val nonce = ByteArray(IV_LEN-Long.SIZE_BYTES)+ByteBuffer.allocate(Long.SIZE_BYTES).putLong(counter).array() + for (i in nonce.indices) { + nonce[i] = nonce[i] xor iv[i] + } + return nonce + } + + fun doHandshake(): Boolean { + val randomBuffer = ByteArray(RANDOM_LEN) + prng.nextBytes(randomBuffer) + val curve25519Cipher = Curve25519.getInstance(Curve25519.BEST) + val keypair = curve25519Cipher.generateKeyPair() + handshakeWrite(randomBuffer+keypair.publicKey) + + var recvBuffer = ByteBuffer.allocate(RANDOM_LEN+PUBLIC_KEY_LEN) + if (handshakeRead(recvBuffer)) { + val peerEphemeralPublicKey = recvBuffer.array().sliceArray(RANDOM_LEN until recvBuffer.capacity()) + val sharedSecret = curve25519Cipher.calculateAgreement(peerEphemeralPublicKey, keypair.privateKey) + val iAmBob = amIBob() //mutual consensus for keys attribution + var handshakeHash = hashHandshake(iAmBob) + val handshakeKeys = deriveHandshakeKeys(sharedSecret, handshakeHash, iAmBob) + + prng.nextBytes(randomBuffer) + handshakeWrite(randomBuffer) + if (handshakeRead(randomBuffer)) { + val localCipher = Cipher.getInstance(CIPHER_TYPE) + localCipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(handshakeKeys.localKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, ivToNonce(handshakeKeys.localIv, 0))) + handshakeWrite(localCipher.doFinal(AIRADatabase.getIdentityPublicKey()+sign(keypair.publicKey))) + + recvBuffer = ByteBuffer.allocate(PUBLIC_KEY_LEN+SIGNATURE_LEN+AES_TAG_LEN) + if (handshakeRead(recvBuffer)) { + val peerCipher = Cipher.getInstance(CIPHER_TYPE) + peerCipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(handshakeKeys.peerKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, ivToNonce(handshakeKeys.peerIv, 0))) + val plainText: ByteArray + try { + plainText = peerCipher.doFinal(recvBuffer.array()) + } catch (e: BadPaddingException) { + Log.w("BadPaddingException", ip) + return false + } catch (e: AEADBadTagException) { + Log.w("AEADBadTagException", ip) + return false + } + peerPublicKey = plainText.sliceArray(0 until PUBLIC_KEY_LEN) + val signature = plainText.sliceArray(PUBLIC_KEY_LEN until plainText.size) + + val edDSAEngine = EdDSAEngine().apply { + initVerify(EdDSAPublicKey(EdDSAPublicKeySpec(peerPublicKey, EdDSANamedCurveTable.ED_25519_CURVE_SPEC))) + } + if (edDSAEngine.verifyOneShot(peerEphemeralPublicKey, signature)) { + handshakeHash = hashHandshake(iAmBob) + val handshakeFinished = computeHandshakeFinished(handshakeKeys.localHandshakeTrafficSecret, handshakeHash) + writeAll(handshakeFinished) + val peerHandshakeFinished = ByteBuffer.allocate(HASH_OUTPUT_LEN) + socket.read(peerHandshakeFinished) + if (verifyHandshakeFinished(peerHandshakeFinished.array(), handshakeKeys.peerHandshakeTrafficSecret, handshakeHash)){ + applicationKeys = deriveApplicationKeys(handshakeKeys.handshakeSecret, handshakeHash, iAmBob) + handshakeSentBuff.reset() + handshakeRecvBuff.reset() + return true + } else { + Log.w("Handshake", "Final verification failed") + } + } else { + Log.w("Handshake", "Signature verification failed") + } + } + } + } + return false + } + + private fun randomPad(input: ByteArray): ByteArray { + val encodedLen = ByteBuffer.allocate(MESSAGE_LEN_LEN).putInt(input.size).array() + val msgLen = input.size + MESSAGE_LEN_LEN + var len = 1000 + while (len < msgLen) { + len *= 2 + } + val padding = ByteArray(len-msgLen) + prng.nextBytes(padding) + return encodedLen + input + padding + } + + private fun unpad(input: ByteArray): ByteArray { + val messageLen = ByteBuffer.wrap(input.sliceArray(0..MESSAGE_LEN_LEN)).int + return input.sliceArray(MESSAGE_LEN_LEN until MESSAGE_LEN_LEN+messageLen) + } + + fun writeAll(buffer: ByteArray) { + val byteBuffer = ByteBuffer.wrap(buffer) + while (byteBuffer.remaining() > 0) { + socket.write(byteBuffer) + } + } + + fun encrypt(plainText: ByteArray): ByteArray { + val padded = randomPad(plainText) + val rawMsgLen = ByteBuffer.allocate(MESSAGE_LEN_LEN).putInt(padded.size).array() + val nonce = ivToNonce(applicationKeys.localIv, localCounter) + localCounter++ + localCipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(applicationKeys.localKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, nonce)) + localCipher.updateAAD(rawMsgLen) + return rawMsgLen+localCipher.doFinal(padded) + } + + fun encryptAndSend(plainText: ByteArray) { + writeAll(encrypt(plainText)) + } + + fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) } + + private fun readAll(buffer: ByteBuffer): Boolean { + while (buffer.position() != buffer.capacity()) { + try { + if (socket.read(buffer) < 0) { + return false + } + } catch (e: ClosedChannelException) { + return false + } + } + return true + } + + fun receiveAndDecrypt(): ByteArray? { + val rawMessageLen = ByteBuffer.allocate(MESSAGE_LEN_LEN) + if (readAll(rawMessageLen)) { + rawMessageLen.position(0) + val messageLen = rawMessageLen.int + AES_TAG_LEN + if (messageLen in 1..MAX_RECV_SIZE) { + val cipherText = ByteBuffer.allocate(messageLen) + if (readAll(cipherText)) { + val nonce = ivToNonce(applicationKeys.peerIv, peerCounter) + peerCounter++ + peerCipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(applicationKeys.peerKey, "AES"), GCMParameterSpec(AES_TAG_LEN*8, nonce)) + rawMessageLen.position(0) + peerCipher.updateAAD(rawMessageLen) + try { + return unpad(peerCipher.doFinal(cipherText.array())) + } catch (e: AEADBadTagException) { + Log.w("AEADBadTagException", ip) + } + } + } else { + Log.w("Message too large", "$messageLen from $ip") + } + } + return null + } + + override fun implCloseChannel() { + socket.close() + } + override fun provider(): SelectorProvider { + return socket.provider() + } + override fun validOps(): Int { + return socket.validOps() + } + override fun isRegistered(): Boolean { + return socket.isRegistered + } + override fun keyFor(sel: Selector?): SelectionKey { + return socket.keyFor(sel) + } + override fun register(sel: Selector?, ops: Int, att: Any?): SelectionKey { + return socket.register(sel, ops, att) + } + override fun configureBlocking(block: Boolean): SelectableChannel { + return socket.configureBlocking(block) + } + override fun isBlocking(): Boolean { + return socket.isBlocking + } + override fun blockingLock(): Any { + return socket.blockingLock() + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/utils/FileUtils.kt b/app/src/main/java/sushi/hardcore/aira/utils/FileUtils.kt new file mode 100644 index 0000000..7e40cf8 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/utils/FileUtils.kt @@ -0,0 +1,52 @@ +package sushi.hardcore.aira.utils + +import android.content.ContentValues +import android.content.Context +import android.os.Environment +import android.provider.MediaStore +import android.webkit.MimeTypeMap +import java.io.File +import java.io.OutputStream +import java.text.DecimalFormat +import java.text.SimpleDateFormat +import java.util.* +import kotlin.math.pow +import kotlin.math.log10 + +object FileUtils { + private val units = arrayOf("B", "kB", "MB", "GB", "TB") + fun formatSize(size: Long): String { + if (size <= 0) { + return "0 B" + } + val digitGroups = (log10(size.toDouble()) / log10(1000.0)).toInt() + return DecimalFormat("#,##0.#").format(size / 1000.0.pow(digitGroups.toDouble()) + ) + " " + units[digitGroups] + } + + fun openFileForDownload(context: Context, fileName: String): OutputStream? { + val fileExtension = fileName.substringAfterLast(".") + val dateExtension = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(Date()) + val datedFilename = if (fileName.contains(".")) { + val basename = fileName.substringBeforeLast(".") + """${basename}_$dateExtension.$fileExtension""" + } else { + fileName + "_" + dateExtension + } + return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { + context.contentResolver.insert( + MediaStore.Downloads.EXTERNAL_CONTENT_URI, + ContentValues().apply { + put(MediaStore.Images.Media.TITLE, datedFilename) + put(MediaStore.Images.Media.DISPLAY_NAME, datedFilename) + put(MediaStore.Images.Media.MIME_TYPE, MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension)) + } + )?.let { + context.contentResolver.openOutputStream(it) + } + } else { + @Suppress("Deprecation") + File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), datedFilename).outputStream() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/utils/StringUtils.kt b/app/src/main/java/sushi/hardcore/aira/utils/StringUtils.kt new file mode 100644 index 0000000..15b1f25 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/utils/StringUtils.kt @@ -0,0 +1,12 @@ +package sushi.hardcore.aira.utils + +object StringUtils { + fun beautifyFingerprint(fingerprint: String): String { + val newFingerprint = StringBuilder(fingerprint.length+7) + for (i in 0..fingerprint.length-8 step 4) { + newFingerprint.append(fingerprint.slice(i until i+4)+" ") + } + newFingerprint.append(fingerprint.slice(fingerprint.length-4 until fingerprint.length)) + return newFingerprint.toString() + } +} \ No newline at end of file diff --git a/app/src/main/java/sushi/hardcore/aira/widgets/TextAvatar.kt b/app/src/main/java/sushi/hardcore/aira/widgets/TextAvatar.kt new file mode 100644 index 0000000..11fdd63 --- /dev/null +++ b/app/src/main/java/sushi/hardcore/aira/widgets/TextAvatar.kt @@ -0,0 +1,38 @@ +package sushi.hardcore.aira.widgets + +import android.content.Context +import android.util.AttributeSet +import android.view.LayoutInflater +import android.widget.RelativeLayout +import android.widget.TextView +import sushi.hardcore.aira.R + +class TextAvatar @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, + defStyle: Int = 0 +) : RelativeLayout(context, attrs, defStyle) { + + private val view = LayoutInflater.from(context).inflate(R.layout.text_avatar, this, true) + + init { + attrs?.let { + val typedArray = context.obtainStyledAttributes(it, R.styleable.TextAvatar) + for (i in 0..typedArray.indexCount) { + val attr = typedArray.getIndex(i) + if (attr == R.styleable.TextAvatar_textSize) { + val textSize = typedArray.getDimension(attr, -1F) + if (textSize != -1F) { + view.findViewById(R.id.text_letter).textSize = textSize + } + break + } + } + typedArray.recycle() + } + } + + fun setLetterFrom(name: String) { + view.findViewById(R.id.text_letter).text = name[0].toUpperCase().toString() + } +} \ No newline at end of file diff --git a/app/src/main/native/.gitignore b/app/src/main/native/.gitignore new file mode 100644 index 0000000..fa8d85a --- /dev/null +++ b/app/src/main/native/.gitignore @@ -0,0 +1,2 @@ +Cargo.lock +target diff --git a/app/src/main/native/Cargo.toml b/app/src/main/native/Cargo.toml new file mode 100644 index 0000000..4e7a1d0 --- /dev/null +++ b/app/src/main/native/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "aira" +version = "0.0.1" +authors = ["Hardcore Sushi "] +edition = "2018" + +[target.'cfg(target_os="android")'.dependencies] +jni = { version = "0.19", default-features = false } + +[lib] +crate-type = ["dylib"] + +[dependencies] +rand-8 = {package = "rand", version = "0.8.3"} +rand-7 = {package = "rand", version = "0.7.3"} +lazy_static = "1.4.0" +rusqlite = {version = "0.25.1", features = ["bundled"]} +ed25519-dalek = "1" #for singing +x25519-dalek = "1.1" #for shared secret +sha2 = "0.9.3" +hkdf = "0.11.0" +aes-gcm = "0.9.0" #PSEC +aes-gcm-siv = "0.10.0" #Database +hmac = "0.11.0" +hex = "0.4.3" +strum_macros = "0.20.1" #display enums +uuid = {version = "0.8", features = ["v4"]} +scrypt = "0.7.0" +zeroize = "1.2.0" +log = "0.4.14" +android_log = "0.1.3" diff --git a/app/src/main/native/build.sh b/app/src/main/native/build.sh new file mode 100755 index 0000000..bb46623 --- /dev/null +++ b/app/src/main/native/build.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +if [ -z ${ANDROID_NDK_HOME+x} ]; then + echo "Error: \$ANDROID_NDK_HOME is not defined." +else + export PATH=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/:$PATH + declare -a androidABIs=("arm64-v8a" "armeabi-v7a") + declare -a targets=("aarch64-linux-android" "armv7-linux-androideabi") + for (( i=0; i < ${#targets[@]}; i++ )) do + cargo build --target ${targets[i]} --release + cp target/${targets[i]}/release/libaira.so ../jniLibs/${androidABIs[i]}/ + done +fi diff --git a/app/src/main/native/check.sh b/app/src/main/native/check.sh new file mode 100755 index 0000000..ab3d621 --- /dev/null +++ b/app/src/main/native/check.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +if [ -z ${ANDROID_NDK_HOME+x} ]; then + echo "Error: \$ANDROID_NDK_HOME is not defined." +else + export PATH=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/:$PATH + cargo check --target aarch64-linux-android +fi diff --git a/app/src/main/native/src/crypto.rs b/app/src/main/native/src/crypto.rs new file mode 100644 index 0000000..29f1142 --- /dev/null +++ b/app/src/main/native/src/crypto.rs @@ -0,0 +1,226 @@ +use std::convert::TryInto; +use hkdf::Hkdf; +use sha2::Sha384; +use hmac::{Hmac, Mac, NewMac}; +use scrypt::{scrypt, Params}; +use rand_8::{RngCore, rngs::OsRng}; +use aes_gcm::{aead::Aead, NewAead, Nonce}; +use aes_gcm_siv::Aes256GcmSiv; +use zeroize::Zeroize; +use strum_macros::Display; +use crate::utils::*; + +pub const HASH_OUTPUT_LEN: usize = 48; //SHA384 +const KEY_LEN: usize = 16; +pub const IV_LEN: usize = 12; +pub const AES_TAG_LEN: usize = 16; +pub const SALT_LEN: usize = 32; +const PASSWORD_HASH_LEN: usize = 32; +pub const MASTER_KEY_LEN: usize = 32; + +fn hkdf_expand_label(key: &[u8], label: &str, context: Option<&[u8]>, okm: &mut [u8]) { + let hkdf = Hkdf::::from_prk(key).unwrap(); + //can't set info conditionnally because of different array size + match context { + Some(context) => { + let info = [&(label.len() as u32).to_be_bytes(), label.as_bytes(), &(context.len() as u32).to_be_bytes(), context]; + hkdf.expand_multi_info(&info, okm).unwrap(); + } + None => { + let info = [&(label.len() as u32).to_be_bytes(), label.as_bytes()]; + hkdf.expand_multi_info(&info, okm).unwrap(); + } + }; +} + +pub struct HandshakeKeys { + pub local_key: [u8; KEY_LEN], + pub local_iv: [u8; IV_LEN], + pub local_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN], + pub peer_key: [u8; KEY_LEN], + pub peer_iv: [u8; IV_LEN], + pub peer_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN], + pub handshake_secret: [u8; HASH_OUTPUT_LEN], +} + +impl HandshakeKeys { + pub fn derive_keys(shared_secret: [u8; 32], handshake_hash: [u8; HASH_OUTPUT_LEN], i_am_bob: bool) -> HandshakeKeys { + let (handshake_secret, _) = Hkdf::::extract(None, &shared_secret); + + let local_label = "handshake".to_owned() + if i_am_bob {"i_am_bob"} else {"i_am_alice"}; + let mut local_handshake_traffic_secret = [0; HASH_OUTPUT_LEN]; + hkdf_expand_label(handshake_secret.as_slice(), &local_label, Some(&handshake_hash), &mut local_handshake_traffic_secret); + + let peer_label = "handshake".to_owned() + if i_am_bob {"i_am_alice"} else {"i_am_bob"}; + let mut peer_handshake_traffic_secret = [0; HASH_OUTPUT_LEN]; + hkdf_expand_label(handshake_secret.as_slice(), &peer_label, Some(&handshake_hash), &mut peer_handshake_traffic_secret); + + let mut local_handshake_key = [0; KEY_LEN]; + hkdf_expand_label(&local_handshake_traffic_secret, "key", None, &mut local_handshake_key); + let mut local_handshake_iv = [0; IV_LEN]; + hkdf_expand_label(&local_handshake_traffic_secret, "iv", None, &mut local_handshake_iv); + + let mut peer_handshake_key = [0; KEY_LEN]; + hkdf_expand_label(&peer_handshake_traffic_secret, "key", None, &mut peer_handshake_key); + let mut peer_handshake_iv = [0; IV_LEN]; + hkdf_expand_label(&peer_handshake_traffic_secret,"iv", None, &mut peer_handshake_iv); + + HandshakeKeys { + local_key: local_handshake_key, + local_iv: local_handshake_iv, + local_handshake_traffic_secret: local_handshake_traffic_secret, + peer_key: peer_handshake_key, + peer_iv: peer_handshake_iv, + peer_handshake_traffic_secret: peer_handshake_traffic_secret, + handshake_secret: to_array_48(handshake_secret.as_slice()) + } + } +} + +pub struct ApplicationKeys { + pub local_key: [u8; KEY_LEN], + pub local_iv: [u8; IV_LEN], + pub peer_key: [u8; KEY_LEN], + pub peer_iv: [u8; IV_LEN], +} + +impl ApplicationKeys { + pub fn derive_keys(handshake_secret: [u8; HASH_OUTPUT_LEN], handshake_hash: [u8; HASH_OUTPUT_LEN], i_am_bob: bool) -> ApplicationKeys { + let mut derived_secret = [0; HASH_OUTPUT_LEN]; + hkdf_expand_label(&handshake_secret, "derived", None, &mut derived_secret); + let (master_secret, _) = Hkdf::::extract(Some(&derived_secret), b""); + + let local_label = "application".to_owned() + if i_am_bob {"i_am_bob"} else {"i_am_alice"}; + let mut local_application_traffic_secret = [0; HASH_OUTPUT_LEN]; + hkdf_expand_label(&master_secret, &local_label, Some(&handshake_hash), &mut local_application_traffic_secret); + + let peer_label = "application".to_owned() + if i_am_bob {"i_am_alice"} else {"i_am_bob"}; + let mut peer_application_traffic_secret = [0; HASH_OUTPUT_LEN]; + hkdf_expand_label(&master_secret, &peer_label, Some(&handshake_hash), &mut peer_application_traffic_secret); + + let mut local_application_key = [0; KEY_LEN]; + hkdf_expand_label(&local_application_traffic_secret, "key", None, &mut local_application_key); + let mut local_application_iv = [0; IV_LEN]; + hkdf_expand_label(&local_application_traffic_secret, "iv", None, &mut local_application_iv); + + let mut peer_application_key = [0; KEY_LEN]; + hkdf_expand_label(&peer_application_traffic_secret, "key", None, &mut peer_application_key); + let mut peer_application_iv = [0; IV_LEN]; + hkdf_expand_label(&peer_application_traffic_secret,"iv", None, &mut peer_application_iv); + + ApplicationKeys { + local_key: local_application_key, + local_iv: local_application_iv, + peer_key: peer_application_key, + peer_iv: peer_application_iv, + } + } +} + +pub fn compute_handshake_finished(local_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN], handshake_hash: [u8; HASH_OUTPUT_LEN]) -> [u8; HASH_OUTPUT_LEN] { + let mut finished_key = [0; HASH_OUTPUT_LEN]; + hkdf_expand_label(&local_handshake_traffic_secret, "finished", None, &mut finished_key); + let mut hmac = Hmac::::new_from_slice(&finished_key).unwrap(); + hmac.update(&handshake_hash); + hmac.finalize().into_bytes().as_slice().try_into().unwrap() +} + +pub fn verify_handshake_finished(peer_handshake_finished: [u8; HASH_OUTPUT_LEN], peer_handshake_traffic_secret: [u8; HASH_OUTPUT_LEN], handshake_hash: [u8; HASH_OUTPUT_LEN]) -> bool { + let mut peer_finished_key = [0; HASH_OUTPUT_LEN]; + hkdf_expand_label(&peer_handshake_traffic_secret, "finished", None, &mut peer_finished_key); + let mut hmac = Hmac::::new_from_slice(&peer_finished_key).unwrap(); + hmac.update(&handshake_hash); + hmac.verify(&peer_handshake_finished).is_ok() +} + + + +pub fn generate_fingerprint(public_key: &[u8]) -> String { + let mut raw_fingerprint = [0; 16]; + Hkdf::::new(None, public_key).expand(&[], &mut raw_fingerprint).unwrap(); + hex::encode(raw_fingerprint).to_uppercase() +} + + + +pub fn generate_master_key() -> [u8; MASTER_KEY_LEN] { + let mut master_key = [0; MASTER_KEY_LEN]; + OsRng.fill_bytes(&mut master_key); + master_key +} + +pub fn encrypt_data(data: &[u8], master_key: &[u8]) -> Result, CryptoError> { + if master_key.len() != MASTER_KEY_LEN { + return Err(CryptoError::InvalidLength); + } + let cipher = Aes256GcmSiv::new_from_slice(master_key).unwrap(); + let mut iv = [0; IV_LEN]; + OsRng.fill_bytes(&mut iv); //use it for IV for now + let mut cipher_text = iv.to_vec(); + cipher_text.extend(cipher.encrypt(Nonce::from_slice(&iv), data).unwrap()); + Ok(cipher_text) +} + +#[derive(Display, Debug, PartialEq, Eq)] +pub enum CryptoError { + DecryptionFailed, + InvalidLength +} + +pub fn decrypt_data(data: &[u8], master_key: &[u8]) -> Result, CryptoError> { + if data.len() <= IV_LEN || master_key.len() != MASTER_KEY_LEN { + return Err(CryptoError::InvalidLength); + } + let cipher = Aes256GcmSiv::new_from_slice(master_key).unwrap(); + match cipher.decrypt(Nonce::from_slice(&data[..IV_LEN]), &data[IV_LEN..]) { + Ok(data) => { + Ok(data) + }, + Err(_) => Err(CryptoError::DecryptionFailed) + } +} + +fn scrypt_params() -> Params { + Params::new(16, 8, 1).unwrap() +} + +pub fn encrypt_master_key(mut master_key: [u8; MASTER_KEY_LEN], password: &[u8]) -> ( + [u8; SALT_LEN], //salt + [u8; IV_LEN+MASTER_KEY_LEN+AES_TAG_LEN] //encrypted masterkey with IV +) { + let mut salt = [0; SALT_LEN]; + OsRng.fill_bytes(&mut salt); + let mut password_hash = [0; PASSWORD_HASH_LEN]; + scrypt(password, &salt, &scrypt_params(), &mut password_hash).unwrap(); + let mut output = [0; IV_LEN+MASTER_KEY_LEN+AES_TAG_LEN]; + OsRng.fill_bytes(&mut output); //use it for IV for now + let cipher = Aes256GcmSiv::new_from_slice(&password_hash).unwrap(); + let encrypted_master_key = cipher.encrypt(Nonce::from_slice(&output[..IV_LEN]), master_key.as_ref()).unwrap(); + master_key.zeroize(); + password_hash.zeroize(); + encrypted_master_key.into_iter().enumerate().for_each(|i|{ + output[IV_LEN+i.0] = i.1; //append encrypted master key to IV + }); + (salt, output) +} + +pub fn decrypt_master_key(encrypted_master_key: &[u8], password: &[u8], salt: &[u8]) -> Result<[u8; MASTER_KEY_LEN], CryptoError> { + if encrypted_master_key.len() != IV_LEN+MASTER_KEY_LEN+AES_TAG_LEN || salt.len() != SALT_LEN { + return Err(CryptoError::InvalidLength); + } + let mut password_hash = [0; PASSWORD_HASH_LEN]; + scrypt(password, salt, &scrypt_params(), &mut password_hash).unwrap(); + let cipher = Aes256GcmSiv::new_from_slice(&password_hash).unwrap(); + let result = match cipher.decrypt(Nonce::from_slice(&encrypted_master_key[..IV_LEN]), &encrypted_master_key[IV_LEN..]) { + Ok(master_key) => { + if master_key.len() == MASTER_KEY_LEN { + Ok(master_key.try_into().unwrap()) + } else { + return Err(CryptoError::InvalidLength) + } + }, + Err(_) => Err(CryptoError::DecryptionFailed) + }; + password_hash.zeroize(); + result +} diff --git a/app/src/main/native/src/identity.rs b/app/src/main/native/src/identity.rs new file mode 100644 index 0000000..da86aca --- /dev/null +++ b/app/src/main/native/src/identity.rs @@ -0,0 +1,469 @@ +use std::{convert::TryInto, path::Path}; +use crypto::CryptoError; +use ed25519_dalek::{Keypair, Signer, SIGNATURE_LENGTH, PUBLIC_KEY_LENGTH}; +use rusqlite::{Connection, params}; +use utils::to_uuid_bytes; +use uuid::Uuid; +use zeroize::Zeroize; +use crate::{crypto, key_value_table::KeyValueTable, print_error, utils}; + +const DB_NAME: &str = "AIRA.db"; +const MAIN_TABLE: &str = "main"; +const CONTACTS_TABLE: &str = "contacts"; +const FILES_TABLE: &str = "files"; + +const DATABASE_CORRUPED_ERROR: &str = "Database corrupted"; + +struct DBKeys; +impl<'a> DBKeys { + pub const NAME: &'a str = "name"; + pub const KEYPAIR: &'a str = "keypair"; + pub const SALT: &'a str = "salt"; + pub const MASTER_KEY: &'a str = "master_key"; +} + +fn bool_to_byte(b: bool) -> u8 { + if b { 75 } else { 30 } //completely arbitrary values +} + +fn byte_to_bool(b: u8) -> Result { + if b == 75 { + Ok(true) + } else if b == 30 { + Ok(false) + } else { + Err(()) + } +} + +fn get_database_path(database_folder: &str) -> String { + Path::new(database_folder).join(DB_NAME).to_str().unwrap().to_owned() +} + +struct EncryptedIdentity { + name: String, + encrypted_keypair: Vec, + salt: Vec, + encrypted_master_key: Vec +} + +pub struct Contact { + pub uuid: Uuid, + pub public_key: [u8; PUBLIC_KEY_LENGTH], + pub name: String, + pub verified: bool, + pub seen: bool, +} + +pub struct Identity { + pub name: String, + keypair: Keypair, + pub master_key: [u8; crypto::MASTER_KEY_LEN], + database_folder: String, +} + +impl Identity { + + pub fn sign(&self, input: &[u8]) -> [u8; SIGNATURE_LENGTH] { + self.keypair.sign(input).to_bytes() + } + + pub fn get_public_key(&self) -> [u8; PUBLIC_KEY_LENGTH] { + self.keypair.public.to_bytes() + } + + fn get_database_path(&self) -> String { + get_database_path(&self.database_folder) + } + + pub fn add_contact(&self, name: String, public_key: [u8; PUBLIC_KEY_LENGTH]) -> Result { + let db = Connection::open(self.get_database_path())?; + db.execute(&("CREATE TABLE IF NOT EXISTS ".to_owned()+CONTACTS_TABLE+"(uuid BLOB PRIMARY KEY, name BLOB, key BLOB, verified BLOB, seen BLOB)"), [])?; + let contact_uuid = Uuid::new_v4(); + let encrypted_name = crypto::encrypt_data(name.as_bytes(), &self.master_key).unwrap(); + let encrypted_public_key = crypto::encrypt_data(&public_key, &self.master_key).unwrap(); + let encrypted_verified = crypto::encrypt_data(&[bool_to_byte(false)], &self.master_key).unwrap(); + let encrypted_seen = crypto::encrypt_data(&[bool_to_byte(true)], &self.master_key).unwrap(); + db.execute(&("INSERT INTO ".to_owned()+CONTACTS_TABLE+" (uuid, name, key, verified, seen) VALUES (?1, ?2, ?3, ?4, ?5)"), params![&contact_uuid.as_bytes()[..], encrypted_name, encrypted_public_key, encrypted_verified, encrypted_seen])?; + Ok(Contact { + uuid: contact_uuid, + public_key: public_key, + name: name, + verified: false, + seen: true, + }) + } + + pub fn remove_contact(&self, uuid: &Uuid) -> Result { + let db = Connection::open(self.get_database_path())?; + self.delete_conversation(uuid)?; + db.execute(&("DELETE FROM ".to_owned()+CONTACTS_TABLE+" WHERE uuid=?"), [&uuid.as_bytes()[..]]) + } + + pub fn set_verified(&self, uuid: &Uuid) -> Result { + let db = Connection::open(self.get_database_path())?; + let encrypted_verified = crypto::encrypt_data(&[bool_to_byte(true)], &self.master_key).unwrap(); + db.execute(&format!("UPDATE {} SET verified=?1 WHERE uuid=?2", CONTACTS_TABLE), [encrypted_verified.as_slice(), &uuid.as_bytes()[..]]) + } + + pub fn change_contact_name(&self, uuid: &Uuid, new_name: &str) -> Result { + let db = Connection::open(self.get_database_path())?; + let encrypted_name = crypto::encrypt_data(new_name.as_bytes(), &self.master_key).unwrap(); + db.execute(&format!("UPDATE {} SET name=?1 WHERE uuid=?2", CONTACTS_TABLE), [encrypted_name.as_slice(), uuid.as_bytes()]) + } + + pub fn set_contact_seen(&self, uuid: &Uuid, seen: bool) -> Result { + let db = Connection::open(self.get_database_path())?; + let encrypted_seen = crypto::encrypt_data(&[bool_to_byte(seen)], &self.master_key).unwrap(); + db.execute(&format!("UPDATE {} SET seen=?1 WHERE uuid=?2", CONTACTS_TABLE), [encrypted_seen.as_slice(), uuid.as_bytes()]) + } + + pub fn load_contacts(&self) -> Option> { + match Connection::open(self.get_database_path()) { + Ok(db) => { + match db.prepare(&("SELECT uuid, name, key, verified, seen FROM ".to_owned()+CONTACTS_TABLE)) { + Ok(mut stmt) => { + let mut rows = stmt.query([]).unwrap(); + let mut contacts = Vec::new(); + while let Some(row) = rows.next().unwrap() { + let encrypted_public_key: Vec = row.get(2).unwrap(); + match crypto::decrypt_data(encrypted_public_key.as_slice(), &self.master_key) { + Ok(public_key) => { + if public_key.len() == PUBLIC_KEY_LENGTH { + let encrypted_name: Vec = row.get(1).unwrap(); + match crypto::decrypt_data(encrypted_name.as_slice(), &self.master_key) { + Ok(name) => { + let encrypted_verified: Vec = row.get(3).unwrap(); + match crypto::decrypt_data(encrypted_verified.as_slice(), &self.master_key) { + Ok(verified) => { + let encrypted_seen: Vec = row.get(4).unwrap(); + match crypto::decrypt_data(encrypted_seen.as_slice(), &self.master_key) { + Ok(seen) => { + let uuid: Vec = row.get(0).unwrap(); + match to_uuid_bytes(&uuid) { + Some(uuid_bytes) => { + contacts.push(Contact { + uuid: Uuid::from_bytes(uuid_bytes), + public_key: public_key.try_into().unwrap(), + name: std::str::from_utf8(name.as_slice()).unwrap().to_owned(), + verified: byte_to_bool(verified[0]).unwrap(), + seen: byte_to_bool(seen[0]).unwrap(), + }) + } + None => {} + } + } + Err(e) => print_error!(e) + } + } + Err(e) => print_error!(e) + } + } + Err(e) => print_error!(e) + } + } else { + print_error!("Invalid public key length: database corrupted"); + } + } + Err(e) => print_error!(e) + } + } + Some(contacts) + } + Err(e) => { + print_error!(e); + None + } + } + } + Err(e) => { + print_error!(e); + None + } + } + } + + pub fn clear_temporary_files(&self) -> Result { + let db = Connection::open(self.get_database_path())?; + db.execute(&format!("DELETE FROM {} WHERE contact_uuid IS NULL", FILES_TABLE), []) + } + + pub fn load_file(&self, uuid: Uuid) -> Option> { + match Connection::open(self.get_database_path()) { + Ok(db) => { + match db.prepare(&format!("SELECT uuid, data FROM \"{}\"", FILES_TABLE)) { + Ok(mut stmt) => { + let mut rows = stmt.query([]).unwrap(); + while let Some(row) = rows.next().unwrap() { + let encrypted_uuid: Vec = row.get(0).unwrap(); + match crypto::decrypt_data(encrypted_uuid.as_slice(), &self.master_key){ + Ok(test_uuid) => { + if test_uuid == uuid.as_bytes() { + let encrypted_data: Vec = row.get(1).unwrap(); + match crypto::decrypt_data(encrypted_data.as_slice(), &self.master_key) { + Ok(data) => return Some(data), + Err(e) => print_error!(e) + } + } + } + Err(e) => print_error!(e) + } + } + None + } + Err(e) => { + print_error!(e); + None + } + } + } + Err(e) => { + print_error!(e); + None + } + } + } + + pub fn store_file(&self, contact_uuid: Option, data: &[u8]) -> Result { + let db = Connection::open(self.get_database_path())?; + db.execute(&format!("CREATE TABLE IF NOT EXISTS \"{}\" (contact_uuid BLOB, uuid BLOB, data BLOB)", FILES_TABLE), [])?; + let file_uuid = Uuid::new_v4(); + let encrypted_uuid = crypto::encrypt_data(file_uuid.as_bytes(), &self.master_key).unwrap(); + let encrypted_data = crypto::encrypt_data(data, &self.master_key).unwrap(); + let query = format!("INSERT INTO \"{}\" (contact_uuid, uuid, data) VALUES (?1, ?2, ?3)", FILES_TABLE); + match contact_uuid { + Some(uuid) => db.execute(&query, params![&uuid.as_bytes()[..], &encrypted_uuid, &encrypted_data])?, + None => db.execute(&query, params![None as Option>, &encrypted_uuid, &encrypted_data])? + }; + Ok(file_uuid) + } + + pub fn store_msg(&self, contact_uuid: &Uuid, outgoing: bool, data: &[u8]) -> Result { + let db = Connection::open(self.get_database_path())?; + db.execute(&format!("CREATE TABLE IF NOT EXISTS \"{}\" (outgoing BLOB, data BLOB)", contact_uuid), [])?; + let outgoing_byte: u8 = bool_to_byte(outgoing); + let encrypted_outgoing = crypto::encrypt_data(&[outgoing_byte], &self.master_key).unwrap(); + let encrypted_data = crypto::encrypt_data(data, &self.master_key).unwrap(); + db.execute(&format!("INSERT INTO \"{}\" (outgoing, data) VALUES (?1, ?2)", contact_uuid), params![encrypted_outgoing, encrypted_data]) + } + + pub fn load_msgs(&self, contact_uuid: &Uuid, offset: usize, mut count: usize) -> Option)>> { + match Connection::open(self.get_database_path()) { + Ok(db) => { + match db.prepare(&format!("SELECT count(*) FROM \"{}\"", contact_uuid)) { + Ok(mut stmt) => { + let mut rows = stmt.query([]).unwrap(); + let row = rows.next().unwrap(); + if row.is_some() { + let total: usize = row.unwrap().get(0).unwrap(); + if offset >= total { + print_error!("Offset larger than total numbers of rows"); + None + } else { + if offset+count >= total { + count = total-offset; + } + match db.prepare(&format!("SELECT outgoing, data FROM \"{}\" LIMIT {} OFFSET {}", contact_uuid, count, total-offset-count)) { + Ok(mut stmt) => { + let mut rows = stmt.query([]).unwrap(); + let mut msgs = Vec::new(); + while let Some(row) = rows.next().unwrap() { + let encrypted_outgoing: Vec = row.get(0).unwrap(); + match crypto::decrypt_data(encrypted_outgoing.as_slice(), &self.master_key){ + Ok(outgoing) => { + match byte_to_bool(outgoing[0]) { + Ok(outgoing) => { + let encrypted_data: Vec = row.get(1).unwrap(); + match crypto::decrypt_data(encrypted_data.as_slice(), &self.master_key) { + Ok(data) => { + msgs.push( + ( + outgoing, + data + ) + ) + }, + Err(e) => print_error!(e) + } + } + Err(_) => {} + } + + } + Err(e) => print_error!(e) + } + } + Some(msgs) + } + Err(e) => { + print_error!(e); + None + } + } + } + } else { + None + } + } + Err(e) => { + print_error!(e); + None + } + } + } + Err(e) => { + print_error!(e); + None + } + } + } + + #[allow(unused_must_use)] + pub fn delete_conversation(&self, contact_uuid: &Uuid) -> Result { + let db = Connection::open(self.get_database_path())?; + db.execute(&format!("DELETE FROM {} WHERE contact_uuid=?", FILES_TABLE), &[&contact_uuid.as_bytes()[..]]); + db.execute(&format!("DROP TABLE IF EXISTS \"{}\"", contact_uuid), []) + } + + pub fn change_name(&mut self, new_name: String) -> Result { + let db = KeyValueTable::new(&self.get_database_path(), MAIN_TABLE)?; + let result = db.update(DBKeys::NAME, new_name.as_bytes()); + if result.is_ok() { + self.name = new_name; + } + result + } + + pub fn zeroize(&mut self){ + self.master_key.zeroize(); + self.keypair.secret.zeroize(); + } + + fn load_encrypted_identity(database_folder: &str) -> Result { + let db = KeyValueTable::new(&get_database_path(database_folder), MAIN_TABLE)?; + let name = db.get(DBKeys::NAME)?; + let encrypted_keypair = db.get(DBKeys::KEYPAIR)?; + let salt = db.get(DBKeys::SALT)?; + let encrypted_master_key = db.get(DBKeys::MASTER_KEY)?; + Ok(EncryptedIdentity { + name: std::str::from_utf8(&name).unwrap().to_owned(), + encrypted_keypair, + salt, + encrypted_master_key, + }) + } + + pub fn load_identity(database_folder: String, password: Option<&[u8]>) -> Result { + match Identity::load_encrypted_identity(&database_folder) { + Ok(encrypted_identity) => { + let master_key: [u8; crypto::MASTER_KEY_LEN] = if password.is_none() { + if encrypted_identity.encrypted_master_key.len() == crypto::MASTER_KEY_LEN { + encrypted_identity.encrypted_master_key.try_into().unwrap() + } else { + return Err(String::from(DATABASE_CORRUPED_ERROR)) + } + } else { + match crypto::decrypt_master_key(&encrypted_identity.encrypted_master_key, password.unwrap(), &encrypted_identity.salt) { + Ok(master_key) => master_key, + Err(e) => return Err( + match e { + CryptoError::DecryptionFailed => "Bad password".to_owned(), + CryptoError::InvalidLength => String::from(DATABASE_CORRUPED_ERROR) + } + ) + } + }; + match crypto::decrypt_data(&encrypted_identity.encrypted_keypair, &master_key) { + Ok(keypair) => { + Ok(Identity{ + name: encrypted_identity.name, + keypair: Keypair::from_bytes(&keypair[..]).unwrap(), + master_key: master_key, + database_folder: database_folder, + }) + } + Err(e) => { + print_error!(e); + Err(String::from(DATABASE_CORRUPED_ERROR)) + } + } + } + Err(e) => Err(e.to_string()) + } + } + + pub fn get_identity_name(database_folder: &str) -> Result { + let db = KeyValueTable::new(&get_database_path(database_folder), MAIN_TABLE)?; + Ok(std::str::from_utf8(&db.get(DBKeys::NAME)?).unwrap().to_string()) + } + + pub fn is_protected(database_folder: String) -> Result { + let db = KeyValueTable::new(&get_database_path(&database_folder), MAIN_TABLE)?; + Ok(db.get(DBKeys::MASTER_KEY)?.len() != crypto::MASTER_KEY_LEN) + } + + pub fn create_identidy(database_folder: String, name: &str, password: Option<&[u8]>) -> Result { + let keypair = Keypair::generate(&mut rand_7::rngs::OsRng); + let master_key = crypto::generate_master_key(); + let encrypted_keypair = crypto::encrypt_data(&keypair.to_bytes(), &master_key).unwrap(); + let db = KeyValueTable::new(&get_database_path(&database_folder), MAIN_TABLE)?; + db.set(DBKeys::NAME, name.as_bytes())?; + db.set(DBKeys::KEYPAIR, &encrypted_keypair)?; + let salt = if password.is_none() { //no password + db.set(DBKeys::MASTER_KEY, &master_key)?; //storing master_key in plaintext + [0; crypto::SALT_LEN] + } else { + let (salt, encrypted_master_key) = crypto::encrypt_master_key(master_key, password.unwrap()); + db.set(DBKeys::MASTER_KEY, &encrypted_master_key)?; + salt + }; + db.set(DBKeys::SALT, &salt)?; + + Ok(Identity { + name: name.to_owned(), + keypair, + master_key, + database_folder + }) + } + + fn update_master_key(database_folder: String, master_key: [u8; crypto::MASTER_KEY_LEN], new_password: Option<&[u8]>) -> Result { + let db = KeyValueTable::new(&get_database_path(&database_folder), MAIN_TABLE)?; + let salt = if new_password.is_none() { //no password + db.update(DBKeys::MASTER_KEY, &master_key)?; + [0; crypto::SALT_LEN] + } else { + let (salt, encrypted_master_key) = crypto::encrypt_master_key(master_key, new_password.unwrap()); + db.update(DBKeys::MASTER_KEY, &encrypted_master_key)?; + salt + }; + db.update(DBKeys::SALT, &salt) + } + + pub fn change_password(database_folder: String, old_password: Option<&[u8]>, new_password: Option<&[u8]>) -> Result { + match Identity::load_encrypted_identity(&database_folder) { + Ok(encrypted_identity) => { + let master_key: [u8; crypto::MASTER_KEY_LEN] = if old_password.is_none() { + if encrypted_identity.encrypted_master_key.len() == crypto::MASTER_KEY_LEN { + encrypted_identity.encrypted_master_key.try_into().unwrap() + } else { + return Err(String::from(DATABASE_CORRUPED_ERROR)) + } + } else { + match crypto::decrypt_master_key(&encrypted_identity.encrypted_master_key, old_password.unwrap(), &encrypted_identity.salt) { + Ok(master_key) => master_key, + Err(e) => return match e { + CryptoError::DecryptionFailed => Ok(false), + CryptoError::InvalidLength => Err(String::from(DATABASE_CORRUPED_ERROR)) + } + } + }; + match Identity::update_master_key(database_folder, master_key, new_password) { + Ok(_) => Ok(true), + Err(e) => Err(e.to_string()) + } + } + Err(e) => Err(e.to_string()) + } + } +} diff --git a/app/src/main/native/src/key_value_table.rs b/app/src/main/native/src/key_value_table.rs new file mode 100644 index 0000000..510d1da --- /dev/null +++ b/app/src/main/native/src/key_value_table.rs @@ -0,0 +1,31 @@ +use rusqlite::{Connection, Error, params}; + +pub struct KeyValueTable<'a> { + db: Connection, + table_name: &'a str, +} + +impl<'a> KeyValueTable<'a> { + pub fn new(db_path: &str, table_name: &'a str) -> Result, Error> { + let db = Connection::open(db_path)?; + db.execute(&format!("CREATE TABLE IF NOT EXISTS {} (key TEXT PRIMARY KEY, value BLOB)", table_name), [])?; + Ok(KeyValueTable {db, table_name}) + } + pub fn set(&self, key: &str, value: &[u8]) -> Result { + Ok(self.db.execute(&format!("INSERT INTO {} (key, value) VALUES (?1, ?2)", self.table_name), params![key, value])?) + } + pub fn get(&self, key: &str) -> Result, Error> { + let mut stmt = self.db.prepare(&format!("SELECT value FROM {} WHERE key=\"{}\"", self.table_name, key))?; + let mut rows = stmt.query([])?; + match rows.next()? { + Some(row) => Ok(row.get(0)?), + None => Err(rusqlite::Error::QueryReturnedNoRows) + } + } + /*pub fn del(&self, key: &str) -> Result { + self.db.execute(&format!("DELETE FROM {} WHERE key=\"{}\"", self.table_name, key), NO_PARAMS) + }*/ + pub fn update(&self, key: &str, value: &[u8]) -> Result { + self.db.execute(&format!("UPDATE {} SET value=? WHERE key=\"{}\"", self.table_name, key), params![value]) + } +} \ No newline at end of file diff --git a/app/src/main/native/src/lib.rs b/app/src/main/native/src/lib.rs new file mode 100644 index 0000000..518e10e --- /dev/null +++ b/app/src/main/native/src/lib.rs @@ -0,0 +1,357 @@ +mod key_value_table; +mod identity; +mod crypto; +mod utils; + +use std::{convert::TryInto, str::FromStr, fmt::Display, sync::{Mutex}}; +use lazy_static::lazy_static; +use uuid::Uuid; +use log::*; +use android_log; +use identity::{Identity, Contact}; +use crate::crypto::{HandshakeKeys, ApplicationKeys}; + +lazy_static! { + static ref loaded_identity: Mutex> = Mutex::new(None); +} + +#[cfg(target_os="android")] +use jni::JNIEnv; +use jni::objects::{JClass, JObject, JString, JList, JValue}; +use jni::sys::{jboolean, jint, jbyteArray, jobject}; + +fn jstring_to_string(env: JNIEnv, input: JString) -> String { + String::from(env.get_string(input).unwrap()) +} + +fn jboolean_to_bool(input: jboolean) -> bool { + input == 1 +} + +fn bool_to_jboolean(input: bool) -> u8 { + if input { 1 } else { 0 } +} + +fn slice_to_jvalue<'a>(env: JNIEnv, input: &'a [u8]) -> JValue<'a> { + JValue::Object(env.byte_array_from_slice(input).unwrap().into()) +} + +#[allow(unused_must_use)] +fn log_error(e: T) { + android_log::init("AIRA Native"); + error!("Error: {}", e) +} + +#[allow(non_snake_case)] +#[no_mangle] +pub extern fn Java_sushi_hardcore_aira_CreateIdentityFragment_createNewIdentity(env: JNIEnv, _: JClass, database_folder: JString, name: JString, password: jbyteArray) -> jboolean { + let database_folder = jstring_to_string(env, database_folder); + let name = jstring_to_string(env, name); + match Identity::create_identidy(database_folder, &name, env.convert_byte_array(password).ok().as_deref()) { + Ok(identity) => { + *loaded_identity.lock().unwrap() = Some(identity); + 1 + } + Err(e) => { + log_error(e); + 0 + } + } +} + + +#[no_mangle] +pub extern fn Java_sushi_hardcore_aira_LoginActivity_getIdentityName(env: JNIEnv, _: JClass, database_folder: JString) -> jobject { + *match Identity::get_identity_name(&jstring_to_string(env, database_folder)) { + Ok(name) => *env.new_string(name).unwrap(), + Err(e) => { + log_error(e); + JObject::null() + } + } +} + +#[no_mangle] +pub extern fn Java_sushi_hardcore_aira_AIRADatabase_isIdentityProtected(env: JNIEnv, _: JClass, database_folder: JString) -> jboolean { + match Identity::is_protected(jstring_to_string(env, database_folder)) { + Ok(is_protected) => bool_to_jboolean(is_protected), + Err(e) => { + log_error(e); + 0 + } + } +} + +#[no_mangle] +pub extern fn Java_sushi_hardcore_aira_AIRADatabase_loadIdentity(env: JNIEnv, _: JClass, database_folder: JString, password: jbyteArray) -> jboolean { + let database_folder = jstring_to_string(env, database_folder); + match Identity::load_identity(database_folder, env.convert_byte_array(password).ok().as_deref()) { + Ok(identity) => { + *loaded_identity.lock().unwrap() = Some(identity); + 1 + } + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_changePassword(env: JNIEnv, _: JClass, database_folder: JString, old_password: jbyteArray, new_password: jbyteArray) -> jboolean { + let database_folder = jstring_to_string(env, database_folder); + match Identity::change_password(database_folder, env.convert_byte_array(old_password).ok().as_deref(), env.convert_byte_array(new_password).ok().as_deref()) { + Ok(success) => bool_to_jboolean(success), + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_getIdentityPublicKey(env: JNIEnv, _: JClass) -> jbyteArray { + env.byte_array_from_slice(&loaded_identity.lock().unwrap().as_ref().unwrap().get_public_key()).unwrap() +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_background_1service_Session_sign(env: JNIEnv, _: JClass, input: jbyteArray) -> jbyteArray { + env.byte_array_from_slice(&loaded_identity.lock().unwrap().as_ref().unwrap().sign(&env.convert_byte_array(input).unwrap())).unwrap() +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_background_1service_Session_deriveHandshakeKeys(env: JNIEnv, _: JClass, shared_secret: jbyteArray, handshake_hash: jbyteArray, i_am_bob: jboolean) -> jobject { + let shared_secret = env.convert_byte_array(shared_secret).unwrap(); + let handshake_hash = env.convert_byte_array(handshake_hash).unwrap(); + let handshake_keys = HandshakeKeys::derive_keys(shared_secret.as_slice().try_into().unwrap(), handshake_hash.as_slice().try_into().unwrap(), jboolean_to_bool(i_am_bob)); + + let args: Vec> = [&handshake_keys.local_key[..], &handshake_keys.local_iv, &handshake_keys.local_handshake_traffic_secret, &handshake_keys.peer_key, &handshake_keys.peer_iv, &handshake_keys.peer_handshake_traffic_secret, &handshake_keys.handshake_secret].iter().map(|field|{ + slice_to_jvalue(env, field) + }).collect(); + let handshake_keys_class = env.find_class("sushi/hardcore/aira/background_service/HandshakeKeys").unwrap(); + *env.new_object(handshake_keys_class, "([B[B[B[B[B[B[B)V", &args).unwrap() +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_background_1service_Session_computeHandshakeFinished(env: JNIEnv, _: JClass, local_handshake_traffic_secret: jbyteArray, handshake_hash: jbyteArray) -> jbyteArray { + env.byte_array_from_slice(&crypto::compute_handshake_finished(env.convert_byte_array(local_handshake_traffic_secret).unwrap()[..].try_into().unwrap(), env.convert_byte_array(handshake_hash).unwrap()[..].try_into().unwrap())).unwrap() +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_background_1service_Session_verifyHandshakeFinished(env: JNIEnv, _: JClass, peer_handshake_finished: jbyteArray, peer_handshake_traffic_secret: jbyteArray, handshake_hash: jbyteArray) -> jboolean { + bool_to_jboolean(crypto::verify_handshake_finished(env.convert_byte_array(peer_handshake_finished).unwrap()[..].try_into().unwrap(), env.convert_byte_array(peer_handshake_traffic_secret).unwrap()[..].try_into().unwrap(), env.convert_byte_array(handshake_hash).unwrap()[..].try_into().unwrap())) +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_background_1service_Session_deriveApplicationKeys(env: JNIEnv, _: JClass, handshake_secret: jbyteArray, handshake_hash: jbyteArray, i_am_bob: jboolean) -> jobject { + let handshake_secret = env.convert_byte_array(handshake_secret).unwrap(); + let handshake_hash = env.convert_byte_array(handshake_hash).unwrap(); + let application_keys = ApplicationKeys::derive_keys(handshake_secret.as_slice().try_into().unwrap(), handshake_hash.as_slice().try_into().unwrap(), jboolean_to_bool(i_am_bob)); + + let args: Vec> = [&application_keys.local_key[..], &application_keys.local_iv, &application_keys.peer_key, &application_keys.peer_iv].iter().map(|field|{ + slice_to_jvalue(env, field) + }).collect(); + let application_keys_class = env.find_class("sushi/hardcore/aira/background_service/ApplicationKeys").unwrap(); + *env.new_object(application_keys_class, "([B[B[B[B)V", &args).unwrap() +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_background_1service_AIRAService_releaseIdentity(_: JNIEnv, _: JClass) { + let mut identity = loaded_identity.lock().unwrap(); + identity.as_mut().unwrap().zeroize(); + *identity = None; +} + +fn new_contact(env: JNIEnv, contact: Contact) -> JObject { + let contact_class = env.find_class("sushi/hardcore/aira/background_service/Contact").unwrap(); + env.new_object(contact_class, "(Ljava/lang/String;[BLjava/lang/String;ZZ)V", &[JValue::Object(*env.new_string(contact.uuid.to_string()).unwrap()), slice_to_jvalue(env, &contact.public_key), JValue::Object(*env.new_string(contact.name).unwrap()), JValue::Bool(bool_to_jboolean(contact.verified)), JValue::Bool(bool_to_jboolean(contact.seen))]).unwrap() +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_addContact(env: JNIEnv, _: JClass, name: JString, public_key: jbyteArray) -> jobject { + *match loaded_identity.lock().unwrap().as_ref().unwrap().add_contact(jstring_to_string(env, name), env.convert_byte_array(public_key).unwrap().try_into().unwrap()) { + Ok(contact) => new_contact(env, contact), + Err(e) => { + log_error(e); + JObject::null() + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_removeContact(env: JNIEnv, _: JClass, uuid: JString) -> jboolean { + match loaded_identity.lock().unwrap().as_ref().unwrap().remove_contact(&Uuid::from_str(&jstring_to_string(env, uuid)).unwrap()) { + Ok(_) => 1, + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_loadContacts(env: JNIEnv, _: JClass) -> jobject { + *match loaded_identity.lock().unwrap().as_ref().unwrap().load_contacts() { + Some(contacts) => { + let array_list_class = env.find_class("java/util/ArrayList").unwrap(); + let array_list = env.new_object(array_list_class, "(I)V", &[JValue::Int(contacts.len().try_into().unwrap())]).unwrap(); + let array_list = JList::from_env(&env, array_list).unwrap(); + for contact in contacts { + array_list.add(new_contact(env, contact)).unwrap(); + } + *array_list + } + None => JObject::null() + } +} + + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_setVerified(env: JNIEnv, _: JClass, uuid: JString) -> jboolean { + match loaded_identity.lock().unwrap().as_ref().unwrap().set_verified(&Uuid::from_str(&jstring_to_string(env, uuid)).unwrap()) { + Ok(_) => 1, + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_changeContactName(env: JNIEnv, _: JClass, contactUuid: JString, newName: JString) -> jboolean { + match loaded_identity.lock().unwrap().as_ref().unwrap().change_contact_name(&Uuid::from_str(&jstring_to_string(env, contactUuid)).unwrap(), &jstring_to_string(env, newName)) { + Ok(_) => 1, + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_setContactSeen(env: JNIEnv, _: JClass, contactUuid: JString, seen: jboolean) -> jboolean { + match loaded_identity.lock().unwrap().as_ref().unwrap().set_contact_seen(&Uuid::from_str(&jstring_to_string(env, contactUuid)).unwrap(), jboolean_to_bool(seen)) { + Ok(_) => 1, + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_storeMsg(env: JNIEnv, _: JClass, contactUuid: JString, outgoing: jboolean, data: jbyteArray) -> jboolean { + match loaded_identity.lock().unwrap().as_ref().unwrap().store_msg(&Uuid::from_str(&jstring_to_string(env, contactUuid)).unwrap(), jboolean_to_bool(outgoing), &env.convert_byte_array(data).unwrap()) { + Ok(_) => 1, + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_loadMsgs(env: JNIEnv, _: JClass, uuid: JString, offset: jint, count: jint) -> jobject { + *match loaded_identity.lock().unwrap().as_ref().unwrap().load_msgs(&Uuid::from_str(&jstring_to_string(env, uuid)).unwrap(), offset as usize, count as usize) { + Some(msgs) => { + let array_list_class = env.find_class("java/util/ArrayList").unwrap(); + let array_list = env.new_object(array_list_class, "(I)V", &[JValue::Int(msgs.len().try_into().unwrap())]).unwrap(); + let array_list = JList::from_env(&env, array_list).unwrap(); + let chat_item_class = env.find_class("sushi/hardcore/aira/ChatItem").unwrap(); + for msg in msgs { + let chat_item_object = env.new_object(chat_item_class, "(Z[B)V", &[JValue::Bool(bool_to_jboolean(msg.0)), slice_to_jvalue(env, &msg.1)]).unwrap(); + array_list.add(chat_item_object).unwrap(); + } + *array_list + } + None => JObject::null() + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_storeFile(env: JNIEnv, _: JClass, contactUuid: JString, data: jbyteArray) -> jbyteArray { + let contact_uuid = match env.get_string(contactUuid) { + Ok(uuid) => Some(Uuid::from_str(&String::from(uuid)).unwrap()), + Err(_) => None + }; + match loaded_identity.lock().unwrap().as_ref().unwrap().store_file(contact_uuid, &env.convert_byte_array(data).unwrap()) { + Ok(uuid) => env.byte_array_from_slice(uuid.as_bytes()).unwrap(), + Err(_) => *JObject::null() + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_loadFile(env: JNIEnv, _: JClass, rawUuid: jbyteArray) -> jbyteArray { + match loaded_identity.lock().unwrap().as_ref().unwrap().load_file(Uuid::from_bytes(env.convert_byte_array(rawUuid).unwrap().try_into().unwrap())) { + Some(buffer) => env.byte_array_from_slice(&buffer).unwrap(), + None => *JObject::null() + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_deleteConversation(env: JNIEnv, _: JClass, contactUuid: JString) -> jboolean { + let contact_uuid = Uuid::from_str(&String::from(env.get_string(contactUuid).unwrap())).unwrap(); + match loaded_identity.lock().unwrap().as_ref().unwrap().delete_conversation(&contact_uuid) { + Ok(_) => 1, + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_clearTemporaryFiles(_: JNIEnv, _: JClass) -> jint { + match loaded_identity.lock().unwrap().as_ref().unwrap().clear_temporary_files() { + Ok(r) => r.try_into().unwrap(), + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_changeName(env: JNIEnv, _: JClass, new_name: JString) -> jboolean { + let new_name = jstring_to_string(env, new_name); + match loaded_identity.lock().unwrap().as_mut().unwrap().change_name(new_name) { + Ok(u) => bool_to_jboolean(u == 1), + Err(e) => { + log_error(e); + 0 + } + } +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_AIRADatabase_getIdentityFingerprint(env: JNIEnv, _: JClass) -> jobject { + **env.new_string(crypto::generate_fingerprint(&loaded_identity.lock().unwrap().as_ref().unwrap().get_public_key())).unwrap() +} + +#[allow(non_snake_case)] +#[no_mangle] +pub fn Java_sushi_hardcore_aira_ChatActivity_generateFingerprint(env: JNIEnv, _: JClass, publicKey: jbyteArray) -> jobject { + **env.new_string(crypto::generate_fingerprint(&env.convert_byte_array(publicKey).unwrap())).unwrap() +} diff --git a/app/src/main/native/src/utils.rs b/app/src/main/native/src/utils.rs new file mode 100644 index 0000000..31faddf --- /dev/null +++ b/app/src/main/native/src/utils.rs @@ -0,0 +1,27 @@ +use std::convert::TryInto; +use uuid::Bytes; +use crate::print_error; + +pub fn to_array_48(s: &[u8]) -> [u8; 48] { + s.try_into().unwrap() +} + +pub fn to_uuid_bytes(bytes: &[u8]) -> Option { + match bytes.try_into() { + Ok(uuid) => Some(uuid), + Err(e) => { + print_error!(e); + None + } + } +} + +#[macro_export] +macro_rules! print_error { + ($arg:tt) => ({ + println!("[{}:{}] {}", file!(), line!(), $arg); + }); + ($($arg:tt)*) => ({ + println!("[{}:{}] {}", file!(), line!(), format_args!($($arg)*)); + }) +} diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/background_adapter_bubble.xml b/app/src/main/res/drawable/background_adapter_bubble.xml new file mode 100644 index 0000000..676d763 --- /dev/null +++ b/app/src/main/res/drawable/background_adapter_bubble.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/background_session.xml b/app/src/main/res/drawable/background_session.xml new file mode 100644 index 0000000..d70974f --- /dev/null +++ b/app/src/main/res/drawable/background_session.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_add.xml b/app/src/main/res/drawable/ic_add.xml new file mode 100644 index 0000000..70046c4 --- /dev/null +++ b/app/src/main/res/drawable/ic_add.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_attach_file.xml b/app/src/main/res/drawable/ic_attach_file.xml new file mode 100644 index 0000000..696e634 --- /dev/null +++ b/app/src/main/res/drawable/ic_attach_file.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_close.xml b/app/src/main/res/drawable/ic_close.xml new file mode 100644 index 0000000..70db409 --- /dev/null +++ b/app/src/main/res/drawable/ic_close.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_delete_conversation.xml b/app/src/main/res/drawable/ic_delete_conversation.xml new file mode 100644 index 0000000..7c56cbe --- /dev/null +++ b/app/src/main/res/drawable/ic_delete_conversation.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_delete_forever.xml b/app/src/main/res/drawable/ic_delete_forever.xml new file mode 100644 index 0000000..f54f7d4 --- /dev/null +++ b/app/src/main/res/drawable/ic_delete_forever.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_info.xml b/app/src/main/res/drawable/ic_info.xml new file mode 100644 index 0000000..654cfb3 --- /dev/null +++ b/app/src/main/res/drawable/ic_info.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_launcher.png b/app/src/main/res/drawable/ic_launcher.png new file mode 100644 index 0000000..f25a419 Binary files /dev/null and b/app/src/main/res/drawable/ic_launcher.png differ 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..07d5da9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_lock.xml b/app/src/main/res/drawable/ic_lock.xml new file mode 100644 index 0000000..6c6b260 --- /dev/null +++ b/app/src/main/res/drawable/ic_lock.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_person.xml b/app/src/main/res/drawable/ic_person.xml new file mode 100644 index 0000000..bd8dc80 --- /dev/null +++ b/app/src/main/res/drawable/ic_person.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_person_add.xml b/app/src/main/res/drawable/ic_person_add.xml new file mode 100644 index 0000000..2a9a71b --- /dev/null +++ b/app/src/main/res/drawable/ic_person_add.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_person_remove.xml b/app/src/main/res/drawable/ic_person_remove.xml new file mode 100644 index 0000000..fd10461 --- /dev/null +++ b/app/src/main/res/drawable/ic_person_remove.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_save.xml b/app/src/main/res/drawable/ic_save.xml new file mode 100644 index 0000000..ddb9d4d --- /dev/null +++ b/app/src/main/res/drawable/ic_save.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_send.xml b/app/src/main/res/drawable/ic_send.xml new file mode 100644 index 0000000..5b10648 --- /dev/null +++ b/app/src/main/res/drawable/ic_send.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings.xml b/app/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000..b240b83 --- /dev/null +++ b/app/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_verified.xml b/app/src/main/res/drawable/ic_verified.xml new file mode 100644 index 0000000..70f2341 --- /dev/null +++ b/app/src/main/res/drawable/ic_verified.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_warning.xml b/app/src/main/res/drawable/ic_warning.xml new file mode 100644 index 0000000..3c9a4b3 --- /dev/null +++ b/app/src/main/res/drawable/ic_warning.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/round_background.xml b/app/src/main/res/drawable/round_background.xml new file mode 100644 index 0000000..369e998 --- /dev/null +++ b/app/src/main/res/drawable/round_background.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_chat.xml b/app/src/main/res/layout/activity_chat.xml new file mode 100644 index 0000000..9d064dd --- /dev/null +++ b/app/src/main/res/layout/activity_chat.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml new file mode 100644 index 0000000..1e8dce3 --- /dev/null +++ b/app/src/main/res/layout/activity_login.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file 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..bff5e3a --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml new file mode 100644 index 0000000..38e897a --- /dev/null +++ b/app/src/main/res/layout/activity_settings.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/adapter_chat_file.xml b/app/src/main/res/layout/adapter_chat_file.xml new file mode 100644 index 0000000..92375dc --- /dev/null +++ b/app/src/main/res/layout/adapter_chat_file.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/adapter_chat_message.xml b/app/src/main/res/layout/adapter_chat_message.xml new file mode 100644 index 0000000..7903680 --- /dev/null +++ b/app/src/main/res/layout/adapter_chat_message.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/adapter_session.xml b/app/src/main/res/layout/adapter_session.xml new file mode 100644 index 0000000..6ec7bf2 --- /dev/null +++ b/app/src/main/res/layout/adapter_session.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_ask_file.xml b/app/src/main/res/layout/dialog_ask_file.xml new file mode 100644 index 0000000..a0ab6c4 --- /dev/null +++ b/app/src/main/res/layout/dialog_ask_file.xml @@ -0,0 +1,19 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_fingerprints.xml b/app/src/main/res/layout/dialog_fingerprints.xml new file mode 100644 index 0000000..eccc767 --- /dev/null +++ b/app/src/main/res/layout/dialog_fingerprints.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_info.xml b/app/src/main/res/layout/dialog_info.xml new file mode 100644 index 0000000..8573f47 --- /dev/null +++ b/app/src/main/res/layout/dialog_info.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_password.xml b/app/src/main/res/layout/dialog_password.xml new file mode 100644 index 0000000..73265ac --- /dev/null +++ b/app/src/main/res/layout/dialog_password.xml @@ -0,0 +1,28 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_create_identity.xml b/app/src/main/res/layout/fragment_create_identity.xml new file mode 100644 index 0000000..b095092 --- /dev/null +++ b/app/src/main/res/layout/fragment_create_identity.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + +